blob: 401865905dec74d17be20120b53f234e13bb2738 [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
Colin Crossae8600b2020-10-29 17:09:13 -070033func NewTestContext(config Config) *TestContext {
Jeff Gaston088e29e2017-11-29 16:47:17 -080034 namespaceExportFilter := func(namespace *Namespace) bool {
35 return true
36 }
Jeff Gastonb274ed32017-12-01 17:10:33 -080037
38 nameResolver := NewNameResolver(namespaceExportFilter)
39 ctx := &TestContext{
Colin Crossae8600b2020-10-29 17:09:13 -070040 Context: &Context{blueprint.NewContext(), config},
Jeff Gastonb274ed32017-12-01 17:10:33 -080041 NameResolver: nameResolver,
42 }
43
44 ctx.SetNameInterface(nameResolver)
Jeff Gaston088e29e2017-11-29 16:47:17 -080045
Colin Cross1b488422019-03-04 22:33:56 -080046 ctx.postDeps = append(ctx.postDeps, registerPathDepsMutator)
47
Colin Crossae8600b2020-10-29 17:09:13 -070048 ctx.SetFs(ctx.config.fs)
49 if ctx.config.mockBpList != "" {
50 ctx.SetModuleListFile(ctx.config.mockBpList)
51 }
52
Jeff Gaston088e29e2017-11-29 16:47:17 -080053 return ctx
Colin Crosscec81712017-07-13 14:43:27 -070054}
55
Paul Duffina560d5a2021-02-28 01:38:51 +000056var PrepareForTestWithArchMutator = GroupFixturePreparers(
Paul Duffin35816122021-02-24 01:49:52 +000057 // Configure architecture targets in the fixture config.
58 FixtureModifyConfig(modifyTestConfigToSupportArchMutator),
59
60 // Add the arch mutator to the context.
61 FixtureRegisterWithContext(func(ctx RegistrationContext) {
62 ctx.PreDepsMutators(registerArchMutator)
63 }),
64)
65
66var PrepareForTestWithDefaults = FixtureRegisterWithContext(func(ctx RegistrationContext) {
67 ctx.PreArchMutators(RegisterDefaultsPreArchMutators)
68})
69
70var PrepareForTestWithComponentsMutator = FixtureRegisterWithContext(func(ctx RegistrationContext) {
71 ctx.PreArchMutators(RegisterComponentsMutator)
72})
73
74var PrepareForTestWithPrebuilts = FixtureRegisterWithContext(RegisterPrebuiltMutators)
75
76var PrepareForTestWithOverrides = FixtureRegisterWithContext(func(ctx RegistrationContext) {
77 ctx.PostDepsMutators(RegisterOverridePostDepsMutators)
78})
79
Paul Duffine96108d2021-05-06 16:39:27 +010080var PrepareForTestWithLicenses = GroupFixturePreparers(
81 FixtureRegisterWithContext(RegisterLicenseKindBuildComponents),
82 FixtureRegisterWithContext(RegisterLicenseBuildComponents),
83 FixtureRegisterWithContext(registerLicenseMutators),
84)
85
Bob Badour05079212022-05-20 16:41:39 -070086var PrepareForTestWithGenNotice = FixtureRegisterWithContext(RegisterGenNoticeBuildComponents)
87
Paul Duffine96108d2021-05-06 16:39:27 +010088func registerLicenseMutators(ctx RegistrationContext) {
89 ctx.PreArchMutators(RegisterLicensesPackageMapper)
90 ctx.PreArchMutators(RegisterLicensesPropertyGatherer)
91 ctx.PostDepsMutators(RegisterLicensesDependencyChecker)
92}
93
94var PrepareForTestWithLicenseDefaultModules = GroupFixturePreparers(
95 FixtureAddTextFile("build/soong/licenses/Android.bp", `
96 license {
97 name: "Android-Apache-2.0",
98 package_name: "Android",
99 license_kinds: ["SPDX-license-identifier-Apache-2.0"],
100 copyright_notice: "Copyright (C) The Android Open Source Project",
101 license_text: ["LICENSE"],
102 }
103
104 license_kind {
105 name: "SPDX-license-identifier-Apache-2.0",
106 conditions: ["notice"],
107 url: "https://spdx.org/licenses/Apache-2.0.html",
108 }
109
110 license_kind {
111 name: "legacy_unencumbered",
112 conditions: ["unencumbered"],
113 }
114 `),
115 FixtureAddFile("build/soong/licenses/LICENSE", nil),
116)
117
Paul Duffin4fbfb592021-07-09 16:47:38 +0100118var PrepareForTestWithNamespace = FixtureRegisterWithContext(func(ctx RegistrationContext) {
119 registerNamespaceBuildComponents(ctx)
120 ctx.PreArchMutators(RegisterNamespaceMutator)
121})
122
Martin Stjernholm1ebef5b2022-02-10 23:34:28 +0000123var PrepareForTestWithMakevars = FixtureRegisterWithContext(func(ctx RegistrationContext) {
124 ctx.RegisterSingletonType("makevars", makeVarsSingletonFunc)
125})
126
Paul Duffinec3292b2021-03-09 01:01:31 +0000127// Test fixture preparer that will register most java build components.
128//
129// Singletons and mutators should only be added here if they are needed for a majority of java
130// module types, otherwise they should be added under a separate preparer to allow them to be
131// selected only when needed to reduce test execution time.
132//
133// Module types do not have much of an overhead unless they are used so this should include as many
134// module types as possible. The exceptions are those module types that require mutators and/or
135// singletons in order to function in which case they should be kept together in a separate
136// preparer.
137//
138// The mutators in this group were chosen because they are needed by the vast majority of tests.
139var PrepareForTestWithAndroidBuildComponents = GroupFixturePreparers(
Paul Duffin530483c2021-03-07 13:20:38 +0000140 // Sorted alphabetically as the actual order does not matter as tests automatically enforce the
141 // correct order.
Paul Duffin35816122021-02-24 01:49:52 +0000142 PrepareForTestWithArchMutator,
Paul Duffin35816122021-02-24 01:49:52 +0000143 PrepareForTestWithComponentsMutator,
Paul Duffin530483c2021-03-07 13:20:38 +0000144 PrepareForTestWithDefaults,
Paul Duffin35816122021-02-24 01:49:52 +0000145 PrepareForTestWithFilegroup,
Paul Duffin530483c2021-03-07 13:20:38 +0000146 PrepareForTestWithOverrides,
147 PrepareForTestWithPackageModule,
148 PrepareForTestWithPrebuilts,
149 PrepareForTestWithVisibility,
Paul Duffin35816122021-02-24 01:49:52 +0000150)
151
Paul Duffinec3292b2021-03-09 01:01:31 +0000152// Prepares an integration test with all build components from the android package.
153//
154// This should only be used by tests that want to run with as much of the build enabled as possible.
155var PrepareForIntegrationTestWithAndroid = GroupFixturePreparers(
156 PrepareForTestWithAndroidBuildComponents,
157)
158
Paul Duffin25259e92021-03-07 15:45:56 +0000159// Prepares a test that may be missing dependencies by setting allow_missing_dependencies to
160// true.
161var PrepareForTestWithAllowMissingDependencies = GroupFixturePreparers(
162 FixtureModifyProductVariables(func(variables FixtureProductVariables) {
163 variables.Allow_missing_dependencies = proptools.BoolPtr(true)
164 }),
165 FixtureModifyContext(func(ctx *TestContext) {
166 ctx.SetAllowMissingDependencies(true)
167 }),
168)
169
Paul Duffin76e5c8a2021-03-20 14:19:46 +0000170// Prepares a test that disallows non-existent paths.
171var PrepareForTestDisallowNonExistentPaths = FixtureModifyConfig(func(config Config) {
172 config.TestAllowNonExistentPaths = false
173})
174
Colin Crossae8600b2020-10-29 17:09:13 -0700175func NewTestArchContext(config Config) *TestContext {
176 ctx := NewTestContext(config)
Colin Crossae4c6182017-09-15 17:33:55 -0700177 ctx.preDeps = append(ctx.preDeps, registerArchMutator)
178 return ctx
179}
180
Colin Crosscec81712017-07-13 14:43:27 -0700181type TestContext struct {
Colin Cross4c83e5c2019-02-25 14:54:28 -0800182 *Context
Chris Parsons5a34ffb2021-07-21 14:34:58 -0400183 preArch, preDeps, postDeps, finalDeps []RegisterMutatorFunc
184 bp2buildPreArch, bp2buildMutators []RegisterMutatorFunc
185 NameResolver *NameResolver
Paul Duffin281deb22021-03-06 20:29:19 +0000186
Paul Duffind182fb32021-03-07 12:24:44 +0000187 // The list of pre-singletons and singletons registered for the test.
188 preSingletons, singletons sortableComponents
189
Paul Duffin41d77c72021-03-07 12:23:48 +0000190 // The order in which the pre-singletons, mutators and singletons will be run in this test
191 // context; for debugging.
192 preSingletonOrder, mutatorOrder, singletonOrder []string
Colin Crosscec81712017-07-13 14:43:27 -0700193}
194
195func (ctx *TestContext) PreArchMutators(f RegisterMutatorFunc) {
196 ctx.preArch = append(ctx.preArch, f)
197}
198
Paul Duffina80ef842020-01-14 12:09:36 +0000199func (ctx *TestContext) HardCodedPreArchMutators(f RegisterMutatorFunc) {
200 // Register mutator function as normal for testing.
201 ctx.PreArchMutators(f)
202}
203
Colin Crosscec81712017-07-13 14:43:27 -0700204func (ctx *TestContext) PreDepsMutators(f RegisterMutatorFunc) {
205 ctx.preDeps = append(ctx.preDeps, f)
206}
207
208func (ctx *TestContext) PostDepsMutators(f RegisterMutatorFunc) {
209 ctx.postDeps = append(ctx.postDeps, f)
210}
211
Martin Stjernholm710ec3a2020-01-16 15:12:04 +0000212func (ctx *TestContext) FinalDepsMutators(f RegisterMutatorFunc) {
213 ctx.finalDeps = append(ctx.finalDeps, f)
214}
215
Cole Faust324a92e2022-08-23 15:29:05 -0700216func (ctx *TestContext) RegisterBp2BuildConfig(config Bp2BuildConversionAllowlist) {
217 ctx.config.Bp2buildPackageConfig = config
Jingwen Chen12b4c272021-03-10 02:05:59 -0500218}
219
Liz Kammer356f7d42021-01-26 09:18:53 -0500220// PreArchBp2BuildMutators adds mutators to be register for converting Android Blueprint modules
221// into Bazel BUILD targets that should run prior to deps and conversion.
222func (ctx *TestContext) PreArchBp2BuildMutators(f RegisterMutatorFunc) {
223 ctx.bp2buildPreArch = append(ctx.bp2buildPreArch, f)
224}
225
Paul Duffin281deb22021-03-06 20:29:19 +0000226// registeredComponentOrder defines the order in which a sortableComponent type is registered at
227// runtime and provides support for reordering the components registered for a test in the same
228// way.
229type registeredComponentOrder struct {
230 // The name of the component type, used for error messages.
231 componentType string
232
233 // The names of the registered components in the order in which they were registered.
234 namesInOrder []string
235
236 // Maps from the component name to its position in the runtime ordering.
237 namesToIndex map[string]int
238
239 // A function that defines the order between two named components that can be used to sort a slice
240 // of component names into the same order as they appear in namesInOrder.
241 less func(string, string) bool
242}
243
244// registeredComponentOrderFromExistingOrder takes an existing slice of sortableComponents and
245// creates a registeredComponentOrder that contains a less function that can be used to sort a
246// subset of that list of names so it is in the same order as the original sortableComponents.
247func registeredComponentOrderFromExistingOrder(componentType string, existingOrder sortableComponents) registeredComponentOrder {
248 // Only the names from the existing order are needed for this so create a list of component names
249 // in the correct order.
250 namesInOrder := componentsToNames(existingOrder)
251
252 // Populate the map from name to position in the list.
253 nameToIndex := make(map[string]int)
254 for i, n := range namesInOrder {
255 nameToIndex[n] = i
256 }
257
258 // A function to use to map from a name to an index in the original order.
259 indexOf := func(name string) int {
260 index, ok := nameToIndex[name]
261 if !ok {
262 // Should never happen as tests that use components that are not known at runtime do not sort
263 // so should never use this function.
264 panic(fmt.Errorf("internal error: unknown %s %q should be one of %s", componentType, name, strings.Join(namesInOrder, ", ")))
265 }
266 return index
267 }
268
269 // The less function.
270 less := func(n1, n2 string) bool {
271 i1 := indexOf(n1)
272 i2 := indexOf(n2)
273 return i1 < i2
274 }
275
276 return registeredComponentOrder{
277 componentType: componentType,
278 namesInOrder: namesInOrder,
279 namesToIndex: nameToIndex,
280 less: less,
281 }
282}
283
284// componentsToNames maps from the slice of components to a slice of their names.
285func componentsToNames(components sortableComponents) []string {
286 names := make([]string, len(components))
287 for i, c := range components {
288 names[i] = c.componentName()
289 }
290 return names
291}
292
293// enforceOrdering enforces the supplied components are in the same order as is defined in this
294// object.
295//
296// If the supplied components contains any components that are not registered at runtime, i.e. test
297// specific components, then it is impossible to sort them into an order that both matches the
298// runtime and also preserves the implicit ordering defined in the test. In that case it will not
299// sort the components, instead it will just check that the components are in the correct order.
300//
301// Otherwise, this will sort the supplied components in place.
302func (o *registeredComponentOrder) enforceOrdering(components sortableComponents) {
303 // Check to see if the list of components contains any components that are
304 // not registered at runtime.
305 var unknownComponents []string
306 testOrder := componentsToNames(components)
307 for _, name := range testOrder {
308 if _, ok := o.namesToIndex[name]; !ok {
309 unknownComponents = append(unknownComponents, name)
310 break
311 }
312 }
313
314 // If the slice contains some unknown components then it is not possible to
315 // sort them into an order that matches the runtime while also preserving the
316 // order expected from the test, so in that case don't sort just check that
317 // the order of the known mutators does match.
318 if len(unknownComponents) > 0 {
319 // Check order.
320 o.checkTestOrder(testOrder, unknownComponents)
321 } else {
322 // Sort the components.
323 sort.Slice(components, func(i, j int) bool {
324 n1 := components[i].componentName()
325 n2 := components[j].componentName()
326 return o.less(n1, n2)
327 })
328 }
329}
330
331// checkTestOrder checks that the supplied testOrder matches the one defined by this object,
332// panicking if it does not.
333func (o *registeredComponentOrder) checkTestOrder(testOrder []string, unknownComponents []string) {
334 lastMatchingTest := -1
335 matchCount := 0
336 // Take a copy of the runtime order as it is modified during the comparison.
337 runtimeOrder := append([]string(nil), o.namesInOrder...)
338 componentType := o.componentType
339 for i, j := 0, 0; i < len(testOrder) && j < len(runtimeOrder); {
340 test := testOrder[i]
341 runtime := runtimeOrder[j]
342
343 if test == runtime {
344 testOrder[i] = test + fmt.Sprintf(" <-- matched with runtime %s %d", componentType, j)
345 runtimeOrder[j] = runtime + fmt.Sprintf(" <-- matched with test %s %d", componentType, i)
346 lastMatchingTest = i
347 i += 1
348 j += 1
349 matchCount += 1
350 } else if _, ok := o.namesToIndex[test]; !ok {
351 // The test component is not registered globally so assume it is the correct place, treat it
352 // as having matched and skip it.
353 i += 1
354 matchCount += 1
355 } else {
356 // Assume that the test list is in the same order as the runtime list but the runtime list
357 // contains some components that are not present in the tests. So, skip the runtime component
358 // to try and find the next one that matches the current test component.
359 j += 1
360 }
361 }
362
363 // If every item in the test order was either test specific or matched one in the runtime then
364 // it is in the correct order. Otherwise, it was not so fail.
365 if matchCount != len(testOrder) {
366 // The test component names were not all matched with a runtime component name so there must
367 // either be a component present in the test that is not present in the runtime or they must be
368 // in the wrong order.
369 testOrder[lastMatchingTest+1] = testOrder[lastMatchingTest+1] + " <--- unmatched"
370 panic(fmt.Errorf("the tests uses test specific components %q and so cannot be automatically sorted."+
371 " Unfortunately it uses %s components in the wrong order.\n"+
372 "test order:\n %s\n"+
373 "runtime order\n %s\n",
374 SortedUniqueStrings(unknownComponents),
375 componentType,
376 strings.Join(testOrder, "\n "),
377 strings.Join(runtimeOrder, "\n ")))
378 }
379}
380
381// registrationSorter encapsulates the information needed to ensure that the test mutators are
382// registered, and thereby executed, in the same order as they are at runtime.
383//
384// It MUST be populated lazily AFTER all package initialization has been done otherwise it will
385// only define the order for a subset of all the registered build components that are available for
386// the packages being tested.
387//
388// e.g if this is initialized during say the cc package initialization then any tests run in the
389// java package will not sort build components registered by the java package's init() functions.
390type registrationSorter struct {
391 // Used to ensure that this is only created once.
392 once sync.Once
393
Paul Duffin41d77c72021-03-07 12:23:48 +0000394 // The order of pre-singletons
395 preSingletonOrder registeredComponentOrder
396
Paul Duffin281deb22021-03-06 20:29:19 +0000397 // The order of mutators
398 mutatorOrder registeredComponentOrder
Paul Duffin41d77c72021-03-07 12:23:48 +0000399
400 // The order of singletons
401 singletonOrder registeredComponentOrder
Paul Duffin281deb22021-03-06 20:29:19 +0000402}
403
404// populate initializes this structure from globally registered build components.
405//
406// Only the first call has any effect.
407func (s *registrationSorter) populate() {
408 s.once.Do(func() {
Paul Duffin41d77c72021-03-07 12:23:48 +0000409 // Create an ordering from the globally registered pre-singletons.
410 s.preSingletonOrder = registeredComponentOrderFromExistingOrder("pre-singleton", preSingletons)
411
Paul Duffin281deb22021-03-06 20:29:19 +0000412 // Created an ordering from the globally registered mutators.
413 globallyRegisteredMutators := collateGloballyRegisteredMutators()
414 s.mutatorOrder = registeredComponentOrderFromExistingOrder("mutator", globallyRegisteredMutators)
Paul Duffin41d77c72021-03-07 12:23:48 +0000415
416 // Create an ordering from the globally registered singletons.
417 globallyRegisteredSingletons := collateGloballyRegisteredSingletons()
418 s.singletonOrder = registeredComponentOrderFromExistingOrder("singleton", globallyRegisteredSingletons)
Paul Duffin281deb22021-03-06 20:29:19 +0000419 })
420}
421
422// Provides support for enforcing the same order in which build components are registered globally
423// to the order in which they are registered during tests.
424//
425// MUST only be accessed via the globallyRegisteredComponentsOrder func.
426var globalRegistrationSorter registrationSorter
427
428// globallyRegisteredComponentsOrder returns the globalRegistrationSorter after ensuring it is
429// correctly populated.
430func globallyRegisteredComponentsOrder() *registrationSorter {
431 globalRegistrationSorter.populate()
432 return &globalRegistrationSorter
433}
434
Colin Crossae8600b2020-10-29 17:09:13 -0700435func (ctx *TestContext) Register() {
Paul Duffin281deb22021-03-06 20:29:19 +0000436 globalOrder := globallyRegisteredComponentsOrder()
437
Paul Duffin41d77c72021-03-07 12:23:48 +0000438 // Ensure that the pre-singletons used in the test are in the same order as they are used at
439 // runtime.
440 globalOrder.preSingletonOrder.enforceOrdering(ctx.preSingletons)
Paul Duffind182fb32021-03-07 12:24:44 +0000441 ctx.preSingletons.registerAll(ctx.Context)
442
Paul Duffinc05b0342021-03-06 13:28:13 +0000443 mutators := collateRegisteredMutators(ctx.preArch, ctx.preDeps, ctx.postDeps, ctx.finalDeps)
Paul Duffin281deb22021-03-06 20:29:19 +0000444 // Ensure that the mutators used in the test are in the same order as they are used at runtime.
445 globalOrder.mutatorOrder.enforceOrdering(mutators)
Paul Duffinc05b0342021-03-06 13:28:13 +0000446 mutators.registerAll(ctx.Context)
Colin Crosscec81712017-07-13 14:43:27 -0700447
Paul Duffin41d77c72021-03-07 12:23:48 +0000448 // Ensure that the singletons used in the test are in the same order as they are used at runtime.
449 globalOrder.singletonOrder.enforceOrdering(ctx.singletons)
Paul Duffind182fb32021-03-07 12:24:44 +0000450 ctx.singletons.registerAll(ctx.Context)
451
Paul Duffin41d77c72021-03-07 12:23:48 +0000452 // Save the sorted components order away to make them easy to access while debugging.
Paul Duffinf5de6682021-03-08 23:42:10 +0000453 ctx.preSingletonOrder = componentsToNames(preSingletons)
454 ctx.mutatorOrder = componentsToNames(mutators)
455 ctx.singletonOrder = componentsToNames(singletons)
Colin Cross31a738b2019-12-30 18:45:15 -0800456}
457
Jingwen Chen73850672020-12-14 08:25:34 -0500458// RegisterForBazelConversion prepares a test context for bp2build conversion.
459func (ctx *TestContext) RegisterForBazelConversion() {
Chris Parsonsad876012022-08-20 14:48:32 -0400460 ctx.config.BuildMode = Bp2build
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400461 RegisterMutatorsForBazelConversion(ctx.Context, ctx.bp2buildPreArch)
Jingwen Chen73850672020-12-14 08:25:34 -0500462}
463
Spandan Das5af0bd32022-09-28 20:43:08 +0000464// RegisterForApiBazelConversion prepares a test context for API bp2build conversion.
465func (ctx *TestContext) RegisterForApiBazelConversion() {
466 ctx.config.BuildMode = ApiBp2build
467 RegisterMutatorsForApiBazelConversion(ctx.Context, ctx.bp2buildPreArch)
468}
469
Colin Cross31a738b2019-12-30 18:45:15 -0800470func (ctx *TestContext) ParseFileList(rootDir string, filePaths []string) (deps []string, errs []error) {
471 // This function adapts the old style ParseFileList calls that are spread throughout the tests
472 // to the new style that takes a config.
473 return ctx.Context.ParseFileList(rootDir, filePaths, ctx.config)
474}
475
476func (ctx *TestContext) ParseBlueprintsFiles(rootDir string) (deps []string, errs []error) {
477 // This function adapts the old style ParseBlueprintsFiles calls that are spread throughout the
478 // tests to the new style that takes a config.
479 return ctx.Context.ParseBlueprintsFiles(rootDir, ctx.config)
Colin Cross4b49b762019-11-22 15:25:03 -0800480}
481
482func (ctx *TestContext) RegisterModuleType(name string, factory ModuleFactory) {
483 ctx.Context.RegisterModuleType(name, ModuleFactoryAdaptor(factory))
484}
485
Colin Cross9aed5bc2020-12-28 15:15:34 -0800486func (ctx *TestContext) RegisterSingletonModuleType(name string, factory SingletonModuleFactory) {
487 s, m := SingletonModuleFactoryAdaptor(name, factory)
488 ctx.RegisterSingletonType(name, s)
489 ctx.RegisterModuleType(name, m)
490}
491
Colin Cross4b49b762019-11-22 15:25:03 -0800492func (ctx *TestContext) RegisterSingletonType(name string, factory SingletonFactory) {
Paul Duffind182fb32021-03-07 12:24:44 +0000493 ctx.singletons = append(ctx.singletons, newSingleton(name, factory))
Colin Crosscec81712017-07-13 14:43:27 -0700494}
495
Paul Duffineafc16b2021-02-24 01:43:18 +0000496func (ctx *TestContext) RegisterPreSingletonType(name string, factory SingletonFactory) {
Paul Duffind182fb32021-03-07 12:24:44 +0000497 ctx.preSingletons = append(ctx.preSingletons, newPreSingleton(name, factory))
Paul Duffineafc16b2021-02-24 01:43:18 +0000498}
499
Martin Stjernholm14cdd712021-09-10 22:39:59 +0100500// ModuleVariantForTests selects a specific variant of the module with the given
501// name by matching the variations map against the variations of each module
502// variant. A module variant matches the map if every variation that exists in
503// both have the same value. Both the module and the map are allowed to have
504// extra variations that the other doesn't have. Panics if not exactly one
505// module variant matches.
506func (ctx *TestContext) ModuleVariantForTests(name string, matchVariations map[string]string) TestingModule {
507 modules := []Module{}
508 ctx.VisitAllModules(func(m blueprint.Module) {
509 if ctx.ModuleName(m) == name {
510 am := m.(Module)
511 amMut := am.base().commonProperties.DebugMutators
512 amVar := am.base().commonProperties.DebugVariations
513 matched := true
514 for i, mut := range amMut {
515 if wantedVar, found := matchVariations[mut]; found && amVar[i] != wantedVar {
516 matched = false
517 break
518 }
519 }
520 if matched {
521 modules = append(modules, am)
522 }
523 }
524 })
525
526 if len(modules) == 0 {
527 // Show all the modules or module variants that do exist.
528 var allModuleNames []string
529 var allVariants []string
530 ctx.VisitAllModules(func(m blueprint.Module) {
531 allModuleNames = append(allModuleNames, ctx.ModuleName(m))
532 if ctx.ModuleName(m) == name {
533 allVariants = append(allVariants, m.(Module).String())
534 }
535 })
536
537 if len(allVariants) == 0 {
538 panic(fmt.Errorf("failed to find module %q. All modules:\n %s",
539 name, strings.Join(SortedUniqueStrings(allModuleNames), "\n ")))
540 } else {
541 sort.Strings(allVariants)
542 panic(fmt.Errorf("failed to find module %q matching %v. All variants:\n %s",
543 name, matchVariations, strings.Join(allVariants, "\n ")))
544 }
545 }
546
547 if len(modules) > 1 {
548 moduleStrings := []string{}
549 for _, m := range modules {
550 moduleStrings = append(moduleStrings, m.String())
551 }
552 sort.Strings(moduleStrings)
553 panic(fmt.Errorf("module %q has more than one variant that match %v:\n %s",
554 name, matchVariations, strings.Join(moduleStrings, "\n ")))
555 }
556
557 return newTestingModule(ctx.config, modules[0])
558}
559
Colin Crosscec81712017-07-13 14:43:27 -0700560func (ctx *TestContext) ModuleForTests(name, variant string) TestingModule {
561 var module Module
562 ctx.VisitAllModules(func(m blueprint.Module) {
563 if ctx.ModuleName(m) == name && ctx.ModuleSubDir(m) == variant {
564 module = m.(Module)
565 }
566 })
567
568 if module == nil {
Jeff Gaston294356f2017-09-27 17:05:30 -0700569 // find all the modules that do exist
Colin Crossbeae6ec2020-08-11 12:02:11 -0700570 var allModuleNames []string
571 var allVariants []string
Jeff Gaston294356f2017-09-27 17:05:30 -0700572 ctx.VisitAllModules(func(m blueprint.Module) {
Colin Crossbeae6ec2020-08-11 12:02:11 -0700573 allModuleNames = append(allModuleNames, ctx.ModuleName(m))
574 if ctx.ModuleName(m) == name {
575 allVariants = append(allVariants, ctx.ModuleSubDir(m))
576 }
Jeff Gaston294356f2017-09-27 17:05:30 -0700577 })
Colin Crossbeae6ec2020-08-11 12:02:11 -0700578 sort.Strings(allVariants)
Jeff Gaston294356f2017-09-27 17:05:30 -0700579
Colin Crossbeae6ec2020-08-11 12:02:11 -0700580 if len(allVariants) == 0 {
581 panic(fmt.Errorf("failed to find module %q. All modules:\n %s",
Martin Stjernholm98e0d882021-09-09 21:34:02 +0100582 name, strings.Join(SortedUniqueStrings(allModuleNames), "\n ")))
Colin Crossbeae6ec2020-08-11 12:02:11 -0700583 } else {
584 panic(fmt.Errorf("failed to find module %q variant %q. All variants:\n %s",
585 name, variant, strings.Join(allVariants, "\n ")))
586 }
Colin Crosscec81712017-07-13 14:43:27 -0700587 }
588
Paul Duffin709e0e32021-03-22 10:09:02 +0000589 return newTestingModule(ctx.config, module)
Colin Crosscec81712017-07-13 14:43:27 -0700590}
591
Jiyong Park37b25202018-07-11 10:49:27 +0900592func (ctx *TestContext) ModuleVariantsForTests(name string) []string {
593 var variants []string
594 ctx.VisitAllModules(func(m blueprint.Module) {
595 if ctx.ModuleName(m) == name {
596 variants = append(variants, ctx.ModuleSubDir(m))
597 }
598 })
599 return variants
600}
601
Colin Cross4c83e5c2019-02-25 14:54:28 -0800602// SingletonForTests returns a TestingSingleton for the singleton registered with the given name.
603func (ctx *TestContext) SingletonForTests(name string) TestingSingleton {
604 allSingletonNames := []string{}
605 for _, s := range ctx.Singletons() {
606 n := ctx.SingletonName(s)
607 if n == name {
608 return TestingSingleton{
Paul Duffin709e0e32021-03-22 10:09:02 +0000609 baseTestingComponent: newBaseTestingComponent(ctx.config, s.(testBuildProvider)),
Paul Duffin31a22882021-03-22 09:29:00 +0000610 singleton: s.(*singletonAdaptor).Singleton,
Colin Cross4c83e5c2019-02-25 14:54:28 -0800611 }
612 }
613 allSingletonNames = append(allSingletonNames, n)
614 }
615
616 panic(fmt.Errorf("failed to find singleton %q."+
617 "\nall singletons: %v", name, allSingletonNames))
618}
619
Martin Stjernholm1ebef5b2022-02-10 23:34:28 +0000620type InstallMakeRule struct {
621 Target string
622 Deps []string
623 OrderOnlyDeps []string
624}
625
626func parseMkRules(t *testing.T, config Config, nodes []mkparser.Node) []InstallMakeRule {
627 var rules []InstallMakeRule
628 for _, node := range nodes {
629 if mkParserRule, ok := node.(*mkparser.Rule); ok {
630 var rule InstallMakeRule
631
632 if targets := mkParserRule.Target.Words(); len(targets) == 0 {
633 t.Fatalf("no targets for rule %s", mkParserRule.Dump())
634 } else if len(targets) > 1 {
635 t.Fatalf("unsupported multiple targets for rule %s", mkParserRule.Dump())
636 } else if !targets[0].Const() {
637 t.Fatalf("unsupported non-const target for rule %s", mkParserRule.Dump())
638 } else {
639 rule.Target = normalizeStringRelativeToTop(config, targets[0].Value(nil))
640 }
641
642 prereqList := &rule.Deps
643 for _, prereq := range mkParserRule.Prerequisites.Words() {
644 if !prereq.Const() {
645 t.Fatalf("unsupported non-const prerequisite for rule %s", mkParserRule.Dump())
646 }
647
648 if prereq.Value(nil) == "|" {
649 prereqList = &rule.OrderOnlyDeps
650 continue
651 }
652
653 *prereqList = append(*prereqList, normalizeStringRelativeToTop(config, prereq.Value(nil)))
654 }
655
656 rules = append(rules, rule)
657 }
658 }
659
660 return rules
661}
662
663func (ctx *TestContext) InstallMakeRulesForTesting(t *testing.T) []InstallMakeRule {
664 installs := ctx.SingletonForTests("makevars").Singleton().(*makeVarsSingleton).installsForTesting
665 buf := bytes.NewBuffer(append([]byte(nil), installs...))
666 parser := mkparser.NewParser("makevars", buf)
667
668 nodes, errs := parser.Parse()
669 if len(errs) > 0 {
670 t.Fatalf("error parsing install rules: %s", errs[0])
671 }
672
673 return parseMkRules(t, ctx.config, nodes)
674}
675
Colin Crossaa255532020-07-03 13:18:24 -0700676func (ctx *TestContext) Config() Config {
677 return ctx.config
678}
679
Colin Cross4c83e5c2019-02-25 14:54:28 -0800680type testBuildProvider interface {
681 BuildParamsForTests() []BuildParams
682 RuleParamsForTests() map[blueprint.Rule]blueprint.RuleParams
683}
684
685type TestingBuildParams struct {
686 BuildParams
687 RuleParams blueprint.RuleParams
Paul Duffin709e0e32021-03-22 10:09:02 +0000688
689 config Config
690}
691
692// RelativeToTop creates a new instance of this which has had any usages of the current test's
693// temporary and test specific build directory replaced with a path relative to the notional top.
694//
695// The parts of this structure which are changed are:
696// * BuildParams
Colin Crossd079e0b2022-08-16 10:27:33 -0700697// - Args
698// - All Path, Paths, WritablePath and WritablePaths fields.
Paul Duffin709e0e32021-03-22 10:09:02 +0000699//
700// * RuleParams
Colin Crossd079e0b2022-08-16 10:27:33 -0700701// - Command
702// - Depfile
703// - Rspfile
704// - RspfileContent
705// - SymlinkOutputs
706// - CommandDeps
707// - CommandOrderOnly
Paul Duffin709e0e32021-03-22 10:09:02 +0000708//
709// See PathRelativeToTop for more details.
Paul Duffina71a67a2021-03-29 00:42:57 +0100710//
711// deprecated: this is no longer needed as TestingBuildParams are created in this form.
Paul Duffin709e0e32021-03-22 10:09:02 +0000712func (p TestingBuildParams) RelativeToTop() TestingBuildParams {
713 // If this is not a valid params then just return it back. That will make it easy to use with the
714 // Maybe...() methods.
715 if p.Rule == nil {
716 return p
717 }
718 if p.config.config == nil {
Paul Duffine8366da2021-03-24 10:40:38 +0000719 return p
Paul Duffin709e0e32021-03-22 10:09:02 +0000720 }
721 // Take a copy of the build params and replace any args that contains test specific temporary
722 // paths with paths relative to the top.
723 bparams := p.BuildParams
Paul Duffinbbb0f8f2021-03-24 10:34:52 +0000724 bparams.Depfile = normalizeWritablePathRelativeToTop(bparams.Depfile)
725 bparams.Output = normalizeWritablePathRelativeToTop(bparams.Output)
726 bparams.Outputs = bparams.Outputs.RelativeToTop()
727 bparams.SymlinkOutput = normalizeWritablePathRelativeToTop(bparams.SymlinkOutput)
728 bparams.SymlinkOutputs = bparams.SymlinkOutputs.RelativeToTop()
729 bparams.ImplicitOutput = normalizeWritablePathRelativeToTop(bparams.ImplicitOutput)
730 bparams.ImplicitOutputs = bparams.ImplicitOutputs.RelativeToTop()
731 bparams.Input = normalizePathRelativeToTop(bparams.Input)
732 bparams.Inputs = bparams.Inputs.RelativeToTop()
733 bparams.Implicit = normalizePathRelativeToTop(bparams.Implicit)
734 bparams.Implicits = bparams.Implicits.RelativeToTop()
735 bparams.OrderOnly = bparams.OrderOnly.RelativeToTop()
736 bparams.Validation = normalizePathRelativeToTop(bparams.Validation)
737 bparams.Validations = bparams.Validations.RelativeToTop()
Paul Duffin709e0e32021-03-22 10:09:02 +0000738 bparams.Args = normalizeStringMapRelativeToTop(p.config, bparams.Args)
739
740 // Ditto for any fields in the RuleParams.
741 rparams := p.RuleParams
742 rparams.Command = normalizeStringRelativeToTop(p.config, rparams.Command)
743 rparams.Depfile = normalizeStringRelativeToTop(p.config, rparams.Depfile)
744 rparams.Rspfile = normalizeStringRelativeToTop(p.config, rparams.Rspfile)
745 rparams.RspfileContent = normalizeStringRelativeToTop(p.config, rparams.RspfileContent)
746 rparams.SymlinkOutputs = normalizeStringArrayRelativeToTop(p.config, rparams.SymlinkOutputs)
747 rparams.CommandDeps = normalizeStringArrayRelativeToTop(p.config, rparams.CommandDeps)
748 rparams.CommandOrderOnly = normalizeStringArrayRelativeToTop(p.config, rparams.CommandOrderOnly)
749
750 return TestingBuildParams{
751 BuildParams: bparams,
752 RuleParams: rparams,
753 }
Colin Cross4c83e5c2019-02-25 14:54:28 -0800754}
755
Paul Duffinbbb0f8f2021-03-24 10:34:52 +0000756func normalizeWritablePathRelativeToTop(path WritablePath) WritablePath {
757 if path == nil {
758 return nil
759 }
760 return path.RelativeToTop().(WritablePath)
761}
762
763func normalizePathRelativeToTop(path Path) Path {
764 if path == nil {
765 return nil
766 }
767 return path.RelativeToTop()
768}
769
Paul Duffin0eda26b92021-03-22 09:34:29 +0000770// baseTestingComponent provides functionality common to both TestingModule and TestingSingleton.
771type baseTestingComponent struct {
Paul Duffin709e0e32021-03-22 10:09:02 +0000772 config Config
Paul Duffin0eda26b92021-03-22 09:34:29 +0000773 provider testBuildProvider
774}
775
Paul Duffin709e0e32021-03-22 10:09:02 +0000776func newBaseTestingComponent(config Config, provider testBuildProvider) baseTestingComponent {
777 return baseTestingComponent{config, provider}
778}
779
780// A function that will normalize a string containing paths, e.g. ninja command, by replacing
781// any references to the test specific temporary build directory that changes with each run to a
782// fixed path relative to a notional top directory.
783//
784// This is similar to StringPathRelativeToTop except that assumes the string is a single path
785// containing at most one instance of the temporary build directory at the start of the path while
786// this assumes that there can be any number at any position.
787func normalizeStringRelativeToTop(config Config, s string) string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200788 // The soongOutDir usually looks something like: /tmp/testFoo2345/001
Paul Duffin709e0e32021-03-22 10:09:02 +0000789 //
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200790 // Replace any usage of the soongOutDir with out/soong, e.g. replace "/tmp/testFoo2345/001" with
Paul Duffin709e0e32021-03-22 10:09:02 +0000791 // "out/soong".
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200792 outSoongDir := filepath.Clean(config.soongOutDir)
Paul Duffin709e0e32021-03-22 10:09:02 +0000793 re := regexp.MustCompile(`\Q` + outSoongDir + `\E\b`)
794 s = re.ReplaceAllString(s, "out/soong")
795
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200796 // Replace any usage of the soongOutDir/.. with out, e.g. replace "/tmp/testFoo2345" with
Paul Duffin709e0e32021-03-22 10:09:02 +0000797 // "out". This must come after the previous replacement otherwise this would replace
798 // "/tmp/testFoo2345/001" with "out/001" instead of "out/soong".
799 outDir := filepath.Dir(outSoongDir)
800 re = regexp.MustCompile(`\Q` + outDir + `\E\b`)
801 s = re.ReplaceAllString(s, "out")
802
803 return s
804}
805
806// normalizeStringArrayRelativeToTop creates a new slice constructed by applying
807// normalizeStringRelativeToTop to each item in the slice.
808func normalizeStringArrayRelativeToTop(config Config, slice []string) []string {
809 newSlice := make([]string, len(slice))
810 for i, s := range slice {
811 newSlice[i] = normalizeStringRelativeToTop(config, s)
812 }
813 return newSlice
814}
815
816// normalizeStringMapRelativeToTop creates a new map constructed by applying
817// normalizeStringRelativeToTop to each value in the map.
818func normalizeStringMapRelativeToTop(config Config, m map[string]string) map[string]string {
819 newMap := map[string]string{}
820 for k, v := range m {
821 newMap[k] = normalizeStringRelativeToTop(config, v)
822 }
823 return newMap
Paul Duffin0eda26b92021-03-22 09:34:29 +0000824}
825
826func (b baseTestingComponent) newTestingBuildParams(bparams BuildParams) TestingBuildParams {
Colin Cross4c83e5c2019-02-25 14:54:28 -0800827 return TestingBuildParams{
Paul Duffin709e0e32021-03-22 10:09:02 +0000828 config: b.config,
Colin Cross4c83e5c2019-02-25 14:54:28 -0800829 BuildParams: bparams,
Paul Duffin0eda26b92021-03-22 09:34:29 +0000830 RuleParams: b.provider.RuleParamsForTests()[bparams.Rule],
Paul Duffine8366da2021-03-24 10:40:38 +0000831 }.RelativeToTop()
Colin Cross4c83e5c2019-02-25 14:54:28 -0800832}
833
Paul Duffin0eda26b92021-03-22 09:34:29 +0000834func (b baseTestingComponent) maybeBuildParamsFromRule(rule string) (TestingBuildParams, []string) {
Thiébaud Weksteen3600b802020-08-27 15:50:24 +0200835 var searchedRules []string
Paul Duffin4dbf6cf2021-06-08 10:06:37 +0100836 buildParams := b.provider.BuildParamsForTests()
837 for _, p := range buildParams {
838 ruleAsString := p.Rule.String()
839 searchedRules = append(searchedRules, ruleAsString)
840 if strings.Contains(ruleAsString, rule) {
Paul Duffin0eda26b92021-03-22 09:34:29 +0000841 return b.newTestingBuildParams(p), searchedRules
Colin Cross4c83e5c2019-02-25 14:54:28 -0800842 }
843 }
Thiébaud Weksteen3600b802020-08-27 15:50:24 +0200844 return TestingBuildParams{}, searchedRules
Colin Cross4c83e5c2019-02-25 14:54:28 -0800845}
846
Paul Duffin0eda26b92021-03-22 09:34:29 +0000847func (b baseTestingComponent) buildParamsFromRule(rule string) TestingBuildParams {
848 p, searchRules := b.maybeBuildParamsFromRule(rule)
Colin Cross4c83e5c2019-02-25 14:54:28 -0800849 if p.Rule == nil {
Paul Duffin4dbf6cf2021-06-08 10:06:37 +0100850 panic(fmt.Errorf("couldn't find rule %q.\nall rules:\n%s", rule, strings.Join(searchRules, "\n")))
Colin Cross4c83e5c2019-02-25 14:54:28 -0800851 }
852 return p
853}
854
Martin Stjernholm827ba622022-02-03 00:20:11 +0000855func (b baseTestingComponent) maybeBuildParamsFromDescription(desc string) (TestingBuildParams, []string) {
856 var searchedDescriptions []string
Paul Duffin0eda26b92021-03-22 09:34:29 +0000857 for _, p := range b.provider.BuildParamsForTests() {
Martin Stjernholm827ba622022-02-03 00:20:11 +0000858 searchedDescriptions = append(searchedDescriptions, p.Description)
Colin Crossb88b3c52019-06-10 15:15:17 -0700859 if strings.Contains(p.Description, desc) {
Martin Stjernholm827ba622022-02-03 00:20:11 +0000860 return b.newTestingBuildParams(p), searchedDescriptions
Colin Cross4c83e5c2019-02-25 14:54:28 -0800861 }
862 }
Martin Stjernholm827ba622022-02-03 00:20:11 +0000863 return TestingBuildParams{}, searchedDescriptions
Colin Cross4c83e5c2019-02-25 14:54:28 -0800864}
865
Paul Duffin0eda26b92021-03-22 09:34:29 +0000866func (b baseTestingComponent) buildParamsFromDescription(desc string) TestingBuildParams {
Martin Stjernholm827ba622022-02-03 00:20:11 +0000867 p, searchedDescriptions := b.maybeBuildParamsFromDescription(desc)
Colin Cross4c83e5c2019-02-25 14:54:28 -0800868 if p.Rule == nil {
Martin Stjernholm827ba622022-02-03 00:20:11 +0000869 panic(fmt.Errorf("couldn't find description %q\nall descriptions:\n%s", desc, strings.Join(searchedDescriptions, "\n")))
Colin Cross4c83e5c2019-02-25 14:54:28 -0800870 }
871 return p
872}
873
Paul Duffin0eda26b92021-03-22 09:34:29 +0000874func (b baseTestingComponent) maybeBuildParamsFromOutput(file string) (TestingBuildParams, []string) {
Martin Stjernholma4aaa472021-09-17 02:51:48 +0100875 searchedOutputs := WritablePaths(nil)
Paul Duffin0eda26b92021-03-22 09:34:29 +0000876 for _, p := range b.provider.BuildParamsForTests() {
Colin Cross4c83e5c2019-02-25 14:54:28 -0800877 outputs := append(WritablePaths(nil), p.Outputs...)
Colin Cross1d2cf042019-03-29 15:33:06 -0700878 outputs = append(outputs, p.ImplicitOutputs...)
Colin Cross4c83e5c2019-02-25 14:54:28 -0800879 if p.Output != nil {
880 outputs = append(outputs, p.Output)
881 }
882 for _, f := range outputs {
Paul Duffin4e6e35c2021-03-22 11:34:57 +0000883 if f.String() == file || f.Rel() == file || PathRelativeToTop(f) == file {
Paul Duffin0eda26b92021-03-22 09:34:29 +0000884 return b.newTestingBuildParams(p), nil
Colin Cross4c83e5c2019-02-25 14:54:28 -0800885 }
Martin Stjernholma4aaa472021-09-17 02:51:48 +0100886 searchedOutputs = append(searchedOutputs, f)
Colin Cross4c83e5c2019-02-25 14:54:28 -0800887 }
888 }
Martin Stjernholma4aaa472021-09-17 02:51:48 +0100889
890 formattedOutputs := []string{}
891 for _, f := range searchedOutputs {
892 formattedOutputs = append(formattedOutputs,
893 fmt.Sprintf("%s (rel=%s)", PathRelativeToTop(f), f.Rel()))
894 }
895
896 return TestingBuildParams{}, formattedOutputs
Colin Cross4c83e5c2019-02-25 14:54:28 -0800897}
898
Paul Duffin0eda26b92021-03-22 09:34:29 +0000899func (b baseTestingComponent) buildParamsFromOutput(file string) TestingBuildParams {
900 p, searchedOutputs := b.maybeBuildParamsFromOutput(file)
Colin Cross4c83e5c2019-02-25 14:54:28 -0800901 if p.Rule == nil {
Paul Duffin4e6e35c2021-03-22 11:34:57 +0000902 panic(fmt.Errorf("couldn't find output %q.\nall outputs:\n %s\n",
903 file, strings.Join(searchedOutputs, "\n ")))
Colin Cross4c83e5c2019-02-25 14:54:28 -0800904 }
905 return p
906}
907
Paul Duffin0eda26b92021-03-22 09:34:29 +0000908func (b baseTestingComponent) allOutputs() []string {
Colin Cross4c83e5c2019-02-25 14:54:28 -0800909 var outputFullPaths []string
Paul Duffin0eda26b92021-03-22 09:34:29 +0000910 for _, p := range b.provider.BuildParamsForTests() {
Colin Cross4c83e5c2019-02-25 14:54:28 -0800911 outputs := append(WritablePaths(nil), p.Outputs...)
Colin Cross1d2cf042019-03-29 15:33:06 -0700912 outputs = append(outputs, p.ImplicitOutputs...)
Colin Cross4c83e5c2019-02-25 14:54:28 -0800913 if p.Output != nil {
914 outputs = append(outputs, p.Output)
915 }
916 outputFullPaths = append(outputFullPaths, outputs.Strings()...)
917 }
918 return outputFullPaths
919}
920
Paul Duffin31a22882021-03-22 09:29:00 +0000921// MaybeRule finds a call to ctx.Build with BuildParams.Rule set to a rule with the given name. Returns an empty
922// BuildParams if no rule is found.
923func (b baseTestingComponent) MaybeRule(rule string) TestingBuildParams {
Paul Duffin0eda26b92021-03-22 09:34:29 +0000924 r, _ := b.maybeBuildParamsFromRule(rule)
Paul Duffin31a22882021-03-22 09:29:00 +0000925 return r
926}
927
928// Rule finds a call to ctx.Build with BuildParams.Rule set to a rule with the given name. Panics if no rule is found.
929func (b baseTestingComponent) Rule(rule string) TestingBuildParams {
Paul Duffin0eda26b92021-03-22 09:34:29 +0000930 return b.buildParamsFromRule(rule)
Paul Duffin31a22882021-03-22 09:29:00 +0000931}
932
933// MaybeDescription finds a call to ctx.Build with BuildParams.Description set to a the given string. Returns an empty
934// BuildParams if no rule is found.
935func (b baseTestingComponent) MaybeDescription(desc string) TestingBuildParams {
Martin Stjernholm827ba622022-02-03 00:20:11 +0000936 p, _ := b.maybeBuildParamsFromDescription(desc)
937 return p
Paul Duffin31a22882021-03-22 09:29:00 +0000938}
939
940// Description finds a call to ctx.Build with BuildParams.Description set to a the given string. Panics if no rule is
941// found.
942func (b baseTestingComponent) Description(desc string) TestingBuildParams {
Paul Duffin0eda26b92021-03-22 09:34:29 +0000943 return b.buildParamsFromDescription(desc)
Paul Duffin31a22882021-03-22 09:29:00 +0000944}
945
946// MaybeOutput finds a call to ctx.Build with a BuildParams.Output or BuildParams.Outputs whose String() or Rel()
947// value matches the provided string. Returns an empty BuildParams if no rule is found.
948func (b baseTestingComponent) MaybeOutput(file string) TestingBuildParams {
Paul Duffin0eda26b92021-03-22 09:34:29 +0000949 p, _ := b.maybeBuildParamsFromOutput(file)
Paul Duffin31a22882021-03-22 09:29:00 +0000950 return p
951}
952
953// Output finds a call to ctx.Build with a BuildParams.Output or BuildParams.Outputs whose String() or Rel()
954// value matches the provided string. Panics if no rule is found.
955func (b baseTestingComponent) Output(file string) TestingBuildParams {
Paul Duffin0eda26b92021-03-22 09:34:29 +0000956 return b.buildParamsFromOutput(file)
Paul Duffin31a22882021-03-22 09:29:00 +0000957}
958
959// AllOutputs returns all 'BuildParams.Output's and 'BuildParams.Outputs's in their full path string forms.
960func (b baseTestingComponent) AllOutputs() []string {
Paul Duffin0eda26b92021-03-22 09:34:29 +0000961 return b.allOutputs()
Paul Duffin31a22882021-03-22 09:29:00 +0000962}
963
Colin Crossb77ffc42019-01-05 22:09:19 -0800964// TestingModule is wrapper around an android.Module that provides methods to find information about individual
965// ctx.Build parameters for verification in tests.
Colin Crosscec81712017-07-13 14:43:27 -0700966type TestingModule struct {
Paul Duffin31a22882021-03-22 09:29:00 +0000967 baseTestingComponent
Colin Crosscec81712017-07-13 14:43:27 -0700968 module Module
969}
970
Paul Duffin709e0e32021-03-22 10:09:02 +0000971func newTestingModule(config Config, module Module) TestingModule {
Paul Duffin31a22882021-03-22 09:29:00 +0000972 return TestingModule{
Paul Duffin709e0e32021-03-22 10:09:02 +0000973 newBaseTestingComponent(config, module),
Paul Duffin31a22882021-03-22 09:29:00 +0000974 module,
975 }
976}
977
Colin Crossb77ffc42019-01-05 22:09:19 -0800978// Module returns the Module wrapped by the TestingModule.
Colin Crosscec81712017-07-13 14:43:27 -0700979func (m TestingModule) Module() Module {
980 return m.module
981}
982
Paul Duffin97d8b402021-03-22 16:04:50 +0000983// VariablesForTestsRelativeToTop returns a copy of the Module.VariablesForTests() with every value
984// having any temporary build dir usages replaced with paths relative to a notional top.
985func (m TestingModule) VariablesForTestsRelativeToTop() map[string]string {
986 return normalizeStringMapRelativeToTop(m.config, m.module.VariablesForTests())
987}
988
Paul Duffin962783a2021-03-29 00:00:17 +0100989// OutputFiles calls OutputFileProducer.OutputFiles on the encapsulated module, exits the test
990// immediately if there is an error and otherwise returns the result of calling Paths.RelativeToTop
991// on the returned Paths.
992func (m TestingModule) OutputFiles(t *testing.T, tag string) Paths {
993 producer, ok := m.module.(OutputFileProducer)
994 if !ok {
995 t.Fatalf("%q must implement OutputFileProducer\n", m.module.Name())
996 }
997 paths, err := producer.OutputFiles(tag)
998 if err != nil {
999 t.Fatal(err)
1000 }
1001
1002 return paths.RelativeToTop()
1003}
1004
Colin Cross4c83e5c2019-02-25 14:54:28 -08001005// TestingSingleton is wrapper around an android.Singleton that provides methods to find information about individual
1006// ctx.Build parameters for verification in tests.
1007type TestingSingleton struct {
Paul Duffin31a22882021-03-22 09:29:00 +00001008 baseTestingComponent
Colin Cross4c83e5c2019-02-25 14:54:28 -08001009 singleton Singleton
Colin Cross4c83e5c2019-02-25 14:54:28 -08001010}
1011
1012// Singleton returns the Singleton wrapped by the TestingSingleton.
1013func (s TestingSingleton) Singleton() Singleton {
1014 return s.singleton
1015}
1016
Logan Chien42039712018-03-12 16:29:17 +08001017func FailIfErrored(t *testing.T, errs []error) {
1018 t.Helper()
1019 if len(errs) > 0 {
1020 for _, err := range errs {
1021 t.Error(err)
1022 }
1023 t.FailNow()
1024 }
1025}
Logan Chienee97c3e2018-03-12 16:34:26 +08001026
Paul Duffinea8a3862021-03-04 17:58:33 +00001027// Fail if no errors that matched the regular expression were found.
1028//
1029// Returns true if a matching error was found, false otherwise.
1030func FailIfNoMatchingErrors(t *testing.T, pattern string, errs []error) bool {
Logan Chienee97c3e2018-03-12 16:34:26 +08001031 t.Helper()
1032
1033 matcher, err := regexp.Compile(pattern)
1034 if err != nil {
Paul Duffinea8a3862021-03-04 17:58:33 +00001035 t.Fatalf("failed to compile regular expression %q because %s", pattern, err)
Logan Chienee97c3e2018-03-12 16:34:26 +08001036 }
1037
1038 found := false
1039 for _, err := range errs {
1040 if matcher.FindStringIndex(err.Error()) != nil {
1041 found = true
1042 break
1043 }
1044 }
1045 if !found {
Steven Moreland082e2062022-08-30 01:11:11 +00001046 t.Errorf("could not match the expected error regex %q (checked %d error(s))", pattern, len(errs))
Logan Chienee97c3e2018-03-12 16:34:26 +08001047 for i, err := range errs {
Colin Crossaede88c2020-08-11 12:17:01 -07001048 t.Errorf("errs[%d] = %q", i, err)
Logan Chienee97c3e2018-03-12 16:34:26 +08001049 }
1050 }
Paul Duffinea8a3862021-03-04 17:58:33 +00001051
1052 return found
Logan Chienee97c3e2018-03-12 16:34:26 +08001053}
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -07001054
Paul Duffin91e38192019-08-05 15:07:57 +01001055func CheckErrorsAgainstExpectations(t *testing.T, errs []error, expectedErrorPatterns []string) {
1056 t.Helper()
1057
1058 if expectedErrorPatterns == nil {
1059 FailIfErrored(t, errs)
1060 } else {
1061 for _, expectedError := range expectedErrorPatterns {
1062 FailIfNoMatchingErrors(t, expectedError, errs)
1063 }
1064 if len(errs) > len(expectedErrorPatterns) {
1065 t.Errorf("additional errors found, expected %d, found %d",
1066 len(expectedErrorPatterns), len(errs))
1067 for i, expectedError := range expectedErrorPatterns {
1068 t.Errorf("expectedErrors[%d] = %s", i, expectedError)
1069 }
1070 for i, err := range errs {
1071 t.Errorf("errs[%d] = %s", i, err)
1072 }
Paul Duffinea8a3862021-03-04 17:58:33 +00001073 t.FailNow()
Paul Duffin91e38192019-08-05 15:07:57 +01001074 }
1075 }
Paul Duffin91e38192019-08-05 15:07:57 +01001076}
1077
Jingwen Chencda22c92020-11-23 00:22:30 -05001078func SetKatiEnabledForTests(config Config) {
1079 config.katiEnabled = true
Paul Duffin8c3fec42020-03-04 20:15:08 +00001080}
1081
Colin Crossaa255532020-07-03 13:18:24 -07001082func AndroidMkEntriesForTest(t *testing.T, ctx *TestContext, mod blueprint.Module) []AndroidMkEntries {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -07001083 var p AndroidMkEntriesProvider
1084 var ok bool
1085 if p, ok = mod.(AndroidMkEntriesProvider); !ok {
Roland Levillaindfe75b32019-07-23 16:53:32 +01001086 t.Errorf("module does not implement AndroidMkEntriesProvider: " + mod.Name())
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -07001087 }
Jiyong Park0b0e1b92019-12-03 13:24:29 +09001088
1089 entriesList := p.AndroidMkEntries()
1090 for i, _ := range entriesList {
Colin Crossaa255532020-07-03 13:18:24 -07001091 entriesList[i].fillInEntries(ctx, mod)
Jiyong Park0b0e1b92019-12-03 13:24:29 +09001092 }
1093 return entriesList
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -07001094}
Jooyung Han12df5fb2019-07-11 16:18:47 +09001095
Colin Crossaa255532020-07-03 13:18:24 -07001096func AndroidMkDataForTest(t *testing.T, ctx *TestContext, mod blueprint.Module) AndroidMkData {
Jooyung Han12df5fb2019-07-11 16:18:47 +09001097 var p AndroidMkDataProvider
1098 var ok bool
1099 if p, ok = mod.(AndroidMkDataProvider); !ok {
Roland Levillaindfe75b32019-07-23 16:53:32 +01001100 t.Errorf("module does not implement AndroidMkDataProvider: " + mod.Name())
Jooyung Han12df5fb2019-07-11 16:18:47 +09001101 }
1102 data := p.AndroidMk()
Colin Crossaa255532020-07-03 13:18:24 -07001103 data.fillInData(ctx, mod)
Jooyung Han12df5fb2019-07-11 16:18:47 +09001104 return data
1105}
Paul Duffin9b478b02019-12-10 13:41:51 +00001106
1107// Normalize the path for testing.
1108//
1109// If the path is relative to the build directory then return the relative path
1110// to avoid tests having to deal with the dynamically generated build directory.
1111//
1112// Otherwise, return the supplied path as it is almost certainly a source path
1113// that is relative to the root of the source tree.
1114//
1115// The build and source paths should be distinguishable based on their contents.
Paul Duffin567465d2021-03-16 01:21:34 +00001116//
1117// deprecated: use PathRelativeToTop instead as it handles make install paths and differentiates
1118// between output and source properly.
Paul Duffin9b478b02019-12-10 13:41:51 +00001119func NormalizePathForTesting(path Path) string {
Paul Duffin064b70c2020-11-02 17:32:38 +00001120 if path == nil {
1121 return "<nil path>"
1122 }
Paul Duffin9b478b02019-12-10 13:41:51 +00001123 p := path.String()
1124 if w, ok := path.(WritablePath); ok {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001125 rel, err := filepath.Rel(w.getSoongOutDir(), p)
Paul Duffin9b478b02019-12-10 13:41:51 +00001126 if err != nil {
1127 panic(err)
1128 }
1129 return rel
1130 }
1131 return p
1132}
1133
Paul Duffin567465d2021-03-16 01:21:34 +00001134// NormalizePathsForTesting creates a slice of strings where each string is the result of applying
1135// NormalizePathForTesting to the corresponding Path in the input slice.
1136//
1137// deprecated: use PathsRelativeToTop instead as it handles make install paths and differentiates
1138// between output and source properly.
Paul Duffin9b478b02019-12-10 13:41:51 +00001139func NormalizePathsForTesting(paths Paths) []string {
1140 var result []string
1141 for _, path := range paths {
1142 relative := NormalizePathForTesting(path)
1143 result = append(result, relative)
1144 }
1145 return result
1146}
Paul Duffin567465d2021-03-16 01:21:34 +00001147
1148// PathRelativeToTop returns a string representation of the path relative to a notional top
1149// directory.
1150//
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001151// It return "<nil path>" if the supplied path is nil, otherwise it returns the result of calling
1152// Path.RelativeToTop to obtain a relative Path and then calling Path.String on that to get the
1153// string representation.
Paul Duffin567465d2021-03-16 01:21:34 +00001154func PathRelativeToTop(path Path) string {
1155 if path == nil {
1156 return "<nil path>"
1157 }
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001158 return path.RelativeToTop().String()
Paul Duffin567465d2021-03-16 01:21:34 +00001159}
1160
1161// PathsRelativeToTop creates a slice of strings where each string is the result of applying
1162// PathRelativeToTop to the corresponding Path in the input slice.
1163func PathsRelativeToTop(paths Paths) []string {
1164 var result []string
1165 for _, path := range paths {
1166 relative := PathRelativeToTop(path)
1167 result = append(result, relative)
1168 }
1169 return result
1170}
1171
1172// StringPathRelativeToTop returns a string representation of the path relative to a notional top
1173// directory.
1174//
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001175// See Path.RelativeToTop for more details as to what `relative to top` means.
Paul Duffin567465d2021-03-16 01:21:34 +00001176//
1177// This is provided for processing paths that have already been converted into a string, e.g. paths
1178// in AndroidMkEntries structures. As a result it needs to be supplied the soong output dir against
1179// which it can try and relativize paths. PathRelativeToTop must be used for process Path objects.
1180func StringPathRelativeToTop(soongOutDir string, path string) string {
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001181 ensureTestOnly()
Paul Duffin567465d2021-03-16 01:21:34 +00001182
1183 // A relative path must be a source path so leave it as it is.
1184 if !filepath.IsAbs(path) {
1185 return path
1186 }
1187
1188 // Check to see if the path is relative to the soong out dir.
1189 rel, isRel, err := maybeRelErr(soongOutDir, path)
1190 if err != nil {
1191 panic(err)
1192 }
1193
1194 if isRel {
1195 // The path is in the soong out dir so indicate that in the relative path.
1196 return filepath.Join("out/soong", rel)
1197 }
1198
1199 // Check to see if the path is relative to the top level out dir.
1200 outDir := filepath.Dir(soongOutDir)
1201 rel, isRel, err = maybeRelErr(outDir, path)
1202 if err != nil {
1203 panic(err)
1204 }
1205
1206 if isRel {
1207 // The path is in the out dir so indicate that in the relative path.
1208 return filepath.Join("out", rel)
1209 }
1210
1211 // This should never happen.
1212 panic(fmt.Errorf("internal error: absolute path %s is not relative to the out dir %s", path, outDir))
1213}
1214
1215// StringPathsRelativeToTop creates a slice of strings where each string is the result of applying
1216// StringPathRelativeToTop to the corresponding string path in the input slice.
1217//
1218// This is provided for processing paths that have already been converted into a string, e.g. paths
1219// in AndroidMkEntries structures. As a result it needs to be supplied the soong output dir against
1220// which it can try and relativize paths. PathsRelativeToTop must be used for process Paths objects.
1221func StringPathsRelativeToTop(soongOutDir string, paths []string) []string {
1222 var result []string
1223 for _, path := range paths {
1224 relative := StringPathRelativeToTop(soongOutDir, path)
1225 result = append(result, relative)
1226 }
1227 return result
1228}
Paul Duffinf53555d2021-03-29 00:21:00 +01001229
1230// StringRelativeToTop will normalize a string containing paths, e.g. ninja command, by replacing
1231// any references to the test specific temporary build directory that changes with each run to a
1232// fixed path relative to a notional top directory.
1233//
1234// This is similar to StringPathRelativeToTop except that assumes the string is a single path
1235// containing at most one instance of the temporary build directory at the start of the path while
1236// this assumes that there can be any number at any position.
1237func StringRelativeToTop(config Config, command string) string {
1238 return normalizeStringRelativeToTop(config, command)
1239}
Paul Duffin0aafcbf2021-03-29 00:56:32 +01001240
1241// StringsRelativeToTop will return a new slice such that each item in the new slice is the result
1242// of calling StringRelativeToTop on the corresponding item in the input slice.
1243func StringsRelativeToTop(config Config, command []string) []string {
1244 return normalizeStringArrayRelativeToTop(config, command)
1245}