blob: 0210f23c778c8c1a703175f51dffb559ab729c6f [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
Paul Duffinec3292b2021-03-09 01:01:31 +000076// Test fixture preparer that will register most java build components.
77//
78// Singletons and mutators should only be added here if they are needed for a majority of java
79// module types, otherwise they should be added under a separate preparer to allow them to be
80// selected only when needed to reduce test execution time.
81//
82// Module types do not have much of an overhead unless they are used so this should include as many
83// module types as possible. The exceptions are those module types that require mutators and/or
84// singletons in order to function in which case they should be kept together in a separate
85// preparer.
86//
87// The mutators in this group were chosen because they are needed by the vast majority of tests.
88var PrepareForTestWithAndroidBuildComponents = GroupFixturePreparers(
Paul Duffin530483c2021-03-07 13:20:38 +000089 // Sorted alphabetically as the actual order does not matter as tests automatically enforce the
90 // correct order.
Paul Duffin35816122021-02-24 01:49:52 +000091 PrepareForTestWithArchMutator,
Paul Duffin35816122021-02-24 01:49:52 +000092 PrepareForTestWithComponentsMutator,
Paul Duffin530483c2021-03-07 13:20:38 +000093 PrepareForTestWithDefaults,
Paul Duffin35816122021-02-24 01:49:52 +000094 PrepareForTestWithFilegroup,
Paul Duffin530483c2021-03-07 13:20:38 +000095 PrepareForTestWithOverrides,
96 PrepareForTestWithPackageModule,
97 PrepareForTestWithPrebuilts,
98 PrepareForTestWithVisibility,
Paul Duffin35816122021-02-24 01:49:52 +000099)
100
Paul Duffinec3292b2021-03-09 01:01:31 +0000101// Prepares an integration test with all build components from the android package.
102//
103// This should only be used by tests that want to run with as much of the build enabled as possible.
104var PrepareForIntegrationTestWithAndroid = GroupFixturePreparers(
105 PrepareForTestWithAndroidBuildComponents,
106)
107
Colin Crossae8600b2020-10-29 17:09:13 -0700108func NewTestArchContext(config Config) *TestContext {
109 ctx := NewTestContext(config)
Colin Crossae4c6182017-09-15 17:33:55 -0700110 ctx.preDeps = append(ctx.preDeps, registerArchMutator)
111 return ctx
112}
113
Colin Crosscec81712017-07-13 14:43:27 -0700114type TestContext struct {
Colin Cross4c83e5c2019-02-25 14:54:28 -0800115 *Context
Liz Kammer356f7d42021-01-26 09:18:53 -0500116 preArch, preDeps, postDeps, finalDeps []RegisterMutatorFunc
117 bp2buildPreArch, bp2buildDeps, bp2buildMutators []RegisterMutatorFunc
118 NameResolver *NameResolver
Paul Duffin281deb22021-03-06 20:29:19 +0000119
Paul Duffind182fb32021-03-07 12:24:44 +0000120 // The list of pre-singletons and singletons registered for the test.
121 preSingletons, singletons sortableComponents
122
Paul Duffin41d77c72021-03-07 12:23:48 +0000123 // The order in which the pre-singletons, mutators and singletons will be run in this test
124 // context; for debugging.
125 preSingletonOrder, mutatorOrder, singletonOrder []string
Colin Crosscec81712017-07-13 14:43:27 -0700126}
127
128func (ctx *TestContext) PreArchMutators(f RegisterMutatorFunc) {
129 ctx.preArch = append(ctx.preArch, f)
130}
131
Paul Duffina80ef842020-01-14 12:09:36 +0000132func (ctx *TestContext) HardCodedPreArchMutators(f RegisterMutatorFunc) {
133 // Register mutator function as normal for testing.
134 ctx.PreArchMutators(f)
135}
136
Colin Crosscec81712017-07-13 14:43:27 -0700137func (ctx *TestContext) PreDepsMutators(f RegisterMutatorFunc) {
138 ctx.preDeps = append(ctx.preDeps, f)
139}
140
141func (ctx *TestContext) PostDepsMutators(f RegisterMutatorFunc) {
142 ctx.postDeps = append(ctx.postDeps, f)
143}
144
Martin Stjernholm710ec3a2020-01-16 15:12:04 +0000145func (ctx *TestContext) FinalDepsMutators(f RegisterMutatorFunc) {
146 ctx.finalDeps = append(ctx.finalDeps, f)
147}
148
Jingwen Chen73850672020-12-14 08:25:34 -0500149// RegisterBp2BuildMutator registers a BazelTargetModule mutator for converting a module
150// type to the equivalent Bazel target.
151func (ctx *TestContext) RegisterBp2BuildMutator(moduleType string, m func(TopDownMutatorContext)) {
Jingwen Chen73850672020-12-14 08:25:34 -0500152 f := func(ctx RegisterMutatorsContext) {
Liz Kammer356f7d42021-01-26 09:18:53 -0500153 ctx.TopDown(moduleType, m)
Jingwen Chen73850672020-12-14 08:25:34 -0500154 }
Jingwen Chena42d6412021-01-26 21:57:27 -0500155 ctx.bp2buildMutators = append(ctx.bp2buildMutators, f)
Jingwen Chen73850672020-12-14 08:25:34 -0500156}
157
Liz Kammer356f7d42021-01-26 09:18:53 -0500158// PreArchBp2BuildMutators adds mutators to be register for converting Android Blueprint modules
159// into Bazel BUILD targets that should run prior to deps and conversion.
160func (ctx *TestContext) PreArchBp2BuildMutators(f RegisterMutatorFunc) {
161 ctx.bp2buildPreArch = append(ctx.bp2buildPreArch, f)
162}
163
164// DepsBp2BuildMutators adds mutators to be register for converting Android Blueprint modules into
165// Bazel BUILD targets that should run prior to conversion to resolve dependencies.
166func (ctx *TestContext) DepsBp2BuildMutators(f RegisterMutatorFunc) {
167 ctx.bp2buildDeps = append(ctx.bp2buildDeps, f)
168}
169
Paul Duffin281deb22021-03-06 20:29:19 +0000170// registeredComponentOrder defines the order in which a sortableComponent type is registered at
171// runtime and provides support for reordering the components registered for a test in the same
172// way.
173type registeredComponentOrder struct {
174 // The name of the component type, used for error messages.
175 componentType string
176
177 // The names of the registered components in the order in which they were registered.
178 namesInOrder []string
179
180 // Maps from the component name to its position in the runtime ordering.
181 namesToIndex map[string]int
182
183 // A function that defines the order between two named components that can be used to sort a slice
184 // of component names into the same order as they appear in namesInOrder.
185 less func(string, string) bool
186}
187
188// registeredComponentOrderFromExistingOrder takes an existing slice of sortableComponents and
189// creates a registeredComponentOrder that contains a less function that can be used to sort a
190// subset of that list of names so it is in the same order as the original sortableComponents.
191func registeredComponentOrderFromExistingOrder(componentType string, existingOrder sortableComponents) registeredComponentOrder {
192 // Only the names from the existing order are needed for this so create a list of component names
193 // in the correct order.
194 namesInOrder := componentsToNames(existingOrder)
195
196 // Populate the map from name to position in the list.
197 nameToIndex := make(map[string]int)
198 for i, n := range namesInOrder {
199 nameToIndex[n] = i
200 }
201
202 // A function to use to map from a name to an index in the original order.
203 indexOf := func(name string) int {
204 index, ok := nameToIndex[name]
205 if !ok {
206 // Should never happen as tests that use components that are not known at runtime do not sort
207 // so should never use this function.
208 panic(fmt.Errorf("internal error: unknown %s %q should be one of %s", componentType, name, strings.Join(namesInOrder, ", ")))
209 }
210 return index
211 }
212
213 // The less function.
214 less := func(n1, n2 string) bool {
215 i1 := indexOf(n1)
216 i2 := indexOf(n2)
217 return i1 < i2
218 }
219
220 return registeredComponentOrder{
221 componentType: componentType,
222 namesInOrder: namesInOrder,
223 namesToIndex: nameToIndex,
224 less: less,
225 }
226}
227
228// componentsToNames maps from the slice of components to a slice of their names.
229func componentsToNames(components sortableComponents) []string {
230 names := make([]string, len(components))
231 for i, c := range components {
232 names[i] = c.componentName()
233 }
234 return names
235}
236
237// enforceOrdering enforces the supplied components are in the same order as is defined in this
238// object.
239//
240// If the supplied components contains any components that are not registered at runtime, i.e. test
241// specific components, then it is impossible to sort them into an order that both matches the
242// runtime and also preserves the implicit ordering defined in the test. In that case it will not
243// sort the components, instead it will just check that the components are in the correct order.
244//
245// Otherwise, this will sort the supplied components in place.
246func (o *registeredComponentOrder) enforceOrdering(components sortableComponents) {
247 // Check to see if the list of components contains any components that are
248 // not registered at runtime.
249 var unknownComponents []string
250 testOrder := componentsToNames(components)
251 for _, name := range testOrder {
252 if _, ok := o.namesToIndex[name]; !ok {
253 unknownComponents = append(unknownComponents, name)
254 break
255 }
256 }
257
258 // If the slice contains some unknown components then it is not possible to
259 // sort them into an order that matches the runtime while also preserving the
260 // order expected from the test, so in that case don't sort just check that
261 // the order of the known mutators does match.
262 if len(unknownComponents) > 0 {
263 // Check order.
264 o.checkTestOrder(testOrder, unknownComponents)
265 } else {
266 // Sort the components.
267 sort.Slice(components, func(i, j int) bool {
268 n1 := components[i].componentName()
269 n2 := components[j].componentName()
270 return o.less(n1, n2)
271 })
272 }
273}
274
275// checkTestOrder checks that the supplied testOrder matches the one defined by this object,
276// panicking if it does not.
277func (o *registeredComponentOrder) checkTestOrder(testOrder []string, unknownComponents []string) {
278 lastMatchingTest := -1
279 matchCount := 0
280 // Take a copy of the runtime order as it is modified during the comparison.
281 runtimeOrder := append([]string(nil), o.namesInOrder...)
282 componentType := o.componentType
283 for i, j := 0, 0; i < len(testOrder) && j < len(runtimeOrder); {
284 test := testOrder[i]
285 runtime := runtimeOrder[j]
286
287 if test == runtime {
288 testOrder[i] = test + fmt.Sprintf(" <-- matched with runtime %s %d", componentType, j)
289 runtimeOrder[j] = runtime + fmt.Sprintf(" <-- matched with test %s %d", componentType, i)
290 lastMatchingTest = i
291 i += 1
292 j += 1
293 matchCount += 1
294 } else if _, ok := o.namesToIndex[test]; !ok {
295 // The test component is not registered globally so assume it is the correct place, treat it
296 // as having matched and skip it.
297 i += 1
298 matchCount += 1
299 } else {
300 // Assume that the test list is in the same order as the runtime list but the runtime list
301 // contains some components that are not present in the tests. So, skip the runtime component
302 // to try and find the next one that matches the current test component.
303 j += 1
304 }
305 }
306
307 // If every item in the test order was either test specific or matched one in the runtime then
308 // it is in the correct order. Otherwise, it was not so fail.
309 if matchCount != len(testOrder) {
310 // The test component names were not all matched with a runtime component name so there must
311 // either be a component present in the test that is not present in the runtime or they must be
312 // in the wrong order.
313 testOrder[lastMatchingTest+1] = testOrder[lastMatchingTest+1] + " <--- unmatched"
314 panic(fmt.Errorf("the tests uses test specific components %q and so cannot be automatically sorted."+
315 " Unfortunately it uses %s components in the wrong order.\n"+
316 "test order:\n %s\n"+
317 "runtime order\n %s\n",
318 SortedUniqueStrings(unknownComponents),
319 componentType,
320 strings.Join(testOrder, "\n "),
321 strings.Join(runtimeOrder, "\n ")))
322 }
323}
324
325// registrationSorter encapsulates the information needed to ensure that the test mutators are
326// registered, and thereby executed, in the same order as they are at runtime.
327//
328// It MUST be populated lazily AFTER all package initialization has been done otherwise it will
329// only define the order for a subset of all the registered build components that are available for
330// the packages being tested.
331//
332// e.g if this is initialized during say the cc package initialization then any tests run in the
333// java package will not sort build components registered by the java package's init() functions.
334type registrationSorter struct {
335 // Used to ensure that this is only created once.
336 once sync.Once
337
Paul Duffin41d77c72021-03-07 12:23:48 +0000338 // The order of pre-singletons
339 preSingletonOrder registeredComponentOrder
340
Paul Duffin281deb22021-03-06 20:29:19 +0000341 // The order of mutators
342 mutatorOrder registeredComponentOrder
Paul Duffin41d77c72021-03-07 12:23:48 +0000343
344 // The order of singletons
345 singletonOrder registeredComponentOrder
Paul Duffin281deb22021-03-06 20:29:19 +0000346}
347
348// populate initializes this structure from globally registered build components.
349//
350// Only the first call has any effect.
351func (s *registrationSorter) populate() {
352 s.once.Do(func() {
Paul Duffin41d77c72021-03-07 12:23:48 +0000353 // Create an ordering from the globally registered pre-singletons.
354 s.preSingletonOrder = registeredComponentOrderFromExistingOrder("pre-singleton", preSingletons)
355
Paul Duffin281deb22021-03-06 20:29:19 +0000356 // Created an ordering from the globally registered mutators.
357 globallyRegisteredMutators := collateGloballyRegisteredMutators()
358 s.mutatorOrder = registeredComponentOrderFromExistingOrder("mutator", globallyRegisteredMutators)
Paul Duffin41d77c72021-03-07 12:23:48 +0000359
360 // Create an ordering from the globally registered singletons.
361 globallyRegisteredSingletons := collateGloballyRegisteredSingletons()
362 s.singletonOrder = registeredComponentOrderFromExistingOrder("singleton", globallyRegisteredSingletons)
Paul Duffin281deb22021-03-06 20:29:19 +0000363 })
364}
365
366// Provides support for enforcing the same order in which build components are registered globally
367// to the order in which they are registered during tests.
368//
369// MUST only be accessed via the globallyRegisteredComponentsOrder func.
370var globalRegistrationSorter registrationSorter
371
372// globallyRegisteredComponentsOrder returns the globalRegistrationSorter after ensuring it is
373// correctly populated.
374func globallyRegisteredComponentsOrder() *registrationSorter {
375 globalRegistrationSorter.populate()
376 return &globalRegistrationSorter
377}
378
Colin Crossae8600b2020-10-29 17:09:13 -0700379func (ctx *TestContext) Register() {
Paul Duffin281deb22021-03-06 20:29:19 +0000380 globalOrder := globallyRegisteredComponentsOrder()
381
Paul Duffin41d77c72021-03-07 12:23:48 +0000382 // Ensure that the pre-singletons used in the test are in the same order as they are used at
383 // runtime.
384 globalOrder.preSingletonOrder.enforceOrdering(ctx.preSingletons)
Paul Duffind182fb32021-03-07 12:24:44 +0000385 ctx.preSingletons.registerAll(ctx.Context)
386
Paul Duffinc05b0342021-03-06 13:28:13 +0000387 mutators := collateRegisteredMutators(ctx.preArch, ctx.preDeps, ctx.postDeps, ctx.finalDeps)
Paul Duffin281deb22021-03-06 20:29:19 +0000388 // Ensure that the mutators used in the test are in the same order as they are used at runtime.
389 globalOrder.mutatorOrder.enforceOrdering(mutators)
Paul Duffinc05b0342021-03-06 13:28:13 +0000390 mutators.registerAll(ctx.Context)
Colin Crosscec81712017-07-13 14:43:27 -0700391
Paul Duffind182fb32021-03-07 12:24:44 +0000392 // Register the env singleton with this context before sorting.
Colin Cross4b49b762019-11-22 15:25:03 -0800393 ctx.RegisterSingletonType("env", EnvSingleton)
Paul Duffin281deb22021-03-06 20:29:19 +0000394
Paul Duffin41d77c72021-03-07 12:23:48 +0000395 // Ensure that the singletons used in the test are in the same order as they are used at runtime.
396 globalOrder.singletonOrder.enforceOrdering(ctx.singletons)
Paul Duffind182fb32021-03-07 12:24:44 +0000397 ctx.singletons.registerAll(ctx.Context)
398
Paul Duffin41d77c72021-03-07 12:23:48 +0000399 // Save the sorted components order away to make them easy to access while debugging.
Paul Duffinf5de6682021-03-08 23:42:10 +0000400 ctx.preSingletonOrder = componentsToNames(preSingletons)
401 ctx.mutatorOrder = componentsToNames(mutators)
402 ctx.singletonOrder = componentsToNames(singletons)
Colin Cross31a738b2019-12-30 18:45:15 -0800403}
404
Jingwen Chen73850672020-12-14 08:25:34 -0500405// RegisterForBazelConversion prepares a test context for bp2build conversion.
406func (ctx *TestContext) RegisterForBazelConversion() {
Paul Duffin1d2d42f2021-03-06 20:08:12 +0000407 RegisterMutatorsForBazelConversion(ctx.Context, ctx.bp2buildPreArch, ctx.bp2buildDeps, ctx.bp2buildMutators)
Jingwen Chen73850672020-12-14 08:25:34 -0500408}
409
Colin Cross31a738b2019-12-30 18:45:15 -0800410func (ctx *TestContext) ParseFileList(rootDir string, filePaths []string) (deps []string, errs []error) {
411 // This function adapts the old style ParseFileList calls that are spread throughout the tests
412 // to the new style that takes a config.
413 return ctx.Context.ParseFileList(rootDir, filePaths, ctx.config)
414}
415
416func (ctx *TestContext) ParseBlueprintsFiles(rootDir string) (deps []string, errs []error) {
417 // This function adapts the old style ParseBlueprintsFiles calls that are spread throughout the
418 // tests to the new style that takes a config.
419 return ctx.Context.ParseBlueprintsFiles(rootDir, ctx.config)
Colin Cross4b49b762019-11-22 15:25:03 -0800420}
421
422func (ctx *TestContext) RegisterModuleType(name string, factory ModuleFactory) {
423 ctx.Context.RegisterModuleType(name, ModuleFactoryAdaptor(factory))
424}
425
Colin Cross9aed5bc2020-12-28 15:15:34 -0800426func (ctx *TestContext) RegisterSingletonModuleType(name string, factory SingletonModuleFactory) {
427 s, m := SingletonModuleFactoryAdaptor(name, factory)
428 ctx.RegisterSingletonType(name, s)
429 ctx.RegisterModuleType(name, m)
430}
431
Colin Cross4b49b762019-11-22 15:25:03 -0800432func (ctx *TestContext) RegisterSingletonType(name string, factory SingletonFactory) {
Paul Duffind182fb32021-03-07 12:24:44 +0000433 ctx.singletons = append(ctx.singletons, newSingleton(name, factory))
Colin Crosscec81712017-07-13 14:43:27 -0700434}
435
Paul Duffineafc16b2021-02-24 01:43:18 +0000436func (ctx *TestContext) RegisterPreSingletonType(name string, factory SingletonFactory) {
Paul Duffind182fb32021-03-07 12:24:44 +0000437 ctx.preSingletons = append(ctx.preSingletons, newPreSingleton(name, factory))
Paul Duffineafc16b2021-02-24 01:43:18 +0000438}
439
Colin Crosscec81712017-07-13 14:43:27 -0700440func (ctx *TestContext) ModuleForTests(name, variant string) TestingModule {
441 var module Module
442 ctx.VisitAllModules(func(m blueprint.Module) {
443 if ctx.ModuleName(m) == name && ctx.ModuleSubDir(m) == variant {
444 module = m.(Module)
445 }
446 })
447
448 if module == nil {
Jeff Gaston294356f2017-09-27 17:05:30 -0700449 // find all the modules that do exist
Colin Crossbeae6ec2020-08-11 12:02:11 -0700450 var allModuleNames []string
451 var allVariants []string
Jeff Gaston294356f2017-09-27 17:05:30 -0700452 ctx.VisitAllModules(func(m blueprint.Module) {
Colin Crossbeae6ec2020-08-11 12:02:11 -0700453 allModuleNames = append(allModuleNames, ctx.ModuleName(m))
454 if ctx.ModuleName(m) == name {
455 allVariants = append(allVariants, ctx.ModuleSubDir(m))
456 }
Jeff Gaston294356f2017-09-27 17:05:30 -0700457 })
Martin Stjernholm4c021242020-05-13 01:13:50 +0100458 sort.Strings(allModuleNames)
Colin Crossbeae6ec2020-08-11 12:02:11 -0700459 sort.Strings(allVariants)
Jeff Gaston294356f2017-09-27 17:05:30 -0700460
Colin Crossbeae6ec2020-08-11 12:02:11 -0700461 if len(allVariants) == 0 {
462 panic(fmt.Errorf("failed to find module %q. All modules:\n %s",
463 name, strings.Join(allModuleNames, "\n ")))
464 } else {
465 panic(fmt.Errorf("failed to find module %q variant %q. All variants:\n %s",
466 name, variant, strings.Join(allVariants, "\n ")))
467 }
Colin Crosscec81712017-07-13 14:43:27 -0700468 }
469
470 return TestingModule{module}
471}
472
Jiyong Park37b25202018-07-11 10:49:27 +0900473func (ctx *TestContext) ModuleVariantsForTests(name string) []string {
474 var variants []string
475 ctx.VisitAllModules(func(m blueprint.Module) {
476 if ctx.ModuleName(m) == name {
477 variants = append(variants, ctx.ModuleSubDir(m))
478 }
479 })
480 return variants
481}
482
Colin Cross4c83e5c2019-02-25 14:54:28 -0800483// SingletonForTests returns a TestingSingleton for the singleton registered with the given name.
484func (ctx *TestContext) SingletonForTests(name string) TestingSingleton {
485 allSingletonNames := []string{}
486 for _, s := range ctx.Singletons() {
487 n := ctx.SingletonName(s)
488 if n == name {
489 return TestingSingleton{
490 singleton: s.(*singletonAdaptor).Singleton,
491 provider: s.(testBuildProvider),
492 }
493 }
494 allSingletonNames = append(allSingletonNames, n)
495 }
496
497 panic(fmt.Errorf("failed to find singleton %q."+
498 "\nall singletons: %v", name, allSingletonNames))
499}
500
Colin Crossaa255532020-07-03 13:18:24 -0700501func (ctx *TestContext) Config() Config {
502 return ctx.config
503}
504
Colin Cross4c83e5c2019-02-25 14:54:28 -0800505type testBuildProvider interface {
506 BuildParamsForTests() []BuildParams
507 RuleParamsForTests() map[blueprint.Rule]blueprint.RuleParams
508}
509
510type TestingBuildParams struct {
511 BuildParams
512 RuleParams blueprint.RuleParams
513}
514
515func newTestingBuildParams(provider testBuildProvider, bparams BuildParams) TestingBuildParams {
516 return TestingBuildParams{
517 BuildParams: bparams,
518 RuleParams: provider.RuleParamsForTests()[bparams.Rule],
519 }
520}
521
Thiébaud Weksteen3600b802020-08-27 15:50:24 +0200522func maybeBuildParamsFromRule(provider testBuildProvider, rule string) (TestingBuildParams, []string) {
523 var searchedRules []string
Colin Cross4c83e5c2019-02-25 14:54:28 -0800524 for _, p := range provider.BuildParamsForTests() {
Thiébaud Weksteen3600b802020-08-27 15:50:24 +0200525 searchedRules = append(searchedRules, p.Rule.String())
Colin Cross4c83e5c2019-02-25 14:54:28 -0800526 if strings.Contains(p.Rule.String(), rule) {
Thiébaud Weksteen3600b802020-08-27 15:50:24 +0200527 return newTestingBuildParams(provider, p), searchedRules
Colin Cross4c83e5c2019-02-25 14:54:28 -0800528 }
529 }
Thiébaud Weksteen3600b802020-08-27 15:50:24 +0200530 return TestingBuildParams{}, searchedRules
Colin Cross4c83e5c2019-02-25 14:54:28 -0800531}
532
533func buildParamsFromRule(provider testBuildProvider, rule string) TestingBuildParams {
Thiébaud Weksteen3600b802020-08-27 15:50:24 +0200534 p, searchRules := maybeBuildParamsFromRule(provider, rule)
Colin Cross4c83e5c2019-02-25 14:54:28 -0800535 if p.Rule == nil {
Thiébaud Weksteen3600b802020-08-27 15:50:24 +0200536 panic(fmt.Errorf("couldn't find rule %q.\nall rules: %v", rule, searchRules))
Colin Cross4c83e5c2019-02-25 14:54:28 -0800537 }
538 return p
539}
540
541func maybeBuildParamsFromDescription(provider testBuildProvider, desc string) TestingBuildParams {
542 for _, p := range provider.BuildParamsForTests() {
Colin Crossb88b3c52019-06-10 15:15:17 -0700543 if strings.Contains(p.Description, desc) {
Colin Cross4c83e5c2019-02-25 14:54:28 -0800544 return newTestingBuildParams(provider, p)
545 }
546 }
547 return TestingBuildParams{}
548}
549
550func buildParamsFromDescription(provider testBuildProvider, desc string) TestingBuildParams {
551 p := maybeBuildParamsFromDescription(provider, desc)
552 if p.Rule == nil {
553 panic(fmt.Errorf("couldn't find description %q", desc))
554 }
555 return p
556}
557
558func maybeBuildParamsFromOutput(provider testBuildProvider, file string) (TestingBuildParams, []string) {
559 var searchedOutputs []string
560 for _, p := range provider.BuildParamsForTests() {
561 outputs := append(WritablePaths(nil), p.Outputs...)
Colin Cross1d2cf042019-03-29 15:33:06 -0700562 outputs = append(outputs, p.ImplicitOutputs...)
Colin Cross4c83e5c2019-02-25 14:54:28 -0800563 if p.Output != nil {
564 outputs = append(outputs, p.Output)
565 }
566 for _, f := range outputs {
567 if f.String() == file || f.Rel() == file {
568 return newTestingBuildParams(provider, p), nil
569 }
570 searchedOutputs = append(searchedOutputs, f.Rel())
571 }
572 }
573 return TestingBuildParams{}, searchedOutputs
574}
575
576func buildParamsFromOutput(provider testBuildProvider, file string) TestingBuildParams {
577 p, searchedOutputs := maybeBuildParamsFromOutput(provider, file)
578 if p.Rule == nil {
579 panic(fmt.Errorf("couldn't find output %q.\nall outputs: %v",
580 file, searchedOutputs))
581 }
582 return p
583}
584
585func allOutputs(provider testBuildProvider) []string {
586 var outputFullPaths []string
587 for _, p := range provider.BuildParamsForTests() {
588 outputs := append(WritablePaths(nil), p.Outputs...)
Colin Cross1d2cf042019-03-29 15:33:06 -0700589 outputs = append(outputs, p.ImplicitOutputs...)
Colin Cross4c83e5c2019-02-25 14:54:28 -0800590 if p.Output != nil {
591 outputs = append(outputs, p.Output)
592 }
593 outputFullPaths = append(outputFullPaths, outputs.Strings()...)
594 }
595 return outputFullPaths
596}
597
Colin Crossb77ffc42019-01-05 22:09:19 -0800598// TestingModule is wrapper around an android.Module that provides methods to find information about individual
599// ctx.Build parameters for verification in tests.
Colin Crosscec81712017-07-13 14:43:27 -0700600type TestingModule struct {
601 module Module
602}
603
Colin Crossb77ffc42019-01-05 22:09:19 -0800604// Module returns the Module wrapped by the TestingModule.
Colin Crosscec81712017-07-13 14:43:27 -0700605func (m TestingModule) Module() Module {
606 return m.module
607}
608
Colin Crossb77ffc42019-01-05 22:09:19 -0800609// MaybeRule finds a call to ctx.Build with BuildParams.Rule set to a rule with the given name. Returns an empty
610// BuildParams if no rule is found.
Colin Cross4c83e5c2019-02-25 14:54:28 -0800611func (m TestingModule) MaybeRule(rule string) TestingBuildParams {
Thiébaud Weksteen3600b802020-08-27 15:50:24 +0200612 r, _ := maybeBuildParamsFromRule(m.module, rule)
613 return r
Colin Crosscec81712017-07-13 14:43:27 -0700614}
615
Colin Crossb77ffc42019-01-05 22:09:19 -0800616// 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 -0800617func (m TestingModule) Rule(rule string) TestingBuildParams {
618 return buildParamsFromRule(m.module, rule)
Colin Crossb77ffc42019-01-05 22:09:19 -0800619}
620
621// MaybeDescription finds a call to ctx.Build with BuildParams.Description set to a the given string. Returns an empty
622// BuildParams if no rule is found.
Colin Cross4c83e5c2019-02-25 14:54:28 -0800623func (m TestingModule) MaybeDescription(desc string) TestingBuildParams {
624 return maybeBuildParamsFromDescription(m.module, desc)
Nan Zhanged19fc32017-10-19 13:06:22 -0700625}
626
Colin Crossb77ffc42019-01-05 22:09:19 -0800627// Description finds a call to ctx.Build with BuildParams.Description set to a the given string. Panics if no rule is
628// found.
Colin Cross4c83e5c2019-02-25 14:54:28 -0800629func (m TestingModule) Description(desc string) TestingBuildParams {
630 return buildParamsFromDescription(m.module, desc)
Colin Crossb77ffc42019-01-05 22:09:19 -0800631}
632
Jaewoong Jung9d22a912019-01-23 16:27:47 -0800633// 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 -0800634// value matches the provided string. Returns an empty BuildParams if no rule is found.
Colin Cross4c83e5c2019-02-25 14:54:28 -0800635func (m TestingModule) MaybeOutput(file string) TestingBuildParams {
636 p, _ := maybeBuildParamsFromOutput(m.module, file)
Colin Crossb77ffc42019-01-05 22:09:19 -0800637 return p
638}
639
Jaewoong Jung9d22a912019-01-23 16:27:47 -0800640// 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 -0800641// value matches the provided string. Panics if no rule is found.
Colin Cross4c83e5c2019-02-25 14:54:28 -0800642func (m TestingModule) Output(file string) TestingBuildParams {
643 return buildParamsFromOutput(m.module, file)
Colin Crosscec81712017-07-13 14:43:27 -0700644}
Logan Chien42039712018-03-12 16:29:17 +0800645
Jaewoong Jung9d22a912019-01-23 16:27:47 -0800646// AllOutputs returns all 'BuildParams.Output's and 'BuildParams.Outputs's in their full path string forms.
647func (m TestingModule) AllOutputs() []string {
Colin Cross4c83e5c2019-02-25 14:54:28 -0800648 return allOutputs(m.module)
649}
650
651// TestingSingleton is wrapper around an android.Singleton that provides methods to find information about individual
652// ctx.Build parameters for verification in tests.
653type TestingSingleton struct {
654 singleton Singleton
655 provider testBuildProvider
656}
657
658// Singleton returns the Singleton wrapped by the TestingSingleton.
659func (s TestingSingleton) Singleton() Singleton {
660 return s.singleton
661}
662
663// MaybeRule finds a call to ctx.Build with BuildParams.Rule set to a rule with the given name. Returns an empty
664// BuildParams if no rule is found.
665func (s TestingSingleton) MaybeRule(rule string) TestingBuildParams {
Thiébaud Weksteen3600b802020-08-27 15:50:24 +0200666 r, _ := maybeBuildParamsFromRule(s.provider, rule)
667 return r
Colin Cross4c83e5c2019-02-25 14:54:28 -0800668}
669
670// Rule finds a call to ctx.Build with BuildParams.Rule set to a rule with the given name. Panics if no rule is found.
671func (s TestingSingleton) Rule(rule string) TestingBuildParams {
672 return buildParamsFromRule(s.provider, rule)
673}
674
675// MaybeDescription finds a call to ctx.Build with BuildParams.Description set to a the given string. Returns an empty
676// BuildParams if no rule is found.
677func (s TestingSingleton) MaybeDescription(desc string) TestingBuildParams {
678 return maybeBuildParamsFromDescription(s.provider, desc)
679}
680
681// Description finds a call to ctx.Build with BuildParams.Description set to a the given string. Panics if no rule is
682// found.
683func (s TestingSingleton) Description(desc string) TestingBuildParams {
684 return buildParamsFromDescription(s.provider, desc)
685}
686
687// MaybeOutput finds a call to ctx.Build with a BuildParams.Output or BuildParams.Outputs whose String() or Rel()
688// value matches the provided string. Returns an empty BuildParams if no rule is found.
689func (s TestingSingleton) MaybeOutput(file string) TestingBuildParams {
690 p, _ := maybeBuildParamsFromOutput(s.provider, file)
691 return p
692}
693
694// Output finds a call to ctx.Build with a BuildParams.Output or BuildParams.Outputs whose String() or Rel()
695// value matches the provided string. Panics if no rule is found.
696func (s TestingSingleton) Output(file string) TestingBuildParams {
697 return buildParamsFromOutput(s.provider, file)
698}
699
700// AllOutputs returns all 'BuildParams.Output's and 'BuildParams.Outputs's in their full path string forms.
701func (s TestingSingleton) AllOutputs() []string {
702 return allOutputs(s.provider)
Jaewoong Jung9d22a912019-01-23 16:27:47 -0800703}
704
Logan Chien42039712018-03-12 16:29:17 +0800705func FailIfErrored(t *testing.T, errs []error) {
706 t.Helper()
707 if len(errs) > 0 {
708 for _, err := range errs {
709 t.Error(err)
710 }
711 t.FailNow()
712 }
713}
Logan Chienee97c3e2018-03-12 16:34:26 +0800714
Paul Duffinea8a3862021-03-04 17:58:33 +0000715// Fail if no errors that matched the regular expression were found.
716//
717// Returns true if a matching error was found, false otherwise.
718func FailIfNoMatchingErrors(t *testing.T, pattern string, errs []error) bool {
Logan Chienee97c3e2018-03-12 16:34:26 +0800719 t.Helper()
720
721 matcher, err := regexp.Compile(pattern)
722 if err != nil {
Paul Duffinea8a3862021-03-04 17:58:33 +0000723 t.Fatalf("failed to compile regular expression %q because %s", pattern, err)
Logan Chienee97c3e2018-03-12 16:34:26 +0800724 }
725
726 found := false
727 for _, err := range errs {
728 if matcher.FindStringIndex(err.Error()) != nil {
729 found = true
730 break
731 }
732 }
733 if !found {
734 t.Errorf("missing the expected error %q (checked %d error(s))", pattern, len(errs))
735 for i, err := range errs {
Colin Crossaede88c2020-08-11 12:17:01 -0700736 t.Errorf("errs[%d] = %q", i, err)
Logan Chienee97c3e2018-03-12 16:34:26 +0800737 }
738 }
Paul Duffinea8a3862021-03-04 17:58:33 +0000739
740 return found
Logan Chienee97c3e2018-03-12 16:34:26 +0800741}
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700742
Paul Duffin91e38192019-08-05 15:07:57 +0100743func CheckErrorsAgainstExpectations(t *testing.T, errs []error, expectedErrorPatterns []string) {
744 t.Helper()
745
746 if expectedErrorPatterns == nil {
747 FailIfErrored(t, errs)
748 } else {
749 for _, expectedError := range expectedErrorPatterns {
750 FailIfNoMatchingErrors(t, expectedError, errs)
751 }
752 if len(errs) > len(expectedErrorPatterns) {
753 t.Errorf("additional errors found, expected %d, found %d",
754 len(expectedErrorPatterns), len(errs))
755 for i, expectedError := range expectedErrorPatterns {
756 t.Errorf("expectedErrors[%d] = %s", i, expectedError)
757 }
758 for i, err := range errs {
759 t.Errorf("errs[%d] = %s", i, err)
760 }
Paul Duffinea8a3862021-03-04 17:58:33 +0000761 t.FailNow()
Paul Duffin91e38192019-08-05 15:07:57 +0100762 }
763 }
Paul Duffin91e38192019-08-05 15:07:57 +0100764}
765
Jingwen Chencda22c92020-11-23 00:22:30 -0500766func SetKatiEnabledForTests(config Config) {
767 config.katiEnabled = true
Paul Duffin8c3fec42020-03-04 20:15:08 +0000768}
769
Colin Crossaa255532020-07-03 13:18:24 -0700770func AndroidMkEntriesForTest(t *testing.T, ctx *TestContext, mod blueprint.Module) []AndroidMkEntries {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700771 var p AndroidMkEntriesProvider
772 var ok bool
773 if p, ok = mod.(AndroidMkEntriesProvider); !ok {
Roland Levillaindfe75b32019-07-23 16:53:32 +0100774 t.Errorf("module does not implement AndroidMkEntriesProvider: " + mod.Name())
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700775 }
Jiyong Park0b0e1b92019-12-03 13:24:29 +0900776
777 entriesList := p.AndroidMkEntries()
778 for i, _ := range entriesList {
Colin Crossaa255532020-07-03 13:18:24 -0700779 entriesList[i].fillInEntries(ctx, mod)
Jiyong Park0b0e1b92019-12-03 13:24:29 +0900780 }
781 return entriesList
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700782}
Jooyung Han12df5fb2019-07-11 16:18:47 +0900783
Colin Crossaa255532020-07-03 13:18:24 -0700784func AndroidMkDataForTest(t *testing.T, ctx *TestContext, mod blueprint.Module) AndroidMkData {
Jooyung Han12df5fb2019-07-11 16:18:47 +0900785 var p AndroidMkDataProvider
786 var ok bool
787 if p, ok = mod.(AndroidMkDataProvider); !ok {
Roland Levillaindfe75b32019-07-23 16:53:32 +0100788 t.Errorf("module does not implement AndroidMkDataProvider: " + mod.Name())
Jooyung Han12df5fb2019-07-11 16:18:47 +0900789 }
790 data := p.AndroidMk()
Colin Crossaa255532020-07-03 13:18:24 -0700791 data.fillInData(ctx, mod)
Jooyung Han12df5fb2019-07-11 16:18:47 +0900792 return data
793}
Paul Duffin9b478b02019-12-10 13:41:51 +0000794
795// Normalize the path for testing.
796//
797// If the path is relative to the build directory then return the relative path
798// to avoid tests having to deal with the dynamically generated build directory.
799//
800// Otherwise, return the supplied path as it is almost certainly a source path
801// that is relative to the root of the source tree.
802//
803// The build and source paths should be distinguishable based on their contents.
804func NormalizePathForTesting(path Path) string {
Paul Duffin064b70c2020-11-02 17:32:38 +0000805 if path == nil {
806 return "<nil path>"
807 }
Paul Duffin9b478b02019-12-10 13:41:51 +0000808 p := path.String()
Paul Duffindb170e42020-12-08 17:48:25 +0000809 // Allow absolute paths to /dev/
810 if strings.HasPrefix(p, "/dev/") {
811 return p
812 }
Paul Duffin9b478b02019-12-10 13:41:51 +0000813 if w, ok := path.(WritablePath); ok {
814 rel, err := filepath.Rel(w.buildDir(), p)
815 if err != nil {
816 panic(err)
817 }
818 return rel
819 }
820 return p
821}
822
823func NormalizePathsForTesting(paths Paths) []string {
824 var result []string
825 for _, path := range paths {
826 relative := NormalizePathForTesting(path)
827 result = append(result, relative)
828 }
829 return result
830}