blob: 6290d4317f113d576919ad9254fd7f8207cbec11 [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 Duffine96108d2021-05-06 16:39:27 +010077var PrepareForTestWithLicenses = GroupFixturePreparers(
78 FixtureRegisterWithContext(RegisterLicenseKindBuildComponents),
79 FixtureRegisterWithContext(RegisterLicenseBuildComponents),
80 FixtureRegisterWithContext(registerLicenseMutators),
81)
82
83func registerLicenseMutators(ctx RegistrationContext) {
84 ctx.PreArchMutators(RegisterLicensesPackageMapper)
85 ctx.PreArchMutators(RegisterLicensesPropertyGatherer)
86 ctx.PostDepsMutators(RegisterLicensesDependencyChecker)
87}
88
89var PrepareForTestWithLicenseDefaultModules = GroupFixturePreparers(
90 FixtureAddTextFile("build/soong/licenses/Android.bp", `
91 license {
92 name: "Android-Apache-2.0",
93 package_name: "Android",
94 license_kinds: ["SPDX-license-identifier-Apache-2.0"],
95 copyright_notice: "Copyright (C) The Android Open Source Project",
96 license_text: ["LICENSE"],
97 }
98
99 license_kind {
100 name: "SPDX-license-identifier-Apache-2.0",
101 conditions: ["notice"],
102 url: "https://spdx.org/licenses/Apache-2.0.html",
103 }
104
105 license_kind {
106 name: "legacy_unencumbered",
107 conditions: ["unencumbered"],
108 }
109 `),
110 FixtureAddFile("build/soong/licenses/LICENSE", nil),
111)
112
Paul Duffin4fbfb592021-07-09 16:47:38 +0100113var PrepareForTestWithNamespace = FixtureRegisterWithContext(func(ctx RegistrationContext) {
114 registerNamespaceBuildComponents(ctx)
115 ctx.PreArchMutators(RegisterNamespaceMutator)
116})
117
Paul Duffinec3292b2021-03-09 01:01:31 +0000118// Test fixture preparer that will register most java build components.
119//
120// Singletons and mutators should only be added here if they are needed for a majority of java
121// module types, otherwise they should be added under a separate preparer to allow them to be
122// selected only when needed to reduce test execution time.
123//
124// Module types do not have much of an overhead unless they are used so this should include as many
125// module types as possible. The exceptions are those module types that require mutators and/or
126// singletons in order to function in which case they should be kept together in a separate
127// preparer.
128//
129// The mutators in this group were chosen because they are needed by the vast majority of tests.
130var PrepareForTestWithAndroidBuildComponents = GroupFixturePreparers(
Paul Duffin530483c2021-03-07 13:20:38 +0000131 // Sorted alphabetically as the actual order does not matter as tests automatically enforce the
132 // correct order.
Paul Duffin35816122021-02-24 01:49:52 +0000133 PrepareForTestWithArchMutator,
Paul Duffin35816122021-02-24 01:49:52 +0000134 PrepareForTestWithComponentsMutator,
Paul Duffin530483c2021-03-07 13:20:38 +0000135 PrepareForTestWithDefaults,
Paul Duffin35816122021-02-24 01:49:52 +0000136 PrepareForTestWithFilegroup,
Paul Duffin530483c2021-03-07 13:20:38 +0000137 PrepareForTestWithOverrides,
138 PrepareForTestWithPackageModule,
139 PrepareForTestWithPrebuilts,
140 PrepareForTestWithVisibility,
Paul Duffin35816122021-02-24 01:49:52 +0000141)
142
Paul Duffinec3292b2021-03-09 01:01:31 +0000143// Prepares an integration test with all build components from the android package.
144//
145// This should only be used by tests that want to run with as much of the build enabled as possible.
146var PrepareForIntegrationTestWithAndroid = GroupFixturePreparers(
147 PrepareForTestWithAndroidBuildComponents,
148)
149
Paul Duffin25259e92021-03-07 15:45:56 +0000150// Prepares a test that may be missing dependencies by setting allow_missing_dependencies to
151// true.
152var PrepareForTestWithAllowMissingDependencies = GroupFixturePreparers(
153 FixtureModifyProductVariables(func(variables FixtureProductVariables) {
154 variables.Allow_missing_dependencies = proptools.BoolPtr(true)
155 }),
156 FixtureModifyContext(func(ctx *TestContext) {
157 ctx.SetAllowMissingDependencies(true)
158 }),
159)
160
Paul Duffin76e5c8a2021-03-20 14:19:46 +0000161// Prepares a test that disallows non-existent paths.
162var PrepareForTestDisallowNonExistentPaths = FixtureModifyConfig(func(config Config) {
163 config.TestAllowNonExistentPaths = false
164})
165
Colin Crossae8600b2020-10-29 17:09:13 -0700166func NewTestArchContext(config Config) *TestContext {
167 ctx := NewTestContext(config)
Colin Crossae4c6182017-09-15 17:33:55 -0700168 ctx.preDeps = append(ctx.preDeps, registerArchMutator)
169 return ctx
170}
171
Colin Crosscec81712017-07-13 14:43:27 -0700172type TestContext struct {
Colin Cross4c83e5c2019-02-25 14:54:28 -0800173 *Context
Chris Parsons5a34ffb2021-07-21 14:34:58 -0400174 preArch, preDeps, postDeps, finalDeps []RegisterMutatorFunc
175 bp2buildPreArch, bp2buildMutators []RegisterMutatorFunc
176 NameResolver *NameResolver
Paul Duffin281deb22021-03-06 20:29:19 +0000177
Paul Duffind182fb32021-03-07 12:24:44 +0000178 // The list of pre-singletons and singletons registered for the test.
179 preSingletons, singletons sortableComponents
180
Paul Duffin41d77c72021-03-07 12:23:48 +0000181 // The order in which the pre-singletons, mutators and singletons will be run in this test
182 // context; for debugging.
183 preSingletonOrder, mutatorOrder, singletonOrder []string
Colin Crosscec81712017-07-13 14:43:27 -0700184}
185
186func (ctx *TestContext) PreArchMutators(f RegisterMutatorFunc) {
187 ctx.preArch = append(ctx.preArch, f)
188}
189
Paul Duffina80ef842020-01-14 12:09:36 +0000190func (ctx *TestContext) HardCodedPreArchMutators(f RegisterMutatorFunc) {
191 // Register mutator function as normal for testing.
192 ctx.PreArchMutators(f)
193}
194
Colin Crosscec81712017-07-13 14:43:27 -0700195func (ctx *TestContext) PreDepsMutators(f RegisterMutatorFunc) {
196 ctx.preDeps = append(ctx.preDeps, f)
197}
198
199func (ctx *TestContext) PostDepsMutators(f RegisterMutatorFunc) {
200 ctx.postDeps = append(ctx.postDeps, f)
201}
202
Martin Stjernholm710ec3a2020-01-16 15:12:04 +0000203func (ctx *TestContext) FinalDepsMutators(f RegisterMutatorFunc) {
204 ctx.finalDeps = append(ctx.finalDeps, f)
205}
206
Jingwen Chen12b4c272021-03-10 02:05:59 -0500207func (ctx *TestContext) RegisterBp2BuildConfig(config Bp2BuildConfig) {
208 ctx.config.bp2buildPackageConfig = config
209}
210
Jingwen Chen73850672020-12-14 08:25:34 -0500211// RegisterBp2BuildMutator registers a BazelTargetModule mutator for converting a module
212// type to the equivalent Bazel target.
213func (ctx *TestContext) RegisterBp2BuildMutator(moduleType string, m func(TopDownMutatorContext)) {
Jingwen Chen73850672020-12-14 08:25:34 -0500214 f := func(ctx RegisterMutatorsContext) {
Liz Kammer356f7d42021-01-26 09:18:53 -0500215 ctx.TopDown(moduleType, m)
Jingwen Chen73850672020-12-14 08:25:34 -0500216 }
Jingwen Chen12b4c272021-03-10 02:05:59 -0500217 ctx.config.bp2buildModuleTypeConfig[moduleType] = true
Jingwen Chena42d6412021-01-26 21:57:27 -0500218 ctx.bp2buildMutators = append(ctx.bp2buildMutators, f)
Jingwen Chen73850672020-12-14 08:25:34 -0500219}
220
Liz Kammer356f7d42021-01-26 09:18:53 -0500221// PreArchBp2BuildMutators adds mutators to be register for converting Android Blueprint modules
222// into Bazel BUILD targets that should run prior to deps and conversion.
223func (ctx *TestContext) PreArchBp2BuildMutators(f RegisterMutatorFunc) {
224 ctx.bp2buildPreArch = append(ctx.bp2buildPreArch, f)
225}
226
Paul Duffin281deb22021-03-06 20:29:19 +0000227// registeredComponentOrder defines the order in which a sortableComponent type is registered at
228// runtime and provides support for reordering the components registered for a test in the same
229// way.
230type registeredComponentOrder struct {
231 // The name of the component type, used for error messages.
232 componentType string
233
234 // The names of the registered components in the order in which they were registered.
235 namesInOrder []string
236
237 // Maps from the component name to its position in the runtime ordering.
238 namesToIndex map[string]int
239
240 // A function that defines the order between two named components that can be used to sort a slice
241 // of component names into the same order as they appear in namesInOrder.
242 less func(string, string) bool
243}
244
245// registeredComponentOrderFromExistingOrder takes an existing slice of sortableComponents and
246// creates a registeredComponentOrder that contains a less function that can be used to sort a
247// subset of that list of names so it is in the same order as the original sortableComponents.
248func registeredComponentOrderFromExistingOrder(componentType string, existingOrder sortableComponents) registeredComponentOrder {
249 // Only the names from the existing order are needed for this so create a list of component names
250 // in the correct order.
251 namesInOrder := componentsToNames(existingOrder)
252
253 // Populate the map from name to position in the list.
254 nameToIndex := make(map[string]int)
255 for i, n := range namesInOrder {
256 nameToIndex[n] = i
257 }
258
259 // A function to use to map from a name to an index in the original order.
260 indexOf := func(name string) int {
261 index, ok := nameToIndex[name]
262 if !ok {
263 // Should never happen as tests that use components that are not known at runtime do not sort
264 // so should never use this function.
265 panic(fmt.Errorf("internal error: unknown %s %q should be one of %s", componentType, name, strings.Join(namesInOrder, ", ")))
266 }
267 return index
268 }
269
270 // The less function.
271 less := func(n1, n2 string) bool {
272 i1 := indexOf(n1)
273 i2 := indexOf(n2)
274 return i1 < i2
275 }
276
277 return registeredComponentOrder{
278 componentType: componentType,
279 namesInOrder: namesInOrder,
280 namesToIndex: nameToIndex,
281 less: less,
282 }
283}
284
285// componentsToNames maps from the slice of components to a slice of their names.
286func componentsToNames(components sortableComponents) []string {
287 names := make([]string, len(components))
288 for i, c := range components {
289 names[i] = c.componentName()
290 }
291 return names
292}
293
294// enforceOrdering enforces the supplied components are in the same order as is defined in this
295// object.
296//
297// If the supplied components contains any components that are not registered at runtime, i.e. test
298// specific components, then it is impossible to sort them into an order that both matches the
299// runtime and also preserves the implicit ordering defined in the test. In that case it will not
300// sort the components, instead it will just check that the components are in the correct order.
301//
302// Otherwise, this will sort the supplied components in place.
303func (o *registeredComponentOrder) enforceOrdering(components sortableComponents) {
304 // Check to see if the list of components contains any components that are
305 // not registered at runtime.
306 var unknownComponents []string
307 testOrder := componentsToNames(components)
308 for _, name := range testOrder {
309 if _, ok := o.namesToIndex[name]; !ok {
310 unknownComponents = append(unknownComponents, name)
311 break
312 }
313 }
314
315 // If the slice contains some unknown components then it is not possible to
316 // sort them into an order that matches the runtime while also preserving the
317 // order expected from the test, so in that case don't sort just check that
318 // the order of the known mutators does match.
319 if len(unknownComponents) > 0 {
320 // Check order.
321 o.checkTestOrder(testOrder, unknownComponents)
322 } else {
323 // Sort the components.
324 sort.Slice(components, func(i, j int) bool {
325 n1 := components[i].componentName()
326 n2 := components[j].componentName()
327 return o.less(n1, n2)
328 })
329 }
330}
331
332// checkTestOrder checks that the supplied testOrder matches the one defined by this object,
333// panicking if it does not.
334func (o *registeredComponentOrder) checkTestOrder(testOrder []string, unknownComponents []string) {
335 lastMatchingTest := -1
336 matchCount := 0
337 // Take a copy of the runtime order as it is modified during the comparison.
338 runtimeOrder := append([]string(nil), o.namesInOrder...)
339 componentType := o.componentType
340 for i, j := 0, 0; i < len(testOrder) && j < len(runtimeOrder); {
341 test := testOrder[i]
342 runtime := runtimeOrder[j]
343
344 if test == runtime {
345 testOrder[i] = test + fmt.Sprintf(" <-- matched with runtime %s %d", componentType, j)
346 runtimeOrder[j] = runtime + fmt.Sprintf(" <-- matched with test %s %d", componentType, i)
347 lastMatchingTest = i
348 i += 1
349 j += 1
350 matchCount += 1
351 } else if _, ok := o.namesToIndex[test]; !ok {
352 // The test component is not registered globally so assume it is the correct place, treat it
353 // as having matched and skip it.
354 i += 1
355 matchCount += 1
356 } else {
357 // Assume that the test list is in the same order as the runtime list but the runtime list
358 // contains some components that are not present in the tests. So, skip the runtime component
359 // to try and find the next one that matches the current test component.
360 j += 1
361 }
362 }
363
364 // If every item in the test order was either test specific or matched one in the runtime then
365 // it is in the correct order. Otherwise, it was not so fail.
366 if matchCount != len(testOrder) {
367 // The test component names were not all matched with a runtime component name so there must
368 // either be a component present in the test that is not present in the runtime or they must be
369 // in the wrong order.
370 testOrder[lastMatchingTest+1] = testOrder[lastMatchingTest+1] + " <--- unmatched"
371 panic(fmt.Errorf("the tests uses test specific components %q and so cannot be automatically sorted."+
372 " Unfortunately it uses %s components in the wrong order.\n"+
373 "test order:\n %s\n"+
374 "runtime order\n %s\n",
375 SortedUniqueStrings(unknownComponents),
376 componentType,
377 strings.Join(testOrder, "\n "),
378 strings.Join(runtimeOrder, "\n ")))
379 }
380}
381
382// registrationSorter encapsulates the information needed to ensure that the test mutators are
383// registered, and thereby executed, in the same order as they are at runtime.
384//
385// It MUST be populated lazily AFTER all package initialization has been done otherwise it will
386// only define the order for a subset of all the registered build components that are available for
387// the packages being tested.
388//
389// e.g if this is initialized during say the cc package initialization then any tests run in the
390// java package will not sort build components registered by the java package's init() functions.
391type registrationSorter struct {
392 // Used to ensure that this is only created once.
393 once sync.Once
394
Paul Duffin41d77c72021-03-07 12:23:48 +0000395 // The order of pre-singletons
396 preSingletonOrder registeredComponentOrder
397
Paul Duffin281deb22021-03-06 20:29:19 +0000398 // The order of mutators
399 mutatorOrder registeredComponentOrder
Paul Duffin41d77c72021-03-07 12:23:48 +0000400
401 // The order of singletons
402 singletonOrder registeredComponentOrder
Paul Duffin281deb22021-03-06 20:29:19 +0000403}
404
405// populate initializes this structure from globally registered build components.
406//
407// Only the first call has any effect.
408func (s *registrationSorter) populate() {
409 s.once.Do(func() {
Paul Duffin41d77c72021-03-07 12:23:48 +0000410 // Create an ordering from the globally registered pre-singletons.
411 s.preSingletonOrder = registeredComponentOrderFromExistingOrder("pre-singleton", preSingletons)
412
Paul Duffin281deb22021-03-06 20:29:19 +0000413 // Created an ordering from the globally registered mutators.
414 globallyRegisteredMutators := collateGloballyRegisteredMutators()
415 s.mutatorOrder = registeredComponentOrderFromExistingOrder("mutator", globallyRegisteredMutators)
Paul Duffin41d77c72021-03-07 12:23:48 +0000416
417 // Create an ordering from the globally registered singletons.
418 globallyRegisteredSingletons := collateGloballyRegisteredSingletons()
419 s.singletonOrder = registeredComponentOrderFromExistingOrder("singleton", globallyRegisteredSingletons)
Paul Duffin281deb22021-03-06 20:29:19 +0000420 })
421}
422
423// Provides support for enforcing the same order in which build components are registered globally
424// to the order in which they are registered during tests.
425//
426// MUST only be accessed via the globallyRegisteredComponentsOrder func.
427var globalRegistrationSorter registrationSorter
428
429// globallyRegisteredComponentsOrder returns the globalRegistrationSorter after ensuring it is
430// correctly populated.
431func globallyRegisteredComponentsOrder() *registrationSorter {
432 globalRegistrationSorter.populate()
433 return &globalRegistrationSorter
434}
435
Colin Crossae8600b2020-10-29 17:09:13 -0700436func (ctx *TestContext) Register() {
Paul Duffin281deb22021-03-06 20:29:19 +0000437 globalOrder := globallyRegisteredComponentsOrder()
438
Paul Duffin41d77c72021-03-07 12:23:48 +0000439 // Ensure that the pre-singletons used in the test are in the same order as they are used at
440 // runtime.
441 globalOrder.preSingletonOrder.enforceOrdering(ctx.preSingletons)
Paul Duffind182fb32021-03-07 12:24:44 +0000442 ctx.preSingletons.registerAll(ctx.Context)
443
Paul Duffinc05b0342021-03-06 13:28:13 +0000444 mutators := collateRegisteredMutators(ctx.preArch, ctx.preDeps, ctx.postDeps, ctx.finalDeps)
Paul Duffin281deb22021-03-06 20:29:19 +0000445 // Ensure that the mutators used in the test are in the same order as they are used at runtime.
446 globalOrder.mutatorOrder.enforceOrdering(mutators)
Paul Duffinc05b0342021-03-06 13:28:13 +0000447 mutators.registerAll(ctx.Context)
Colin Crosscec81712017-07-13 14:43:27 -0700448
Paul Duffin41d77c72021-03-07 12:23:48 +0000449 // Ensure that the singletons used in the test are in the same order as they are used at runtime.
450 globalOrder.singletonOrder.enforceOrdering(ctx.singletons)
Paul Duffind182fb32021-03-07 12:24:44 +0000451 ctx.singletons.registerAll(ctx.Context)
452
Paul Duffin41d77c72021-03-07 12:23:48 +0000453 // Save the sorted components order away to make them easy to access while debugging.
Paul Duffinf5de6682021-03-08 23:42:10 +0000454 ctx.preSingletonOrder = componentsToNames(preSingletons)
455 ctx.mutatorOrder = componentsToNames(mutators)
456 ctx.singletonOrder = componentsToNames(singletons)
Colin Cross31a738b2019-12-30 18:45:15 -0800457}
458
Jingwen Chen73850672020-12-14 08:25:34 -0500459// RegisterForBazelConversion prepares a test context for bp2build conversion.
460func (ctx *TestContext) RegisterForBazelConversion() {
Jingwen Chena47f28d2021-11-02 16:43:57 +0000461 ctx.SetRunningAsBp2build()
Chris Parsons5a34ffb2021-07-21 14:34:58 -0400462 RegisterMutatorsForBazelConversion(ctx.Context, ctx.bp2buildPreArch, ctx.bp2buildMutators)
Jingwen Chen73850672020-12-14 08:25:34 -0500463}
464
Colin Cross31a738b2019-12-30 18:45:15 -0800465func (ctx *TestContext) ParseFileList(rootDir string, filePaths []string) (deps []string, errs []error) {
466 // This function adapts the old style ParseFileList calls that are spread throughout the tests
467 // to the new style that takes a config.
468 return ctx.Context.ParseFileList(rootDir, filePaths, ctx.config)
469}
470
471func (ctx *TestContext) ParseBlueprintsFiles(rootDir string) (deps []string, errs []error) {
472 // This function adapts the old style ParseBlueprintsFiles calls that are spread throughout the
473 // tests to the new style that takes a config.
474 return ctx.Context.ParseBlueprintsFiles(rootDir, ctx.config)
Colin Cross4b49b762019-11-22 15:25:03 -0800475}
476
477func (ctx *TestContext) RegisterModuleType(name string, factory ModuleFactory) {
478 ctx.Context.RegisterModuleType(name, ModuleFactoryAdaptor(factory))
479}
480
Colin Cross9aed5bc2020-12-28 15:15:34 -0800481func (ctx *TestContext) RegisterSingletonModuleType(name string, factory SingletonModuleFactory) {
482 s, m := SingletonModuleFactoryAdaptor(name, factory)
483 ctx.RegisterSingletonType(name, s)
484 ctx.RegisterModuleType(name, m)
485}
486
Colin Cross4b49b762019-11-22 15:25:03 -0800487func (ctx *TestContext) RegisterSingletonType(name string, factory SingletonFactory) {
Paul Duffind182fb32021-03-07 12:24:44 +0000488 ctx.singletons = append(ctx.singletons, newSingleton(name, factory))
Colin Crosscec81712017-07-13 14:43:27 -0700489}
490
Paul Duffineafc16b2021-02-24 01:43:18 +0000491func (ctx *TestContext) RegisterPreSingletonType(name string, factory SingletonFactory) {
Paul Duffind182fb32021-03-07 12:24:44 +0000492 ctx.preSingletons = append(ctx.preSingletons, newPreSingleton(name, factory))
Paul Duffineafc16b2021-02-24 01:43:18 +0000493}
494
Martin Stjernholm14cdd712021-09-10 22:39:59 +0100495// ModuleVariantForTests selects a specific variant of the module with the given
496// name by matching the variations map against the variations of each module
497// variant. A module variant matches the map if every variation that exists in
498// both have the same value. Both the module and the map are allowed to have
499// extra variations that the other doesn't have. Panics if not exactly one
500// module variant matches.
501func (ctx *TestContext) ModuleVariantForTests(name string, matchVariations map[string]string) TestingModule {
502 modules := []Module{}
503 ctx.VisitAllModules(func(m blueprint.Module) {
504 if ctx.ModuleName(m) == name {
505 am := m.(Module)
506 amMut := am.base().commonProperties.DebugMutators
507 amVar := am.base().commonProperties.DebugVariations
508 matched := true
509 for i, mut := range amMut {
510 if wantedVar, found := matchVariations[mut]; found && amVar[i] != wantedVar {
511 matched = false
512 break
513 }
514 }
515 if matched {
516 modules = append(modules, am)
517 }
518 }
519 })
520
521 if len(modules) == 0 {
522 // Show all the modules or module variants that do exist.
523 var allModuleNames []string
524 var allVariants []string
525 ctx.VisitAllModules(func(m blueprint.Module) {
526 allModuleNames = append(allModuleNames, ctx.ModuleName(m))
527 if ctx.ModuleName(m) == name {
528 allVariants = append(allVariants, m.(Module).String())
529 }
530 })
531
532 if len(allVariants) == 0 {
533 panic(fmt.Errorf("failed to find module %q. All modules:\n %s",
534 name, strings.Join(SortedUniqueStrings(allModuleNames), "\n ")))
535 } else {
536 sort.Strings(allVariants)
537 panic(fmt.Errorf("failed to find module %q matching %v. All variants:\n %s",
538 name, matchVariations, strings.Join(allVariants, "\n ")))
539 }
540 }
541
542 if len(modules) > 1 {
543 moduleStrings := []string{}
544 for _, m := range modules {
545 moduleStrings = append(moduleStrings, m.String())
546 }
547 sort.Strings(moduleStrings)
548 panic(fmt.Errorf("module %q has more than one variant that match %v:\n %s",
549 name, matchVariations, strings.Join(moduleStrings, "\n ")))
550 }
551
552 return newTestingModule(ctx.config, modules[0])
553}
554
Colin Crosscec81712017-07-13 14:43:27 -0700555func (ctx *TestContext) ModuleForTests(name, variant string) TestingModule {
556 var module Module
557 ctx.VisitAllModules(func(m blueprint.Module) {
558 if ctx.ModuleName(m) == name && ctx.ModuleSubDir(m) == variant {
559 module = m.(Module)
560 }
561 })
562
563 if module == nil {
Jeff Gaston294356f2017-09-27 17:05:30 -0700564 // find all the modules that do exist
Colin Crossbeae6ec2020-08-11 12:02:11 -0700565 var allModuleNames []string
566 var allVariants []string
Jeff Gaston294356f2017-09-27 17:05:30 -0700567 ctx.VisitAllModules(func(m blueprint.Module) {
Colin Crossbeae6ec2020-08-11 12:02:11 -0700568 allModuleNames = append(allModuleNames, ctx.ModuleName(m))
569 if ctx.ModuleName(m) == name {
570 allVariants = append(allVariants, ctx.ModuleSubDir(m))
571 }
Jeff Gaston294356f2017-09-27 17:05:30 -0700572 })
Colin Crossbeae6ec2020-08-11 12:02:11 -0700573 sort.Strings(allVariants)
Jeff Gaston294356f2017-09-27 17:05:30 -0700574
Colin Crossbeae6ec2020-08-11 12:02:11 -0700575 if len(allVariants) == 0 {
576 panic(fmt.Errorf("failed to find module %q. All modules:\n %s",
Martin Stjernholm98e0d882021-09-09 21:34:02 +0100577 name, strings.Join(SortedUniqueStrings(allModuleNames), "\n ")))
Colin Crossbeae6ec2020-08-11 12:02:11 -0700578 } else {
579 panic(fmt.Errorf("failed to find module %q variant %q. All variants:\n %s",
580 name, variant, strings.Join(allVariants, "\n ")))
581 }
Colin Crosscec81712017-07-13 14:43:27 -0700582 }
583
Paul Duffin709e0e32021-03-22 10:09:02 +0000584 return newTestingModule(ctx.config, module)
Colin Crosscec81712017-07-13 14:43:27 -0700585}
586
Jiyong Park37b25202018-07-11 10:49:27 +0900587func (ctx *TestContext) ModuleVariantsForTests(name string) []string {
588 var variants []string
589 ctx.VisitAllModules(func(m blueprint.Module) {
590 if ctx.ModuleName(m) == name {
591 variants = append(variants, ctx.ModuleSubDir(m))
592 }
593 })
594 return variants
595}
596
Colin Cross4c83e5c2019-02-25 14:54:28 -0800597// SingletonForTests returns a TestingSingleton for the singleton registered with the given name.
598func (ctx *TestContext) SingletonForTests(name string) TestingSingleton {
599 allSingletonNames := []string{}
600 for _, s := range ctx.Singletons() {
601 n := ctx.SingletonName(s)
602 if n == name {
603 return TestingSingleton{
Paul Duffin709e0e32021-03-22 10:09:02 +0000604 baseTestingComponent: newBaseTestingComponent(ctx.config, s.(testBuildProvider)),
Paul Duffin31a22882021-03-22 09:29:00 +0000605 singleton: s.(*singletonAdaptor).Singleton,
Colin Cross4c83e5c2019-02-25 14:54:28 -0800606 }
607 }
608 allSingletonNames = append(allSingletonNames, n)
609 }
610
611 panic(fmt.Errorf("failed to find singleton %q."+
612 "\nall singletons: %v", name, allSingletonNames))
613}
614
Colin Crossaa255532020-07-03 13:18:24 -0700615func (ctx *TestContext) Config() Config {
616 return ctx.config
617}
618
Colin Cross4c83e5c2019-02-25 14:54:28 -0800619type testBuildProvider interface {
620 BuildParamsForTests() []BuildParams
621 RuleParamsForTests() map[blueprint.Rule]blueprint.RuleParams
622}
623
624type TestingBuildParams struct {
625 BuildParams
626 RuleParams blueprint.RuleParams
Paul Duffin709e0e32021-03-22 10:09:02 +0000627
628 config Config
629}
630
631// RelativeToTop creates a new instance of this which has had any usages of the current test's
632// temporary and test specific build directory replaced with a path relative to the notional top.
633//
634// The parts of this structure which are changed are:
635// * BuildParams
636// * Args
Paul Duffinbbb0f8f2021-03-24 10:34:52 +0000637// * All Path, Paths, WritablePath and WritablePaths fields.
Paul Duffin709e0e32021-03-22 10:09:02 +0000638//
639// * RuleParams
640// * Command
641// * Depfile
642// * Rspfile
643// * RspfileContent
644// * SymlinkOutputs
645// * CommandDeps
646// * CommandOrderOnly
647//
648// See PathRelativeToTop for more details.
Paul Duffina71a67a2021-03-29 00:42:57 +0100649//
650// deprecated: this is no longer needed as TestingBuildParams are created in this form.
Paul Duffin709e0e32021-03-22 10:09:02 +0000651func (p TestingBuildParams) RelativeToTop() TestingBuildParams {
652 // If this is not a valid params then just return it back. That will make it easy to use with the
653 // Maybe...() methods.
654 if p.Rule == nil {
655 return p
656 }
657 if p.config.config == nil {
Paul Duffine8366da2021-03-24 10:40:38 +0000658 return p
Paul Duffin709e0e32021-03-22 10:09:02 +0000659 }
660 // Take a copy of the build params and replace any args that contains test specific temporary
661 // paths with paths relative to the top.
662 bparams := p.BuildParams
Paul Duffinbbb0f8f2021-03-24 10:34:52 +0000663 bparams.Depfile = normalizeWritablePathRelativeToTop(bparams.Depfile)
664 bparams.Output = normalizeWritablePathRelativeToTop(bparams.Output)
665 bparams.Outputs = bparams.Outputs.RelativeToTop()
666 bparams.SymlinkOutput = normalizeWritablePathRelativeToTop(bparams.SymlinkOutput)
667 bparams.SymlinkOutputs = bparams.SymlinkOutputs.RelativeToTop()
668 bparams.ImplicitOutput = normalizeWritablePathRelativeToTop(bparams.ImplicitOutput)
669 bparams.ImplicitOutputs = bparams.ImplicitOutputs.RelativeToTop()
670 bparams.Input = normalizePathRelativeToTop(bparams.Input)
671 bparams.Inputs = bparams.Inputs.RelativeToTop()
672 bparams.Implicit = normalizePathRelativeToTop(bparams.Implicit)
673 bparams.Implicits = bparams.Implicits.RelativeToTop()
674 bparams.OrderOnly = bparams.OrderOnly.RelativeToTop()
675 bparams.Validation = normalizePathRelativeToTop(bparams.Validation)
676 bparams.Validations = bparams.Validations.RelativeToTop()
Paul Duffin709e0e32021-03-22 10:09:02 +0000677 bparams.Args = normalizeStringMapRelativeToTop(p.config, bparams.Args)
678
679 // Ditto for any fields in the RuleParams.
680 rparams := p.RuleParams
681 rparams.Command = normalizeStringRelativeToTop(p.config, rparams.Command)
682 rparams.Depfile = normalizeStringRelativeToTop(p.config, rparams.Depfile)
683 rparams.Rspfile = normalizeStringRelativeToTop(p.config, rparams.Rspfile)
684 rparams.RspfileContent = normalizeStringRelativeToTop(p.config, rparams.RspfileContent)
685 rparams.SymlinkOutputs = normalizeStringArrayRelativeToTop(p.config, rparams.SymlinkOutputs)
686 rparams.CommandDeps = normalizeStringArrayRelativeToTop(p.config, rparams.CommandDeps)
687 rparams.CommandOrderOnly = normalizeStringArrayRelativeToTop(p.config, rparams.CommandOrderOnly)
688
689 return TestingBuildParams{
690 BuildParams: bparams,
691 RuleParams: rparams,
692 }
Colin Cross4c83e5c2019-02-25 14:54:28 -0800693}
694
Paul Duffinbbb0f8f2021-03-24 10:34:52 +0000695func normalizeWritablePathRelativeToTop(path WritablePath) WritablePath {
696 if path == nil {
697 return nil
698 }
699 return path.RelativeToTop().(WritablePath)
700}
701
702func normalizePathRelativeToTop(path Path) Path {
703 if path == nil {
704 return nil
705 }
706 return path.RelativeToTop()
707}
708
Paul Duffin0eda26b92021-03-22 09:34:29 +0000709// baseTestingComponent provides functionality common to both TestingModule and TestingSingleton.
710type baseTestingComponent struct {
Paul Duffin709e0e32021-03-22 10:09:02 +0000711 config Config
Paul Duffin0eda26b92021-03-22 09:34:29 +0000712 provider testBuildProvider
713}
714
Paul Duffin709e0e32021-03-22 10:09:02 +0000715func newBaseTestingComponent(config Config, provider testBuildProvider) baseTestingComponent {
716 return baseTestingComponent{config, provider}
717}
718
719// A function that will normalize a string containing paths, e.g. ninja command, by replacing
720// any references to the test specific temporary build directory that changes with each run to a
721// fixed path relative to a notional top directory.
722//
723// This is similar to StringPathRelativeToTop except that assumes the string is a single path
724// containing at most one instance of the temporary build directory at the start of the path while
725// this assumes that there can be any number at any position.
726func normalizeStringRelativeToTop(config Config, s string) string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200727 // The soongOutDir usually looks something like: /tmp/testFoo2345/001
Paul Duffin709e0e32021-03-22 10:09:02 +0000728 //
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200729 // Replace any usage of the soongOutDir with out/soong, e.g. replace "/tmp/testFoo2345/001" with
Paul Duffin709e0e32021-03-22 10:09:02 +0000730 // "out/soong".
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200731 outSoongDir := filepath.Clean(config.soongOutDir)
Paul Duffin709e0e32021-03-22 10:09:02 +0000732 re := regexp.MustCompile(`\Q` + outSoongDir + `\E\b`)
733 s = re.ReplaceAllString(s, "out/soong")
734
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200735 // Replace any usage of the soongOutDir/.. with out, e.g. replace "/tmp/testFoo2345" with
Paul Duffin709e0e32021-03-22 10:09:02 +0000736 // "out". This must come after the previous replacement otherwise this would replace
737 // "/tmp/testFoo2345/001" with "out/001" instead of "out/soong".
738 outDir := filepath.Dir(outSoongDir)
739 re = regexp.MustCompile(`\Q` + outDir + `\E\b`)
740 s = re.ReplaceAllString(s, "out")
741
742 return s
743}
744
745// normalizeStringArrayRelativeToTop creates a new slice constructed by applying
746// normalizeStringRelativeToTop to each item in the slice.
747func normalizeStringArrayRelativeToTop(config Config, slice []string) []string {
748 newSlice := make([]string, len(slice))
749 for i, s := range slice {
750 newSlice[i] = normalizeStringRelativeToTop(config, s)
751 }
752 return newSlice
753}
754
755// normalizeStringMapRelativeToTop creates a new map constructed by applying
756// normalizeStringRelativeToTop to each value in the map.
757func normalizeStringMapRelativeToTop(config Config, m map[string]string) map[string]string {
758 newMap := map[string]string{}
759 for k, v := range m {
760 newMap[k] = normalizeStringRelativeToTop(config, v)
761 }
762 return newMap
Paul Duffin0eda26b92021-03-22 09:34:29 +0000763}
764
765func (b baseTestingComponent) newTestingBuildParams(bparams BuildParams) TestingBuildParams {
Colin Cross4c83e5c2019-02-25 14:54:28 -0800766 return TestingBuildParams{
Paul Duffin709e0e32021-03-22 10:09:02 +0000767 config: b.config,
Colin Cross4c83e5c2019-02-25 14:54:28 -0800768 BuildParams: bparams,
Paul Duffin0eda26b92021-03-22 09:34:29 +0000769 RuleParams: b.provider.RuleParamsForTests()[bparams.Rule],
Paul Duffine8366da2021-03-24 10:40:38 +0000770 }.RelativeToTop()
Colin Cross4c83e5c2019-02-25 14:54:28 -0800771}
772
Paul Duffin0eda26b92021-03-22 09:34:29 +0000773func (b baseTestingComponent) maybeBuildParamsFromRule(rule string) (TestingBuildParams, []string) {
Thiébaud Weksteen3600b802020-08-27 15:50:24 +0200774 var searchedRules []string
Paul Duffin4dbf6cf2021-06-08 10:06:37 +0100775 buildParams := b.provider.BuildParamsForTests()
776 for _, p := range buildParams {
777 ruleAsString := p.Rule.String()
778 searchedRules = append(searchedRules, ruleAsString)
779 if strings.Contains(ruleAsString, rule) {
Paul Duffin0eda26b92021-03-22 09:34:29 +0000780 return b.newTestingBuildParams(p), searchedRules
Colin Cross4c83e5c2019-02-25 14:54:28 -0800781 }
782 }
Thiébaud Weksteen3600b802020-08-27 15:50:24 +0200783 return TestingBuildParams{}, searchedRules
Colin Cross4c83e5c2019-02-25 14:54:28 -0800784}
785
Paul Duffin0eda26b92021-03-22 09:34:29 +0000786func (b baseTestingComponent) buildParamsFromRule(rule string) TestingBuildParams {
787 p, searchRules := b.maybeBuildParamsFromRule(rule)
Colin Cross4c83e5c2019-02-25 14:54:28 -0800788 if p.Rule == nil {
Paul Duffin4dbf6cf2021-06-08 10:06:37 +0100789 panic(fmt.Errorf("couldn't find rule %q.\nall rules:\n%s", rule, strings.Join(searchRules, "\n")))
Colin Cross4c83e5c2019-02-25 14:54:28 -0800790 }
791 return p
792}
793
Paul Duffin0eda26b92021-03-22 09:34:29 +0000794func (b baseTestingComponent) maybeBuildParamsFromDescription(desc string) TestingBuildParams {
795 for _, p := range b.provider.BuildParamsForTests() {
Colin Crossb88b3c52019-06-10 15:15:17 -0700796 if strings.Contains(p.Description, desc) {
Paul Duffin0eda26b92021-03-22 09:34:29 +0000797 return b.newTestingBuildParams(p)
Colin Cross4c83e5c2019-02-25 14:54:28 -0800798 }
799 }
800 return TestingBuildParams{}
801}
802
Paul Duffin0eda26b92021-03-22 09:34:29 +0000803func (b baseTestingComponent) buildParamsFromDescription(desc string) TestingBuildParams {
804 p := b.maybeBuildParamsFromDescription(desc)
Colin Cross4c83e5c2019-02-25 14:54:28 -0800805 if p.Rule == nil {
806 panic(fmt.Errorf("couldn't find description %q", desc))
807 }
808 return p
809}
810
Paul Duffin0eda26b92021-03-22 09:34:29 +0000811func (b baseTestingComponent) maybeBuildParamsFromOutput(file string) (TestingBuildParams, []string) {
Martin Stjernholma4aaa472021-09-17 02:51:48 +0100812 searchedOutputs := WritablePaths(nil)
Paul Duffin0eda26b92021-03-22 09:34:29 +0000813 for _, p := range b.provider.BuildParamsForTests() {
Colin Cross4c83e5c2019-02-25 14:54:28 -0800814 outputs := append(WritablePaths(nil), p.Outputs...)
Colin Cross1d2cf042019-03-29 15:33:06 -0700815 outputs = append(outputs, p.ImplicitOutputs...)
Colin Cross4c83e5c2019-02-25 14:54:28 -0800816 if p.Output != nil {
817 outputs = append(outputs, p.Output)
818 }
819 for _, f := range outputs {
Paul Duffin4e6e35c2021-03-22 11:34:57 +0000820 if f.String() == file || f.Rel() == file || PathRelativeToTop(f) == file {
Paul Duffin0eda26b92021-03-22 09:34:29 +0000821 return b.newTestingBuildParams(p), nil
Colin Cross4c83e5c2019-02-25 14:54:28 -0800822 }
Martin Stjernholma4aaa472021-09-17 02:51:48 +0100823 searchedOutputs = append(searchedOutputs, f)
Colin Cross4c83e5c2019-02-25 14:54:28 -0800824 }
825 }
Martin Stjernholma4aaa472021-09-17 02:51:48 +0100826
827 formattedOutputs := []string{}
828 for _, f := range searchedOutputs {
829 formattedOutputs = append(formattedOutputs,
830 fmt.Sprintf("%s (rel=%s)", PathRelativeToTop(f), f.Rel()))
831 }
832
833 return TestingBuildParams{}, formattedOutputs
Colin Cross4c83e5c2019-02-25 14:54:28 -0800834}
835
Paul Duffin0eda26b92021-03-22 09:34:29 +0000836func (b baseTestingComponent) buildParamsFromOutput(file string) TestingBuildParams {
837 p, searchedOutputs := b.maybeBuildParamsFromOutput(file)
Colin Cross4c83e5c2019-02-25 14:54:28 -0800838 if p.Rule == nil {
Paul Duffin4e6e35c2021-03-22 11:34:57 +0000839 panic(fmt.Errorf("couldn't find output %q.\nall outputs:\n %s\n",
840 file, strings.Join(searchedOutputs, "\n ")))
Colin Cross4c83e5c2019-02-25 14:54:28 -0800841 }
842 return p
843}
844
Paul Duffin0eda26b92021-03-22 09:34:29 +0000845func (b baseTestingComponent) allOutputs() []string {
Colin Cross4c83e5c2019-02-25 14:54:28 -0800846 var outputFullPaths []string
Paul Duffin0eda26b92021-03-22 09:34:29 +0000847 for _, p := range b.provider.BuildParamsForTests() {
Colin Cross4c83e5c2019-02-25 14:54:28 -0800848 outputs := append(WritablePaths(nil), p.Outputs...)
Colin Cross1d2cf042019-03-29 15:33:06 -0700849 outputs = append(outputs, p.ImplicitOutputs...)
Colin Cross4c83e5c2019-02-25 14:54:28 -0800850 if p.Output != nil {
851 outputs = append(outputs, p.Output)
852 }
853 outputFullPaths = append(outputFullPaths, outputs.Strings()...)
854 }
855 return outputFullPaths
856}
857
Paul Duffin31a22882021-03-22 09:29:00 +0000858// MaybeRule finds a call to ctx.Build with BuildParams.Rule set to a rule with the given name. Returns an empty
859// BuildParams if no rule is found.
860func (b baseTestingComponent) MaybeRule(rule string) TestingBuildParams {
Paul Duffin0eda26b92021-03-22 09:34:29 +0000861 r, _ := b.maybeBuildParamsFromRule(rule)
Paul Duffin31a22882021-03-22 09:29:00 +0000862 return r
863}
864
865// Rule finds a call to ctx.Build with BuildParams.Rule set to a rule with the given name. Panics if no rule is found.
866func (b baseTestingComponent) Rule(rule string) TestingBuildParams {
Paul Duffin0eda26b92021-03-22 09:34:29 +0000867 return b.buildParamsFromRule(rule)
Paul Duffin31a22882021-03-22 09:29:00 +0000868}
869
870// MaybeDescription finds a call to ctx.Build with BuildParams.Description set to a the given string. Returns an empty
871// BuildParams if no rule is found.
872func (b baseTestingComponent) MaybeDescription(desc string) TestingBuildParams {
Paul Duffin0eda26b92021-03-22 09:34:29 +0000873 return b.maybeBuildParamsFromDescription(desc)
Paul Duffin31a22882021-03-22 09:29:00 +0000874}
875
876// Description finds a call to ctx.Build with BuildParams.Description set to a the given string. Panics if no rule is
877// found.
878func (b baseTestingComponent) Description(desc string) TestingBuildParams {
Paul Duffin0eda26b92021-03-22 09:34:29 +0000879 return b.buildParamsFromDescription(desc)
Paul Duffin31a22882021-03-22 09:29:00 +0000880}
881
882// MaybeOutput finds a call to ctx.Build with a BuildParams.Output or BuildParams.Outputs whose String() or Rel()
883// value matches the provided string. Returns an empty BuildParams if no rule is found.
884func (b baseTestingComponent) MaybeOutput(file string) TestingBuildParams {
Paul Duffin0eda26b92021-03-22 09:34:29 +0000885 p, _ := b.maybeBuildParamsFromOutput(file)
Paul Duffin31a22882021-03-22 09:29:00 +0000886 return p
887}
888
889// Output finds a call to ctx.Build with a BuildParams.Output or BuildParams.Outputs whose String() or Rel()
890// value matches the provided string. Panics if no rule is found.
891func (b baseTestingComponent) Output(file string) TestingBuildParams {
Paul Duffin0eda26b92021-03-22 09:34:29 +0000892 return b.buildParamsFromOutput(file)
Paul Duffin31a22882021-03-22 09:29:00 +0000893}
894
895// AllOutputs returns all 'BuildParams.Output's and 'BuildParams.Outputs's in their full path string forms.
896func (b baseTestingComponent) AllOutputs() []string {
Paul Duffin0eda26b92021-03-22 09:34:29 +0000897 return b.allOutputs()
Paul Duffin31a22882021-03-22 09:29:00 +0000898}
899
Colin Crossb77ffc42019-01-05 22:09:19 -0800900// TestingModule is wrapper around an android.Module that provides methods to find information about individual
901// ctx.Build parameters for verification in tests.
Colin Crosscec81712017-07-13 14:43:27 -0700902type TestingModule struct {
Paul Duffin31a22882021-03-22 09:29:00 +0000903 baseTestingComponent
Colin Crosscec81712017-07-13 14:43:27 -0700904 module Module
905}
906
Paul Duffin709e0e32021-03-22 10:09:02 +0000907func newTestingModule(config Config, module Module) TestingModule {
Paul Duffin31a22882021-03-22 09:29:00 +0000908 return TestingModule{
Paul Duffin709e0e32021-03-22 10:09:02 +0000909 newBaseTestingComponent(config, module),
Paul Duffin31a22882021-03-22 09:29:00 +0000910 module,
911 }
912}
913
Colin Crossb77ffc42019-01-05 22:09:19 -0800914// Module returns the Module wrapped by the TestingModule.
Colin Crosscec81712017-07-13 14:43:27 -0700915func (m TestingModule) Module() Module {
916 return m.module
917}
918
Paul Duffin97d8b402021-03-22 16:04:50 +0000919// VariablesForTestsRelativeToTop returns a copy of the Module.VariablesForTests() with every value
920// having any temporary build dir usages replaced with paths relative to a notional top.
921func (m TestingModule) VariablesForTestsRelativeToTop() map[string]string {
922 return normalizeStringMapRelativeToTop(m.config, m.module.VariablesForTests())
923}
924
Paul Duffin962783a2021-03-29 00:00:17 +0100925// OutputFiles calls OutputFileProducer.OutputFiles on the encapsulated module, exits the test
926// immediately if there is an error and otherwise returns the result of calling Paths.RelativeToTop
927// on the returned Paths.
928func (m TestingModule) OutputFiles(t *testing.T, tag string) Paths {
929 producer, ok := m.module.(OutputFileProducer)
930 if !ok {
931 t.Fatalf("%q must implement OutputFileProducer\n", m.module.Name())
932 }
933 paths, err := producer.OutputFiles(tag)
934 if err != nil {
935 t.Fatal(err)
936 }
937
938 return paths.RelativeToTop()
939}
940
Colin Cross4c83e5c2019-02-25 14:54:28 -0800941// TestingSingleton is wrapper around an android.Singleton that provides methods to find information about individual
942// ctx.Build parameters for verification in tests.
943type TestingSingleton struct {
Paul Duffin31a22882021-03-22 09:29:00 +0000944 baseTestingComponent
Colin Cross4c83e5c2019-02-25 14:54:28 -0800945 singleton Singleton
Colin Cross4c83e5c2019-02-25 14:54:28 -0800946}
947
948// Singleton returns the Singleton wrapped by the TestingSingleton.
949func (s TestingSingleton) Singleton() Singleton {
950 return s.singleton
951}
952
Logan Chien42039712018-03-12 16:29:17 +0800953func FailIfErrored(t *testing.T, errs []error) {
954 t.Helper()
955 if len(errs) > 0 {
956 for _, err := range errs {
957 t.Error(err)
958 }
959 t.FailNow()
960 }
961}
Logan Chienee97c3e2018-03-12 16:34:26 +0800962
Paul Duffinea8a3862021-03-04 17:58:33 +0000963// Fail if no errors that matched the regular expression were found.
964//
965// Returns true if a matching error was found, false otherwise.
966func FailIfNoMatchingErrors(t *testing.T, pattern string, errs []error) bool {
Logan Chienee97c3e2018-03-12 16:34:26 +0800967 t.Helper()
968
969 matcher, err := regexp.Compile(pattern)
970 if err != nil {
Paul Duffinea8a3862021-03-04 17:58:33 +0000971 t.Fatalf("failed to compile regular expression %q because %s", pattern, err)
Logan Chienee97c3e2018-03-12 16:34:26 +0800972 }
973
974 found := false
975 for _, err := range errs {
976 if matcher.FindStringIndex(err.Error()) != nil {
977 found = true
978 break
979 }
980 }
981 if !found {
982 t.Errorf("missing the expected error %q (checked %d error(s))", pattern, len(errs))
983 for i, err := range errs {
Colin Crossaede88c2020-08-11 12:17:01 -0700984 t.Errorf("errs[%d] = %q", i, err)
Logan Chienee97c3e2018-03-12 16:34:26 +0800985 }
986 }
Paul Duffinea8a3862021-03-04 17:58:33 +0000987
988 return found
Logan Chienee97c3e2018-03-12 16:34:26 +0800989}
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700990
Paul Duffin91e38192019-08-05 15:07:57 +0100991func CheckErrorsAgainstExpectations(t *testing.T, errs []error, expectedErrorPatterns []string) {
992 t.Helper()
993
994 if expectedErrorPatterns == nil {
995 FailIfErrored(t, errs)
996 } else {
997 for _, expectedError := range expectedErrorPatterns {
998 FailIfNoMatchingErrors(t, expectedError, errs)
999 }
1000 if len(errs) > len(expectedErrorPatterns) {
1001 t.Errorf("additional errors found, expected %d, found %d",
1002 len(expectedErrorPatterns), len(errs))
1003 for i, expectedError := range expectedErrorPatterns {
1004 t.Errorf("expectedErrors[%d] = %s", i, expectedError)
1005 }
1006 for i, err := range errs {
1007 t.Errorf("errs[%d] = %s", i, err)
1008 }
Paul Duffinea8a3862021-03-04 17:58:33 +00001009 t.FailNow()
Paul Duffin91e38192019-08-05 15:07:57 +01001010 }
1011 }
Paul Duffin91e38192019-08-05 15:07:57 +01001012}
1013
Jingwen Chencda22c92020-11-23 00:22:30 -05001014func SetKatiEnabledForTests(config Config) {
1015 config.katiEnabled = true
Paul Duffin8c3fec42020-03-04 20:15:08 +00001016}
1017
Colin Crossaa255532020-07-03 13:18:24 -07001018func AndroidMkEntriesForTest(t *testing.T, ctx *TestContext, mod blueprint.Module) []AndroidMkEntries {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -07001019 var p AndroidMkEntriesProvider
1020 var ok bool
1021 if p, ok = mod.(AndroidMkEntriesProvider); !ok {
Roland Levillaindfe75b32019-07-23 16:53:32 +01001022 t.Errorf("module does not implement AndroidMkEntriesProvider: " + mod.Name())
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -07001023 }
Jiyong Park0b0e1b92019-12-03 13:24:29 +09001024
1025 entriesList := p.AndroidMkEntries()
1026 for i, _ := range entriesList {
Colin Crossaa255532020-07-03 13:18:24 -07001027 entriesList[i].fillInEntries(ctx, mod)
Jiyong Park0b0e1b92019-12-03 13:24:29 +09001028 }
1029 return entriesList
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -07001030}
Jooyung Han12df5fb2019-07-11 16:18:47 +09001031
Colin Crossaa255532020-07-03 13:18:24 -07001032func AndroidMkDataForTest(t *testing.T, ctx *TestContext, mod blueprint.Module) AndroidMkData {
Jooyung Han12df5fb2019-07-11 16:18:47 +09001033 var p AndroidMkDataProvider
1034 var ok bool
1035 if p, ok = mod.(AndroidMkDataProvider); !ok {
Roland Levillaindfe75b32019-07-23 16:53:32 +01001036 t.Errorf("module does not implement AndroidMkDataProvider: " + mod.Name())
Jooyung Han12df5fb2019-07-11 16:18:47 +09001037 }
1038 data := p.AndroidMk()
Colin Crossaa255532020-07-03 13:18:24 -07001039 data.fillInData(ctx, mod)
Jooyung Han12df5fb2019-07-11 16:18:47 +09001040 return data
1041}
Paul Duffin9b478b02019-12-10 13:41:51 +00001042
1043// Normalize the path for testing.
1044//
1045// If the path is relative to the build directory then return the relative path
1046// to avoid tests having to deal with the dynamically generated build directory.
1047//
1048// Otherwise, return the supplied path as it is almost certainly a source path
1049// that is relative to the root of the source tree.
1050//
1051// The build and source paths should be distinguishable based on their contents.
Paul Duffin567465d2021-03-16 01:21:34 +00001052//
1053// deprecated: use PathRelativeToTop instead as it handles make install paths and differentiates
1054// between output and source properly.
Paul Duffin9b478b02019-12-10 13:41:51 +00001055func NormalizePathForTesting(path Path) string {
Paul Duffin064b70c2020-11-02 17:32:38 +00001056 if path == nil {
1057 return "<nil path>"
1058 }
Paul Duffin9b478b02019-12-10 13:41:51 +00001059 p := path.String()
1060 if w, ok := path.(WritablePath); ok {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001061 rel, err := filepath.Rel(w.getSoongOutDir(), p)
Paul Duffin9b478b02019-12-10 13:41:51 +00001062 if err != nil {
1063 panic(err)
1064 }
1065 return rel
1066 }
1067 return p
1068}
1069
Paul Duffin567465d2021-03-16 01:21:34 +00001070// NormalizePathsForTesting creates a slice of strings where each string is the result of applying
1071// NormalizePathForTesting to the corresponding Path in the input slice.
1072//
1073// deprecated: use PathsRelativeToTop instead as it handles make install paths and differentiates
1074// between output and source properly.
Paul Duffin9b478b02019-12-10 13:41:51 +00001075func NormalizePathsForTesting(paths Paths) []string {
1076 var result []string
1077 for _, path := range paths {
1078 relative := NormalizePathForTesting(path)
1079 result = append(result, relative)
1080 }
1081 return result
1082}
Paul Duffin567465d2021-03-16 01:21:34 +00001083
1084// PathRelativeToTop returns a string representation of the path relative to a notional top
1085// directory.
1086//
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001087// It return "<nil path>" if the supplied path is nil, otherwise it returns the result of calling
1088// Path.RelativeToTop to obtain a relative Path and then calling Path.String on that to get the
1089// string representation.
Paul Duffin567465d2021-03-16 01:21:34 +00001090func PathRelativeToTop(path Path) string {
1091 if path == nil {
1092 return "<nil path>"
1093 }
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001094 return path.RelativeToTop().String()
Paul Duffin567465d2021-03-16 01:21:34 +00001095}
1096
1097// PathsRelativeToTop creates a slice of strings where each string is the result of applying
1098// PathRelativeToTop to the corresponding Path in the input slice.
1099func PathsRelativeToTop(paths Paths) []string {
1100 var result []string
1101 for _, path := range paths {
1102 relative := PathRelativeToTop(path)
1103 result = append(result, relative)
1104 }
1105 return result
1106}
1107
1108// StringPathRelativeToTop returns a string representation of the path relative to a notional top
1109// directory.
1110//
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001111// See Path.RelativeToTop for more details as to what `relative to top` means.
Paul Duffin567465d2021-03-16 01:21:34 +00001112//
1113// This is provided for processing paths that have already been converted into a string, e.g. paths
1114// in AndroidMkEntries structures. As a result it needs to be supplied the soong output dir against
1115// which it can try and relativize paths. PathRelativeToTop must be used for process Path objects.
1116func StringPathRelativeToTop(soongOutDir string, path string) string {
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001117 ensureTestOnly()
Paul Duffin567465d2021-03-16 01:21:34 +00001118
1119 // A relative path must be a source path so leave it as it is.
1120 if !filepath.IsAbs(path) {
1121 return path
1122 }
1123
1124 // Check to see if the path is relative to the soong out dir.
1125 rel, isRel, err := maybeRelErr(soongOutDir, path)
1126 if err != nil {
1127 panic(err)
1128 }
1129
1130 if isRel {
1131 // The path is in the soong out dir so indicate that in the relative path.
1132 return filepath.Join("out/soong", rel)
1133 }
1134
1135 // Check to see if the path is relative to the top level out dir.
1136 outDir := filepath.Dir(soongOutDir)
1137 rel, isRel, err = maybeRelErr(outDir, path)
1138 if err != nil {
1139 panic(err)
1140 }
1141
1142 if isRel {
1143 // The path is in the out dir so indicate that in the relative path.
1144 return filepath.Join("out", rel)
1145 }
1146
1147 // This should never happen.
1148 panic(fmt.Errorf("internal error: absolute path %s is not relative to the out dir %s", path, outDir))
1149}
1150
1151// StringPathsRelativeToTop creates a slice of strings where each string is the result of applying
1152// StringPathRelativeToTop to the corresponding string path in the input slice.
1153//
1154// This is provided for processing paths that have already been converted into a string, e.g. paths
1155// in AndroidMkEntries structures. As a result it needs to be supplied the soong output dir against
1156// which it can try and relativize paths. PathsRelativeToTop must be used for process Paths objects.
1157func StringPathsRelativeToTop(soongOutDir string, paths []string) []string {
1158 var result []string
1159 for _, path := range paths {
1160 relative := StringPathRelativeToTop(soongOutDir, path)
1161 result = append(result, relative)
1162 }
1163 return result
1164}
Paul Duffinf53555d2021-03-29 00:21:00 +01001165
1166// StringRelativeToTop will normalize a string containing paths, e.g. ninja command, by replacing
1167// any references to the test specific temporary build directory that changes with each run to a
1168// fixed path relative to a notional top directory.
1169//
1170// This is similar to StringPathRelativeToTop except that assumes the string is a single path
1171// containing at most one instance of the temporary build directory at the start of the path while
1172// this assumes that there can be any number at any position.
1173func StringRelativeToTop(config Config, command string) string {
1174 return normalizeStringRelativeToTop(config, command)
1175}
Paul Duffin0aafcbf2021-03-29 00:56:32 +01001176
1177// StringsRelativeToTop will return a new slice such that each item in the new slice is the result
1178// of calling StringRelativeToTop on the corresponding item in the input slice.
1179func StringsRelativeToTop(config Config, command []string) []string {
1180 return normalizeStringArrayRelativeToTop(config, command)
1181}