blob: 9e272019e1b27be4637575311ab59d518510f1b7 [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 Duffinc3c5d5e2019-11-29 20:45:22 +0000176func (h *TestHelper) AssertTrimmedStringEquals(message string, expected string, actual string) {
177 h.t.Helper()
178 h.AssertStringEquals(message, strings.TrimSpace(expected), strings.TrimSpace(actual))
179}
180
Paul Duffinb07fa512020-03-10 22:17:04 +0000181func (h *TestHelper) AssertDeepEquals(message string, expected interface{}, actual interface{}) {
182 h.t.Helper()
183 if !reflect.DeepEqual(actual, expected) {
184 h.t.Errorf("%s: expected %#v, actual %#v", message, expected, actual)
185 }
186}
187
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000188// Encapsulates result of processing an SDK definition. Provides support for
189// checking the state of the build structures.
190type testSdkResult struct {
191 TestHelper
192 ctx *android.TestContext
193 config android.Config
194}
195
196// Analyse the sdk build rules to extract information about what it is doing.
197
198// e.g. find the src/dest pairs from each cp command, the various zip files
199// generated, etc.
200func (r *testSdkResult) getSdkSnapshotBuildInfo(sdk *sdk) *snapshotBuildInfo {
201 androidBpContents := strings.NewReplacer("\\n", "\n").Replace(sdk.GetAndroidBpContentsForTests())
202
203 info := &snapshotBuildInfo{
204 r: r,
205 androidBpContents: androidBpContents,
206 }
207
208 buildParams := sdk.BuildParamsForTests()
209 copyRules := &strings.Builder{}
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +0000210 otherCopyRules := &strings.Builder{}
Paul Duffine1ddcc92020-03-03 16:01:26 +0000211 snapshotDirPrefix := sdk.builderForTests.snapshotDir.String() + "/"
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000212 for _, bp := range buildParams {
213 switch bp.Rule.String() {
214 case android.Cp.String():
Paul Duffine1ddcc92020-03-03 16:01:26 +0000215 output := bp.Output
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +0000216 // Get destination relative to the snapshot root
217 dest := output.Rel()
218 src := android.NormalizePathForTesting(bp.Input)
219 // We differentiate between copy rules for the snapshot, and copy rules for the install file.
Paul Duffine1ddcc92020-03-03 16:01:26 +0000220 if strings.HasPrefix(output.String(), snapshotDirPrefix) {
221 // Get source relative to build directory.
Paul Duffine1ddcc92020-03-03 16:01:26 +0000222 _, _ = fmt.Fprintf(copyRules, "%s -> %s\n", src, dest)
223 info.snapshotContents = append(info.snapshotContents, dest)
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +0000224 } else {
225 _, _ = fmt.Fprintf(otherCopyRules, "%s -> %s\n", src, dest)
Paul Duffine1ddcc92020-03-03 16:01:26 +0000226 }
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000227
228 case repackageZip.String():
229 // Add the destdir to the snapshot contents as that is effectively where
230 // the content of the repackaged zip is copied.
231 dest := bp.Args["destdir"]
232 info.snapshotContents = append(info.snapshotContents, dest)
233
234 case zipFiles.String():
235 // This could be an intermediate zip file and not the actual output zip.
236 // In that case this will be overridden when the rule to merge the zips
237 // is processed.
Paul Duffin9b478b02019-12-10 13:41:51 +0000238 info.outputZip = android.NormalizePathForTesting(bp.Output)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000239
240 case mergeZips.String():
241 // Copy the current outputZip to the intermediateZip.
242 info.intermediateZip = info.outputZip
Paul Duffin9b478b02019-12-10 13:41:51 +0000243 mergeInput := android.NormalizePathForTesting(bp.Input)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000244 if info.intermediateZip != mergeInput {
245 r.t.Errorf("Expected intermediate zip %s to be an input to merge zips but found %s instead",
246 info.intermediateZip, mergeInput)
247 }
248
249 // Override output zip (which was actually the intermediate zip file) with the actual
250 // output zip.
Paul Duffin9b478b02019-12-10 13:41:51 +0000251 info.outputZip = android.NormalizePathForTesting(bp.Output)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000252
253 // Save the zips to be merged into the intermediate zip.
Paul Duffin9b478b02019-12-10 13:41:51 +0000254 info.mergeZips = android.NormalizePathsForTesting(bp.Inputs)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000255 }
256 }
257
258 info.copyRules = copyRules.String()
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +0000259 info.otherCopyRules = otherCopyRules.String()
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000260
261 return info
262}
263
264func (r *testSdkResult) Module(name string, variant string) android.Module {
265 return r.ctx.ModuleForTests(name, variant).Module()
266}
267
268func (r *testSdkResult) ModuleForTests(name string, variant string) android.TestingModule {
269 return r.ctx.ModuleForTests(name, variant)
270}
271
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000272// 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 Duffin1356d8c2020-02-25 19:26:33 +0000277func (r *testSdkResult) CheckSnapshot(name string, dir string, checkers ...snapshotBuildInfoChecker) {
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000278 r.t.Helper()
279
Paul Duffin1356d8c2020-02-25 19:26:33 +0000280 // The sdk CommonOS variant is always responsible for generating the snapshot.
281 variant := android.CommonOS.Name
282
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000283 sdk := r.Module(name, variant).(*sdk)
284
285 snapshotBuildInfo := r.getSdkSnapshotBuildInfo(sdk)
286
287 // Check state of the snapshot build.
288 for _, checker := range checkers {
289 checker(snapshotBuildInfo)
290 }
291
292 // Make sure that the generated zip file is in the correct place.
293 actual := snapshotBuildInfo.outputZip
Paul Duffin593b3c92019-12-05 14:31:48 +0000294 if dir != "" {
295 dir = filepath.Clean(dir) + "/"
296 }
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000297 r.AssertStringEquals("Snapshot zip file in wrong place",
Paul Duffin593b3c92019-12-05 14:31:48 +0000298 fmt.Sprintf(".intermediates/%s%s/%s/%s-current.zip", dir, name, variant, name), actual)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000299
300 // Populate a mock filesystem with the files that would have been copied by
301 // the rules.
302 fs := make(map[string][]byte)
303 for _, dest := range snapshotBuildInfo.snapshotContents {
304 fs[dest] = nil
305 }
306
307 // Process the generated bp file to make sure it is valid.
308 testSdkWithFs(r.t, snapshotBuildInfo.androidBpContents, fs)
309}
310
311type snapshotBuildInfoChecker func(info *snapshotBuildInfo)
312
313// Check that the snapshot's generated Android.bp is correct.
314//
315// Both the expected and actual string are both trimmed before comparing.
316func checkAndroidBpContents(expected string) snapshotBuildInfoChecker {
317 return func(info *snapshotBuildInfo) {
318 info.r.t.Helper()
319 info.r.AssertTrimmedStringEquals("Android.bp contents do not match", expected, info.androidBpContents)
320 }
321}
322
323// Check that the snapshot's copy rules are correct.
324//
325// The copy rules are formatted as <src> -> <dest>, one per line and then compared
326// to the supplied expected string. Both the expected and actual string are trimmed
327// before comparing.
328func checkAllCopyRules(expected string) snapshotBuildInfoChecker {
329 return func(info *snapshotBuildInfo) {
330 info.r.t.Helper()
331 info.r.AssertTrimmedStringEquals("Incorrect copy rules", expected, info.copyRules)
332 }
333}
334
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +0000335func checkAllOtherCopyRules(expected string) snapshotBuildInfoChecker {
336 return func(info *snapshotBuildInfo) {
337 info.r.t.Helper()
338 info.r.AssertTrimmedStringEquals("Incorrect copy rules", expected, info.otherCopyRules)
339 }
340}
341
Paul Duffin3d1248c2020-04-09 00:10:17 +0100342// Check that the specified paths match the list of zips to merge with the intermediate zip.
343func checkMergeZips(expected ...string) snapshotBuildInfoChecker {
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000344 return func(info *snapshotBuildInfo) {
345 info.r.t.Helper()
346 if info.intermediateZip == "" {
347 info.r.t.Errorf("No intermediate zip file was created")
348 }
Paul Duffin3d1248c2020-04-09 00:10:17 +0100349
350 info.r.AssertDeepEquals("mismatching merge zip files", expected, info.mergeZips)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000351 }
352}
353
354// Encapsulates information about the snapshot build structure in order to insulate tests from
355// knowing too much about internal structures.
356//
357// All source/input paths are relative either the build directory. All dest/output paths are
358// relative to the snapshot root directory.
359type snapshotBuildInfo struct {
360 r *testSdkResult
361
362 // The contents of the generated Android.bp file
363 androidBpContents string
364
365 // The paths, relative to the snapshot root, of all files and directories copied into the
366 // snapshot.
367 snapshotContents []string
368
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +0000369 // A formatted representation of the src/dest pairs for a snapshot, one pair per line,
370 // of the format src -> dest
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000371 copyRules string
372
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +0000373 // A formatted representation of the src/dest pairs for files not in a snapshot, one pair
374 // per line, of the format src -> dest
375 otherCopyRules string
376
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000377 // The path to the intermediate zip, which is a zip created from the source files copied
378 // into the snapshot directory and which will be merged with other zips to form the final output.
379 // Is am empty string if there is no intermediate zip because there are no zips to merge in.
380 intermediateZip string
381
382 // The paths to the zips to merge into the output zip, does not include the intermediate
383 // zip.
384 mergeZips []string
385
386 // The final output zip.
387 outputZip string
388}
389
Paul Duffin82d90432019-11-30 09:24:33 +0000390var buildDir string
391
392func setUp() {
393 var err error
394 buildDir, err = ioutil.TempDir("", "soong_sdk_test")
395 if err != nil {
396 panic(err)
397 }
398}
399
400func tearDown() {
401 _ = os.RemoveAll(buildDir)
402}
403
404func runTestWithBuildDir(m *testing.M) {
405 run := func() int {
406 setUp()
407 defer tearDown()
408
409 return m.Run()
410 }
411
412 os.Exit(run())
413}
414
415func SkipIfNotLinux(t *testing.T) {
416 t.Helper()
417 if android.BuildOs != android.Linux {
418 t.Skipf("Skipping as sdk snapshot generation is only supported on %s not %s", android.Linux, android.BuildOs)
419 }
420}