blob: 2992678316a6007ecd7c00ef29d773d7e6cf2ad5 [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 (
18 "fmt"
Paul Duffin9b478b02019-12-10 13:41:51 +000019 "path/filepath"
Logan Chienee97c3e2018-03-12 16:34:26 +080020 "regexp"
Martin Stjernholm4c021242020-05-13 01:13:50 +010021 "sort"
Colin Crosscec81712017-07-13 14:43:27 -070022 "strings"
Paul Duffin281deb22021-03-06 20:29:19 +000023 "sync"
Logan Chien42039712018-03-12 16:29:17 +080024 "testing"
Colin Crosscec81712017-07-13 14:43:27 -070025
26 "github.com/google/blueprint"
27)
28
Colin Crossae8600b2020-10-29 17:09:13 -070029func NewTestContext(config Config) *TestContext {
Jeff Gaston088e29e2017-11-29 16:47:17 -080030 namespaceExportFilter := func(namespace *Namespace) bool {
31 return true
32 }
Jeff Gastonb274ed32017-12-01 17:10:33 -080033
34 nameResolver := NewNameResolver(namespaceExportFilter)
35 ctx := &TestContext{
Colin Crossae8600b2020-10-29 17:09:13 -070036 Context: &Context{blueprint.NewContext(), config},
Jeff Gastonb274ed32017-12-01 17:10:33 -080037 NameResolver: nameResolver,
38 }
39
40 ctx.SetNameInterface(nameResolver)
Jeff Gaston088e29e2017-11-29 16:47:17 -080041
Colin Cross1b488422019-03-04 22:33:56 -080042 ctx.postDeps = append(ctx.postDeps, registerPathDepsMutator)
43
Colin Crossae8600b2020-10-29 17:09:13 -070044 ctx.SetFs(ctx.config.fs)
45 if ctx.config.mockBpList != "" {
46 ctx.SetModuleListFile(ctx.config.mockBpList)
47 }
48
Jeff Gaston088e29e2017-11-29 16:47:17 -080049 return ctx
Colin Crosscec81712017-07-13 14:43:27 -070050}
51
Paul Duffina560d5a2021-02-28 01:38:51 +000052var PrepareForTestWithArchMutator = GroupFixturePreparers(
Paul Duffin35816122021-02-24 01:49:52 +000053 // Configure architecture targets in the fixture config.
54 FixtureModifyConfig(modifyTestConfigToSupportArchMutator),
55
56 // Add the arch mutator to the context.
57 FixtureRegisterWithContext(func(ctx RegistrationContext) {
58 ctx.PreDepsMutators(registerArchMutator)
59 }),
60)
61
62var PrepareForTestWithDefaults = FixtureRegisterWithContext(func(ctx RegistrationContext) {
63 ctx.PreArchMutators(RegisterDefaultsPreArchMutators)
64})
65
66var PrepareForTestWithComponentsMutator = FixtureRegisterWithContext(func(ctx RegistrationContext) {
67 ctx.PreArchMutators(RegisterComponentsMutator)
68})
69
70var PrepareForTestWithPrebuilts = FixtureRegisterWithContext(RegisterPrebuiltMutators)
71
72var PrepareForTestWithOverrides = FixtureRegisterWithContext(func(ctx RegistrationContext) {
73 ctx.PostDepsMutators(RegisterOverridePostDepsMutators)
74})
75
76// Prepares an integration test with build components from the android package.
Paul Duffina560d5a2021-02-28 01:38:51 +000077var PrepareForIntegrationTestWithAndroid = GroupFixturePreparers(
Paul Duffin530483c2021-03-07 13:20:38 +000078 // Sorted alphabetically as the actual order does not matter as tests automatically enforce the
79 // correct order.
Paul Duffin35816122021-02-24 01:49:52 +000080 PrepareForTestWithArchMutator,
Paul Duffin35816122021-02-24 01:49:52 +000081 PrepareForTestWithComponentsMutator,
Paul Duffin530483c2021-03-07 13:20:38 +000082 PrepareForTestWithDefaults,
Paul Duffin35816122021-02-24 01:49:52 +000083 PrepareForTestWithFilegroup,
Paul Duffin530483c2021-03-07 13:20:38 +000084 PrepareForTestWithOverrides,
85 PrepareForTestWithPackageModule,
86 PrepareForTestWithPrebuilts,
87 PrepareForTestWithVisibility,
Paul Duffin35816122021-02-24 01:49:52 +000088)
89
Colin Crossae8600b2020-10-29 17:09:13 -070090func NewTestArchContext(config Config) *TestContext {
91 ctx := NewTestContext(config)
Colin Crossae4c6182017-09-15 17:33:55 -070092 ctx.preDeps = append(ctx.preDeps, registerArchMutator)
93 return ctx
94}
95
Colin Crosscec81712017-07-13 14:43:27 -070096type TestContext struct {
Colin Cross4c83e5c2019-02-25 14:54:28 -080097 *Context
Liz Kammer356f7d42021-01-26 09:18:53 -050098 preArch, preDeps, postDeps, finalDeps []RegisterMutatorFunc
99 bp2buildPreArch, bp2buildDeps, bp2buildMutators []RegisterMutatorFunc
100 NameResolver *NameResolver
Paul Duffin281deb22021-03-06 20:29:19 +0000101
Paul Duffind182fb32021-03-07 12:24:44 +0000102 // The list of pre-singletons and singletons registered for the test.
103 preSingletons, singletons sortableComponents
104
Paul Duffin41d77c72021-03-07 12:23:48 +0000105 // The order in which the pre-singletons, mutators and singletons will be run in this test
106 // context; for debugging.
107 preSingletonOrder, mutatorOrder, singletonOrder []string
Colin Crosscec81712017-07-13 14:43:27 -0700108}
109
110func (ctx *TestContext) PreArchMutators(f RegisterMutatorFunc) {
111 ctx.preArch = append(ctx.preArch, f)
112}
113
Paul Duffina80ef842020-01-14 12:09:36 +0000114func (ctx *TestContext) HardCodedPreArchMutators(f RegisterMutatorFunc) {
115 // Register mutator function as normal for testing.
116 ctx.PreArchMutators(f)
117}
118
Colin Crosscec81712017-07-13 14:43:27 -0700119func (ctx *TestContext) PreDepsMutators(f RegisterMutatorFunc) {
120 ctx.preDeps = append(ctx.preDeps, f)
121}
122
123func (ctx *TestContext) PostDepsMutators(f RegisterMutatorFunc) {
124 ctx.postDeps = append(ctx.postDeps, f)
125}
126
Martin Stjernholm710ec3a2020-01-16 15:12:04 +0000127func (ctx *TestContext) FinalDepsMutators(f RegisterMutatorFunc) {
128 ctx.finalDeps = append(ctx.finalDeps, f)
129}
130
Jingwen Chen73850672020-12-14 08:25:34 -0500131// RegisterBp2BuildMutator registers a BazelTargetModule mutator for converting a module
132// type to the equivalent Bazel target.
133func (ctx *TestContext) RegisterBp2BuildMutator(moduleType string, m func(TopDownMutatorContext)) {
Jingwen Chen73850672020-12-14 08:25:34 -0500134 f := func(ctx RegisterMutatorsContext) {
Liz Kammer356f7d42021-01-26 09:18:53 -0500135 ctx.TopDown(moduleType, m)
Jingwen Chen73850672020-12-14 08:25:34 -0500136 }
Jingwen Chena42d6412021-01-26 21:57:27 -0500137 ctx.bp2buildMutators = append(ctx.bp2buildMutators, f)
Jingwen Chen73850672020-12-14 08:25:34 -0500138}
139
Liz Kammer356f7d42021-01-26 09:18:53 -0500140// PreArchBp2BuildMutators adds mutators to be register for converting Android Blueprint modules
141// into Bazel BUILD targets that should run prior to deps and conversion.
142func (ctx *TestContext) PreArchBp2BuildMutators(f RegisterMutatorFunc) {
143 ctx.bp2buildPreArch = append(ctx.bp2buildPreArch, f)
144}
145
146// DepsBp2BuildMutators adds mutators to be register for converting Android Blueprint modules into
147// Bazel BUILD targets that should run prior to conversion to resolve dependencies.
148func (ctx *TestContext) DepsBp2BuildMutators(f RegisterMutatorFunc) {
149 ctx.bp2buildDeps = append(ctx.bp2buildDeps, f)
150}
151
Paul Duffin281deb22021-03-06 20:29:19 +0000152// registeredComponentOrder defines the order in which a sortableComponent type is registered at
153// runtime and provides support for reordering the components registered for a test in the same
154// way.
155type registeredComponentOrder struct {
156 // The name of the component type, used for error messages.
157 componentType string
158
159 // The names of the registered components in the order in which they were registered.
160 namesInOrder []string
161
162 // Maps from the component name to its position in the runtime ordering.
163 namesToIndex map[string]int
164
165 // A function that defines the order between two named components that can be used to sort a slice
166 // of component names into the same order as they appear in namesInOrder.
167 less func(string, string) bool
168}
169
170// registeredComponentOrderFromExistingOrder takes an existing slice of sortableComponents and
171// creates a registeredComponentOrder that contains a less function that can be used to sort a
172// subset of that list of names so it is in the same order as the original sortableComponents.
173func registeredComponentOrderFromExistingOrder(componentType string, existingOrder sortableComponents) registeredComponentOrder {
174 // Only the names from the existing order are needed for this so create a list of component names
175 // in the correct order.
176 namesInOrder := componentsToNames(existingOrder)
177
178 // Populate the map from name to position in the list.
179 nameToIndex := make(map[string]int)
180 for i, n := range namesInOrder {
181 nameToIndex[n] = i
182 }
183
184 // A function to use to map from a name to an index in the original order.
185 indexOf := func(name string) int {
186 index, ok := nameToIndex[name]
187 if !ok {
188 // Should never happen as tests that use components that are not known at runtime do not sort
189 // so should never use this function.
190 panic(fmt.Errorf("internal error: unknown %s %q should be one of %s", componentType, name, strings.Join(namesInOrder, ", ")))
191 }
192 return index
193 }
194
195 // The less function.
196 less := func(n1, n2 string) bool {
197 i1 := indexOf(n1)
198 i2 := indexOf(n2)
199 return i1 < i2
200 }
201
202 return registeredComponentOrder{
203 componentType: componentType,
204 namesInOrder: namesInOrder,
205 namesToIndex: nameToIndex,
206 less: less,
207 }
208}
209
210// componentsToNames maps from the slice of components to a slice of their names.
211func componentsToNames(components sortableComponents) []string {
212 names := make([]string, len(components))
213 for i, c := range components {
214 names[i] = c.componentName()
215 }
216 return names
217}
218
219// enforceOrdering enforces the supplied components are in the same order as is defined in this
220// object.
221//
222// If the supplied components contains any components that are not registered at runtime, i.e. test
223// specific components, then it is impossible to sort them into an order that both matches the
224// runtime and also preserves the implicit ordering defined in the test. In that case it will not
225// sort the components, instead it will just check that the components are in the correct order.
226//
227// Otherwise, this will sort the supplied components in place.
228func (o *registeredComponentOrder) enforceOrdering(components sortableComponents) {
229 // Check to see if the list of components contains any components that are
230 // not registered at runtime.
231 var unknownComponents []string
232 testOrder := componentsToNames(components)
233 for _, name := range testOrder {
234 if _, ok := o.namesToIndex[name]; !ok {
235 unknownComponents = append(unknownComponents, name)
236 break
237 }
238 }
239
240 // If the slice contains some unknown components then it is not possible to
241 // sort them into an order that matches the runtime while also preserving the
242 // order expected from the test, so in that case don't sort just check that
243 // the order of the known mutators does match.
244 if len(unknownComponents) > 0 {
245 // Check order.
246 o.checkTestOrder(testOrder, unknownComponents)
247 } else {
248 // Sort the components.
249 sort.Slice(components, func(i, j int) bool {
250 n1 := components[i].componentName()
251 n2 := components[j].componentName()
252 return o.less(n1, n2)
253 })
254 }
255}
256
257// checkTestOrder checks that the supplied testOrder matches the one defined by this object,
258// panicking if it does not.
259func (o *registeredComponentOrder) checkTestOrder(testOrder []string, unknownComponents []string) {
260 lastMatchingTest := -1
261 matchCount := 0
262 // Take a copy of the runtime order as it is modified during the comparison.
263 runtimeOrder := append([]string(nil), o.namesInOrder...)
264 componentType := o.componentType
265 for i, j := 0, 0; i < len(testOrder) && j < len(runtimeOrder); {
266 test := testOrder[i]
267 runtime := runtimeOrder[j]
268
269 if test == runtime {
270 testOrder[i] = test + fmt.Sprintf(" <-- matched with runtime %s %d", componentType, j)
271 runtimeOrder[j] = runtime + fmt.Sprintf(" <-- matched with test %s %d", componentType, i)
272 lastMatchingTest = i
273 i += 1
274 j += 1
275 matchCount += 1
276 } else if _, ok := o.namesToIndex[test]; !ok {
277 // The test component is not registered globally so assume it is the correct place, treat it
278 // as having matched and skip it.
279 i += 1
280 matchCount += 1
281 } else {
282 // Assume that the test list is in the same order as the runtime list but the runtime list
283 // contains some components that are not present in the tests. So, skip the runtime component
284 // to try and find the next one that matches the current test component.
285 j += 1
286 }
287 }
288
289 // If every item in the test order was either test specific or matched one in the runtime then
290 // it is in the correct order. Otherwise, it was not so fail.
291 if matchCount != len(testOrder) {
292 // The test component names were not all matched with a runtime component name so there must
293 // either be a component present in the test that is not present in the runtime or they must be
294 // in the wrong order.
295 testOrder[lastMatchingTest+1] = testOrder[lastMatchingTest+1] + " <--- unmatched"
296 panic(fmt.Errorf("the tests uses test specific components %q and so cannot be automatically sorted."+
297 " Unfortunately it uses %s components in the wrong order.\n"+
298 "test order:\n %s\n"+
299 "runtime order\n %s\n",
300 SortedUniqueStrings(unknownComponents),
301 componentType,
302 strings.Join(testOrder, "\n "),
303 strings.Join(runtimeOrder, "\n ")))
304 }
305}
306
307// registrationSorter encapsulates the information needed to ensure that the test mutators are
308// registered, and thereby executed, in the same order as they are at runtime.
309//
310// It MUST be populated lazily AFTER all package initialization has been done otherwise it will
311// only define the order for a subset of all the registered build components that are available for
312// the packages being tested.
313//
314// e.g if this is initialized during say the cc package initialization then any tests run in the
315// java package will not sort build components registered by the java package's init() functions.
316type registrationSorter struct {
317 // Used to ensure that this is only created once.
318 once sync.Once
319
Paul Duffin41d77c72021-03-07 12:23:48 +0000320 // The order of pre-singletons
321 preSingletonOrder registeredComponentOrder
322
Paul Duffin281deb22021-03-06 20:29:19 +0000323 // The order of mutators
324 mutatorOrder registeredComponentOrder
Paul Duffin41d77c72021-03-07 12:23:48 +0000325
326 // The order of singletons
327 singletonOrder registeredComponentOrder
Paul Duffin281deb22021-03-06 20:29:19 +0000328}
329
330// populate initializes this structure from globally registered build components.
331//
332// Only the first call has any effect.
333func (s *registrationSorter) populate() {
334 s.once.Do(func() {
Paul Duffin41d77c72021-03-07 12:23:48 +0000335 // Create an ordering from the globally registered pre-singletons.
336 s.preSingletonOrder = registeredComponentOrderFromExistingOrder("pre-singleton", preSingletons)
337
Paul Duffin281deb22021-03-06 20:29:19 +0000338 // Created an ordering from the globally registered mutators.
339 globallyRegisteredMutators := collateGloballyRegisteredMutators()
340 s.mutatorOrder = registeredComponentOrderFromExistingOrder("mutator", globallyRegisteredMutators)
Paul Duffin41d77c72021-03-07 12:23:48 +0000341
342 // Create an ordering from the globally registered singletons.
343 globallyRegisteredSingletons := collateGloballyRegisteredSingletons()
344 s.singletonOrder = registeredComponentOrderFromExistingOrder("singleton", globallyRegisteredSingletons)
Paul Duffin281deb22021-03-06 20:29:19 +0000345 })
346}
347
348// Provides support for enforcing the same order in which build components are registered globally
349// to the order in which they are registered during tests.
350//
351// MUST only be accessed via the globallyRegisteredComponentsOrder func.
352var globalRegistrationSorter registrationSorter
353
354// globallyRegisteredComponentsOrder returns the globalRegistrationSorter after ensuring it is
355// correctly populated.
356func globallyRegisteredComponentsOrder() *registrationSorter {
357 globalRegistrationSorter.populate()
358 return &globalRegistrationSorter
359}
360
Colin Crossae8600b2020-10-29 17:09:13 -0700361func (ctx *TestContext) Register() {
Paul Duffin281deb22021-03-06 20:29:19 +0000362 globalOrder := globallyRegisteredComponentsOrder()
363
Paul Duffin41d77c72021-03-07 12:23:48 +0000364 // Ensure that the pre-singletons used in the test are in the same order as they are used at
365 // runtime.
366 globalOrder.preSingletonOrder.enforceOrdering(ctx.preSingletons)
Paul Duffind182fb32021-03-07 12:24:44 +0000367 ctx.preSingletons.registerAll(ctx.Context)
368
Paul Duffinc05b0342021-03-06 13:28:13 +0000369 mutators := collateRegisteredMutators(ctx.preArch, ctx.preDeps, ctx.postDeps, ctx.finalDeps)
Paul Duffin281deb22021-03-06 20:29:19 +0000370 // Ensure that the mutators used in the test are in the same order as they are used at runtime.
371 globalOrder.mutatorOrder.enforceOrdering(mutators)
Paul Duffinc05b0342021-03-06 13:28:13 +0000372 mutators.registerAll(ctx.Context)
Colin Crosscec81712017-07-13 14:43:27 -0700373
Paul Duffind182fb32021-03-07 12:24:44 +0000374 // Register the env singleton with this context before sorting.
Colin Cross4b49b762019-11-22 15:25:03 -0800375 ctx.RegisterSingletonType("env", EnvSingleton)
Paul Duffin281deb22021-03-06 20:29:19 +0000376
Paul Duffin41d77c72021-03-07 12:23:48 +0000377 // Ensure that the singletons used in the test are in the same order as they are used at runtime.
378 globalOrder.singletonOrder.enforceOrdering(ctx.singletons)
Paul Duffind182fb32021-03-07 12:24:44 +0000379 ctx.singletons.registerAll(ctx.Context)
380
Paul Duffin41d77c72021-03-07 12:23:48 +0000381 // Save the sorted components order away to make them easy to access while debugging.
Paul Duffinf5de6682021-03-08 23:42:10 +0000382 ctx.preSingletonOrder = componentsToNames(preSingletons)
383 ctx.mutatorOrder = componentsToNames(mutators)
384 ctx.singletonOrder = componentsToNames(singletons)
Colin Cross31a738b2019-12-30 18:45:15 -0800385}
386
Jingwen Chen73850672020-12-14 08:25:34 -0500387// RegisterForBazelConversion prepares a test context for bp2build conversion.
388func (ctx *TestContext) RegisterForBazelConversion() {
Paul Duffin1d2d42f2021-03-06 20:08:12 +0000389 RegisterMutatorsForBazelConversion(ctx.Context, ctx.bp2buildPreArch, ctx.bp2buildDeps, ctx.bp2buildMutators)
Jingwen Chen73850672020-12-14 08:25:34 -0500390}
391
Colin Cross31a738b2019-12-30 18:45:15 -0800392func (ctx *TestContext) ParseFileList(rootDir string, filePaths []string) (deps []string, errs []error) {
393 // This function adapts the old style ParseFileList calls that are spread throughout the tests
394 // to the new style that takes a config.
395 return ctx.Context.ParseFileList(rootDir, filePaths, ctx.config)
396}
397
398func (ctx *TestContext) ParseBlueprintsFiles(rootDir string) (deps []string, errs []error) {
399 // This function adapts the old style ParseBlueprintsFiles calls that are spread throughout the
400 // tests to the new style that takes a config.
401 return ctx.Context.ParseBlueprintsFiles(rootDir, ctx.config)
Colin Cross4b49b762019-11-22 15:25:03 -0800402}
403
404func (ctx *TestContext) RegisterModuleType(name string, factory ModuleFactory) {
405 ctx.Context.RegisterModuleType(name, ModuleFactoryAdaptor(factory))
406}
407
Colin Cross9aed5bc2020-12-28 15:15:34 -0800408func (ctx *TestContext) RegisterSingletonModuleType(name string, factory SingletonModuleFactory) {
409 s, m := SingletonModuleFactoryAdaptor(name, factory)
410 ctx.RegisterSingletonType(name, s)
411 ctx.RegisterModuleType(name, m)
412}
413
Colin Cross4b49b762019-11-22 15:25:03 -0800414func (ctx *TestContext) RegisterSingletonType(name string, factory SingletonFactory) {
Paul Duffind182fb32021-03-07 12:24:44 +0000415 ctx.singletons = append(ctx.singletons, newSingleton(name, factory))
Colin Crosscec81712017-07-13 14:43:27 -0700416}
417
Paul Duffineafc16b2021-02-24 01:43:18 +0000418func (ctx *TestContext) RegisterPreSingletonType(name string, factory SingletonFactory) {
Paul Duffind182fb32021-03-07 12:24:44 +0000419 ctx.preSingletons = append(ctx.preSingletons, newPreSingleton(name, factory))
Paul Duffineafc16b2021-02-24 01:43:18 +0000420}
421
Colin Crosscec81712017-07-13 14:43:27 -0700422func (ctx *TestContext) ModuleForTests(name, variant string) TestingModule {
423 var module Module
424 ctx.VisitAllModules(func(m blueprint.Module) {
425 if ctx.ModuleName(m) == name && ctx.ModuleSubDir(m) == variant {
426 module = m.(Module)
427 }
428 })
429
430 if module == nil {
Jeff Gaston294356f2017-09-27 17:05:30 -0700431 // find all the modules that do exist
Colin Crossbeae6ec2020-08-11 12:02:11 -0700432 var allModuleNames []string
433 var allVariants []string
Jeff Gaston294356f2017-09-27 17:05:30 -0700434 ctx.VisitAllModules(func(m blueprint.Module) {
Colin Crossbeae6ec2020-08-11 12:02:11 -0700435 allModuleNames = append(allModuleNames, ctx.ModuleName(m))
436 if ctx.ModuleName(m) == name {
437 allVariants = append(allVariants, ctx.ModuleSubDir(m))
438 }
Jeff Gaston294356f2017-09-27 17:05:30 -0700439 })
Martin Stjernholm4c021242020-05-13 01:13:50 +0100440 sort.Strings(allModuleNames)
Colin Crossbeae6ec2020-08-11 12:02:11 -0700441 sort.Strings(allVariants)
Jeff Gaston294356f2017-09-27 17:05:30 -0700442
Colin Crossbeae6ec2020-08-11 12:02:11 -0700443 if len(allVariants) == 0 {
444 panic(fmt.Errorf("failed to find module %q. All modules:\n %s",
445 name, strings.Join(allModuleNames, "\n ")))
446 } else {
447 panic(fmt.Errorf("failed to find module %q variant %q. All variants:\n %s",
448 name, variant, strings.Join(allVariants, "\n ")))
449 }
Colin Crosscec81712017-07-13 14:43:27 -0700450 }
451
452 return TestingModule{module}
453}
454
Jiyong Park37b25202018-07-11 10:49:27 +0900455func (ctx *TestContext) ModuleVariantsForTests(name string) []string {
456 var variants []string
457 ctx.VisitAllModules(func(m blueprint.Module) {
458 if ctx.ModuleName(m) == name {
459 variants = append(variants, ctx.ModuleSubDir(m))
460 }
461 })
462 return variants
463}
464
Colin Cross4c83e5c2019-02-25 14:54:28 -0800465// SingletonForTests returns a TestingSingleton for the singleton registered with the given name.
466func (ctx *TestContext) SingletonForTests(name string) TestingSingleton {
467 allSingletonNames := []string{}
468 for _, s := range ctx.Singletons() {
469 n := ctx.SingletonName(s)
470 if n == name {
471 return TestingSingleton{
472 singleton: s.(*singletonAdaptor).Singleton,
473 provider: s.(testBuildProvider),
474 }
475 }
476 allSingletonNames = append(allSingletonNames, n)
477 }
478
479 panic(fmt.Errorf("failed to find singleton %q."+
480 "\nall singletons: %v", name, allSingletonNames))
481}
482
Colin Crossaa255532020-07-03 13:18:24 -0700483func (ctx *TestContext) Config() Config {
484 return ctx.config
485}
486
Colin Cross4c83e5c2019-02-25 14:54:28 -0800487type testBuildProvider interface {
488 BuildParamsForTests() []BuildParams
489 RuleParamsForTests() map[blueprint.Rule]blueprint.RuleParams
490}
491
492type TestingBuildParams struct {
493 BuildParams
494 RuleParams blueprint.RuleParams
495}
496
497func newTestingBuildParams(provider testBuildProvider, bparams BuildParams) TestingBuildParams {
498 return TestingBuildParams{
499 BuildParams: bparams,
500 RuleParams: provider.RuleParamsForTests()[bparams.Rule],
501 }
502}
503
Thiébaud Weksteen3600b802020-08-27 15:50:24 +0200504func maybeBuildParamsFromRule(provider testBuildProvider, rule string) (TestingBuildParams, []string) {
505 var searchedRules []string
Colin Cross4c83e5c2019-02-25 14:54:28 -0800506 for _, p := range provider.BuildParamsForTests() {
Thiébaud Weksteen3600b802020-08-27 15:50:24 +0200507 searchedRules = append(searchedRules, p.Rule.String())
Colin Cross4c83e5c2019-02-25 14:54:28 -0800508 if strings.Contains(p.Rule.String(), rule) {
Thiébaud Weksteen3600b802020-08-27 15:50:24 +0200509 return newTestingBuildParams(provider, p), searchedRules
Colin Cross4c83e5c2019-02-25 14:54:28 -0800510 }
511 }
Thiébaud Weksteen3600b802020-08-27 15:50:24 +0200512 return TestingBuildParams{}, searchedRules
Colin Cross4c83e5c2019-02-25 14:54:28 -0800513}
514
515func buildParamsFromRule(provider testBuildProvider, rule string) TestingBuildParams {
Thiébaud Weksteen3600b802020-08-27 15:50:24 +0200516 p, searchRules := maybeBuildParamsFromRule(provider, rule)
Colin Cross4c83e5c2019-02-25 14:54:28 -0800517 if p.Rule == nil {
Thiébaud Weksteen3600b802020-08-27 15:50:24 +0200518 panic(fmt.Errorf("couldn't find rule %q.\nall rules: %v", rule, searchRules))
Colin Cross4c83e5c2019-02-25 14:54:28 -0800519 }
520 return p
521}
522
523func maybeBuildParamsFromDescription(provider testBuildProvider, desc string) TestingBuildParams {
524 for _, p := range provider.BuildParamsForTests() {
Colin Crossb88b3c52019-06-10 15:15:17 -0700525 if strings.Contains(p.Description, desc) {
Colin Cross4c83e5c2019-02-25 14:54:28 -0800526 return newTestingBuildParams(provider, p)
527 }
528 }
529 return TestingBuildParams{}
530}
531
532func buildParamsFromDescription(provider testBuildProvider, desc string) TestingBuildParams {
533 p := maybeBuildParamsFromDescription(provider, desc)
534 if p.Rule == nil {
535 panic(fmt.Errorf("couldn't find description %q", desc))
536 }
537 return p
538}
539
540func maybeBuildParamsFromOutput(provider testBuildProvider, file string) (TestingBuildParams, []string) {
541 var searchedOutputs []string
542 for _, p := range provider.BuildParamsForTests() {
543 outputs := append(WritablePaths(nil), p.Outputs...)
Colin Cross1d2cf042019-03-29 15:33:06 -0700544 outputs = append(outputs, p.ImplicitOutputs...)
Colin Cross4c83e5c2019-02-25 14:54:28 -0800545 if p.Output != nil {
546 outputs = append(outputs, p.Output)
547 }
548 for _, f := range outputs {
549 if f.String() == file || f.Rel() == file {
550 return newTestingBuildParams(provider, p), nil
551 }
552 searchedOutputs = append(searchedOutputs, f.Rel())
553 }
554 }
555 return TestingBuildParams{}, searchedOutputs
556}
557
558func buildParamsFromOutput(provider testBuildProvider, file string) TestingBuildParams {
559 p, searchedOutputs := maybeBuildParamsFromOutput(provider, file)
560 if p.Rule == nil {
561 panic(fmt.Errorf("couldn't find output %q.\nall outputs: %v",
562 file, searchedOutputs))
563 }
564 return p
565}
566
567func allOutputs(provider testBuildProvider) []string {
568 var outputFullPaths []string
569 for _, p := range provider.BuildParamsForTests() {
570 outputs := append(WritablePaths(nil), p.Outputs...)
Colin Cross1d2cf042019-03-29 15:33:06 -0700571 outputs = append(outputs, p.ImplicitOutputs...)
Colin Cross4c83e5c2019-02-25 14:54:28 -0800572 if p.Output != nil {
573 outputs = append(outputs, p.Output)
574 }
575 outputFullPaths = append(outputFullPaths, outputs.Strings()...)
576 }
577 return outputFullPaths
578}
579
Colin Crossb77ffc42019-01-05 22:09:19 -0800580// TestingModule is wrapper around an android.Module that provides methods to find information about individual
581// ctx.Build parameters for verification in tests.
Colin Crosscec81712017-07-13 14:43:27 -0700582type TestingModule struct {
583 module Module
584}
585
Colin Crossb77ffc42019-01-05 22:09:19 -0800586// Module returns the Module wrapped by the TestingModule.
Colin Crosscec81712017-07-13 14:43:27 -0700587func (m TestingModule) Module() Module {
588 return m.module
589}
590
Colin Crossb77ffc42019-01-05 22:09:19 -0800591// MaybeRule finds a call to ctx.Build with BuildParams.Rule set to a rule with the given name. Returns an empty
592// BuildParams if no rule is found.
Colin Cross4c83e5c2019-02-25 14:54:28 -0800593func (m TestingModule) MaybeRule(rule string) TestingBuildParams {
Thiébaud Weksteen3600b802020-08-27 15:50:24 +0200594 r, _ := maybeBuildParamsFromRule(m.module, rule)
595 return r
Colin Crosscec81712017-07-13 14:43:27 -0700596}
597
Colin Crossb77ffc42019-01-05 22:09:19 -0800598// Rule finds a call to ctx.Build with BuildParams.Rule set to a rule with the given name. Panics if no rule is found.
Colin Cross4c83e5c2019-02-25 14:54:28 -0800599func (m TestingModule) Rule(rule string) TestingBuildParams {
600 return buildParamsFromRule(m.module, rule)
Colin Crossb77ffc42019-01-05 22:09:19 -0800601}
602
603// MaybeDescription finds a call to ctx.Build with BuildParams.Description set to a the given string. Returns an empty
604// BuildParams if no rule is found.
Colin Cross4c83e5c2019-02-25 14:54:28 -0800605func (m TestingModule) MaybeDescription(desc string) TestingBuildParams {
606 return maybeBuildParamsFromDescription(m.module, desc)
Nan Zhanged19fc32017-10-19 13:06:22 -0700607}
608
Colin Crossb77ffc42019-01-05 22:09:19 -0800609// Description finds a call to ctx.Build with BuildParams.Description set to a the given string. Panics if no rule is
610// found.
Colin Cross4c83e5c2019-02-25 14:54:28 -0800611func (m TestingModule) Description(desc string) TestingBuildParams {
612 return buildParamsFromDescription(m.module, desc)
Colin Crossb77ffc42019-01-05 22:09:19 -0800613}
614
Jaewoong Jung9d22a912019-01-23 16:27:47 -0800615// MaybeOutput finds a call to ctx.Build with a BuildParams.Output or BuildParams.Outputs whose String() or Rel()
Colin Crossb77ffc42019-01-05 22:09:19 -0800616// value matches the provided string. Returns an empty BuildParams if no rule is found.
Colin Cross4c83e5c2019-02-25 14:54:28 -0800617func (m TestingModule) MaybeOutput(file string) TestingBuildParams {
618 p, _ := maybeBuildParamsFromOutput(m.module, file)
Colin Crossb77ffc42019-01-05 22:09:19 -0800619 return p
620}
621
Jaewoong Jung9d22a912019-01-23 16:27:47 -0800622// Output finds a call to ctx.Build with a BuildParams.Output or BuildParams.Outputs whose String() or Rel()
Colin Crossb77ffc42019-01-05 22:09:19 -0800623// value matches the provided string. Panics if no rule is found.
Colin Cross4c83e5c2019-02-25 14:54:28 -0800624func (m TestingModule) Output(file string) TestingBuildParams {
625 return buildParamsFromOutput(m.module, file)
Colin Crosscec81712017-07-13 14:43:27 -0700626}
Logan Chien42039712018-03-12 16:29:17 +0800627
Jaewoong Jung9d22a912019-01-23 16:27:47 -0800628// AllOutputs returns all 'BuildParams.Output's and 'BuildParams.Outputs's in their full path string forms.
629func (m TestingModule) AllOutputs() []string {
Colin Cross4c83e5c2019-02-25 14:54:28 -0800630 return allOutputs(m.module)
631}
632
633// TestingSingleton is wrapper around an android.Singleton that provides methods to find information about individual
634// ctx.Build parameters for verification in tests.
635type TestingSingleton struct {
636 singleton Singleton
637 provider testBuildProvider
638}
639
640// Singleton returns the Singleton wrapped by the TestingSingleton.
641func (s TestingSingleton) Singleton() Singleton {
642 return s.singleton
643}
644
645// MaybeRule finds a call to ctx.Build with BuildParams.Rule set to a rule with the given name. Returns an empty
646// BuildParams if no rule is found.
647func (s TestingSingleton) MaybeRule(rule string) TestingBuildParams {
Thiébaud Weksteen3600b802020-08-27 15:50:24 +0200648 r, _ := maybeBuildParamsFromRule(s.provider, rule)
649 return r
Colin Cross4c83e5c2019-02-25 14:54:28 -0800650}
651
652// Rule finds a call to ctx.Build with BuildParams.Rule set to a rule with the given name. Panics if no rule is found.
653func (s TestingSingleton) Rule(rule string) TestingBuildParams {
654 return buildParamsFromRule(s.provider, rule)
655}
656
657// MaybeDescription finds a call to ctx.Build with BuildParams.Description set to a the given string. Returns an empty
658// BuildParams if no rule is found.
659func (s TestingSingleton) MaybeDescription(desc string) TestingBuildParams {
660 return maybeBuildParamsFromDescription(s.provider, desc)
661}
662
663// Description finds a call to ctx.Build with BuildParams.Description set to a the given string. Panics if no rule is
664// found.
665func (s TestingSingleton) Description(desc string) TestingBuildParams {
666 return buildParamsFromDescription(s.provider, desc)
667}
668
669// MaybeOutput finds a call to ctx.Build with a BuildParams.Output or BuildParams.Outputs whose String() or Rel()
670// value matches the provided string. Returns an empty BuildParams if no rule is found.
671func (s TestingSingleton) MaybeOutput(file string) TestingBuildParams {
672 p, _ := maybeBuildParamsFromOutput(s.provider, file)
673 return p
674}
675
676// Output finds a call to ctx.Build with a BuildParams.Output or BuildParams.Outputs whose String() or Rel()
677// value matches the provided string. Panics if no rule is found.
678func (s TestingSingleton) Output(file string) TestingBuildParams {
679 return buildParamsFromOutput(s.provider, file)
680}
681
682// AllOutputs returns all 'BuildParams.Output's and 'BuildParams.Outputs's in their full path string forms.
683func (s TestingSingleton) AllOutputs() []string {
684 return allOutputs(s.provider)
Jaewoong Jung9d22a912019-01-23 16:27:47 -0800685}
686
Logan Chien42039712018-03-12 16:29:17 +0800687func FailIfErrored(t *testing.T, errs []error) {
688 t.Helper()
689 if len(errs) > 0 {
690 for _, err := range errs {
691 t.Error(err)
692 }
693 t.FailNow()
694 }
695}
Logan Chienee97c3e2018-03-12 16:34:26 +0800696
Paul Duffinea8a3862021-03-04 17:58:33 +0000697// Fail if no errors that matched the regular expression were found.
698//
699// Returns true if a matching error was found, false otherwise.
700func FailIfNoMatchingErrors(t *testing.T, pattern string, errs []error) bool {
Logan Chienee97c3e2018-03-12 16:34:26 +0800701 t.Helper()
702
703 matcher, err := regexp.Compile(pattern)
704 if err != nil {
Paul Duffinea8a3862021-03-04 17:58:33 +0000705 t.Fatalf("failed to compile regular expression %q because %s", pattern, err)
Logan Chienee97c3e2018-03-12 16:34:26 +0800706 }
707
708 found := false
709 for _, err := range errs {
710 if matcher.FindStringIndex(err.Error()) != nil {
711 found = true
712 break
713 }
714 }
715 if !found {
716 t.Errorf("missing the expected error %q (checked %d error(s))", pattern, len(errs))
717 for i, err := range errs {
Colin Crossaede88c2020-08-11 12:17:01 -0700718 t.Errorf("errs[%d] = %q", i, err)
Logan Chienee97c3e2018-03-12 16:34:26 +0800719 }
720 }
Paul Duffinea8a3862021-03-04 17:58:33 +0000721
722 return found
Logan Chienee97c3e2018-03-12 16:34:26 +0800723}
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700724
Paul Duffin91e38192019-08-05 15:07:57 +0100725func CheckErrorsAgainstExpectations(t *testing.T, errs []error, expectedErrorPatterns []string) {
726 t.Helper()
727
728 if expectedErrorPatterns == nil {
729 FailIfErrored(t, errs)
730 } else {
731 for _, expectedError := range expectedErrorPatterns {
732 FailIfNoMatchingErrors(t, expectedError, errs)
733 }
734 if len(errs) > len(expectedErrorPatterns) {
735 t.Errorf("additional errors found, expected %d, found %d",
736 len(expectedErrorPatterns), len(errs))
737 for i, expectedError := range expectedErrorPatterns {
738 t.Errorf("expectedErrors[%d] = %s", i, expectedError)
739 }
740 for i, err := range errs {
741 t.Errorf("errs[%d] = %s", i, err)
742 }
Paul Duffinea8a3862021-03-04 17:58:33 +0000743 t.FailNow()
Paul Duffin91e38192019-08-05 15:07:57 +0100744 }
745 }
Paul Duffin91e38192019-08-05 15:07:57 +0100746}
747
Jingwen Chencda22c92020-11-23 00:22:30 -0500748func SetKatiEnabledForTests(config Config) {
749 config.katiEnabled = true
Paul Duffin8c3fec42020-03-04 20:15:08 +0000750}
751
Colin Crossaa255532020-07-03 13:18:24 -0700752func AndroidMkEntriesForTest(t *testing.T, ctx *TestContext, mod blueprint.Module) []AndroidMkEntries {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700753 var p AndroidMkEntriesProvider
754 var ok bool
755 if p, ok = mod.(AndroidMkEntriesProvider); !ok {
Roland Levillaindfe75b32019-07-23 16:53:32 +0100756 t.Errorf("module does not implement AndroidMkEntriesProvider: " + mod.Name())
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700757 }
Jiyong Park0b0e1b92019-12-03 13:24:29 +0900758
759 entriesList := p.AndroidMkEntries()
760 for i, _ := range entriesList {
Colin Crossaa255532020-07-03 13:18:24 -0700761 entriesList[i].fillInEntries(ctx, mod)
Jiyong Park0b0e1b92019-12-03 13:24:29 +0900762 }
763 return entriesList
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700764}
Jooyung Han12df5fb2019-07-11 16:18:47 +0900765
Colin Crossaa255532020-07-03 13:18:24 -0700766func AndroidMkDataForTest(t *testing.T, ctx *TestContext, mod blueprint.Module) AndroidMkData {
Jooyung Han12df5fb2019-07-11 16:18:47 +0900767 var p AndroidMkDataProvider
768 var ok bool
769 if p, ok = mod.(AndroidMkDataProvider); !ok {
Roland Levillaindfe75b32019-07-23 16:53:32 +0100770 t.Errorf("module does not implement AndroidMkDataProvider: " + mod.Name())
Jooyung Han12df5fb2019-07-11 16:18:47 +0900771 }
772 data := p.AndroidMk()
Colin Crossaa255532020-07-03 13:18:24 -0700773 data.fillInData(ctx, mod)
Jooyung Han12df5fb2019-07-11 16:18:47 +0900774 return data
775}
Paul Duffin9b478b02019-12-10 13:41:51 +0000776
777// Normalize the path for testing.
778//
779// If the path is relative to the build directory then return the relative path
780// to avoid tests having to deal with the dynamically generated build directory.
781//
782// Otherwise, return the supplied path as it is almost certainly a source path
783// that is relative to the root of the source tree.
784//
785// The build and source paths should be distinguishable based on their contents.
786func NormalizePathForTesting(path Path) string {
Paul Duffin064b70c2020-11-02 17:32:38 +0000787 if path == nil {
788 return "<nil path>"
789 }
Paul Duffin9b478b02019-12-10 13:41:51 +0000790 p := path.String()
Paul Duffindb170e42020-12-08 17:48:25 +0000791 // Allow absolute paths to /dev/
792 if strings.HasPrefix(p, "/dev/") {
793 return p
794 }
Paul Duffin9b478b02019-12-10 13:41:51 +0000795 if w, ok := path.(WritablePath); ok {
796 rel, err := filepath.Rel(w.buildDir(), p)
797 if err != nil {
798 panic(err)
799 }
800 return rel
801 }
802 return p
803}
804
805func NormalizePathsForTesting(paths Paths) []string {
806 var result []string
807 for _, path := range paths {
808 relative := NormalizePathForTesting(path)
809 result = append(result, relative)
810 }
811 return result
812}