blob: 625b4608fe6f94c92da0f135d50271ad2b83cba4 [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 }
43 ` + cc.GatherRequiredDepsForTest(android.Android)
44
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
72 // from android package
Paul Duffinc1327422020-01-14 12:15:29 +000073 android.RegisterPackageBuildComponents(ctx)
Paul Duffin593b3c92019-12-05 14:31:48 +000074 ctx.PreArchMutators(android.RegisterVisibilityRuleChecker)
Paul Duffin82d90432019-11-30 09:24:33 +000075 ctx.PreArchMutators(android.RegisterDefaultsPreArchMutators)
Paul Duffin593b3c92019-12-05 14:31:48 +000076 ctx.PreArchMutators(android.RegisterVisibilityRuleGatherer)
77 ctx.PostDepsMutators(android.RegisterVisibilityRuleEnforcer)
78
Paul Duffin82d90432019-11-30 09:24:33 +000079 // from java package
Paul Duffinf9b1da02019-12-18 19:51:55 +000080 java.RegisterJavaBuildComponents(ctx)
81 java.RegisterAppBuildComponents(ctx)
Paul Duffin884363e2019-12-19 10:21:09 +000082 java.RegisterStubsBuildComponents(ctx)
Paul Duffin7b81f5e2020-01-13 21:03:22 +000083 java.RegisterSystemModulesBuildComponents(ctx)
Paul Duffin82d90432019-11-30 09:24:33 +000084
85 // from cc package
Paul Duffin77980a82019-12-19 16:01:36 +000086 cc.RegisterRequiredBuildComponentsForTest(ctx)
Paul Duffin82d90432019-11-30 09:24:33 +000087
88 // from apex package
89 ctx.RegisterModuleType("apex", apex.BundleFactory)
90 ctx.RegisterModuleType("apex_key", apex.ApexKeyFactory)
91 ctx.PostDepsMutators(apex.RegisterPostDepsMutators)
92
93 // from this package
Paul Duffin8150da62019-12-16 17:21:27 +000094 ctx.RegisterModuleType("sdk", SdkModuleFactory)
Paul Duffin82d90432019-11-30 09:24:33 +000095 ctx.RegisterModuleType("sdk_snapshot", SnapshotModuleFactory)
Paul Duffin8150da62019-12-16 17:21:27 +000096 ctx.RegisterModuleType("module_exports", ModuleExportsFactory)
97 ctx.RegisterModuleType("module_exports_snapshot", ModuleExportsSnapshotsFactory)
Paul Duffin82d90432019-11-30 09:24:33 +000098 ctx.PreDepsMutators(RegisterPreDepsMutators)
99 ctx.PostDepsMutators(RegisterPostDepsMutators)
100
Colin Cross98be1bb2019-12-13 20:41:13 -0800101 ctx.Register(config)
Paul Duffin82d90432019-11-30 09:24:33 +0000102
103 return ctx, config
104}
105
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000106func testSdkWithFs(t *testing.T, bp string, fs map[string][]byte) *testSdkResult {
107 t.Helper()
108 ctx, config := testSdkContext(bp, fs)
Paul Duffin593b3c92019-12-05 14:31:48 +0000109 _, errs := ctx.ParseBlueprintsFiles(".")
Paul Duffin82d90432019-11-30 09:24:33 +0000110 android.FailIfErrored(t, errs)
111 _, errs = ctx.PrepareBuildActions(config)
112 android.FailIfErrored(t, errs)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000113 return &testSdkResult{
114 TestHelper: TestHelper{t: t},
115 ctx: ctx,
116 config: config,
117 }
Paul Duffin82d90432019-11-30 09:24:33 +0000118}
119
120func testSdkError(t *testing.T, pattern, bp string) {
121 t.Helper()
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000122 ctx, config := testSdkContext(bp, nil)
Paul Duffin82d90432019-11-30 09:24:33 +0000123 _, errs := ctx.ParseFileList(".", []string{"Android.bp"})
124 if len(errs) > 0 {
125 android.FailIfNoMatchingErrors(t, pattern, errs)
126 return
127 }
128 _, errs = ctx.PrepareBuildActions(config)
129 if len(errs) > 0 {
130 android.FailIfNoMatchingErrors(t, pattern, errs)
131 return
132 }
133
134 t.Fatalf("missing expected error %q (0 errors are returned)", pattern)
135}
136
137func ensureListContains(t *testing.T, result []string, expected string) {
138 t.Helper()
139 if !android.InList(expected, result) {
140 t.Errorf("%q is not found in %v", expected, result)
141 }
142}
143
144func pathsToStrings(paths android.Paths) []string {
145 var ret []string
146 for _, p := range paths {
147 ret = append(ret, p.String())
148 }
149 return ret
150}
151
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000152// Provides general test support.
153type TestHelper struct {
154 t *testing.T
155}
156
157func (h *TestHelper) AssertStringEquals(message string, expected string, actual string) {
158 h.t.Helper()
159 if actual != expected {
160 h.t.Errorf("%s: expected %s, actual %s", message, expected, actual)
Paul Duffin82d90432019-11-30 09:24:33 +0000161 }
162}
163
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000164func (h *TestHelper) AssertTrimmedStringEquals(message string, expected string, actual string) {
165 h.t.Helper()
166 h.AssertStringEquals(message, strings.TrimSpace(expected), strings.TrimSpace(actual))
167}
168
169// Encapsulates result of processing an SDK definition. Provides support for
170// checking the state of the build structures.
171type testSdkResult struct {
172 TestHelper
173 ctx *android.TestContext
174 config android.Config
175}
176
177// Analyse the sdk build rules to extract information about what it is doing.
178
179// e.g. find the src/dest pairs from each cp command, the various zip files
180// generated, etc.
181func (r *testSdkResult) getSdkSnapshotBuildInfo(sdk *sdk) *snapshotBuildInfo {
182 androidBpContents := strings.NewReplacer("\\n", "\n").Replace(sdk.GetAndroidBpContentsForTests())
183
184 info := &snapshotBuildInfo{
185 r: r,
186 androidBpContents: androidBpContents,
187 }
188
189 buildParams := sdk.BuildParamsForTests()
190 copyRules := &strings.Builder{}
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +0000191 otherCopyRules := &strings.Builder{}
Paul Duffine1ddcc92020-03-03 16:01:26 +0000192 snapshotDirPrefix := sdk.builderForTests.snapshotDir.String() + "/"
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000193 for _, bp := range buildParams {
194 switch bp.Rule.String() {
195 case android.Cp.String():
Paul Duffine1ddcc92020-03-03 16:01:26 +0000196 output := bp.Output
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +0000197 // Get destination relative to the snapshot root
198 dest := output.Rel()
199 src := android.NormalizePathForTesting(bp.Input)
200 // We differentiate between copy rules for the snapshot, and copy rules for the install file.
Paul Duffine1ddcc92020-03-03 16:01:26 +0000201 if strings.HasPrefix(output.String(), snapshotDirPrefix) {
202 // Get source relative to build directory.
Paul Duffine1ddcc92020-03-03 16:01:26 +0000203 _, _ = fmt.Fprintf(copyRules, "%s -> %s\n", src, dest)
204 info.snapshotContents = append(info.snapshotContents, dest)
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +0000205 } else {
206 _, _ = fmt.Fprintf(otherCopyRules, "%s -> %s\n", src, dest)
Paul Duffine1ddcc92020-03-03 16:01:26 +0000207 }
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000208
209 case repackageZip.String():
210 // Add the destdir to the snapshot contents as that is effectively where
211 // the content of the repackaged zip is copied.
212 dest := bp.Args["destdir"]
213 info.snapshotContents = append(info.snapshotContents, dest)
214
215 case zipFiles.String():
216 // This could be an intermediate zip file and not the actual output zip.
217 // In that case this will be overridden when the rule to merge the zips
218 // is processed.
Paul Duffin9b478b02019-12-10 13:41:51 +0000219 info.outputZip = android.NormalizePathForTesting(bp.Output)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000220
221 case mergeZips.String():
222 // Copy the current outputZip to the intermediateZip.
223 info.intermediateZip = info.outputZip
Paul Duffin9b478b02019-12-10 13:41:51 +0000224 mergeInput := android.NormalizePathForTesting(bp.Input)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000225 if info.intermediateZip != mergeInput {
226 r.t.Errorf("Expected intermediate zip %s to be an input to merge zips but found %s instead",
227 info.intermediateZip, mergeInput)
228 }
229
230 // Override output zip (which was actually the intermediate zip file) with the actual
231 // output zip.
Paul Duffin9b478b02019-12-10 13:41:51 +0000232 info.outputZip = android.NormalizePathForTesting(bp.Output)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000233
234 // Save the zips to be merged into the intermediate zip.
Paul Duffin9b478b02019-12-10 13:41:51 +0000235 info.mergeZips = android.NormalizePathsForTesting(bp.Inputs)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000236 }
237 }
238
239 info.copyRules = copyRules.String()
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +0000240 info.otherCopyRules = otherCopyRules.String()
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000241
242 return info
243}
244
245func (r *testSdkResult) Module(name string, variant string) android.Module {
246 return r.ctx.ModuleForTests(name, variant).Module()
247}
248
249func (r *testSdkResult) ModuleForTests(name string, variant string) android.TestingModule {
250 return r.ctx.ModuleForTests(name, variant)
251}
252
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000253// Check the snapshot build rules.
254//
255// Takes a list of functions which check different facets of the snapshot build rules.
256// Allows each test to customize what is checked without duplicating lots of code
257// or proliferating check methods of different flavors.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000258func (r *testSdkResult) CheckSnapshot(name string, dir string, checkers ...snapshotBuildInfoChecker) {
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000259 r.t.Helper()
260
Paul Duffin1356d8c2020-02-25 19:26:33 +0000261 // The sdk CommonOS variant is always responsible for generating the snapshot.
262 variant := android.CommonOS.Name
263
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000264 sdk := r.Module(name, variant).(*sdk)
265
266 snapshotBuildInfo := r.getSdkSnapshotBuildInfo(sdk)
267
268 // Check state of the snapshot build.
269 for _, checker := range checkers {
270 checker(snapshotBuildInfo)
271 }
272
273 // Make sure that the generated zip file is in the correct place.
274 actual := snapshotBuildInfo.outputZip
Paul Duffin593b3c92019-12-05 14:31:48 +0000275 if dir != "" {
276 dir = filepath.Clean(dir) + "/"
277 }
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000278 r.AssertStringEquals("Snapshot zip file in wrong place",
Paul Duffin593b3c92019-12-05 14:31:48 +0000279 fmt.Sprintf(".intermediates/%s%s/%s/%s-current.zip", dir, name, variant, name), actual)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000280
281 // Populate a mock filesystem with the files that would have been copied by
282 // the rules.
283 fs := make(map[string][]byte)
284 for _, dest := range snapshotBuildInfo.snapshotContents {
285 fs[dest] = nil
286 }
287
288 // Process the generated bp file to make sure it is valid.
289 testSdkWithFs(r.t, snapshotBuildInfo.androidBpContents, fs)
290}
291
292type snapshotBuildInfoChecker func(info *snapshotBuildInfo)
293
294// Check that the snapshot's generated Android.bp is correct.
295//
296// Both the expected and actual string are both trimmed before comparing.
297func checkAndroidBpContents(expected string) snapshotBuildInfoChecker {
298 return func(info *snapshotBuildInfo) {
299 info.r.t.Helper()
300 info.r.AssertTrimmedStringEquals("Android.bp contents do not match", expected, info.androidBpContents)
301 }
302}
303
304// Check that the snapshot's copy rules are correct.
305//
306// The copy rules are formatted as <src> -> <dest>, one per line and then compared
307// to the supplied expected string. Both the expected and actual string are trimmed
308// before comparing.
309func checkAllCopyRules(expected string) snapshotBuildInfoChecker {
310 return func(info *snapshotBuildInfo) {
311 info.r.t.Helper()
312 info.r.AssertTrimmedStringEquals("Incorrect copy rules", expected, info.copyRules)
313 }
314}
315
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +0000316func checkAllOtherCopyRules(expected string) snapshotBuildInfoChecker {
317 return func(info *snapshotBuildInfo) {
318 info.r.t.Helper()
319 info.r.AssertTrimmedStringEquals("Incorrect copy rules", expected, info.otherCopyRules)
320 }
321}
322
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000323// Check that the specified path is in the list of zips to merge with the intermediate zip.
324func checkMergeZip(expected string) snapshotBuildInfoChecker {
325 return func(info *snapshotBuildInfo) {
326 info.r.t.Helper()
327 if info.intermediateZip == "" {
328 info.r.t.Errorf("No intermediate zip file was created")
329 }
330 ensureListContains(info.r.t, info.mergeZips, expected)
331 }
332}
333
334// Encapsulates information about the snapshot build structure in order to insulate tests from
335// knowing too much about internal structures.
336//
337// All source/input paths are relative either the build directory. All dest/output paths are
338// relative to the snapshot root directory.
339type snapshotBuildInfo struct {
340 r *testSdkResult
341
342 // The contents of the generated Android.bp file
343 androidBpContents string
344
345 // The paths, relative to the snapshot root, of all files and directories copied into the
346 // snapshot.
347 snapshotContents []string
348
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +0000349 // A formatted representation of the src/dest pairs for a snapshot, one pair per line,
350 // of the format src -> dest
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000351 copyRules string
352
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +0000353 // A formatted representation of the src/dest pairs for files not in a snapshot, one pair
354 // per line, of the format src -> dest
355 otherCopyRules string
356
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000357 // The path to the intermediate zip, which is a zip created from the source files copied
358 // into the snapshot directory and which will be merged with other zips to form the final output.
359 // Is am empty string if there is no intermediate zip because there are no zips to merge in.
360 intermediateZip string
361
362 // The paths to the zips to merge into the output zip, does not include the intermediate
363 // zip.
364 mergeZips []string
365
366 // The final output zip.
367 outputZip string
368}
369
Paul Duffin82d90432019-11-30 09:24:33 +0000370var buildDir string
371
372func setUp() {
373 var err error
374 buildDir, err = ioutil.TempDir("", "soong_sdk_test")
375 if err != nil {
376 panic(err)
377 }
378}
379
380func tearDown() {
381 _ = os.RemoveAll(buildDir)
382}
383
384func runTestWithBuildDir(m *testing.M) {
385 run := func() int {
386 setUp()
387 defer tearDown()
388
389 return m.Run()
390 }
391
392 os.Exit(run())
393}
394
395func SkipIfNotLinux(t *testing.T) {
396 t.Helper()
397 if android.BuildOs != android.Linux {
398 t.Skipf("Skipping as sdk snapshot generation is only supported on %s not %s", android.Linux, android.BuildOs)
399 }
400}