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