blob: bfea6c5148c42fef40d0dfb08e845d2c5b6e6db0 [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"
Paul Duffin25259e92021-03-07 15:45:56 +000027 "github.com/google/blueprint/proptools"
Colin Crosscec81712017-07-13 14:43:27 -070028)
29
Colin Crossae8600b2020-10-29 17:09:13 -070030func NewTestContext(config Config) *TestContext {
Jeff Gaston088e29e2017-11-29 16:47:17 -080031 namespaceExportFilter := func(namespace *Namespace) bool {
32 return true
33 }
Jeff Gastonb274ed32017-12-01 17:10:33 -080034
35 nameResolver := NewNameResolver(namespaceExportFilter)
36 ctx := &TestContext{
Colin Crossae8600b2020-10-29 17:09:13 -070037 Context: &Context{blueprint.NewContext(), config},
Jeff Gastonb274ed32017-12-01 17:10:33 -080038 NameResolver: nameResolver,
39 }
40
41 ctx.SetNameInterface(nameResolver)
Jeff Gaston088e29e2017-11-29 16:47:17 -080042
Colin Cross1b488422019-03-04 22:33:56 -080043 ctx.postDeps = append(ctx.postDeps, registerPathDepsMutator)
44
Colin Crossae8600b2020-10-29 17:09:13 -070045 ctx.SetFs(ctx.config.fs)
46 if ctx.config.mockBpList != "" {
47 ctx.SetModuleListFile(ctx.config.mockBpList)
48 }
49
Jeff Gaston088e29e2017-11-29 16:47:17 -080050 return ctx
Colin Crosscec81712017-07-13 14:43:27 -070051}
52
Paul Duffina560d5a2021-02-28 01:38:51 +000053var PrepareForTestWithArchMutator = GroupFixturePreparers(
Paul Duffin35816122021-02-24 01:49:52 +000054 // Configure architecture targets in the fixture config.
55 FixtureModifyConfig(modifyTestConfigToSupportArchMutator),
56
57 // Add the arch mutator to the context.
58 FixtureRegisterWithContext(func(ctx RegistrationContext) {
59 ctx.PreDepsMutators(registerArchMutator)
60 }),
61)
62
63var PrepareForTestWithDefaults = FixtureRegisterWithContext(func(ctx RegistrationContext) {
64 ctx.PreArchMutators(RegisterDefaultsPreArchMutators)
65})
66
67var PrepareForTestWithComponentsMutator = FixtureRegisterWithContext(func(ctx RegistrationContext) {
68 ctx.PreArchMutators(RegisterComponentsMutator)
69})
70
71var PrepareForTestWithPrebuilts = FixtureRegisterWithContext(RegisterPrebuiltMutators)
72
73var PrepareForTestWithOverrides = FixtureRegisterWithContext(func(ctx RegistrationContext) {
74 ctx.PostDepsMutators(RegisterOverridePostDepsMutators)
75})
76
Paul Duffinec3292b2021-03-09 01:01:31 +000077// Test fixture preparer that will register most java build components.
78//
79// Singletons and mutators should only be added here if they are needed for a majority of java
80// module types, otherwise they should be added under a separate preparer to allow them to be
81// selected only when needed to reduce test execution time.
82//
83// Module types do not have much of an overhead unless they are used so this should include as many
84// module types as possible. The exceptions are those module types that require mutators and/or
85// singletons in order to function in which case they should be kept together in a separate
86// preparer.
87//
88// The mutators in this group were chosen because they are needed by the vast majority of tests.
89var PrepareForTestWithAndroidBuildComponents = GroupFixturePreparers(
Paul Duffin530483c2021-03-07 13:20:38 +000090 // Sorted alphabetically as the actual order does not matter as tests automatically enforce the
91 // correct order.
Paul Duffin35816122021-02-24 01:49:52 +000092 PrepareForTestWithArchMutator,
Paul Duffin35816122021-02-24 01:49:52 +000093 PrepareForTestWithComponentsMutator,
Paul Duffin530483c2021-03-07 13:20:38 +000094 PrepareForTestWithDefaults,
Paul Duffin35816122021-02-24 01:49:52 +000095 PrepareForTestWithFilegroup,
Paul Duffin530483c2021-03-07 13:20:38 +000096 PrepareForTestWithOverrides,
97 PrepareForTestWithPackageModule,
98 PrepareForTestWithPrebuilts,
99 PrepareForTestWithVisibility,
Paul Duffin35816122021-02-24 01:49:52 +0000100)
101
Paul Duffinec3292b2021-03-09 01:01:31 +0000102// Prepares an integration test with all build components from the android package.
103//
104// This should only be used by tests that want to run with as much of the build enabled as possible.
105var PrepareForIntegrationTestWithAndroid = GroupFixturePreparers(
106 PrepareForTestWithAndroidBuildComponents,
107)
108
Paul Duffin25259e92021-03-07 15:45:56 +0000109// Prepares a test that may be missing dependencies by setting allow_missing_dependencies to
110// true.
111var PrepareForTestWithAllowMissingDependencies = GroupFixturePreparers(
112 FixtureModifyProductVariables(func(variables FixtureProductVariables) {
113 variables.Allow_missing_dependencies = proptools.BoolPtr(true)
114 }),
115 FixtureModifyContext(func(ctx *TestContext) {
116 ctx.SetAllowMissingDependencies(true)
117 }),
118)
119
Paul Duffin76e5c8a2021-03-20 14:19:46 +0000120// Prepares a test that disallows non-existent paths.
121var PrepareForTestDisallowNonExistentPaths = FixtureModifyConfig(func(config Config) {
122 config.TestAllowNonExistentPaths = false
123})
124
Colin Crossae8600b2020-10-29 17:09:13 -0700125func NewTestArchContext(config Config) *TestContext {
126 ctx := NewTestContext(config)
Colin Crossae4c6182017-09-15 17:33:55 -0700127 ctx.preDeps = append(ctx.preDeps, registerArchMutator)
128 return ctx
129}
130
Colin Crosscec81712017-07-13 14:43:27 -0700131type TestContext struct {
Colin Cross4c83e5c2019-02-25 14:54:28 -0800132 *Context
Liz Kammer356f7d42021-01-26 09:18:53 -0500133 preArch, preDeps, postDeps, finalDeps []RegisterMutatorFunc
134 bp2buildPreArch, bp2buildDeps, bp2buildMutators []RegisterMutatorFunc
135 NameResolver *NameResolver
Paul Duffin281deb22021-03-06 20:29:19 +0000136
Paul Duffind182fb32021-03-07 12:24:44 +0000137 // The list of pre-singletons and singletons registered for the test.
138 preSingletons, singletons sortableComponents
139
Paul Duffin41d77c72021-03-07 12:23:48 +0000140 // The order in which the pre-singletons, mutators and singletons will be run in this test
141 // context; for debugging.
142 preSingletonOrder, mutatorOrder, singletonOrder []string
Colin Crosscec81712017-07-13 14:43:27 -0700143}
144
145func (ctx *TestContext) PreArchMutators(f RegisterMutatorFunc) {
146 ctx.preArch = append(ctx.preArch, f)
147}
148
Paul Duffina80ef842020-01-14 12:09:36 +0000149func (ctx *TestContext) HardCodedPreArchMutators(f RegisterMutatorFunc) {
150 // Register mutator function as normal for testing.
151 ctx.PreArchMutators(f)
152}
153
Colin Crosscec81712017-07-13 14:43:27 -0700154func (ctx *TestContext) PreDepsMutators(f RegisterMutatorFunc) {
155 ctx.preDeps = append(ctx.preDeps, f)
156}
157
158func (ctx *TestContext) PostDepsMutators(f RegisterMutatorFunc) {
159 ctx.postDeps = append(ctx.postDeps, f)
160}
161
Martin Stjernholm710ec3a2020-01-16 15:12:04 +0000162func (ctx *TestContext) FinalDepsMutators(f RegisterMutatorFunc) {
163 ctx.finalDeps = append(ctx.finalDeps, f)
164}
165
Jingwen Chen12b4c272021-03-10 02:05:59 -0500166func (ctx *TestContext) RegisterBp2BuildConfig(config Bp2BuildConfig) {
167 ctx.config.bp2buildPackageConfig = config
168}
169
Jingwen Chen73850672020-12-14 08:25:34 -0500170// RegisterBp2BuildMutator registers a BazelTargetModule mutator for converting a module
171// type to the equivalent Bazel target.
172func (ctx *TestContext) RegisterBp2BuildMutator(moduleType string, m func(TopDownMutatorContext)) {
Jingwen Chen73850672020-12-14 08:25:34 -0500173 f := func(ctx RegisterMutatorsContext) {
Liz Kammer356f7d42021-01-26 09:18:53 -0500174 ctx.TopDown(moduleType, m)
Jingwen Chen73850672020-12-14 08:25:34 -0500175 }
Jingwen Chen12b4c272021-03-10 02:05:59 -0500176 ctx.config.bp2buildModuleTypeConfig[moduleType] = true
Jingwen Chena42d6412021-01-26 21:57:27 -0500177 ctx.bp2buildMutators = append(ctx.bp2buildMutators, f)
Jingwen Chen73850672020-12-14 08:25:34 -0500178}
179
Liz Kammer356f7d42021-01-26 09:18:53 -0500180// PreArchBp2BuildMutators adds mutators to be register for converting Android Blueprint modules
181// into Bazel BUILD targets that should run prior to deps and conversion.
182func (ctx *TestContext) PreArchBp2BuildMutators(f RegisterMutatorFunc) {
183 ctx.bp2buildPreArch = append(ctx.bp2buildPreArch, f)
184}
185
186// DepsBp2BuildMutators adds mutators to be register for converting Android Blueprint modules into
187// Bazel BUILD targets that should run prior to conversion to resolve dependencies.
188func (ctx *TestContext) DepsBp2BuildMutators(f RegisterMutatorFunc) {
189 ctx.bp2buildDeps = append(ctx.bp2buildDeps, f)
190}
191
Paul Duffin281deb22021-03-06 20:29:19 +0000192// registeredComponentOrder defines the order in which a sortableComponent type is registered at
193// runtime and provides support for reordering the components registered for a test in the same
194// way.
195type registeredComponentOrder struct {
196 // The name of the component type, used for error messages.
197 componentType string
198
199 // The names of the registered components in the order in which they were registered.
200 namesInOrder []string
201
202 // Maps from the component name to its position in the runtime ordering.
203 namesToIndex map[string]int
204
205 // A function that defines the order between two named components that can be used to sort a slice
206 // of component names into the same order as they appear in namesInOrder.
207 less func(string, string) bool
208}
209
210// registeredComponentOrderFromExistingOrder takes an existing slice of sortableComponents and
211// creates a registeredComponentOrder that contains a less function that can be used to sort a
212// subset of that list of names so it is in the same order as the original sortableComponents.
213func registeredComponentOrderFromExistingOrder(componentType string, existingOrder sortableComponents) registeredComponentOrder {
214 // Only the names from the existing order are needed for this so create a list of component names
215 // in the correct order.
216 namesInOrder := componentsToNames(existingOrder)
217
218 // Populate the map from name to position in the list.
219 nameToIndex := make(map[string]int)
220 for i, n := range namesInOrder {
221 nameToIndex[n] = i
222 }
223
224 // A function to use to map from a name to an index in the original order.
225 indexOf := func(name string) int {
226 index, ok := nameToIndex[name]
227 if !ok {
228 // Should never happen as tests that use components that are not known at runtime do not sort
229 // so should never use this function.
230 panic(fmt.Errorf("internal error: unknown %s %q should be one of %s", componentType, name, strings.Join(namesInOrder, ", ")))
231 }
232 return index
233 }
234
235 // The less function.
236 less := func(n1, n2 string) bool {
237 i1 := indexOf(n1)
238 i2 := indexOf(n2)
239 return i1 < i2
240 }
241
242 return registeredComponentOrder{
243 componentType: componentType,
244 namesInOrder: namesInOrder,
245 namesToIndex: nameToIndex,
246 less: less,
247 }
248}
249
250// componentsToNames maps from the slice of components to a slice of their names.
251func componentsToNames(components sortableComponents) []string {
252 names := make([]string, len(components))
253 for i, c := range components {
254 names[i] = c.componentName()
255 }
256 return names
257}
258
259// enforceOrdering enforces the supplied components are in the same order as is defined in this
260// object.
261//
262// If the supplied components contains any components that are not registered at runtime, i.e. test
263// specific components, then it is impossible to sort them into an order that both matches the
264// runtime and also preserves the implicit ordering defined in the test. In that case it will not
265// sort the components, instead it will just check that the components are in the correct order.
266//
267// Otherwise, this will sort the supplied components in place.
268func (o *registeredComponentOrder) enforceOrdering(components sortableComponents) {
269 // Check to see if the list of components contains any components that are
270 // not registered at runtime.
271 var unknownComponents []string
272 testOrder := componentsToNames(components)
273 for _, name := range testOrder {
274 if _, ok := o.namesToIndex[name]; !ok {
275 unknownComponents = append(unknownComponents, name)
276 break
277 }
278 }
279
280 // If the slice contains some unknown components then it is not possible to
281 // sort them into an order that matches the runtime while also preserving the
282 // order expected from the test, so in that case don't sort just check that
283 // the order of the known mutators does match.
284 if len(unknownComponents) > 0 {
285 // Check order.
286 o.checkTestOrder(testOrder, unknownComponents)
287 } else {
288 // Sort the components.
289 sort.Slice(components, func(i, j int) bool {
290 n1 := components[i].componentName()
291 n2 := components[j].componentName()
292 return o.less(n1, n2)
293 })
294 }
295}
296
297// checkTestOrder checks that the supplied testOrder matches the one defined by this object,
298// panicking if it does not.
299func (o *registeredComponentOrder) checkTestOrder(testOrder []string, unknownComponents []string) {
300 lastMatchingTest := -1
301 matchCount := 0
302 // Take a copy of the runtime order as it is modified during the comparison.
303 runtimeOrder := append([]string(nil), o.namesInOrder...)
304 componentType := o.componentType
305 for i, j := 0, 0; i < len(testOrder) && j < len(runtimeOrder); {
306 test := testOrder[i]
307 runtime := runtimeOrder[j]
308
309 if test == runtime {
310 testOrder[i] = test + fmt.Sprintf(" <-- matched with runtime %s %d", componentType, j)
311 runtimeOrder[j] = runtime + fmt.Sprintf(" <-- matched with test %s %d", componentType, i)
312 lastMatchingTest = i
313 i += 1
314 j += 1
315 matchCount += 1
316 } else if _, ok := o.namesToIndex[test]; !ok {
317 // The test component is not registered globally so assume it is the correct place, treat it
318 // as having matched and skip it.
319 i += 1
320 matchCount += 1
321 } else {
322 // Assume that the test list is in the same order as the runtime list but the runtime list
323 // contains some components that are not present in the tests. So, skip the runtime component
324 // to try and find the next one that matches the current test component.
325 j += 1
326 }
327 }
328
329 // If every item in the test order was either test specific or matched one in the runtime then
330 // it is in the correct order. Otherwise, it was not so fail.
331 if matchCount != len(testOrder) {
332 // The test component names were not all matched with a runtime component name so there must
333 // either be a component present in the test that is not present in the runtime or they must be
334 // in the wrong order.
335 testOrder[lastMatchingTest+1] = testOrder[lastMatchingTest+1] + " <--- unmatched"
336 panic(fmt.Errorf("the tests uses test specific components %q and so cannot be automatically sorted."+
337 " Unfortunately it uses %s components in the wrong order.\n"+
338 "test order:\n %s\n"+
339 "runtime order\n %s\n",
340 SortedUniqueStrings(unknownComponents),
341 componentType,
342 strings.Join(testOrder, "\n "),
343 strings.Join(runtimeOrder, "\n ")))
344 }
345}
346
347// registrationSorter encapsulates the information needed to ensure that the test mutators are
348// registered, and thereby executed, in the same order as they are at runtime.
349//
350// It MUST be populated lazily AFTER all package initialization has been done otherwise it will
351// only define the order for a subset of all the registered build components that are available for
352// the packages being tested.
353//
354// e.g if this is initialized during say the cc package initialization then any tests run in the
355// java package will not sort build components registered by the java package's init() functions.
356type registrationSorter struct {
357 // Used to ensure that this is only created once.
358 once sync.Once
359
Paul Duffin41d77c72021-03-07 12:23:48 +0000360 // The order of pre-singletons
361 preSingletonOrder registeredComponentOrder
362
Paul Duffin281deb22021-03-06 20:29:19 +0000363 // The order of mutators
364 mutatorOrder registeredComponentOrder
Paul Duffin41d77c72021-03-07 12:23:48 +0000365
366 // The order of singletons
367 singletonOrder registeredComponentOrder
Paul Duffin281deb22021-03-06 20:29:19 +0000368}
369
370// populate initializes this structure from globally registered build components.
371//
372// Only the first call has any effect.
373func (s *registrationSorter) populate() {
374 s.once.Do(func() {
Paul Duffin41d77c72021-03-07 12:23:48 +0000375 // Create an ordering from the globally registered pre-singletons.
376 s.preSingletonOrder = registeredComponentOrderFromExistingOrder("pre-singleton", preSingletons)
377
Paul Duffin281deb22021-03-06 20:29:19 +0000378 // Created an ordering from the globally registered mutators.
379 globallyRegisteredMutators := collateGloballyRegisteredMutators()
380 s.mutatorOrder = registeredComponentOrderFromExistingOrder("mutator", globallyRegisteredMutators)
Paul Duffin41d77c72021-03-07 12:23:48 +0000381
382 // Create an ordering from the globally registered singletons.
383 globallyRegisteredSingletons := collateGloballyRegisteredSingletons()
384 s.singletonOrder = registeredComponentOrderFromExistingOrder("singleton", globallyRegisteredSingletons)
Paul Duffin281deb22021-03-06 20:29:19 +0000385 })
386}
387
388// Provides support for enforcing the same order in which build components are registered globally
389// to the order in which they are registered during tests.
390//
391// MUST only be accessed via the globallyRegisteredComponentsOrder func.
392var globalRegistrationSorter registrationSorter
393
394// globallyRegisteredComponentsOrder returns the globalRegistrationSorter after ensuring it is
395// correctly populated.
396func globallyRegisteredComponentsOrder() *registrationSorter {
397 globalRegistrationSorter.populate()
398 return &globalRegistrationSorter
399}
400
Colin Crossae8600b2020-10-29 17:09:13 -0700401func (ctx *TestContext) Register() {
Paul Duffin281deb22021-03-06 20:29:19 +0000402 globalOrder := globallyRegisteredComponentsOrder()
403
Paul Duffin41d77c72021-03-07 12:23:48 +0000404 // Ensure that the pre-singletons used in the test are in the same order as they are used at
405 // runtime.
406 globalOrder.preSingletonOrder.enforceOrdering(ctx.preSingletons)
Paul Duffind182fb32021-03-07 12:24:44 +0000407 ctx.preSingletons.registerAll(ctx.Context)
408
Paul Duffinc05b0342021-03-06 13:28:13 +0000409 mutators := collateRegisteredMutators(ctx.preArch, ctx.preDeps, ctx.postDeps, ctx.finalDeps)
Paul Duffin281deb22021-03-06 20:29:19 +0000410 // Ensure that the mutators used in the test are in the same order as they are used at runtime.
411 globalOrder.mutatorOrder.enforceOrdering(mutators)
Paul Duffinc05b0342021-03-06 13:28:13 +0000412 mutators.registerAll(ctx.Context)
Colin Crosscec81712017-07-13 14:43:27 -0700413
Paul Duffin41d77c72021-03-07 12:23:48 +0000414 // Ensure that the singletons used in the test are in the same order as they are used at runtime.
415 globalOrder.singletonOrder.enforceOrdering(ctx.singletons)
Paul Duffind182fb32021-03-07 12:24:44 +0000416 ctx.singletons.registerAll(ctx.Context)
417
Paul Duffin41d77c72021-03-07 12:23:48 +0000418 // Save the sorted components order away to make them easy to access while debugging.
Paul Duffinf5de6682021-03-08 23:42:10 +0000419 ctx.preSingletonOrder = componentsToNames(preSingletons)
420 ctx.mutatorOrder = componentsToNames(mutators)
421 ctx.singletonOrder = componentsToNames(singletons)
Colin Cross31a738b2019-12-30 18:45:15 -0800422}
423
Jingwen Chen73850672020-12-14 08:25:34 -0500424// RegisterForBazelConversion prepares a test context for bp2build conversion.
425func (ctx *TestContext) RegisterForBazelConversion() {
Paul Duffin1d2d42f2021-03-06 20:08:12 +0000426 RegisterMutatorsForBazelConversion(ctx.Context, ctx.bp2buildPreArch, ctx.bp2buildDeps, ctx.bp2buildMutators)
Jingwen Chen73850672020-12-14 08:25:34 -0500427}
428
Colin Cross31a738b2019-12-30 18:45:15 -0800429func (ctx *TestContext) ParseFileList(rootDir string, filePaths []string) (deps []string, errs []error) {
430 // This function adapts the old style ParseFileList calls that are spread throughout the tests
431 // to the new style that takes a config.
432 return ctx.Context.ParseFileList(rootDir, filePaths, ctx.config)
433}
434
435func (ctx *TestContext) ParseBlueprintsFiles(rootDir string) (deps []string, errs []error) {
436 // This function adapts the old style ParseBlueprintsFiles calls that are spread throughout the
437 // tests to the new style that takes a config.
438 return ctx.Context.ParseBlueprintsFiles(rootDir, ctx.config)
Colin Cross4b49b762019-11-22 15:25:03 -0800439}
440
441func (ctx *TestContext) RegisterModuleType(name string, factory ModuleFactory) {
442 ctx.Context.RegisterModuleType(name, ModuleFactoryAdaptor(factory))
443}
444
Colin Cross9aed5bc2020-12-28 15:15:34 -0800445func (ctx *TestContext) RegisterSingletonModuleType(name string, factory SingletonModuleFactory) {
446 s, m := SingletonModuleFactoryAdaptor(name, factory)
447 ctx.RegisterSingletonType(name, s)
448 ctx.RegisterModuleType(name, m)
449}
450
Colin Cross4b49b762019-11-22 15:25:03 -0800451func (ctx *TestContext) RegisterSingletonType(name string, factory SingletonFactory) {
Paul Duffind182fb32021-03-07 12:24:44 +0000452 ctx.singletons = append(ctx.singletons, newSingleton(name, factory))
Colin Crosscec81712017-07-13 14:43:27 -0700453}
454
Paul Duffineafc16b2021-02-24 01:43:18 +0000455func (ctx *TestContext) RegisterPreSingletonType(name string, factory SingletonFactory) {
Paul Duffind182fb32021-03-07 12:24:44 +0000456 ctx.preSingletons = append(ctx.preSingletons, newPreSingleton(name, factory))
Paul Duffineafc16b2021-02-24 01:43:18 +0000457}
458
Colin Crosscec81712017-07-13 14:43:27 -0700459func (ctx *TestContext) ModuleForTests(name, variant string) TestingModule {
460 var module Module
461 ctx.VisitAllModules(func(m blueprint.Module) {
462 if ctx.ModuleName(m) == name && ctx.ModuleSubDir(m) == variant {
463 module = m.(Module)
464 }
465 })
466
467 if module == nil {
Jeff Gaston294356f2017-09-27 17:05:30 -0700468 // find all the modules that do exist
Colin Crossbeae6ec2020-08-11 12:02:11 -0700469 var allModuleNames []string
470 var allVariants []string
Jeff Gaston294356f2017-09-27 17:05:30 -0700471 ctx.VisitAllModules(func(m blueprint.Module) {
Colin Crossbeae6ec2020-08-11 12:02:11 -0700472 allModuleNames = append(allModuleNames, ctx.ModuleName(m))
473 if ctx.ModuleName(m) == name {
474 allVariants = append(allVariants, ctx.ModuleSubDir(m))
475 }
Jeff Gaston294356f2017-09-27 17:05:30 -0700476 })
Martin Stjernholm4c021242020-05-13 01:13:50 +0100477 sort.Strings(allModuleNames)
Colin Crossbeae6ec2020-08-11 12:02:11 -0700478 sort.Strings(allVariants)
Jeff Gaston294356f2017-09-27 17:05:30 -0700479
Colin Crossbeae6ec2020-08-11 12:02:11 -0700480 if len(allVariants) == 0 {
481 panic(fmt.Errorf("failed to find module %q. All modules:\n %s",
482 name, strings.Join(allModuleNames, "\n ")))
483 } else {
484 panic(fmt.Errorf("failed to find module %q variant %q. All variants:\n %s",
485 name, variant, strings.Join(allVariants, "\n ")))
486 }
Colin Crosscec81712017-07-13 14:43:27 -0700487 }
488
Paul Duffin709e0e32021-03-22 10:09:02 +0000489 return newTestingModule(ctx.config, module)
Colin Crosscec81712017-07-13 14:43:27 -0700490}
491
Jiyong Park37b25202018-07-11 10:49:27 +0900492func (ctx *TestContext) ModuleVariantsForTests(name string) []string {
493 var variants []string
494 ctx.VisitAllModules(func(m blueprint.Module) {
495 if ctx.ModuleName(m) == name {
496 variants = append(variants, ctx.ModuleSubDir(m))
497 }
498 })
499 return variants
500}
501
Colin Cross4c83e5c2019-02-25 14:54:28 -0800502// SingletonForTests returns a TestingSingleton for the singleton registered with the given name.
503func (ctx *TestContext) SingletonForTests(name string) TestingSingleton {
504 allSingletonNames := []string{}
505 for _, s := range ctx.Singletons() {
506 n := ctx.SingletonName(s)
507 if n == name {
508 return TestingSingleton{
Paul Duffin709e0e32021-03-22 10:09:02 +0000509 baseTestingComponent: newBaseTestingComponent(ctx.config, s.(testBuildProvider)),
Paul Duffin31a22882021-03-22 09:29:00 +0000510 singleton: s.(*singletonAdaptor).Singleton,
Colin Cross4c83e5c2019-02-25 14:54:28 -0800511 }
512 }
513 allSingletonNames = append(allSingletonNames, n)
514 }
515
516 panic(fmt.Errorf("failed to find singleton %q."+
517 "\nall singletons: %v", name, allSingletonNames))
518}
519
Colin Crossaa255532020-07-03 13:18:24 -0700520func (ctx *TestContext) Config() Config {
521 return ctx.config
522}
523
Colin Cross4c83e5c2019-02-25 14:54:28 -0800524type testBuildProvider interface {
525 BuildParamsForTests() []BuildParams
526 RuleParamsForTests() map[blueprint.Rule]blueprint.RuleParams
527}
528
529type TestingBuildParams struct {
530 BuildParams
531 RuleParams blueprint.RuleParams
Paul Duffin709e0e32021-03-22 10:09:02 +0000532
533 config Config
534}
535
536// RelativeToTop creates a new instance of this which has had any usages of the current test's
537// temporary and test specific build directory replaced with a path relative to the notional top.
538//
539// The parts of this structure which are changed are:
540// * BuildParams
541// * Args
Paul Duffinbbb0f8f2021-03-24 10:34:52 +0000542// * All Path, Paths, WritablePath and WritablePaths fields.
Paul Duffin709e0e32021-03-22 10:09:02 +0000543//
544// * RuleParams
545// * Command
546// * Depfile
547// * Rspfile
548// * RspfileContent
549// * SymlinkOutputs
550// * CommandDeps
551// * CommandOrderOnly
552//
553// See PathRelativeToTop for more details.
554func (p TestingBuildParams) RelativeToTop() TestingBuildParams {
555 // If this is not a valid params then just return it back. That will make it easy to use with the
556 // Maybe...() methods.
557 if p.Rule == nil {
558 return p
559 }
560 if p.config.config == nil {
561 panic("cannot call RelativeToTop() on a TestingBuildParams previously returned by RelativeToTop()")
562 }
563 // Take a copy of the build params and replace any args that contains test specific temporary
564 // paths with paths relative to the top.
565 bparams := p.BuildParams
Paul Duffinbbb0f8f2021-03-24 10:34:52 +0000566 bparams.Depfile = normalizeWritablePathRelativeToTop(bparams.Depfile)
567 bparams.Output = normalizeWritablePathRelativeToTop(bparams.Output)
568 bparams.Outputs = bparams.Outputs.RelativeToTop()
569 bparams.SymlinkOutput = normalizeWritablePathRelativeToTop(bparams.SymlinkOutput)
570 bparams.SymlinkOutputs = bparams.SymlinkOutputs.RelativeToTop()
571 bparams.ImplicitOutput = normalizeWritablePathRelativeToTop(bparams.ImplicitOutput)
572 bparams.ImplicitOutputs = bparams.ImplicitOutputs.RelativeToTop()
573 bparams.Input = normalizePathRelativeToTop(bparams.Input)
574 bparams.Inputs = bparams.Inputs.RelativeToTop()
575 bparams.Implicit = normalizePathRelativeToTop(bparams.Implicit)
576 bparams.Implicits = bparams.Implicits.RelativeToTop()
577 bparams.OrderOnly = bparams.OrderOnly.RelativeToTop()
578 bparams.Validation = normalizePathRelativeToTop(bparams.Validation)
579 bparams.Validations = bparams.Validations.RelativeToTop()
Paul Duffin709e0e32021-03-22 10:09:02 +0000580 bparams.Args = normalizeStringMapRelativeToTop(p.config, bparams.Args)
581
582 // Ditto for any fields in the RuleParams.
583 rparams := p.RuleParams
584 rparams.Command = normalizeStringRelativeToTop(p.config, rparams.Command)
585 rparams.Depfile = normalizeStringRelativeToTop(p.config, rparams.Depfile)
586 rparams.Rspfile = normalizeStringRelativeToTop(p.config, rparams.Rspfile)
587 rparams.RspfileContent = normalizeStringRelativeToTop(p.config, rparams.RspfileContent)
588 rparams.SymlinkOutputs = normalizeStringArrayRelativeToTop(p.config, rparams.SymlinkOutputs)
589 rparams.CommandDeps = normalizeStringArrayRelativeToTop(p.config, rparams.CommandDeps)
590 rparams.CommandOrderOnly = normalizeStringArrayRelativeToTop(p.config, rparams.CommandOrderOnly)
591
592 return TestingBuildParams{
593 BuildParams: bparams,
594 RuleParams: rparams,
595 }
Colin Cross4c83e5c2019-02-25 14:54:28 -0800596}
597
Paul Duffinbbb0f8f2021-03-24 10:34:52 +0000598func normalizeWritablePathRelativeToTop(path WritablePath) WritablePath {
599 if path == nil {
600 return nil
601 }
602 return path.RelativeToTop().(WritablePath)
603}
604
605func normalizePathRelativeToTop(path Path) Path {
606 if path == nil {
607 return nil
608 }
609 return path.RelativeToTop()
610}
611
Paul Duffin0eda26b92021-03-22 09:34:29 +0000612// baseTestingComponent provides functionality common to both TestingModule and TestingSingleton.
613type baseTestingComponent struct {
Paul Duffin709e0e32021-03-22 10:09:02 +0000614 config Config
Paul Duffin0eda26b92021-03-22 09:34:29 +0000615 provider testBuildProvider
616}
617
Paul Duffin709e0e32021-03-22 10:09:02 +0000618func newBaseTestingComponent(config Config, provider testBuildProvider) baseTestingComponent {
619 return baseTestingComponent{config, provider}
620}
621
622// A function that will normalize a string containing paths, e.g. ninja command, by replacing
623// any references to the test specific temporary build directory that changes with each run to a
624// fixed path relative to a notional top directory.
625//
626// This is similar to StringPathRelativeToTop except that assumes the string is a single path
627// containing at most one instance of the temporary build directory at the start of the path while
628// this assumes that there can be any number at any position.
629func normalizeStringRelativeToTop(config Config, s string) string {
630 // The buildDir usually looks something like: /tmp/testFoo2345/001
631 //
632 // Replace any usage of the buildDir with out/soong, e.g. replace "/tmp/testFoo2345/001" with
633 // "out/soong".
634 outSoongDir := filepath.Clean(config.buildDir)
635 re := regexp.MustCompile(`\Q` + outSoongDir + `\E\b`)
636 s = re.ReplaceAllString(s, "out/soong")
637
638 // Replace any usage of the buildDir/.. with out, e.g. replace "/tmp/testFoo2345" with
639 // "out". This must come after the previous replacement otherwise this would replace
640 // "/tmp/testFoo2345/001" with "out/001" instead of "out/soong".
641 outDir := filepath.Dir(outSoongDir)
642 re = regexp.MustCompile(`\Q` + outDir + `\E\b`)
643 s = re.ReplaceAllString(s, "out")
644
645 return s
646}
647
648// normalizeStringArrayRelativeToTop creates a new slice constructed by applying
649// normalizeStringRelativeToTop to each item in the slice.
650func normalizeStringArrayRelativeToTop(config Config, slice []string) []string {
651 newSlice := make([]string, len(slice))
652 for i, s := range slice {
653 newSlice[i] = normalizeStringRelativeToTop(config, s)
654 }
655 return newSlice
656}
657
658// normalizeStringMapRelativeToTop creates a new map constructed by applying
659// normalizeStringRelativeToTop to each value in the map.
660func normalizeStringMapRelativeToTop(config Config, m map[string]string) map[string]string {
661 newMap := map[string]string{}
662 for k, v := range m {
663 newMap[k] = normalizeStringRelativeToTop(config, v)
664 }
665 return newMap
Paul Duffin0eda26b92021-03-22 09:34:29 +0000666}
667
668func (b baseTestingComponent) newTestingBuildParams(bparams BuildParams) TestingBuildParams {
Colin Cross4c83e5c2019-02-25 14:54:28 -0800669 return TestingBuildParams{
Paul Duffin709e0e32021-03-22 10:09:02 +0000670 config: b.config,
Colin Cross4c83e5c2019-02-25 14:54:28 -0800671 BuildParams: bparams,
Paul Duffin0eda26b92021-03-22 09:34:29 +0000672 RuleParams: b.provider.RuleParamsForTests()[bparams.Rule],
Colin Cross4c83e5c2019-02-25 14:54:28 -0800673 }
674}
675
Paul Duffin0eda26b92021-03-22 09:34:29 +0000676func (b baseTestingComponent) maybeBuildParamsFromRule(rule string) (TestingBuildParams, []string) {
Thiébaud Weksteen3600b802020-08-27 15:50:24 +0200677 var searchedRules []string
Paul Duffin0eda26b92021-03-22 09:34:29 +0000678 for _, p := range b.provider.BuildParamsForTests() {
Thiébaud Weksteen3600b802020-08-27 15:50:24 +0200679 searchedRules = append(searchedRules, p.Rule.String())
Colin Cross4c83e5c2019-02-25 14:54:28 -0800680 if strings.Contains(p.Rule.String(), rule) {
Paul Duffin0eda26b92021-03-22 09:34:29 +0000681 return b.newTestingBuildParams(p), searchedRules
Colin Cross4c83e5c2019-02-25 14:54:28 -0800682 }
683 }
Thiébaud Weksteen3600b802020-08-27 15:50:24 +0200684 return TestingBuildParams{}, searchedRules
Colin Cross4c83e5c2019-02-25 14:54:28 -0800685}
686
Paul Duffin0eda26b92021-03-22 09:34:29 +0000687func (b baseTestingComponent) buildParamsFromRule(rule string) TestingBuildParams {
688 p, searchRules := b.maybeBuildParamsFromRule(rule)
Colin Cross4c83e5c2019-02-25 14:54:28 -0800689 if p.Rule == nil {
Thiébaud Weksteen3600b802020-08-27 15:50:24 +0200690 panic(fmt.Errorf("couldn't find rule %q.\nall rules: %v", rule, searchRules))
Colin Cross4c83e5c2019-02-25 14:54:28 -0800691 }
692 return p
693}
694
Paul Duffin0eda26b92021-03-22 09:34:29 +0000695func (b baseTestingComponent) maybeBuildParamsFromDescription(desc string) TestingBuildParams {
696 for _, p := range b.provider.BuildParamsForTests() {
Colin Crossb88b3c52019-06-10 15:15:17 -0700697 if strings.Contains(p.Description, desc) {
Paul Duffin0eda26b92021-03-22 09:34:29 +0000698 return b.newTestingBuildParams(p)
Colin Cross4c83e5c2019-02-25 14:54:28 -0800699 }
700 }
701 return TestingBuildParams{}
702}
703
Paul Duffin0eda26b92021-03-22 09:34:29 +0000704func (b baseTestingComponent) buildParamsFromDescription(desc string) TestingBuildParams {
705 p := b.maybeBuildParamsFromDescription(desc)
Colin Cross4c83e5c2019-02-25 14:54:28 -0800706 if p.Rule == nil {
707 panic(fmt.Errorf("couldn't find description %q", desc))
708 }
709 return p
710}
711
Paul Duffin0eda26b92021-03-22 09:34:29 +0000712func (b baseTestingComponent) maybeBuildParamsFromOutput(file string) (TestingBuildParams, []string) {
Colin Cross4c83e5c2019-02-25 14:54:28 -0800713 var searchedOutputs []string
Paul Duffin0eda26b92021-03-22 09:34:29 +0000714 for _, p := range b.provider.BuildParamsForTests() {
Colin Cross4c83e5c2019-02-25 14:54:28 -0800715 outputs := append(WritablePaths(nil), p.Outputs...)
Colin Cross1d2cf042019-03-29 15:33:06 -0700716 outputs = append(outputs, p.ImplicitOutputs...)
Colin Cross4c83e5c2019-02-25 14:54:28 -0800717 if p.Output != nil {
718 outputs = append(outputs, p.Output)
719 }
720 for _, f := range outputs {
Paul Duffin4e6e35c2021-03-22 11:34:57 +0000721 if f.String() == file || f.Rel() == file || PathRelativeToTop(f) == file {
Paul Duffin0eda26b92021-03-22 09:34:29 +0000722 return b.newTestingBuildParams(p), nil
Colin Cross4c83e5c2019-02-25 14:54:28 -0800723 }
724 searchedOutputs = append(searchedOutputs, f.Rel())
725 }
726 }
727 return TestingBuildParams{}, searchedOutputs
728}
729
Paul Duffin0eda26b92021-03-22 09:34:29 +0000730func (b baseTestingComponent) buildParamsFromOutput(file string) TestingBuildParams {
731 p, searchedOutputs := b.maybeBuildParamsFromOutput(file)
Colin Cross4c83e5c2019-02-25 14:54:28 -0800732 if p.Rule == nil {
Paul Duffin4e6e35c2021-03-22 11:34:57 +0000733 panic(fmt.Errorf("couldn't find output %q.\nall outputs:\n %s\n",
734 file, strings.Join(searchedOutputs, "\n ")))
Colin Cross4c83e5c2019-02-25 14:54:28 -0800735 }
736 return p
737}
738
Paul Duffin0eda26b92021-03-22 09:34:29 +0000739func (b baseTestingComponent) allOutputs() []string {
Colin Cross4c83e5c2019-02-25 14:54:28 -0800740 var outputFullPaths []string
Paul Duffin0eda26b92021-03-22 09:34:29 +0000741 for _, p := range b.provider.BuildParamsForTests() {
Colin Cross4c83e5c2019-02-25 14:54:28 -0800742 outputs := append(WritablePaths(nil), p.Outputs...)
Colin Cross1d2cf042019-03-29 15:33:06 -0700743 outputs = append(outputs, p.ImplicitOutputs...)
Colin Cross4c83e5c2019-02-25 14:54:28 -0800744 if p.Output != nil {
745 outputs = append(outputs, p.Output)
746 }
747 outputFullPaths = append(outputFullPaths, outputs.Strings()...)
748 }
749 return outputFullPaths
750}
751
Paul Duffin31a22882021-03-22 09:29:00 +0000752// MaybeRule finds a call to ctx.Build with BuildParams.Rule set to a rule with the given name. Returns an empty
753// BuildParams if no rule is found.
754func (b baseTestingComponent) MaybeRule(rule string) TestingBuildParams {
Paul Duffin0eda26b92021-03-22 09:34:29 +0000755 r, _ := b.maybeBuildParamsFromRule(rule)
Paul Duffin31a22882021-03-22 09:29:00 +0000756 return r
757}
758
759// Rule finds a call to ctx.Build with BuildParams.Rule set to a rule with the given name. Panics if no rule is found.
760func (b baseTestingComponent) Rule(rule string) TestingBuildParams {
Paul Duffin0eda26b92021-03-22 09:34:29 +0000761 return b.buildParamsFromRule(rule)
Paul Duffin31a22882021-03-22 09:29:00 +0000762}
763
764// MaybeDescription finds a call to ctx.Build with BuildParams.Description set to a the given string. Returns an empty
765// BuildParams if no rule is found.
766func (b baseTestingComponent) MaybeDescription(desc string) TestingBuildParams {
Paul Duffin0eda26b92021-03-22 09:34:29 +0000767 return b.maybeBuildParamsFromDescription(desc)
Paul Duffin31a22882021-03-22 09:29:00 +0000768}
769
770// Description finds a call to ctx.Build with BuildParams.Description set to a the given string. Panics if no rule is
771// found.
772func (b baseTestingComponent) Description(desc string) TestingBuildParams {
Paul Duffin0eda26b92021-03-22 09:34:29 +0000773 return b.buildParamsFromDescription(desc)
Paul Duffin31a22882021-03-22 09:29:00 +0000774}
775
776// MaybeOutput finds a call to ctx.Build with a BuildParams.Output or BuildParams.Outputs whose String() or Rel()
777// value matches the provided string. Returns an empty BuildParams if no rule is found.
778func (b baseTestingComponent) MaybeOutput(file string) TestingBuildParams {
Paul Duffin0eda26b92021-03-22 09:34:29 +0000779 p, _ := b.maybeBuildParamsFromOutput(file)
Paul Duffin31a22882021-03-22 09:29:00 +0000780 return p
781}
782
783// Output finds a call to ctx.Build with a BuildParams.Output or BuildParams.Outputs whose String() or Rel()
784// value matches the provided string. Panics if no rule is found.
785func (b baseTestingComponent) Output(file string) TestingBuildParams {
Paul Duffin0eda26b92021-03-22 09:34:29 +0000786 return b.buildParamsFromOutput(file)
Paul Duffin31a22882021-03-22 09:29:00 +0000787}
788
789// AllOutputs returns all 'BuildParams.Output's and 'BuildParams.Outputs's in their full path string forms.
790func (b baseTestingComponent) AllOutputs() []string {
Paul Duffin0eda26b92021-03-22 09:34:29 +0000791 return b.allOutputs()
Paul Duffin31a22882021-03-22 09:29:00 +0000792}
793
Colin Crossb77ffc42019-01-05 22:09:19 -0800794// TestingModule is wrapper around an android.Module that provides methods to find information about individual
795// ctx.Build parameters for verification in tests.
Colin Crosscec81712017-07-13 14:43:27 -0700796type TestingModule struct {
Paul Duffin31a22882021-03-22 09:29:00 +0000797 baseTestingComponent
Colin Crosscec81712017-07-13 14:43:27 -0700798 module Module
799}
800
Paul Duffin709e0e32021-03-22 10:09:02 +0000801func newTestingModule(config Config, module Module) TestingModule {
Paul Duffin31a22882021-03-22 09:29:00 +0000802 return TestingModule{
Paul Duffin709e0e32021-03-22 10:09:02 +0000803 newBaseTestingComponent(config, module),
Paul Duffin31a22882021-03-22 09:29:00 +0000804 module,
805 }
806}
807
Colin Crossb77ffc42019-01-05 22:09:19 -0800808// Module returns the Module wrapped by the TestingModule.
Colin Crosscec81712017-07-13 14:43:27 -0700809func (m TestingModule) Module() Module {
810 return m.module
811}
812
Paul Duffin97d8b402021-03-22 16:04:50 +0000813// VariablesForTestsRelativeToTop returns a copy of the Module.VariablesForTests() with every value
814// having any temporary build dir usages replaced with paths relative to a notional top.
815func (m TestingModule) VariablesForTestsRelativeToTop() map[string]string {
816 return normalizeStringMapRelativeToTop(m.config, m.module.VariablesForTests())
817}
818
Colin Cross4c83e5c2019-02-25 14:54:28 -0800819// TestingSingleton is wrapper around an android.Singleton that provides methods to find information about individual
820// ctx.Build parameters for verification in tests.
821type TestingSingleton struct {
Paul Duffin31a22882021-03-22 09:29:00 +0000822 baseTestingComponent
Colin Cross4c83e5c2019-02-25 14:54:28 -0800823 singleton Singleton
Colin Cross4c83e5c2019-02-25 14:54:28 -0800824}
825
826// Singleton returns the Singleton wrapped by the TestingSingleton.
827func (s TestingSingleton) Singleton() Singleton {
828 return s.singleton
829}
830
Logan Chien42039712018-03-12 16:29:17 +0800831func FailIfErrored(t *testing.T, errs []error) {
832 t.Helper()
833 if len(errs) > 0 {
834 for _, err := range errs {
835 t.Error(err)
836 }
837 t.FailNow()
838 }
839}
Logan Chienee97c3e2018-03-12 16:34:26 +0800840
Paul Duffinea8a3862021-03-04 17:58:33 +0000841// Fail if no errors that matched the regular expression were found.
842//
843// Returns true if a matching error was found, false otherwise.
844func FailIfNoMatchingErrors(t *testing.T, pattern string, errs []error) bool {
Logan Chienee97c3e2018-03-12 16:34:26 +0800845 t.Helper()
846
847 matcher, err := regexp.Compile(pattern)
848 if err != nil {
Paul Duffinea8a3862021-03-04 17:58:33 +0000849 t.Fatalf("failed to compile regular expression %q because %s", pattern, err)
Logan Chienee97c3e2018-03-12 16:34:26 +0800850 }
851
852 found := false
853 for _, err := range errs {
854 if matcher.FindStringIndex(err.Error()) != nil {
855 found = true
856 break
857 }
858 }
859 if !found {
860 t.Errorf("missing the expected error %q (checked %d error(s))", pattern, len(errs))
861 for i, err := range errs {
Colin Crossaede88c2020-08-11 12:17:01 -0700862 t.Errorf("errs[%d] = %q", i, err)
Logan Chienee97c3e2018-03-12 16:34:26 +0800863 }
864 }
Paul Duffinea8a3862021-03-04 17:58:33 +0000865
866 return found
Logan Chienee97c3e2018-03-12 16:34:26 +0800867}
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700868
Paul Duffin91e38192019-08-05 15:07:57 +0100869func CheckErrorsAgainstExpectations(t *testing.T, errs []error, expectedErrorPatterns []string) {
870 t.Helper()
871
872 if expectedErrorPatterns == nil {
873 FailIfErrored(t, errs)
874 } else {
875 for _, expectedError := range expectedErrorPatterns {
876 FailIfNoMatchingErrors(t, expectedError, errs)
877 }
878 if len(errs) > len(expectedErrorPatterns) {
879 t.Errorf("additional errors found, expected %d, found %d",
880 len(expectedErrorPatterns), len(errs))
881 for i, expectedError := range expectedErrorPatterns {
882 t.Errorf("expectedErrors[%d] = %s", i, expectedError)
883 }
884 for i, err := range errs {
885 t.Errorf("errs[%d] = %s", i, err)
886 }
Paul Duffinea8a3862021-03-04 17:58:33 +0000887 t.FailNow()
Paul Duffin91e38192019-08-05 15:07:57 +0100888 }
889 }
Paul Duffin91e38192019-08-05 15:07:57 +0100890}
891
Jingwen Chencda22c92020-11-23 00:22:30 -0500892func SetKatiEnabledForTests(config Config) {
893 config.katiEnabled = true
Paul Duffin8c3fec42020-03-04 20:15:08 +0000894}
895
Colin Crossaa255532020-07-03 13:18:24 -0700896func AndroidMkEntriesForTest(t *testing.T, ctx *TestContext, mod blueprint.Module) []AndroidMkEntries {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700897 var p AndroidMkEntriesProvider
898 var ok bool
899 if p, ok = mod.(AndroidMkEntriesProvider); !ok {
Roland Levillaindfe75b32019-07-23 16:53:32 +0100900 t.Errorf("module does not implement AndroidMkEntriesProvider: " + mod.Name())
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700901 }
Jiyong Park0b0e1b92019-12-03 13:24:29 +0900902
903 entriesList := p.AndroidMkEntries()
904 for i, _ := range entriesList {
Colin Crossaa255532020-07-03 13:18:24 -0700905 entriesList[i].fillInEntries(ctx, mod)
Jiyong Park0b0e1b92019-12-03 13:24:29 +0900906 }
907 return entriesList
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700908}
Jooyung Han12df5fb2019-07-11 16:18:47 +0900909
Colin Crossaa255532020-07-03 13:18:24 -0700910func AndroidMkDataForTest(t *testing.T, ctx *TestContext, mod blueprint.Module) AndroidMkData {
Jooyung Han12df5fb2019-07-11 16:18:47 +0900911 var p AndroidMkDataProvider
912 var ok bool
913 if p, ok = mod.(AndroidMkDataProvider); !ok {
Roland Levillaindfe75b32019-07-23 16:53:32 +0100914 t.Errorf("module does not implement AndroidMkDataProvider: " + mod.Name())
Jooyung Han12df5fb2019-07-11 16:18:47 +0900915 }
916 data := p.AndroidMk()
Colin Crossaa255532020-07-03 13:18:24 -0700917 data.fillInData(ctx, mod)
Jooyung Han12df5fb2019-07-11 16:18:47 +0900918 return data
919}
Paul Duffin9b478b02019-12-10 13:41:51 +0000920
921// Normalize the path for testing.
922//
923// If the path is relative to the build directory then return the relative path
924// to avoid tests having to deal with the dynamically generated build directory.
925//
926// Otherwise, return the supplied path as it is almost certainly a source path
927// that is relative to the root of the source tree.
928//
929// The build and source paths should be distinguishable based on their contents.
Paul Duffin567465d2021-03-16 01:21:34 +0000930//
931// deprecated: use PathRelativeToTop instead as it handles make install paths and differentiates
932// between output and source properly.
Paul Duffin9b478b02019-12-10 13:41:51 +0000933func NormalizePathForTesting(path Path) string {
Paul Duffin064b70c2020-11-02 17:32:38 +0000934 if path == nil {
935 return "<nil path>"
936 }
Paul Duffin9b478b02019-12-10 13:41:51 +0000937 p := path.String()
938 if w, ok := path.(WritablePath); ok {
Paul Duffind65c58b2021-03-24 09:22:07 +0000939 rel, err := filepath.Rel(w.getBuildDir(), p)
Paul Duffin9b478b02019-12-10 13:41:51 +0000940 if err != nil {
941 panic(err)
942 }
943 return rel
944 }
945 return p
946}
947
Paul Duffin567465d2021-03-16 01:21:34 +0000948// NormalizePathsForTesting creates a slice of strings where each string is the result of applying
949// NormalizePathForTesting to the corresponding Path in the input slice.
950//
951// deprecated: use PathsRelativeToTop instead as it handles make install paths and differentiates
952// between output and source properly.
Paul Duffin9b478b02019-12-10 13:41:51 +0000953func NormalizePathsForTesting(paths Paths) []string {
954 var result []string
955 for _, path := range paths {
956 relative := NormalizePathForTesting(path)
957 result = append(result, relative)
958 }
959 return result
960}
Paul Duffin567465d2021-03-16 01:21:34 +0000961
962// PathRelativeToTop returns a string representation of the path relative to a notional top
963// directory.
964//
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000965// It return "<nil path>" if the supplied path is nil, otherwise it returns the result of calling
966// Path.RelativeToTop to obtain a relative Path and then calling Path.String on that to get the
967// string representation.
Paul Duffin567465d2021-03-16 01:21:34 +0000968func PathRelativeToTop(path Path) string {
969 if path == nil {
970 return "<nil path>"
971 }
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000972 return path.RelativeToTop().String()
Paul Duffin567465d2021-03-16 01:21:34 +0000973}
974
975// PathsRelativeToTop creates a slice of strings where each string is the result of applying
976// PathRelativeToTop to the corresponding Path in the input slice.
977func PathsRelativeToTop(paths Paths) []string {
978 var result []string
979 for _, path := range paths {
980 relative := PathRelativeToTop(path)
981 result = append(result, relative)
982 }
983 return result
984}
985
986// StringPathRelativeToTop returns a string representation of the path relative to a notional top
987// directory.
988//
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000989// See Path.RelativeToTop for more details as to what `relative to top` means.
Paul Duffin567465d2021-03-16 01:21:34 +0000990//
991// This is provided for processing paths that have already been converted into a string, e.g. paths
992// in AndroidMkEntries structures. As a result it needs to be supplied the soong output dir against
993// which it can try and relativize paths. PathRelativeToTop must be used for process Path objects.
994func StringPathRelativeToTop(soongOutDir string, path string) string {
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000995 ensureTestOnly()
Paul Duffin567465d2021-03-16 01:21:34 +0000996
997 // A relative path must be a source path so leave it as it is.
998 if !filepath.IsAbs(path) {
999 return path
1000 }
1001
1002 // Check to see if the path is relative to the soong out dir.
1003 rel, isRel, err := maybeRelErr(soongOutDir, path)
1004 if err != nil {
1005 panic(err)
1006 }
1007
1008 if isRel {
1009 // The path is in the soong out dir so indicate that in the relative path.
1010 return filepath.Join("out/soong", rel)
1011 }
1012
1013 // Check to see if the path is relative to the top level out dir.
1014 outDir := filepath.Dir(soongOutDir)
1015 rel, isRel, err = maybeRelErr(outDir, path)
1016 if err != nil {
1017 panic(err)
1018 }
1019
1020 if isRel {
1021 // The path is in the out dir so indicate that in the relative path.
1022 return filepath.Join("out", rel)
1023 }
1024
1025 // This should never happen.
1026 panic(fmt.Errorf("internal error: absolute path %s is not relative to the out dir %s", path, outDir))
1027}
1028
1029// StringPathsRelativeToTop creates a slice of strings where each string is the result of applying
1030// StringPathRelativeToTop to the corresponding string path in the input slice.
1031//
1032// This is provided for processing paths that have already been converted into a string, e.g. paths
1033// in AndroidMkEntries structures. As a result it needs to be supplied the soong output dir against
1034// which it can try and relativize paths. PathsRelativeToTop must be used for process Paths objects.
1035func StringPathsRelativeToTop(soongOutDir string, paths []string) []string {
1036 var result []string
1037 for _, path := range paths {
1038 relative := StringPathRelativeToTop(soongOutDir, path)
1039 result = append(result, relative)
1040 }
1041 return result
1042}
Paul Duffinf53555d2021-03-29 00:21:00 +01001043
1044// StringRelativeToTop will normalize a string containing paths, e.g. ninja command, by replacing
1045// any references to the test specific temporary build directory that changes with each run to a
1046// fixed path relative to a notional top directory.
1047//
1048// This is similar to StringPathRelativeToTop except that assumes the string is a single path
1049// containing at most one instance of the temporary build directory at the start of the path while
1050// this assumes that there can be any number at any position.
1051func StringRelativeToTop(config Config, command string) string {
1052 return normalizeStringRelativeToTop(config, command)
1053}
Paul Duffin0aafcbf2021-03-29 00:56:32 +01001054
1055// StringsRelativeToTop will return a new slice such that each item in the new slice is the result
1056// of calling StringRelativeToTop on the corresponding item in the input slice.
1057func StringsRelativeToTop(config Config, command []string) []string {
1058 return normalizeStringArrayRelativeToTop(config, command)
1059}