blob: 61043f30ad305fa1e1ce58e48d41ee040869df38 [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 Duffin593b3c92019-12-05 14:31:48 +000065 ctx.PreArchMutators(android.RegisterPackageRenamer)
66 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 ctx.PreArchMutators(func(ctx android.RegisterMutatorsContext) {
72 ctx.BottomUp("prebuilts", android.PrebuiltMutator).Parallel()
73 })
74 ctx.PostDepsMutators(func(ctx android.RegisterMutatorsContext) {
75 ctx.TopDown("prebuilt_select", android.PrebuiltSelectModuleMutator).Parallel()
76 ctx.BottomUp("prebuilt_postdeps", android.PrebuiltPostDepsMutator).Parallel()
77 })
Paul Duffin593b3c92019-12-05 14:31:48 +000078 ctx.RegisterModuleType("package", android.PackageFactory)
Paul Duffin82d90432019-11-30 09:24:33 +000079
80 // from java package
Paul Duffinf9b1da02019-12-18 19:51:55 +000081 java.RegisterJavaBuildComponents(ctx)
82 java.RegisterAppBuildComponents(ctx)
Paul Duffin884363e2019-12-19 10:21:09 +000083 java.RegisterStubsBuildComponents(ctx)
Paul Duffin82d90432019-11-30 09:24:33 +000084
85 // from cc package
86 ctx.RegisterModuleType("cc_library", cc.LibraryFactory)
87 ctx.RegisterModuleType("cc_library_shared", cc.LibrarySharedFactory)
Paul Duffin9ab556f2019-12-11 18:42:17 +000088 ctx.RegisterModuleType("cc_library_static", cc.LibraryStaticFactory)
Paul Duffin82d90432019-11-30 09:24:33 +000089 ctx.RegisterModuleType("cc_object", cc.ObjectFactory)
Paul Duffin59986b22019-12-19 14:38:36 +000090 cc.RegisterPrebuiltBuildComponents(ctx)
Paul Duffin82d90432019-11-30 09:24:33 +000091 ctx.RegisterModuleType("llndk_library", cc.LlndkLibraryFactory)
92 ctx.RegisterModuleType("toolchain_library", cc.ToolchainLibraryFactory)
93 ctx.PreDepsMutators(func(ctx android.RegisterMutatorsContext) {
Paul Duffin82d90432019-11-30 09:24:33 +000094 ctx.BottomUp("link", cc.LinkageMutator).Parallel()
95 ctx.BottomUp("vndk", cc.VndkMutator).Parallel()
96 ctx.BottomUp("test_per_src", cc.TestPerSrcMutator).Parallel()
97 ctx.BottomUp("version", cc.VersionMutator).Parallel()
98 ctx.BottomUp("begin", cc.BeginMutator).Parallel()
99 })
100
101 // from apex package
102 ctx.RegisterModuleType("apex", apex.BundleFactory)
103 ctx.RegisterModuleType("apex_key", apex.ApexKeyFactory)
104 ctx.PostDepsMutators(apex.RegisterPostDepsMutators)
105
106 // from this package
107 ctx.RegisterModuleType("sdk", ModuleFactory)
108 ctx.RegisterModuleType("sdk_snapshot", SnapshotModuleFactory)
109 ctx.PreDepsMutators(RegisterPreDepsMutators)
110 ctx.PostDepsMutators(RegisterPostDepsMutators)
111
Colin Cross98be1bb2019-12-13 20:41:13 -0800112 ctx.Register(config)
Paul Duffin82d90432019-11-30 09:24:33 +0000113
114 return ctx, config
115}
116
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000117func testSdkWithFs(t *testing.T, bp string, fs map[string][]byte) *testSdkResult {
118 t.Helper()
119 ctx, config := testSdkContext(bp, fs)
Paul Duffin593b3c92019-12-05 14:31:48 +0000120 _, errs := ctx.ParseBlueprintsFiles(".")
Paul Duffin82d90432019-11-30 09:24:33 +0000121 android.FailIfErrored(t, errs)
122 _, errs = ctx.PrepareBuildActions(config)
123 android.FailIfErrored(t, errs)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000124 return &testSdkResult{
125 TestHelper: TestHelper{t: t},
126 ctx: ctx,
127 config: config,
128 }
Paul Duffin82d90432019-11-30 09:24:33 +0000129}
130
131func testSdkError(t *testing.T, pattern, bp string) {
132 t.Helper()
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000133 ctx, config := testSdkContext(bp, nil)
Paul Duffin82d90432019-11-30 09:24:33 +0000134 _, errs := ctx.ParseFileList(".", []string{"Android.bp"})
135 if len(errs) > 0 {
136 android.FailIfNoMatchingErrors(t, pattern, errs)
137 return
138 }
139 _, errs = ctx.PrepareBuildActions(config)
140 if len(errs) > 0 {
141 android.FailIfNoMatchingErrors(t, pattern, errs)
142 return
143 }
144
145 t.Fatalf("missing expected error %q (0 errors are returned)", pattern)
146}
147
148func ensureListContains(t *testing.T, result []string, expected string) {
149 t.Helper()
150 if !android.InList(expected, result) {
151 t.Errorf("%q is not found in %v", expected, result)
152 }
153}
154
155func pathsToStrings(paths android.Paths) []string {
156 var ret []string
157 for _, p := range paths {
158 ret = append(ret, p.String())
159 }
160 return ret
161}
162
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000163// Provides general test support.
164type TestHelper struct {
165 t *testing.T
166}
167
168func (h *TestHelper) AssertStringEquals(message string, expected string, actual string) {
169 h.t.Helper()
170 if actual != expected {
171 h.t.Errorf("%s: expected %s, actual %s", message, expected, actual)
Paul Duffin82d90432019-11-30 09:24:33 +0000172 }
173}
174
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000175func (h *TestHelper) AssertTrimmedStringEquals(message string, expected string, actual string) {
176 h.t.Helper()
177 h.AssertStringEquals(message, strings.TrimSpace(expected), strings.TrimSpace(actual))
178}
179
180// Encapsulates result of processing an SDK definition. Provides support for
181// checking the state of the build structures.
182type testSdkResult struct {
183 TestHelper
184 ctx *android.TestContext
185 config android.Config
186}
187
188// Analyse the sdk build rules to extract information about what it is doing.
189
190// e.g. find the src/dest pairs from each cp command, the various zip files
191// generated, etc.
192func (r *testSdkResult) getSdkSnapshotBuildInfo(sdk *sdk) *snapshotBuildInfo {
193 androidBpContents := strings.NewReplacer("\\n", "\n").Replace(sdk.GetAndroidBpContentsForTests())
194
195 info := &snapshotBuildInfo{
196 r: r,
197 androidBpContents: androidBpContents,
198 }
199
200 buildParams := sdk.BuildParamsForTests()
201 copyRules := &strings.Builder{}
202 for _, bp := range buildParams {
203 switch bp.Rule.String() {
204 case android.Cp.String():
205 // Get source relative to build directory.
206 src := r.pathRelativeToBuildDir(bp.Input)
207 // Get destination relative to the snapshot root
208 dest := bp.Output.Rel()
209 _, _ = fmt.Fprintf(copyRules, "%s -> %s\n", src, dest)
210 info.snapshotContents = append(info.snapshotContents, dest)
211
212 case repackageZip.String():
213 // Add the destdir to the snapshot contents as that is effectively where
214 // the content of the repackaged zip is copied.
215 dest := bp.Args["destdir"]
216 info.snapshotContents = append(info.snapshotContents, dest)
217
218 case zipFiles.String():
219 // This could be an intermediate zip file and not the actual output zip.
220 // In that case this will be overridden when the rule to merge the zips
221 // is processed.
222 info.outputZip = r.pathRelativeToBuildDir(bp.Output)
223
224 case mergeZips.String():
225 // Copy the current outputZip to the intermediateZip.
226 info.intermediateZip = info.outputZip
227 mergeInput := r.pathRelativeToBuildDir(bp.Input)
228 if info.intermediateZip != mergeInput {
229 r.t.Errorf("Expected intermediate zip %s to be an input to merge zips but found %s instead",
230 info.intermediateZip, mergeInput)
231 }
232
233 // Override output zip (which was actually the intermediate zip file) with the actual
234 // output zip.
235 info.outputZip = r.pathRelativeToBuildDir(bp.Output)
236
237 // Save the zips to be merged into the intermediate zip.
238 info.mergeZips = r.pathsRelativeToBuildDir(bp.Inputs)
239 }
240 }
241
242 info.copyRules = copyRules.String()
243
244 return info
245}
246
247func (r *testSdkResult) Module(name string, variant string) android.Module {
248 return r.ctx.ModuleForTests(name, variant).Module()
249}
250
251func (r *testSdkResult) ModuleForTests(name string, variant string) android.TestingModule {
252 return r.ctx.ModuleForTests(name, variant)
253}
254
255func (r *testSdkResult) pathRelativeToBuildDir(path android.Path) string {
256 buildDir := filepath.Clean(r.config.BuildDir()) + "/"
257 return strings.TrimPrefix(filepath.Clean(path.String()), buildDir)
258}
259
260func (r *testSdkResult) pathsRelativeToBuildDir(paths android.Paths) []string {
261 var result []string
262 for _, path := range paths {
263 result = append(result, r.pathRelativeToBuildDir(path))
264 }
265 return result
266}
267
268// Check the snapshot build rules.
269//
270// Takes a list of functions which check different facets of the snapshot build rules.
271// Allows each test to customize what is checked without duplicating lots of code
272// or proliferating check methods of different flavors.
Paul Duffin593b3c92019-12-05 14:31:48 +0000273func (r *testSdkResult) CheckSnapshot(name string, variant string, dir string, checkers ...snapshotBuildInfoChecker) {
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000274 r.t.Helper()
275
276 sdk := r.Module(name, variant).(*sdk)
277
278 snapshotBuildInfo := r.getSdkSnapshotBuildInfo(sdk)
279
280 // Check state of the snapshot build.
281 for _, checker := range checkers {
282 checker(snapshotBuildInfo)
283 }
284
285 // Make sure that the generated zip file is in the correct place.
286 actual := snapshotBuildInfo.outputZip
Paul Duffin593b3c92019-12-05 14:31:48 +0000287 if dir != "" {
288 dir = filepath.Clean(dir) + "/"
289 }
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000290 r.AssertStringEquals("Snapshot zip file in wrong place",
Paul Duffin593b3c92019-12-05 14:31:48 +0000291 fmt.Sprintf(".intermediates/%s%s/%s/%s-current.zip", dir, name, variant, name), actual)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000292
293 // Populate a mock filesystem with the files that would have been copied by
294 // the rules.
295 fs := make(map[string][]byte)
296 for _, dest := range snapshotBuildInfo.snapshotContents {
297 fs[dest] = nil
298 }
299
300 // Process the generated bp file to make sure it is valid.
301 testSdkWithFs(r.t, snapshotBuildInfo.androidBpContents, fs)
302}
303
304type snapshotBuildInfoChecker func(info *snapshotBuildInfo)
305
306// Check that the snapshot's generated Android.bp is correct.
307//
308// Both the expected and actual string are both trimmed before comparing.
309func checkAndroidBpContents(expected string) snapshotBuildInfoChecker {
310 return func(info *snapshotBuildInfo) {
311 info.r.t.Helper()
312 info.r.AssertTrimmedStringEquals("Android.bp contents do not match", expected, info.androidBpContents)
313 }
314}
315
316// Check that the snapshot's copy rules are correct.
317//
318// The copy rules are formatted as <src> -> <dest>, one per line and then compared
319// to the supplied expected string. Both the expected and actual string are trimmed
320// before comparing.
321func checkAllCopyRules(expected string) snapshotBuildInfoChecker {
322 return func(info *snapshotBuildInfo) {
323 info.r.t.Helper()
324 info.r.AssertTrimmedStringEquals("Incorrect copy rules", expected, info.copyRules)
325 }
326}
327
328// Check that the specified path is in the list of zips to merge with the intermediate zip.
329func checkMergeZip(expected string) snapshotBuildInfoChecker {
330 return func(info *snapshotBuildInfo) {
331 info.r.t.Helper()
332 if info.intermediateZip == "" {
333 info.r.t.Errorf("No intermediate zip file was created")
334 }
335 ensureListContains(info.r.t, info.mergeZips, expected)
336 }
337}
338
339// Encapsulates information about the snapshot build structure in order to insulate tests from
340// knowing too much about internal structures.
341//
342// All source/input paths are relative either the build directory. All dest/output paths are
343// relative to the snapshot root directory.
344type snapshotBuildInfo struct {
345 r *testSdkResult
346
347 // The contents of the generated Android.bp file
348 androidBpContents string
349
350 // The paths, relative to the snapshot root, of all files and directories copied into the
351 // snapshot.
352 snapshotContents []string
353
354 // A formatted representation of the src/dest pairs, one pair per line, of the format
355 // src -> dest
356 copyRules string
357
358 // The path to the intermediate zip, which is a zip created from the source files copied
359 // into the snapshot directory and which will be merged with other zips to form the final output.
360 // Is am empty string if there is no intermediate zip because there are no zips to merge in.
361 intermediateZip string
362
363 // The paths to the zips to merge into the output zip, does not include the intermediate
364 // zip.
365 mergeZips []string
366
367 // The final output zip.
368 outputZip string
369}
370
Paul Duffin82d90432019-11-30 09:24:33 +0000371var buildDir string
372
373func setUp() {
374 var err error
375 buildDir, err = ioutil.TempDir("", "soong_sdk_test")
376 if err != nil {
377 panic(err)
378 }
379}
380
381func tearDown() {
382 _ = os.RemoveAll(buildDir)
383}
384
385func runTestWithBuildDir(m *testing.M) {
386 run := func() int {
387 setUp()
388 defer tearDown()
389
390 return m.Run()
391 }
392
393 os.Exit(run())
394}
395
396func SkipIfNotLinux(t *testing.T) {
397 t.Helper()
398 if android.BuildOs != android.Linux {
399 t.Skipf("Skipping as sdk snapshot generation is only supported on %s not %s", android.Linux, android.BuildOs)
400 }
401}