blob: 436175419e2a37c6515f508d35514b53727dd6bb [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
Paul Duffinc3c5d5e2019-11-29 20:45:22 +000032func testSdkContext(bp string, fs map[string][]byte) (*android.TestContext, android.Config) {
Colin Cross98be1bb2019-12-13 20:41:13 -080033 bp = bp + `
34 apex_key {
35 name: "myapex.key",
36 public_key: "myapex.avbpubkey",
37 private_key: "myapex.pem",
38 }
39
40 android_app_certificate {
41 name: "myapex.cert",
42 certificate: "myapex",
43 }
Paul Duffina04c1072020-03-02 10:16:35 +000044 ` + cc.GatherRequiredDepsForTest(android.Android, android.Windows)
Colin Cross98be1bb2019-12-13 20:41:13 -080045
46 mockFS := map[string][]byte{
47 "build/make/target/product/security": nil,
48 "apex_manifest.json": nil,
49 "system/sepolicy/apex/myapex-file_contexts": nil,
50 "system/sepolicy/apex/myapex2-file_contexts": nil,
51 "myapex.avbpubkey": nil,
52 "myapex.pem": nil,
53 "myapex.x509.pem": nil,
54 "myapex.pk8": nil,
55 }
56
Colin Crossf28329d2020-02-15 11:00:10 -080057 cc.GatherRequiredFilesForTest(mockFS)
58
Colin Cross98be1bb2019-12-13 20:41:13 -080059 for k, v := range fs {
60 mockFS[k] = v
61 }
62
63 config := android.TestArchConfig(buildDir, nil, bp, mockFS)
64
Paul Duffin08798aa2020-02-27 13:12:46 +000065 // Add windows as a default disable OS to test behavior when some OS variants
66 // are disabled.
67 config.Targets[android.Windows] = []android.Target{
68 {android.Windows, android.Arch{ArchType: android.X86_64}, android.NativeBridgeDisabled, "", ""},
69 }
70
Paul Duffin82d90432019-11-30 09:24:33 +000071 ctx := android.NewTestArchContext()
72
Paul Duffin8c3fec42020-03-04 20:15:08 +000073 // Enable androidmk support.
74 // * Register the singleton
75 // * Configure that we are inside make
76 // * Add CommonOS to ensure that androidmk processing works.
77 android.RegisterAndroidMkBuildComponents(ctx)
78 android.SetInMakeForTests(config)
79 config.Targets[android.CommonOS] = []android.Target{
80 {android.CommonOS, android.Arch{ArchType: android.Common}, android.NativeBridgeDisabled, "", ""},
81 }
82
Paul Duffin82d90432019-11-30 09:24:33 +000083 // from android package
Paul Duffinc1327422020-01-14 12:15:29 +000084 android.RegisterPackageBuildComponents(ctx)
Paul Duffin593b3c92019-12-05 14:31:48 +000085 ctx.PreArchMutators(android.RegisterVisibilityRuleChecker)
Paul Duffin82d90432019-11-30 09:24:33 +000086 ctx.PreArchMutators(android.RegisterDefaultsPreArchMutators)
Paul Duffin593b3c92019-12-05 14:31:48 +000087 ctx.PreArchMutators(android.RegisterVisibilityRuleGatherer)
88 ctx.PostDepsMutators(android.RegisterVisibilityRuleEnforcer)
89
Paul Duffin82d90432019-11-30 09:24:33 +000090 // from java package
Paul Duffinf9b1da02019-12-18 19:51:55 +000091 java.RegisterJavaBuildComponents(ctx)
92 java.RegisterAppBuildComponents(ctx)
Paul Duffindd46f712020-02-10 13:37:10 +000093 java.RegisterSdkLibraryBuildComponents(ctx)
Paul Duffin884363e2019-12-19 10:21:09 +000094 java.RegisterStubsBuildComponents(ctx)
Paul Duffin7b81f5e2020-01-13 21:03:22 +000095 java.RegisterSystemModulesBuildComponents(ctx)
Paul Duffin82d90432019-11-30 09:24:33 +000096
97 // from cc package
Paul Duffin77980a82019-12-19 16:01:36 +000098 cc.RegisterRequiredBuildComponentsForTest(ctx)
Paul Duffin82d90432019-11-30 09:24:33 +000099
100 // from apex package
101 ctx.RegisterModuleType("apex", apex.BundleFactory)
102 ctx.RegisterModuleType("apex_key", apex.ApexKeyFactory)
103 ctx.PostDepsMutators(apex.RegisterPostDepsMutators)
104
105 // from this package
Paul Duffin8150da62019-12-16 17:21:27 +0000106 ctx.RegisterModuleType("sdk", SdkModuleFactory)
Paul Duffin82d90432019-11-30 09:24:33 +0000107 ctx.RegisterModuleType("sdk_snapshot", SnapshotModuleFactory)
Paul Duffin8150da62019-12-16 17:21:27 +0000108 ctx.RegisterModuleType("module_exports", ModuleExportsFactory)
109 ctx.RegisterModuleType("module_exports_snapshot", ModuleExportsSnapshotsFactory)
Paul Duffin82d90432019-11-30 09:24:33 +0000110 ctx.PreDepsMutators(RegisterPreDepsMutators)
111 ctx.PostDepsMutators(RegisterPostDepsMutators)
112
Colin Cross98be1bb2019-12-13 20:41:13 -0800113 ctx.Register(config)
Paul Duffin82d90432019-11-30 09:24:33 +0000114
115 return ctx, config
116}
117
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000118func testSdkWithFs(t *testing.T, bp string, fs map[string][]byte) *testSdkResult {
119 t.Helper()
120 ctx, config := testSdkContext(bp, fs)
Paul Duffin593b3c92019-12-05 14:31:48 +0000121 _, errs := ctx.ParseBlueprintsFiles(".")
Paul Duffin82d90432019-11-30 09:24:33 +0000122 android.FailIfErrored(t, errs)
123 _, errs = ctx.PrepareBuildActions(config)
124 android.FailIfErrored(t, errs)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000125 return &testSdkResult{
126 TestHelper: TestHelper{t: t},
127 ctx: ctx,
128 config: config,
129 }
Paul Duffin82d90432019-11-30 09:24:33 +0000130}
131
132func testSdkError(t *testing.T, pattern, bp string) {
133 t.Helper()
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000134 ctx, config := testSdkContext(bp, nil)
Paul Duffin82d90432019-11-30 09:24:33 +0000135 _, errs := ctx.ParseFileList(".", []string{"Android.bp"})
136 if len(errs) > 0 {
137 android.FailIfNoMatchingErrors(t, pattern, errs)
138 return
139 }
140 _, errs = ctx.PrepareBuildActions(config)
141 if len(errs) > 0 {
142 android.FailIfNoMatchingErrors(t, pattern, errs)
143 return
144 }
145
146 t.Fatalf("missing expected error %q (0 errors are returned)", pattern)
147}
148
149func ensureListContains(t *testing.T, result []string, expected string) {
150 t.Helper()
151 if !android.InList(expected, result) {
152 t.Errorf("%q is not found in %v", expected, result)
153 }
154}
155
156func pathsToStrings(paths android.Paths) []string {
157 var ret []string
158 for _, p := range paths {
159 ret = append(ret, p.String())
160 }
161 return ret
162}
163
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000164// Provides general test support.
165type TestHelper struct {
166 t *testing.T
167}
168
169func (h *TestHelper) AssertStringEquals(message string, expected string, actual string) {
170 h.t.Helper()
171 if actual != expected {
172 h.t.Errorf("%s: expected %s, actual %s", message, expected, actual)
Paul Duffin82d90432019-11-30 09:24:33 +0000173 }
174}
175
Paul Duffin4b8b7932020-05-06 12:35:38 +0100176func (h *TestHelper) AssertErrorMessageEquals(message string, expected string, actual error) {
177 h.t.Helper()
178 if actual == nil {
179 h.t.Errorf("Expected error but was nil")
180 } else if actual.Error() != expected {
181 h.t.Errorf("%s: expected %s, actual %s", message, expected, actual.Error())
182 }
183}
184
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000185func (h *TestHelper) AssertTrimmedStringEquals(message string, expected string, actual string) {
186 h.t.Helper()
187 h.AssertStringEquals(message, strings.TrimSpace(expected), strings.TrimSpace(actual))
188}
189
Paul Duffinb07fa512020-03-10 22:17:04 +0000190func (h *TestHelper) AssertDeepEquals(message string, expected interface{}, actual interface{}) {
191 h.t.Helper()
192 if !reflect.DeepEqual(actual, expected) {
193 h.t.Errorf("%s: expected %#v, actual %#v", message, expected, actual)
194 }
195}
196
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000197// Encapsulates result of processing an SDK definition. Provides support for
198// checking the state of the build structures.
199type testSdkResult struct {
200 TestHelper
201 ctx *android.TestContext
202 config android.Config
203}
204
205// Analyse the sdk build rules to extract information about what it is doing.
206
207// e.g. find the src/dest pairs from each cp command, the various zip files
208// generated, etc.
209func (r *testSdkResult) getSdkSnapshotBuildInfo(sdk *sdk) *snapshotBuildInfo {
Paul Duffin11108272020-05-11 22:59:25 +0100210 androidBpContents := sdk.GetAndroidBpContentsForTests()
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000211
212 info := &snapshotBuildInfo{
213 r: r,
214 androidBpContents: androidBpContents,
215 }
216
217 buildParams := sdk.BuildParamsForTests()
218 copyRules := &strings.Builder{}
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +0000219 otherCopyRules := &strings.Builder{}
Paul Duffine1ddcc92020-03-03 16:01:26 +0000220 snapshotDirPrefix := sdk.builderForTests.snapshotDir.String() + "/"
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000221 for _, bp := range buildParams {
222 switch bp.Rule.String() {
223 case android.Cp.String():
Paul Duffine1ddcc92020-03-03 16:01:26 +0000224 output := bp.Output
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +0000225 // Get destination relative to the snapshot root
226 dest := output.Rel()
227 src := android.NormalizePathForTesting(bp.Input)
228 // We differentiate between copy rules for the snapshot, and copy rules for the install file.
Paul Duffine1ddcc92020-03-03 16:01:26 +0000229 if strings.HasPrefix(output.String(), snapshotDirPrefix) {
230 // Get source relative to build directory.
Paul Duffine1ddcc92020-03-03 16:01:26 +0000231 _, _ = fmt.Fprintf(copyRules, "%s -> %s\n", src, dest)
232 info.snapshotContents = append(info.snapshotContents, dest)
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +0000233 } else {
234 _, _ = fmt.Fprintf(otherCopyRules, "%s -> %s\n", src, dest)
Paul Duffine1ddcc92020-03-03 16:01:26 +0000235 }
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000236
237 case repackageZip.String():
238 // Add the destdir to the snapshot contents as that is effectively where
239 // the content of the repackaged zip is copied.
240 dest := bp.Args["destdir"]
241 info.snapshotContents = append(info.snapshotContents, dest)
242
243 case zipFiles.String():
244 // This could be an intermediate zip file and not the actual output zip.
245 // In that case this will be overridden when the rule to merge the zips
246 // is processed.
Paul Duffin9b478b02019-12-10 13:41:51 +0000247 info.outputZip = android.NormalizePathForTesting(bp.Output)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000248
249 case mergeZips.String():
250 // Copy the current outputZip to the intermediateZip.
251 info.intermediateZip = info.outputZip
Paul Duffin9b478b02019-12-10 13:41:51 +0000252 mergeInput := android.NormalizePathForTesting(bp.Input)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000253 if info.intermediateZip != mergeInput {
254 r.t.Errorf("Expected intermediate zip %s to be an input to merge zips but found %s instead",
255 info.intermediateZip, mergeInput)
256 }
257
258 // Override output zip (which was actually the intermediate zip file) with the actual
259 // output zip.
Paul Duffin9b478b02019-12-10 13:41:51 +0000260 info.outputZip = android.NormalizePathForTesting(bp.Output)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000261
262 // Save the zips to be merged into the intermediate zip.
Paul Duffin9b478b02019-12-10 13:41:51 +0000263 info.mergeZips = android.NormalizePathsForTesting(bp.Inputs)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000264 }
265 }
266
267 info.copyRules = copyRules.String()
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +0000268 info.otherCopyRules = otherCopyRules.String()
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000269
270 return info
271}
272
273func (r *testSdkResult) Module(name string, variant string) android.Module {
274 return r.ctx.ModuleForTests(name, variant).Module()
275}
276
277func (r *testSdkResult) ModuleForTests(name string, variant string) android.TestingModule {
278 return r.ctx.ModuleForTests(name, variant)
279}
280
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000281// Check the snapshot build rules.
282//
283// Takes a list of functions which check different facets of the snapshot build rules.
284// Allows each test to customize what is checked without duplicating lots of code
285// or proliferating check methods of different flavors.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000286func (r *testSdkResult) CheckSnapshot(name string, dir string, checkers ...snapshotBuildInfoChecker) {
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000287 r.t.Helper()
288
Paul Duffin1356d8c2020-02-25 19:26:33 +0000289 // The sdk CommonOS variant is always responsible for generating the snapshot.
290 variant := android.CommonOS.Name
291
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000292 sdk := r.Module(name, variant).(*sdk)
293
294 snapshotBuildInfo := r.getSdkSnapshotBuildInfo(sdk)
295
296 // Check state of the snapshot build.
297 for _, checker := range checkers {
298 checker(snapshotBuildInfo)
299 }
300
301 // Make sure that the generated zip file is in the correct place.
302 actual := snapshotBuildInfo.outputZip
Paul Duffin593b3c92019-12-05 14:31:48 +0000303 if dir != "" {
304 dir = filepath.Clean(dir) + "/"
305 }
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000306 r.AssertStringEquals("Snapshot zip file in wrong place",
Paul Duffin593b3c92019-12-05 14:31:48 +0000307 fmt.Sprintf(".intermediates/%s%s/%s/%s-current.zip", dir, name, variant, name), actual)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000308
309 // Populate a mock filesystem with the files that would have been copied by
310 // the rules.
311 fs := make(map[string][]byte)
312 for _, dest := range snapshotBuildInfo.snapshotContents {
313 fs[dest] = nil
314 }
315
316 // Process the generated bp file to make sure it is valid.
317 testSdkWithFs(r.t, snapshotBuildInfo.androidBpContents, fs)
318}
319
320type snapshotBuildInfoChecker func(info *snapshotBuildInfo)
321
322// Check that the snapshot's generated Android.bp is correct.
323//
324// Both the expected and actual string are both trimmed before comparing.
325func checkAndroidBpContents(expected string) snapshotBuildInfoChecker {
326 return func(info *snapshotBuildInfo) {
327 info.r.t.Helper()
328 info.r.AssertTrimmedStringEquals("Android.bp contents do not match", expected, info.androidBpContents)
329 }
330}
331
332// Check that the snapshot's copy rules are correct.
333//
334// The copy rules are formatted as <src> -> <dest>, one per line and then compared
335// to the supplied expected string. Both the expected and actual string are trimmed
336// before comparing.
337func checkAllCopyRules(expected string) snapshotBuildInfoChecker {
338 return func(info *snapshotBuildInfo) {
339 info.r.t.Helper()
340 info.r.AssertTrimmedStringEquals("Incorrect copy rules", expected, info.copyRules)
341 }
342}
343
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +0000344func checkAllOtherCopyRules(expected string) snapshotBuildInfoChecker {
345 return func(info *snapshotBuildInfo) {
346 info.r.t.Helper()
347 info.r.AssertTrimmedStringEquals("Incorrect copy rules", expected, info.otherCopyRules)
348 }
349}
350
Paul Duffin3d1248c2020-04-09 00:10:17 +0100351// Check that the specified paths match the list of zips to merge with the intermediate zip.
352func checkMergeZips(expected ...string) snapshotBuildInfoChecker {
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000353 return func(info *snapshotBuildInfo) {
354 info.r.t.Helper()
355 if info.intermediateZip == "" {
356 info.r.t.Errorf("No intermediate zip file was created")
357 }
Paul Duffin3d1248c2020-04-09 00:10:17 +0100358
359 info.r.AssertDeepEquals("mismatching merge zip files", expected, info.mergeZips)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000360 }
361}
362
363// Encapsulates information about the snapshot build structure in order to insulate tests from
364// knowing too much about internal structures.
365//
366// All source/input paths are relative either the build directory. All dest/output paths are
367// relative to the snapshot root directory.
368type snapshotBuildInfo struct {
369 r *testSdkResult
370
371 // The contents of the generated Android.bp file
372 androidBpContents string
373
374 // The paths, relative to the snapshot root, of all files and directories copied into the
375 // snapshot.
376 snapshotContents []string
377
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +0000378 // A formatted representation of the src/dest pairs for a snapshot, one pair per line,
379 // of the format src -> dest
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000380 copyRules string
381
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +0000382 // A formatted representation of the src/dest pairs for files not in a snapshot, one pair
383 // per line, of the format src -> dest
384 otherCopyRules string
385
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000386 // The path to the intermediate zip, which is a zip created from the source files copied
387 // into the snapshot directory and which will be merged with other zips to form the final output.
388 // Is am empty string if there is no intermediate zip because there are no zips to merge in.
389 intermediateZip string
390
391 // The paths to the zips to merge into the output zip, does not include the intermediate
392 // zip.
393 mergeZips []string
394
395 // The final output zip.
396 outputZip string
397}
398
Paul Duffin82d90432019-11-30 09:24:33 +0000399var buildDir string
400
401func setUp() {
402 var err error
403 buildDir, err = ioutil.TempDir("", "soong_sdk_test")
404 if err != nil {
405 panic(err)
406 }
407}
408
409func tearDown() {
410 _ = os.RemoveAll(buildDir)
411}
412
413func runTestWithBuildDir(m *testing.M) {
414 run := func() int {
415 setUp()
416 defer tearDown()
417
418 return m.Run()
419 }
420
421 os.Exit(run())
422}
423
424func SkipIfNotLinux(t *testing.T) {
425 t.Helper()
426 if android.BuildOs != android.Linux {
427 t.Skipf("Skipping as sdk snapshot generation is only supported on %s not %s", android.Linux, android.BuildOs)
428 }
429}