blob: ae0620d83712a967e22e977797cdf42e8b8147f5 [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 Duffin82d90432019-11-30 09:24:33 +000064 ctx := android.NewTestArchContext()
65
66 // from android package
Paul Duffinc1327422020-01-14 12:15:29 +000067 android.RegisterPackageBuildComponents(ctx)
Paul Duffin593b3c92019-12-05 14:31:48 +000068 ctx.PreArchMutators(android.RegisterVisibilityRuleChecker)
Paul Duffin82d90432019-11-30 09:24:33 +000069 ctx.PreArchMutators(android.RegisterDefaultsPreArchMutators)
Paul Duffin593b3c92019-12-05 14:31:48 +000070 ctx.PreArchMutators(android.RegisterVisibilityRuleGatherer)
71 ctx.PostDepsMutators(android.RegisterVisibilityRuleEnforcer)
72
Paul Duffin82d90432019-11-30 09:24:33 +000073 // from java package
Paul Duffinf9b1da02019-12-18 19:51:55 +000074 java.RegisterJavaBuildComponents(ctx)
75 java.RegisterAppBuildComponents(ctx)
Paul Duffin884363e2019-12-19 10:21:09 +000076 java.RegisterStubsBuildComponents(ctx)
Paul Duffin7b81f5e2020-01-13 21:03:22 +000077 java.RegisterSystemModulesBuildComponents(ctx)
Paul Duffin82d90432019-11-30 09:24:33 +000078
79 // from cc package
Paul Duffin77980a82019-12-19 16:01:36 +000080 cc.RegisterRequiredBuildComponentsForTest(ctx)
Paul Duffin82d90432019-11-30 09:24:33 +000081
82 // from apex package
83 ctx.RegisterModuleType("apex", apex.BundleFactory)
84 ctx.RegisterModuleType("apex_key", apex.ApexKeyFactory)
85 ctx.PostDepsMutators(apex.RegisterPostDepsMutators)
86
87 // from this package
Paul Duffin8150da62019-12-16 17:21:27 +000088 ctx.RegisterModuleType("sdk", SdkModuleFactory)
Paul Duffin82d90432019-11-30 09:24:33 +000089 ctx.RegisterModuleType("sdk_snapshot", SnapshotModuleFactory)
Paul Duffin8150da62019-12-16 17:21:27 +000090 ctx.RegisterModuleType("module_exports", ModuleExportsFactory)
91 ctx.RegisterModuleType("module_exports_snapshot", ModuleExportsSnapshotsFactory)
Paul Duffin82d90432019-11-30 09:24:33 +000092 ctx.PreDepsMutators(RegisterPreDepsMutators)
93 ctx.PostDepsMutators(RegisterPostDepsMutators)
94
Colin Cross98be1bb2019-12-13 20:41:13 -080095 ctx.Register(config)
Paul Duffin82d90432019-11-30 09:24:33 +000096
97 return ctx, config
98}
99
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000100func testSdkWithFs(t *testing.T, bp string, fs map[string][]byte) *testSdkResult {
101 t.Helper()
102 ctx, config := testSdkContext(bp, fs)
Paul Duffin593b3c92019-12-05 14:31:48 +0000103 _, errs := ctx.ParseBlueprintsFiles(".")
Paul Duffin82d90432019-11-30 09:24:33 +0000104 android.FailIfErrored(t, errs)
105 _, errs = ctx.PrepareBuildActions(config)
106 android.FailIfErrored(t, errs)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000107 return &testSdkResult{
108 TestHelper: TestHelper{t: t},
109 ctx: ctx,
110 config: config,
111 }
Paul Duffin82d90432019-11-30 09:24:33 +0000112}
113
114func testSdkError(t *testing.T, pattern, bp string) {
115 t.Helper()
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000116 ctx, config := testSdkContext(bp, nil)
Paul Duffin82d90432019-11-30 09:24:33 +0000117 _, errs := ctx.ParseFileList(".", []string{"Android.bp"})
118 if len(errs) > 0 {
119 android.FailIfNoMatchingErrors(t, pattern, errs)
120 return
121 }
122 _, errs = ctx.PrepareBuildActions(config)
123 if len(errs) > 0 {
124 android.FailIfNoMatchingErrors(t, pattern, errs)
125 return
126 }
127
128 t.Fatalf("missing expected error %q (0 errors are returned)", pattern)
129}
130
131func ensureListContains(t *testing.T, result []string, expected string) {
132 t.Helper()
133 if !android.InList(expected, result) {
134 t.Errorf("%q is not found in %v", expected, result)
135 }
136}
137
138func pathsToStrings(paths android.Paths) []string {
139 var ret []string
140 for _, p := range paths {
141 ret = append(ret, p.String())
142 }
143 return ret
144}
145
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000146// Provides general test support.
147type TestHelper struct {
148 t *testing.T
149}
150
151func (h *TestHelper) AssertStringEquals(message string, expected string, actual string) {
152 h.t.Helper()
153 if actual != expected {
154 h.t.Errorf("%s: expected %s, actual %s", message, expected, actual)
Paul Duffin82d90432019-11-30 09:24:33 +0000155 }
156}
157
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000158func (h *TestHelper) AssertTrimmedStringEquals(message string, expected string, actual string) {
159 h.t.Helper()
160 h.AssertStringEquals(message, strings.TrimSpace(expected), strings.TrimSpace(actual))
161}
162
163// Encapsulates result of processing an SDK definition. Provides support for
164// checking the state of the build structures.
165type testSdkResult struct {
166 TestHelper
167 ctx *android.TestContext
168 config android.Config
169}
170
171// Analyse the sdk build rules to extract information about what it is doing.
172
173// e.g. find the src/dest pairs from each cp command, the various zip files
174// generated, etc.
175func (r *testSdkResult) getSdkSnapshotBuildInfo(sdk *sdk) *snapshotBuildInfo {
176 androidBpContents := strings.NewReplacer("\\n", "\n").Replace(sdk.GetAndroidBpContentsForTests())
177
178 info := &snapshotBuildInfo{
179 r: r,
180 androidBpContents: androidBpContents,
181 }
182
183 buildParams := sdk.BuildParamsForTests()
184 copyRules := &strings.Builder{}
185 for _, bp := range buildParams {
186 switch bp.Rule.String() {
187 case android.Cp.String():
188 // Get source relative to build directory.
Paul Duffin9b478b02019-12-10 13:41:51 +0000189 src := android.NormalizePathForTesting(bp.Input)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000190 // Get destination relative to the snapshot root
191 dest := bp.Output.Rel()
192 _, _ = fmt.Fprintf(copyRules, "%s -> %s\n", src, dest)
193 info.snapshotContents = append(info.snapshotContents, dest)
194
195 case repackageZip.String():
196 // Add the destdir to the snapshot contents as that is effectively where
197 // the content of the repackaged zip is copied.
198 dest := bp.Args["destdir"]
199 info.snapshotContents = append(info.snapshotContents, dest)
200
201 case zipFiles.String():
202 // This could be an intermediate zip file and not the actual output zip.
203 // In that case this will be overridden when the rule to merge the zips
204 // is processed.
Paul Duffin9b478b02019-12-10 13:41:51 +0000205 info.outputZip = android.NormalizePathForTesting(bp.Output)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000206
207 case mergeZips.String():
208 // Copy the current outputZip to the intermediateZip.
209 info.intermediateZip = info.outputZip
Paul Duffin9b478b02019-12-10 13:41:51 +0000210 mergeInput := android.NormalizePathForTesting(bp.Input)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000211 if info.intermediateZip != mergeInput {
212 r.t.Errorf("Expected intermediate zip %s to be an input to merge zips but found %s instead",
213 info.intermediateZip, mergeInput)
214 }
215
216 // Override output zip (which was actually the intermediate zip file) with the actual
217 // output zip.
Paul Duffin9b478b02019-12-10 13:41:51 +0000218 info.outputZip = android.NormalizePathForTesting(bp.Output)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000219
220 // Save the zips to be merged into the intermediate zip.
Paul Duffin9b478b02019-12-10 13:41:51 +0000221 info.mergeZips = android.NormalizePathsForTesting(bp.Inputs)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000222 }
223 }
224
225 info.copyRules = copyRules.String()
226
227 return info
228}
229
230func (r *testSdkResult) Module(name string, variant string) android.Module {
231 return r.ctx.ModuleForTests(name, variant).Module()
232}
233
234func (r *testSdkResult) ModuleForTests(name string, variant string) android.TestingModule {
235 return r.ctx.ModuleForTests(name, variant)
236}
237
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000238// Check the snapshot build rules.
239//
240// Takes a list of functions which check different facets of the snapshot build rules.
241// Allows each test to customize what is checked without duplicating lots of code
242// or proliferating check methods of different flavors.
Paul Duffin593b3c92019-12-05 14:31:48 +0000243func (r *testSdkResult) CheckSnapshot(name string, variant string, dir string, checkers ...snapshotBuildInfoChecker) {
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000244 r.t.Helper()
245
246 sdk := r.Module(name, variant).(*sdk)
247
248 snapshotBuildInfo := r.getSdkSnapshotBuildInfo(sdk)
249
250 // Check state of the snapshot build.
251 for _, checker := range checkers {
252 checker(snapshotBuildInfo)
253 }
254
255 // Make sure that the generated zip file is in the correct place.
256 actual := snapshotBuildInfo.outputZip
Paul Duffin593b3c92019-12-05 14:31:48 +0000257 if dir != "" {
258 dir = filepath.Clean(dir) + "/"
259 }
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000260 r.AssertStringEquals("Snapshot zip file in wrong place",
Paul Duffin593b3c92019-12-05 14:31:48 +0000261 fmt.Sprintf(".intermediates/%s%s/%s/%s-current.zip", dir, name, variant, name), actual)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000262
263 // Populate a mock filesystem with the files that would have been copied by
264 // the rules.
265 fs := make(map[string][]byte)
266 for _, dest := range snapshotBuildInfo.snapshotContents {
267 fs[dest] = nil
268 }
269
270 // Process the generated bp file to make sure it is valid.
271 testSdkWithFs(r.t, snapshotBuildInfo.androidBpContents, fs)
272}
273
274type snapshotBuildInfoChecker func(info *snapshotBuildInfo)
275
276// Check that the snapshot's generated Android.bp is correct.
277//
278// Both the expected and actual string are both trimmed before comparing.
279func checkAndroidBpContents(expected string) snapshotBuildInfoChecker {
280 return func(info *snapshotBuildInfo) {
281 info.r.t.Helper()
282 info.r.AssertTrimmedStringEquals("Android.bp contents do not match", expected, info.androidBpContents)
283 }
284}
285
286// Check that the snapshot's copy rules are correct.
287//
288// The copy rules are formatted as <src> -> <dest>, one per line and then compared
289// to the supplied expected string. Both the expected and actual string are trimmed
290// before comparing.
291func checkAllCopyRules(expected string) snapshotBuildInfoChecker {
292 return func(info *snapshotBuildInfo) {
293 info.r.t.Helper()
294 info.r.AssertTrimmedStringEquals("Incorrect copy rules", expected, info.copyRules)
295 }
296}
297
298// Check that the specified path is in the list of zips to merge with the intermediate zip.
299func checkMergeZip(expected string) snapshotBuildInfoChecker {
300 return func(info *snapshotBuildInfo) {
301 info.r.t.Helper()
302 if info.intermediateZip == "" {
303 info.r.t.Errorf("No intermediate zip file was created")
304 }
305 ensureListContains(info.r.t, info.mergeZips, expected)
306 }
307}
308
309// Encapsulates information about the snapshot build structure in order to insulate tests from
310// knowing too much about internal structures.
311//
312// All source/input paths are relative either the build directory. All dest/output paths are
313// relative to the snapshot root directory.
314type snapshotBuildInfo struct {
315 r *testSdkResult
316
317 // The contents of the generated Android.bp file
318 androidBpContents string
319
320 // The paths, relative to the snapshot root, of all files and directories copied into the
321 // snapshot.
322 snapshotContents []string
323
324 // A formatted representation of the src/dest pairs, one pair per line, of the format
325 // src -> dest
326 copyRules string
327
328 // The path to the intermediate zip, which is a zip created from the source files copied
329 // into the snapshot directory and which will be merged with other zips to form the final output.
330 // Is am empty string if there is no intermediate zip because there are no zips to merge in.
331 intermediateZip string
332
333 // The paths to the zips to merge into the output zip, does not include the intermediate
334 // zip.
335 mergeZips []string
336
337 // The final output zip.
338 outputZip string
339}
340
Paul Duffin82d90432019-11-30 09:24:33 +0000341var buildDir string
342
343func setUp() {
344 var err error
345 buildDir, err = ioutil.TempDir("", "soong_sdk_test")
346 if err != nil {
347 panic(err)
348 }
349}
350
351func tearDown() {
352 _ = os.RemoveAll(buildDir)
353}
354
355func runTestWithBuildDir(m *testing.M) {
356 run := func() int {
357 setUp()
358 defer tearDown()
359
360 return m.Run()
361 }
362
363 os.Exit(run())
364}
365
366func SkipIfNotLinux(t *testing.T) {
367 t.Helper()
368 if android.BuildOs != android.Linux {
369 t.Skipf("Skipping as sdk snapshot generation is only supported on %s not %s", android.Linux, android.BuildOs)
370 }
371}