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