blob: 23aadda5336bbee6f4c78dd6e597e3383b578012 [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"
Yu Liue70976d2024-10-15 20:45:35 +000022 "runtime"
Martin Stjernholm4c021242020-05-13 01:13:50 +010023 "sort"
Colin Crosscec81712017-07-13 14:43:27 -070024 "strings"
Paul Duffin281deb22021-03-06 20:29:19 +000025 "sync"
Logan Chien42039712018-03-12 16:29:17 +080026 "testing"
Colin Crosscec81712017-07-13 14:43:27 -070027
Martin Stjernholm1ebef5b2022-02-10 23:34:28 +000028 mkparser "android/soong/androidmk/parser"
29
Colin Crosscec81712017-07-13 14:43:27 -070030 "github.com/google/blueprint"
Paul Duffin25259e92021-03-07 15:45:56 +000031 "github.com/google/blueprint/proptools"
Colin Crosscec81712017-07-13 14:43:27 -070032)
33
Paul Duffin3f7bf9f2022-11-08 12:21:15 +000034func newTestContextForFixture(config Config) *TestContext {
Jeff Gastonb274ed32017-12-01 17:10:33 -080035 ctx := &TestContext{
Paul Duffin3f7bf9f2022-11-08 12:21:15 +000036 Context: &Context{blueprint.NewContext(), config},
Jeff Gastonb274ed32017-12-01 17:10:33 -080037 }
38
Colin Cross1b488422019-03-04 22:33:56 -080039 ctx.postDeps = append(ctx.postDeps, registerPathDepsMutator)
40
Colin Crossae8600b2020-10-29 17:09:13 -070041 ctx.SetFs(ctx.config.fs)
42 if ctx.config.mockBpList != "" {
43 ctx.SetModuleListFile(ctx.config.mockBpList)
44 }
45
Jeff Gaston088e29e2017-11-29 16:47:17 -080046 return ctx
Colin Crosscec81712017-07-13 14:43:27 -070047}
48
Paul Duffin3f7bf9f2022-11-08 12:21:15 +000049func NewTestContext(config Config) *TestContext {
50 ctx := newTestContextForFixture(config)
51
52 nameResolver := NewNameResolver(config)
53 ctx.NameResolver = nameResolver
54 ctx.SetNameInterface(nameResolver)
55
56 return ctx
57}
58
Paul Duffina560d5a2021-02-28 01:38:51 +000059var PrepareForTestWithArchMutator = GroupFixturePreparers(
Paul Duffin35816122021-02-24 01:49:52 +000060 // Configure architecture targets in the fixture config.
61 FixtureModifyConfig(modifyTestConfigToSupportArchMutator),
62
63 // Add the arch mutator to the context.
64 FixtureRegisterWithContext(func(ctx RegistrationContext) {
65 ctx.PreDepsMutators(registerArchMutator)
66 }),
67)
68
69var PrepareForTestWithDefaults = FixtureRegisterWithContext(func(ctx RegistrationContext) {
70 ctx.PreArchMutators(RegisterDefaultsPreArchMutators)
71})
72
73var PrepareForTestWithComponentsMutator = FixtureRegisterWithContext(func(ctx RegistrationContext) {
74 ctx.PreArchMutators(RegisterComponentsMutator)
75})
76
77var PrepareForTestWithPrebuilts = FixtureRegisterWithContext(RegisterPrebuiltMutators)
78
79var PrepareForTestWithOverrides = FixtureRegisterWithContext(func(ctx RegistrationContext) {
80 ctx.PostDepsMutators(RegisterOverridePostDepsMutators)
81})
82
Paul Duffine96108d2021-05-06 16:39:27 +010083var PrepareForTestWithLicenses = GroupFixturePreparers(
84 FixtureRegisterWithContext(RegisterLicenseKindBuildComponents),
85 FixtureRegisterWithContext(RegisterLicenseBuildComponents),
86 FixtureRegisterWithContext(registerLicenseMutators),
87)
88
Bob Badour05079212022-05-20 16:41:39 -070089var PrepareForTestWithGenNotice = FixtureRegisterWithContext(RegisterGenNoticeBuildComponents)
90
Paul Duffine96108d2021-05-06 16:39:27 +010091func registerLicenseMutators(ctx RegistrationContext) {
92 ctx.PreArchMutators(RegisterLicensesPackageMapper)
93 ctx.PreArchMutators(RegisterLicensesPropertyGatherer)
94 ctx.PostDepsMutators(RegisterLicensesDependencyChecker)
95}
96
97var PrepareForTestWithLicenseDefaultModules = GroupFixturePreparers(
98 FixtureAddTextFile("build/soong/licenses/Android.bp", `
99 license {
100 name: "Android-Apache-2.0",
101 package_name: "Android",
102 license_kinds: ["SPDX-license-identifier-Apache-2.0"],
103 copyright_notice: "Copyright (C) The Android Open Source Project",
104 license_text: ["LICENSE"],
105 }
106
107 license_kind {
108 name: "SPDX-license-identifier-Apache-2.0",
109 conditions: ["notice"],
110 url: "https://spdx.org/licenses/Apache-2.0.html",
111 }
112
113 license_kind {
114 name: "legacy_unencumbered",
115 conditions: ["unencumbered"],
116 }
117 `),
118 FixtureAddFile("build/soong/licenses/LICENSE", nil),
119)
120
Paul Duffin4fbfb592021-07-09 16:47:38 +0100121var PrepareForTestWithNamespace = FixtureRegisterWithContext(func(ctx RegistrationContext) {
122 registerNamespaceBuildComponents(ctx)
123 ctx.PreArchMutators(RegisterNamespaceMutator)
124})
125
Martin Stjernholm1ebef5b2022-02-10 23:34:28 +0000126var PrepareForTestWithMakevars = FixtureRegisterWithContext(func(ctx RegistrationContext) {
127 ctx.RegisterSingletonType("makevars", makeVarsSingletonFunc)
128})
129
Kiyoung Kimfaf6af32024-08-12 11:15:19 +0900130var PrepareForTestVintfFragmentModules = FixtureRegisterWithContext(func(ctx RegistrationContext) {
131 registerVintfFragmentComponents(ctx)
132})
133
Paul Duffinec3292b2021-03-09 01:01:31 +0000134// Test fixture preparer that will register most java build components.
135//
136// Singletons and mutators should only be added here if they are needed for a majority of java
137// module types, otherwise they should be added under a separate preparer to allow them to be
138// selected only when needed to reduce test execution time.
139//
140// Module types do not have much of an overhead unless they are used so this should include as many
141// module types as possible. The exceptions are those module types that require mutators and/or
142// singletons in order to function in which case they should be kept together in a separate
143// preparer.
144//
145// The mutators in this group were chosen because they are needed by the vast majority of tests.
146var PrepareForTestWithAndroidBuildComponents = GroupFixturePreparers(
Paul Duffin530483c2021-03-07 13:20:38 +0000147 // Sorted alphabetically as the actual order does not matter as tests automatically enforce the
148 // correct order.
Paul Duffin35816122021-02-24 01:49:52 +0000149 PrepareForTestWithArchMutator,
Paul Duffin35816122021-02-24 01:49:52 +0000150 PrepareForTestWithComponentsMutator,
Paul Duffin530483c2021-03-07 13:20:38 +0000151 PrepareForTestWithDefaults,
Paul Duffin35816122021-02-24 01:49:52 +0000152 PrepareForTestWithFilegroup,
Paul Duffin530483c2021-03-07 13:20:38 +0000153 PrepareForTestWithOverrides,
154 PrepareForTestWithPackageModule,
155 PrepareForTestWithPrebuilts,
156 PrepareForTestWithVisibility,
Kiyoung Kimfaf6af32024-08-12 11:15:19 +0900157 PrepareForTestVintfFragmentModules,
Paul Duffin35816122021-02-24 01:49:52 +0000158)
159
Paul Duffinec3292b2021-03-09 01:01:31 +0000160// Prepares an integration test with all build components from the android package.
161//
162// This should only be used by tests that want to run with as much of the build enabled as possible.
163var PrepareForIntegrationTestWithAndroid = GroupFixturePreparers(
164 PrepareForTestWithAndroidBuildComponents,
165)
166
Paul Duffin25259e92021-03-07 15:45:56 +0000167// Prepares a test that may be missing dependencies by setting allow_missing_dependencies to
168// true.
169var PrepareForTestWithAllowMissingDependencies = GroupFixturePreparers(
170 FixtureModifyProductVariables(func(variables FixtureProductVariables) {
171 variables.Allow_missing_dependencies = proptools.BoolPtr(true)
172 }),
173 FixtureModifyContext(func(ctx *TestContext) {
174 ctx.SetAllowMissingDependencies(true)
175 }),
176)
177
Paul Duffin76e5c8a2021-03-20 14:19:46 +0000178// Prepares a test that disallows non-existent paths.
179var PrepareForTestDisallowNonExistentPaths = FixtureModifyConfig(func(config Config) {
180 config.TestAllowNonExistentPaths = false
181})
182
Colin Crossa66b4632024-08-08 15:50:47 -0700183// PrepareForTestWithBuildFlag returns a FixturePreparer that sets the given flag to the given value.
184func PrepareForTestWithBuildFlag(flag, value string) FixturePreparer {
185 return FixtureModifyProductVariables(func(variables FixtureProductVariables) {
186 if variables.BuildFlags == nil {
187 variables.BuildFlags = make(map[string]string)
188 }
189 variables.BuildFlags[flag] = value
190 })
191}
192
Colin Crossae8600b2020-10-29 17:09:13 -0700193func NewTestArchContext(config Config) *TestContext {
194 ctx := NewTestContext(config)
Colin Crossae4c6182017-09-15 17:33:55 -0700195 ctx.preDeps = append(ctx.preDeps, registerArchMutator)
196 return ctx
197}
198
Colin Crosscec81712017-07-13 14:43:27 -0700199type TestContext struct {
Colin Cross4c83e5c2019-02-25 14:54:28 -0800200 *Context
Colin Crossf22fe412024-10-01 14:02:12 -0700201 preArch, preDeps, postDeps, postApex, finalDeps []RegisterMutatorFunc
202 NameResolver *NameResolver
Paul Duffin281deb22021-03-06 20:29:19 +0000203
Cole Faustae6cda62023-11-01 15:32:40 -0700204 // The list of singletons registered for the test.
205 singletons sortableComponents
Paul Duffind182fb32021-03-07 12:24:44 +0000206
Cole Faustae6cda62023-11-01 15:32:40 -0700207 // The order in which the mutators and singletons will be run in this test
Paul Duffin41d77c72021-03-07 12:23:48 +0000208 // context; for debugging.
Cole Faustae6cda62023-11-01 15:32:40 -0700209 mutatorOrder, singletonOrder []string
Colin Crosscec81712017-07-13 14:43:27 -0700210}
211
212func (ctx *TestContext) PreArchMutators(f RegisterMutatorFunc) {
213 ctx.preArch = append(ctx.preArch, f)
214}
215
Paul Duffina80ef842020-01-14 12:09:36 +0000216func (ctx *TestContext) HardCodedPreArchMutators(f RegisterMutatorFunc) {
217 // Register mutator function as normal for testing.
218 ctx.PreArchMutators(f)
219}
220
Yu Liu663e4502024-08-12 18:23:59 +0000221func (ctx *TestContext) otherModuleProvider(m blueprint.Module, p blueprint.AnyProviderKey) (any, bool) {
Liz Kammer92c72592022-10-31 14:44:28 -0400222 return ctx.Context.ModuleProvider(m, p)
223}
224
Colin Crosscec81712017-07-13 14:43:27 -0700225func (ctx *TestContext) PreDepsMutators(f RegisterMutatorFunc) {
226 ctx.preDeps = append(ctx.preDeps, f)
227}
228
229func (ctx *TestContext) PostDepsMutators(f RegisterMutatorFunc) {
230 ctx.postDeps = append(ctx.postDeps, f)
231}
232
Colin Crossf22fe412024-10-01 14:02:12 -0700233func (ctx *TestContext) PostApexMutators(f RegisterMutatorFunc) {
234 ctx.postApex = append(ctx.postApex, f)
235}
236
Martin Stjernholm710ec3a2020-01-16 15:12:04 +0000237func (ctx *TestContext) FinalDepsMutators(f RegisterMutatorFunc) {
238 ctx.finalDeps = append(ctx.finalDeps, f)
239}
240
Colin Cross3c0a83d2023-12-12 14:13:26 -0800241func (ctx *TestContext) OtherModuleProviderAdaptor() OtherModuleProviderContext {
242 return NewOtherModuleProviderAdaptor(func(module blueprint.Module, provider blueprint.AnyProviderKey) (any, bool) {
Yu Liu663e4502024-08-12 18:23:59 +0000243 return ctx.otherModuleProvider(module, provider)
Colin Cross3c0a83d2023-12-12 14:13:26 -0800244 })
245}
246
Cole Faust43ddd082024-06-17 12:32:40 -0700247func (ctx *TestContext) OtherModulePropertyErrorf(module Module, property string, fmt_ string, args ...interface{}) {
248 panic(fmt.Sprintf(fmt_, args...))
249}
250
Paul Duffin281deb22021-03-06 20:29:19 +0000251// registeredComponentOrder defines the order in which a sortableComponent type is registered at
252// runtime and provides support for reordering the components registered for a test in the same
253// way.
254type registeredComponentOrder struct {
255 // The name of the component type, used for error messages.
256 componentType string
257
258 // The names of the registered components in the order in which they were registered.
259 namesInOrder []string
260
261 // Maps from the component name to its position in the runtime ordering.
262 namesToIndex map[string]int
263
264 // A function that defines the order between two named components that can be used to sort a slice
265 // of component names into the same order as they appear in namesInOrder.
266 less func(string, string) bool
267}
268
269// registeredComponentOrderFromExistingOrder takes an existing slice of sortableComponents and
270// creates a registeredComponentOrder that contains a less function that can be used to sort a
271// subset of that list of names so it is in the same order as the original sortableComponents.
272func registeredComponentOrderFromExistingOrder(componentType string, existingOrder sortableComponents) registeredComponentOrder {
273 // Only the names from the existing order are needed for this so create a list of component names
274 // in the correct order.
275 namesInOrder := componentsToNames(existingOrder)
276
277 // Populate the map from name to position in the list.
278 nameToIndex := make(map[string]int)
279 for i, n := range namesInOrder {
280 nameToIndex[n] = i
281 }
282
283 // A function to use to map from a name to an index in the original order.
284 indexOf := func(name string) int {
285 index, ok := nameToIndex[name]
286 if !ok {
287 // Should never happen as tests that use components that are not known at runtime do not sort
288 // so should never use this function.
289 panic(fmt.Errorf("internal error: unknown %s %q should be one of %s", componentType, name, strings.Join(namesInOrder, ", ")))
290 }
291 return index
292 }
293
294 // The less function.
295 less := func(n1, n2 string) bool {
296 i1 := indexOf(n1)
297 i2 := indexOf(n2)
298 return i1 < i2
299 }
300
301 return registeredComponentOrder{
302 componentType: componentType,
303 namesInOrder: namesInOrder,
304 namesToIndex: nameToIndex,
305 less: less,
306 }
307}
308
309// componentsToNames maps from the slice of components to a slice of their names.
310func componentsToNames(components sortableComponents) []string {
311 names := make([]string, len(components))
312 for i, c := range components {
313 names[i] = c.componentName()
314 }
315 return names
316}
317
318// enforceOrdering enforces the supplied components are in the same order as is defined in this
319// object.
320//
321// If the supplied components contains any components that are not registered at runtime, i.e. test
322// specific components, then it is impossible to sort them into an order that both matches the
323// runtime and also preserves the implicit ordering defined in the test. In that case it will not
324// sort the components, instead it will just check that the components are in the correct order.
325//
326// Otherwise, this will sort the supplied components in place.
327func (o *registeredComponentOrder) enforceOrdering(components sortableComponents) {
328 // Check to see if the list of components contains any components that are
329 // not registered at runtime.
330 var unknownComponents []string
331 testOrder := componentsToNames(components)
332 for _, name := range testOrder {
333 if _, ok := o.namesToIndex[name]; !ok {
334 unknownComponents = append(unknownComponents, name)
335 break
336 }
337 }
338
339 // If the slice contains some unknown components then it is not possible to
340 // sort them into an order that matches the runtime while also preserving the
341 // order expected from the test, so in that case don't sort just check that
342 // the order of the known mutators does match.
343 if len(unknownComponents) > 0 {
344 // Check order.
345 o.checkTestOrder(testOrder, unknownComponents)
346 } else {
347 // Sort the components.
348 sort.Slice(components, func(i, j int) bool {
349 n1 := components[i].componentName()
350 n2 := components[j].componentName()
351 return o.less(n1, n2)
352 })
353 }
354}
355
356// checkTestOrder checks that the supplied testOrder matches the one defined by this object,
357// panicking if it does not.
358func (o *registeredComponentOrder) checkTestOrder(testOrder []string, unknownComponents []string) {
359 lastMatchingTest := -1
360 matchCount := 0
361 // Take a copy of the runtime order as it is modified during the comparison.
362 runtimeOrder := append([]string(nil), o.namesInOrder...)
363 componentType := o.componentType
364 for i, j := 0, 0; i < len(testOrder) && j < len(runtimeOrder); {
365 test := testOrder[i]
366 runtime := runtimeOrder[j]
367
368 if test == runtime {
369 testOrder[i] = test + fmt.Sprintf(" <-- matched with runtime %s %d", componentType, j)
370 runtimeOrder[j] = runtime + fmt.Sprintf(" <-- matched with test %s %d", componentType, i)
371 lastMatchingTest = i
372 i += 1
373 j += 1
374 matchCount += 1
375 } else if _, ok := o.namesToIndex[test]; !ok {
376 // The test component is not registered globally so assume it is the correct place, treat it
377 // as having matched and skip it.
378 i += 1
379 matchCount += 1
380 } else {
381 // Assume that the test list is in the same order as the runtime list but the runtime list
382 // contains some components that are not present in the tests. So, skip the runtime component
383 // to try and find the next one that matches the current test component.
384 j += 1
385 }
386 }
387
388 // If every item in the test order was either test specific or matched one in the runtime then
389 // it is in the correct order. Otherwise, it was not so fail.
390 if matchCount != len(testOrder) {
391 // The test component names were not all matched with a runtime component name so there must
392 // either be a component present in the test that is not present in the runtime or they must be
393 // in the wrong order.
394 testOrder[lastMatchingTest+1] = testOrder[lastMatchingTest+1] + " <--- unmatched"
395 panic(fmt.Errorf("the tests uses test specific components %q and so cannot be automatically sorted."+
396 " Unfortunately it uses %s components in the wrong order.\n"+
397 "test order:\n %s\n"+
398 "runtime order\n %s\n",
399 SortedUniqueStrings(unknownComponents),
400 componentType,
401 strings.Join(testOrder, "\n "),
402 strings.Join(runtimeOrder, "\n ")))
403 }
404}
405
406// registrationSorter encapsulates the information needed to ensure that the test mutators are
407// registered, and thereby executed, in the same order as they are at runtime.
408//
409// It MUST be populated lazily AFTER all package initialization has been done otherwise it will
410// only define the order for a subset of all the registered build components that are available for
411// the packages being tested.
412//
413// e.g if this is initialized during say the cc package initialization then any tests run in the
414// java package will not sort build components registered by the java package's init() functions.
415type registrationSorter struct {
416 // Used to ensure that this is only created once.
417 once sync.Once
418
419 // The order of mutators
420 mutatorOrder registeredComponentOrder
Paul Duffin41d77c72021-03-07 12:23:48 +0000421
422 // The order of singletons
423 singletonOrder registeredComponentOrder
Paul Duffin281deb22021-03-06 20:29:19 +0000424}
425
426// populate initializes this structure from globally registered build components.
427//
428// Only the first call has any effect.
429func (s *registrationSorter) populate() {
430 s.once.Do(func() {
431 // Created an ordering from the globally registered mutators.
432 globallyRegisteredMutators := collateGloballyRegisteredMutators()
433 s.mutatorOrder = registeredComponentOrderFromExistingOrder("mutator", globallyRegisteredMutators)
Paul Duffin41d77c72021-03-07 12:23:48 +0000434
435 // Create an ordering from the globally registered singletons.
436 globallyRegisteredSingletons := collateGloballyRegisteredSingletons()
437 s.singletonOrder = registeredComponentOrderFromExistingOrder("singleton", globallyRegisteredSingletons)
Paul Duffin281deb22021-03-06 20:29:19 +0000438 })
439}
440
441// Provides support for enforcing the same order in which build components are registered globally
442// to the order in which they are registered during tests.
443//
444// MUST only be accessed via the globallyRegisteredComponentsOrder func.
445var globalRegistrationSorter registrationSorter
446
447// globallyRegisteredComponentsOrder returns the globalRegistrationSorter after ensuring it is
448// correctly populated.
449func globallyRegisteredComponentsOrder() *registrationSorter {
450 globalRegistrationSorter.populate()
451 return &globalRegistrationSorter
452}
453
Colin Crossae8600b2020-10-29 17:09:13 -0700454func (ctx *TestContext) Register() {
Paul Duffin281deb22021-03-06 20:29:19 +0000455 globalOrder := globallyRegisteredComponentsOrder()
456
Colin Crossf22fe412024-10-01 14:02:12 -0700457 mutators := collateRegisteredMutators(ctx.preArch, ctx.preDeps, ctx.postDeps, ctx.postApex, ctx.finalDeps)
Paul Duffin281deb22021-03-06 20:29:19 +0000458 // Ensure that the mutators used in the test are in the same order as they are used at runtime.
459 globalOrder.mutatorOrder.enforceOrdering(mutators)
Paul Duffinc05b0342021-03-06 13:28:13 +0000460 mutators.registerAll(ctx.Context)
Colin Crosscec81712017-07-13 14:43:27 -0700461
Paul Duffin41d77c72021-03-07 12:23:48 +0000462 // Ensure that the singletons used in the test are in the same order as they are used at runtime.
463 globalOrder.singletonOrder.enforceOrdering(ctx.singletons)
Paul Duffind182fb32021-03-07 12:24:44 +0000464 ctx.singletons.registerAll(ctx.Context)
465
Paul Duffin41d77c72021-03-07 12:23:48 +0000466 // Save the sorted components order away to make them easy to access while debugging.
Paul Duffinf5de6682021-03-08 23:42:10 +0000467 ctx.mutatorOrder = componentsToNames(mutators)
468 ctx.singletonOrder = componentsToNames(singletons)
Colin Cross31a738b2019-12-30 18:45:15 -0800469}
470
471func (ctx *TestContext) ParseFileList(rootDir string, filePaths []string) (deps []string, errs []error) {
472 // This function adapts the old style ParseFileList calls that are spread throughout the tests
473 // to the new style that takes a config.
474 return ctx.Context.ParseFileList(rootDir, filePaths, ctx.config)
475}
476
477func (ctx *TestContext) ParseBlueprintsFiles(rootDir string) (deps []string, errs []error) {
478 // This function adapts the old style ParseBlueprintsFiles calls that are spread throughout the
479 // tests to the new style that takes a config.
480 return ctx.Context.ParseBlueprintsFiles(rootDir, ctx.config)
Colin Cross4b49b762019-11-22 15:25:03 -0800481}
482
483func (ctx *TestContext) RegisterModuleType(name string, factory ModuleFactory) {
484 ctx.Context.RegisterModuleType(name, ModuleFactoryAdaptor(factory))
485}
486
Colin Cross9aed5bc2020-12-28 15:15:34 -0800487func (ctx *TestContext) RegisterSingletonModuleType(name string, factory SingletonModuleFactory) {
488 s, m := SingletonModuleFactoryAdaptor(name, factory)
489 ctx.RegisterSingletonType(name, s)
490 ctx.RegisterModuleType(name, m)
491}
492
LaMont Jonese59c0db2023-05-15 21:50:29 +0000493func (ctx *TestContext) RegisterParallelSingletonModuleType(name string, factory SingletonModuleFactory) {
494 s, m := SingletonModuleFactoryAdaptor(name, factory)
495 ctx.RegisterParallelSingletonType(name, s)
496 ctx.RegisterModuleType(name, m)
497}
498
Colin Cross4b49b762019-11-22 15:25:03 -0800499func (ctx *TestContext) RegisterSingletonType(name string, factory SingletonFactory) {
LaMont Jonese59c0db2023-05-15 21:50:29 +0000500 ctx.singletons = append(ctx.singletons, newSingleton(name, factory, false))
501}
502
503func (ctx *TestContext) RegisterParallelSingletonType(name string, factory SingletonFactory) {
504 ctx.singletons = append(ctx.singletons, newSingleton(name, factory, true))
Colin Crosscec81712017-07-13 14:43:27 -0700505}
506
Martin Stjernholm14cdd712021-09-10 22:39:59 +0100507// ModuleVariantForTests selects a specific variant of the module with the given
508// name by matching the variations map against the variations of each module
509// variant. A module variant matches the map if every variation that exists in
510// both have the same value. Both the module and the map are allowed to have
511// extra variations that the other doesn't have. Panics if not exactly one
512// module variant matches.
513func (ctx *TestContext) ModuleVariantForTests(name string, matchVariations map[string]string) TestingModule {
514 modules := []Module{}
515 ctx.VisitAllModules(func(m blueprint.Module) {
516 if ctx.ModuleName(m) == name {
517 am := m.(Module)
518 amMut := am.base().commonProperties.DebugMutators
519 amVar := am.base().commonProperties.DebugVariations
520 matched := true
521 for i, mut := range amMut {
522 if wantedVar, found := matchVariations[mut]; found && amVar[i] != wantedVar {
523 matched = false
524 break
525 }
526 }
527 if matched {
528 modules = append(modules, am)
529 }
530 }
531 })
532
533 if len(modules) == 0 {
534 // Show all the modules or module variants that do exist.
535 var allModuleNames []string
536 var allVariants []string
537 ctx.VisitAllModules(func(m blueprint.Module) {
538 allModuleNames = append(allModuleNames, ctx.ModuleName(m))
539 if ctx.ModuleName(m) == name {
540 allVariants = append(allVariants, m.(Module).String())
541 }
542 })
543
544 if len(allVariants) == 0 {
545 panic(fmt.Errorf("failed to find module %q. All modules:\n %s",
546 name, strings.Join(SortedUniqueStrings(allModuleNames), "\n ")))
547 } else {
548 sort.Strings(allVariants)
549 panic(fmt.Errorf("failed to find module %q matching %v. All variants:\n %s",
550 name, matchVariations, strings.Join(allVariants, "\n ")))
551 }
552 }
553
554 if len(modules) > 1 {
555 moduleStrings := []string{}
556 for _, m := range modules {
557 moduleStrings = append(moduleStrings, m.String())
558 }
559 sort.Strings(moduleStrings)
560 panic(fmt.Errorf("module %q has more than one variant that match %v:\n %s",
561 name, matchVariations, strings.Join(moduleStrings, "\n ")))
562 }
563
564 return newTestingModule(ctx.config, modules[0])
565}
566
Colin Crosscec81712017-07-13 14:43:27 -0700567func (ctx *TestContext) ModuleForTests(name, variant string) TestingModule {
568 var module Module
569 ctx.VisitAllModules(func(m blueprint.Module) {
570 if ctx.ModuleName(m) == name && ctx.ModuleSubDir(m) == variant {
571 module = m.(Module)
572 }
573 })
574
575 if module == nil {
Jeff Gaston294356f2017-09-27 17:05:30 -0700576 // find all the modules that do exist
Colin Crossbeae6ec2020-08-11 12:02:11 -0700577 var allModuleNames []string
578 var allVariants []string
Jeff Gaston294356f2017-09-27 17:05:30 -0700579 ctx.VisitAllModules(func(m blueprint.Module) {
Colin Crossbeae6ec2020-08-11 12:02:11 -0700580 allModuleNames = append(allModuleNames, ctx.ModuleName(m))
581 if ctx.ModuleName(m) == name {
582 allVariants = append(allVariants, ctx.ModuleSubDir(m))
583 }
Jeff Gaston294356f2017-09-27 17:05:30 -0700584 })
Colin Crossbeae6ec2020-08-11 12:02:11 -0700585 sort.Strings(allVariants)
Jeff Gaston294356f2017-09-27 17:05:30 -0700586
Colin Crossbeae6ec2020-08-11 12:02:11 -0700587 if len(allVariants) == 0 {
588 panic(fmt.Errorf("failed to find module %q. All modules:\n %s",
Martin Stjernholm98e0d882021-09-09 21:34:02 +0100589 name, strings.Join(SortedUniqueStrings(allModuleNames), "\n ")))
Colin Crossbeae6ec2020-08-11 12:02:11 -0700590 } else {
591 panic(fmt.Errorf("failed to find module %q variant %q. All variants:\n %s",
592 name, variant, strings.Join(allVariants, "\n ")))
593 }
Colin Crosscec81712017-07-13 14:43:27 -0700594 }
595
Paul Duffin709e0e32021-03-22 10:09:02 +0000596 return newTestingModule(ctx.config, module)
Colin Crosscec81712017-07-13 14:43:27 -0700597}
598
Jiyong Park37b25202018-07-11 10:49:27 +0900599func (ctx *TestContext) ModuleVariantsForTests(name string) []string {
600 var variants []string
601 ctx.VisitAllModules(func(m blueprint.Module) {
602 if ctx.ModuleName(m) == name {
603 variants = append(variants, ctx.ModuleSubDir(m))
604 }
605 })
606 return variants
607}
608
Colin Cross4c83e5c2019-02-25 14:54:28 -0800609// SingletonForTests returns a TestingSingleton for the singleton registered with the given name.
610func (ctx *TestContext) SingletonForTests(name string) TestingSingleton {
611 allSingletonNames := []string{}
612 for _, s := range ctx.Singletons() {
613 n := ctx.SingletonName(s)
614 if n == name {
615 return TestingSingleton{
Paul Duffin709e0e32021-03-22 10:09:02 +0000616 baseTestingComponent: newBaseTestingComponent(ctx.config, s.(testBuildProvider)),
Paul Duffin31a22882021-03-22 09:29:00 +0000617 singleton: s.(*singletonAdaptor).Singleton,
Colin Cross4c83e5c2019-02-25 14:54:28 -0800618 }
619 }
620 allSingletonNames = append(allSingletonNames, n)
621 }
622
623 panic(fmt.Errorf("failed to find singleton %q."+
624 "\nall singletons: %v", name, allSingletonNames))
625}
626
Martin Stjernholm1ebef5b2022-02-10 23:34:28 +0000627type InstallMakeRule struct {
628 Target string
629 Deps []string
630 OrderOnlyDeps []string
631}
632
633func parseMkRules(t *testing.T, config Config, nodes []mkparser.Node) []InstallMakeRule {
634 var rules []InstallMakeRule
635 for _, node := range nodes {
636 if mkParserRule, ok := node.(*mkparser.Rule); ok {
637 var rule InstallMakeRule
638
639 if targets := mkParserRule.Target.Words(); len(targets) == 0 {
640 t.Fatalf("no targets for rule %s", mkParserRule.Dump())
641 } else if len(targets) > 1 {
642 t.Fatalf("unsupported multiple targets for rule %s", mkParserRule.Dump())
643 } else if !targets[0].Const() {
644 t.Fatalf("unsupported non-const target for rule %s", mkParserRule.Dump())
645 } else {
646 rule.Target = normalizeStringRelativeToTop(config, targets[0].Value(nil))
647 }
648
649 prereqList := &rule.Deps
650 for _, prereq := range mkParserRule.Prerequisites.Words() {
651 if !prereq.Const() {
652 t.Fatalf("unsupported non-const prerequisite for rule %s", mkParserRule.Dump())
653 }
654
655 if prereq.Value(nil) == "|" {
656 prereqList = &rule.OrderOnlyDeps
657 continue
658 }
659
660 *prereqList = append(*prereqList, normalizeStringRelativeToTop(config, prereq.Value(nil)))
661 }
662
663 rules = append(rules, rule)
664 }
665 }
666
667 return rules
668}
669
670func (ctx *TestContext) InstallMakeRulesForTesting(t *testing.T) []InstallMakeRule {
671 installs := ctx.SingletonForTests("makevars").Singleton().(*makeVarsSingleton).installsForTesting
672 buf := bytes.NewBuffer(append([]byte(nil), installs...))
673 parser := mkparser.NewParser("makevars", buf)
674
675 nodes, errs := parser.Parse()
676 if len(errs) > 0 {
677 t.Fatalf("error parsing install rules: %s", errs[0])
678 }
679
680 return parseMkRules(t, ctx.config, nodes)
681}
682
Paul Duffin8eb45732022-10-04 19:03:31 +0100683// MakeVarVariable provides access to make vars that will be written by the makeVarsSingleton
684type MakeVarVariable interface {
685 // Name is the name of the variable.
686 Name() string
687
688 // Value is the value of the variable.
689 Value() string
690}
691
692func (v makeVarsVariable) Name() string {
693 return v.name
694}
695
696func (v makeVarsVariable) Value() string {
697 return v.value
698}
699
700// PrepareForTestAccessingMakeVars sets up the test so that MakeVarsForTesting will work.
701var PrepareForTestAccessingMakeVars = GroupFixturePreparers(
702 PrepareForTestWithAndroidMk,
703 PrepareForTestWithMakevars,
704)
705
706// MakeVarsForTesting returns a filtered list of MakeVarVariable objects that represent the
707// variables that will be written out.
708//
709// It is necessary to use PrepareForTestAccessingMakeVars in tests that want to call this function.
710// Along with any other preparers needed to add the make vars.
711func (ctx *TestContext) MakeVarsForTesting(filter func(variable MakeVarVariable) bool) []MakeVarVariable {
712 vars := ctx.SingletonForTests("makevars").Singleton().(*makeVarsSingleton).varsForTesting
713 result := make([]MakeVarVariable, 0, len(vars))
714 for _, v := range vars {
715 if filter(v) {
716 result = append(result, v)
717 }
718 }
719
720 return result
721}
722
Colin Crossaa255532020-07-03 13:18:24 -0700723func (ctx *TestContext) Config() Config {
724 return ctx.config
725}
726
Colin Cross4c83e5c2019-02-25 14:54:28 -0800727type testBuildProvider interface {
728 BuildParamsForTests() []BuildParams
729 RuleParamsForTests() map[blueprint.Rule]blueprint.RuleParams
730}
731
732type TestingBuildParams struct {
733 BuildParams
734 RuleParams blueprint.RuleParams
Paul Duffin709e0e32021-03-22 10:09:02 +0000735
736 config Config
737}
738
739// RelativeToTop creates a new instance of this which has had any usages of the current test's
740// temporary and test specific build directory replaced with a path relative to the notional top.
741//
742// The parts of this structure which are changed are:
743// * BuildParams
Colin Crossd079e0b2022-08-16 10:27:33 -0700744// - Args
745// - All Path, Paths, WritablePath and WritablePaths fields.
Paul Duffin709e0e32021-03-22 10:09:02 +0000746//
747// * RuleParams
Colin Crossd079e0b2022-08-16 10:27:33 -0700748// - Command
749// - Depfile
750// - Rspfile
751// - RspfileContent
Colin Crossd079e0b2022-08-16 10:27:33 -0700752// - CommandDeps
753// - CommandOrderOnly
Paul Duffin709e0e32021-03-22 10:09:02 +0000754//
755// See PathRelativeToTop for more details.
Paul Duffina71a67a2021-03-29 00:42:57 +0100756//
757// deprecated: this is no longer needed as TestingBuildParams are created in this form.
Paul Duffin709e0e32021-03-22 10:09:02 +0000758func (p TestingBuildParams) RelativeToTop() TestingBuildParams {
759 // If this is not a valid params then just return it back. That will make it easy to use with the
760 // Maybe...() methods.
761 if p.Rule == nil {
762 return p
763 }
764 if p.config.config == nil {
Paul Duffine8366da2021-03-24 10:40:38 +0000765 return p
Paul Duffin709e0e32021-03-22 10:09:02 +0000766 }
767 // Take a copy of the build params and replace any args that contains test specific temporary
768 // paths with paths relative to the top.
769 bparams := p.BuildParams
Paul Duffinbbb0f8f2021-03-24 10:34:52 +0000770 bparams.Depfile = normalizeWritablePathRelativeToTop(bparams.Depfile)
771 bparams.Output = normalizeWritablePathRelativeToTop(bparams.Output)
772 bparams.Outputs = bparams.Outputs.RelativeToTop()
Paul Duffinbbb0f8f2021-03-24 10:34:52 +0000773 bparams.ImplicitOutput = normalizeWritablePathRelativeToTop(bparams.ImplicitOutput)
774 bparams.ImplicitOutputs = bparams.ImplicitOutputs.RelativeToTop()
775 bparams.Input = normalizePathRelativeToTop(bparams.Input)
776 bparams.Inputs = bparams.Inputs.RelativeToTop()
777 bparams.Implicit = normalizePathRelativeToTop(bparams.Implicit)
778 bparams.Implicits = bparams.Implicits.RelativeToTop()
779 bparams.OrderOnly = bparams.OrderOnly.RelativeToTop()
780 bparams.Validation = normalizePathRelativeToTop(bparams.Validation)
781 bparams.Validations = bparams.Validations.RelativeToTop()
Paul Duffin709e0e32021-03-22 10:09:02 +0000782 bparams.Args = normalizeStringMapRelativeToTop(p.config, bparams.Args)
783
784 // Ditto for any fields in the RuleParams.
785 rparams := p.RuleParams
786 rparams.Command = normalizeStringRelativeToTop(p.config, rparams.Command)
787 rparams.Depfile = normalizeStringRelativeToTop(p.config, rparams.Depfile)
788 rparams.Rspfile = normalizeStringRelativeToTop(p.config, rparams.Rspfile)
789 rparams.RspfileContent = normalizeStringRelativeToTop(p.config, rparams.RspfileContent)
Paul Duffin709e0e32021-03-22 10:09:02 +0000790 rparams.CommandDeps = normalizeStringArrayRelativeToTop(p.config, rparams.CommandDeps)
791 rparams.CommandOrderOnly = normalizeStringArrayRelativeToTop(p.config, rparams.CommandOrderOnly)
792
793 return TestingBuildParams{
794 BuildParams: bparams,
795 RuleParams: rparams,
796 }
Colin Cross4c83e5c2019-02-25 14:54:28 -0800797}
798
Paul Duffinbbb0f8f2021-03-24 10:34:52 +0000799func normalizeWritablePathRelativeToTop(path WritablePath) WritablePath {
800 if path == nil {
801 return nil
802 }
803 return path.RelativeToTop().(WritablePath)
804}
805
806func normalizePathRelativeToTop(path Path) Path {
807 if path == nil {
808 return nil
809 }
810 return path.RelativeToTop()
811}
812
Jiakai Zhangcf61e3c2023-05-08 16:28:38 +0000813func allOutputs(p BuildParams) []string {
814 outputs := append(WritablePaths(nil), p.Outputs...)
815 outputs = append(outputs, p.ImplicitOutputs...)
816 if p.Output != nil {
817 outputs = append(outputs, p.Output)
818 }
819 return outputs.Strings()
820}
821
822// AllOutputs returns all 'BuildParams.Output's and 'BuildParams.Outputs's in their full path string forms.
823func (p TestingBuildParams) AllOutputs() []string {
824 return allOutputs(p.BuildParams)
825}
826
Paul Duffin0eda26b92021-03-22 09:34:29 +0000827// baseTestingComponent provides functionality common to both TestingModule and TestingSingleton.
828type baseTestingComponent struct {
Paul Duffin709e0e32021-03-22 10:09:02 +0000829 config Config
Paul Duffin0eda26b92021-03-22 09:34:29 +0000830 provider testBuildProvider
831}
832
Paul Duffin709e0e32021-03-22 10:09:02 +0000833func newBaseTestingComponent(config Config, provider testBuildProvider) baseTestingComponent {
834 return baseTestingComponent{config, provider}
835}
836
837// A function that will normalize a string containing paths, e.g. ninja command, by replacing
838// any references to the test specific temporary build directory that changes with each run to a
839// fixed path relative to a notional top directory.
840//
841// This is similar to StringPathRelativeToTop except that assumes the string is a single path
842// containing at most one instance of the temporary build directory at the start of the path while
843// this assumes that there can be any number at any position.
844func normalizeStringRelativeToTop(config Config, s string) string {
Colin Cross3b1c6842024-07-26 11:52:57 -0700845 // The outDir usually looks something like: /tmp/testFoo2345/001
Paul Duffin709e0e32021-03-22 10:09:02 +0000846 //
Colin Cross3b1c6842024-07-26 11:52:57 -0700847 // Replace any usage of the outDir with out/soong, e.g. replace "/tmp/testFoo2345/001" with
Paul Duffin709e0e32021-03-22 10:09:02 +0000848 // "out/soong".
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200849 outSoongDir := filepath.Clean(config.soongOutDir)
Paul Duffin709e0e32021-03-22 10:09:02 +0000850 re := regexp.MustCompile(`\Q` + outSoongDir + `\E\b`)
851 s = re.ReplaceAllString(s, "out/soong")
852
Colin Cross3b1c6842024-07-26 11:52:57 -0700853 // Replace any usage of the outDir/.. with out, e.g. replace "/tmp/testFoo2345" with
Paul Duffin709e0e32021-03-22 10:09:02 +0000854 // "out". This must come after the previous replacement otherwise this would replace
855 // "/tmp/testFoo2345/001" with "out/001" instead of "out/soong".
856 outDir := filepath.Dir(outSoongDir)
857 re = regexp.MustCompile(`\Q` + outDir + `\E\b`)
858 s = re.ReplaceAllString(s, "out")
859
860 return s
861}
862
863// normalizeStringArrayRelativeToTop creates a new slice constructed by applying
864// normalizeStringRelativeToTop to each item in the slice.
865func normalizeStringArrayRelativeToTop(config Config, slice []string) []string {
866 newSlice := make([]string, len(slice))
867 for i, s := range slice {
868 newSlice[i] = normalizeStringRelativeToTop(config, s)
869 }
870 return newSlice
871}
872
873// normalizeStringMapRelativeToTop creates a new map constructed by applying
874// normalizeStringRelativeToTop to each value in the map.
875func normalizeStringMapRelativeToTop(config Config, m map[string]string) map[string]string {
876 newMap := map[string]string{}
877 for k, v := range m {
878 newMap[k] = normalizeStringRelativeToTop(config, v)
879 }
880 return newMap
Paul Duffin0eda26b92021-03-22 09:34:29 +0000881}
882
883func (b baseTestingComponent) newTestingBuildParams(bparams BuildParams) TestingBuildParams {
Colin Cross4c83e5c2019-02-25 14:54:28 -0800884 return TestingBuildParams{
Paul Duffin709e0e32021-03-22 10:09:02 +0000885 config: b.config,
Colin Cross4c83e5c2019-02-25 14:54:28 -0800886 BuildParams: bparams,
Paul Duffin0eda26b92021-03-22 09:34:29 +0000887 RuleParams: b.provider.RuleParamsForTests()[bparams.Rule],
Paul Duffine8366da2021-03-24 10:40:38 +0000888 }.RelativeToTop()
Colin Cross4c83e5c2019-02-25 14:54:28 -0800889}
890
Paul Duffin0eda26b92021-03-22 09:34:29 +0000891func (b baseTestingComponent) maybeBuildParamsFromRule(rule string) (TestingBuildParams, []string) {
Thiébaud Weksteen3600b802020-08-27 15:50:24 +0200892 var searchedRules []string
Paul Duffin4dbf6cf2021-06-08 10:06:37 +0100893 buildParams := b.provider.BuildParamsForTests()
894 for _, p := range buildParams {
895 ruleAsString := p.Rule.String()
896 searchedRules = append(searchedRules, ruleAsString)
897 if strings.Contains(ruleAsString, rule) {
Paul Duffin0eda26b92021-03-22 09:34:29 +0000898 return b.newTestingBuildParams(p), searchedRules
Colin Cross4c83e5c2019-02-25 14:54:28 -0800899 }
900 }
Thiébaud Weksteen3600b802020-08-27 15:50:24 +0200901 return TestingBuildParams{}, searchedRules
Colin Cross4c83e5c2019-02-25 14:54:28 -0800902}
903
Paul Duffin0eda26b92021-03-22 09:34:29 +0000904func (b baseTestingComponent) buildParamsFromRule(rule string) TestingBuildParams {
905 p, searchRules := b.maybeBuildParamsFromRule(rule)
Colin Cross4c83e5c2019-02-25 14:54:28 -0800906 if p.Rule == nil {
Paul Duffin4dbf6cf2021-06-08 10:06:37 +0100907 panic(fmt.Errorf("couldn't find rule %q.\nall rules:\n%s", rule, strings.Join(searchRules, "\n")))
Colin Cross4c83e5c2019-02-25 14:54:28 -0800908 }
909 return p
910}
911
Martin Stjernholm827ba622022-02-03 00:20:11 +0000912func (b baseTestingComponent) maybeBuildParamsFromDescription(desc string) (TestingBuildParams, []string) {
913 var searchedDescriptions []string
Paul Duffin0eda26b92021-03-22 09:34:29 +0000914 for _, p := range b.provider.BuildParamsForTests() {
Martin Stjernholm827ba622022-02-03 00:20:11 +0000915 searchedDescriptions = append(searchedDescriptions, p.Description)
Colin Crossb88b3c52019-06-10 15:15:17 -0700916 if strings.Contains(p.Description, desc) {
Martin Stjernholm827ba622022-02-03 00:20:11 +0000917 return b.newTestingBuildParams(p), searchedDescriptions
Colin Cross4c83e5c2019-02-25 14:54:28 -0800918 }
919 }
Martin Stjernholm827ba622022-02-03 00:20:11 +0000920 return TestingBuildParams{}, searchedDescriptions
Colin Cross4c83e5c2019-02-25 14:54:28 -0800921}
922
Paul Duffin0eda26b92021-03-22 09:34:29 +0000923func (b baseTestingComponent) buildParamsFromDescription(desc string) TestingBuildParams {
Martin Stjernholm827ba622022-02-03 00:20:11 +0000924 p, searchedDescriptions := b.maybeBuildParamsFromDescription(desc)
Colin Cross4c83e5c2019-02-25 14:54:28 -0800925 if p.Rule == nil {
Martin Stjernholm827ba622022-02-03 00:20:11 +0000926 panic(fmt.Errorf("couldn't find description %q\nall descriptions:\n%s", desc, strings.Join(searchedDescriptions, "\n")))
Colin Cross4c83e5c2019-02-25 14:54:28 -0800927 }
928 return p
929}
930
Paul Duffin0eda26b92021-03-22 09:34:29 +0000931func (b baseTestingComponent) maybeBuildParamsFromOutput(file string) (TestingBuildParams, []string) {
Martin Stjernholma4aaa472021-09-17 02:51:48 +0100932 searchedOutputs := WritablePaths(nil)
Paul Duffin0eda26b92021-03-22 09:34:29 +0000933 for _, p := range b.provider.BuildParamsForTests() {
Colin Cross4c83e5c2019-02-25 14:54:28 -0800934 outputs := append(WritablePaths(nil), p.Outputs...)
Colin Cross1d2cf042019-03-29 15:33:06 -0700935 outputs = append(outputs, p.ImplicitOutputs...)
Colin Cross4c83e5c2019-02-25 14:54:28 -0800936 if p.Output != nil {
937 outputs = append(outputs, p.Output)
938 }
939 for _, f := range outputs {
Paul Duffin4e6e35c2021-03-22 11:34:57 +0000940 if f.String() == file || f.Rel() == file || PathRelativeToTop(f) == file {
Paul Duffin0eda26b92021-03-22 09:34:29 +0000941 return b.newTestingBuildParams(p), nil
Colin Cross4c83e5c2019-02-25 14:54:28 -0800942 }
Martin Stjernholma4aaa472021-09-17 02:51:48 +0100943 searchedOutputs = append(searchedOutputs, f)
Colin Cross4c83e5c2019-02-25 14:54:28 -0800944 }
945 }
Martin Stjernholma4aaa472021-09-17 02:51:48 +0100946
947 formattedOutputs := []string{}
948 for _, f := range searchedOutputs {
949 formattedOutputs = append(formattedOutputs,
950 fmt.Sprintf("%s (rel=%s)", PathRelativeToTop(f), f.Rel()))
951 }
952
953 return TestingBuildParams{}, formattedOutputs
Colin Cross4c83e5c2019-02-25 14:54:28 -0800954}
955
Paul Duffin0eda26b92021-03-22 09:34:29 +0000956func (b baseTestingComponent) buildParamsFromOutput(file string) TestingBuildParams {
957 p, searchedOutputs := b.maybeBuildParamsFromOutput(file)
Colin Cross4c83e5c2019-02-25 14:54:28 -0800958 if p.Rule == nil {
Paul Duffin4e6e35c2021-03-22 11:34:57 +0000959 panic(fmt.Errorf("couldn't find output %q.\nall outputs:\n %s\n",
960 file, strings.Join(searchedOutputs, "\n ")))
Colin Cross4c83e5c2019-02-25 14:54:28 -0800961 }
962 return p
963}
964
Paul Duffin0eda26b92021-03-22 09:34:29 +0000965func (b baseTestingComponent) allOutputs() []string {
Colin Cross4c83e5c2019-02-25 14:54:28 -0800966 var outputFullPaths []string
Paul Duffin0eda26b92021-03-22 09:34:29 +0000967 for _, p := range b.provider.BuildParamsForTests() {
Jiakai Zhangcf61e3c2023-05-08 16:28:38 +0000968 outputFullPaths = append(outputFullPaths, allOutputs(p)...)
Colin Cross4c83e5c2019-02-25 14:54:28 -0800969 }
970 return outputFullPaths
971}
972
Paul Duffin31a22882021-03-22 09:29:00 +0000973// MaybeRule finds a call to ctx.Build with BuildParams.Rule set to a rule with the given name. Returns an empty
974// BuildParams if no rule is found.
975func (b baseTestingComponent) MaybeRule(rule string) TestingBuildParams {
Paul Duffin0eda26b92021-03-22 09:34:29 +0000976 r, _ := b.maybeBuildParamsFromRule(rule)
Paul Duffin31a22882021-03-22 09:29:00 +0000977 return r
978}
979
980// Rule finds a call to ctx.Build with BuildParams.Rule set to a rule with the given name. Panics if no rule is found.
981func (b baseTestingComponent) Rule(rule string) TestingBuildParams {
Paul Duffin0eda26b92021-03-22 09:34:29 +0000982 return b.buildParamsFromRule(rule)
Paul Duffin31a22882021-03-22 09:29:00 +0000983}
984
985// MaybeDescription finds a call to ctx.Build with BuildParams.Description set to a the given string. Returns an empty
986// BuildParams if no rule is found.
987func (b baseTestingComponent) MaybeDescription(desc string) TestingBuildParams {
Martin Stjernholm827ba622022-02-03 00:20:11 +0000988 p, _ := b.maybeBuildParamsFromDescription(desc)
989 return p
Paul Duffin31a22882021-03-22 09:29:00 +0000990}
991
992// Description finds a call to ctx.Build with BuildParams.Description set to a the given string. Panics if no rule is
993// found.
994func (b baseTestingComponent) Description(desc string) TestingBuildParams {
Paul Duffin0eda26b92021-03-22 09:34:29 +0000995 return b.buildParamsFromDescription(desc)
Paul Duffin31a22882021-03-22 09:29:00 +0000996}
997
998// MaybeOutput finds a call to ctx.Build with a BuildParams.Output or BuildParams.Outputs whose String() or Rel()
999// value matches the provided string. Returns an empty BuildParams if no rule is found.
1000func (b baseTestingComponent) MaybeOutput(file string) TestingBuildParams {
Paul Duffin0eda26b92021-03-22 09:34:29 +00001001 p, _ := b.maybeBuildParamsFromOutput(file)
Paul Duffin31a22882021-03-22 09:29:00 +00001002 return p
1003}
1004
1005// Output finds a call to ctx.Build with a BuildParams.Output or BuildParams.Outputs whose String() or Rel()
1006// value matches the provided string. Panics if no rule is found.
1007func (b baseTestingComponent) Output(file string) TestingBuildParams {
Paul Duffin0eda26b92021-03-22 09:34:29 +00001008 return b.buildParamsFromOutput(file)
Paul Duffin31a22882021-03-22 09:29:00 +00001009}
1010
1011// AllOutputs returns all 'BuildParams.Output's and 'BuildParams.Outputs's in their full path string forms.
1012func (b baseTestingComponent) AllOutputs() []string {
Paul Duffin0eda26b92021-03-22 09:34:29 +00001013 return b.allOutputs()
Paul Duffin31a22882021-03-22 09:29:00 +00001014}
1015
Colin Crossb77ffc42019-01-05 22:09:19 -08001016// TestingModule is wrapper around an android.Module that provides methods to find information about individual
1017// ctx.Build parameters for verification in tests.
Colin Crosscec81712017-07-13 14:43:27 -07001018type TestingModule struct {
Paul Duffin31a22882021-03-22 09:29:00 +00001019 baseTestingComponent
Colin Crosscec81712017-07-13 14:43:27 -07001020 module Module
1021}
1022
Paul Duffin709e0e32021-03-22 10:09:02 +00001023func newTestingModule(config Config, module Module) TestingModule {
Paul Duffin31a22882021-03-22 09:29:00 +00001024 return TestingModule{
Paul Duffin709e0e32021-03-22 10:09:02 +00001025 newBaseTestingComponent(config, module),
Paul Duffin31a22882021-03-22 09:29:00 +00001026 module,
1027 }
1028}
1029
Colin Crossb77ffc42019-01-05 22:09:19 -08001030// Module returns the Module wrapped by the TestingModule.
Colin Crosscec81712017-07-13 14:43:27 -07001031func (m TestingModule) Module() Module {
1032 return m.module
1033}
1034
Paul Duffin97d8b402021-03-22 16:04:50 +00001035// VariablesForTestsRelativeToTop returns a copy of the Module.VariablesForTests() with every value
1036// having any temporary build dir usages replaced with paths relative to a notional top.
1037func (m TestingModule) VariablesForTestsRelativeToTop() map[string]string {
1038 return normalizeStringMapRelativeToTop(m.config, m.module.VariablesForTests())
1039}
1040
mrziwangd38e63d2024-07-15 13:43:37 -07001041// OutputFiles checks if module base outputFiles property has any output
mrziwange81e77a2024-06-13 17:02:59 -07001042// files can be used to return.
mrziwangd38e63d2024-07-15 13:43:37 -07001043// Exits the test immediately if there is an error and
mrziwange81e77a2024-06-13 17:02:59 -07001044// otherwise returns the result of calling Paths.RelativeToTop
Paul Duffin962783a2021-03-29 00:00:17 +01001045// on the returned Paths.
Yu Liu51c22312024-08-20 23:56:15 +00001046func (m TestingModule) OutputFiles(ctx *TestContext, t *testing.T, tag string) Paths {
1047 outputFiles := OtherModuleProviderOrDefault(ctx.OtherModuleProviderAdaptor(), m.Module(), OutputFilesProvider)
mrziwangabdb2932024-06-18 12:43:41 -07001048 if tag == "" && outputFiles.DefaultOutputFiles != nil {
1049 return outputFiles.DefaultOutputFiles.RelativeToTop()
1050 } else if taggedOutputFiles, hasTag := outputFiles.TaggedOutputFiles[tag]; hasTag {
mrziwangd38e63d2024-07-15 13:43:37 -07001051 return taggedOutputFiles.RelativeToTop()
mrziwange81e77a2024-06-13 17:02:59 -07001052 }
1053
mrziwangd38e63d2024-07-15 13:43:37 -07001054 t.Fatal(fmt.Errorf("No test output file has been set for tag %q", tag))
1055 return nil
Paul Duffin962783a2021-03-29 00:00:17 +01001056}
1057
Colin Cross4c83e5c2019-02-25 14:54:28 -08001058// TestingSingleton is wrapper around an android.Singleton that provides methods to find information about individual
1059// ctx.Build parameters for verification in tests.
1060type TestingSingleton struct {
Paul Duffin31a22882021-03-22 09:29:00 +00001061 baseTestingComponent
Colin Cross4c83e5c2019-02-25 14:54:28 -08001062 singleton Singleton
Colin Cross4c83e5c2019-02-25 14:54:28 -08001063}
1064
1065// Singleton returns the Singleton wrapped by the TestingSingleton.
1066func (s TestingSingleton) Singleton() Singleton {
1067 return s.singleton
1068}
1069
Logan Chien42039712018-03-12 16:29:17 +08001070func FailIfErrored(t *testing.T, errs []error) {
1071 t.Helper()
1072 if len(errs) > 0 {
1073 for _, err := range errs {
1074 t.Error(err)
1075 }
1076 t.FailNow()
1077 }
1078}
Logan Chienee97c3e2018-03-12 16:34:26 +08001079
Paul Duffinea8a3862021-03-04 17:58:33 +00001080// Fail if no errors that matched the regular expression were found.
1081//
1082// Returns true if a matching error was found, false otherwise.
1083func FailIfNoMatchingErrors(t *testing.T, pattern string, errs []error) bool {
Logan Chienee97c3e2018-03-12 16:34:26 +08001084 t.Helper()
1085
1086 matcher, err := regexp.Compile(pattern)
1087 if err != nil {
Paul Duffinea8a3862021-03-04 17:58:33 +00001088 t.Fatalf("failed to compile regular expression %q because %s", pattern, err)
Logan Chienee97c3e2018-03-12 16:34:26 +08001089 }
1090
1091 found := false
1092 for _, err := range errs {
1093 if matcher.FindStringIndex(err.Error()) != nil {
1094 found = true
1095 break
1096 }
1097 }
1098 if !found {
Steven Moreland082e2062022-08-30 01:11:11 +00001099 t.Errorf("could not match the expected error regex %q (checked %d error(s))", pattern, len(errs))
Logan Chienee97c3e2018-03-12 16:34:26 +08001100 for i, err := range errs {
Colin Crossaede88c2020-08-11 12:17:01 -07001101 t.Errorf("errs[%d] = %q", i, err)
Logan Chienee97c3e2018-03-12 16:34:26 +08001102 }
1103 }
Paul Duffinea8a3862021-03-04 17:58:33 +00001104
1105 return found
Logan Chienee97c3e2018-03-12 16:34:26 +08001106}
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -07001107
Paul Duffin91e38192019-08-05 15:07:57 +01001108func CheckErrorsAgainstExpectations(t *testing.T, errs []error, expectedErrorPatterns []string) {
1109 t.Helper()
1110
1111 if expectedErrorPatterns == nil {
1112 FailIfErrored(t, errs)
1113 } else {
1114 for _, expectedError := range expectedErrorPatterns {
1115 FailIfNoMatchingErrors(t, expectedError, errs)
1116 }
1117 if len(errs) > len(expectedErrorPatterns) {
1118 t.Errorf("additional errors found, expected %d, found %d",
1119 len(expectedErrorPatterns), len(errs))
1120 for i, expectedError := range expectedErrorPatterns {
1121 t.Errorf("expectedErrors[%d] = %s", i, expectedError)
1122 }
1123 for i, err := range errs {
1124 t.Errorf("errs[%d] = %s", i, err)
1125 }
Paul Duffinea8a3862021-03-04 17:58:33 +00001126 t.FailNow()
Paul Duffin91e38192019-08-05 15:07:57 +01001127 }
1128 }
Paul Duffin91e38192019-08-05 15:07:57 +01001129}
1130
Jingwen Chencda22c92020-11-23 00:22:30 -05001131func SetKatiEnabledForTests(config Config) {
1132 config.katiEnabled = true
Paul Duffin8c3fec42020-03-04 20:15:08 +00001133}
1134
Dennis Shend4f5d932023-01-31 20:27:21 +00001135func SetTrimmedApexEnabledForTests(config Config) {
1136 config.productVariables.TrimmedApex = new(bool)
1137 *config.productVariables.TrimmedApex = true
1138}
1139
Colin Crossaa255532020-07-03 13:18:24 -07001140func AndroidMkEntriesForTest(t *testing.T, ctx *TestContext, mod blueprint.Module) []AndroidMkEntries {
Liz Kammer6be69062022-11-04 16:06:02 -04001141 t.Helper()
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -07001142 var p AndroidMkEntriesProvider
1143 var ok bool
1144 if p, ok = mod.(AndroidMkEntriesProvider); !ok {
Roland Levillaindfe75b32019-07-23 16:53:32 +01001145 t.Errorf("module does not implement AndroidMkEntriesProvider: " + mod.Name())
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -07001146 }
Jiyong Park0b0e1b92019-12-03 13:24:29 +09001147
1148 entriesList := p.AndroidMkEntries()
LaMont Jonesb5099382024-01-10 23:42:36 +00001149 aconfigUpdateAndroidMkEntries(ctx, mod.(Module), &entriesList)
Jihoon Kanga3a05462024-04-05 00:36:44 +00001150 for i := range entriesList {
Colin Crossaa255532020-07-03 13:18:24 -07001151 entriesList[i].fillInEntries(ctx, mod)
Jiyong Park0b0e1b92019-12-03 13:24:29 +09001152 }
1153 return entriesList
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -07001154}
Jooyung Han12df5fb2019-07-11 16:18:47 +09001155
Yu Liue70976d2024-10-15 20:45:35 +00001156func AndroidMkInfoForTest(t *testing.T, ctx *TestContext, mod blueprint.Module) *AndroidMkProviderInfo {
1157 if runtime.GOOS == "darwin" && mod.(Module).base().Os() != Darwin {
1158 // The AndroidMkInfo provider is not set in this case.
1159 t.Skip("AndroidMkInfo provider is not set on darwin")
1160 }
1161
1162 t.Helper()
1163 var ok bool
1164 if _, ok = mod.(AndroidMkProviderInfoProducer); !ok {
1165 t.Errorf("module does not implement AndroidMkProviderInfoProducer: " + mod.Name())
1166 }
1167
1168 info := OtherModuleProviderOrDefault(ctx, mod, AndroidMkInfoProvider)
1169 aconfigUpdateAndroidMkInfos(ctx, mod.(Module), info)
1170 info.PrimaryInfo.fillInEntries(ctx, mod)
1171 if len(info.ExtraInfo) > 0 {
1172 for _, ei := range info.ExtraInfo {
1173 ei.fillInEntries(ctx, mod)
1174 }
1175 }
1176
1177 return info
1178}
1179
Colin Crossaa255532020-07-03 13:18:24 -07001180func AndroidMkDataForTest(t *testing.T, ctx *TestContext, mod blueprint.Module) AndroidMkData {
Liz Kammer6be69062022-11-04 16:06:02 -04001181 t.Helper()
Jooyung Han12df5fb2019-07-11 16:18:47 +09001182 var p AndroidMkDataProvider
1183 var ok bool
1184 if p, ok = mod.(AndroidMkDataProvider); !ok {
Sam Delmerico4e115cc2023-01-19 15:36:52 -05001185 t.Fatalf("module does not implement AndroidMkDataProvider: " + mod.Name())
Jooyung Han12df5fb2019-07-11 16:18:47 +09001186 }
1187 data := p.AndroidMk()
Colin Crossaa255532020-07-03 13:18:24 -07001188 data.fillInData(ctx, mod)
LaMont Jonesb5099382024-01-10 23:42:36 +00001189 aconfigUpdateAndroidMkData(ctx, mod.(Module), &data)
Jooyung Han12df5fb2019-07-11 16:18:47 +09001190 return data
1191}
Paul Duffin9b478b02019-12-10 13:41:51 +00001192
1193// Normalize the path for testing.
1194//
1195// If the path is relative to the build directory then return the relative path
1196// to avoid tests having to deal with the dynamically generated build directory.
1197//
1198// Otherwise, return the supplied path as it is almost certainly a source path
1199// that is relative to the root of the source tree.
1200//
1201// The build and source paths should be distinguishable based on their contents.
Paul Duffin567465d2021-03-16 01:21:34 +00001202//
1203// deprecated: use PathRelativeToTop instead as it handles make install paths and differentiates
1204// between output and source properly.
Paul Duffin9b478b02019-12-10 13:41:51 +00001205func NormalizePathForTesting(path Path) string {
Paul Duffin064b70c2020-11-02 17:32:38 +00001206 if path == nil {
1207 return "<nil path>"
1208 }
Paul Duffin9b478b02019-12-10 13:41:51 +00001209 p := path.String()
1210 if w, ok := path.(WritablePath); ok {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001211 rel, err := filepath.Rel(w.getSoongOutDir(), p)
Paul Duffin9b478b02019-12-10 13:41:51 +00001212 if err != nil {
1213 panic(err)
1214 }
1215 return rel
1216 }
1217 return p
1218}
1219
Paul Duffin567465d2021-03-16 01:21:34 +00001220// NormalizePathsForTesting creates a slice of strings where each string is the result of applying
1221// NormalizePathForTesting to the corresponding Path in the input slice.
1222//
1223// deprecated: use PathsRelativeToTop instead as it handles make install paths and differentiates
1224// between output and source properly.
Paul Duffin9b478b02019-12-10 13:41:51 +00001225func NormalizePathsForTesting(paths Paths) []string {
1226 var result []string
1227 for _, path := range paths {
1228 relative := NormalizePathForTesting(path)
1229 result = append(result, relative)
1230 }
1231 return result
1232}
Paul Duffin567465d2021-03-16 01:21:34 +00001233
1234// PathRelativeToTop returns a string representation of the path relative to a notional top
1235// directory.
1236//
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001237// It return "<nil path>" if the supplied path is nil, otherwise it returns the result of calling
1238// Path.RelativeToTop to obtain a relative Path and then calling Path.String on that to get the
1239// string representation.
Paul Duffin567465d2021-03-16 01:21:34 +00001240func PathRelativeToTop(path Path) string {
1241 if path == nil {
1242 return "<nil path>"
1243 }
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001244 return path.RelativeToTop().String()
Paul Duffin567465d2021-03-16 01:21:34 +00001245}
1246
1247// PathsRelativeToTop creates a slice of strings where each string is the result of applying
1248// PathRelativeToTop to the corresponding Path in the input slice.
1249func PathsRelativeToTop(paths Paths) []string {
1250 var result []string
1251 for _, path := range paths {
1252 relative := PathRelativeToTop(path)
1253 result = append(result, relative)
1254 }
1255 return result
1256}
1257
1258// StringPathRelativeToTop returns a string representation of the path relative to a notional top
1259// directory.
1260//
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001261// See Path.RelativeToTop for more details as to what `relative to top` means.
Paul Duffin567465d2021-03-16 01:21:34 +00001262//
1263// This is provided for processing paths that have already been converted into a string, e.g. paths
1264// in AndroidMkEntries structures. As a result it needs to be supplied the soong output dir against
1265// which it can try and relativize paths. PathRelativeToTop must be used for process Path objects.
1266func StringPathRelativeToTop(soongOutDir string, path string) string {
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001267 ensureTestOnly()
Paul Duffin567465d2021-03-16 01:21:34 +00001268
1269 // A relative path must be a source path so leave it as it is.
1270 if !filepath.IsAbs(path) {
1271 return path
1272 }
1273
1274 // Check to see if the path is relative to the soong out dir.
1275 rel, isRel, err := maybeRelErr(soongOutDir, path)
1276 if err != nil {
1277 panic(err)
1278 }
1279
1280 if isRel {
Colin Cross3b1c6842024-07-26 11:52:57 -07001281 if strings.HasSuffix(soongOutDir, testOutSoongSubDir) {
1282 // The path is in the soong out dir so indicate that in the relative path.
1283 return filepath.Join(TestOutSoongDir, rel)
1284 } else {
1285 // Handle the PathForArbitraryOutput case
1286 return filepath.Join(testOutDir, rel)
1287
1288 }
Paul Duffin567465d2021-03-16 01:21:34 +00001289 }
1290
1291 // Check to see if the path is relative to the top level out dir.
1292 outDir := filepath.Dir(soongOutDir)
1293 rel, isRel, err = maybeRelErr(outDir, path)
1294 if err != nil {
1295 panic(err)
1296 }
1297
1298 if isRel {
1299 // The path is in the out dir so indicate that in the relative path.
1300 return filepath.Join("out", rel)
1301 }
1302
1303 // This should never happen.
1304 panic(fmt.Errorf("internal error: absolute path %s is not relative to the out dir %s", path, outDir))
1305}
1306
1307// StringPathsRelativeToTop creates a slice of strings where each string is the result of applying
1308// StringPathRelativeToTop to the corresponding string path in the input slice.
1309//
1310// This is provided for processing paths that have already been converted into a string, e.g. paths
1311// in AndroidMkEntries structures. As a result it needs to be supplied the soong output dir against
1312// which it can try and relativize paths. PathsRelativeToTop must be used for process Paths objects.
1313func StringPathsRelativeToTop(soongOutDir string, paths []string) []string {
1314 var result []string
1315 for _, path := range paths {
1316 relative := StringPathRelativeToTop(soongOutDir, path)
1317 result = append(result, relative)
1318 }
1319 return result
1320}
Paul Duffinf53555d2021-03-29 00:21:00 +01001321
1322// StringRelativeToTop will normalize a string containing paths, e.g. ninja command, by replacing
1323// any references to the test specific temporary build directory that changes with each run to a
1324// fixed path relative to a notional top directory.
1325//
1326// This is similar to StringPathRelativeToTop except that assumes the string is a single path
1327// containing at most one instance of the temporary build directory at the start of the path while
1328// this assumes that there can be any number at any position.
1329func StringRelativeToTop(config Config, command string) string {
1330 return normalizeStringRelativeToTop(config, command)
1331}
Paul Duffin0aafcbf2021-03-29 00:56:32 +01001332
1333// StringsRelativeToTop will return a new slice such that each item in the new slice is the result
1334// of calling StringRelativeToTop on the corresponding item in the input slice.
1335func StringsRelativeToTop(config Config, command []string) []string {
1336 return normalizeStringArrayRelativeToTop(config, command)
1337}
Yu Liueae7b362023-11-16 17:05:47 -08001338
1339func EnsureListContainsSuffix(t *testing.T, result []string, expected string) {
1340 t.Helper()
1341 if !SuffixInList(result, expected) {
1342 t.Errorf("%q is not found in %v", expected, result)
1343 }
1344}
Cole Fausta963b942024-04-11 17:43:00 -07001345
1346type panickingConfigAndErrorContext struct {
1347 ctx *TestContext
1348}
1349
1350func (ctx *panickingConfigAndErrorContext) OtherModulePropertyErrorf(module Module, property, fmt string, args ...interface{}) {
1351 panic(ctx.ctx.PropertyErrorf(module, property, fmt, args...).Error())
1352}
1353
1354func (ctx *panickingConfigAndErrorContext) Config() Config {
1355 return ctx.ctx.Config()
1356}
1357
Cole Faust4e2bf9f2024-09-11 13:26:20 -07001358func (ctx *panickingConfigAndErrorContext) HasMutatorFinished(mutatorName string) bool {
1359 return ctx.ctx.HasMutatorFinished(mutatorName)
1360}
1361
Cole Faust55b56fe2024-08-23 12:06:11 -07001362func (ctx *panickingConfigAndErrorContext) otherModuleProvider(m blueprint.Module, p blueprint.AnyProviderKey) (any, bool) {
1363 return ctx.ctx.otherModuleProvider(m, p)
1364}
1365
Cole Fauste8a87832024-09-11 11:35:46 -07001366func PanickingConfigAndErrorContext(ctx *TestContext) ConfigurableEvaluatorContext {
Cole Fausta963b942024-04-11 17:43:00 -07001367 return &panickingConfigAndErrorContext{
1368 ctx: ctx,
1369 }
1370}