blob: 5ad7ad07ffb56578869609dca50f4743a0daf61b [file] [log] [blame]
Colin Crosscec81712017-07-13 14:43:27 -07001// Copyright 2017 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 android
16
17import (
Martin Stjernholm1ebef5b2022-02-10 23:34:28 +000018 "bytes"
Colin Crosscec81712017-07-13 14:43:27 -070019 "fmt"
Paul Duffin9b478b02019-12-10 13:41:51 +000020 "path/filepath"
Logan Chienee97c3e2018-03-12 16:34:26 +080021 "regexp"
Martin Stjernholm4c021242020-05-13 01:13:50 +010022 "sort"
Colin Crosscec81712017-07-13 14:43:27 -070023 "strings"
Paul Duffin281deb22021-03-06 20:29:19 +000024 "sync"
Logan Chien42039712018-03-12 16:29:17 +080025 "testing"
Colin Crosscec81712017-07-13 14:43:27 -070026
Martin Stjernholm1ebef5b2022-02-10 23:34:28 +000027 mkparser "android/soong/androidmk/parser"
28
Colin Crosscec81712017-07-13 14:43:27 -070029 "github.com/google/blueprint"
Paul Duffin25259e92021-03-07 15:45:56 +000030 "github.com/google/blueprint/proptools"
Colin Crosscec81712017-07-13 14:43:27 -070031)
32
Paul Duffin3f7bf9f2022-11-08 12:21:15 +000033func newTestContextForFixture(config Config) *TestContext {
Jeff Gastonb274ed32017-12-01 17:10:33 -080034 ctx := &TestContext{
Paul Duffin3f7bf9f2022-11-08 12:21:15 +000035 Context: &Context{blueprint.NewContext(), config},
Jeff Gastonb274ed32017-12-01 17:10:33 -080036 }
37
Colin Cross1b488422019-03-04 22:33:56 -080038 ctx.postDeps = append(ctx.postDeps, registerPathDepsMutator)
39
Colin Crossae8600b2020-10-29 17:09:13 -070040 ctx.SetFs(ctx.config.fs)
41 if ctx.config.mockBpList != "" {
42 ctx.SetModuleListFile(ctx.config.mockBpList)
43 }
44
Jeff Gaston088e29e2017-11-29 16:47:17 -080045 return ctx
Colin Crosscec81712017-07-13 14:43:27 -070046}
47
Paul Duffin3f7bf9f2022-11-08 12:21:15 +000048func NewTestContext(config Config) *TestContext {
49 ctx := newTestContextForFixture(config)
50
51 nameResolver := NewNameResolver(config)
52 ctx.NameResolver = nameResolver
53 ctx.SetNameInterface(nameResolver)
54
55 return ctx
56}
57
Paul Duffina560d5a2021-02-28 01:38:51 +000058var PrepareForTestWithArchMutator = GroupFixturePreparers(
Paul Duffin35816122021-02-24 01:49:52 +000059 // Configure architecture targets in the fixture config.
60 FixtureModifyConfig(modifyTestConfigToSupportArchMutator),
61
62 // Add the arch mutator to the context.
63 FixtureRegisterWithContext(func(ctx RegistrationContext) {
64 ctx.PreDepsMutators(registerArchMutator)
65 }),
66)
67
68var PrepareForTestWithDefaults = FixtureRegisterWithContext(func(ctx RegistrationContext) {
69 ctx.PreArchMutators(RegisterDefaultsPreArchMutators)
70})
71
72var PrepareForTestWithComponentsMutator = FixtureRegisterWithContext(func(ctx RegistrationContext) {
73 ctx.PreArchMutators(RegisterComponentsMutator)
74})
75
76var PrepareForTestWithPrebuilts = FixtureRegisterWithContext(RegisterPrebuiltMutators)
77
78var PrepareForTestWithOverrides = FixtureRegisterWithContext(func(ctx RegistrationContext) {
79 ctx.PostDepsMutators(RegisterOverridePostDepsMutators)
80})
81
Paul Duffine96108d2021-05-06 16:39:27 +010082var PrepareForTestWithLicenses = GroupFixturePreparers(
83 FixtureRegisterWithContext(RegisterLicenseKindBuildComponents),
84 FixtureRegisterWithContext(RegisterLicenseBuildComponents),
85 FixtureRegisterWithContext(registerLicenseMutators),
86)
87
Bob Badour05079212022-05-20 16:41:39 -070088var PrepareForTestWithGenNotice = FixtureRegisterWithContext(RegisterGenNoticeBuildComponents)
89
Paul Duffine96108d2021-05-06 16:39:27 +010090func registerLicenseMutators(ctx RegistrationContext) {
91 ctx.PreArchMutators(RegisterLicensesPackageMapper)
92 ctx.PreArchMutators(RegisterLicensesPropertyGatherer)
93 ctx.PostDepsMutators(RegisterLicensesDependencyChecker)
94}
95
96var PrepareForTestWithLicenseDefaultModules = GroupFixturePreparers(
97 FixtureAddTextFile("build/soong/licenses/Android.bp", `
98 license {
99 name: "Android-Apache-2.0",
100 package_name: "Android",
101 license_kinds: ["SPDX-license-identifier-Apache-2.0"],
102 copyright_notice: "Copyright (C) The Android Open Source Project",
103 license_text: ["LICENSE"],
104 }
105
106 license_kind {
107 name: "SPDX-license-identifier-Apache-2.0",
108 conditions: ["notice"],
109 url: "https://spdx.org/licenses/Apache-2.0.html",
110 }
111
112 license_kind {
113 name: "legacy_unencumbered",
114 conditions: ["unencumbered"],
115 }
116 `),
117 FixtureAddFile("build/soong/licenses/LICENSE", nil),
118)
119
Paul Duffin4fbfb592021-07-09 16:47:38 +0100120var PrepareForTestWithNamespace = FixtureRegisterWithContext(func(ctx RegistrationContext) {
121 registerNamespaceBuildComponents(ctx)
122 ctx.PreArchMutators(RegisterNamespaceMutator)
123})
124
Martin Stjernholm1ebef5b2022-02-10 23:34:28 +0000125var PrepareForTestWithMakevars = FixtureRegisterWithContext(func(ctx RegistrationContext) {
126 ctx.RegisterSingletonType("makevars", makeVarsSingletonFunc)
127})
128
Paul Duffinec3292b2021-03-09 01:01:31 +0000129// Test fixture preparer that will register most java build components.
130//
131// Singletons and mutators should only be added here if they are needed for a majority of java
132// module types, otherwise they should be added under a separate preparer to allow them to be
133// selected only when needed to reduce test execution time.
134//
135// Module types do not have much of an overhead unless they are used so this should include as many
136// module types as possible. The exceptions are those module types that require mutators and/or
137// singletons in order to function in which case they should be kept together in a separate
138// preparer.
139//
140// The mutators in this group were chosen because they are needed by the vast majority of tests.
141var PrepareForTestWithAndroidBuildComponents = GroupFixturePreparers(
Paul Duffin530483c2021-03-07 13:20:38 +0000142 // Sorted alphabetically as the actual order does not matter as tests automatically enforce the
143 // correct order.
Paul Duffin35816122021-02-24 01:49:52 +0000144 PrepareForTestWithArchMutator,
Paul Duffin35816122021-02-24 01:49:52 +0000145 PrepareForTestWithComponentsMutator,
Paul Duffin530483c2021-03-07 13:20:38 +0000146 PrepareForTestWithDefaults,
Paul Duffin35816122021-02-24 01:49:52 +0000147 PrepareForTestWithFilegroup,
Paul Duffin530483c2021-03-07 13:20:38 +0000148 PrepareForTestWithOverrides,
149 PrepareForTestWithPackageModule,
150 PrepareForTestWithPrebuilts,
151 PrepareForTestWithVisibility,
Paul Duffin35816122021-02-24 01:49:52 +0000152)
153
Paul Duffinec3292b2021-03-09 01:01:31 +0000154// Prepares an integration test with all build components from the android package.
155//
156// This should only be used by tests that want to run with as much of the build enabled as possible.
157var PrepareForIntegrationTestWithAndroid = GroupFixturePreparers(
158 PrepareForTestWithAndroidBuildComponents,
159)
160
Paul Duffin25259e92021-03-07 15:45:56 +0000161// Prepares a test that may be missing dependencies by setting allow_missing_dependencies to
162// true.
163var PrepareForTestWithAllowMissingDependencies = GroupFixturePreparers(
164 FixtureModifyProductVariables(func(variables FixtureProductVariables) {
165 variables.Allow_missing_dependencies = proptools.BoolPtr(true)
166 }),
167 FixtureModifyContext(func(ctx *TestContext) {
168 ctx.SetAllowMissingDependencies(true)
169 }),
170)
171
Paul Duffin76e5c8a2021-03-20 14:19:46 +0000172// Prepares a test that disallows non-existent paths.
173var PrepareForTestDisallowNonExistentPaths = FixtureModifyConfig(func(config Config) {
174 config.TestAllowNonExistentPaths = false
175})
176
Colin Crossae8600b2020-10-29 17:09:13 -0700177func NewTestArchContext(config Config) *TestContext {
178 ctx := NewTestContext(config)
Colin Crossae4c6182017-09-15 17:33:55 -0700179 ctx.preDeps = append(ctx.preDeps, registerArchMutator)
180 return ctx
181}
182
Colin Crosscec81712017-07-13 14:43:27 -0700183type TestContext struct {
Colin Cross4c83e5c2019-02-25 14:54:28 -0800184 *Context
Chris Parsons5a34ffb2021-07-21 14:34:58 -0400185 preArch, preDeps, postDeps, finalDeps []RegisterMutatorFunc
186 bp2buildPreArch, bp2buildMutators []RegisterMutatorFunc
187 NameResolver *NameResolver
Paul Duffin281deb22021-03-06 20:29:19 +0000188
Paul Duffind182fb32021-03-07 12:24:44 +0000189 // The list of pre-singletons and singletons registered for the test.
190 preSingletons, singletons sortableComponents
191
Paul Duffin41d77c72021-03-07 12:23:48 +0000192 // The order in which the pre-singletons, mutators and singletons will be run in this test
193 // context; for debugging.
194 preSingletonOrder, mutatorOrder, singletonOrder []string
Colin Crosscec81712017-07-13 14:43:27 -0700195}
196
197func (ctx *TestContext) PreArchMutators(f RegisterMutatorFunc) {
198 ctx.preArch = append(ctx.preArch, f)
199}
200
Paul Duffina80ef842020-01-14 12:09:36 +0000201func (ctx *TestContext) HardCodedPreArchMutators(f RegisterMutatorFunc) {
202 // Register mutator function as normal for testing.
203 ctx.PreArchMutators(f)
204}
205
Liz Kammer92c72592022-10-31 14:44:28 -0400206func (ctx *TestContext) ModuleProvider(m blueprint.Module, p blueprint.ProviderKey) interface{} {
207 return ctx.Context.ModuleProvider(m, p)
208}
209
Colin Crosscec81712017-07-13 14:43:27 -0700210func (ctx *TestContext) PreDepsMutators(f RegisterMutatorFunc) {
211 ctx.preDeps = append(ctx.preDeps, f)
212}
213
214func (ctx *TestContext) PostDepsMutators(f RegisterMutatorFunc) {
215 ctx.postDeps = append(ctx.postDeps, f)
216}
217
Martin Stjernholm710ec3a2020-01-16 15:12:04 +0000218func (ctx *TestContext) FinalDepsMutators(f RegisterMutatorFunc) {
219 ctx.finalDeps = append(ctx.finalDeps, f)
220}
221
Cole Faust324a92e2022-08-23 15:29:05 -0700222func (ctx *TestContext) RegisterBp2BuildConfig(config Bp2BuildConversionAllowlist) {
223 ctx.config.Bp2buildPackageConfig = config
Jingwen Chen12b4c272021-03-10 02:05:59 -0500224}
225
Liz Kammer356f7d42021-01-26 09:18:53 -0500226// PreArchBp2BuildMutators adds mutators to be register for converting Android Blueprint modules
227// into Bazel BUILD targets that should run prior to deps and conversion.
228func (ctx *TestContext) PreArchBp2BuildMutators(f RegisterMutatorFunc) {
229 ctx.bp2buildPreArch = append(ctx.bp2buildPreArch, f)
230}
231
Paul Duffin281deb22021-03-06 20:29:19 +0000232// registeredComponentOrder defines the order in which a sortableComponent type is registered at
233// runtime and provides support for reordering the components registered for a test in the same
234// way.
235type registeredComponentOrder struct {
236 // The name of the component type, used for error messages.
237 componentType string
238
239 // The names of the registered components in the order in which they were registered.
240 namesInOrder []string
241
242 // Maps from the component name to its position in the runtime ordering.
243 namesToIndex map[string]int
244
245 // A function that defines the order between two named components that can be used to sort a slice
246 // of component names into the same order as they appear in namesInOrder.
247 less func(string, string) bool
248}
249
250// registeredComponentOrderFromExistingOrder takes an existing slice of sortableComponents and
251// creates a registeredComponentOrder that contains a less function that can be used to sort a
252// subset of that list of names so it is in the same order as the original sortableComponents.
253func registeredComponentOrderFromExistingOrder(componentType string, existingOrder sortableComponents) registeredComponentOrder {
254 // Only the names from the existing order are needed for this so create a list of component names
255 // in the correct order.
256 namesInOrder := componentsToNames(existingOrder)
257
258 // Populate the map from name to position in the list.
259 nameToIndex := make(map[string]int)
260 for i, n := range namesInOrder {
261 nameToIndex[n] = i
262 }
263
264 // A function to use to map from a name to an index in the original order.
265 indexOf := func(name string) int {
266 index, ok := nameToIndex[name]
267 if !ok {
268 // Should never happen as tests that use components that are not known at runtime do not sort
269 // so should never use this function.
270 panic(fmt.Errorf("internal error: unknown %s %q should be one of %s", componentType, name, strings.Join(namesInOrder, ", ")))
271 }
272 return index
273 }
274
275 // The less function.
276 less := func(n1, n2 string) bool {
277 i1 := indexOf(n1)
278 i2 := indexOf(n2)
279 return i1 < i2
280 }
281
282 return registeredComponentOrder{
283 componentType: componentType,
284 namesInOrder: namesInOrder,
285 namesToIndex: nameToIndex,
286 less: less,
287 }
288}
289
290// componentsToNames maps from the slice of components to a slice of their names.
291func componentsToNames(components sortableComponents) []string {
292 names := make([]string, len(components))
293 for i, c := range components {
294 names[i] = c.componentName()
295 }
296 return names
297}
298
299// enforceOrdering enforces the supplied components are in the same order as is defined in this
300// object.
301//
302// If the supplied components contains any components that are not registered at runtime, i.e. test
303// specific components, then it is impossible to sort them into an order that both matches the
304// runtime and also preserves the implicit ordering defined in the test. In that case it will not
305// sort the components, instead it will just check that the components are in the correct order.
306//
307// Otherwise, this will sort the supplied components in place.
308func (o *registeredComponentOrder) enforceOrdering(components sortableComponents) {
309 // Check to see if the list of components contains any components that are
310 // not registered at runtime.
311 var unknownComponents []string
312 testOrder := componentsToNames(components)
313 for _, name := range testOrder {
314 if _, ok := o.namesToIndex[name]; !ok {
315 unknownComponents = append(unknownComponents, name)
316 break
317 }
318 }
319
320 // If the slice contains some unknown components then it is not possible to
321 // sort them into an order that matches the runtime while also preserving the
322 // order expected from the test, so in that case don't sort just check that
323 // the order of the known mutators does match.
324 if len(unknownComponents) > 0 {
325 // Check order.
326 o.checkTestOrder(testOrder, unknownComponents)
327 } else {
328 // Sort the components.
329 sort.Slice(components, func(i, j int) bool {
330 n1 := components[i].componentName()
331 n2 := components[j].componentName()
332 return o.less(n1, n2)
333 })
334 }
335}
336
337// checkTestOrder checks that the supplied testOrder matches the one defined by this object,
338// panicking if it does not.
339func (o *registeredComponentOrder) checkTestOrder(testOrder []string, unknownComponents []string) {
340 lastMatchingTest := -1
341 matchCount := 0
342 // Take a copy of the runtime order as it is modified during the comparison.
343 runtimeOrder := append([]string(nil), o.namesInOrder...)
344 componentType := o.componentType
345 for i, j := 0, 0; i < len(testOrder) && j < len(runtimeOrder); {
346 test := testOrder[i]
347 runtime := runtimeOrder[j]
348
349 if test == runtime {
350 testOrder[i] = test + fmt.Sprintf(" <-- matched with runtime %s %d", componentType, j)
351 runtimeOrder[j] = runtime + fmt.Sprintf(" <-- matched with test %s %d", componentType, i)
352 lastMatchingTest = i
353 i += 1
354 j += 1
355 matchCount += 1
356 } else if _, ok := o.namesToIndex[test]; !ok {
357 // The test component is not registered globally so assume it is the correct place, treat it
358 // as having matched and skip it.
359 i += 1
360 matchCount += 1
361 } else {
362 // Assume that the test list is in the same order as the runtime list but the runtime list
363 // contains some components that are not present in the tests. So, skip the runtime component
364 // to try and find the next one that matches the current test component.
365 j += 1
366 }
367 }
368
369 // If every item in the test order was either test specific or matched one in the runtime then
370 // it is in the correct order. Otherwise, it was not so fail.
371 if matchCount != len(testOrder) {
372 // The test component names were not all matched with a runtime component name so there must
373 // either be a component present in the test that is not present in the runtime or they must be
374 // in the wrong order.
375 testOrder[lastMatchingTest+1] = testOrder[lastMatchingTest+1] + " <--- unmatched"
376 panic(fmt.Errorf("the tests uses test specific components %q and so cannot be automatically sorted."+
377 " Unfortunately it uses %s components in the wrong order.\n"+
378 "test order:\n %s\n"+
379 "runtime order\n %s\n",
380 SortedUniqueStrings(unknownComponents),
381 componentType,
382 strings.Join(testOrder, "\n "),
383 strings.Join(runtimeOrder, "\n ")))
384 }
385}
386
387// registrationSorter encapsulates the information needed to ensure that the test mutators are
388// registered, and thereby executed, in the same order as they are at runtime.
389//
390// It MUST be populated lazily AFTER all package initialization has been done otherwise it will
391// only define the order for a subset of all the registered build components that are available for
392// the packages being tested.
393//
394// e.g if this is initialized during say the cc package initialization then any tests run in the
395// java package will not sort build components registered by the java package's init() functions.
396type registrationSorter struct {
397 // Used to ensure that this is only created once.
398 once sync.Once
399
Paul Duffin41d77c72021-03-07 12:23:48 +0000400 // The order of pre-singletons
401 preSingletonOrder registeredComponentOrder
402
Paul Duffin281deb22021-03-06 20:29:19 +0000403 // The order of mutators
404 mutatorOrder registeredComponentOrder
Paul Duffin41d77c72021-03-07 12:23:48 +0000405
406 // The order of singletons
407 singletonOrder registeredComponentOrder
Paul Duffin281deb22021-03-06 20:29:19 +0000408}
409
410// populate initializes this structure from globally registered build components.
411//
412// Only the first call has any effect.
413func (s *registrationSorter) populate() {
414 s.once.Do(func() {
Paul Duffin41d77c72021-03-07 12:23:48 +0000415 // Create an ordering from the globally registered pre-singletons.
416 s.preSingletonOrder = registeredComponentOrderFromExistingOrder("pre-singleton", preSingletons)
417
Paul Duffin281deb22021-03-06 20:29:19 +0000418 // Created an ordering from the globally registered mutators.
419 globallyRegisteredMutators := collateGloballyRegisteredMutators()
420 s.mutatorOrder = registeredComponentOrderFromExistingOrder("mutator", globallyRegisteredMutators)
Paul Duffin41d77c72021-03-07 12:23:48 +0000421
422 // Create an ordering from the globally registered singletons.
423 globallyRegisteredSingletons := collateGloballyRegisteredSingletons()
424 s.singletonOrder = registeredComponentOrderFromExistingOrder("singleton", globallyRegisteredSingletons)
Paul Duffin281deb22021-03-06 20:29:19 +0000425 })
426}
427
428// Provides support for enforcing the same order in which build components are registered globally
429// to the order in which they are registered during tests.
430//
431// MUST only be accessed via the globallyRegisteredComponentsOrder func.
432var globalRegistrationSorter registrationSorter
433
434// globallyRegisteredComponentsOrder returns the globalRegistrationSorter after ensuring it is
435// correctly populated.
436func globallyRegisteredComponentsOrder() *registrationSorter {
437 globalRegistrationSorter.populate()
438 return &globalRegistrationSorter
439}
440
Colin Crossae8600b2020-10-29 17:09:13 -0700441func (ctx *TestContext) Register() {
Paul Duffin281deb22021-03-06 20:29:19 +0000442 globalOrder := globallyRegisteredComponentsOrder()
443
Paul Duffin41d77c72021-03-07 12:23:48 +0000444 // Ensure that the pre-singletons used in the test are in the same order as they are used at
445 // runtime.
446 globalOrder.preSingletonOrder.enforceOrdering(ctx.preSingletons)
Paul Duffind182fb32021-03-07 12:24:44 +0000447 ctx.preSingletons.registerAll(ctx.Context)
448
Paul Duffinc05b0342021-03-06 13:28:13 +0000449 mutators := collateRegisteredMutators(ctx.preArch, ctx.preDeps, ctx.postDeps, ctx.finalDeps)
Paul Duffin281deb22021-03-06 20:29:19 +0000450 // Ensure that the mutators used in the test are in the same order as they are used at runtime.
451 globalOrder.mutatorOrder.enforceOrdering(mutators)
Paul Duffinc05b0342021-03-06 13:28:13 +0000452 mutators.registerAll(ctx.Context)
Colin Crosscec81712017-07-13 14:43:27 -0700453
Paul Duffin41d77c72021-03-07 12:23:48 +0000454 // Ensure that the singletons used in the test are in the same order as they are used at runtime.
455 globalOrder.singletonOrder.enforceOrdering(ctx.singletons)
Paul Duffind182fb32021-03-07 12:24:44 +0000456 ctx.singletons.registerAll(ctx.Context)
457
Paul Duffin41d77c72021-03-07 12:23:48 +0000458 // Save the sorted components order away to make them easy to access while debugging.
Paul Duffinf5de6682021-03-08 23:42:10 +0000459 ctx.preSingletonOrder = componentsToNames(preSingletons)
460 ctx.mutatorOrder = componentsToNames(mutators)
461 ctx.singletonOrder = componentsToNames(singletons)
Colin Cross31a738b2019-12-30 18:45:15 -0800462}
463
Jingwen Chen73850672020-12-14 08:25:34 -0500464// RegisterForBazelConversion prepares a test context for bp2build conversion.
465func (ctx *TestContext) RegisterForBazelConversion() {
Chris Parsonsad876012022-08-20 14:48:32 -0400466 ctx.config.BuildMode = Bp2build
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400467 RegisterMutatorsForBazelConversion(ctx.Context, ctx.bp2buildPreArch)
Jingwen Chen73850672020-12-14 08:25:34 -0500468}
469
Spandan Das5af0bd32022-09-28 20:43:08 +0000470// RegisterForApiBazelConversion prepares a test context for API bp2build conversion.
471func (ctx *TestContext) RegisterForApiBazelConversion() {
472 ctx.config.BuildMode = ApiBp2build
473 RegisterMutatorsForApiBazelConversion(ctx.Context, ctx.bp2buildPreArch)
474}
475
Colin Cross31a738b2019-12-30 18:45:15 -0800476func (ctx *TestContext) ParseFileList(rootDir string, filePaths []string) (deps []string, errs []error) {
477 // This function adapts the old style ParseFileList calls that are spread throughout the tests
478 // to the new style that takes a config.
479 return ctx.Context.ParseFileList(rootDir, filePaths, ctx.config)
480}
481
482func (ctx *TestContext) ParseBlueprintsFiles(rootDir string) (deps []string, errs []error) {
483 // This function adapts the old style ParseBlueprintsFiles calls that are spread throughout the
484 // tests to the new style that takes a config.
485 return ctx.Context.ParseBlueprintsFiles(rootDir, ctx.config)
Colin Cross4b49b762019-11-22 15:25:03 -0800486}
487
488func (ctx *TestContext) RegisterModuleType(name string, factory ModuleFactory) {
489 ctx.Context.RegisterModuleType(name, ModuleFactoryAdaptor(factory))
490}
491
Colin Cross9aed5bc2020-12-28 15:15:34 -0800492func (ctx *TestContext) RegisterSingletonModuleType(name string, factory SingletonModuleFactory) {
493 s, m := SingletonModuleFactoryAdaptor(name, factory)
494 ctx.RegisterSingletonType(name, s)
495 ctx.RegisterModuleType(name, m)
496}
497
LaMont Jonese59c0db2023-05-15 21:50:29 +0000498func (ctx *TestContext) RegisterParallelSingletonModuleType(name string, factory SingletonModuleFactory) {
499 s, m := SingletonModuleFactoryAdaptor(name, factory)
500 ctx.RegisterParallelSingletonType(name, s)
501 ctx.RegisterModuleType(name, m)
502}
503
Colin Cross4b49b762019-11-22 15:25:03 -0800504func (ctx *TestContext) RegisterSingletonType(name string, factory SingletonFactory) {
LaMont Jonese59c0db2023-05-15 21:50:29 +0000505 ctx.singletons = append(ctx.singletons, newSingleton(name, factory, false))
506}
507
508func (ctx *TestContext) RegisterParallelSingletonType(name string, factory SingletonFactory) {
509 ctx.singletons = append(ctx.singletons, newSingleton(name, factory, true))
Colin Crosscec81712017-07-13 14:43:27 -0700510}
511
Paul Duffineafc16b2021-02-24 01:43:18 +0000512func (ctx *TestContext) RegisterPreSingletonType(name string, factory SingletonFactory) {
Paul Duffind182fb32021-03-07 12:24:44 +0000513 ctx.preSingletons = append(ctx.preSingletons, newPreSingleton(name, factory))
Paul Duffineafc16b2021-02-24 01:43:18 +0000514}
515
Martin Stjernholm14cdd712021-09-10 22:39:59 +0100516// ModuleVariantForTests selects a specific variant of the module with the given
517// name by matching the variations map against the variations of each module
518// variant. A module variant matches the map if every variation that exists in
519// both have the same value. Both the module and the map are allowed to have
520// extra variations that the other doesn't have. Panics if not exactly one
521// module variant matches.
522func (ctx *TestContext) ModuleVariantForTests(name string, matchVariations map[string]string) TestingModule {
523 modules := []Module{}
524 ctx.VisitAllModules(func(m blueprint.Module) {
525 if ctx.ModuleName(m) == name {
526 am := m.(Module)
527 amMut := am.base().commonProperties.DebugMutators
528 amVar := am.base().commonProperties.DebugVariations
529 matched := true
530 for i, mut := range amMut {
531 if wantedVar, found := matchVariations[mut]; found && amVar[i] != wantedVar {
532 matched = false
533 break
534 }
535 }
536 if matched {
537 modules = append(modules, am)
538 }
539 }
540 })
541
542 if len(modules) == 0 {
543 // Show all the modules or module variants that do exist.
544 var allModuleNames []string
545 var allVariants []string
546 ctx.VisitAllModules(func(m blueprint.Module) {
547 allModuleNames = append(allModuleNames, ctx.ModuleName(m))
548 if ctx.ModuleName(m) == name {
549 allVariants = append(allVariants, m.(Module).String())
550 }
551 })
552
553 if len(allVariants) == 0 {
554 panic(fmt.Errorf("failed to find module %q. All modules:\n %s",
555 name, strings.Join(SortedUniqueStrings(allModuleNames), "\n ")))
556 } else {
557 sort.Strings(allVariants)
558 panic(fmt.Errorf("failed to find module %q matching %v. All variants:\n %s",
559 name, matchVariations, strings.Join(allVariants, "\n ")))
560 }
561 }
562
563 if len(modules) > 1 {
564 moduleStrings := []string{}
565 for _, m := range modules {
566 moduleStrings = append(moduleStrings, m.String())
567 }
568 sort.Strings(moduleStrings)
569 panic(fmt.Errorf("module %q has more than one variant that match %v:\n %s",
570 name, matchVariations, strings.Join(moduleStrings, "\n ")))
571 }
572
573 return newTestingModule(ctx.config, modules[0])
574}
575
Colin Crosscec81712017-07-13 14:43:27 -0700576func (ctx *TestContext) ModuleForTests(name, variant string) TestingModule {
577 var module Module
578 ctx.VisitAllModules(func(m blueprint.Module) {
579 if ctx.ModuleName(m) == name && ctx.ModuleSubDir(m) == variant {
580 module = m.(Module)
581 }
582 })
583
584 if module == nil {
Jeff Gaston294356f2017-09-27 17:05:30 -0700585 // find all the modules that do exist
Colin Crossbeae6ec2020-08-11 12:02:11 -0700586 var allModuleNames []string
587 var allVariants []string
Jeff Gaston294356f2017-09-27 17:05:30 -0700588 ctx.VisitAllModules(func(m blueprint.Module) {
Colin Crossbeae6ec2020-08-11 12:02:11 -0700589 allModuleNames = append(allModuleNames, ctx.ModuleName(m))
590 if ctx.ModuleName(m) == name {
591 allVariants = append(allVariants, ctx.ModuleSubDir(m))
592 }
Jeff Gaston294356f2017-09-27 17:05:30 -0700593 })
Colin Crossbeae6ec2020-08-11 12:02:11 -0700594 sort.Strings(allVariants)
Jeff Gaston294356f2017-09-27 17:05:30 -0700595
Colin Crossbeae6ec2020-08-11 12:02:11 -0700596 if len(allVariants) == 0 {
597 panic(fmt.Errorf("failed to find module %q. All modules:\n %s",
Martin Stjernholm98e0d882021-09-09 21:34:02 +0100598 name, strings.Join(SortedUniqueStrings(allModuleNames), "\n ")))
Colin Crossbeae6ec2020-08-11 12:02:11 -0700599 } else {
600 panic(fmt.Errorf("failed to find module %q variant %q. All variants:\n %s",
601 name, variant, strings.Join(allVariants, "\n ")))
602 }
Colin Crosscec81712017-07-13 14:43:27 -0700603 }
604
Paul Duffin709e0e32021-03-22 10:09:02 +0000605 return newTestingModule(ctx.config, module)
Colin Crosscec81712017-07-13 14:43:27 -0700606}
607
Jiyong Park37b25202018-07-11 10:49:27 +0900608func (ctx *TestContext) ModuleVariantsForTests(name string) []string {
609 var variants []string
610 ctx.VisitAllModules(func(m blueprint.Module) {
611 if ctx.ModuleName(m) == name {
612 variants = append(variants, ctx.ModuleSubDir(m))
613 }
614 })
615 return variants
616}
617
Colin Cross4c83e5c2019-02-25 14:54:28 -0800618// SingletonForTests returns a TestingSingleton for the singleton registered with the given name.
619func (ctx *TestContext) SingletonForTests(name string) TestingSingleton {
620 allSingletonNames := []string{}
621 for _, s := range ctx.Singletons() {
622 n := ctx.SingletonName(s)
623 if n == name {
624 return TestingSingleton{
Paul Duffin709e0e32021-03-22 10:09:02 +0000625 baseTestingComponent: newBaseTestingComponent(ctx.config, s.(testBuildProvider)),
Paul Duffin31a22882021-03-22 09:29:00 +0000626 singleton: s.(*singletonAdaptor).Singleton,
Colin Cross4c83e5c2019-02-25 14:54:28 -0800627 }
628 }
629 allSingletonNames = append(allSingletonNames, n)
630 }
631
632 panic(fmt.Errorf("failed to find singleton %q."+
633 "\nall singletons: %v", name, allSingletonNames))
634}
635
Martin Stjernholm1ebef5b2022-02-10 23:34:28 +0000636type InstallMakeRule struct {
637 Target string
638 Deps []string
639 OrderOnlyDeps []string
640}
641
642func parseMkRules(t *testing.T, config Config, nodes []mkparser.Node) []InstallMakeRule {
643 var rules []InstallMakeRule
644 for _, node := range nodes {
645 if mkParserRule, ok := node.(*mkparser.Rule); ok {
646 var rule InstallMakeRule
647
648 if targets := mkParserRule.Target.Words(); len(targets) == 0 {
649 t.Fatalf("no targets for rule %s", mkParserRule.Dump())
650 } else if len(targets) > 1 {
651 t.Fatalf("unsupported multiple targets for rule %s", mkParserRule.Dump())
652 } else if !targets[0].Const() {
653 t.Fatalf("unsupported non-const target for rule %s", mkParserRule.Dump())
654 } else {
655 rule.Target = normalizeStringRelativeToTop(config, targets[0].Value(nil))
656 }
657
658 prereqList := &rule.Deps
659 for _, prereq := range mkParserRule.Prerequisites.Words() {
660 if !prereq.Const() {
661 t.Fatalf("unsupported non-const prerequisite for rule %s", mkParserRule.Dump())
662 }
663
664 if prereq.Value(nil) == "|" {
665 prereqList = &rule.OrderOnlyDeps
666 continue
667 }
668
669 *prereqList = append(*prereqList, normalizeStringRelativeToTop(config, prereq.Value(nil)))
670 }
671
672 rules = append(rules, rule)
673 }
674 }
675
676 return rules
677}
678
679func (ctx *TestContext) InstallMakeRulesForTesting(t *testing.T) []InstallMakeRule {
680 installs := ctx.SingletonForTests("makevars").Singleton().(*makeVarsSingleton).installsForTesting
681 buf := bytes.NewBuffer(append([]byte(nil), installs...))
682 parser := mkparser.NewParser("makevars", buf)
683
684 nodes, errs := parser.Parse()
685 if len(errs) > 0 {
686 t.Fatalf("error parsing install rules: %s", errs[0])
687 }
688
689 return parseMkRules(t, ctx.config, nodes)
690}
691
Paul Duffin8eb45732022-10-04 19:03:31 +0100692// MakeVarVariable provides access to make vars that will be written by the makeVarsSingleton
693type MakeVarVariable interface {
694 // Name is the name of the variable.
695 Name() string
696
697 // Value is the value of the variable.
698 Value() string
699}
700
701func (v makeVarsVariable) Name() string {
702 return v.name
703}
704
705func (v makeVarsVariable) Value() string {
706 return v.value
707}
708
709// PrepareForTestAccessingMakeVars sets up the test so that MakeVarsForTesting will work.
710var PrepareForTestAccessingMakeVars = GroupFixturePreparers(
711 PrepareForTestWithAndroidMk,
712 PrepareForTestWithMakevars,
713)
714
715// MakeVarsForTesting returns a filtered list of MakeVarVariable objects that represent the
716// variables that will be written out.
717//
718// It is necessary to use PrepareForTestAccessingMakeVars in tests that want to call this function.
719// Along with any other preparers needed to add the make vars.
720func (ctx *TestContext) MakeVarsForTesting(filter func(variable MakeVarVariable) bool) []MakeVarVariable {
721 vars := ctx.SingletonForTests("makevars").Singleton().(*makeVarsSingleton).varsForTesting
722 result := make([]MakeVarVariable, 0, len(vars))
723 for _, v := range vars {
724 if filter(v) {
725 result = append(result, v)
726 }
727 }
728
729 return result
730}
731
Colin Crossaa255532020-07-03 13:18:24 -0700732func (ctx *TestContext) Config() Config {
733 return ctx.config
734}
735
Colin Cross4c83e5c2019-02-25 14:54:28 -0800736type testBuildProvider interface {
737 BuildParamsForTests() []BuildParams
738 RuleParamsForTests() map[blueprint.Rule]blueprint.RuleParams
739}
740
741type TestingBuildParams struct {
742 BuildParams
743 RuleParams blueprint.RuleParams
Paul Duffin709e0e32021-03-22 10:09:02 +0000744
745 config Config
746}
747
748// RelativeToTop creates a new instance of this which has had any usages of the current test's
749// temporary and test specific build directory replaced with a path relative to the notional top.
750//
751// The parts of this structure which are changed are:
752// * BuildParams
Colin Crossd079e0b2022-08-16 10:27:33 -0700753// - Args
754// - All Path, Paths, WritablePath and WritablePaths fields.
Paul Duffin709e0e32021-03-22 10:09:02 +0000755//
756// * RuleParams
Colin Crossd079e0b2022-08-16 10:27:33 -0700757// - Command
758// - Depfile
759// - Rspfile
760// - RspfileContent
761// - SymlinkOutputs
762// - CommandDeps
763// - CommandOrderOnly
Paul Duffin709e0e32021-03-22 10:09:02 +0000764//
765// See PathRelativeToTop for more details.
Paul Duffina71a67a2021-03-29 00:42:57 +0100766//
767// deprecated: this is no longer needed as TestingBuildParams are created in this form.
Paul Duffin709e0e32021-03-22 10:09:02 +0000768func (p TestingBuildParams) RelativeToTop() TestingBuildParams {
769 // If this is not a valid params then just return it back. That will make it easy to use with the
770 // Maybe...() methods.
771 if p.Rule == nil {
772 return p
773 }
774 if p.config.config == nil {
Paul Duffine8366da2021-03-24 10:40:38 +0000775 return p
Paul Duffin709e0e32021-03-22 10:09:02 +0000776 }
777 // Take a copy of the build params and replace any args that contains test specific temporary
778 // paths with paths relative to the top.
779 bparams := p.BuildParams
Paul Duffinbbb0f8f2021-03-24 10:34:52 +0000780 bparams.Depfile = normalizeWritablePathRelativeToTop(bparams.Depfile)
781 bparams.Output = normalizeWritablePathRelativeToTop(bparams.Output)
782 bparams.Outputs = bparams.Outputs.RelativeToTop()
783 bparams.SymlinkOutput = normalizeWritablePathRelativeToTop(bparams.SymlinkOutput)
784 bparams.SymlinkOutputs = bparams.SymlinkOutputs.RelativeToTop()
785 bparams.ImplicitOutput = normalizeWritablePathRelativeToTop(bparams.ImplicitOutput)
786 bparams.ImplicitOutputs = bparams.ImplicitOutputs.RelativeToTop()
787 bparams.Input = normalizePathRelativeToTop(bparams.Input)
788 bparams.Inputs = bparams.Inputs.RelativeToTop()
789 bparams.Implicit = normalizePathRelativeToTop(bparams.Implicit)
790 bparams.Implicits = bparams.Implicits.RelativeToTop()
791 bparams.OrderOnly = bparams.OrderOnly.RelativeToTop()
792 bparams.Validation = normalizePathRelativeToTop(bparams.Validation)
793 bparams.Validations = bparams.Validations.RelativeToTop()
Paul Duffin709e0e32021-03-22 10:09:02 +0000794 bparams.Args = normalizeStringMapRelativeToTop(p.config, bparams.Args)
795
796 // Ditto for any fields in the RuleParams.
797 rparams := p.RuleParams
798 rparams.Command = normalizeStringRelativeToTop(p.config, rparams.Command)
799 rparams.Depfile = normalizeStringRelativeToTop(p.config, rparams.Depfile)
800 rparams.Rspfile = normalizeStringRelativeToTop(p.config, rparams.Rspfile)
801 rparams.RspfileContent = normalizeStringRelativeToTop(p.config, rparams.RspfileContent)
802 rparams.SymlinkOutputs = normalizeStringArrayRelativeToTop(p.config, rparams.SymlinkOutputs)
803 rparams.CommandDeps = normalizeStringArrayRelativeToTop(p.config, rparams.CommandDeps)
804 rparams.CommandOrderOnly = normalizeStringArrayRelativeToTop(p.config, rparams.CommandOrderOnly)
805
806 return TestingBuildParams{
807 BuildParams: bparams,
808 RuleParams: rparams,
809 }
Colin Cross4c83e5c2019-02-25 14:54:28 -0800810}
811
Paul Duffinbbb0f8f2021-03-24 10:34:52 +0000812func normalizeWritablePathRelativeToTop(path WritablePath) WritablePath {
813 if path == nil {
814 return nil
815 }
816 return path.RelativeToTop().(WritablePath)
817}
818
819func normalizePathRelativeToTop(path Path) Path {
820 if path == nil {
821 return nil
822 }
823 return path.RelativeToTop()
824}
825
Jiakai Zhangcf61e3c2023-05-08 16:28:38 +0000826func allOutputs(p BuildParams) []string {
827 outputs := append(WritablePaths(nil), p.Outputs...)
828 outputs = append(outputs, p.ImplicitOutputs...)
829 if p.Output != nil {
830 outputs = append(outputs, p.Output)
831 }
832 return outputs.Strings()
833}
834
835// AllOutputs returns all 'BuildParams.Output's and 'BuildParams.Outputs's in their full path string forms.
836func (p TestingBuildParams) AllOutputs() []string {
837 return allOutputs(p.BuildParams)
838}
839
Paul Duffin0eda26b92021-03-22 09:34:29 +0000840// baseTestingComponent provides functionality common to both TestingModule and TestingSingleton.
841type baseTestingComponent struct {
Paul Duffin709e0e32021-03-22 10:09:02 +0000842 config Config
Paul Duffin0eda26b92021-03-22 09:34:29 +0000843 provider testBuildProvider
844}
845
Paul Duffin709e0e32021-03-22 10:09:02 +0000846func newBaseTestingComponent(config Config, provider testBuildProvider) baseTestingComponent {
847 return baseTestingComponent{config, provider}
848}
849
850// A function that will normalize a string containing paths, e.g. ninja command, by replacing
851// any references to the test specific temporary build directory that changes with each run to a
852// fixed path relative to a notional top directory.
853//
854// This is similar to StringPathRelativeToTop except that assumes the string is a single path
855// containing at most one instance of the temporary build directory at the start of the path while
856// this assumes that there can be any number at any position.
857func normalizeStringRelativeToTop(config Config, s string) string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200858 // The soongOutDir usually looks something like: /tmp/testFoo2345/001
Paul Duffin709e0e32021-03-22 10:09:02 +0000859 //
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200860 // Replace any usage of the soongOutDir with out/soong, e.g. replace "/tmp/testFoo2345/001" with
Paul Duffin709e0e32021-03-22 10:09:02 +0000861 // "out/soong".
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200862 outSoongDir := filepath.Clean(config.soongOutDir)
Paul Duffin709e0e32021-03-22 10:09:02 +0000863 re := regexp.MustCompile(`\Q` + outSoongDir + `\E\b`)
864 s = re.ReplaceAllString(s, "out/soong")
865
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200866 // Replace any usage of the soongOutDir/.. with out, e.g. replace "/tmp/testFoo2345" with
Paul Duffin709e0e32021-03-22 10:09:02 +0000867 // "out". This must come after the previous replacement otherwise this would replace
868 // "/tmp/testFoo2345/001" with "out/001" instead of "out/soong".
869 outDir := filepath.Dir(outSoongDir)
870 re = regexp.MustCompile(`\Q` + outDir + `\E\b`)
871 s = re.ReplaceAllString(s, "out")
872
873 return s
874}
875
876// normalizeStringArrayRelativeToTop creates a new slice constructed by applying
877// normalizeStringRelativeToTop to each item in the slice.
878func normalizeStringArrayRelativeToTop(config Config, slice []string) []string {
879 newSlice := make([]string, len(slice))
880 for i, s := range slice {
881 newSlice[i] = normalizeStringRelativeToTop(config, s)
882 }
883 return newSlice
884}
885
886// normalizeStringMapRelativeToTop creates a new map constructed by applying
887// normalizeStringRelativeToTop to each value in the map.
888func normalizeStringMapRelativeToTop(config Config, m map[string]string) map[string]string {
889 newMap := map[string]string{}
890 for k, v := range m {
891 newMap[k] = normalizeStringRelativeToTop(config, v)
892 }
893 return newMap
Paul Duffin0eda26b92021-03-22 09:34:29 +0000894}
895
896func (b baseTestingComponent) newTestingBuildParams(bparams BuildParams) TestingBuildParams {
Colin Cross4c83e5c2019-02-25 14:54:28 -0800897 return TestingBuildParams{
Paul Duffin709e0e32021-03-22 10:09:02 +0000898 config: b.config,
Colin Cross4c83e5c2019-02-25 14:54:28 -0800899 BuildParams: bparams,
Paul Duffin0eda26b92021-03-22 09:34:29 +0000900 RuleParams: b.provider.RuleParamsForTests()[bparams.Rule],
Paul Duffine8366da2021-03-24 10:40:38 +0000901 }.RelativeToTop()
Colin Cross4c83e5c2019-02-25 14:54:28 -0800902}
903
Paul Duffin0eda26b92021-03-22 09:34:29 +0000904func (b baseTestingComponent) maybeBuildParamsFromRule(rule string) (TestingBuildParams, []string) {
Thiébaud Weksteen3600b802020-08-27 15:50:24 +0200905 var searchedRules []string
Paul Duffin4dbf6cf2021-06-08 10:06:37 +0100906 buildParams := b.provider.BuildParamsForTests()
907 for _, p := range buildParams {
908 ruleAsString := p.Rule.String()
909 searchedRules = append(searchedRules, ruleAsString)
910 if strings.Contains(ruleAsString, rule) {
Paul Duffin0eda26b92021-03-22 09:34:29 +0000911 return b.newTestingBuildParams(p), searchedRules
Colin Cross4c83e5c2019-02-25 14:54:28 -0800912 }
913 }
Thiébaud Weksteen3600b802020-08-27 15:50:24 +0200914 return TestingBuildParams{}, searchedRules
Colin Cross4c83e5c2019-02-25 14:54:28 -0800915}
916
Paul Duffin0eda26b92021-03-22 09:34:29 +0000917func (b baseTestingComponent) buildParamsFromRule(rule string) TestingBuildParams {
918 p, searchRules := b.maybeBuildParamsFromRule(rule)
Colin Cross4c83e5c2019-02-25 14:54:28 -0800919 if p.Rule == nil {
Paul Duffin4dbf6cf2021-06-08 10:06:37 +0100920 panic(fmt.Errorf("couldn't find rule %q.\nall rules:\n%s", rule, strings.Join(searchRules, "\n")))
Colin Cross4c83e5c2019-02-25 14:54:28 -0800921 }
922 return p
923}
924
Martin Stjernholm827ba622022-02-03 00:20:11 +0000925func (b baseTestingComponent) maybeBuildParamsFromDescription(desc string) (TestingBuildParams, []string) {
926 var searchedDescriptions []string
Paul Duffin0eda26b92021-03-22 09:34:29 +0000927 for _, p := range b.provider.BuildParamsForTests() {
Martin Stjernholm827ba622022-02-03 00:20:11 +0000928 searchedDescriptions = append(searchedDescriptions, p.Description)
Colin Crossb88b3c52019-06-10 15:15:17 -0700929 if strings.Contains(p.Description, desc) {
Martin Stjernholm827ba622022-02-03 00:20:11 +0000930 return b.newTestingBuildParams(p), searchedDescriptions
Colin Cross4c83e5c2019-02-25 14:54:28 -0800931 }
932 }
Martin Stjernholm827ba622022-02-03 00:20:11 +0000933 return TestingBuildParams{}, searchedDescriptions
Colin Cross4c83e5c2019-02-25 14:54:28 -0800934}
935
Paul Duffin0eda26b92021-03-22 09:34:29 +0000936func (b baseTestingComponent) buildParamsFromDescription(desc string) TestingBuildParams {
Martin Stjernholm827ba622022-02-03 00:20:11 +0000937 p, searchedDescriptions := b.maybeBuildParamsFromDescription(desc)
Colin Cross4c83e5c2019-02-25 14:54:28 -0800938 if p.Rule == nil {
Martin Stjernholm827ba622022-02-03 00:20:11 +0000939 panic(fmt.Errorf("couldn't find description %q\nall descriptions:\n%s", desc, strings.Join(searchedDescriptions, "\n")))
Colin Cross4c83e5c2019-02-25 14:54:28 -0800940 }
941 return p
942}
943
Paul Duffin0eda26b92021-03-22 09:34:29 +0000944func (b baseTestingComponent) maybeBuildParamsFromOutput(file string) (TestingBuildParams, []string) {
Martin Stjernholma4aaa472021-09-17 02:51:48 +0100945 searchedOutputs := WritablePaths(nil)
Paul Duffin0eda26b92021-03-22 09:34:29 +0000946 for _, p := range b.provider.BuildParamsForTests() {
Colin Cross4c83e5c2019-02-25 14:54:28 -0800947 outputs := append(WritablePaths(nil), p.Outputs...)
Colin Cross1d2cf042019-03-29 15:33:06 -0700948 outputs = append(outputs, p.ImplicitOutputs...)
Colin Cross4c83e5c2019-02-25 14:54:28 -0800949 if p.Output != nil {
950 outputs = append(outputs, p.Output)
951 }
952 for _, f := range outputs {
Paul Duffin4e6e35c2021-03-22 11:34:57 +0000953 if f.String() == file || f.Rel() == file || PathRelativeToTop(f) == file {
Paul Duffin0eda26b92021-03-22 09:34:29 +0000954 return b.newTestingBuildParams(p), nil
Colin Cross4c83e5c2019-02-25 14:54:28 -0800955 }
Martin Stjernholma4aaa472021-09-17 02:51:48 +0100956 searchedOutputs = append(searchedOutputs, f)
Colin Cross4c83e5c2019-02-25 14:54:28 -0800957 }
958 }
Martin Stjernholma4aaa472021-09-17 02:51:48 +0100959
960 formattedOutputs := []string{}
961 for _, f := range searchedOutputs {
962 formattedOutputs = append(formattedOutputs,
963 fmt.Sprintf("%s (rel=%s)", PathRelativeToTop(f), f.Rel()))
964 }
965
966 return TestingBuildParams{}, formattedOutputs
Colin Cross4c83e5c2019-02-25 14:54:28 -0800967}
968
Paul Duffin0eda26b92021-03-22 09:34:29 +0000969func (b baseTestingComponent) buildParamsFromOutput(file string) TestingBuildParams {
970 p, searchedOutputs := b.maybeBuildParamsFromOutput(file)
Colin Cross4c83e5c2019-02-25 14:54:28 -0800971 if p.Rule == nil {
Paul Duffin4e6e35c2021-03-22 11:34:57 +0000972 panic(fmt.Errorf("couldn't find output %q.\nall outputs:\n %s\n",
973 file, strings.Join(searchedOutputs, "\n ")))
Colin Cross4c83e5c2019-02-25 14:54:28 -0800974 }
975 return p
976}
977
Paul Duffin0eda26b92021-03-22 09:34:29 +0000978func (b baseTestingComponent) allOutputs() []string {
Colin Cross4c83e5c2019-02-25 14:54:28 -0800979 var outputFullPaths []string
Paul Duffin0eda26b92021-03-22 09:34:29 +0000980 for _, p := range b.provider.BuildParamsForTests() {
Jiakai Zhangcf61e3c2023-05-08 16:28:38 +0000981 outputFullPaths = append(outputFullPaths, allOutputs(p)...)
Colin Cross4c83e5c2019-02-25 14:54:28 -0800982 }
983 return outputFullPaths
984}
985
Paul Duffin31a22882021-03-22 09:29:00 +0000986// MaybeRule finds a call to ctx.Build with BuildParams.Rule set to a rule with the given name. Returns an empty
987// BuildParams if no rule is found.
988func (b baseTestingComponent) MaybeRule(rule string) TestingBuildParams {
Paul Duffin0eda26b92021-03-22 09:34:29 +0000989 r, _ := b.maybeBuildParamsFromRule(rule)
Paul Duffin31a22882021-03-22 09:29:00 +0000990 return r
991}
992
993// Rule finds a call to ctx.Build with BuildParams.Rule set to a rule with the given name. Panics if no rule is found.
994func (b baseTestingComponent) Rule(rule string) TestingBuildParams {
Paul Duffin0eda26b92021-03-22 09:34:29 +0000995 return b.buildParamsFromRule(rule)
Paul Duffin31a22882021-03-22 09:29:00 +0000996}
997
998// MaybeDescription finds a call to ctx.Build with BuildParams.Description set to a the given string. Returns an empty
999// BuildParams if no rule is found.
1000func (b baseTestingComponent) MaybeDescription(desc string) TestingBuildParams {
Martin Stjernholm827ba622022-02-03 00:20:11 +00001001 p, _ := b.maybeBuildParamsFromDescription(desc)
1002 return p
Paul Duffin31a22882021-03-22 09:29:00 +00001003}
1004
1005// Description finds a call to ctx.Build with BuildParams.Description set to a the given string. Panics if no rule is
1006// found.
1007func (b baseTestingComponent) Description(desc string) TestingBuildParams {
Paul Duffin0eda26b92021-03-22 09:34:29 +00001008 return b.buildParamsFromDescription(desc)
Paul Duffin31a22882021-03-22 09:29:00 +00001009}
1010
1011// MaybeOutput finds a call to ctx.Build with a BuildParams.Output or BuildParams.Outputs whose String() or Rel()
1012// value matches the provided string. Returns an empty BuildParams if no rule is found.
1013func (b baseTestingComponent) MaybeOutput(file string) TestingBuildParams {
Paul Duffin0eda26b92021-03-22 09:34:29 +00001014 p, _ := b.maybeBuildParamsFromOutput(file)
Paul Duffin31a22882021-03-22 09:29:00 +00001015 return p
1016}
1017
1018// Output finds a call to ctx.Build with a BuildParams.Output or BuildParams.Outputs whose String() or Rel()
1019// value matches the provided string. Panics if no rule is found.
1020func (b baseTestingComponent) Output(file string) TestingBuildParams {
Paul Duffin0eda26b92021-03-22 09:34:29 +00001021 return b.buildParamsFromOutput(file)
Paul Duffin31a22882021-03-22 09:29:00 +00001022}
1023
1024// AllOutputs returns all 'BuildParams.Output's and 'BuildParams.Outputs's in their full path string forms.
1025func (b baseTestingComponent) AllOutputs() []string {
Paul Duffin0eda26b92021-03-22 09:34:29 +00001026 return b.allOutputs()
Paul Duffin31a22882021-03-22 09:29:00 +00001027}
1028
Colin Crossb77ffc42019-01-05 22:09:19 -08001029// TestingModule is wrapper around an android.Module that provides methods to find information about individual
1030// ctx.Build parameters for verification in tests.
Colin Crosscec81712017-07-13 14:43:27 -07001031type TestingModule struct {
Paul Duffin31a22882021-03-22 09:29:00 +00001032 baseTestingComponent
Colin Crosscec81712017-07-13 14:43:27 -07001033 module Module
1034}
1035
Paul Duffin709e0e32021-03-22 10:09:02 +00001036func newTestingModule(config Config, module Module) TestingModule {
Paul Duffin31a22882021-03-22 09:29:00 +00001037 return TestingModule{
Paul Duffin709e0e32021-03-22 10:09:02 +00001038 newBaseTestingComponent(config, module),
Paul Duffin31a22882021-03-22 09:29:00 +00001039 module,
1040 }
1041}
1042
Colin Crossb77ffc42019-01-05 22:09:19 -08001043// Module returns the Module wrapped by the TestingModule.
Colin Crosscec81712017-07-13 14:43:27 -07001044func (m TestingModule) Module() Module {
1045 return m.module
1046}
1047
Paul Duffin97d8b402021-03-22 16:04:50 +00001048// VariablesForTestsRelativeToTop returns a copy of the Module.VariablesForTests() with every value
1049// having any temporary build dir usages replaced with paths relative to a notional top.
1050func (m TestingModule) VariablesForTestsRelativeToTop() map[string]string {
1051 return normalizeStringMapRelativeToTop(m.config, m.module.VariablesForTests())
1052}
1053
Paul Duffin962783a2021-03-29 00:00:17 +01001054// OutputFiles calls OutputFileProducer.OutputFiles on the encapsulated module, exits the test
1055// immediately if there is an error and otherwise returns the result of calling Paths.RelativeToTop
1056// on the returned Paths.
1057func (m TestingModule) OutputFiles(t *testing.T, tag string) Paths {
1058 producer, ok := m.module.(OutputFileProducer)
1059 if !ok {
1060 t.Fatalf("%q must implement OutputFileProducer\n", m.module.Name())
1061 }
1062 paths, err := producer.OutputFiles(tag)
1063 if err != nil {
1064 t.Fatal(err)
1065 }
1066
1067 return paths.RelativeToTop()
1068}
1069
Colin Cross4c83e5c2019-02-25 14:54:28 -08001070// TestingSingleton is wrapper around an android.Singleton that provides methods to find information about individual
1071// ctx.Build parameters for verification in tests.
1072type TestingSingleton struct {
Paul Duffin31a22882021-03-22 09:29:00 +00001073 baseTestingComponent
Colin Cross4c83e5c2019-02-25 14:54:28 -08001074 singleton Singleton
Colin Cross4c83e5c2019-02-25 14:54:28 -08001075}
1076
1077// Singleton returns the Singleton wrapped by the TestingSingleton.
1078func (s TestingSingleton) Singleton() Singleton {
1079 return s.singleton
1080}
1081
Logan Chien42039712018-03-12 16:29:17 +08001082func FailIfErrored(t *testing.T, errs []error) {
1083 t.Helper()
1084 if len(errs) > 0 {
1085 for _, err := range errs {
1086 t.Error(err)
1087 }
1088 t.FailNow()
1089 }
1090}
Logan Chienee97c3e2018-03-12 16:34:26 +08001091
Paul Duffinea8a3862021-03-04 17:58:33 +00001092// Fail if no errors that matched the regular expression were found.
1093//
1094// Returns true if a matching error was found, false otherwise.
1095func FailIfNoMatchingErrors(t *testing.T, pattern string, errs []error) bool {
Logan Chienee97c3e2018-03-12 16:34:26 +08001096 t.Helper()
1097
1098 matcher, err := regexp.Compile(pattern)
1099 if err != nil {
Paul Duffinea8a3862021-03-04 17:58:33 +00001100 t.Fatalf("failed to compile regular expression %q because %s", pattern, err)
Logan Chienee97c3e2018-03-12 16:34:26 +08001101 }
1102
1103 found := false
1104 for _, err := range errs {
1105 if matcher.FindStringIndex(err.Error()) != nil {
1106 found = true
1107 break
1108 }
1109 }
1110 if !found {
Steven Moreland082e2062022-08-30 01:11:11 +00001111 t.Errorf("could not match the expected error regex %q (checked %d error(s))", pattern, len(errs))
Logan Chienee97c3e2018-03-12 16:34:26 +08001112 for i, err := range errs {
Colin Crossaede88c2020-08-11 12:17:01 -07001113 t.Errorf("errs[%d] = %q", i, err)
Logan Chienee97c3e2018-03-12 16:34:26 +08001114 }
1115 }
Paul Duffinea8a3862021-03-04 17:58:33 +00001116
1117 return found
Logan Chienee97c3e2018-03-12 16:34:26 +08001118}
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -07001119
Paul Duffin91e38192019-08-05 15:07:57 +01001120func CheckErrorsAgainstExpectations(t *testing.T, errs []error, expectedErrorPatterns []string) {
1121 t.Helper()
1122
1123 if expectedErrorPatterns == nil {
1124 FailIfErrored(t, errs)
1125 } else {
1126 for _, expectedError := range expectedErrorPatterns {
1127 FailIfNoMatchingErrors(t, expectedError, errs)
1128 }
1129 if len(errs) > len(expectedErrorPatterns) {
1130 t.Errorf("additional errors found, expected %d, found %d",
1131 len(expectedErrorPatterns), len(errs))
1132 for i, expectedError := range expectedErrorPatterns {
1133 t.Errorf("expectedErrors[%d] = %s", i, expectedError)
1134 }
1135 for i, err := range errs {
1136 t.Errorf("errs[%d] = %s", i, err)
1137 }
Paul Duffinea8a3862021-03-04 17:58:33 +00001138 t.FailNow()
Paul Duffin91e38192019-08-05 15:07:57 +01001139 }
1140 }
Paul Duffin91e38192019-08-05 15:07:57 +01001141}
1142
Jingwen Chencda22c92020-11-23 00:22:30 -05001143func SetKatiEnabledForTests(config Config) {
1144 config.katiEnabled = true
Paul Duffin8c3fec42020-03-04 20:15:08 +00001145}
1146
Dennis Shend4f5d932023-01-31 20:27:21 +00001147func SetTrimmedApexEnabledForTests(config Config) {
1148 config.productVariables.TrimmedApex = new(bool)
1149 *config.productVariables.TrimmedApex = true
1150}
1151
Colin Crossaa255532020-07-03 13:18:24 -07001152func AndroidMkEntriesForTest(t *testing.T, ctx *TestContext, mod blueprint.Module) []AndroidMkEntries {
Liz Kammer6be69062022-11-04 16:06:02 -04001153 t.Helper()
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -07001154 var p AndroidMkEntriesProvider
1155 var ok bool
1156 if p, ok = mod.(AndroidMkEntriesProvider); !ok {
Roland Levillaindfe75b32019-07-23 16:53:32 +01001157 t.Errorf("module does not implement AndroidMkEntriesProvider: " + mod.Name())
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -07001158 }
Jiyong Park0b0e1b92019-12-03 13:24:29 +09001159
1160 entriesList := p.AndroidMkEntries()
1161 for i, _ := range entriesList {
Colin Crossaa255532020-07-03 13:18:24 -07001162 entriesList[i].fillInEntries(ctx, mod)
Jiyong Park0b0e1b92019-12-03 13:24:29 +09001163 }
1164 return entriesList
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -07001165}
Jooyung Han12df5fb2019-07-11 16:18:47 +09001166
Colin Crossaa255532020-07-03 13:18:24 -07001167func AndroidMkDataForTest(t *testing.T, ctx *TestContext, mod blueprint.Module) AndroidMkData {
Liz Kammer6be69062022-11-04 16:06:02 -04001168 t.Helper()
Jooyung Han12df5fb2019-07-11 16:18:47 +09001169 var p AndroidMkDataProvider
1170 var ok bool
1171 if p, ok = mod.(AndroidMkDataProvider); !ok {
Sam Delmerico4e115cc2023-01-19 15:36:52 -05001172 t.Fatalf("module does not implement AndroidMkDataProvider: " + mod.Name())
Jooyung Han12df5fb2019-07-11 16:18:47 +09001173 }
1174 data := p.AndroidMk()
Colin Crossaa255532020-07-03 13:18:24 -07001175 data.fillInData(ctx, mod)
Jooyung Han12df5fb2019-07-11 16:18:47 +09001176 return data
1177}
Paul Duffin9b478b02019-12-10 13:41:51 +00001178
1179// Normalize the path for testing.
1180//
1181// If the path is relative to the build directory then return the relative path
1182// to avoid tests having to deal with the dynamically generated build directory.
1183//
1184// Otherwise, return the supplied path as it is almost certainly a source path
1185// that is relative to the root of the source tree.
1186//
1187// The build and source paths should be distinguishable based on their contents.
Paul Duffin567465d2021-03-16 01:21:34 +00001188//
1189// deprecated: use PathRelativeToTop instead as it handles make install paths and differentiates
1190// between output and source properly.
Paul Duffin9b478b02019-12-10 13:41:51 +00001191func NormalizePathForTesting(path Path) string {
Paul Duffin064b70c2020-11-02 17:32:38 +00001192 if path == nil {
1193 return "<nil path>"
1194 }
Paul Duffin9b478b02019-12-10 13:41:51 +00001195 p := path.String()
1196 if w, ok := path.(WritablePath); ok {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001197 rel, err := filepath.Rel(w.getSoongOutDir(), p)
Paul Duffin9b478b02019-12-10 13:41:51 +00001198 if err != nil {
1199 panic(err)
1200 }
1201 return rel
1202 }
1203 return p
1204}
1205
Paul Duffin567465d2021-03-16 01:21:34 +00001206// NormalizePathsForTesting creates a slice of strings where each string is the result of applying
1207// NormalizePathForTesting to the corresponding Path in the input slice.
1208//
1209// deprecated: use PathsRelativeToTop instead as it handles make install paths and differentiates
1210// between output and source properly.
Paul Duffin9b478b02019-12-10 13:41:51 +00001211func NormalizePathsForTesting(paths Paths) []string {
1212 var result []string
1213 for _, path := range paths {
1214 relative := NormalizePathForTesting(path)
1215 result = append(result, relative)
1216 }
1217 return result
1218}
Paul Duffin567465d2021-03-16 01:21:34 +00001219
1220// PathRelativeToTop returns a string representation of the path relative to a notional top
1221// directory.
1222//
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001223// It return "<nil path>" if the supplied path is nil, otherwise it returns the result of calling
1224// Path.RelativeToTop to obtain a relative Path and then calling Path.String on that to get the
1225// string representation.
Paul Duffin567465d2021-03-16 01:21:34 +00001226func PathRelativeToTop(path Path) string {
1227 if path == nil {
1228 return "<nil path>"
1229 }
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001230 return path.RelativeToTop().String()
Paul Duffin567465d2021-03-16 01:21:34 +00001231}
1232
1233// PathsRelativeToTop creates a slice of strings where each string is the result of applying
1234// PathRelativeToTop to the corresponding Path in the input slice.
1235func PathsRelativeToTop(paths Paths) []string {
1236 var result []string
1237 for _, path := range paths {
1238 relative := PathRelativeToTop(path)
1239 result = append(result, relative)
1240 }
1241 return result
1242}
1243
1244// StringPathRelativeToTop returns a string representation of the path relative to a notional top
1245// directory.
1246//
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001247// See Path.RelativeToTop for more details as to what `relative to top` means.
Paul Duffin567465d2021-03-16 01:21:34 +00001248//
1249// This is provided for processing paths that have already been converted into a string, e.g. paths
1250// in AndroidMkEntries structures. As a result it needs to be supplied the soong output dir against
1251// which it can try and relativize paths. PathRelativeToTop must be used for process Path objects.
1252func StringPathRelativeToTop(soongOutDir string, path string) string {
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001253 ensureTestOnly()
Paul Duffin567465d2021-03-16 01:21:34 +00001254
1255 // A relative path must be a source path so leave it as it is.
1256 if !filepath.IsAbs(path) {
1257 return path
1258 }
1259
1260 // Check to see if the path is relative to the soong out dir.
1261 rel, isRel, err := maybeRelErr(soongOutDir, path)
1262 if err != nil {
1263 panic(err)
1264 }
1265
1266 if isRel {
1267 // The path is in the soong out dir so indicate that in the relative path.
1268 return filepath.Join("out/soong", rel)
1269 }
1270
1271 // Check to see if the path is relative to the top level out dir.
1272 outDir := filepath.Dir(soongOutDir)
1273 rel, isRel, err = maybeRelErr(outDir, path)
1274 if err != nil {
1275 panic(err)
1276 }
1277
1278 if isRel {
1279 // The path is in the out dir so indicate that in the relative path.
1280 return filepath.Join("out", rel)
1281 }
1282
1283 // This should never happen.
1284 panic(fmt.Errorf("internal error: absolute path %s is not relative to the out dir %s", path, outDir))
1285}
1286
1287// StringPathsRelativeToTop creates a slice of strings where each string is the result of applying
1288// StringPathRelativeToTop to the corresponding string path in the input slice.
1289//
1290// This is provided for processing paths that have already been converted into a string, e.g. paths
1291// in AndroidMkEntries structures. As a result it needs to be supplied the soong output dir against
1292// which it can try and relativize paths. PathsRelativeToTop must be used for process Paths objects.
1293func StringPathsRelativeToTop(soongOutDir string, paths []string) []string {
1294 var result []string
1295 for _, path := range paths {
1296 relative := StringPathRelativeToTop(soongOutDir, path)
1297 result = append(result, relative)
1298 }
1299 return result
1300}
Paul Duffinf53555d2021-03-29 00:21:00 +01001301
1302// StringRelativeToTop will normalize a string containing paths, e.g. ninja command, by replacing
1303// any references to the test specific temporary build directory that changes with each run to a
1304// fixed path relative to a notional top directory.
1305//
1306// This is similar to StringPathRelativeToTop except that assumes the string is a single path
1307// containing at most one instance of the temporary build directory at the start of the path while
1308// this assumes that there can be any number at any position.
1309func StringRelativeToTop(config Config, command string) string {
1310 return normalizeStringRelativeToTop(config, command)
1311}
Paul Duffin0aafcbf2021-03-29 00:56:32 +01001312
1313// StringsRelativeToTop will return a new slice such that each item in the new slice is the result
1314// of calling StringRelativeToTop on the corresponding item in the input slice.
1315func StringsRelativeToTop(config Config, command []string) []string {
1316 return normalizeStringArrayRelativeToTop(config, command)
1317}