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