blob: 464c3ca9af4005c4f124b336b4842e5f70f4285e [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 Duffin82d90432019-11-30 09:24:33 +000022 "strings"
23 "testing"
24
25 "android/soong/android"
26 "android/soong/apex"
27 "android/soong/cc"
28 "android/soong/java"
29)
30
Paul Duffinc3c5d5e2019-11-29 20:45:22 +000031func testSdkContext(bp string, fs map[string][]byte) (*android.TestContext, android.Config) {
Colin Cross98be1bb2019-12-13 20:41:13 -080032 bp = bp + `
33 apex_key {
34 name: "myapex.key",
35 public_key: "myapex.avbpubkey",
36 private_key: "myapex.pem",
37 }
38
39 android_app_certificate {
40 name: "myapex.cert",
41 certificate: "myapex",
42 }
Paul Duffina04c1072020-03-02 10:16:35 +000043 ` + cc.GatherRequiredDepsForTest(android.Android, android.Windows)
Colin Cross98be1bb2019-12-13 20:41:13 -080044
45 mockFS := map[string][]byte{
46 "build/make/target/product/security": nil,
47 "apex_manifest.json": nil,
48 "system/sepolicy/apex/myapex-file_contexts": nil,
49 "system/sepolicy/apex/myapex2-file_contexts": nil,
50 "myapex.avbpubkey": nil,
51 "myapex.pem": nil,
52 "myapex.x509.pem": nil,
53 "myapex.pk8": nil,
54 }
55
Colin Crossf28329d2020-02-15 11:00:10 -080056 cc.GatherRequiredFilesForTest(mockFS)
57
Colin Cross98be1bb2019-12-13 20:41:13 -080058 for k, v := range fs {
59 mockFS[k] = v
60 }
61
62 config := android.TestArchConfig(buildDir, nil, bp, mockFS)
63
Paul Duffin08798aa2020-02-27 13:12:46 +000064 // Add windows as a default disable OS to test behavior when some OS variants
65 // are disabled.
66 config.Targets[android.Windows] = []android.Target{
67 {android.Windows, android.Arch{ArchType: android.X86_64}, android.NativeBridgeDisabled, "", ""},
68 }
69
Paul Duffin82d90432019-11-30 09:24:33 +000070 ctx := android.NewTestArchContext()
71
Paul Duffin8c3fec42020-03-04 20:15:08 +000072 // Enable androidmk support.
73 // * Register the singleton
74 // * Configure that we are inside make
75 // * Add CommonOS to ensure that androidmk processing works.
76 android.RegisterAndroidMkBuildComponents(ctx)
77 android.SetInMakeForTests(config)
78 config.Targets[android.CommonOS] = []android.Target{
79 {android.CommonOS, android.Arch{ArchType: android.Common}, android.NativeBridgeDisabled, "", ""},
80 }
81
Paul Duffin82d90432019-11-30 09:24:33 +000082 // from android package
Paul Duffinc1327422020-01-14 12:15:29 +000083 android.RegisterPackageBuildComponents(ctx)
Paul Duffin593b3c92019-12-05 14:31:48 +000084 ctx.PreArchMutators(android.RegisterVisibilityRuleChecker)
Paul Duffin82d90432019-11-30 09:24:33 +000085 ctx.PreArchMutators(android.RegisterDefaultsPreArchMutators)
Paul Duffin593b3c92019-12-05 14:31:48 +000086 ctx.PreArchMutators(android.RegisterVisibilityRuleGatherer)
87 ctx.PostDepsMutators(android.RegisterVisibilityRuleEnforcer)
88
Paul Duffin82d90432019-11-30 09:24:33 +000089 // from java package
Paul Duffinf9b1da02019-12-18 19:51:55 +000090 java.RegisterJavaBuildComponents(ctx)
91 java.RegisterAppBuildComponents(ctx)
Paul Duffin884363e2019-12-19 10:21:09 +000092 java.RegisterStubsBuildComponents(ctx)
Paul Duffin7b81f5e2020-01-13 21:03:22 +000093 java.RegisterSystemModulesBuildComponents(ctx)
Paul Duffin82d90432019-11-30 09:24:33 +000094
95 // from cc package
Paul Duffin77980a82019-12-19 16:01:36 +000096 cc.RegisterRequiredBuildComponentsForTest(ctx)
Paul Duffin82d90432019-11-30 09:24:33 +000097
98 // from apex package
99 ctx.RegisterModuleType("apex", apex.BundleFactory)
100 ctx.RegisterModuleType("apex_key", apex.ApexKeyFactory)
101 ctx.PostDepsMutators(apex.RegisterPostDepsMutators)
102
103 // from this package
Paul Duffin8150da62019-12-16 17:21:27 +0000104 ctx.RegisterModuleType("sdk", SdkModuleFactory)
Paul Duffin82d90432019-11-30 09:24:33 +0000105 ctx.RegisterModuleType("sdk_snapshot", SnapshotModuleFactory)
Paul Duffin8150da62019-12-16 17:21:27 +0000106 ctx.RegisterModuleType("module_exports", ModuleExportsFactory)
107 ctx.RegisterModuleType("module_exports_snapshot", ModuleExportsSnapshotsFactory)
Paul Duffin82d90432019-11-30 09:24:33 +0000108 ctx.PreDepsMutators(RegisterPreDepsMutators)
109 ctx.PostDepsMutators(RegisterPostDepsMutators)
110
Colin Cross98be1bb2019-12-13 20:41:13 -0800111 ctx.Register(config)
Paul Duffin82d90432019-11-30 09:24:33 +0000112
113 return ctx, config
114}
115
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000116func testSdkWithFs(t *testing.T, bp string, fs map[string][]byte) *testSdkResult {
117 t.Helper()
118 ctx, config := testSdkContext(bp, fs)
Paul Duffin593b3c92019-12-05 14:31:48 +0000119 _, errs := ctx.ParseBlueprintsFiles(".")
Paul Duffin82d90432019-11-30 09:24:33 +0000120 android.FailIfErrored(t, errs)
121 _, errs = ctx.PrepareBuildActions(config)
122 android.FailIfErrored(t, errs)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000123 return &testSdkResult{
124 TestHelper: TestHelper{t: t},
125 ctx: ctx,
126 config: config,
127 }
Paul Duffin82d90432019-11-30 09:24:33 +0000128}
129
130func testSdkError(t *testing.T, pattern, bp string) {
131 t.Helper()
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000132 ctx, config := testSdkContext(bp, nil)
Paul Duffin82d90432019-11-30 09:24:33 +0000133 _, errs := ctx.ParseFileList(".", []string{"Android.bp"})
134 if len(errs) > 0 {
135 android.FailIfNoMatchingErrors(t, pattern, errs)
136 return
137 }
138 _, errs = ctx.PrepareBuildActions(config)
139 if len(errs) > 0 {
140 android.FailIfNoMatchingErrors(t, pattern, errs)
141 return
142 }
143
144 t.Fatalf("missing expected error %q (0 errors are returned)", pattern)
145}
146
147func ensureListContains(t *testing.T, result []string, expected string) {
148 t.Helper()
149 if !android.InList(expected, result) {
150 t.Errorf("%q is not found in %v", expected, result)
151 }
152}
153
154func pathsToStrings(paths android.Paths) []string {
155 var ret []string
156 for _, p := range paths {
157 ret = append(ret, p.String())
158 }
159 return ret
160}
161
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000162// Provides general test support.
163type TestHelper struct {
164 t *testing.T
165}
166
167func (h *TestHelper) AssertStringEquals(message string, expected string, actual string) {
168 h.t.Helper()
169 if actual != expected {
170 h.t.Errorf("%s: expected %s, actual %s", message, expected, actual)
Paul Duffin82d90432019-11-30 09:24:33 +0000171 }
172}
173
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000174func (h *TestHelper) AssertTrimmedStringEquals(message string, expected string, actual string) {
175 h.t.Helper()
176 h.AssertStringEquals(message, strings.TrimSpace(expected), strings.TrimSpace(actual))
177}
178
179// Encapsulates result of processing an SDK definition. Provides support for
180// checking the state of the build structures.
181type testSdkResult struct {
182 TestHelper
183 ctx *android.TestContext
184 config android.Config
185}
186
187// Analyse the sdk build rules to extract information about what it is doing.
188
189// e.g. find the src/dest pairs from each cp command, the various zip files
190// generated, etc.
191func (r *testSdkResult) getSdkSnapshotBuildInfo(sdk *sdk) *snapshotBuildInfo {
192 androidBpContents := strings.NewReplacer("\\n", "\n").Replace(sdk.GetAndroidBpContentsForTests())
193
194 info := &snapshotBuildInfo{
195 r: r,
196 androidBpContents: androidBpContents,
197 }
198
199 buildParams := sdk.BuildParamsForTests()
200 copyRules := &strings.Builder{}
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +0000201 otherCopyRules := &strings.Builder{}
Paul Duffine1ddcc92020-03-03 16:01:26 +0000202 snapshotDirPrefix := sdk.builderForTests.snapshotDir.String() + "/"
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000203 for _, bp := range buildParams {
204 switch bp.Rule.String() {
205 case android.Cp.String():
Paul Duffine1ddcc92020-03-03 16:01:26 +0000206 output := bp.Output
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +0000207 // Get destination relative to the snapshot root
208 dest := output.Rel()
209 src := android.NormalizePathForTesting(bp.Input)
210 // We differentiate between copy rules for the snapshot, and copy rules for the install file.
Paul Duffine1ddcc92020-03-03 16:01:26 +0000211 if strings.HasPrefix(output.String(), snapshotDirPrefix) {
212 // Get source relative to build directory.
Paul Duffine1ddcc92020-03-03 16:01:26 +0000213 _, _ = fmt.Fprintf(copyRules, "%s -> %s\n", src, dest)
214 info.snapshotContents = append(info.snapshotContents, dest)
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +0000215 } else {
216 _, _ = fmt.Fprintf(otherCopyRules, "%s -> %s\n", src, dest)
Paul Duffine1ddcc92020-03-03 16:01:26 +0000217 }
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000218
219 case repackageZip.String():
220 // Add the destdir to the snapshot contents as that is effectively where
221 // the content of the repackaged zip is copied.
222 dest := bp.Args["destdir"]
223 info.snapshotContents = append(info.snapshotContents, dest)
224
225 case zipFiles.String():
226 // This could be an intermediate zip file and not the actual output zip.
227 // In that case this will be overridden when the rule to merge the zips
228 // is processed.
Paul Duffin9b478b02019-12-10 13:41:51 +0000229 info.outputZip = android.NormalizePathForTesting(bp.Output)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000230
231 case mergeZips.String():
232 // Copy the current outputZip to the intermediateZip.
233 info.intermediateZip = info.outputZip
Paul Duffin9b478b02019-12-10 13:41:51 +0000234 mergeInput := android.NormalizePathForTesting(bp.Input)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000235 if info.intermediateZip != mergeInput {
236 r.t.Errorf("Expected intermediate zip %s to be an input to merge zips but found %s instead",
237 info.intermediateZip, mergeInput)
238 }
239
240 // Override output zip (which was actually the intermediate zip file) with the actual
241 // output zip.
Paul Duffin9b478b02019-12-10 13:41:51 +0000242 info.outputZip = android.NormalizePathForTesting(bp.Output)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000243
244 // Save the zips to be merged into the intermediate zip.
Paul Duffin9b478b02019-12-10 13:41:51 +0000245 info.mergeZips = android.NormalizePathsForTesting(bp.Inputs)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000246 }
247 }
248
249 info.copyRules = copyRules.String()
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +0000250 info.otherCopyRules = otherCopyRules.String()
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000251
252 return info
253}
254
255func (r *testSdkResult) Module(name string, variant string) android.Module {
256 return r.ctx.ModuleForTests(name, variant).Module()
257}
258
259func (r *testSdkResult) ModuleForTests(name string, variant string) android.TestingModule {
260 return r.ctx.ModuleForTests(name, variant)
261}
262
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000263// Check the snapshot build rules.
264//
265// Takes a list of functions which check different facets of the snapshot build rules.
266// Allows each test to customize what is checked without duplicating lots of code
267// or proliferating check methods of different flavors.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000268func (r *testSdkResult) CheckSnapshot(name string, dir string, checkers ...snapshotBuildInfoChecker) {
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000269 r.t.Helper()
270
Paul Duffin1356d8c2020-02-25 19:26:33 +0000271 // The sdk CommonOS variant is always responsible for generating the snapshot.
272 variant := android.CommonOS.Name
273
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000274 sdk := r.Module(name, variant).(*sdk)
275
276 snapshotBuildInfo := r.getSdkSnapshotBuildInfo(sdk)
277
278 // Check state of the snapshot build.
279 for _, checker := range checkers {
280 checker(snapshotBuildInfo)
281 }
282
283 // Make sure that the generated zip file is in the correct place.
284 actual := snapshotBuildInfo.outputZip
Paul Duffin593b3c92019-12-05 14:31:48 +0000285 if dir != "" {
286 dir = filepath.Clean(dir) + "/"
287 }
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000288 r.AssertStringEquals("Snapshot zip file in wrong place",
Paul Duffin593b3c92019-12-05 14:31:48 +0000289 fmt.Sprintf(".intermediates/%s%s/%s/%s-current.zip", dir, name, variant, name), actual)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000290
291 // Populate a mock filesystem with the files that would have been copied by
292 // the rules.
293 fs := make(map[string][]byte)
294 for _, dest := range snapshotBuildInfo.snapshotContents {
295 fs[dest] = nil
296 }
297
298 // Process the generated bp file to make sure it is valid.
299 testSdkWithFs(r.t, snapshotBuildInfo.androidBpContents, fs)
300}
301
302type snapshotBuildInfoChecker func(info *snapshotBuildInfo)
303
304// Check that the snapshot's generated Android.bp is correct.
305//
306// Both the expected and actual string are both trimmed before comparing.
307func checkAndroidBpContents(expected string) snapshotBuildInfoChecker {
308 return func(info *snapshotBuildInfo) {
309 info.r.t.Helper()
310 info.r.AssertTrimmedStringEquals("Android.bp contents do not match", expected, info.androidBpContents)
311 }
312}
313
314// Check that the snapshot's copy rules are correct.
315//
316// The copy rules are formatted as <src> -> <dest>, one per line and then compared
317// to the supplied expected string. Both the expected and actual string are trimmed
318// before comparing.
319func checkAllCopyRules(expected string) snapshotBuildInfoChecker {
320 return func(info *snapshotBuildInfo) {
321 info.r.t.Helper()
322 info.r.AssertTrimmedStringEquals("Incorrect copy rules", expected, info.copyRules)
323 }
324}
325
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +0000326func checkAllOtherCopyRules(expected string) snapshotBuildInfoChecker {
327 return func(info *snapshotBuildInfo) {
328 info.r.t.Helper()
329 info.r.AssertTrimmedStringEquals("Incorrect copy rules", expected, info.otherCopyRules)
330 }
331}
332
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000333// Check that the specified path is in the list of zips to merge with the intermediate zip.
334func checkMergeZip(expected string) snapshotBuildInfoChecker {
335 return func(info *snapshotBuildInfo) {
336 info.r.t.Helper()
337 if info.intermediateZip == "" {
338 info.r.t.Errorf("No intermediate zip file was created")
339 }
340 ensureListContains(info.r.t, info.mergeZips, expected)
341 }
342}
343
344// Encapsulates information about the snapshot build structure in order to insulate tests from
345// knowing too much about internal structures.
346//
347// All source/input paths are relative either the build directory. All dest/output paths are
348// relative to the snapshot root directory.
349type snapshotBuildInfo struct {
350 r *testSdkResult
351
352 // The contents of the generated Android.bp file
353 androidBpContents string
354
355 // The paths, relative to the snapshot root, of all files and directories copied into the
356 // snapshot.
357 snapshotContents []string
358
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +0000359 // A formatted representation of the src/dest pairs for a snapshot, one pair per line,
360 // of the format src -> dest
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000361 copyRules string
362
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +0000363 // A formatted representation of the src/dest pairs for files not in a snapshot, one pair
364 // per line, of the format src -> dest
365 otherCopyRules string
366
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000367 // The path to the intermediate zip, which is a zip created from the source files copied
368 // into the snapshot directory and which will be merged with other zips to form the final output.
369 // Is am empty string if there is no intermediate zip because there are no zips to merge in.
370 intermediateZip string
371
372 // The paths to the zips to merge into the output zip, does not include the intermediate
373 // zip.
374 mergeZips []string
375
376 // The final output zip.
377 outputZip string
378}
379
Paul Duffin82d90432019-11-30 09:24:33 +0000380var buildDir string
381
382func setUp() {
383 var err error
384 buildDir, err = ioutil.TempDir("", "soong_sdk_test")
385 if err != nil {
386 panic(err)
387 }
388}
389
390func tearDown() {
391 _ = os.RemoveAll(buildDir)
392}
393
394func runTestWithBuildDir(m *testing.M) {
395 run := func() int {
396 setUp()
397 defer tearDown()
398
399 return m.Run()
400 }
401
402 os.Exit(run())
403}
404
405func SkipIfNotLinux(t *testing.T) {
406 t.Helper()
407 if android.BuildOs != android.Linux {
408 t.Skipf("Skipping as sdk snapshot generation is only supported on %s not %s", android.Linux, android.BuildOs)
409 }
410}