blob: 09d0247c03d69c9bde69f45b19b629ca4aa3d3ba [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 Duffin593b3c92019-12-05 14:31:48 +000071 ctx.RegisterModuleType("package", android.PackageFactory)
Paul Duffin82d90432019-11-30 09:24:33 +000072
73 // from java package
Paul Duffinf9b1da02019-12-18 19:51:55 +000074 java.RegisterJavaBuildComponents(ctx)
75 java.RegisterAppBuildComponents(ctx)
Paul Duffin884363e2019-12-19 10:21:09 +000076 java.RegisterStubsBuildComponents(ctx)
Paul Duffin82d90432019-11-30 09:24:33 +000077
78 // from cc package
Paul Duffin77980a82019-12-19 16:01:36 +000079 cc.RegisterRequiredBuildComponentsForTest(ctx)
Paul Duffin82d90432019-11-30 09:24:33 +000080 ctx.RegisterModuleType("cc_library_shared", cc.LibrarySharedFactory)
Paul Duffin9ab556f2019-12-11 18:42:17 +000081 ctx.RegisterModuleType("cc_library_static", cc.LibraryStaticFactory)
Paul Duffin82d90432019-11-30 09:24:33 +000082
83 // from apex package
84 ctx.RegisterModuleType("apex", apex.BundleFactory)
85 ctx.RegisterModuleType("apex_key", apex.ApexKeyFactory)
86 ctx.PostDepsMutators(apex.RegisterPostDepsMutators)
87
88 // from this package
89 ctx.RegisterModuleType("sdk", ModuleFactory)
90 ctx.RegisterModuleType("sdk_snapshot", SnapshotModuleFactory)
91 ctx.PreDepsMutators(RegisterPreDepsMutators)
92 ctx.PostDepsMutators(RegisterPostDepsMutators)
93
Colin Cross98be1bb2019-12-13 20:41:13 -080094 ctx.Register(config)
Paul Duffin82d90432019-11-30 09:24:33 +000095
96 return ctx, config
97}
98
Paul Duffinc3c5d5e2019-11-29 20:45:22 +000099func testSdkWithFs(t *testing.T, bp string, fs map[string][]byte) *testSdkResult {
100 t.Helper()
101 ctx, config := testSdkContext(bp, fs)
Paul Duffin593b3c92019-12-05 14:31:48 +0000102 _, errs := ctx.ParseBlueprintsFiles(".")
Paul Duffin82d90432019-11-30 09:24:33 +0000103 android.FailIfErrored(t, errs)
104 _, errs = ctx.PrepareBuildActions(config)
105 android.FailIfErrored(t, errs)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000106 return &testSdkResult{
107 TestHelper: TestHelper{t: t},
108 ctx: ctx,
109 config: config,
110 }
Paul Duffin82d90432019-11-30 09:24:33 +0000111}
112
113func testSdkError(t *testing.T, pattern, bp string) {
114 t.Helper()
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000115 ctx, config := testSdkContext(bp, nil)
Paul Duffin82d90432019-11-30 09:24:33 +0000116 _, errs := ctx.ParseFileList(".", []string{"Android.bp"})
117 if len(errs) > 0 {
118 android.FailIfNoMatchingErrors(t, pattern, errs)
119 return
120 }
121 _, errs = ctx.PrepareBuildActions(config)
122 if len(errs) > 0 {
123 android.FailIfNoMatchingErrors(t, pattern, errs)
124 return
125 }
126
127 t.Fatalf("missing expected error %q (0 errors are returned)", pattern)
128}
129
130func ensureListContains(t *testing.T, result []string, expected string) {
131 t.Helper()
132 if !android.InList(expected, result) {
133 t.Errorf("%q is not found in %v", expected, result)
134 }
135}
136
137func pathsToStrings(paths android.Paths) []string {
138 var ret []string
139 for _, p := range paths {
140 ret = append(ret, p.String())
141 }
142 return ret
143}
144
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000145// Provides general test support.
146type TestHelper struct {
147 t *testing.T
148}
149
150func (h *TestHelper) AssertStringEquals(message string, expected string, actual string) {
151 h.t.Helper()
152 if actual != expected {
153 h.t.Errorf("%s: expected %s, actual %s", message, expected, actual)
Paul Duffin82d90432019-11-30 09:24:33 +0000154 }
155}
156
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000157func (h *TestHelper) AssertTrimmedStringEquals(message string, expected string, actual string) {
158 h.t.Helper()
159 h.AssertStringEquals(message, strings.TrimSpace(expected), strings.TrimSpace(actual))
160}
161
162// Encapsulates result of processing an SDK definition. Provides support for
163// checking the state of the build structures.
164type testSdkResult struct {
165 TestHelper
166 ctx *android.TestContext
167 config android.Config
168}
169
170// Analyse the sdk build rules to extract information about what it is doing.
171
172// e.g. find the src/dest pairs from each cp command, the various zip files
173// generated, etc.
174func (r *testSdkResult) getSdkSnapshotBuildInfo(sdk *sdk) *snapshotBuildInfo {
175 androidBpContents := strings.NewReplacer("\\n", "\n").Replace(sdk.GetAndroidBpContentsForTests())
176
177 info := &snapshotBuildInfo{
178 r: r,
179 androidBpContents: androidBpContents,
180 }
181
182 buildParams := sdk.BuildParamsForTests()
183 copyRules := &strings.Builder{}
184 for _, bp := range buildParams {
185 switch bp.Rule.String() {
186 case android.Cp.String():
187 // Get source relative to build directory.
Paul Duffin9b478b02019-12-10 13:41:51 +0000188 src := android.NormalizePathForTesting(bp.Input)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000189 // Get destination relative to the snapshot root
190 dest := bp.Output.Rel()
191 _, _ = fmt.Fprintf(copyRules, "%s -> %s\n", src, dest)
192 info.snapshotContents = append(info.snapshotContents, dest)
193
194 case repackageZip.String():
195 // Add the destdir to the snapshot contents as that is effectively where
196 // the content of the repackaged zip is copied.
197 dest := bp.Args["destdir"]
198 info.snapshotContents = append(info.snapshotContents, dest)
199
200 case zipFiles.String():
201 // This could be an intermediate zip file and not the actual output zip.
202 // In that case this will be overridden when the rule to merge the zips
203 // is processed.
Paul Duffin9b478b02019-12-10 13:41:51 +0000204 info.outputZip = android.NormalizePathForTesting(bp.Output)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000205
206 case mergeZips.String():
207 // Copy the current outputZip to the intermediateZip.
208 info.intermediateZip = info.outputZip
Paul Duffin9b478b02019-12-10 13:41:51 +0000209 mergeInput := android.NormalizePathForTesting(bp.Input)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000210 if info.intermediateZip != mergeInput {
211 r.t.Errorf("Expected intermediate zip %s to be an input to merge zips but found %s instead",
212 info.intermediateZip, mergeInput)
213 }
214
215 // Override output zip (which was actually the intermediate zip file) with the actual
216 // output zip.
Paul Duffin9b478b02019-12-10 13:41:51 +0000217 info.outputZip = android.NormalizePathForTesting(bp.Output)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000218
219 // Save the zips to be merged into the intermediate zip.
Paul Duffin9b478b02019-12-10 13:41:51 +0000220 info.mergeZips = android.NormalizePathsForTesting(bp.Inputs)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000221 }
222 }
223
224 info.copyRules = copyRules.String()
225
226 return info
227}
228
229func (r *testSdkResult) Module(name string, variant string) android.Module {
230 return r.ctx.ModuleForTests(name, variant).Module()
231}
232
233func (r *testSdkResult) ModuleForTests(name string, variant string) android.TestingModule {
234 return r.ctx.ModuleForTests(name, variant)
235}
236
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000237// Check the snapshot build rules.
238//
239// Takes a list of functions which check different facets of the snapshot build rules.
240// Allows each test to customize what is checked without duplicating lots of code
241// or proliferating check methods of different flavors.
Paul Duffin593b3c92019-12-05 14:31:48 +0000242func (r *testSdkResult) CheckSnapshot(name string, variant string, dir string, checkers ...snapshotBuildInfoChecker) {
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000243 r.t.Helper()
244
245 sdk := r.Module(name, variant).(*sdk)
246
247 snapshotBuildInfo := r.getSdkSnapshotBuildInfo(sdk)
248
249 // Check state of the snapshot build.
250 for _, checker := range checkers {
251 checker(snapshotBuildInfo)
252 }
253
254 // Make sure that the generated zip file is in the correct place.
255 actual := snapshotBuildInfo.outputZip
Paul Duffin593b3c92019-12-05 14:31:48 +0000256 if dir != "" {
257 dir = filepath.Clean(dir) + "/"
258 }
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000259 r.AssertStringEquals("Snapshot zip file in wrong place",
Paul Duffin593b3c92019-12-05 14:31:48 +0000260 fmt.Sprintf(".intermediates/%s%s/%s/%s-current.zip", dir, name, variant, name), actual)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000261
262 // Populate a mock filesystem with the files that would have been copied by
263 // the rules.
264 fs := make(map[string][]byte)
265 for _, dest := range snapshotBuildInfo.snapshotContents {
266 fs[dest] = nil
267 }
268
269 // Process the generated bp file to make sure it is valid.
270 testSdkWithFs(r.t, snapshotBuildInfo.androidBpContents, fs)
271}
272
273type snapshotBuildInfoChecker func(info *snapshotBuildInfo)
274
275// Check that the snapshot's generated Android.bp is correct.
276//
277// Both the expected and actual string are both trimmed before comparing.
278func checkAndroidBpContents(expected string) snapshotBuildInfoChecker {
279 return func(info *snapshotBuildInfo) {
280 info.r.t.Helper()
281 info.r.AssertTrimmedStringEquals("Android.bp contents do not match", expected, info.androidBpContents)
282 }
283}
284
285// Check that the snapshot's copy rules are correct.
286//
287// The copy rules are formatted as <src> -> <dest>, one per line and then compared
288// to the supplied expected string. Both the expected and actual string are trimmed
289// before comparing.
290func checkAllCopyRules(expected string) snapshotBuildInfoChecker {
291 return func(info *snapshotBuildInfo) {
292 info.r.t.Helper()
293 info.r.AssertTrimmedStringEquals("Incorrect copy rules", expected, info.copyRules)
294 }
295}
296
297// Check that the specified path is in the list of zips to merge with the intermediate zip.
298func checkMergeZip(expected string) snapshotBuildInfoChecker {
299 return func(info *snapshotBuildInfo) {
300 info.r.t.Helper()
301 if info.intermediateZip == "" {
302 info.r.t.Errorf("No intermediate zip file was created")
303 }
304 ensureListContains(info.r.t, info.mergeZips, expected)
305 }
306}
307
308// Encapsulates information about the snapshot build structure in order to insulate tests from
309// knowing too much about internal structures.
310//
311// All source/input paths are relative either the build directory. All dest/output paths are
312// relative to the snapshot root directory.
313type snapshotBuildInfo struct {
314 r *testSdkResult
315
316 // The contents of the generated Android.bp file
317 androidBpContents string
318
319 // The paths, relative to the snapshot root, of all files and directories copied into the
320 // snapshot.
321 snapshotContents []string
322
323 // A formatted representation of the src/dest pairs, one pair per line, of the format
324 // src -> dest
325 copyRules string
326
327 // The path to the intermediate zip, which is a zip created from the source files copied
328 // into the snapshot directory and which will be merged with other zips to form the final output.
329 // Is am empty string if there is no intermediate zip because there are no zips to merge in.
330 intermediateZip string
331
332 // The paths to the zips to merge into the output zip, does not include the intermediate
333 // zip.
334 mergeZips []string
335
336 // The final output zip.
337 outputZip string
338}
339
Paul Duffin82d90432019-11-30 09:24:33 +0000340var buildDir string
341
342func setUp() {
343 var err error
344 buildDir, err = ioutil.TempDir("", "soong_sdk_test")
345 if err != nil {
346 panic(err)
347 }
348}
349
350func tearDown() {
351 _ = os.RemoveAll(buildDir)
352}
353
354func runTestWithBuildDir(m *testing.M) {
355 run := func() int {
356 setUp()
357 defer tearDown()
358
359 return m.Run()
360 }
361
362 os.Exit(run())
363}
364
365func SkipIfNotLinux(t *testing.T) {
366 t.Helper()
367 if android.BuildOs != android.Linux {
368 t.Skipf("Skipping as sdk snapshot generation is only supported on %s not %s", android.Linux, android.BuildOs)
369 }
370}