blob: 40abdcd0f1f765424770cea4f731072a4cd47d6c [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 Duffin44f1d842020-06-26 20:17:02 +010087 ctx.PreArchMutators(android.RegisterComponentsMutator)
Paul Duffin593b3c92019-12-05 14:31:48 +000088 ctx.PreArchMutators(android.RegisterVisibilityRuleGatherer)
89 ctx.PostDepsMutators(android.RegisterVisibilityRuleEnforcer)
90
Paul Duffin82d90432019-11-30 09:24:33 +000091 // from java package
Paul Duffinf9b1da02019-12-18 19:51:55 +000092 java.RegisterJavaBuildComponents(ctx)
93 java.RegisterAppBuildComponents(ctx)
Paul Duffindd46f712020-02-10 13:37:10 +000094 java.RegisterSdkLibraryBuildComponents(ctx)
Paul Duffin884363e2019-12-19 10:21:09 +000095 java.RegisterStubsBuildComponents(ctx)
Paul Duffin7b81f5e2020-01-13 21:03:22 +000096 java.RegisterSystemModulesBuildComponents(ctx)
Paul Duffin82d90432019-11-30 09:24:33 +000097
98 // from cc package
Paul Duffin77980a82019-12-19 16:01:36 +000099 cc.RegisterRequiredBuildComponentsForTest(ctx)
Paul Duffin82d90432019-11-30 09:24:33 +0000100
101 // from apex package
102 ctx.RegisterModuleType("apex", apex.BundleFactory)
103 ctx.RegisterModuleType("apex_key", apex.ApexKeyFactory)
104 ctx.PostDepsMutators(apex.RegisterPostDepsMutators)
105
106 // from this package
Paul Duffin8150da62019-12-16 17:21:27 +0000107 ctx.RegisterModuleType("sdk", SdkModuleFactory)
Paul Duffin82d90432019-11-30 09:24:33 +0000108 ctx.RegisterModuleType("sdk_snapshot", SnapshotModuleFactory)
Paul Duffin8150da62019-12-16 17:21:27 +0000109 ctx.RegisterModuleType("module_exports", ModuleExportsFactory)
110 ctx.RegisterModuleType("module_exports_snapshot", ModuleExportsSnapshotsFactory)
Paul Duffin82d90432019-11-30 09:24:33 +0000111 ctx.PreDepsMutators(RegisterPreDepsMutators)
112 ctx.PostDepsMutators(RegisterPostDepsMutators)
113
Colin Cross98be1bb2019-12-13 20:41:13 -0800114 ctx.Register(config)
Paul Duffin82d90432019-11-30 09:24:33 +0000115
116 return ctx, config
117}
118
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000119func testSdkWithFs(t *testing.T, bp string, fs map[string][]byte) *testSdkResult {
120 t.Helper()
121 ctx, config := testSdkContext(bp, fs)
Paul Duffin593b3c92019-12-05 14:31:48 +0000122 _, errs := ctx.ParseBlueprintsFiles(".")
Paul Duffin82d90432019-11-30 09:24:33 +0000123 android.FailIfErrored(t, errs)
124 _, errs = ctx.PrepareBuildActions(config)
125 android.FailIfErrored(t, errs)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000126 return &testSdkResult{
127 TestHelper: TestHelper{t: t},
128 ctx: ctx,
129 config: config,
130 }
Paul Duffin82d90432019-11-30 09:24:33 +0000131}
132
133func testSdkError(t *testing.T, pattern, bp string) {
134 t.Helper()
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000135 ctx, config := testSdkContext(bp, nil)
Paul Duffin82d90432019-11-30 09:24:33 +0000136 _, errs := ctx.ParseFileList(".", []string{"Android.bp"})
137 if len(errs) > 0 {
138 android.FailIfNoMatchingErrors(t, pattern, errs)
139 return
140 }
141 _, errs = ctx.PrepareBuildActions(config)
142 if len(errs) > 0 {
143 android.FailIfNoMatchingErrors(t, pattern, errs)
144 return
145 }
146
147 t.Fatalf("missing expected error %q (0 errors are returned)", pattern)
148}
149
150func ensureListContains(t *testing.T, result []string, expected string) {
151 t.Helper()
152 if !android.InList(expected, result) {
153 t.Errorf("%q is not found in %v", expected, result)
154 }
155}
156
157func pathsToStrings(paths android.Paths) []string {
158 var ret []string
159 for _, p := range paths {
160 ret = append(ret, p.String())
161 }
162 return ret
163}
164
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000165// Provides general test support.
166type TestHelper struct {
167 t *testing.T
168}
169
170func (h *TestHelper) AssertStringEquals(message string, expected string, actual string) {
171 h.t.Helper()
172 if actual != expected {
173 h.t.Errorf("%s: expected %s, actual %s", message, expected, actual)
Paul Duffin82d90432019-11-30 09:24:33 +0000174 }
175}
176
Paul Duffin4b8b7932020-05-06 12:35:38 +0100177func (h *TestHelper) AssertErrorMessageEquals(message string, expected string, actual error) {
178 h.t.Helper()
179 if actual == nil {
180 h.t.Errorf("Expected error but was nil")
181 } else if actual.Error() != expected {
182 h.t.Errorf("%s: expected %s, actual %s", message, expected, actual.Error())
183 }
184}
185
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000186func (h *TestHelper) AssertTrimmedStringEquals(message string, expected string, actual string) {
187 h.t.Helper()
188 h.AssertStringEquals(message, strings.TrimSpace(expected), strings.TrimSpace(actual))
189}
190
Paul Duffinb07fa512020-03-10 22:17:04 +0000191func (h *TestHelper) AssertDeepEquals(message string, expected interface{}, actual interface{}) {
192 h.t.Helper()
193 if !reflect.DeepEqual(actual, expected) {
194 h.t.Errorf("%s: expected %#v, actual %#v", message, expected, actual)
195 }
196}
197
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000198// Encapsulates result of processing an SDK definition. Provides support for
199// checking the state of the build structures.
200type testSdkResult struct {
201 TestHelper
202 ctx *android.TestContext
203 config android.Config
204}
205
206// Analyse the sdk build rules to extract information about what it is doing.
207
208// e.g. find the src/dest pairs from each cp command, the various zip files
209// generated, etc.
210func (r *testSdkResult) getSdkSnapshotBuildInfo(sdk *sdk) *snapshotBuildInfo {
Paul Duffin11108272020-05-11 22:59:25 +0100211 androidBpContents := sdk.GetAndroidBpContentsForTests()
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000212
213 info := &snapshotBuildInfo{
214 r: r,
215 androidBpContents: androidBpContents,
216 }
217
218 buildParams := sdk.BuildParamsForTests()
219 copyRules := &strings.Builder{}
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +0000220 otherCopyRules := &strings.Builder{}
Paul Duffine1ddcc92020-03-03 16:01:26 +0000221 snapshotDirPrefix := sdk.builderForTests.snapshotDir.String() + "/"
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000222 for _, bp := range buildParams {
223 switch bp.Rule.String() {
224 case android.Cp.String():
Paul Duffine1ddcc92020-03-03 16:01:26 +0000225 output := bp.Output
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +0000226 // Get destination relative to the snapshot root
227 dest := output.Rel()
228 src := android.NormalizePathForTesting(bp.Input)
229 // We differentiate between copy rules for the snapshot, and copy rules for the install file.
Paul Duffine1ddcc92020-03-03 16:01:26 +0000230 if strings.HasPrefix(output.String(), snapshotDirPrefix) {
231 // Get source relative to build directory.
Paul Duffine1ddcc92020-03-03 16:01:26 +0000232 _, _ = fmt.Fprintf(copyRules, "%s -> %s\n", src, dest)
233 info.snapshotContents = append(info.snapshotContents, dest)
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +0000234 } else {
235 _, _ = fmt.Fprintf(otherCopyRules, "%s -> %s\n", src, dest)
Paul Duffine1ddcc92020-03-03 16:01:26 +0000236 }
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000237
238 case repackageZip.String():
239 // Add the destdir to the snapshot contents as that is effectively where
240 // the content of the repackaged zip is copied.
241 dest := bp.Args["destdir"]
242 info.snapshotContents = append(info.snapshotContents, dest)
243
244 case zipFiles.String():
245 // This could be an intermediate zip file and not the actual output zip.
246 // In that case this will be overridden when the rule to merge the zips
247 // is processed.
Paul Duffin9b478b02019-12-10 13:41:51 +0000248 info.outputZip = android.NormalizePathForTesting(bp.Output)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000249
250 case mergeZips.String():
251 // Copy the current outputZip to the intermediateZip.
252 info.intermediateZip = info.outputZip
Paul Duffin9b478b02019-12-10 13:41:51 +0000253 mergeInput := android.NormalizePathForTesting(bp.Input)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000254 if info.intermediateZip != mergeInput {
255 r.t.Errorf("Expected intermediate zip %s to be an input to merge zips but found %s instead",
256 info.intermediateZip, mergeInput)
257 }
258
259 // Override output zip (which was actually the intermediate zip file) with the actual
260 // output zip.
Paul Duffin9b478b02019-12-10 13:41:51 +0000261 info.outputZip = android.NormalizePathForTesting(bp.Output)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000262
263 // Save the zips to be merged into the intermediate zip.
Paul Duffin9b478b02019-12-10 13:41:51 +0000264 info.mergeZips = android.NormalizePathsForTesting(bp.Inputs)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000265 }
266 }
267
268 info.copyRules = copyRules.String()
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +0000269 info.otherCopyRules = otherCopyRules.String()
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000270
271 return info
272}
273
274func (r *testSdkResult) Module(name string, variant string) android.Module {
275 return r.ctx.ModuleForTests(name, variant).Module()
276}
277
278func (r *testSdkResult) ModuleForTests(name string, variant string) android.TestingModule {
279 return r.ctx.ModuleForTests(name, variant)
280}
281
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000282// Check the snapshot build rules.
283//
284// Takes a list of functions which check different facets of the snapshot build rules.
285// Allows each test to customize what is checked without duplicating lots of code
286// or proliferating check methods of different flavors.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000287func (r *testSdkResult) CheckSnapshot(name string, dir string, checkers ...snapshotBuildInfoChecker) {
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000288 r.t.Helper()
289
Paul Duffin1356d8c2020-02-25 19:26:33 +0000290 // The sdk CommonOS variant is always responsible for generating the snapshot.
291 variant := android.CommonOS.Name
292
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000293 sdk := r.Module(name, variant).(*sdk)
294
295 snapshotBuildInfo := r.getSdkSnapshotBuildInfo(sdk)
296
297 // Check state of the snapshot build.
298 for _, checker := range checkers {
299 checker(snapshotBuildInfo)
300 }
301
302 // Make sure that the generated zip file is in the correct place.
303 actual := snapshotBuildInfo.outputZip
Paul Duffin593b3c92019-12-05 14:31:48 +0000304 if dir != "" {
305 dir = filepath.Clean(dir) + "/"
306 }
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000307 r.AssertStringEquals("Snapshot zip file in wrong place",
Paul Duffin593b3c92019-12-05 14:31:48 +0000308 fmt.Sprintf(".intermediates/%s%s/%s/%s-current.zip", dir, name, variant, name), actual)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000309
310 // Populate a mock filesystem with the files that would have been copied by
311 // the rules.
312 fs := make(map[string][]byte)
313 for _, dest := range snapshotBuildInfo.snapshotContents {
314 fs[dest] = nil
315 }
316
317 // Process the generated bp file to make sure it is valid.
318 testSdkWithFs(r.t, snapshotBuildInfo.androidBpContents, fs)
319}
320
321type snapshotBuildInfoChecker func(info *snapshotBuildInfo)
322
323// Check that the snapshot's generated Android.bp is correct.
324//
325// Both the expected and actual string are both trimmed before comparing.
326func checkAndroidBpContents(expected string) snapshotBuildInfoChecker {
327 return func(info *snapshotBuildInfo) {
328 info.r.t.Helper()
329 info.r.AssertTrimmedStringEquals("Android.bp contents do not match", expected, info.androidBpContents)
330 }
331}
332
333// Check that the snapshot's copy rules are correct.
334//
335// The copy rules are formatted as <src> -> <dest>, one per line and then compared
336// to the supplied expected string. Both the expected and actual string are trimmed
337// before comparing.
338func checkAllCopyRules(expected string) snapshotBuildInfoChecker {
339 return func(info *snapshotBuildInfo) {
340 info.r.t.Helper()
341 info.r.AssertTrimmedStringEquals("Incorrect copy rules", expected, info.copyRules)
342 }
343}
344
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +0000345func checkAllOtherCopyRules(expected string) snapshotBuildInfoChecker {
346 return func(info *snapshotBuildInfo) {
347 info.r.t.Helper()
348 info.r.AssertTrimmedStringEquals("Incorrect copy rules", expected, info.otherCopyRules)
349 }
350}
351
Paul Duffin3d1248c2020-04-09 00:10:17 +0100352// Check that the specified paths match the list of zips to merge with the intermediate zip.
353func checkMergeZips(expected ...string) snapshotBuildInfoChecker {
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000354 return func(info *snapshotBuildInfo) {
355 info.r.t.Helper()
356 if info.intermediateZip == "" {
357 info.r.t.Errorf("No intermediate zip file was created")
358 }
Paul Duffin3d1248c2020-04-09 00:10:17 +0100359
360 info.r.AssertDeepEquals("mismatching merge zip files", expected, info.mergeZips)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000361 }
362}
363
364// Encapsulates information about the snapshot build structure in order to insulate tests from
365// knowing too much about internal structures.
366//
367// All source/input paths are relative either the build directory. All dest/output paths are
368// relative to the snapshot root directory.
369type snapshotBuildInfo struct {
370 r *testSdkResult
371
372 // The contents of the generated Android.bp file
373 androidBpContents string
374
375 // The paths, relative to the snapshot root, of all files and directories copied into the
376 // snapshot.
377 snapshotContents []string
378
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +0000379 // A formatted representation of the src/dest pairs for a snapshot, one pair per line,
380 // of the format src -> dest
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000381 copyRules string
382
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +0000383 // A formatted representation of the src/dest pairs for files not in a snapshot, one pair
384 // per line, of the format src -> dest
385 otherCopyRules string
386
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000387 // The path to the intermediate zip, which is a zip created from the source files copied
388 // into the snapshot directory and which will be merged with other zips to form the final output.
389 // Is am empty string if there is no intermediate zip because there are no zips to merge in.
390 intermediateZip string
391
392 // The paths to the zips to merge into the output zip, does not include the intermediate
393 // zip.
394 mergeZips []string
395
396 // The final output zip.
397 outputZip string
398}
399
Paul Duffin82d90432019-11-30 09:24:33 +0000400var buildDir string
401
402func setUp() {
403 var err error
404 buildDir, err = ioutil.TempDir("", "soong_sdk_test")
405 if err != nil {
406 panic(err)
407 }
408}
409
410func tearDown() {
411 _ = os.RemoveAll(buildDir)
412}
413
414func runTestWithBuildDir(m *testing.M) {
415 run := func() int {
416 setUp()
417 defer tearDown()
418
419 return m.Run()
420 }
421
422 os.Exit(run())
423}
424
425func SkipIfNotLinux(t *testing.T) {
426 t.Helper()
427 if android.BuildOs != android.Linux {
428 t.Skipf("Skipping as sdk snapshot generation is only supported on %s not %s", android.Linux, android.BuildOs)
429 }
430}