blob: 77ba2e6907f383ff36c572705f83ce41964d82b5 [file] [log] [blame]
Paul Duffin82d90432019-11-30 09:24:33 +00001// Copyright 2019 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package sdk
16
17import (
Paul Duffinc3c5d5e2019-11-29 20:45:22 +000018 "fmt"
Paul Duffin82d90432019-11-30 09:24:33 +000019 "io/ioutil"
20 "os"
Paul Duffinc3c5d5e2019-11-29 20:45:22 +000021 "path/filepath"
Paul Duffin82d90432019-11-30 09:24:33 +000022 "strings"
23 "testing"
24
25 "android/soong/android"
26 "android/soong/apex"
27 "android/soong/cc"
28 "android/soong/java"
29)
30
Paul Duffinc3c5d5e2019-11-29 20:45:22 +000031func testSdkContext(bp string, fs map[string][]byte) (*android.TestContext, android.Config) {
Colin Cross98be1bb2019-12-13 20:41:13 -080032 bp = bp + `
33 apex_key {
34 name: "myapex.key",
35 public_key: "myapex.avbpubkey",
36 private_key: "myapex.pem",
37 }
38
39 android_app_certificate {
40 name: "myapex.cert",
41 certificate: "myapex",
42 }
43 ` + cc.GatherRequiredDepsForTest(android.Android)
44
45 mockFS := map[string][]byte{
46 "build/make/target/product/security": nil,
47 "apex_manifest.json": nil,
48 "system/sepolicy/apex/myapex-file_contexts": nil,
49 "system/sepolicy/apex/myapex2-file_contexts": nil,
50 "myapex.avbpubkey": nil,
51 "myapex.pem": nil,
52 "myapex.x509.pem": nil,
53 "myapex.pk8": nil,
54 }
55
56 for k, v := range fs {
57 mockFS[k] = v
58 }
59
60 config := android.TestArchConfig(buildDir, nil, bp, mockFS)
61
Paul Duffin82d90432019-11-30 09:24:33 +000062 ctx := android.NewTestArchContext()
63
64 // from android package
Paul Duffin593b3c92019-12-05 14:31:48 +000065 ctx.PreArchMutators(android.RegisterPackageRenamer)
66 ctx.PreArchMutators(android.RegisterVisibilityRuleChecker)
Paul Duffin82d90432019-11-30 09:24:33 +000067 ctx.PreArchMutators(android.RegisterDefaultsPreArchMutators)
Paul Duffin593b3c92019-12-05 14:31:48 +000068 ctx.PreArchMutators(android.RegisterVisibilityRuleGatherer)
69 ctx.PostDepsMutators(android.RegisterVisibilityRuleEnforcer)
70
Paul Duffin82d90432019-11-30 09:24:33 +000071 ctx.PreArchMutators(func(ctx android.RegisterMutatorsContext) {
72 ctx.BottomUp("prebuilts", android.PrebuiltMutator).Parallel()
73 })
74 ctx.PostDepsMutators(func(ctx android.RegisterMutatorsContext) {
75 ctx.TopDown("prebuilt_select", android.PrebuiltSelectModuleMutator).Parallel()
76 ctx.BottomUp("prebuilt_postdeps", android.PrebuiltPostDepsMutator).Parallel()
77 })
Paul Duffin593b3c92019-12-05 14:31:48 +000078 ctx.RegisterModuleType("package", android.PackageFactory)
Paul Duffin82d90432019-11-30 09:24:33 +000079
80 // from java package
81 ctx.RegisterModuleType("android_app_certificate", java.AndroidAppCertificateFactory)
Paul Duffin593b3c92019-12-05 14:31:48 +000082 ctx.RegisterModuleType("java_defaults", java.DefaultsFactory)
Paul Duffin82d90432019-11-30 09:24:33 +000083 ctx.RegisterModuleType("java_library", java.LibraryFactory)
84 ctx.RegisterModuleType("java_import", java.ImportFactory)
85 ctx.RegisterModuleType("droidstubs", java.DroidstubsFactory)
86 ctx.RegisterModuleType("prebuilt_stubs_sources", java.PrebuiltStubsSourcesFactory)
87
88 // from cc package
89 ctx.RegisterModuleType("cc_library", cc.LibraryFactory)
90 ctx.RegisterModuleType("cc_library_shared", cc.LibrarySharedFactory)
Paul Duffin9ab556f2019-12-11 18:42:17 +000091 ctx.RegisterModuleType("cc_library_static", cc.LibraryStaticFactory)
Paul Duffin82d90432019-11-30 09:24:33 +000092 ctx.RegisterModuleType("cc_object", cc.ObjectFactory)
93 ctx.RegisterModuleType("cc_prebuilt_library_shared", cc.PrebuiltSharedLibraryFactory)
94 ctx.RegisterModuleType("cc_prebuilt_library_static", cc.PrebuiltStaticLibraryFactory)
95 ctx.RegisterModuleType("llndk_library", cc.LlndkLibraryFactory)
96 ctx.RegisterModuleType("toolchain_library", cc.ToolchainLibraryFactory)
97 ctx.PreDepsMutators(func(ctx android.RegisterMutatorsContext) {
Paul Duffin82d90432019-11-30 09:24:33 +000098 ctx.BottomUp("link", cc.LinkageMutator).Parallel()
99 ctx.BottomUp("vndk", cc.VndkMutator).Parallel()
100 ctx.BottomUp("test_per_src", cc.TestPerSrcMutator).Parallel()
101 ctx.BottomUp("version", cc.VersionMutator).Parallel()
102 ctx.BottomUp("begin", cc.BeginMutator).Parallel()
103 })
104
105 // from apex package
106 ctx.RegisterModuleType("apex", apex.BundleFactory)
107 ctx.RegisterModuleType("apex_key", apex.ApexKeyFactory)
108 ctx.PostDepsMutators(apex.RegisterPostDepsMutators)
109
110 // from this package
111 ctx.RegisterModuleType("sdk", ModuleFactory)
112 ctx.RegisterModuleType("sdk_snapshot", SnapshotModuleFactory)
113 ctx.PreDepsMutators(RegisterPreDepsMutators)
114 ctx.PostDepsMutators(RegisterPostDepsMutators)
115
Colin Cross98be1bb2019-12-13 20:41:13 -0800116 ctx.Register(config)
Paul Duffin82d90432019-11-30 09:24:33 +0000117
118 return ctx, config
119}
120
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000121func testSdkWithFs(t *testing.T, bp string, fs map[string][]byte) *testSdkResult {
122 t.Helper()
123 ctx, config := testSdkContext(bp, fs)
Paul Duffin593b3c92019-12-05 14:31:48 +0000124 _, errs := ctx.ParseBlueprintsFiles(".")
Paul Duffin82d90432019-11-30 09:24:33 +0000125 android.FailIfErrored(t, errs)
126 _, errs = ctx.PrepareBuildActions(config)
127 android.FailIfErrored(t, errs)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000128 return &testSdkResult{
129 TestHelper: TestHelper{t: t},
130 ctx: ctx,
131 config: config,
132 }
Paul Duffin82d90432019-11-30 09:24:33 +0000133}
134
135func testSdkError(t *testing.T, pattern, bp string) {
136 t.Helper()
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000137 ctx, config := testSdkContext(bp, nil)
Paul Duffin82d90432019-11-30 09:24:33 +0000138 _, errs := ctx.ParseFileList(".", []string{"Android.bp"})
139 if len(errs) > 0 {
140 android.FailIfNoMatchingErrors(t, pattern, errs)
141 return
142 }
143 _, errs = ctx.PrepareBuildActions(config)
144 if len(errs) > 0 {
145 android.FailIfNoMatchingErrors(t, pattern, errs)
146 return
147 }
148
149 t.Fatalf("missing expected error %q (0 errors are returned)", pattern)
150}
151
152func ensureListContains(t *testing.T, result []string, expected string) {
153 t.Helper()
154 if !android.InList(expected, result) {
155 t.Errorf("%q is not found in %v", expected, result)
156 }
157}
158
159func pathsToStrings(paths android.Paths) []string {
160 var ret []string
161 for _, p := range paths {
162 ret = append(ret, p.String())
163 }
164 return ret
165}
166
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000167// Provides general test support.
168type TestHelper struct {
169 t *testing.T
170}
171
172func (h *TestHelper) AssertStringEquals(message string, expected string, actual string) {
173 h.t.Helper()
174 if actual != expected {
175 h.t.Errorf("%s: expected %s, actual %s", message, expected, actual)
Paul Duffin82d90432019-11-30 09:24:33 +0000176 }
177}
178
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000179func (h *TestHelper) AssertTrimmedStringEquals(message string, expected string, actual string) {
180 h.t.Helper()
181 h.AssertStringEquals(message, strings.TrimSpace(expected), strings.TrimSpace(actual))
182}
183
184// Encapsulates result of processing an SDK definition. Provides support for
185// checking the state of the build structures.
186type testSdkResult struct {
187 TestHelper
188 ctx *android.TestContext
189 config android.Config
190}
191
192// Analyse the sdk build rules to extract information about what it is doing.
193
194// e.g. find the src/dest pairs from each cp command, the various zip files
195// generated, etc.
196func (r *testSdkResult) getSdkSnapshotBuildInfo(sdk *sdk) *snapshotBuildInfo {
197 androidBpContents := strings.NewReplacer("\\n", "\n").Replace(sdk.GetAndroidBpContentsForTests())
198
199 info := &snapshotBuildInfo{
200 r: r,
201 androidBpContents: androidBpContents,
202 }
203
204 buildParams := sdk.BuildParamsForTests()
205 copyRules := &strings.Builder{}
206 for _, bp := range buildParams {
207 switch bp.Rule.String() {
208 case android.Cp.String():
209 // Get source relative to build directory.
210 src := r.pathRelativeToBuildDir(bp.Input)
211 // Get destination relative to the snapshot root
212 dest := bp.Output.Rel()
213 _, _ = fmt.Fprintf(copyRules, "%s -> %s\n", src, dest)
214 info.snapshotContents = append(info.snapshotContents, dest)
215
216 case repackageZip.String():
217 // Add the destdir to the snapshot contents as that is effectively where
218 // the content of the repackaged zip is copied.
219 dest := bp.Args["destdir"]
220 info.snapshotContents = append(info.snapshotContents, dest)
221
222 case zipFiles.String():
223 // This could be an intermediate zip file and not the actual output zip.
224 // In that case this will be overridden when the rule to merge the zips
225 // is processed.
226 info.outputZip = r.pathRelativeToBuildDir(bp.Output)
227
228 case mergeZips.String():
229 // Copy the current outputZip to the intermediateZip.
230 info.intermediateZip = info.outputZip
231 mergeInput := r.pathRelativeToBuildDir(bp.Input)
232 if info.intermediateZip != mergeInput {
233 r.t.Errorf("Expected intermediate zip %s to be an input to merge zips but found %s instead",
234 info.intermediateZip, mergeInput)
235 }
236
237 // Override output zip (which was actually the intermediate zip file) with the actual
238 // output zip.
239 info.outputZip = r.pathRelativeToBuildDir(bp.Output)
240
241 // Save the zips to be merged into the intermediate zip.
242 info.mergeZips = r.pathsRelativeToBuildDir(bp.Inputs)
243 }
244 }
245
246 info.copyRules = copyRules.String()
247
248 return info
249}
250
251func (r *testSdkResult) Module(name string, variant string) android.Module {
252 return r.ctx.ModuleForTests(name, variant).Module()
253}
254
255func (r *testSdkResult) ModuleForTests(name string, variant string) android.TestingModule {
256 return r.ctx.ModuleForTests(name, variant)
257}
258
259func (r *testSdkResult) pathRelativeToBuildDir(path android.Path) string {
260 buildDir := filepath.Clean(r.config.BuildDir()) + "/"
261 return strings.TrimPrefix(filepath.Clean(path.String()), buildDir)
262}
263
264func (r *testSdkResult) pathsRelativeToBuildDir(paths android.Paths) []string {
265 var result []string
266 for _, path := range paths {
267 result = append(result, r.pathRelativeToBuildDir(path))
268 }
269 return result
270}
271
272// Check the snapshot build rules.
273//
274// Takes a list of functions which check different facets of the snapshot build rules.
275// Allows each test to customize what is checked without duplicating lots of code
276// or proliferating check methods of different flavors.
Paul Duffin593b3c92019-12-05 14:31:48 +0000277func (r *testSdkResult) CheckSnapshot(name string, variant string, dir string, checkers ...snapshotBuildInfoChecker) {
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000278 r.t.Helper()
279
280 sdk := r.Module(name, variant).(*sdk)
281
282 snapshotBuildInfo := r.getSdkSnapshotBuildInfo(sdk)
283
284 // Check state of the snapshot build.
285 for _, checker := range checkers {
286 checker(snapshotBuildInfo)
287 }
288
289 // Make sure that the generated zip file is in the correct place.
290 actual := snapshotBuildInfo.outputZip
Paul Duffin593b3c92019-12-05 14:31:48 +0000291 if dir != "" {
292 dir = filepath.Clean(dir) + "/"
293 }
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000294 r.AssertStringEquals("Snapshot zip file in wrong place",
Paul Duffin593b3c92019-12-05 14:31:48 +0000295 fmt.Sprintf(".intermediates/%s%s/%s/%s-current.zip", dir, name, variant, name), actual)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000296
297 // Populate a mock filesystem with the files that would have been copied by
298 // the rules.
299 fs := make(map[string][]byte)
300 for _, dest := range snapshotBuildInfo.snapshotContents {
301 fs[dest] = nil
302 }
303
304 // Process the generated bp file to make sure it is valid.
305 testSdkWithFs(r.t, snapshotBuildInfo.androidBpContents, fs)
306}
307
308type snapshotBuildInfoChecker func(info *snapshotBuildInfo)
309
310// Check that the snapshot's generated Android.bp is correct.
311//
312// Both the expected and actual string are both trimmed before comparing.
313func checkAndroidBpContents(expected string) snapshotBuildInfoChecker {
314 return func(info *snapshotBuildInfo) {
315 info.r.t.Helper()
316 info.r.AssertTrimmedStringEquals("Android.bp contents do not match", expected, info.androidBpContents)
317 }
318}
319
320// Check that the snapshot's copy rules are correct.
321//
322// The copy rules are formatted as <src> -> <dest>, one per line and then compared
323// to the supplied expected string. Both the expected and actual string are trimmed
324// before comparing.
325func checkAllCopyRules(expected string) snapshotBuildInfoChecker {
326 return func(info *snapshotBuildInfo) {
327 info.r.t.Helper()
328 info.r.AssertTrimmedStringEquals("Incorrect copy rules", expected, info.copyRules)
329 }
330}
331
332// Check that the specified path is in the list of zips to merge with the intermediate zip.
333func checkMergeZip(expected string) snapshotBuildInfoChecker {
334 return func(info *snapshotBuildInfo) {
335 info.r.t.Helper()
336 if info.intermediateZip == "" {
337 info.r.t.Errorf("No intermediate zip file was created")
338 }
339 ensureListContains(info.r.t, info.mergeZips, expected)
340 }
341}
342
343// Encapsulates information about the snapshot build structure in order to insulate tests from
344// knowing too much about internal structures.
345//
346// All source/input paths are relative either the build directory. All dest/output paths are
347// relative to the snapshot root directory.
348type snapshotBuildInfo struct {
349 r *testSdkResult
350
351 // The contents of the generated Android.bp file
352 androidBpContents string
353
354 // The paths, relative to the snapshot root, of all files and directories copied into the
355 // snapshot.
356 snapshotContents []string
357
358 // A formatted representation of the src/dest pairs, one pair per line, of the format
359 // src -> dest
360 copyRules string
361
362 // The path to the intermediate zip, which is a zip created from the source files copied
363 // into the snapshot directory and which will be merged with other zips to form the final output.
364 // Is am empty string if there is no intermediate zip because there are no zips to merge in.
365 intermediateZip string
366
367 // The paths to the zips to merge into the output zip, does not include the intermediate
368 // zip.
369 mergeZips []string
370
371 // The final output zip.
372 outputZip string
373}
374
Paul Duffin82d90432019-11-30 09:24:33 +0000375var buildDir string
376
377func setUp() {
378 var err error
379 buildDir, err = ioutil.TempDir("", "soong_sdk_test")
380 if err != nil {
381 panic(err)
382 }
383}
384
385func tearDown() {
386 _ = os.RemoveAll(buildDir)
387}
388
389func runTestWithBuildDir(m *testing.M) {
390 run := func() int {
391 setUp()
392 defer tearDown()
393
394 return m.Run()
395 }
396
397 os.Exit(run())
398}
399
400func SkipIfNotLinux(t *testing.T) {
401 t.Helper()
402 if android.BuildOs != android.Linux {
403 t.Skipf("Skipping as sdk snapshot generation is only supported on %s not %s", android.Linux, android.BuildOs)
404 }
405}