blob: 00245cef47fb017eb327a2e2b14d517d78670fd5 [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 Duffin884363e2019-12-19 10:21:09 +000093 java.RegisterStubsBuildComponents(ctx)
Paul Duffin7b81f5e2020-01-13 21:03:22 +000094 java.RegisterSystemModulesBuildComponents(ctx)
Paul Duffin82d90432019-11-30 09:24:33 +000095
96 // from cc package
Paul Duffin77980a82019-12-19 16:01:36 +000097 cc.RegisterRequiredBuildComponentsForTest(ctx)
Paul Duffin82d90432019-11-30 09:24:33 +000098
99 // from apex package
100 ctx.RegisterModuleType("apex", apex.BundleFactory)
101 ctx.RegisterModuleType("apex_key", apex.ApexKeyFactory)
102 ctx.PostDepsMutators(apex.RegisterPostDepsMutators)
103
104 // from this package
Paul Duffin8150da62019-12-16 17:21:27 +0000105 ctx.RegisterModuleType("sdk", SdkModuleFactory)
Paul Duffin82d90432019-11-30 09:24:33 +0000106 ctx.RegisterModuleType("sdk_snapshot", SnapshotModuleFactory)
Paul Duffin8150da62019-12-16 17:21:27 +0000107 ctx.RegisterModuleType("module_exports", ModuleExportsFactory)
108 ctx.RegisterModuleType("module_exports_snapshot", ModuleExportsSnapshotsFactory)
Paul Duffin82d90432019-11-30 09:24:33 +0000109 ctx.PreDepsMutators(RegisterPreDepsMutators)
110 ctx.PostDepsMutators(RegisterPostDepsMutators)
111
Colin Cross98be1bb2019-12-13 20:41:13 -0800112 ctx.Register(config)
Paul Duffin82d90432019-11-30 09:24:33 +0000113
114 return ctx, config
115}
116
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000117func testSdkWithFs(t *testing.T, bp string, fs map[string][]byte) *testSdkResult {
118 t.Helper()
119 ctx, config := testSdkContext(bp, fs)
Paul Duffin593b3c92019-12-05 14:31:48 +0000120 _, errs := ctx.ParseBlueprintsFiles(".")
Paul Duffin82d90432019-11-30 09:24:33 +0000121 android.FailIfErrored(t, errs)
122 _, errs = ctx.PrepareBuildActions(config)
123 android.FailIfErrored(t, errs)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000124 return &testSdkResult{
125 TestHelper: TestHelper{t: t},
126 ctx: ctx,
127 config: config,
128 }
Paul Duffin82d90432019-11-30 09:24:33 +0000129}
130
131func testSdkError(t *testing.T, pattern, bp string) {
132 t.Helper()
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000133 ctx, config := testSdkContext(bp, nil)
Paul Duffin82d90432019-11-30 09:24:33 +0000134 _, errs := ctx.ParseFileList(".", []string{"Android.bp"})
135 if len(errs) > 0 {
136 android.FailIfNoMatchingErrors(t, pattern, errs)
137 return
138 }
139 _, errs = ctx.PrepareBuildActions(config)
140 if len(errs) > 0 {
141 android.FailIfNoMatchingErrors(t, pattern, errs)
142 return
143 }
144
145 t.Fatalf("missing expected error %q (0 errors are returned)", pattern)
146}
147
148func ensureListContains(t *testing.T, result []string, expected string) {
149 t.Helper()
150 if !android.InList(expected, result) {
151 t.Errorf("%q is not found in %v", expected, result)
152 }
153}
154
155func pathsToStrings(paths android.Paths) []string {
156 var ret []string
157 for _, p := range paths {
158 ret = append(ret, p.String())
159 }
160 return ret
161}
162
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000163// Provides general test support.
164type TestHelper struct {
165 t *testing.T
166}
167
168func (h *TestHelper) AssertStringEquals(message string, expected string, actual string) {
169 h.t.Helper()
170 if actual != expected {
171 h.t.Errorf("%s: expected %s, actual %s", message, expected, actual)
Paul Duffin82d90432019-11-30 09:24:33 +0000172 }
173}
174
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000175func (h *TestHelper) AssertTrimmedStringEquals(message string, expected string, actual string) {
176 h.t.Helper()
177 h.AssertStringEquals(message, strings.TrimSpace(expected), strings.TrimSpace(actual))
178}
179
Paul Duffinb07fa512020-03-10 22:17:04 +0000180func (h *TestHelper) AssertDeepEquals(message string, expected interface{}, actual interface{}) {
181 h.t.Helper()
182 if !reflect.DeepEqual(actual, expected) {
183 h.t.Errorf("%s: expected %#v, actual %#v", message, expected, actual)
184 }
185}
186
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000187// Encapsulates result of processing an SDK definition. Provides support for
188// checking the state of the build structures.
189type testSdkResult struct {
190 TestHelper
191 ctx *android.TestContext
192 config android.Config
193}
194
195// Analyse the sdk build rules to extract information about what it is doing.
196
197// e.g. find the src/dest pairs from each cp command, the various zip files
198// generated, etc.
199func (r *testSdkResult) getSdkSnapshotBuildInfo(sdk *sdk) *snapshotBuildInfo {
200 androidBpContents := strings.NewReplacer("\\n", "\n").Replace(sdk.GetAndroidBpContentsForTests())
201
202 info := &snapshotBuildInfo{
203 r: r,
204 androidBpContents: androidBpContents,
205 }
206
207 buildParams := sdk.BuildParamsForTests()
208 copyRules := &strings.Builder{}
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +0000209 otherCopyRules := &strings.Builder{}
Paul Duffine1ddcc92020-03-03 16:01:26 +0000210 snapshotDirPrefix := sdk.builderForTests.snapshotDir.String() + "/"
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000211 for _, bp := range buildParams {
212 switch bp.Rule.String() {
213 case android.Cp.String():
Paul Duffine1ddcc92020-03-03 16:01:26 +0000214 output := bp.Output
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +0000215 // Get destination relative to the snapshot root
216 dest := output.Rel()
217 src := android.NormalizePathForTesting(bp.Input)
218 // We differentiate between copy rules for the snapshot, and copy rules for the install file.
Paul Duffine1ddcc92020-03-03 16:01:26 +0000219 if strings.HasPrefix(output.String(), snapshotDirPrefix) {
220 // Get source relative to build directory.
Paul Duffine1ddcc92020-03-03 16:01:26 +0000221 _, _ = fmt.Fprintf(copyRules, "%s -> %s\n", src, dest)
222 info.snapshotContents = append(info.snapshotContents, dest)
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +0000223 } else {
224 _, _ = fmt.Fprintf(otherCopyRules, "%s -> %s\n", src, dest)
Paul Duffine1ddcc92020-03-03 16:01:26 +0000225 }
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000226
227 case repackageZip.String():
228 // Add the destdir to the snapshot contents as that is effectively where
229 // the content of the repackaged zip is copied.
230 dest := bp.Args["destdir"]
231 info.snapshotContents = append(info.snapshotContents, dest)
232
233 case zipFiles.String():
234 // This could be an intermediate zip file and not the actual output zip.
235 // In that case this will be overridden when the rule to merge the zips
236 // is processed.
Paul Duffin9b478b02019-12-10 13:41:51 +0000237 info.outputZip = android.NormalizePathForTesting(bp.Output)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000238
239 case mergeZips.String():
240 // Copy the current outputZip to the intermediateZip.
241 info.intermediateZip = info.outputZip
Paul Duffin9b478b02019-12-10 13:41:51 +0000242 mergeInput := android.NormalizePathForTesting(bp.Input)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000243 if info.intermediateZip != mergeInput {
244 r.t.Errorf("Expected intermediate zip %s to be an input to merge zips but found %s instead",
245 info.intermediateZip, mergeInput)
246 }
247
248 // Override output zip (which was actually the intermediate zip file) with the actual
249 // output zip.
Paul Duffin9b478b02019-12-10 13:41:51 +0000250 info.outputZip = android.NormalizePathForTesting(bp.Output)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000251
252 // Save the zips to be merged into the intermediate zip.
Paul Duffin9b478b02019-12-10 13:41:51 +0000253 info.mergeZips = android.NormalizePathsForTesting(bp.Inputs)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000254 }
255 }
256
257 info.copyRules = copyRules.String()
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +0000258 info.otherCopyRules = otherCopyRules.String()
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000259
260 return info
261}
262
263func (r *testSdkResult) Module(name string, variant string) android.Module {
264 return r.ctx.ModuleForTests(name, variant).Module()
265}
266
267func (r *testSdkResult) ModuleForTests(name string, variant string) android.TestingModule {
268 return r.ctx.ModuleForTests(name, variant)
269}
270
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000271// Check the snapshot build rules.
272//
273// Takes a list of functions which check different facets of the snapshot build rules.
274// Allows each test to customize what is checked without duplicating lots of code
275// or proliferating check methods of different flavors.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000276func (r *testSdkResult) CheckSnapshot(name string, dir string, checkers ...snapshotBuildInfoChecker) {
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000277 r.t.Helper()
278
Paul Duffin1356d8c2020-02-25 19:26:33 +0000279 // The sdk CommonOS variant is always responsible for generating the snapshot.
280 variant := android.CommonOS.Name
281
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000282 sdk := r.Module(name, variant).(*sdk)
283
284 snapshotBuildInfo := r.getSdkSnapshotBuildInfo(sdk)
285
286 // Check state of the snapshot build.
287 for _, checker := range checkers {
288 checker(snapshotBuildInfo)
289 }
290
291 // Make sure that the generated zip file is in the correct place.
292 actual := snapshotBuildInfo.outputZip
Paul Duffin593b3c92019-12-05 14:31:48 +0000293 if dir != "" {
294 dir = filepath.Clean(dir) + "/"
295 }
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000296 r.AssertStringEquals("Snapshot zip file in wrong place",
Paul Duffin593b3c92019-12-05 14:31:48 +0000297 fmt.Sprintf(".intermediates/%s%s/%s/%s-current.zip", dir, name, variant, name), actual)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000298
299 // Populate a mock filesystem with the files that would have been copied by
300 // the rules.
301 fs := make(map[string][]byte)
302 for _, dest := range snapshotBuildInfo.snapshotContents {
303 fs[dest] = nil
304 }
305
306 // Process the generated bp file to make sure it is valid.
307 testSdkWithFs(r.t, snapshotBuildInfo.androidBpContents, fs)
308}
309
310type snapshotBuildInfoChecker func(info *snapshotBuildInfo)
311
312// Check that the snapshot's generated Android.bp is correct.
313//
314// Both the expected and actual string are both trimmed before comparing.
315func checkAndroidBpContents(expected string) snapshotBuildInfoChecker {
316 return func(info *snapshotBuildInfo) {
317 info.r.t.Helper()
318 info.r.AssertTrimmedStringEquals("Android.bp contents do not match", expected, info.androidBpContents)
319 }
320}
321
322// Check that the snapshot's copy rules are correct.
323//
324// The copy rules are formatted as <src> -> <dest>, one per line and then compared
325// to the supplied expected string. Both the expected and actual string are trimmed
326// before comparing.
327func checkAllCopyRules(expected string) snapshotBuildInfoChecker {
328 return func(info *snapshotBuildInfo) {
329 info.r.t.Helper()
330 info.r.AssertTrimmedStringEquals("Incorrect copy rules", expected, info.copyRules)
331 }
332}
333
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +0000334func checkAllOtherCopyRules(expected string) snapshotBuildInfoChecker {
335 return func(info *snapshotBuildInfo) {
336 info.r.t.Helper()
337 info.r.AssertTrimmedStringEquals("Incorrect copy rules", expected, info.otherCopyRules)
338 }
339}
340
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000341// Check that the specified path is in the list of zips to merge with the intermediate zip.
342func checkMergeZip(expected string) snapshotBuildInfoChecker {
343 return func(info *snapshotBuildInfo) {
344 info.r.t.Helper()
345 if info.intermediateZip == "" {
346 info.r.t.Errorf("No intermediate zip file was created")
347 }
348 ensureListContains(info.r.t, info.mergeZips, expected)
349 }
350}
351
352// Encapsulates information about the snapshot build structure in order to insulate tests from
353// knowing too much about internal structures.
354//
355// All source/input paths are relative either the build directory. All dest/output paths are
356// relative to the snapshot root directory.
357type snapshotBuildInfo struct {
358 r *testSdkResult
359
360 // The contents of the generated Android.bp file
361 androidBpContents string
362
363 // The paths, relative to the snapshot root, of all files and directories copied into the
364 // snapshot.
365 snapshotContents []string
366
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +0000367 // A formatted representation of the src/dest pairs for a snapshot, one pair per line,
368 // of the format src -> dest
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000369 copyRules string
370
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +0000371 // A formatted representation of the src/dest pairs for files not in a snapshot, one pair
372 // per line, of the format src -> dest
373 otherCopyRules string
374
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000375 // The path to the intermediate zip, which is a zip created from the source files copied
376 // into the snapshot directory and which will be merged with other zips to form the final output.
377 // Is am empty string if there is no intermediate zip because there are no zips to merge in.
378 intermediateZip string
379
380 // The paths to the zips to merge into the output zip, does not include the intermediate
381 // zip.
382 mergeZips []string
383
384 // The final output zip.
385 outputZip string
386}
387
Paul Duffin82d90432019-11-30 09:24:33 +0000388var buildDir string
389
390func setUp() {
391 var err error
392 buildDir, err = ioutil.TempDir("", "soong_sdk_test")
393 if err != nil {
394 panic(err)
395 }
396}
397
398func tearDown() {
399 _ = os.RemoveAll(buildDir)
400}
401
402func runTestWithBuildDir(m *testing.M) {
403 run := func() int {
404 setUp()
405 defer tearDown()
406
407 return m.Run()
408 }
409
410 os.Exit(run())
411}
412
413func SkipIfNotLinux(t *testing.T) {
414 t.Helper()
415 if android.BuildOs != android.Linux {
416 t.Skipf("Skipping as sdk snapshot generation is only supported on %s not %s", android.Linux, android.BuildOs)
417 }
418}