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