blob: bd929a4f84bde4f8d0770401c94de7cbce0c8527 [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) {
Paul Duffin82d90432019-11-30 09:24:33 +000032 config := android.TestArchConfig(buildDir, nil)
33 ctx := android.NewTestArchContext()
34
35 // from android package
Paul Duffin593b3c92019-12-05 14:31:48 +000036 ctx.PreArchMutators(android.RegisterPackageRenamer)
37 ctx.PreArchMutators(android.RegisterVisibilityRuleChecker)
Paul Duffin82d90432019-11-30 09:24:33 +000038 ctx.PreArchMutators(android.RegisterDefaultsPreArchMutators)
Paul Duffin593b3c92019-12-05 14:31:48 +000039 ctx.PreArchMutators(android.RegisterVisibilityRuleGatherer)
40 ctx.PostDepsMutators(android.RegisterVisibilityRuleEnforcer)
41
Paul Duffin82d90432019-11-30 09:24:33 +000042 ctx.PreArchMutators(func(ctx android.RegisterMutatorsContext) {
43 ctx.BottomUp("prebuilts", android.PrebuiltMutator).Parallel()
44 })
45 ctx.PostDepsMutators(func(ctx android.RegisterMutatorsContext) {
46 ctx.TopDown("prebuilt_select", android.PrebuiltSelectModuleMutator).Parallel()
47 ctx.BottomUp("prebuilt_postdeps", android.PrebuiltPostDepsMutator).Parallel()
48 })
Paul Duffin593b3c92019-12-05 14:31:48 +000049 ctx.RegisterModuleType("package", android.PackageFactory)
Paul Duffin82d90432019-11-30 09:24:33 +000050
51 // from java package
52 ctx.RegisterModuleType("android_app_certificate", java.AndroidAppCertificateFactory)
Paul Duffin593b3c92019-12-05 14:31:48 +000053 ctx.RegisterModuleType("java_defaults", java.DefaultsFactory)
Paul Duffin82d90432019-11-30 09:24:33 +000054 ctx.RegisterModuleType("java_library", java.LibraryFactory)
55 ctx.RegisterModuleType("java_import", java.ImportFactory)
56 ctx.RegisterModuleType("droidstubs", java.DroidstubsFactory)
57 ctx.RegisterModuleType("prebuilt_stubs_sources", java.PrebuiltStubsSourcesFactory)
58
59 // from cc package
60 ctx.RegisterModuleType("cc_library", cc.LibraryFactory)
61 ctx.RegisterModuleType("cc_library_shared", cc.LibrarySharedFactory)
62 ctx.RegisterModuleType("cc_object", cc.ObjectFactory)
63 ctx.RegisterModuleType("cc_prebuilt_library_shared", cc.PrebuiltSharedLibraryFactory)
64 ctx.RegisterModuleType("cc_prebuilt_library_static", cc.PrebuiltStaticLibraryFactory)
65 ctx.RegisterModuleType("llndk_library", cc.LlndkLibraryFactory)
66 ctx.RegisterModuleType("toolchain_library", cc.ToolchainLibraryFactory)
67 ctx.PreDepsMutators(func(ctx android.RegisterMutatorsContext) {
Paul Duffin82d90432019-11-30 09:24:33 +000068 ctx.BottomUp("link", cc.LinkageMutator).Parallel()
69 ctx.BottomUp("vndk", cc.VndkMutator).Parallel()
70 ctx.BottomUp("test_per_src", cc.TestPerSrcMutator).Parallel()
71 ctx.BottomUp("version", cc.VersionMutator).Parallel()
72 ctx.BottomUp("begin", cc.BeginMutator).Parallel()
73 })
74
75 // from apex package
76 ctx.RegisterModuleType("apex", apex.BundleFactory)
77 ctx.RegisterModuleType("apex_key", apex.ApexKeyFactory)
78 ctx.PostDepsMutators(apex.RegisterPostDepsMutators)
79
80 // from this package
81 ctx.RegisterModuleType("sdk", ModuleFactory)
82 ctx.RegisterModuleType("sdk_snapshot", SnapshotModuleFactory)
83 ctx.PreDepsMutators(RegisterPreDepsMutators)
84 ctx.PostDepsMutators(RegisterPostDepsMutators)
85
86 ctx.Register()
87
88 bp = bp + `
89 apex_key {
90 name: "myapex.key",
91 public_key: "myapex.avbpubkey",
92 private_key: "myapex.pem",
93 }
94
95 android_app_certificate {
96 name: "myapex.cert",
97 certificate: "myapex",
98 }
99 ` + cc.GatherRequiredDepsForTest(android.Android)
100
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000101 mockFS := map[string][]byte{
Paul Duffin82d90432019-11-30 09:24:33 +0000102 "Android.bp": []byte(bp),
103 "build/make/target/product/security": nil,
104 "apex_manifest.json": nil,
105 "system/sepolicy/apex/myapex-file_contexts": nil,
106 "system/sepolicy/apex/myapex2-file_contexts": nil,
107 "myapex.avbpubkey": nil,
108 "myapex.pem": nil,
109 "myapex.x509.pem": nil,
110 "myapex.pk8": nil,
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000111 }
112
113 for k, v := range fs {
114 mockFS[k] = v
115 }
116
117 ctx.MockFileSystem(mockFS)
Paul Duffin82d90432019-11-30 09:24:33 +0000118
119 return ctx, config
120}
121
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000122func testSdkWithFs(t *testing.T, bp string, fs map[string][]byte) *testSdkResult {
123 t.Helper()
124 ctx, config := testSdkContext(bp, fs)
Paul Duffin593b3c92019-12-05 14:31:48 +0000125 _, errs := ctx.ParseBlueprintsFiles(".")
Paul Duffin82d90432019-11-30 09:24:33 +0000126 android.FailIfErrored(t, errs)
127 _, errs = ctx.PrepareBuildActions(config)
128 android.FailIfErrored(t, errs)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000129 return &testSdkResult{
130 TestHelper: TestHelper{t: t},
131 ctx: ctx,
132 config: config,
133 }
Paul Duffin82d90432019-11-30 09:24:33 +0000134}
135
136func testSdkError(t *testing.T, pattern, bp string) {
137 t.Helper()
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000138 ctx, config := testSdkContext(bp, nil)
Paul Duffin82d90432019-11-30 09:24:33 +0000139 _, errs := ctx.ParseFileList(".", []string{"Android.bp"})
140 if len(errs) > 0 {
141 android.FailIfNoMatchingErrors(t, pattern, errs)
142 return
143 }
144 _, errs = ctx.PrepareBuildActions(config)
145 if len(errs) > 0 {
146 android.FailIfNoMatchingErrors(t, pattern, errs)
147 return
148 }
149
150 t.Fatalf("missing expected error %q (0 errors are returned)", pattern)
151}
152
153func ensureListContains(t *testing.T, result []string, expected string) {
154 t.Helper()
155 if !android.InList(expected, result) {
156 t.Errorf("%q is not found in %v", expected, result)
157 }
158}
159
160func pathsToStrings(paths android.Paths) []string {
161 var ret []string
162 for _, p := range paths {
163 ret = append(ret, p.String())
164 }
165 return ret
166}
167
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000168// Provides general test support.
169type TestHelper struct {
170 t *testing.T
171}
172
173func (h *TestHelper) AssertStringEquals(message string, expected string, actual string) {
174 h.t.Helper()
175 if actual != expected {
176 h.t.Errorf("%s: expected %s, actual %s", message, expected, actual)
Paul Duffin82d90432019-11-30 09:24:33 +0000177 }
178}
179
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000180func (h *TestHelper) AssertTrimmedStringEquals(message string, expected string, actual string) {
181 h.t.Helper()
182 h.AssertStringEquals(message, strings.TrimSpace(expected), strings.TrimSpace(actual))
183}
184
185// Encapsulates result of processing an SDK definition. Provides support for
186// checking the state of the build structures.
187type testSdkResult struct {
188 TestHelper
189 ctx *android.TestContext
190 config android.Config
191}
192
193// Analyse the sdk build rules to extract information about what it is doing.
194
195// e.g. find the src/dest pairs from each cp command, the various zip files
196// generated, etc.
197func (r *testSdkResult) getSdkSnapshotBuildInfo(sdk *sdk) *snapshotBuildInfo {
198 androidBpContents := strings.NewReplacer("\\n", "\n").Replace(sdk.GetAndroidBpContentsForTests())
199
200 info := &snapshotBuildInfo{
201 r: r,
202 androidBpContents: androidBpContents,
203 }
204
205 buildParams := sdk.BuildParamsForTests()
206 copyRules := &strings.Builder{}
207 for _, bp := range buildParams {
208 switch bp.Rule.String() {
209 case android.Cp.String():
210 // Get source relative to build directory.
211 src := r.pathRelativeToBuildDir(bp.Input)
212 // Get destination relative to the snapshot root
213 dest := bp.Output.Rel()
214 _, _ = fmt.Fprintf(copyRules, "%s -> %s\n", src, dest)
215 info.snapshotContents = append(info.snapshotContents, dest)
216
217 case repackageZip.String():
218 // Add the destdir to the snapshot contents as that is effectively where
219 // the content of the repackaged zip is copied.
220 dest := bp.Args["destdir"]
221 info.snapshotContents = append(info.snapshotContents, dest)
222
223 case zipFiles.String():
224 // This could be an intermediate zip file and not the actual output zip.
225 // In that case this will be overridden when the rule to merge the zips
226 // is processed.
227 info.outputZip = r.pathRelativeToBuildDir(bp.Output)
228
229 case mergeZips.String():
230 // Copy the current outputZip to the intermediateZip.
231 info.intermediateZip = info.outputZip
232 mergeInput := r.pathRelativeToBuildDir(bp.Input)
233 if info.intermediateZip != mergeInput {
234 r.t.Errorf("Expected intermediate zip %s to be an input to merge zips but found %s instead",
235 info.intermediateZip, mergeInput)
236 }
237
238 // Override output zip (which was actually the intermediate zip file) with the actual
239 // output zip.
240 info.outputZip = r.pathRelativeToBuildDir(bp.Output)
241
242 // Save the zips to be merged into the intermediate zip.
243 info.mergeZips = r.pathsRelativeToBuildDir(bp.Inputs)
244 }
245 }
246
247 info.copyRules = copyRules.String()
248
249 return info
250}
251
252func (r *testSdkResult) Module(name string, variant string) android.Module {
253 return r.ctx.ModuleForTests(name, variant).Module()
254}
255
256func (r *testSdkResult) ModuleForTests(name string, variant string) android.TestingModule {
257 return r.ctx.ModuleForTests(name, variant)
258}
259
260func (r *testSdkResult) pathRelativeToBuildDir(path android.Path) string {
261 buildDir := filepath.Clean(r.config.BuildDir()) + "/"
262 return strings.TrimPrefix(filepath.Clean(path.String()), buildDir)
263}
264
265func (r *testSdkResult) pathsRelativeToBuildDir(paths android.Paths) []string {
266 var result []string
267 for _, path := range paths {
268 result = append(result, r.pathRelativeToBuildDir(path))
269 }
270 return result
271}
272
273// Check the snapshot build rules.
274//
275// Takes a list of functions which check different facets of the snapshot build rules.
276// Allows each test to customize what is checked without duplicating lots of code
277// or proliferating check methods of different flavors.
Paul Duffin593b3c92019-12-05 14:31:48 +0000278func (r *testSdkResult) CheckSnapshot(name string, variant string, dir string, checkers ...snapshotBuildInfoChecker) {
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000279 r.t.Helper()
280
281 sdk := r.Module(name, variant).(*sdk)
282
283 snapshotBuildInfo := r.getSdkSnapshotBuildInfo(sdk)
284
285 // Check state of the snapshot build.
286 for _, checker := range checkers {
287 checker(snapshotBuildInfo)
288 }
289
290 // Make sure that the generated zip file is in the correct place.
291 actual := snapshotBuildInfo.outputZip
Paul Duffin593b3c92019-12-05 14:31:48 +0000292 if dir != "" {
293 dir = filepath.Clean(dir) + "/"
294 }
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000295 r.AssertStringEquals("Snapshot zip file in wrong place",
Paul Duffin593b3c92019-12-05 14:31:48 +0000296 fmt.Sprintf(".intermediates/%s%s/%s/%s-current.zip", dir, name, variant, name), actual)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000297
298 // Populate a mock filesystem with the files that would have been copied by
299 // the rules.
300 fs := make(map[string][]byte)
301 for _, dest := range snapshotBuildInfo.snapshotContents {
302 fs[dest] = nil
303 }
304
305 // Process the generated bp file to make sure it is valid.
306 testSdkWithFs(r.t, snapshotBuildInfo.androidBpContents, fs)
307}
308
309type snapshotBuildInfoChecker func(info *snapshotBuildInfo)
310
311// Check that the snapshot's generated Android.bp is correct.
312//
313// Both the expected and actual string are both trimmed before comparing.
314func checkAndroidBpContents(expected string) snapshotBuildInfoChecker {
315 return func(info *snapshotBuildInfo) {
316 info.r.t.Helper()
317 info.r.AssertTrimmedStringEquals("Android.bp contents do not match", expected, info.androidBpContents)
318 }
319}
320
321// Check that the snapshot's copy rules are correct.
322//
323// The copy rules are formatted as <src> -> <dest>, one per line and then compared
324// to the supplied expected string. Both the expected and actual string are trimmed
325// before comparing.
326func checkAllCopyRules(expected string) snapshotBuildInfoChecker {
327 return func(info *snapshotBuildInfo) {
328 info.r.t.Helper()
329 info.r.AssertTrimmedStringEquals("Incorrect copy rules", expected, info.copyRules)
330 }
331}
332
333// 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
359 // A formatted representation of the src/dest pairs, one pair per line, of the format
360 // src -> dest
361 copyRules string
362
363 // The path to the intermediate zip, which is a zip created from the source files copied
364 // into the snapshot directory and which will be merged with other zips to form the final output.
365 // Is am empty string if there is no intermediate zip because there are no zips to merge in.
366 intermediateZip string
367
368 // The paths to the zips to merge into the output zip, does not include the intermediate
369 // zip.
370 mergeZips []string
371
372 // The final output zip.
373 outputZip string
374}
375
Paul Duffin82d90432019-11-30 09:24:33 +0000376var buildDir string
377
378func setUp() {
379 var err error
380 buildDir, err = ioutil.TempDir("", "soong_sdk_test")
381 if err != nil {
382 panic(err)
383 }
384}
385
386func tearDown() {
387 _ = os.RemoveAll(buildDir)
388}
389
390func runTestWithBuildDir(m *testing.M) {
391 run := func() int {
392 setUp()
393 defer tearDown()
394
395 return m.Run()
396 }
397
398 os.Exit(run())
399}
400
401func SkipIfNotLinux(t *testing.T) {
402 t.Helper()
403 if android.BuildOs != android.Linux {
404 t.Skipf("Skipping as sdk snapshot generation is only supported on %s not %s", android.Linux, android.BuildOs)
405 }
406}