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