blob: a3e35cb99491b1947628c5847c7bbfbbc783511b [file] [log] [blame]
Colin Crosscec81712017-07-13 14:43:27 -07001// Copyright 2017 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package android
16
17import (
Martin Stjernholm1ebef5b2022-02-10 23:34:28 +000018 "bytes"
Colin Crosscec81712017-07-13 14:43:27 -070019 "fmt"
Paul Duffin9b478b02019-12-10 13:41:51 +000020 "path/filepath"
Logan Chienee97c3e2018-03-12 16:34:26 +080021 "regexp"
Martin Stjernholm4c021242020-05-13 01:13:50 +010022 "sort"
Colin Crosscec81712017-07-13 14:43:27 -070023 "strings"
Paul Duffin281deb22021-03-06 20:29:19 +000024 "sync"
Logan Chien42039712018-03-12 16:29:17 +080025 "testing"
Colin Crosscec81712017-07-13 14:43:27 -070026
Martin Stjernholm1ebef5b2022-02-10 23:34:28 +000027 mkparser "android/soong/androidmk/parser"
28
Colin Crosscec81712017-07-13 14:43:27 -070029 "github.com/google/blueprint"
Paul Duffin25259e92021-03-07 15:45:56 +000030 "github.com/google/blueprint/proptools"
Colin Crosscec81712017-07-13 14:43:27 -070031)
32
Paul Duffin3f7bf9f2022-11-08 12:21:15 +000033func newTestContextForFixture(config Config) *TestContext {
Jeff Gastonb274ed32017-12-01 17:10:33 -080034 ctx := &TestContext{
Paul Duffin3f7bf9f2022-11-08 12:21:15 +000035 Context: &Context{blueprint.NewContext(), config},
Jeff Gastonb274ed32017-12-01 17:10:33 -080036 }
37
Colin Cross1b488422019-03-04 22:33:56 -080038 ctx.postDeps = append(ctx.postDeps, registerPathDepsMutator)
39
Colin Crossae8600b2020-10-29 17:09:13 -070040 ctx.SetFs(ctx.config.fs)
41 if ctx.config.mockBpList != "" {
42 ctx.SetModuleListFile(ctx.config.mockBpList)
43 }
44
Jeff Gaston088e29e2017-11-29 16:47:17 -080045 return ctx
Colin Crosscec81712017-07-13 14:43:27 -070046}
47
Paul Duffin3f7bf9f2022-11-08 12:21:15 +000048func NewTestContext(config Config) *TestContext {
49 ctx := newTestContextForFixture(config)
50
51 nameResolver := NewNameResolver(config)
52 ctx.NameResolver = nameResolver
53 ctx.SetNameInterface(nameResolver)
54
55 return ctx
56}
57
Paul Duffina560d5a2021-02-28 01:38:51 +000058var PrepareForTestWithArchMutator = GroupFixturePreparers(
Paul Duffin35816122021-02-24 01:49:52 +000059 // Configure architecture targets in the fixture config.
60 FixtureModifyConfig(modifyTestConfigToSupportArchMutator),
61
62 // Add the arch mutator to the context.
63 FixtureRegisterWithContext(func(ctx RegistrationContext) {
64 ctx.PreDepsMutators(registerArchMutator)
65 }),
66)
67
68var PrepareForTestWithDefaults = FixtureRegisterWithContext(func(ctx RegistrationContext) {
69 ctx.PreArchMutators(RegisterDefaultsPreArchMutators)
70})
71
72var PrepareForTestWithComponentsMutator = FixtureRegisterWithContext(func(ctx RegistrationContext) {
73 ctx.PreArchMutators(RegisterComponentsMutator)
74})
75
76var PrepareForTestWithPrebuilts = FixtureRegisterWithContext(RegisterPrebuiltMutators)
77
78var PrepareForTestWithOverrides = FixtureRegisterWithContext(func(ctx RegistrationContext) {
79 ctx.PostDepsMutators(RegisterOverridePostDepsMutators)
80})
81
Paul Duffine96108d2021-05-06 16:39:27 +010082var PrepareForTestWithLicenses = GroupFixturePreparers(
83 FixtureRegisterWithContext(RegisterLicenseKindBuildComponents),
84 FixtureRegisterWithContext(RegisterLicenseBuildComponents),
85 FixtureRegisterWithContext(registerLicenseMutators),
86)
87
Bob Badour05079212022-05-20 16:41:39 -070088var PrepareForTestWithGenNotice = FixtureRegisterWithContext(RegisterGenNoticeBuildComponents)
89
Paul Duffine96108d2021-05-06 16:39:27 +010090func registerLicenseMutators(ctx RegistrationContext) {
91 ctx.PreArchMutators(RegisterLicensesPackageMapper)
92 ctx.PreArchMutators(RegisterLicensesPropertyGatherer)
93 ctx.PostDepsMutators(RegisterLicensesDependencyChecker)
94}
95
96var PrepareForTestWithLicenseDefaultModules = GroupFixturePreparers(
97 FixtureAddTextFile("build/soong/licenses/Android.bp", `
98 license {
99 name: "Android-Apache-2.0",
100 package_name: "Android",
101 license_kinds: ["SPDX-license-identifier-Apache-2.0"],
102 copyright_notice: "Copyright (C) The Android Open Source Project",
103 license_text: ["LICENSE"],
104 }
105
106 license_kind {
107 name: "SPDX-license-identifier-Apache-2.0",
108 conditions: ["notice"],
109 url: "https://spdx.org/licenses/Apache-2.0.html",
110 }
111
112 license_kind {
113 name: "legacy_unencumbered",
114 conditions: ["unencumbered"],
115 }
116 `),
117 FixtureAddFile("build/soong/licenses/LICENSE", nil),
118)
119
Paul Duffin4fbfb592021-07-09 16:47:38 +0100120var PrepareForTestWithNamespace = FixtureRegisterWithContext(func(ctx RegistrationContext) {
121 registerNamespaceBuildComponents(ctx)
122 ctx.PreArchMutators(RegisterNamespaceMutator)
123})
124
Martin Stjernholm1ebef5b2022-02-10 23:34:28 +0000125var PrepareForTestWithMakevars = FixtureRegisterWithContext(func(ctx RegistrationContext) {
126 ctx.RegisterSingletonType("makevars", makeVarsSingletonFunc)
127})
128
Paul Duffinec3292b2021-03-09 01:01:31 +0000129// Test fixture preparer that will register most java build components.
130//
131// Singletons and mutators should only be added here if they are needed for a majority of java
132// module types, otherwise they should be added under a separate preparer to allow them to be
133// selected only when needed to reduce test execution time.
134//
135// Module types do not have much of an overhead unless they are used so this should include as many
136// module types as possible. The exceptions are those module types that require mutators and/or
137// singletons in order to function in which case they should be kept together in a separate
138// preparer.
139//
140// The mutators in this group were chosen because they are needed by the vast majority of tests.
141var PrepareForTestWithAndroidBuildComponents = GroupFixturePreparers(
Paul Duffin530483c2021-03-07 13:20:38 +0000142 // Sorted alphabetically as the actual order does not matter as tests automatically enforce the
143 // correct order.
Paul Duffin35816122021-02-24 01:49:52 +0000144 PrepareForTestWithArchMutator,
Paul Duffin35816122021-02-24 01:49:52 +0000145 PrepareForTestWithComponentsMutator,
Paul Duffin530483c2021-03-07 13:20:38 +0000146 PrepareForTestWithDefaults,
Paul Duffin35816122021-02-24 01:49:52 +0000147 PrepareForTestWithFilegroup,
Paul Duffin530483c2021-03-07 13:20:38 +0000148 PrepareForTestWithOverrides,
149 PrepareForTestWithPackageModule,
150 PrepareForTestWithPrebuilts,
151 PrepareForTestWithVisibility,
Paul Duffin35816122021-02-24 01:49:52 +0000152)
153
Paul Duffinec3292b2021-03-09 01:01:31 +0000154// Prepares an integration test with all build components from the android package.
155//
156// This should only be used by tests that want to run with as much of the build enabled as possible.
157var PrepareForIntegrationTestWithAndroid = GroupFixturePreparers(
158 PrepareForTestWithAndroidBuildComponents,
159)
160
Paul Duffin25259e92021-03-07 15:45:56 +0000161// Prepares a test that may be missing dependencies by setting allow_missing_dependencies to
162// true.
163var PrepareForTestWithAllowMissingDependencies = GroupFixturePreparers(
164 FixtureModifyProductVariables(func(variables FixtureProductVariables) {
165 variables.Allow_missing_dependencies = proptools.BoolPtr(true)
166 }),
167 FixtureModifyContext(func(ctx *TestContext) {
168 ctx.SetAllowMissingDependencies(true)
169 }),
170)
171
Paul Duffin76e5c8a2021-03-20 14:19:46 +0000172// Prepares a test that disallows non-existent paths.
173var PrepareForTestDisallowNonExistentPaths = FixtureModifyConfig(func(config Config) {
174 config.TestAllowNonExistentPaths = false
175})
176
Colin Crossa66b4632024-08-08 15:50:47 -0700177// PrepareForTestWithBuildFlag returns a FixturePreparer that sets the given flag to the given value.
178func PrepareForTestWithBuildFlag(flag, value string) FixturePreparer {
179 return FixtureModifyProductVariables(func(variables FixtureProductVariables) {
180 if variables.BuildFlags == nil {
181 variables.BuildFlags = make(map[string]string)
182 }
183 variables.BuildFlags[flag] = value
184 })
185}
186
Colin Crossae8600b2020-10-29 17:09:13 -0700187func NewTestArchContext(config Config) *TestContext {
188 ctx := NewTestContext(config)
Colin Crossae4c6182017-09-15 17:33:55 -0700189 ctx.preDeps = append(ctx.preDeps, registerArchMutator)
190 return ctx
191}
192
Colin Crosscec81712017-07-13 14:43:27 -0700193type TestContext struct {
Colin Cross4c83e5c2019-02-25 14:54:28 -0800194 *Context
Chris Parsons5a34ffb2021-07-21 14:34:58 -0400195 preArch, preDeps, postDeps, finalDeps []RegisterMutatorFunc
Chris Parsons5a34ffb2021-07-21 14:34:58 -0400196 NameResolver *NameResolver
Paul Duffin281deb22021-03-06 20:29:19 +0000197
Cole Faustae6cda62023-11-01 15:32:40 -0700198 // The list of singletons registered for the test.
199 singletons sortableComponents
Paul Duffind182fb32021-03-07 12:24:44 +0000200
Cole Faustae6cda62023-11-01 15:32:40 -0700201 // The order in which the mutators and singletons will be run in this test
Paul Duffin41d77c72021-03-07 12:23:48 +0000202 // context; for debugging.
Cole Faustae6cda62023-11-01 15:32:40 -0700203 mutatorOrder, singletonOrder []string
Colin Crosscec81712017-07-13 14:43:27 -0700204}
205
206func (ctx *TestContext) PreArchMutators(f RegisterMutatorFunc) {
207 ctx.preArch = append(ctx.preArch, f)
208}
209
Paul Duffina80ef842020-01-14 12:09:36 +0000210func (ctx *TestContext) HardCodedPreArchMutators(f RegisterMutatorFunc) {
211 // Register mutator function as normal for testing.
212 ctx.PreArchMutators(f)
213}
214
Yu Liu663e4502024-08-12 18:23:59 +0000215func (ctx *TestContext) otherModuleProvider(m blueprint.Module, p blueprint.AnyProviderKey) (any, bool) {
Liz Kammer92c72592022-10-31 14:44:28 -0400216 return ctx.Context.ModuleProvider(m, p)
217}
218
Colin Crosscec81712017-07-13 14:43:27 -0700219func (ctx *TestContext) PreDepsMutators(f RegisterMutatorFunc) {
220 ctx.preDeps = append(ctx.preDeps, f)
221}
222
223func (ctx *TestContext) PostDepsMutators(f RegisterMutatorFunc) {
224 ctx.postDeps = append(ctx.postDeps, f)
225}
226
Martin Stjernholm710ec3a2020-01-16 15:12:04 +0000227func (ctx *TestContext) FinalDepsMutators(f RegisterMutatorFunc) {
228 ctx.finalDeps = append(ctx.finalDeps, f)
229}
230
Colin Cross3c0a83d2023-12-12 14:13:26 -0800231func (ctx *TestContext) OtherModuleProviderAdaptor() OtherModuleProviderContext {
232 return NewOtherModuleProviderAdaptor(func(module blueprint.Module, provider blueprint.AnyProviderKey) (any, bool) {
Yu Liu663e4502024-08-12 18:23:59 +0000233 return ctx.otherModuleProvider(module, provider)
Colin Cross3c0a83d2023-12-12 14:13:26 -0800234 })
235}
236
Cole Faust43ddd082024-06-17 12:32:40 -0700237func (ctx *TestContext) OtherModulePropertyErrorf(module Module, property string, fmt_ string, args ...interface{}) {
238 panic(fmt.Sprintf(fmt_, args...))
239}
240
Paul Duffin281deb22021-03-06 20:29:19 +0000241// registeredComponentOrder defines the order in which a sortableComponent type is registered at
242// runtime and provides support for reordering the components registered for a test in the same
243// way.
244type registeredComponentOrder struct {
245 // The name of the component type, used for error messages.
246 componentType string
247
248 // The names of the registered components in the order in which they were registered.
249 namesInOrder []string
250
251 // Maps from the component name to its position in the runtime ordering.
252 namesToIndex map[string]int
253
254 // A function that defines the order between two named components that can be used to sort a slice
255 // of component names into the same order as they appear in namesInOrder.
256 less func(string, string) bool
257}
258
259// registeredComponentOrderFromExistingOrder takes an existing slice of sortableComponents and
260// creates a registeredComponentOrder that contains a less function that can be used to sort a
261// subset of that list of names so it is in the same order as the original sortableComponents.
262func registeredComponentOrderFromExistingOrder(componentType string, existingOrder sortableComponents) registeredComponentOrder {
263 // Only the names from the existing order are needed for this so create a list of component names
264 // in the correct order.
265 namesInOrder := componentsToNames(existingOrder)
266
267 // Populate the map from name to position in the list.
268 nameToIndex := make(map[string]int)
269 for i, n := range namesInOrder {
270 nameToIndex[n] = i
271 }
272
273 // A function to use to map from a name to an index in the original order.
274 indexOf := func(name string) int {
275 index, ok := nameToIndex[name]
276 if !ok {
277 // Should never happen as tests that use components that are not known at runtime do not sort
278 // so should never use this function.
279 panic(fmt.Errorf("internal error: unknown %s %q should be one of %s", componentType, name, strings.Join(namesInOrder, ", ")))
280 }
281 return index
282 }
283
284 // The less function.
285 less := func(n1, n2 string) bool {
286 i1 := indexOf(n1)
287 i2 := indexOf(n2)
288 return i1 < i2
289 }
290
291 return registeredComponentOrder{
292 componentType: componentType,
293 namesInOrder: namesInOrder,
294 namesToIndex: nameToIndex,
295 less: less,
296 }
297}
298
299// componentsToNames maps from the slice of components to a slice of their names.
300func componentsToNames(components sortableComponents) []string {
301 names := make([]string, len(components))
302 for i, c := range components {
303 names[i] = c.componentName()
304 }
305 return names
306}
307
308// enforceOrdering enforces the supplied components are in the same order as is defined in this
309// object.
310//
311// If the supplied components contains any components that are not registered at runtime, i.e. test
312// specific components, then it is impossible to sort them into an order that both matches the
313// runtime and also preserves the implicit ordering defined in the test. In that case it will not
314// sort the components, instead it will just check that the components are in the correct order.
315//
316// Otherwise, this will sort the supplied components in place.
317func (o *registeredComponentOrder) enforceOrdering(components sortableComponents) {
318 // Check to see if the list of components contains any components that are
319 // not registered at runtime.
320 var unknownComponents []string
321 testOrder := componentsToNames(components)
322 for _, name := range testOrder {
323 if _, ok := o.namesToIndex[name]; !ok {
324 unknownComponents = append(unknownComponents, name)
325 break
326 }
327 }
328
329 // If the slice contains some unknown components then it is not possible to
330 // sort them into an order that matches the runtime while also preserving the
331 // order expected from the test, so in that case don't sort just check that
332 // the order of the known mutators does match.
333 if len(unknownComponents) > 0 {
334 // Check order.
335 o.checkTestOrder(testOrder, unknownComponents)
336 } else {
337 // Sort the components.
338 sort.Slice(components, func(i, j int) bool {
339 n1 := components[i].componentName()
340 n2 := components[j].componentName()
341 return o.less(n1, n2)
342 })
343 }
344}
345
346// checkTestOrder checks that the supplied testOrder matches the one defined by this object,
347// panicking if it does not.
348func (o *registeredComponentOrder) checkTestOrder(testOrder []string, unknownComponents []string) {
349 lastMatchingTest := -1
350 matchCount := 0
351 // Take a copy of the runtime order as it is modified during the comparison.
352 runtimeOrder := append([]string(nil), o.namesInOrder...)
353 componentType := o.componentType
354 for i, j := 0, 0; i < len(testOrder) && j < len(runtimeOrder); {
355 test := testOrder[i]
356 runtime := runtimeOrder[j]
357
358 if test == runtime {
359 testOrder[i] = test + fmt.Sprintf(" <-- matched with runtime %s %d", componentType, j)
360 runtimeOrder[j] = runtime + fmt.Sprintf(" <-- matched with test %s %d", componentType, i)
361 lastMatchingTest = i
362 i += 1
363 j += 1
364 matchCount += 1
365 } else if _, ok := o.namesToIndex[test]; !ok {
366 // The test component is not registered globally so assume it is the correct place, treat it
367 // as having matched and skip it.
368 i += 1
369 matchCount += 1
370 } else {
371 // Assume that the test list is in the same order as the runtime list but the runtime list
372 // contains some components that are not present in the tests. So, skip the runtime component
373 // to try and find the next one that matches the current test component.
374 j += 1
375 }
376 }
377
378 // If every item in the test order was either test specific or matched one in the runtime then
379 // it is in the correct order. Otherwise, it was not so fail.
380 if matchCount != len(testOrder) {
381 // The test component names were not all matched with a runtime component name so there must
382 // either be a component present in the test that is not present in the runtime or they must be
383 // in the wrong order.
384 testOrder[lastMatchingTest+1] = testOrder[lastMatchingTest+1] + " <--- unmatched"
385 panic(fmt.Errorf("the tests uses test specific components %q and so cannot be automatically sorted."+
386 " Unfortunately it uses %s components in the wrong order.\n"+
387 "test order:\n %s\n"+
388 "runtime order\n %s\n",
389 SortedUniqueStrings(unknownComponents),
390 componentType,
391 strings.Join(testOrder, "\n "),
392 strings.Join(runtimeOrder, "\n ")))
393 }
394}
395
396// registrationSorter encapsulates the information needed to ensure that the test mutators are
397// registered, and thereby executed, in the same order as they are at runtime.
398//
399// It MUST be populated lazily AFTER all package initialization has been done otherwise it will
400// only define the order for a subset of all the registered build components that are available for
401// the packages being tested.
402//
403// e.g if this is initialized during say the cc package initialization then any tests run in the
404// java package will not sort build components registered by the java package's init() functions.
405type registrationSorter struct {
406 // Used to ensure that this is only created once.
407 once sync.Once
408
409 // The order of mutators
410 mutatorOrder registeredComponentOrder
Paul Duffin41d77c72021-03-07 12:23:48 +0000411
412 // The order of singletons
413 singletonOrder registeredComponentOrder
Paul Duffin281deb22021-03-06 20:29:19 +0000414}
415
416// populate initializes this structure from globally registered build components.
417//
418// Only the first call has any effect.
419func (s *registrationSorter) populate() {
420 s.once.Do(func() {
421 // Created an ordering from the globally registered mutators.
422 globallyRegisteredMutators := collateGloballyRegisteredMutators()
423 s.mutatorOrder = registeredComponentOrderFromExistingOrder("mutator", globallyRegisteredMutators)
Paul Duffin41d77c72021-03-07 12:23:48 +0000424
425 // Create an ordering from the globally registered singletons.
426 globallyRegisteredSingletons := collateGloballyRegisteredSingletons()
427 s.singletonOrder = registeredComponentOrderFromExistingOrder("singleton", globallyRegisteredSingletons)
Paul Duffin281deb22021-03-06 20:29:19 +0000428 })
429}
430
431// Provides support for enforcing the same order in which build components are registered globally
432// to the order in which they are registered during tests.
433//
434// MUST only be accessed via the globallyRegisteredComponentsOrder func.
435var globalRegistrationSorter registrationSorter
436
437// globallyRegisteredComponentsOrder returns the globalRegistrationSorter after ensuring it is
438// correctly populated.
439func globallyRegisteredComponentsOrder() *registrationSorter {
440 globalRegistrationSorter.populate()
441 return &globalRegistrationSorter
442}
443
Colin Crossae8600b2020-10-29 17:09:13 -0700444func (ctx *TestContext) Register() {
Paul Duffin281deb22021-03-06 20:29:19 +0000445 globalOrder := globallyRegisteredComponentsOrder()
446
Paul Duffinc05b0342021-03-06 13:28:13 +0000447 mutators := collateRegisteredMutators(ctx.preArch, ctx.preDeps, ctx.postDeps, ctx.finalDeps)
Paul Duffin281deb22021-03-06 20:29:19 +0000448 // Ensure that the mutators used in the test are in the same order as they are used at runtime.
449 globalOrder.mutatorOrder.enforceOrdering(mutators)
Paul Duffinc05b0342021-03-06 13:28:13 +0000450 mutators.registerAll(ctx.Context)
Colin Crosscec81712017-07-13 14:43:27 -0700451
Paul Duffin41d77c72021-03-07 12:23:48 +0000452 // Ensure that the singletons used in the test are in the same order as they are used at runtime.
453 globalOrder.singletonOrder.enforceOrdering(ctx.singletons)
Paul Duffind182fb32021-03-07 12:24:44 +0000454 ctx.singletons.registerAll(ctx.Context)
455
Paul Duffin41d77c72021-03-07 12:23:48 +0000456 // Save the sorted components order away to make them easy to access while debugging.
Paul Duffinf5de6682021-03-08 23:42:10 +0000457 ctx.mutatorOrder = componentsToNames(mutators)
458 ctx.singletonOrder = componentsToNames(singletons)
Colin Cross31a738b2019-12-30 18:45:15 -0800459}
460
461func (ctx *TestContext) ParseFileList(rootDir string, filePaths []string) (deps []string, errs []error) {
462 // This function adapts the old style ParseFileList calls that are spread throughout the tests
463 // to the new style that takes a config.
464 return ctx.Context.ParseFileList(rootDir, filePaths, ctx.config)
465}
466
467func (ctx *TestContext) ParseBlueprintsFiles(rootDir string) (deps []string, errs []error) {
468 // This function adapts the old style ParseBlueprintsFiles calls that are spread throughout the
469 // tests to the new style that takes a config.
470 return ctx.Context.ParseBlueprintsFiles(rootDir, ctx.config)
Colin Cross4b49b762019-11-22 15:25:03 -0800471}
472
473func (ctx *TestContext) RegisterModuleType(name string, factory ModuleFactory) {
474 ctx.Context.RegisterModuleType(name, ModuleFactoryAdaptor(factory))
475}
476
Colin Cross9aed5bc2020-12-28 15:15:34 -0800477func (ctx *TestContext) RegisterSingletonModuleType(name string, factory SingletonModuleFactory) {
478 s, m := SingletonModuleFactoryAdaptor(name, factory)
479 ctx.RegisterSingletonType(name, s)
480 ctx.RegisterModuleType(name, m)
481}
482
LaMont Jonese59c0db2023-05-15 21:50:29 +0000483func (ctx *TestContext) RegisterParallelSingletonModuleType(name string, factory SingletonModuleFactory) {
484 s, m := SingletonModuleFactoryAdaptor(name, factory)
485 ctx.RegisterParallelSingletonType(name, s)
486 ctx.RegisterModuleType(name, m)
487}
488
Colin Cross4b49b762019-11-22 15:25:03 -0800489func (ctx *TestContext) RegisterSingletonType(name string, factory SingletonFactory) {
LaMont Jonese59c0db2023-05-15 21:50:29 +0000490 ctx.singletons = append(ctx.singletons, newSingleton(name, factory, false))
491}
492
493func (ctx *TestContext) RegisterParallelSingletonType(name string, factory SingletonFactory) {
494 ctx.singletons = append(ctx.singletons, newSingleton(name, factory, true))
Colin Crosscec81712017-07-13 14:43:27 -0700495}
496
Martin Stjernholm14cdd712021-09-10 22:39:59 +0100497// ModuleVariantForTests selects a specific variant of the module with the given
498// name by matching the variations map against the variations of each module
499// variant. A module variant matches the map if every variation that exists in
500// both have the same value. Both the module and the map are allowed to have
501// extra variations that the other doesn't have. Panics if not exactly one
502// module variant matches.
503func (ctx *TestContext) ModuleVariantForTests(name string, matchVariations map[string]string) TestingModule {
504 modules := []Module{}
505 ctx.VisitAllModules(func(m blueprint.Module) {
506 if ctx.ModuleName(m) == name {
507 am := m.(Module)
508 amMut := am.base().commonProperties.DebugMutators
509 amVar := am.base().commonProperties.DebugVariations
510 matched := true
511 for i, mut := range amMut {
512 if wantedVar, found := matchVariations[mut]; found && amVar[i] != wantedVar {
513 matched = false
514 break
515 }
516 }
517 if matched {
518 modules = append(modules, am)
519 }
520 }
521 })
522
523 if len(modules) == 0 {
524 // Show all the modules or module variants that do exist.
525 var allModuleNames []string
526 var allVariants []string
527 ctx.VisitAllModules(func(m blueprint.Module) {
528 allModuleNames = append(allModuleNames, ctx.ModuleName(m))
529 if ctx.ModuleName(m) == name {
530 allVariants = append(allVariants, m.(Module).String())
531 }
532 })
533
534 if len(allVariants) == 0 {
535 panic(fmt.Errorf("failed to find module %q. All modules:\n %s",
536 name, strings.Join(SortedUniqueStrings(allModuleNames), "\n ")))
537 } else {
538 sort.Strings(allVariants)
539 panic(fmt.Errorf("failed to find module %q matching %v. All variants:\n %s",
540 name, matchVariations, strings.Join(allVariants, "\n ")))
541 }
542 }
543
544 if len(modules) > 1 {
545 moduleStrings := []string{}
546 for _, m := range modules {
547 moduleStrings = append(moduleStrings, m.String())
548 }
549 sort.Strings(moduleStrings)
550 panic(fmt.Errorf("module %q has more than one variant that match %v:\n %s",
551 name, matchVariations, strings.Join(moduleStrings, "\n ")))
552 }
553
554 return newTestingModule(ctx.config, modules[0])
555}
556
Colin Crosscec81712017-07-13 14:43:27 -0700557func (ctx *TestContext) ModuleForTests(name, variant string) TestingModule {
558 var module Module
559 ctx.VisitAllModules(func(m blueprint.Module) {
560 if ctx.ModuleName(m) == name && ctx.ModuleSubDir(m) == variant {
561 module = m.(Module)
562 }
563 })
564
565 if module == nil {
Jeff Gaston294356f2017-09-27 17:05:30 -0700566 // find all the modules that do exist
Colin Crossbeae6ec2020-08-11 12:02:11 -0700567 var allModuleNames []string
568 var allVariants []string
Jeff Gaston294356f2017-09-27 17:05:30 -0700569 ctx.VisitAllModules(func(m blueprint.Module) {
Colin Crossbeae6ec2020-08-11 12:02:11 -0700570 allModuleNames = append(allModuleNames, ctx.ModuleName(m))
571 if ctx.ModuleName(m) == name {
572 allVariants = append(allVariants, ctx.ModuleSubDir(m))
573 }
Jeff Gaston294356f2017-09-27 17:05:30 -0700574 })
Colin Crossbeae6ec2020-08-11 12:02:11 -0700575 sort.Strings(allVariants)
Jeff Gaston294356f2017-09-27 17:05:30 -0700576
Colin Crossbeae6ec2020-08-11 12:02:11 -0700577 if len(allVariants) == 0 {
578 panic(fmt.Errorf("failed to find module %q. All modules:\n %s",
Martin Stjernholm98e0d882021-09-09 21:34:02 +0100579 name, strings.Join(SortedUniqueStrings(allModuleNames), "\n ")))
Colin Crossbeae6ec2020-08-11 12:02:11 -0700580 } else {
581 panic(fmt.Errorf("failed to find module %q variant %q. All variants:\n %s",
582 name, variant, strings.Join(allVariants, "\n ")))
583 }
Colin Crosscec81712017-07-13 14:43:27 -0700584 }
585
Paul Duffin709e0e32021-03-22 10:09:02 +0000586 return newTestingModule(ctx.config, module)
Colin Crosscec81712017-07-13 14:43:27 -0700587}
588
Jiyong Park37b25202018-07-11 10:49:27 +0900589func (ctx *TestContext) ModuleVariantsForTests(name string) []string {
590 var variants []string
591 ctx.VisitAllModules(func(m blueprint.Module) {
592 if ctx.ModuleName(m) == name {
593 variants = append(variants, ctx.ModuleSubDir(m))
594 }
595 })
596 return variants
597}
598
Colin Cross4c83e5c2019-02-25 14:54:28 -0800599// SingletonForTests returns a TestingSingleton for the singleton registered with the given name.
600func (ctx *TestContext) SingletonForTests(name string) TestingSingleton {
601 allSingletonNames := []string{}
602 for _, s := range ctx.Singletons() {
603 n := ctx.SingletonName(s)
604 if n == name {
605 return TestingSingleton{
Paul Duffin709e0e32021-03-22 10:09:02 +0000606 baseTestingComponent: newBaseTestingComponent(ctx.config, s.(testBuildProvider)),
Paul Duffin31a22882021-03-22 09:29:00 +0000607 singleton: s.(*singletonAdaptor).Singleton,
Colin Cross4c83e5c2019-02-25 14:54:28 -0800608 }
609 }
610 allSingletonNames = append(allSingletonNames, n)
611 }
612
613 panic(fmt.Errorf("failed to find singleton %q."+
614 "\nall singletons: %v", name, allSingletonNames))
615}
616
Martin Stjernholm1ebef5b2022-02-10 23:34:28 +0000617type InstallMakeRule struct {
618 Target string
619 Deps []string
620 OrderOnlyDeps []string
621}
622
623func parseMkRules(t *testing.T, config Config, nodes []mkparser.Node) []InstallMakeRule {
624 var rules []InstallMakeRule
625 for _, node := range nodes {
626 if mkParserRule, ok := node.(*mkparser.Rule); ok {
627 var rule InstallMakeRule
628
629 if targets := mkParserRule.Target.Words(); len(targets) == 0 {
630 t.Fatalf("no targets for rule %s", mkParserRule.Dump())
631 } else if len(targets) > 1 {
632 t.Fatalf("unsupported multiple targets for rule %s", mkParserRule.Dump())
633 } else if !targets[0].Const() {
634 t.Fatalf("unsupported non-const target for rule %s", mkParserRule.Dump())
635 } else {
636 rule.Target = normalizeStringRelativeToTop(config, targets[0].Value(nil))
637 }
638
639 prereqList := &rule.Deps
640 for _, prereq := range mkParserRule.Prerequisites.Words() {
641 if !prereq.Const() {
642 t.Fatalf("unsupported non-const prerequisite for rule %s", mkParserRule.Dump())
643 }
644
645 if prereq.Value(nil) == "|" {
646 prereqList = &rule.OrderOnlyDeps
647 continue
648 }
649
650 *prereqList = append(*prereqList, normalizeStringRelativeToTop(config, prereq.Value(nil)))
651 }
652
653 rules = append(rules, rule)
654 }
655 }
656
657 return rules
658}
659
660func (ctx *TestContext) InstallMakeRulesForTesting(t *testing.T) []InstallMakeRule {
661 installs := ctx.SingletonForTests("makevars").Singleton().(*makeVarsSingleton).installsForTesting
662 buf := bytes.NewBuffer(append([]byte(nil), installs...))
663 parser := mkparser.NewParser("makevars", buf)
664
665 nodes, errs := parser.Parse()
666 if len(errs) > 0 {
667 t.Fatalf("error parsing install rules: %s", errs[0])
668 }
669
670 return parseMkRules(t, ctx.config, nodes)
671}
672
Paul Duffin8eb45732022-10-04 19:03:31 +0100673// MakeVarVariable provides access to make vars that will be written by the makeVarsSingleton
674type MakeVarVariable interface {
675 // Name is the name of the variable.
676 Name() string
677
678 // Value is the value of the variable.
679 Value() string
680}
681
682func (v makeVarsVariable) Name() string {
683 return v.name
684}
685
686func (v makeVarsVariable) Value() string {
687 return v.value
688}
689
690// PrepareForTestAccessingMakeVars sets up the test so that MakeVarsForTesting will work.
691var PrepareForTestAccessingMakeVars = GroupFixturePreparers(
692 PrepareForTestWithAndroidMk,
693 PrepareForTestWithMakevars,
694)
695
696// MakeVarsForTesting returns a filtered list of MakeVarVariable objects that represent the
697// variables that will be written out.
698//
699// It is necessary to use PrepareForTestAccessingMakeVars in tests that want to call this function.
700// Along with any other preparers needed to add the make vars.
701func (ctx *TestContext) MakeVarsForTesting(filter func(variable MakeVarVariable) bool) []MakeVarVariable {
702 vars := ctx.SingletonForTests("makevars").Singleton().(*makeVarsSingleton).varsForTesting
703 result := make([]MakeVarVariable, 0, len(vars))
704 for _, v := range vars {
705 if filter(v) {
706 result = append(result, v)
707 }
708 }
709
710 return result
711}
712
Colin Crossaa255532020-07-03 13:18:24 -0700713func (ctx *TestContext) Config() Config {
714 return ctx.config
715}
716
Colin Cross4c83e5c2019-02-25 14:54:28 -0800717type testBuildProvider interface {
718 BuildParamsForTests() []BuildParams
719 RuleParamsForTests() map[blueprint.Rule]blueprint.RuleParams
720}
721
722type TestingBuildParams struct {
723 BuildParams
724 RuleParams blueprint.RuleParams
Paul Duffin709e0e32021-03-22 10:09:02 +0000725
726 config Config
727}
728
729// RelativeToTop creates a new instance of this which has had any usages of the current test's
730// temporary and test specific build directory replaced with a path relative to the notional top.
731//
732// The parts of this structure which are changed are:
733// * BuildParams
Colin Crossd079e0b2022-08-16 10:27:33 -0700734// - Args
735// - All Path, Paths, WritablePath and WritablePaths fields.
Paul Duffin709e0e32021-03-22 10:09:02 +0000736//
737// * RuleParams
Colin Crossd079e0b2022-08-16 10:27:33 -0700738// - Command
739// - Depfile
740// - Rspfile
741// - RspfileContent
Colin Crossd079e0b2022-08-16 10:27:33 -0700742// - CommandDeps
743// - CommandOrderOnly
Paul Duffin709e0e32021-03-22 10:09:02 +0000744//
745// See PathRelativeToTop for more details.
Paul Duffina71a67a2021-03-29 00:42:57 +0100746//
747// deprecated: this is no longer needed as TestingBuildParams are created in this form.
Paul Duffin709e0e32021-03-22 10:09:02 +0000748func (p TestingBuildParams) RelativeToTop() TestingBuildParams {
749 // If this is not a valid params then just return it back. That will make it easy to use with the
750 // Maybe...() methods.
751 if p.Rule == nil {
752 return p
753 }
754 if p.config.config == nil {
Paul Duffine8366da2021-03-24 10:40:38 +0000755 return p
Paul Duffin709e0e32021-03-22 10:09:02 +0000756 }
757 // Take a copy of the build params and replace any args that contains test specific temporary
758 // paths with paths relative to the top.
759 bparams := p.BuildParams
Paul Duffinbbb0f8f2021-03-24 10:34:52 +0000760 bparams.Depfile = normalizeWritablePathRelativeToTop(bparams.Depfile)
761 bparams.Output = normalizeWritablePathRelativeToTop(bparams.Output)
762 bparams.Outputs = bparams.Outputs.RelativeToTop()
Paul Duffinbbb0f8f2021-03-24 10:34:52 +0000763 bparams.ImplicitOutput = normalizeWritablePathRelativeToTop(bparams.ImplicitOutput)
764 bparams.ImplicitOutputs = bparams.ImplicitOutputs.RelativeToTop()
765 bparams.Input = normalizePathRelativeToTop(bparams.Input)
766 bparams.Inputs = bparams.Inputs.RelativeToTop()
767 bparams.Implicit = normalizePathRelativeToTop(bparams.Implicit)
768 bparams.Implicits = bparams.Implicits.RelativeToTop()
769 bparams.OrderOnly = bparams.OrderOnly.RelativeToTop()
770 bparams.Validation = normalizePathRelativeToTop(bparams.Validation)
771 bparams.Validations = bparams.Validations.RelativeToTop()
Paul Duffin709e0e32021-03-22 10:09:02 +0000772 bparams.Args = normalizeStringMapRelativeToTop(p.config, bparams.Args)
773
774 // Ditto for any fields in the RuleParams.
775 rparams := p.RuleParams
776 rparams.Command = normalizeStringRelativeToTop(p.config, rparams.Command)
777 rparams.Depfile = normalizeStringRelativeToTop(p.config, rparams.Depfile)
778 rparams.Rspfile = normalizeStringRelativeToTop(p.config, rparams.Rspfile)
779 rparams.RspfileContent = normalizeStringRelativeToTop(p.config, rparams.RspfileContent)
Paul Duffin709e0e32021-03-22 10:09:02 +0000780 rparams.CommandDeps = normalizeStringArrayRelativeToTop(p.config, rparams.CommandDeps)
781 rparams.CommandOrderOnly = normalizeStringArrayRelativeToTop(p.config, rparams.CommandOrderOnly)
782
783 return TestingBuildParams{
784 BuildParams: bparams,
785 RuleParams: rparams,
786 }
Colin Cross4c83e5c2019-02-25 14:54:28 -0800787}
788
Paul Duffinbbb0f8f2021-03-24 10:34:52 +0000789func normalizeWritablePathRelativeToTop(path WritablePath) WritablePath {
790 if path == nil {
791 return nil
792 }
793 return path.RelativeToTop().(WritablePath)
794}
795
796func normalizePathRelativeToTop(path Path) Path {
797 if path == nil {
798 return nil
799 }
800 return path.RelativeToTop()
801}
802
Jiakai Zhangcf61e3c2023-05-08 16:28:38 +0000803func allOutputs(p BuildParams) []string {
804 outputs := append(WritablePaths(nil), p.Outputs...)
805 outputs = append(outputs, p.ImplicitOutputs...)
806 if p.Output != nil {
807 outputs = append(outputs, p.Output)
808 }
809 return outputs.Strings()
810}
811
812// AllOutputs returns all 'BuildParams.Output's and 'BuildParams.Outputs's in their full path string forms.
813func (p TestingBuildParams) AllOutputs() []string {
814 return allOutputs(p.BuildParams)
815}
816
Paul Duffin0eda26b92021-03-22 09:34:29 +0000817// baseTestingComponent provides functionality common to both TestingModule and TestingSingleton.
818type baseTestingComponent struct {
Paul Duffin709e0e32021-03-22 10:09:02 +0000819 config Config
Paul Duffin0eda26b92021-03-22 09:34:29 +0000820 provider testBuildProvider
821}
822
Paul Duffin709e0e32021-03-22 10:09:02 +0000823func newBaseTestingComponent(config Config, provider testBuildProvider) baseTestingComponent {
824 return baseTestingComponent{config, provider}
825}
826
827// A function that will normalize a string containing paths, e.g. ninja command, by replacing
828// any references to the test specific temporary build directory that changes with each run to a
829// fixed path relative to a notional top directory.
830//
831// This is similar to StringPathRelativeToTop except that assumes the string is a single path
832// containing at most one instance of the temporary build directory at the start of the path while
833// this assumes that there can be any number at any position.
834func normalizeStringRelativeToTop(config Config, s string) string {
Colin Cross3b1c6842024-07-26 11:52:57 -0700835 // The outDir usually looks something like: /tmp/testFoo2345/001
Paul Duffin709e0e32021-03-22 10:09:02 +0000836 //
Colin Cross3b1c6842024-07-26 11:52:57 -0700837 // Replace any usage of the outDir with out/soong, e.g. replace "/tmp/testFoo2345/001" with
Paul Duffin709e0e32021-03-22 10:09:02 +0000838 // "out/soong".
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200839 outSoongDir := filepath.Clean(config.soongOutDir)
Paul Duffin709e0e32021-03-22 10:09:02 +0000840 re := regexp.MustCompile(`\Q` + outSoongDir + `\E\b`)
841 s = re.ReplaceAllString(s, "out/soong")
842
Colin Cross3b1c6842024-07-26 11:52:57 -0700843 // Replace any usage of the outDir/.. with out, e.g. replace "/tmp/testFoo2345" with
Paul Duffin709e0e32021-03-22 10:09:02 +0000844 // "out". This must come after the previous replacement otherwise this would replace
845 // "/tmp/testFoo2345/001" with "out/001" instead of "out/soong".
846 outDir := filepath.Dir(outSoongDir)
847 re = regexp.MustCompile(`\Q` + outDir + `\E\b`)
848 s = re.ReplaceAllString(s, "out")
849
850 return s
851}
852
853// normalizeStringArrayRelativeToTop creates a new slice constructed by applying
854// normalizeStringRelativeToTop to each item in the slice.
855func normalizeStringArrayRelativeToTop(config Config, slice []string) []string {
856 newSlice := make([]string, len(slice))
857 for i, s := range slice {
858 newSlice[i] = normalizeStringRelativeToTop(config, s)
859 }
860 return newSlice
861}
862
863// normalizeStringMapRelativeToTop creates a new map constructed by applying
864// normalizeStringRelativeToTop to each value in the map.
865func normalizeStringMapRelativeToTop(config Config, m map[string]string) map[string]string {
866 newMap := map[string]string{}
867 for k, v := range m {
868 newMap[k] = normalizeStringRelativeToTop(config, v)
869 }
870 return newMap
Paul Duffin0eda26b92021-03-22 09:34:29 +0000871}
872
873func (b baseTestingComponent) newTestingBuildParams(bparams BuildParams) TestingBuildParams {
Colin Cross4c83e5c2019-02-25 14:54:28 -0800874 return TestingBuildParams{
Paul Duffin709e0e32021-03-22 10:09:02 +0000875 config: b.config,
Colin Cross4c83e5c2019-02-25 14:54:28 -0800876 BuildParams: bparams,
Paul Duffin0eda26b92021-03-22 09:34:29 +0000877 RuleParams: b.provider.RuleParamsForTests()[bparams.Rule],
Paul Duffine8366da2021-03-24 10:40:38 +0000878 }.RelativeToTop()
Colin Cross4c83e5c2019-02-25 14:54:28 -0800879}
880
Paul Duffin0eda26b92021-03-22 09:34:29 +0000881func (b baseTestingComponent) maybeBuildParamsFromRule(rule string) (TestingBuildParams, []string) {
Thiébaud Weksteen3600b802020-08-27 15:50:24 +0200882 var searchedRules []string
Paul Duffin4dbf6cf2021-06-08 10:06:37 +0100883 buildParams := b.provider.BuildParamsForTests()
884 for _, p := range buildParams {
885 ruleAsString := p.Rule.String()
886 searchedRules = append(searchedRules, ruleAsString)
887 if strings.Contains(ruleAsString, rule) {
Paul Duffin0eda26b92021-03-22 09:34:29 +0000888 return b.newTestingBuildParams(p), searchedRules
Colin Cross4c83e5c2019-02-25 14:54:28 -0800889 }
890 }
Thiébaud Weksteen3600b802020-08-27 15:50:24 +0200891 return TestingBuildParams{}, searchedRules
Colin Cross4c83e5c2019-02-25 14:54:28 -0800892}
893
Paul Duffin0eda26b92021-03-22 09:34:29 +0000894func (b baseTestingComponent) buildParamsFromRule(rule string) TestingBuildParams {
895 p, searchRules := b.maybeBuildParamsFromRule(rule)
Colin Cross4c83e5c2019-02-25 14:54:28 -0800896 if p.Rule == nil {
Paul Duffin4dbf6cf2021-06-08 10:06:37 +0100897 panic(fmt.Errorf("couldn't find rule %q.\nall rules:\n%s", rule, strings.Join(searchRules, "\n")))
Colin Cross4c83e5c2019-02-25 14:54:28 -0800898 }
899 return p
900}
901
Martin Stjernholm827ba622022-02-03 00:20:11 +0000902func (b baseTestingComponent) maybeBuildParamsFromDescription(desc string) (TestingBuildParams, []string) {
903 var searchedDescriptions []string
Paul Duffin0eda26b92021-03-22 09:34:29 +0000904 for _, p := range b.provider.BuildParamsForTests() {
Martin Stjernholm827ba622022-02-03 00:20:11 +0000905 searchedDescriptions = append(searchedDescriptions, p.Description)
Colin Crossb88b3c52019-06-10 15:15:17 -0700906 if strings.Contains(p.Description, desc) {
Martin Stjernholm827ba622022-02-03 00:20:11 +0000907 return b.newTestingBuildParams(p), searchedDescriptions
Colin Cross4c83e5c2019-02-25 14:54:28 -0800908 }
909 }
Martin Stjernholm827ba622022-02-03 00:20:11 +0000910 return TestingBuildParams{}, searchedDescriptions
Colin Cross4c83e5c2019-02-25 14:54:28 -0800911}
912
Paul Duffin0eda26b92021-03-22 09:34:29 +0000913func (b baseTestingComponent) buildParamsFromDescription(desc string) TestingBuildParams {
Martin Stjernholm827ba622022-02-03 00:20:11 +0000914 p, searchedDescriptions := b.maybeBuildParamsFromDescription(desc)
Colin Cross4c83e5c2019-02-25 14:54:28 -0800915 if p.Rule == nil {
Martin Stjernholm827ba622022-02-03 00:20:11 +0000916 panic(fmt.Errorf("couldn't find description %q\nall descriptions:\n%s", desc, strings.Join(searchedDescriptions, "\n")))
Colin Cross4c83e5c2019-02-25 14:54:28 -0800917 }
918 return p
919}
920
Paul Duffin0eda26b92021-03-22 09:34:29 +0000921func (b baseTestingComponent) maybeBuildParamsFromOutput(file string) (TestingBuildParams, []string) {
Martin Stjernholma4aaa472021-09-17 02:51:48 +0100922 searchedOutputs := WritablePaths(nil)
Paul Duffin0eda26b92021-03-22 09:34:29 +0000923 for _, p := range b.provider.BuildParamsForTests() {
Colin Cross4c83e5c2019-02-25 14:54:28 -0800924 outputs := append(WritablePaths(nil), p.Outputs...)
Colin Cross1d2cf042019-03-29 15:33:06 -0700925 outputs = append(outputs, p.ImplicitOutputs...)
Colin Cross4c83e5c2019-02-25 14:54:28 -0800926 if p.Output != nil {
927 outputs = append(outputs, p.Output)
928 }
929 for _, f := range outputs {
Paul Duffin4e6e35c2021-03-22 11:34:57 +0000930 if f.String() == file || f.Rel() == file || PathRelativeToTop(f) == file {
Paul Duffin0eda26b92021-03-22 09:34:29 +0000931 return b.newTestingBuildParams(p), nil
Colin Cross4c83e5c2019-02-25 14:54:28 -0800932 }
Martin Stjernholma4aaa472021-09-17 02:51:48 +0100933 searchedOutputs = append(searchedOutputs, f)
Colin Cross4c83e5c2019-02-25 14:54:28 -0800934 }
935 }
Martin Stjernholma4aaa472021-09-17 02:51:48 +0100936
937 formattedOutputs := []string{}
938 for _, f := range searchedOutputs {
939 formattedOutputs = append(formattedOutputs,
940 fmt.Sprintf("%s (rel=%s)", PathRelativeToTop(f), f.Rel()))
941 }
942
943 return TestingBuildParams{}, formattedOutputs
Colin Cross4c83e5c2019-02-25 14:54:28 -0800944}
945
Paul Duffin0eda26b92021-03-22 09:34:29 +0000946func (b baseTestingComponent) buildParamsFromOutput(file string) TestingBuildParams {
947 p, searchedOutputs := b.maybeBuildParamsFromOutput(file)
Colin Cross4c83e5c2019-02-25 14:54:28 -0800948 if p.Rule == nil {
Paul Duffin4e6e35c2021-03-22 11:34:57 +0000949 panic(fmt.Errorf("couldn't find output %q.\nall outputs:\n %s\n",
950 file, strings.Join(searchedOutputs, "\n ")))
Colin Cross4c83e5c2019-02-25 14:54:28 -0800951 }
952 return p
953}
954
Paul Duffin0eda26b92021-03-22 09:34:29 +0000955func (b baseTestingComponent) allOutputs() []string {
Colin Cross4c83e5c2019-02-25 14:54:28 -0800956 var outputFullPaths []string
Paul Duffin0eda26b92021-03-22 09:34:29 +0000957 for _, p := range b.provider.BuildParamsForTests() {
Jiakai Zhangcf61e3c2023-05-08 16:28:38 +0000958 outputFullPaths = append(outputFullPaths, allOutputs(p)...)
Colin Cross4c83e5c2019-02-25 14:54:28 -0800959 }
960 return outputFullPaths
961}
962
Paul Duffin31a22882021-03-22 09:29:00 +0000963// MaybeRule finds a call to ctx.Build with BuildParams.Rule set to a rule with the given name. Returns an empty
964// BuildParams if no rule is found.
965func (b baseTestingComponent) MaybeRule(rule string) TestingBuildParams {
Paul Duffin0eda26b92021-03-22 09:34:29 +0000966 r, _ := b.maybeBuildParamsFromRule(rule)
Paul Duffin31a22882021-03-22 09:29:00 +0000967 return r
968}
969
970// Rule finds a call to ctx.Build with BuildParams.Rule set to a rule with the given name. Panics if no rule is found.
971func (b baseTestingComponent) Rule(rule string) TestingBuildParams {
Paul Duffin0eda26b92021-03-22 09:34:29 +0000972 return b.buildParamsFromRule(rule)
Paul Duffin31a22882021-03-22 09:29:00 +0000973}
974
975// MaybeDescription finds a call to ctx.Build with BuildParams.Description set to a the given string. Returns an empty
976// BuildParams if no rule is found.
977func (b baseTestingComponent) MaybeDescription(desc string) TestingBuildParams {
Martin Stjernholm827ba622022-02-03 00:20:11 +0000978 p, _ := b.maybeBuildParamsFromDescription(desc)
979 return p
Paul Duffin31a22882021-03-22 09:29:00 +0000980}
981
982// Description finds a call to ctx.Build with BuildParams.Description set to a the given string. Panics if no rule is
983// found.
984func (b baseTestingComponent) Description(desc string) TestingBuildParams {
Paul Duffin0eda26b92021-03-22 09:34:29 +0000985 return b.buildParamsFromDescription(desc)
Paul Duffin31a22882021-03-22 09:29:00 +0000986}
987
988// MaybeOutput finds a call to ctx.Build with a BuildParams.Output or BuildParams.Outputs whose String() or Rel()
989// value matches the provided string. Returns an empty BuildParams if no rule is found.
990func (b baseTestingComponent) MaybeOutput(file string) TestingBuildParams {
Paul Duffin0eda26b92021-03-22 09:34:29 +0000991 p, _ := b.maybeBuildParamsFromOutput(file)
Paul Duffin31a22882021-03-22 09:29:00 +0000992 return p
993}
994
995// Output finds a call to ctx.Build with a BuildParams.Output or BuildParams.Outputs whose String() or Rel()
996// value matches the provided string. Panics if no rule is found.
997func (b baseTestingComponent) Output(file string) TestingBuildParams {
Paul Duffin0eda26b92021-03-22 09:34:29 +0000998 return b.buildParamsFromOutput(file)
Paul Duffin31a22882021-03-22 09:29:00 +0000999}
1000
1001// AllOutputs returns all 'BuildParams.Output's and 'BuildParams.Outputs's in their full path string forms.
1002func (b baseTestingComponent) AllOutputs() []string {
Paul Duffin0eda26b92021-03-22 09:34:29 +00001003 return b.allOutputs()
Paul Duffin31a22882021-03-22 09:29:00 +00001004}
1005
Colin Crossb77ffc42019-01-05 22:09:19 -08001006// TestingModule is wrapper around an android.Module that provides methods to find information about individual
1007// ctx.Build parameters for verification in tests.
Colin Crosscec81712017-07-13 14:43:27 -07001008type TestingModule struct {
Paul Duffin31a22882021-03-22 09:29:00 +00001009 baseTestingComponent
Colin Crosscec81712017-07-13 14:43:27 -07001010 module Module
1011}
1012
Paul Duffin709e0e32021-03-22 10:09:02 +00001013func newTestingModule(config Config, module Module) TestingModule {
Paul Duffin31a22882021-03-22 09:29:00 +00001014 return TestingModule{
Paul Duffin709e0e32021-03-22 10:09:02 +00001015 newBaseTestingComponent(config, module),
Paul Duffin31a22882021-03-22 09:29:00 +00001016 module,
1017 }
1018}
1019
Colin Crossb77ffc42019-01-05 22:09:19 -08001020// Module returns the Module wrapped by the TestingModule.
Colin Crosscec81712017-07-13 14:43:27 -07001021func (m TestingModule) Module() Module {
1022 return m.module
1023}
1024
Paul Duffin97d8b402021-03-22 16:04:50 +00001025// VariablesForTestsRelativeToTop returns a copy of the Module.VariablesForTests() with every value
1026// having any temporary build dir usages replaced with paths relative to a notional top.
1027func (m TestingModule) VariablesForTestsRelativeToTop() map[string]string {
1028 return normalizeStringMapRelativeToTop(m.config, m.module.VariablesForTests())
1029}
1030
mrziwangd38e63d2024-07-15 13:43:37 -07001031// OutputFiles checks if module base outputFiles property has any output
mrziwange81e77a2024-06-13 17:02:59 -07001032// files can be used to return.
mrziwangd38e63d2024-07-15 13:43:37 -07001033// Exits the test immediately if there is an error and
mrziwange81e77a2024-06-13 17:02:59 -07001034// otherwise returns the result of calling Paths.RelativeToTop
Paul Duffin962783a2021-03-29 00:00:17 +01001035// on the returned Paths.
1036func (m TestingModule) OutputFiles(t *testing.T, tag string) Paths {
mrziwangabdb2932024-06-18 12:43:41 -07001037 outputFiles := m.Module().base().outputFiles
1038 if tag == "" && outputFiles.DefaultOutputFiles != nil {
1039 return outputFiles.DefaultOutputFiles.RelativeToTop()
1040 } else if taggedOutputFiles, hasTag := outputFiles.TaggedOutputFiles[tag]; hasTag {
mrziwangd38e63d2024-07-15 13:43:37 -07001041 return taggedOutputFiles.RelativeToTop()
mrziwange81e77a2024-06-13 17:02:59 -07001042 }
1043
mrziwangd38e63d2024-07-15 13:43:37 -07001044 t.Fatal(fmt.Errorf("No test output file has been set for tag %q", tag))
1045 return nil
Paul Duffin962783a2021-03-29 00:00:17 +01001046}
1047
Colin Cross4c83e5c2019-02-25 14:54:28 -08001048// TestingSingleton is wrapper around an android.Singleton that provides methods to find information about individual
1049// ctx.Build parameters for verification in tests.
1050type TestingSingleton struct {
Paul Duffin31a22882021-03-22 09:29:00 +00001051 baseTestingComponent
Colin Cross4c83e5c2019-02-25 14:54:28 -08001052 singleton Singleton
Colin Cross4c83e5c2019-02-25 14:54:28 -08001053}
1054
1055// Singleton returns the Singleton wrapped by the TestingSingleton.
1056func (s TestingSingleton) Singleton() Singleton {
1057 return s.singleton
1058}
1059
Logan Chien42039712018-03-12 16:29:17 +08001060func FailIfErrored(t *testing.T, errs []error) {
1061 t.Helper()
1062 if len(errs) > 0 {
1063 for _, err := range errs {
1064 t.Error(err)
1065 }
1066 t.FailNow()
1067 }
1068}
Logan Chienee97c3e2018-03-12 16:34:26 +08001069
Paul Duffinea8a3862021-03-04 17:58:33 +00001070// Fail if no errors that matched the regular expression were found.
1071//
1072// Returns true if a matching error was found, false otherwise.
1073func FailIfNoMatchingErrors(t *testing.T, pattern string, errs []error) bool {
Logan Chienee97c3e2018-03-12 16:34:26 +08001074 t.Helper()
1075
1076 matcher, err := regexp.Compile(pattern)
1077 if err != nil {
Paul Duffinea8a3862021-03-04 17:58:33 +00001078 t.Fatalf("failed to compile regular expression %q because %s", pattern, err)
Logan Chienee97c3e2018-03-12 16:34:26 +08001079 }
1080
1081 found := false
1082 for _, err := range errs {
1083 if matcher.FindStringIndex(err.Error()) != nil {
1084 found = true
1085 break
1086 }
1087 }
1088 if !found {
Steven Moreland082e2062022-08-30 01:11:11 +00001089 t.Errorf("could not match the expected error regex %q (checked %d error(s))", pattern, len(errs))
Logan Chienee97c3e2018-03-12 16:34:26 +08001090 for i, err := range errs {
Colin Crossaede88c2020-08-11 12:17:01 -07001091 t.Errorf("errs[%d] = %q", i, err)
Logan Chienee97c3e2018-03-12 16:34:26 +08001092 }
1093 }
Paul Duffinea8a3862021-03-04 17:58:33 +00001094
1095 return found
Logan Chienee97c3e2018-03-12 16:34:26 +08001096}
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -07001097
Paul Duffin91e38192019-08-05 15:07:57 +01001098func CheckErrorsAgainstExpectations(t *testing.T, errs []error, expectedErrorPatterns []string) {
1099 t.Helper()
1100
1101 if expectedErrorPatterns == nil {
1102 FailIfErrored(t, errs)
1103 } else {
1104 for _, expectedError := range expectedErrorPatterns {
1105 FailIfNoMatchingErrors(t, expectedError, errs)
1106 }
1107 if len(errs) > len(expectedErrorPatterns) {
1108 t.Errorf("additional errors found, expected %d, found %d",
1109 len(expectedErrorPatterns), len(errs))
1110 for i, expectedError := range expectedErrorPatterns {
1111 t.Errorf("expectedErrors[%d] = %s", i, expectedError)
1112 }
1113 for i, err := range errs {
1114 t.Errorf("errs[%d] = %s", i, err)
1115 }
Paul Duffinea8a3862021-03-04 17:58:33 +00001116 t.FailNow()
Paul Duffin91e38192019-08-05 15:07:57 +01001117 }
1118 }
Paul Duffin91e38192019-08-05 15:07:57 +01001119}
1120
Jingwen Chencda22c92020-11-23 00:22:30 -05001121func SetKatiEnabledForTests(config Config) {
1122 config.katiEnabled = true
Paul Duffin8c3fec42020-03-04 20:15:08 +00001123}
1124
Dennis Shend4f5d932023-01-31 20:27:21 +00001125func SetTrimmedApexEnabledForTests(config Config) {
1126 config.productVariables.TrimmedApex = new(bool)
1127 *config.productVariables.TrimmedApex = true
1128}
1129
Colin Crossaa255532020-07-03 13:18:24 -07001130func AndroidMkEntriesForTest(t *testing.T, ctx *TestContext, mod blueprint.Module) []AndroidMkEntries {
Liz Kammer6be69062022-11-04 16:06:02 -04001131 t.Helper()
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -07001132 var p AndroidMkEntriesProvider
1133 var ok bool
1134 if p, ok = mod.(AndroidMkEntriesProvider); !ok {
Roland Levillaindfe75b32019-07-23 16:53:32 +01001135 t.Errorf("module does not implement AndroidMkEntriesProvider: " + mod.Name())
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -07001136 }
Jiyong Park0b0e1b92019-12-03 13:24:29 +09001137
1138 entriesList := p.AndroidMkEntries()
LaMont Jonesb5099382024-01-10 23:42:36 +00001139 aconfigUpdateAndroidMkEntries(ctx, mod.(Module), &entriesList)
Jihoon Kanga3a05462024-04-05 00:36:44 +00001140 for i := range entriesList {
Colin Crossaa255532020-07-03 13:18:24 -07001141 entriesList[i].fillInEntries(ctx, mod)
Jiyong Park0b0e1b92019-12-03 13:24:29 +09001142 }
1143 return entriesList
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -07001144}
Jooyung Han12df5fb2019-07-11 16:18:47 +09001145
Colin Crossaa255532020-07-03 13:18:24 -07001146func AndroidMkDataForTest(t *testing.T, ctx *TestContext, mod blueprint.Module) AndroidMkData {
Liz Kammer6be69062022-11-04 16:06:02 -04001147 t.Helper()
Jooyung Han12df5fb2019-07-11 16:18:47 +09001148 var p AndroidMkDataProvider
1149 var ok bool
1150 if p, ok = mod.(AndroidMkDataProvider); !ok {
Sam Delmerico4e115cc2023-01-19 15:36:52 -05001151 t.Fatalf("module does not implement AndroidMkDataProvider: " + mod.Name())
Jooyung Han12df5fb2019-07-11 16:18:47 +09001152 }
1153 data := p.AndroidMk()
Colin Crossaa255532020-07-03 13:18:24 -07001154 data.fillInData(ctx, mod)
LaMont Jonesb5099382024-01-10 23:42:36 +00001155 aconfigUpdateAndroidMkData(ctx, mod.(Module), &data)
Jooyung Han12df5fb2019-07-11 16:18:47 +09001156 return data
1157}
Paul Duffin9b478b02019-12-10 13:41:51 +00001158
1159// Normalize the path for testing.
1160//
1161// If the path is relative to the build directory then return the relative path
1162// to avoid tests having to deal with the dynamically generated build directory.
1163//
1164// Otherwise, return the supplied path as it is almost certainly a source path
1165// that is relative to the root of the source tree.
1166//
1167// The build and source paths should be distinguishable based on their contents.
Paul Duffin567465d2021-03-16 01:21:34 +00001168//
1169// deprecated: use PathRelativeToTop instead as it handles make install paths and differentiates
1170// between output and source properly.
Paul Duffin9b478b02019-12-10 13:41:51 +00001171func NormalizePathForTesting(path Path) string {
Paul Duffin064b70c2020-11-02 17:32:38 +00001172 if path == nil {
1173 return "<nil path>"
1174 }
Paul Duffin9b478b02019-12-10 13:41:51 +00001175 p := path.String()
1176 if w, ok := path.(WritablePath); ok {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001177 rel, err := filepath.Rel(w.getSoongOutDir(), p)
Paul Duffin9b478b02019-12-10 13:41:51 +00001178 if err != nil {
1179 panic(err)
1180 }
1181 return rel
1182 }
1183 return p
1184}
1185
Paul Duffin567465d2021-03-16 01:21:34 +00001186// NormalizePathsForTesting creates a slice of strings where each string is the result of applying
1187// NormalizePathForTesting to the corresponding Path in the input slice.
1188//
1189// deprecated: use PathsRelativeToTop instead as it handles make install paths and differentiates
1190// between output and source properly.
Paul Duffin9b478b02019-12-10 13:41:51 +00001191func NormalizePathsForTesting(paths Paths) []string {
1192 var result []string
1193 for _, path := range paths {
1194 relative := NormalizePathForTesting(path)
1195 result = append(result, relative)
1196 }
1197 return result
1198}
Paul Duffin567465d2021-03-16 01:21:34 +00001199
1200// PathRelativeToTop returns a string representation of the path relative to a notional top
1201// directory.
1202//
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001203// It return "<nil path>" if the supplied path is nil, otherwise it returns the result of calling
1204// Path.RelativeToTop to obtain a relative Path and then calling Path.String on that to get the
1205// string representation.
Paul Duffin567465d2021-03-16 01:21:34 +00001206func PathRelativeToTop(path Path) string {
1207 if path == nil {
1208 return "<nil path>"
1209 }
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001210 return path.RelativeToTop().String()
Paul Duffin567465d2021-03-16 01:21:34 +00001211}
1212
1213// PathsRelativeToTop creates a slice of strings where each string is the result of applying
1214// PathRelativeToTop to the corresponding Path in the input slice.
1215func PathsRelativeToTop(paths Paths) []string {
1216 var result []string
1217 for _, path := range paths {
1218 relative := PathRelativeToTop(path)
1219 result = append(result, relative)
1220 }
1221 return result
1222}
1223
1224// StringPathRelativeToTop returns a string representation of the path relative to a notional top
1225// directory.
1226//
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001227// See Path.RelativeToTop for more details as to what `relative to top` means.
Paul Duffin567465d2021-03-16 01:21:34 +00001228//
1229// This is provided for processing paths that have already been converted into a string, e.g. paths
1230// in AndroidMkEntries structures. As a result it needs to be supplied the soong output dir against
1231// which it can try and relativize paths. PathRelativeToTop must be used for process Path objects.
1232func StringPathRelativeToTop(soongOutDir string, path string) string {
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001233 ensureTestOnly()
Paul Duffin567465d2021-03-16 01:21:34 +00001234
1235 // A relative path must be a source path so leave it as it is.
1236 if !filepath.IsAbs(path) {
1237 return path
1238 }
1239
1240 // Check to see if the path is relative to the soong out dir.
1241 rel, isRel, err := maybeRelErr(soongOutDir, path)
1242 if err != nil {
1243 panic(err)
1244 }
1245
1246 if isRel {
Colin Cross3b1c6842024-07-26 11:52:57 -07001247 if strings.HasSuffix(soongOutDir, testOutSoongSubDir) {
1248 // The path is in the soong out dir so indicate that in the relative path.
1249 return filepath.Join(TestOutSoongDir, rel)
1250 } else {
1251 // Handle the PathForArbitraryOutput case
1252 return filepath.Join(testOutDir, rel)
1253
1254 }
Paul Duffin567465d2021-03-16 01:21:34 +00001255 }
1256
1257 // Check to see if the path is relative to the top level out dir.
1258 outDir := filepath.Dir(soongOutDir)
1259 rel, isRel, err = maybeRelErr(outDir, path)
1260 if err != nil {
1261 panic(err)
1262 }
1263
1264 if isRel {
1265 // The path is in the out dir so indicate that in the relative path.
1266 return filepath.Join("out", rel)
1267 }
1268
1269 // This should never happen.
1270 panic(fmt.Errorf("internal error: absolute path %s is not relative to the out dir %s", path, outDir))
1271}
1272
1273// StringPathsRelativeToTop creates a slice of strings where each string is the result of applying
1274// StringPathRelativeToTop to the corresponding string path in the input slice.
1275//
1276// This is provided for processing paths that have already been converted into a string, e.g. paths
1277// in AndroidMkEntries structures. As a result it needs to be supplied the soong output dir against
1278// which it can try and relativize paths. PathsRelativeToTop must be used for process Paths objects.
1279func StringPathsRelativeToTop(soongOutDir string, paths []string) []string {
1280 var result []string
1281 for _, path := range paths {
1282 relative := StringPathRelativeToTop(soongOutDir, path)
1283 result = append(result, relative)
1284 }
1285 return result
1286}
Paul Duffinf53555d2021-03-29 00:21:00 +01001287
1288// StringRelativeToTop will normalize a string containing paths, e.g. ninja command, by replacing
1289// any references to the test specific temporary build directory that changes with each run to a
1290// fixed path relative to a notional top directory.
1291//
1292// This is similar to StringPathRelativeToTop except that assumes the string is a single path
1293// containing at most one instance of the temporary build directory at the start of the path while
1294// this assumes that there can be any number at any position.
1295func StringRelativeToTop(config Config, command string) string {
1296 return normalizeStringRelativeToTop(config, command)
1297}
Paul Duffin0aafcbf2021-03-29 00:56:32 +01001298
1299// StringsRelativeToTop will return a new slice such that each item in the new slice is the result
1300// of calling StringRelativeToTop on the corresponding item in the input slice.
1301func StringsRelativeToTop(config Config, command []string) []string {
1302 return normalizeStringArrayRelativeToTop(config, command)
1303}
Yu Liueae7b362023-11-16 17:05:47 -08001304
1305func EnsureListContainsSuffix(t *testing.T, result []string, expected string) {
1306 t.Helper()
1307 if !SuffixInList(result, expected) {
1308 t.Errorf("%q is not found in %v", expected, result)
1309 }
1310}
Cole Fausta963b942024-04-11 17:43:00 -07001311
1312type panickingConfigAndErrorContext struct {
1313 ctx *TestContext
1314}
1315
1316func (ctx *panickingConfigAndErrorContext) OtherModulePropertyErrorf(module Module, property, fmt string, args ...interface{}) {
1317 panic(ctx.ctx.PropertyErrorf(module, property, fmt, args...).Error())
1318}
1319
1320func (ctx *panickingConfigAndErrorContext) Config() Config {
1321 return ctx.ctx.Config()
1322}
1323
1324func PanickingConfigAndErrorContext(ctx *TestContext) ConfigAndErrorContext {
1325 return &panickingConfigAndErrorContext{
1326 ctx: ctx,
1327 }
1328}