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