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