blob: 38755a9e67ad844ee1467bb1e7465bfdc4a505fa [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 Duffinb07fa512020-03-10 22:17:04 +000022 "reflect"
Paul Duffin82d90432019-11-30 09:24:33 +000023 "strings"
24 "testing"
25
26 "android/soong/android"
27 "android/soong/apex"
28 "android/soong/cc"
29 "android/soong/java"
30)
31
Martin Stjernholm7feceb22020-07-11 04:33:29 +010032func testSdkContext(bp string, fs map[string][]byte, extraOsTypes []android.OsType) (*android.TestContext, android.Config) {
33 extraOsTypes = append(extraOsTypes, android.Android, android.Windows)
34
Colin Cross98be1bb2019-12-13 20:41:13 -080035 bp = bp + `
36 apex_key {
37 name: "myapex.key",
38 public_key: "myapex.avbpubkey",
39 private_key: "myapex.pem",
40 }
41
42 android_app_certificate {
43 name: "myapex.cert",
44 certificate: "myapex",
45 }
Martin Stjernholm7feceb22020-07-11 04:33:29 +010046 ` + cc.GatherRequiredDepsForTest(extraOsTypes...)
Colin Cross98be1bb2019-12-13 20:41:13 -080047
48 mockFS := map[string][]byte{
Martin Stjernholmcc776012020-07-07 03:22:21 +010049 "build/make/target/product/security": nil,
50 "apex_manifest.json": nil,
51 "system/sepolicy/apex/myapex-file_contexts": nil,
52 "system/sepolicy/apex/myapex2-file_contexts": nil,
53 "system/sepolicy/apex/mysdkapex-file_contexts": nil,
54 "myapex.avbpubkey": nil,
55 "myapex.pem": nil,
56 "myapex.x509.pem": nil,
57 "myapex.pk8": nil,
Colin Cross98be1bb2019-12-13 20:41:13 -080058 }
59
Colin Crossf28329d2020-02-15 11:00:10 -080060 cc.GatherRequiredFilesForTest(mockFS)
61
Colin Cross98be1bb2019-12-13 20:41:13 -080062 for k, v := range fs {
63 mockFS[k] = v
64 }
65
66 config := android.TestArchConfig(buildDir, nil, bp, mockFS)
67
Paul Duffin08798aa2020-02-27 13:12:46 +000068 // Add windows as a default disable OS to test behavior when some OS variants
69 // are disabled.
70 config.Targets[android.Windows] = []android.Target{
Jiyong Park1613e552020-09-14 19:43:17 +090071 {android.Windows, android.Arch{ArchType: android.X86_64}, android.NativeBridgeDisabled, "", "", true},
Paul Duffin08798aa2020-02-27 13:12:46 +000072 }
73
Martin Stjernholm7feceb22020-07-11 04:33:29 +010074 for _, extraOsType := range extraOsTypes {
75 switch extraOsType {
76 case android.LinuxBionic:
77 config.Targets[android.LinuxBionic] = []android.Target{
Jiyong Park1613e552020-09-14 19:43:17 +090078 {android.LinuxBionic, android.Arch{ArchType: android.X86_64}, android.NativeBridgeDisabled, "", "", false},
Martin Stjernholm7feceb22020-07-11 04:33:29 +010079 }
80 }
81 }
82
Colin Crossae8600b2020-10-29 17:09:13 -070083 ctx := android.NewTestArchContext(config)
Paul Duffin82d90432019-11-30 09:24:33 +000084
Paul Duffin8c3fec42020-03-04 20:15:08 +000085 // Enable androidmk support.
86 // * Register the singleton
87 // * Configure that we are inside make
88 // * Add CommonOS to ensure that androidmk processing works.
89 android.RegisterAndroidMkBuildComponents(ctx)
Jingwen Chencda22c92020-11-23 00:22:30 -050090 android.SetKatiEnabledForTests(config)
Paul Duffin8c3fec42020-03-04 20:15:08 +000091 config.Targets[android.CommonOS] = []android.Target{
Jiyong Park1613e552020-09-14 19:43:17 +090092 {android.CommonOS, android.Arch{ArchType: android.Common}, android.NativeBridgeDisabled, "", "", true},
Paul Duffin8c3fec42020-03-04 20:15:08 +000093 }
94
Paul Duffin82d90432019-11-30 09:24:33 +000095 // from android package
Paul Duffinc1327422020-01-14 12:15:29 +000096 android.RegisterPackageBuildComponents(ctx)
Paul Duffina2ae7e02020-09-11 11:55:00 +010097 ctx.RegisterModuleType("filegroup", android.FileGroupFactory)
Paul Duffin593b3c92019-12-05 14:31:48 +000098 ctx.PreArchMutators(android.RegisterVisibilityRuleChecker)
Paul Duffin82d90432019-11-30 09:24:33 +000099 ctx.PreArchMutators(android.RegisterDefaultsPreArchMutators)
Paul Duffin44f1d842020-06-26 20:17:02 +0100100 ctx.PreArchMutators(android.RegisterComponentsMutator)
Paul Duffin021f4e52020-07-30 16:04:17 +0100101
102 android.RegisterPrebuiltMutators(ctx)
103
104 // Register these after the prebuilt mutators have been registered to match what
105 // happens at runtime.
Paul Duffin593b3c92019-12-05 14:31:48 +0000106 ctx.PreArchMutators(android.RegisterVisibilityRuleGatherer)
107 ctx.PostDepsMutators(android.RegisterVisibilityRuleEnforcer)
108
Paul Duffin82d90432019-11-30 09:24:33 +0000109 // from java package
Paul Duffinf9b1da02019-12-18 19:51:55 +0000110 java.RegisterJavaBuildComponents(ctx)
111 java.RegisterAppBuildComponents(ctx)
Paul Duffindd46f712020-02-10 13:37:10 +0000112 java.RegisterSdkLibraryBuildComponents(ctx)
Anton Hanssondff2c782020-12-21 17:10:01 +0000113 java.RegisterPrebuiltApisBuildComponents(ctx)
Paul Duffin884363e2019-12-19 10:21:09 +0000114 java.RegisterStubsBuildComponents(ctx)
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000115 java.RegisterSystemModulesBuildComponents(ctx)
Paul Duffin82d90432019-11-30 09:24:33 +0000116
117 // from cc package
Paul Duffin77980a82019-12-19 16:01:36 +0000118 cc.RegisterRequiredBuildComponentsForTest(ctx)
Paul Duffin82d90432019-11-30 09:24:33 +0000119
120 // from apex package
121 ctx.RegisterModuleType("apex", apex.BundleFactory)
122 ctx.RegisterModuleType("apex_key", apex.ApexKeyFactory)
123 ctx.PostDepsMutators(apex.RegisterPostDepsMutators)
124
125 // from this package
Paul Duffin8150da62019-12-16 17:21:27 +0000126 ctx.RegisterModuleType("sdk", SdkModuleFactory)
Paul Duffin82d90432019-11-30 09:24:33 +0000127 ctx.RegisterModuleType("sdk_snapshot", SnapshotModuleFactory)
Paul Duffin8150da62019-12-16 17:21:27 +0000128 ctx.RegisterModuleType("module_exports", ModuleExportsFactory)
129 ctx.RegisterModuleType("module_exports_snapshot", ModuleExportsSnapshotsFactory)
Paul Duffin82d90432019-11-30 09:24:33 +0000130 ctx.PreDepsMutators(RegisterPreDepsMutators)
131 ctx.PostDepsMutators(RegisterPostDepsMutators)
132
Colin Crossae8600b2020-10-29 17:09:13 -0700133 ctx.Register()
Paul Duffin82d90432019-11-30 09:24:33 +0000134
135 return ctx, config
136}
137
Martin Stjernholm7feceb22020-07-11 04:33:29 +0100138func runTests(t *testing.T, ctx *android.TestContext, config android.Config) *testSdkResult {
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000139 t.Helper()
Paul Duffin593b3c92019-12-05 14:31:48 +0000140 _, errs := ctx.ParseBlueprintsFiles(".")
Paul Duffin82d90432019-11-30 09:24:33 +0000141 android.FailIfErrored(t, errs)
142 _, errs = ctx.PrepareBuildActions(config)
143 android.FailIfErrored(t, errs)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000144 return &testSdkResult{
145 TestHelper: TestHelper{t: t},
146 ctx: ctx,
147 config: config,
148 }
Paul Duffin82d90432019-11-30 09:24:33 +0000149}
150
Martin Stjernholm7feceb22020-07-11 04:33:29 +0100151func testSdkWithFs(t *testing.T, bp string, fs map[string][]byte) *testSdkResult {
152 t.Helper()
153 ctx, config := testSdkContext(bp, fs, nil)
154 return runTests(t, ctx, config)
155}
156
Paul Duffin82d90432019-11-30 09:24:33 +0000157func testSdkError(t *testing.T, pattern, bp string) {
158 t.Helper()
Martin Stjernholm7feceb22020-07-11 04:33:29 +0100159 ctx, config := testSdkContext(bp, nil, nil)
Paul Duffin82d90432019-11-30 09:24:33 +0000160 _, errs := ctx.ParseFileList(".", []string{"Android.bp"})
161 if len(errs) > 0 {
162 android.FailIfNoMatchingErrors(t, pattern, errs)
163 return
164 }
165 _, errs = ctx.PrepareBuildActions(config)
166 if len(errs) > 0 {
167 android.FailIfNoMatchingErrors(t, pattern, errs)
168 return
169 }
170
171 t.Fatalf("missing expected error %q (0 errors are returned)", pattern)
172}
173
174func ensureListContains(t *testing.T, result []string, expected string) {
175 t.Helper()
176 if !android.InList(expected, result) {
177 t.Errorf("%q is not found in %v", expected, result)
178 }
179}
180
181func pathsToStrings(paths android.Paths) []string {
182 var ret []string
183 for _, p := range paths {
184 ret = append(ret, p.String())
185 }
186 return ret
187}
188
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000189// Provides general test support.
190type TestHelper struct {
191 t *testing.T
192}
193
194func (h *TestHelper) AssertStringEquals(message string, expected string, actual string) {
195 h.t.Helper()
196 if actual != expected {
197 h.t.Errorf("%s: expected %s, actual %s", message, expected, actual)
Paul Duffin82d90432019-11-30 09:24:33 +0000198 }
199}
200
Paul Duffin4b8b7932020-05-06 12:35:38 +0100201func (h *TestHelper) AssertErrorMessageEquals(message string, expected string, actual error) {
202 h.t.Helper()
203 if actual == nil {
204 h.t.Errorf("Expected error but was nil")
205 } else if actual.Error() != expected {
206 h.t.Errorf("%s: expected %s, actual %s", message, expected, actual.Error())
207 }
208}
209
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000210func (h *TestHelper) AssertTrimmedStringEquals(message string, expected string, actual string) {
211 h.t.Helper()
212 h.AssertStringEquals(message, strings.TrimSpace(expected), strings.TrimSpace(actual))
213}
214
Paul Duffinb07fa512020-03-10 22:17:04 +0000215func (h *TestHelper) AssertDeepEquals(message string, expected interface{}, actual interface{}) {
216 h.t.Helper()
217 if !reflect.DeepEqual(actual, expected) {
218 h.t.Errorf("%s: expected %#v, actual %#v", message, expected, actual)
219 }
220}
221
Martin Stjernholm191c25f2020-09-10 00:40:37 +0100222func (h *TestHelper) AssertPanic(message string, funcThatShouldPanic func()) {
223 h.t.Helper()
224 panicked := false
225 func() {
226 defer func() {
227 if x := recover(); x != nil {
228 panicked = true
229 }
230 }()
231 funcThatShouldPanic()
232 }()
233 if !panicked {
234 h.t.Error(message)
235 }
236}
237
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000238// Encapsulates result of processing an SDK definition. Provides support for
239// checking the state of the build structures.
240type testSdkResult struct {
241 TestHelper
242 ctx *android.TestContext
243 config android.Config
244}
245
246// Analyse the sdk build rules to extract information about what it is doing.
247
248// e.g. find the src/dest pairs from each cp command, the various zip files
249// generated, etc.
250func (r *testSdkResult) getSdkSnapshotBuildInfo(sdk *sdk) *snapshotBuildInfo {
Paul Duffin11108272020-05-11 22:59:25 +0100251 androidBpContents := sdk.GetAndroidBpContentsForTests()
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000252
253 info := &snapshotBuildInfo{
254 r: r,
255 androidBpContents: androidBpContents,
256 }
257
258 buildParams := sdk.BuildParamsForTests()
259 copyRules := &strings.Builder{}
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +0000260 otherCopyRules := &strings.Builder{}
Paul Duffine1ddcc92020-03-03 16:01:26 +0000261 snapshotDirPrefix := sdk.builderForTests.snapshotDir.String() + "/"
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000262 for _, bp := range buildParams {
263 switch bp.Rule.String() {
264 case android.Cp.String():
Paul Duffine1ddcc92020-03-03 16:01:26 +0000265 output := bp.Output
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +0000266 // Get destination relative to the snapshot root
267 dest := output.Rel()
268 src := android.NormalizePathForTesting(bp.Input)
269 // We differentiate between copy rules for the snapshot, and copy rules for the install file.
Paul Duffine1ddcc92020-03-03 16:01:26 +0000270 if strings.HasPrefix(output.String(), snapshotDirPrefix) {
271 // Get source relative to build directory.
Paul Duffine1ddcc92020-03-03 16:01:26 +0000272 _, _ = fmt.Fprintf(copyRules, "%s -> %s\n", src, dest)
273 info.snapshotContents = append(info.snapshotContents, dest)
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +0000274 } else {
275 _, _ = fmt.Fprintf(otherCopyRules, "%s -> %s\n", src, dest)
Paul Duffine1ddcc92020-03-03 16:01:26 +0000276 }
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000277
278 case repackageZip.String():
279 // Add the destdir to the snapshot contents as that is effectively where
280 // the content of the repackaged zip is copied.
281 dest := bp.Args["destdir"]
282 info.snapshotContents = append(info.snapshotContents, dest)
283
284 case zipFiles.String():
285 // This could be an intermediate zip file and not the actual output zip.
286 // In that case this will be overridden when the rule to merge the zips
287 // is processed.
Paul Duffin9b478b02019-12-10 13:41:51 +0000288 info.outputZip = android.NormalizePathForTesting(bp.Output)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000289
290 case mergeZips.String():
291 // Copy the current outputZip to the intermediateZip.
292 info.intermediateZip = info.outputZip
Paul Duffin9b478b02019-12-10 13:41:51 +0000293 mergeInput := android.NormalizePathForTesting(bp.Input)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000294 if info.intermediateZip != mergeInput {
295 r.t.Errorf("Expected intermediate zip %s to be an input to merge zips but found %s instead",
296 info.intermediateZip, mergeInput)
297 }
298
299 // Override output zip (which was actually the intermediate zip file) with the actual
300 // output zip.
Paul Duffin9b478b02019-12-10 13:41:51 +0000301 info.outputZip = android.NormalizePathForTesting(bp.Output)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000302
303 // Save the zips to be merged into the intermediate zip.
Paul Duffin9b478b02019-12-10 13:41:51 +0000304 info.mergeZips = android.NormalizePathsForTesting(bp.Inputs)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000305 }
306 }
307
308 info.copyRules = copyRules.String()
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +0000309 info.otherCopyRules = otherCopyRules.String()
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000310
311 return info
312}
313
314func (r *testSdkResult) Module(name string, variant string) android.Module {
315 return r.ctx.ModuleForTests(name, variant).Module()
316}
317
318func (r *testSdkResult) ModuleForTests(name string, variant string) android.TestingModule {
319 return r.ctx.ModuleForTests(name, variant)
320}
321
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000322// Check the snapshot build rules.
323//
324// Takes a list of functions which check different facets of the snapshot build rules.
325// Allows each test to customize what is checked without duplicating lots of code
326// or proliferating check methods of different flavors.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000327func (r *testSdkResult) CheckSnapshot(name string, dir string, checkers ...snapshotBuildInfoChecker) {
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000328 r.t.Helper()
329
Paul Duffin1356d8c2020-02-25 19:26:33 +0000330 // The sdk CommonOS variant is always responsible for generating the snapshot.
331 variant := android.CommonOS.Name
332
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000333 sdk := r.Module(name, variant).(*sdk)
334
335 snapshotBuildInfo := r.getSdkSnapshotBuildInfo(sdk)
336
337 // Check state of the snapshot build.
338 for _, checker := range checkers {
339 checker(snapshotBuildInfo)
340 }
341
342 // Make sure that the generated zip file is in the correct place.
343 actual := snapshotBuildInfo.outputZip
Paul Duffin593b3c92019-12-05 14:31:48 +0000344 if dir != "" {
345 dir = filepath.Clean(dir) + "/"
346 }
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000347 r.AssertStringEquals("Snapshot zip file in wrong place",
Paul Duffin593b3c92019-12-05 14:31:48 +0000348 fmt.Sprintf(".intermediates/%s%s/%s/%s-current.zip", dir, name, variant, name), actual)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000349
350 // Populate a mock filesystem with the files that would have been copied by
351 // the rules.
352 fs := make(map[string][]byte)
353 for _, dest := range snapshotBuildInfo.snapshotContents {
354 fs[dest] = nil
355 }
356
357 // Process the generated bp file to make sure it is valid.
358 testSdkWithFs(r.t, snapshotBuildInfo.androidBpContents, fs)
359}
360
361type snapshotBuildInfoChecker func(info *snapshotBuildInfo)
362
363// Check that the snapshot's generated Android.bp is correct.
364//
365// Both the expected and actual string are both trimmed before comparing.
366func checkAndroidBpContents(expected string) snapshotBuildInfoChecker {
367 return func(info *snapshotBuildInfo) {
368 info.r.t.Helper()
369 info.r.AssertTrimmedStringEquals("Android.bp contents do not match", expected, info.androidBpContents)
370 }
371}
372
373// Check that the snapshot's copy rules are correct.
374//
375// The copy rules are formatted as <src> -> <dest>, one per line and then compared
376// to the supplied expected string. Both the expected and actual string are trimmed
377// before comparing.
378func checkAllCopyRules(expected string) snapshotBuildInfoChecker {
379 return func(info *snapshotBuildInfo) {
380 info.r.t.Helper()
381 info.r.AssertTrimmedStringEquals("Incorrect copy rules", expected, info.copyRules)
382 }
383}
384
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +0000385func checkAllOtherCopyRules(expected string) snapshotBuildInfoChecker {
386 return func(info *snapshotBuildInfo) {
387 info.r.t.Helper()
388 info.r.AssertTrimmedStringEquals("Incorrect copy rules", expected, info.otherCopyRules)
389 }
390}
391
Paul Duffin3d1248c2020-04-09 00:10:17 +0100392// Check that the specified paths match the list of zips to merge with the intermediate zip.
393func checkMergeZips(expected ...string) snapshotBuildInfoChecker {
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000394 return func(info *snapshotBuildInfo) {
395 info.r.t.Helper()
396 if info.intermediateZip == "" {
397 info.r.t.Errorf("No intermediate zip file was created")
398 }
Paul Duffin3d1248c2020-04-09 00:10:17 +0100399
400 info.r.AssertDeepEquals("mismatching merge zip files", expected, info.mergeZips)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000401 }
402}
403
404// Encapsulates information about the snapshot build structure in order to insulate tests from
405// knowing too much about internal structures.
406//
407// All source/input paths are relative either the build directory. All dest/output paths are
408// relative to the snapshot root directory.
409type snapshotBuildInfo struct {
410 r *testSdkResult
411
412 // The contents of the generated Android.bp file
413 androidBpContents string
414
415 // The paths, relative to the snapshot root, of all files and directories copied into the
416 // snapshot.
417 snapshotContents []string
418
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +0000419 // A formatted representation of the src/dest pairs for a snapshot, one pair per line,
420 // of the format src -> dest
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000421 copyRules string
422
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +0000423 // A formatted representation of the src/dest pairs for files not in a snapshot, one pair
424 // per line, of the format src -> dest
425 otherCopyRules string
426
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000427 // The path to the intermediate zip, which is a zip created from the source files copied
428 // into the snapshot directory and which will be merged with other zips to form the final output.
429 // Is am empty string if there is no intermediate zip because there are no zips to merge in.
430 intermediateZip string
431
432 // The paths to the zips to merge into the output zip, does not include the intermediate
433 // zip.
434 mergeZips []string
435
436 // The final output zip.
437 outputZip string
438}
439
Paul Duffin82d90432019-11-30 09:24:33 +0000440var buildDir string
441
442func setUp() {
443 var err error
444 buildDir, err = ioutil.TempDir("", "soong_sdk_test")
445 if err != nil {
446 panic(err)
447 }
448}
449
450func tearDown() {
451 _ = os.RemoveAll(buildDir)
452}
453
454func runTestWithBuildDir(m *testing.M) {
455 run := func() int {
456 setUp()
457 defer tearDown()
458
459 return m.Run()
460 }
461
462 os.Exit(run())
463}