blob: 8e38b3b1c60769d2189b61d5cfd84aef78d0cdcd [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
Spandan Das45e40012024-12-02 22:45:48 +0000193// PrepareForNativeBridgeEnabled sets configuration with targets including:
194// - X86_64 (primary)
195// - X86 (secondary)
196// - Arm64 on X86_64 (native bridge)
197// - Arm on X86 (native bridge)
198var PrepareForNativeBridgeEnabled = FixtureModifyConfig(
199 func(config Config) {
200 config.Targets[Android] = []Target{
201 {Os: Android, Arch: Arch{ArchType: X86_64, ArchVariant: "silvermont", Abi: []string{"arm64-v8a"}},
202 NativeBridge: NativeBridgeDisabled, NativeBridgeHostArchName: "", NativeBridgeRelativePath: ""},
203 {Os: Android, Arch: Arch{ArchType: X86, ArchVariant: "silvermont", Abi: []string{"armeabi-v7a"}},
204 NativeBridge: NativeBridgeDisabled, NativeBridgeHostArchName: "", NativeBridgeRelativePath: ""},
205 {Os: Android, Arch: Arch{ArchType: Arm64, ArchVariant: "armv8-a", Abi: []string{"arm64-v8a"}},
206 NativeBridge: NativeBridgeEnabled, NativeBridgeHostArchName: "x86_64", NativeBridgeRelativePath: "arm64"},
207 {Os: Android, Arch: Arch{ArchType: Arm, ArchVariant: "armv7-a-neon", Abi: []string{"armeabi-v7a"}},
208 NativeBridge: NativeBridgeEnabled, NativeBridgeHostArchName: "x86", NativeBridgeRelativePath: "arm"},
209 }
210 },
211)
212
Colin Crossae8600b2020-10-29 17:09:13 -0700213func NewTestArchContext(config Config) *TestContext {
214 ctx := NewTestContext(config)
Colin Crossae4c6182017-09-15 17:33:55 -0700215 ctx.preDeps = append(ctx.preDeps, registerArchMutator)
216 return ctx
217}
218
Colin Crosscec81712017-07-13 14:43:27 -0700219type TestContext struct {
Colin Cross4c83e5c2019-02-25 14:54:28 -0800220 *Context
Colin Crossf22fe412024-10-01 14:02:12 -0700221 preArch, preDeps, postDeps, postApex, finalDeps []RegisterMutatorFunc
222 NameResolver *NameResolver
Paul Duffin281deb22021-03-06 20:29:19 +0000223
Cole Faustae6cda62023-11-01 15:32:40 -0700224 // The list of singletons registered for the test.
225 singletons sortableComponents
Paul Duffind182fb32021-03-07 12:24:44 +0000226
Cole Faustae6cda62023-11-01 15:32:40 -0700227 // The order in which the mutators and singletons will be run in this test
Paul Duffin41d77c72021-03-07 12:23:48 +0000228 // context; for debugging.
Cole Faustae6cda62023-11-01 15:32:40 -0700229 mutatorOrder, singletonOrder []string
Colin Crosscec81712017-07-13 14:43:27 -0700230}
231
232func (ctx *TestContext) PreArchMutators(f RegisterMutatorFunc) {
233 ctx.preArch = append(ctx.preArch, f)
234}
235
Paul Duffina80ef842020-01-14 12:09:36 +0000236func (ctx *TestContext) HardCodedPreArchMutators(f RegisterMutatorFunc) {
237 // Register mutator function as normal for testing.
238 ctx.PreArchMutators(f)
239}
240
Yu Liu663e4502024-08-12 18:23:59 +0000241func (ctx *TestContext) otherModuleProvider(m blueprint.Module, p blueprint.AnyProviderKey) (any, bool) {
Liz Kammer92c72592022-10-31 14:44:28 -0400242 return ctx.Context.ModuleProvider(m, p)
243}
244
Colin Crosscec81712017-07-13 14:43:27 -0700245func (ctx *TestContext) PreDepsMutators(f RegisterMutatorFunc) {
246 ctx.preDeps = append(ctx.preDeps, f)
247}
248
249func (ctx *TestContext) PostDepsMutators(f RegisterMutatorFunc) {
250 ctx.postDeps = append(ctx.postDeps, f)
251}
252
Colin Crossf22fe412024-10-01 14:02:12 -0700253func (ctx *TestContext) PostApexMutators(f RegisterMutatorFunc) {
254 ctx.postApex = append(ctx.postApex, f)
255}
256
Martin Stjernholm710ec3a2020-01-16 15:12:04 +0000257func (ctx *TestContext) FinalDepsMutators(f RegisterMutatorFunc) {
258 ctx.finalDeps = append(ctx.finalDeps, f)
259}
260
Colin Cross3c0a83d2023-12-12 14:13:26 -0800261func (ctx *TestContext) OtherModuleProviderAdaptor() OtherModuleProviderContext {
262 return NewOtherModuleProviderAdaptor(func(module blueprint.Module, provider blueprint.AnyProviderKey) (any, bool) {
Yu Liu663e4502024-08-12 18:23:59 +0000263 return ctx.otherModuleProvider(module, provider)
Colin Cross3c0a83d2023-12-12 14:13:26 -0800264 })
265}
266
Cole Faust43ddd082024-06-17 12:32:40 -0700267func (ctx *TestContext) OtherModulePropertyErrorf(module Module, property string, fmt_ string, args ...interface{}) {
268 panic(fmt.Sprintf(fmt_, args...))
269}
270
Paul Duffin281deb22021-03-06 20:29:19 +0000271// registeredComponentOrder defines the order in which a sortableComponent type is registered at
272// runtime and provides support for reordering the components registered for a test in the same
273// way.
274type registeredComponentOrder struct {
275 // The name of the component type, used for error messages.
276 componentType string
277
278 // The names of the registered components in the order in which they were registered.
279 namesInOrder []string
280
281 // Maps from the component name to its position in the runtime ordering.
282 namesToIndex map[string]int
283
284 // A function that defines the order between two named components that can be used to sort a slice
285 // of component names into the same order as they appear in namesInOrder.
286 less func(string, string) bool
287}
288
289// registeredComponentOrderFromExistingOrder takes an existing slice of sortableComponents and
290// creates a registeredComponentOrder that contains a less function that can be used to sort a
291// subset of that list of names so it is in the same order as the original sortableComponents.
292func registeredComponentOrderFromExistingOrder(componentType string, existingOrder sortableComponents) registeredComponentOrder {
293 // Only the names from the existing order are needed for this so create a list of component names
294 // in the correct order.
295 namesInOrder := componentsToNames(existingOrder)
296
297 // Populate the map from name to position in the list.
298 nameToIndex := make(map[string]int)
299 for i, n := range namesInOrder {
300 nameToIndex[n] = i
301 }
302
303 // A function to use to map from a name to an index in the original order.
304 indexOf := func(name string) int {
305 index, ok := nameToIndex[name]
306 if !ok {
307 // Should never happen as tests that use components that are not known at runtime do not sort
308 // so should never use this function.
309 panic(fmt.Errorf("internal error: unknown %s %q should be one of %s", componentType, name, strings.Join(namesInOrder, ", ")))
310 }
311 return index
312 }
313
314 // The less function.
315 less := func(n1, n2 string) bool {
316 i1 := indexOf(n1)
317 i2 := indexOf(n2)
318 return i1 < i2
319 }
320
321 return registeredComponentOrder{
322 componentType: componentType,
323 namesInOrder: namesInOrder,
324 namesToIndex: nameToIndex,
325 less: less,
326 }
327}
328
329// componentsToNames maps from the slice of components to a slice of their names.
330func componentsToNames(components sortableComponents) []string {
331 names := make([]string, len(components))
332 for i, c := range components {
333 names[i] = c.componentName()
334 }
335 return names
336}
337
338// enforceOrdering enforces the supplied components are in the same order as is defined in this
339// object.
340//
341// If the supplied components contains any components that are not registered at runtime, i.e. test
342// specific components, then it is impossible to sort them into an order that both matches the
343// runtime and also preserves the implicit ordering defined in the test. In that case it will not
344// sort the components, instead it will just check that the components are in the correct order.
345//
346// Otherwise, this will sort the supplied components in place.
347func (o *registeredComponentOrder) enforceOrdering(components sortableComponents) {
348 // Check to see if the list of components contains any components that are
349 // not registered at runtime.
350 var unknownComponents []string
351 testOrder := componentsToNames(components)
352 for _, name := range testOrder {
353 if _, ok := o.namesToIndex[name]; !ok {
354 unknownComponents = append(unknownComponents, name)
355 break
356 }
357 }
358
359 // If the slice contains some unknown components then it is not possible to
360 // sort them into an order that matches the runtime while also preserving the
361 // order expected from the test, so in that case don't sort just check that
362 // the order of the known mutators does match.
363 if len(unknownComponents) > 0 {
364 // Check order.
365 o.checkTestOrder(testOrder, unknownComponents)
366 } else {
367 // Sort the components.
368 sort.Slice(components, func(i, j int) bool {
369 n1 := components[i].componentName()
370 n2 := components[j].componentName()
371 return o.less(n1, n2)
372 })
373 }
374}
375
376// checkTestOrder checks that the supplied testOrder matches the one defined by this object,
377// panicking if it does not.
378func (o *registeredComponentOrder) checkTestOrder(testOrder []string, unknownComponents []string) {
379 lastMatchingTest := -1
380 matchCount := 0
381 // Take a copy of the runtime order as it is modified during the comparison.
382 runtimeOrder := append([]string(nil), o.namesInOrder...)
383 componentType := o.componentType
384 for i, j := 0, 0; i < len(testOrder) && j < len(runtimeOrder); {
385 test := testOrder[i]
386 runtime := runtimeOrder[j]
387
388 if test == runtime {
389 testOrder[i] = test + fmt.Sprintf(" <-- matched with runtime %s %d", componentType, j)
390 runtimeOrder[j] = runtime + fmt.Sprintf(" <-- matched with test %s %d", componentType, i)
391 lastMatchingTest = i
392 i += 1
393 j += 1
394 matchCount += 1
395 } else if _, ok := o.namesToIndex[test]; !ok {
396 // The test component is not registered globally so assume it is the correct place, treat it
397 // as having matched and skip it.
398 i += 1
399 matchCount += 1
400 } else {
401 // Assume that the test list is in the same order as the runtime list but the runtime list
402 // contains some components that are not present in the tests. So, skip the runtime component
403 // to try and find the next one that matches the current test component.
404 j += 1
405 }
406 }
407
408 // If every item in the test order was either test specific or matched one in the runtime then
409 // it is in the correct order. Otherwise, it was not so fail.
410 if matchCount != len(testOrder) {
411 // The test component names were not all matched with a runtime component name so there must
412 // either be a component present in the test that is not present in the runtime or they must be
413 // in the wrong order.
414 testOrder[lastMatchingTest+1] = testOrder[lastMatchingTest+1] + " <--- unmatched"
415 panic(fmt.Errorf("the tests uses test specific components %q and so cannot be automatically sorted."+
416 " Unfortunately it uses %s components in the wrong order.\n"+
417 "test order:\n %s\n"+
418 "runtime order\n %s\n",
419 SortedUniqueStrings(unknownComponents),
420 componentType,
421 strings.Join(testOrder, "\n "),
422 strings.Join(runtimeOrder, "\n ")))
423 }
424}
425
426// registrationSorter encapsulates the information needed to ensure that the test mutators are
427// registered, and thereby executed, in the same order as they are at runtime.
428//
429// It MUST be populated lazily AFTER all package initialization has been done otherwise it will
430// only define the order for a subset of all the registered build components that are available for
431// the packages being tested.
432//
433// e.g if this is initialized during say the cc package initialization then any tests run in the
434// java package will not sort build components registered by the java package's init() functions.
435type registrationSorter struct {
436 // Used to ensure that this is only created once.
437 once sync.Once
438
439 // The order of mutators
440 mutatorOrder registeredComponentOrder
Paul Duffin41d77c72021-03-07 12:23:48 +0000441
442 // The order of singletons
443 singletonOrder registeredComponentOrder
Paul Duffin281deb22021-03-06 20:29:19 +0000444}
445
446// populate initializes this structure from globally registered build components.
447//
448// Only the first call has any effect.
449func (s *registrationSorter) populate() {
450 s.once.Do(func() {
451 // Created an ordering from the globally registered mutators.
452 globallyRegisteredMutators := collateGloballyRegisteredMutators()
453 s.mutatorOrder = registeredComponentOrderFromExistingOrder("mutator", globallyRegisteredMutators)
Paul Duffin41d77c72021-03-07 12:23:48 +0000454
455 // Create an ordering from the globally registered singletons.
456 globallyRegisteredSingletons := collateGloballyRegisteredSingletons()
457 s.singletonOrder = registeredComponentOrderFromExistingOrder("singleton", globallyRegisteredSingletons)
Paul Duffin281deb22021-03-06 20:29:19 +0000458 })
459}
460
461// Provides support for enforcing the same order in which build components are registered globally
462// to the order in which they are registered during tests.
463//
464// MUST only be accessed via the globallyRegisteredComponentsOrder func.
465var globalRegistrationSorter registrationSorter
466
467// globallyRegisteredComponentsOrder returns the globalRegistrationSorter after ensuring it is
468// correctly populated.
469func globallyRegisteredComponentsOrder() *registrationSorter {
470 globalRegistrationSorter.populate()
471 return &globalRegistrationSorter
472}
473
Colin Crossae8600b2020-10-29 17:09:13 -0700474func (ctx *TestContext) Register() {
Paul Duffin281deb22021-03-06 20:29:19 +0000475 globalOrder := globallyRegisteredComponentsOrder()
476
Colin Crossf22fe412024-10-01 14:02:12 -0700477 mutators := collateRegisteredMutators(ctx.preArch, ctx.preDeps, ctx.postDeps, ctx.postApex, ctx.finalDeps)
Paul Duffin281deb22021-03-06 20:29:19 +0000478 // Ensure that the mutators used in the test are in the same order as they are used at runtime.
479 globalOrder.mutatorOrder.enforceOrdering(mutators)
Paul Duffinc05b0342021-03-06 13:28:13 +0000480 mutators.registerAll(ctx.Context)
Colin Crosscec81712017-07-13 14:43:27 -0700481
Paul Duffin41d77c72021-03-07 12:23:48 +0000482 // Ensure that the singletons used in the test are in the same order as they are used at runtime.
483 globalOrder.singletonOrder.enforceOrdering(ctx.singletons)
Paul Duffind182fb32021-03-07 12:24:44 +0000484 ctx.singletons.registerAll(ctx.Context)
485
Paul Duffin41d77c72021-03-07 12:23:48 +0000486 // Save the sorted components order away to make them easy to access while debugging.
Paul Duffinf5de6682021-03-08 23:42:10 +0000487 ctx.mutatorOrder = componentsToNames(mutators)
488 ctx.singletonOrder = componentsToNames(singletons)
Colin Cross31a738b2019-12-30 18:45:15 -0800489}
490
491func (ctx *TestContext) ParseFileList(rootDir string, filePaths []string) (deps []string, errs []error) {
492 // This function adapts the old style ParseFileList calls that are spread throughout the tests
493 // to the new style that takes a config.
494 return ctx.Context.ParseFileList(rootDir, filePaths, ctx.config)
495}
496
497func (ctx *TestContext) ParseBlueprintsFiles(rootDir string) (deps []string, errs []error) {
498 // This function adapts the old style ParseBlueprintsFiles calls that are spread throughout the
499 // tests to the new style that takes a config.
500 return ctx.Context.ParseBlueprintsFiles(rootDir, ctx.config)
Colin Cross4b49b762019-11-22 15:25:03 -0800501}
502
503func (ctx *TestContext) RegisterModuleType(name string, factory ModuleFactory) {
504 ctx.Context.RegisterModuleType(name, ModuleFactoryAdaptor(factory))
505}
506
Colin Cross9aed5bc2020-12-28 15:15:34 -0800507func (ctx *TestContext) RegisterSingletonModuleType(name string, factory SingletonModuleFactory) {
508 s, m := SingletonModuleFactoryAdaptor(name, factory)
509 ctx.RegisterSingletonType(name, s)
510 ctx.RegisterModuleType(name, m)
511}
512
LaMont Jonese59c0db2023-05-15 21:50:29 +0000513func (ctx *TestContext) RegisterParallelSingletonModuleType(name string, factory SingletonModuleFactory) {
514 s, m := SingletonModuleFactoryAdaptor(name, factory)
515 ctx.RegisterParallelSingletonType(name, s)
516 ctx.RegisterModuleType(name, m)
517}
518
Colin Cross4b49b762019-11-22 15:25:03 -0800519func (ctx *TestContext) RegisterSingletonType(name string, factory SingletonFactory) {
LaMont Jonese59c0db2023-05-15 21:50:29 +0000520 ctx.singletons = append(ctx.singletons, newSingleton(name, factory, false))
521}
522
523func (ctx *TestContext) RegisterParallelSingletonType(name string, factory SingletonFactory) {
524 ctx.singletons = append(ctx.singletons, newSingleton(name, factory, true))
Colin Crosscec81712017-07-13 14:43:27 -0700525}
526
Martin Stjernholm14cdd712021-09-10 22:39:59 +0100527// ModuleVariantForTests selects a specific variant of the module with the given
528// name by matching the variations map against the variations of each module
529// variant. A module variant matches the map if every variation that exists in
530// both have the same value. Both the module and the map are allowed to have
531// extra variations that the other doesn't have. Panics if not exactly one
532// module variant matches.
Colin Cross90607e92025-02-11 14:58:07 -0800533func (ctx *TestContext) ModuleVariantForTests(t *testing.T, name string, matchVariations map[string]string) TestingModule {
534 t.Helper()
Martin Stjernholm14cdd712021-09-10 22:39:59 +0100535 modules := []Module{}
536 ctx.VisitAllModules(func(m blueprint.Module) {
537 if ctx.ModuleName(m) == name {
538 am := m.(Module)
539 amMut := am.base().commonProperties.DebugMutators
540 amVar := am.base().commonProperties.DebugVariations
541 matched := true
542 for i, mut := range amMut {
543 if wantedVar, found := matchVariations[mut]; found && amVar[i] != wantedVar {
544 matched = false
545 break
546 }
547 }
548 if matched {
549 modules = append(modules, am)
550 }
551 }
552 })
553
554 if len(modules) == 0 {
555 // Show all the modules or module variants that do exist.
556 var allModuleNames []string
557 var allVariants []string
558 ctx.VisitAllModules(func(m blueprint.Module) {
559 allModuleNames = append(allModuleNames, ctx.ModuleName(m))
560 if ctx.ModuleName(m) == name {
561 allVariants = append(allVariants, m.(Module).String())
562 }
563 })
564
565 if len(allVariants) == 0 {
Colin Cross90607e92025-02-11 14:58:07 -0800566 t.Fatalf("failed to find module %q. All modules:\n %s",
567 name, strings.Join(SortedUniqueStrings(allModuleNames), "\n "))
Martin Stjernholm14cdd712021-09-10 22:39:59 +0100568 } else {
569 sort.Strings(allVariants)
Colin Cross90607e92025-02-11 14:58:07 -0800570 t.Fatalf("failed to find module %q matching %v. All variants:\n %s",
571 name, matchVariations, strings.Join(allVariants, "\n "))
Martin Stjernholm14cdd712021-09-10 22:39:59 +0100572 }
573 }
574
575 if len(modules) > 1 {
576 moduleStrings := []string{}
577 for _, m := range modules {
578 moduleStrings = append(moduleStrings, m.String())
579 }
580 sort.Strings(moduleStrings)
Colin Cross90607e92025-02-11 14:58:07 -0800581 t.Fatalf("module %q has more than one variant that match %v:\n %s",
582 name, matchVariations, strings.Join(moduleStrings, "\n "))
Martin Stjernholm14cdd712021-09-10 22:39:59 +0100583 }
584
Colin Cross90607e92025-02-11 14:58:07 -0800585 return newTestingModule(t, ctx.config, modules[0])
Martin Stjernholm14cdd712021-09-10 22:39:59 +0100586}
587
Colin Cross90607e92025-02-11 14:58:07 -0800588func (ctx *TestContext) ModuleForTests(t *testing.T, name, variant string) TestingModule {
589 t.Helper()
Colin Crosscec81712017-07-13 14:43:27 -0700590 var module Module
591 ctx.VisitAllModules(func(m blueprint.Module) {
592 if ctx.ModuleName(m) == name && ctx.ModuleSubDir(m) == variant {
593 module = m.(Module)
594 }
595 })
596
597 if module == nil {
Jeff Gaston294356f2017-09-27 17:05:30 -0700598 // find all the modules that do exist
Colin Crossbeae6ec2020-08-11 12:02:11 -0700599 var allModuleNames []string
600 var allVariants []string
Jeff Gaston294356f2017-09-27 17:05:30 -0700601 ctx.VisitAllModules(func(m blueprint.Module) {
Colin Crossbeae6ec2020-08-11 12:02:11 -0700602 allModuleNames = append(allModuleNames, ctx.ModuleName(m))
603 if ctx.ModuleName(m) == name {
604 allVariants = append(allVariants, ctx.ModuleSubDir(m))
605 }
Jeff Gaston294356f2017-09-27 17:05:30 -0700606 })
Colin Crossbeae6ec2020-08-11 12:02:11 -0700607 sort.Strings(allVariants)
Jeff Gaston294356f2017-09-27 17:05:30 -0700608
Colin Crossbeae6ec2020-08-11 12:02:11 -0700609 if len(allVariants) == 0 {
Colin Cross90607e92025-02-11 14:58:07 -0800610 t.Fatalf("failed to find module %q. All modules:\n %s",
611 name, strings.Join(SortedUniqueStrings(allModuleNames), "\n "))
Colin Crossbeae6ec2020-08-11 12:02:11 -0700612 } else {
Colin Cross90607e92025-02-11 14:58:07 -0800613 t.Fatalf("failed to find module %q variant %q. All variants:\n %s",
614 name, variant, strings.Join(allVariants, "\n "))
Colin Crossbeae6ec2020-08-11 12:02:11 -0700615 }
Colin Crosscec81712017-07-13 14:43:27 -0700616 }
617
Colin Cross90607e92025-02-11 14:58:07 -0800618 return newTestingModule(t, ctx.config, module)
Colin Crosscec81712017-07-13 14:43:27 -0700619}
620
Jiyong Park37b25202018-07-11 10:49:27 +0900621func (ctx *TestContext) ModuleVariantsForTests(name string) []string {
622 var variants []string
623 ctx.VisitAllModules(func(m blueprint.Module) {
624 if ctx.ModuleName(m) == name {
625 variants = append(variants, ctx.ModuleSubDir(m))
626 }
627 })
628 return variants
629}
630
Colin Cross4c83e5c2019-02-25 14:54:28 -0800631// SingletonForTests returns a TestingSingleton for the singleton registered with the given name.
Colin Cross90607e92025-02-11 14:58:07 -0800632func (ctx *TestContext) SingletonForTests(t *testing.T, name string) TestingSingleton {
633 t.Helper()
Colin Cross4c83e5c2019-02-25 14:54:28 -0800634 allSingletonNames := []string{}
635 for _, s := range ctx.Singletons() {
636 n := ctx.SingletonName(s)
637 if n == name {
638 return TestingSingleton{
Colin Cross90607e92025-02-11 14:58:07 -0800639 baseTestingComponent: newBaseTestingComponent(t, ctx.config, s.(testBuildProvider)),
Paul Duffin31a22882021-03-22 09:29:00 +0000640 singleton: s.(*singletonAdaptor).Singleton,
Colin Cross4c83e5c2019-02-25 14:54:28 -0800641 }
642 }
643 allSingletonNames = append(allSingletonNames, n)
644 }
645
Colin Cross90607e92025-02-11 14:58:07 -0800646 t.Fatalf("failed to find singleton %q."+
647 "\nall singletons: %v", name, allSingletonNames)
648
649 return TestingSingleton{}
Colin Cross4c83e5c2019-02-25 14:54:28 -0800650}
651
Martin Stjernholm1ebef5b2022-02-10 23:34:28 +0000652type InstallMakeRule struct {
653 Target string
654 Deps []string
655 OrderOnlyDeps []string
656}
657
658func parseMkRules(t *testing.T, config Config, nodes []mkparser.Node) []InstallMakeRule {
Colin Cross90607e92025-02-11 14:58:07 -0800659 t.Helper()
Martin Stjernholm1ebef5b2022-02-10 23:34:28 +0000660 var rules []InstallMakeRule
661 for _, node := range nodes {
662 if mkParserRule, ok := node.(*mkparser.Rule); ok {
663 var rule InstallMakeRule
664
665 if targets := mkParserRule.Target.Words(); len(targets) == 0 {
666 t.Fatalf("no targets for rule %s", mkParserRule.Dump())
667 } else if len(targets) > 1 {
668 t.Fatalf("unsupported multiple targets for rule %s", mkParserRule.Dump())
669 } else if !targets[0].Const() {
670 t.Fatalf("unsupported non-const target for rule %s", mkParserRule.Dump())
671 } else {
672 rule.Target = normalizeStringRelativeToTop(config, targets[0].Value(nil))
673 }
674
675 prereqList := &rule.Deps
676 for _, prereq := range mkParserRule.Prerequisites.Words() {
677 if !prereq.Const() {
678 t.Fatalf("unsupported non-const prerequisite for rule %s", mkParserRule.Dump())
679 }
680
681 if prereq.Value(nil) == "|" {
682 prereqList = &rule.OrderOnlyDeps
683 continue
684 }
685
686 *prereqList = append(*prereqList, normalizeStringRelativeToTop(config, prereq.Value(nil)))
687 }
688
689 rules = append(rules, rule)
690 }
691 }
692
693 return rules
694}
695
696func (ctx *TestContext) InstallMakeRulesForTesting(t *testing.T) []InstallMakeRule {
Colin Cross90607e92025-02-11 14:58:07 -0800697 t.Helper()
698 installs := ctx.SingletonForTests(t, "makevars").Singleton().(*makeVarsSingleton).installsForTesting
Martin Stjernholm1ebef5b2022-02-10 23:34:28 +0000699 buf := bytes.NewBuffer(append([]byte(nil), installs...))
700 parser := mkparser.NewParser("makevars", buf)
701
702 nodes, errs := parser.Parse()
703 if len(errs) > 0 {
704 t.Fatalf("error parsing install rules: %s", errs[0])
705 }
706
707 return parseMkRules(t, ctx.config, nodes)
708}
709
Paul Duffin8eb45732022-10-04 19:03:31 +0100710// MakeVarVariable provides access to make vars that will be written by the makeVarsSingleton
711type MakeVarVariable interface {
712 // Name is the name of the variable.
713 Name() string
714
715 // Value is the value of the variable.
716 Value() string
717}
718
719func (v makeVarsVariable) Name() string {
720 return v.name
721}
722
723func (v makeVarsVariable) Value() string {
724 return v.value
725}
726
727// PrepareForTestAccessingMakeVars sets up the test so that MakeVarsForTesting will work.
728var PrepareForTestAccessingMakeVars = GroupFixturePreparers(
729 PrepareForTestWithAndroidMk,
730 PrepareForTestWithMakevars,
731)
732
733// MakeVarsForTesting returns a filtered list of MakeVarVariable objects that represent the
734// variables that will be written out.
735//
736// It is necessary to use PrepareForTestAccessingMakeVars in tests that want to call this function.
737// Along with any other preparers needed to add the make vars.
Colin Cross90607e92025-02-11 14:58:07 -0800738func (ctx *TestContext) MakeVarsForTesting(t *testing.T, filter func(variable MakeVarVariable) bool) []MakeVarVariable {
739 t.Helper()
740 vars := ctx.SingletonForTests(t, "makevars").Singleton().(*makeVarsSingleton).varsForTesting
Paul Duffin8eb45732022-10-04 19:03:31 +0100741 result := make([]MakeVarVariable, 0, len(vars))
742 for _, v := range vars {
743 if filter(v) {
744 result = append(result, v)
745 }
746 }
747
748 return result
749}
750
Colin Crossaa255532020-07-03 13:18:24 -0700751func (ctx *TestContext) Config() Config {
752 return ctx.config
753}
754
Colin Cross4c83e5c2019-02-25 14:54:28 -0800755type testBuildProvider interface {
756 BuildParamsForTests() []BuildParams
757 RuleParamsForTests() map[blueprint.Rule]blueprint.RuleParams
758}
759
760type TestingBuildParams struct {
761 BuildParams
762 RuleParams blueprint.RuleParams
Paul Duffin709e0e32021-03-22 10:09:02 +0000763
764 config Config
765}
766
767// RelativeToTop creates a new instance of this which has had any usages of the current test's
768// temporary and test specific build directory replaced with a path relative to the notional top.
769//
770// The parts of this structure which are changed are:
771// * BuildParams
Colin Crossd079e0b2022-08-16 10:27:33 -0700772// - Args
773// - All Path, Paths, WritablePath and WritablePaths fields.
Paul Duffin709e0e32021-03-22 10:09:02 +0000774//
775// * RuleParams
Colin Crossd079e0b2022-08-16 10:27:33 -0700776// - Command
777// - Depfile
778// - Rspfile
779// - RspfileContent
Colin Crossd079e0b2022-08-16 10:27:33 -0700780// - CommandDeps
781// - CommandOrderOnly
Paul Duffin709e0e32021-03-22 10:09:02 +0000782//
783// See PathRelativeToTop for more details.
Paul Duffina71a67a2021-03-29 00:42:57 +0100784//
785// deprecated: this is no longer needed as TestingBuildParams are created in this form.
Paul Duffin709e0e32021-03-22 10:09:02 +0000786func (p TestingBuildParams) RelativeToTop() TestingBuildParams {
787 // If this is not a valid params then just return it back. That will make it easy to use with the
788 // Maybe...() methods.
789 if p.Rule == nil {
790 return p
791 }
792 if p.config.config == nil {
Paul Duffine8366da2021-03-24 10:40:38 +0000793 return p
Paul Duffin709e0e32021-03-22 10:09:02 +0000794 }
795 // Take a copy of the build params and replace any args that contains test specific temporary
796 // paths with paths relative to the top.
797 bparams := p.BuildParams
Paul Duffinbbb0f8f2021-03-24 10:34:52 +0000798 bparams.Depfile = normalizeWritablePathRelativeToTop(bparams.Depfile)
799 bparams.Output = normalizeWritablePathRelativeToTop(bparams.Output)
800 bparams.Outputs = bparams.Outputs.RelativeToTop()
Paul Duffinbbb0f8f2021-03-24 10:34:52 +0000801 bparams.ImplicitOutput = normalizeWritablePathRelativeToTop(bparams.ImplicitOutput)
802 bparams.ImplicitOutputs = bparams.ImplicitOutputs.RelativeToTop()
803 bparams.Input = normalizePathRelativeToTop(bparams.Input)
804 bparams.Inputs = bparams.Inputs.RelativeToTop()
805 bparams.Implicit = normalizePathRelativeToTop(bparams.Implicit)
806 bparams.Implicits = bparams.Implicits.RelativeToTop()
807 bparams.OrderOnly = bparams.OrderOnly.RelativeToTop()
808 bparams.Validation = normalizePathRelativeToTop(bparams.Validation)
809 bparams.Validations = bparams.Validations.RelativeToTop()
Paul Duffin709e0e32021-03-22 10:09:02 +0000810 bparams.Args = normalizeStringMapRelativeToTop(p.config, bparams.Args)
811
812 // Ditto for any fields in the RuleParams.
813 rparams := p.RuleParams
814 rparams.Command = normalizeStringRelativeToTop(p.config, rparams.Command)
815 rparams.Depfile = normalizeStringRelativeToTop(p.config, rparams.Depfile)
816 rparams.Rspfile = normalizeStringRelativeToTop(p.config, rparams.Rspfile)
817 rparams.RspfileContent = normalizeStringRelativeToTop(p.config, rparams.RspfileContent)
Paul Duffin709e0e32021-03-22 10:09:02 +0000818 rparams.CommandDeps = normalizeStringArrayRelativeToTop(p.config, rparams.CommandDeps)
819 rparams.CommandOrderOnly = normalizeStringArrayRelativeToTop(p.config, rparams.CommandOrderOnly)
820
821 return TestingBuildParams{
822 BuildParams: bparams,
823 RuleParams: rparams,
824 }
Colin Cross4c83e5c2019-02-25 14:54:28 -0800825}
826
Paul Duffinbbb0f8f2021-03-24 10:34:52 +0000827func normalizeWritablePathRelativeToTop(path WritablePath) WritablePath {
828 if path == nil {
829 return nil
830 }
831 return path.RelativeToTop().(WritablePath)
832}
833
834func normalizePathRelativeToTop(path Path) Path {
835 if path == nil {
836 return nil
837 }
838 return path.RelativeToTop()
839}
840
Jiakai Zhangcf61e3c2023-05-08 16:28:38 +0000841func allOutputs(p BuildParams) []string {
842 outputs := append(WritablePaths(nil), p.Outputs...)
843 outputs = append(outputs, p.ImplicitOutputs...)
844 if p.Output != nil {
845 outputs = append(outputs, p.Output)
846 }
847 return outputs.Strings()
848}
849
850// AllOutputs returns all 'BuildParams.Output's and 'BuildParams.Outputs's in their full path string forms.
851func (p TestingBuildParams) AllOutputs() []string {
852 return allOutputs(p.BuildParams)
853}
854
Paul Duffin0eda26b92021-03-22 09:34:29 +0000855// baseTestingComponent provides functionality common to both TestingModule and TestingSingleton.
856type baseTestingComponent struct {
Colin Cross90607e92025-02-11 14:58:07 -0800857 t *testing.T
Paul Duffin709e0e32021-03-22 10:09:02 +0000858 config Config
Paul Duffin0eda26b92021-03-22 09:34:29 +0000859 provider testBuildProvider
860}
861
Colin Cross90607e92025-02-11 14:58:07 -0800862func newBaseTestingComponent(t *testing.T, config Config, provider testBuildProvider) baseTestingComponent {
863 return baseTestingComponent{t, config, provider}
Paul Duffin709e0e32021-03-22 10:09:02 +0000864}
865
866// A function that will normalize a string containing paths, e.g. ninja command, by replacing
867// any references to the test specific temporary build directory that changes with each run to a
868// fixed path relative to a notional top directory.
869//
870// This is similar to StringPathRelativeToTop except that assumes the string is a single path
871// containing at most one instance of the temporary build directory at the start of the path while
872// this assumes that there can be any number at any position.
873func normalizeStringRelativeToTop(config Config, s string) string {
Colin Cross3b1c6842024-07-26 11:52:57 -0700874 // The outDir usually looks something like: /tmp/testFoo2345/001
Paul Duffin709e0e32021-03-22 10:09:02 +0000875 //
Colin Cross3b1c6842024-07-26 11:52:57 -0700876 // Replace any usage of the outDir with out/soong, e.g. replace "/tmp/testFoo2345/001" with
Paul Duffin709e0e32021-03-22 10:09:02 +0000877 // "out/soong".
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200878 outSoongDir := filepath.Clean(config.soongOutDir)
Paul Duffin709e0e32021-03-22 10:09:02 +0000879 re := regexp.MustCompile(`\Q` + outSoongDir + `\E\b`)
880 s = re.ReplaceAllString(s, "out/soong")
881
Colin Cross3b1c6842024-07-26 11:52:57 -0700882 // Replace any usage of the outDir/.. with out, e.g. replace "/tmp/testFoo2345" with
Paul Duffin709e0e32021-03-22 10:09:02 +0000883 // "out". This must come after the previous replacement otherwise this would replace
884 // "/tmp/testFoo2345/001" with "out/001" instead of "out/soong".
885 outDir := filepath.Dir(outSoongDir)
886 re = regexp.MustCompile(`\Q` + outDir + `\E\b`)
887 s = re.ReplaceAllString(s, "out")
888
889 return s
890}
891
892// normalizeStringArrayRelativeToTop creates a new slice constructed by applying
893// normalizeStringRelativeToTop to each item in the slice.
894func normalizeStringArrayRelativeToTop(config Config, slice []string) []string {
895 newSlice := make([]string, len(slice))
896 for i, s := range slice {
897 newSlice[i] = normalizeStringRelativeToTop(config, s)
898 }
899 return newSlice
900}
901
902// normalizeStringMapRelativeToTop creates a new map constructed by applying
903// normalizeStringRelativeToTop to each value in the map.
904func normalizeStringMapRelativeToTop(config Config, m map[string]string) map[string]string {
905 newMap := map[string]string{}
906 for k, v := range m {
907 newMap[k] = normalizeStringRelativeToTop(config, v)
908 }
909 return newMap
Paul Duffin0eda26b92021-03-22 09:34:29 +0000910}
911
912func (b baseTestingComponent) newTestingBuildParams(bparams BuildParams) TestingBuildParams {
Colin Cross4c83e5c2019-02-25 14:54:28 -0800913 return TestingBuildParams{
Paul Duffin709e0e32021-03-22 10:09:02 +0000914 config: b.config,
Colin Cross4c83e5c2019-02-25 14:54:28 -0800915 BuildParams: bparams,
Paul Duffin0eda26b92021-03-22 09:34:29 +0000916 RuleParams: b.provider.RuleParamsForTests()[bparams.Rule],
Paul Duffine8366da2021-03-24 10:40:38 +0000917 }.RelativeToTop()
Colin Cross4c83e5c2019-02-25 14:54:28 -0800918}
919
Paul Duffin0eda26b92021-03-22 09:34:29 +0000920func (b baseTestingComponent) maybeBuildParamsFromRule(rule string) (TestingBuildParams, []string) {
Thiébaud Weksteen3600b802020-08-27 15:50:24 +0200921 var searchedRules []string
Paul Duffin4dbf6cf2021-06-08 10:06:37 +0100922 buildParams := b.provider.BuildParamsForTests()
923 for _, p := range buildParams {
924 ruleAsString := p.Rule.String()
925 searchedRules = append(searchedRules, ruleAsString)
926 if strings.Contains(ruleAsString, rule) {
Paul Duffin0eda26b92021-03-22 09:34:29 +0000927 return b.newTestingBuildParams(p), searchedRules
Colin Cross4c83e5c2019-02-25 14:54:28 -0800928 }
929 }
Thiébaud Weksteen3600b802020-08-27 15:50:24 +0200930 return TestingBuildParams{}, searchedRules
Colin Cross4c83e5c2019-02-25 14:54:28 -0800931}
932
Paul Duffin0eda26b92021-03-22 09:34:29 +0000933func (b baseTestingComponent) buildParamsFromRule(rule string) TestingBuildParams {
934 p, searchRules := b.maybeBuildParamsFromRule(rule)
Colin Cross4c83e5c2019-02-25 14:54:28 -0800935 if p.Rule == nil {
Colin Cross90607e92025-02-11 14:58:07 -0800936 b.t.Fatalf("couldn't find rule %q.\nall rules:\n%s", rule, strings.Join(searchRules, "\n"))
Colin Cross4c83e5c2019-02-25 14:54:28 -0800937 }
938 return p
939}
940
Martin Stjernholm827ba622022-02-03 00:20:11 +0000941func (b baseTestingComponent) maybeBuildParamsFromDescription(desc string) (TestingBuildParams, []string) {
942 var searchedDescriptions []string
Paul Duffin0eda26b92021-03-22 09:34:29 +0000943 for _, p := range b.provider.BuildParamsForTests() {
Martin Stjernholm827ba622022-02-03 00:20:11 +0000944 searchedDescriptions = append(searchedDescriptions, p.Description)
Colin Crossb88b3c52019-06-10 15:15:17 -0700945 if strings.Contains(p.Description, desc) {
Martin Stjernholm827ba622022-02-03 00:20:11 +0000946 return b.newTestingBuildParams(p), searchedDescriptions
Colin Cross4c83e5c2019-02-25 14:54:28 -0800947 }
948 }
Martin Stjernholm827ba622022-02-03 00:20:11 +0000949 return TestingBuildParams{}, searchedDescriptions
Colin Cross4c83e5c2019-02-25 14:54:28 -0800950}
951
Paul Duffin0eda26b92021-03-22 09:34:29 +0000952func (b baseTestingComponent) buildParamsFromDescription(desc string) TestingBuildParams {
Martin Stjernholm827ba622022-02-03 00:20:11 +0000953 p, searchedDescriptions := b.maybeBuildParamsFromDescription(desc)
Colin Cross4c83e5c2019-02-25 14:54:28 -0800954 if p.Rule == nil {
Colin Cross90607e92025-02-11 14:58:07 -0800955 b.t.Fatalf("couldn't find description %q\nall descriptions:\n%s", desc, strings.Join(searchedDescriptions, "\n"))
Colin Cross4c83e5c2019-02-25 14:54:28 -0800956 }
957 return p
958}
959
Paul Duffin0eda26b92021-03-22 09:34:29 +0000960func (b baseTestingComponent) maybeBuildParamsFromOutput(file string) (TestingBuildParams, []string) {
Martin Stjernholma4aaa472021-09-17 02:51:48 +0100961 searchedOutputs := WritablePaths(nil)
Paul Duffin0eda26b92021-03-22 09:34:29 +0000962 for _, p := range b.provider.BuildParamsForTests() {
Colin Cross4c83e5c2019-02-25 14:54:28 -0800963 outputs := append(WritablePaths(nil), p.Outputs...)
Colin Cross1d2cf042019-03-29 15:33:06 -0700964 outputs = append(outputs, p.ImplicitOutputs...)
Colin Cross4c83e5c2019-02-25 14:54:28 -0800965 if p.Output != nil {
966 outputs = append(outputs, p.Output)
967 }
968 for _, f := range outputs {
Paul Duffin4e6e35c2021-03-22 11:34:57 +0000969 if f.String() == file || f.Rel() == file || PathRelativeToTop(f) == file {
Paul Duffin0eda26b92021-03-22 09:34:29 +0000970 return b.newTestingBuildParams(p), nil
Colin Cross4c83e5c2019-02-25 14:54:28 -0800971 }
Martin Stjernholma4aaa472021-09-17 02:51:48 +0100972 searchedOutputs = append(searchedOutputs, f)
Colin Cross4c83e5c2019-02-25 14:54:28 -0800973 }
974 }
Martin Stjernholma4aaa472021-09-17 02:51:48 +0100975
976 formattedOutputs := []string{}
977 for _, f := range searchedOutputs {
978 formattedOutputs = append(formattedOutputs,
979 fmt.Sprintf("%s (rel=%s)", PathRelativeToTop(f), f.Rel()))
980 }
981
982 return TestingBuildParams{}, formattedOutputs
Colin Cross4c83e5c2019-02-25 14:54:28 -0800983}
984
Paul Duffin0eda26b92021-03-22 09:34:29 +0000985func (b baseTestingComponent) buildParamsFromOutput(file string) TestingBuildParams {
986 p, searchedOutputs := b.maybeBuildParamsFromOutput(file)
Colin Cross4c83e5c2019-02-25 14:54:28 -0800987 if p.Rule == nil {
Colin Cross90607e92025-02-11 14:58:07 -0800988 b.t.Fatalf("couldn't find output %q.\nall outputs:\n %s\n",
989 file, strings.Join(searchedOutputs, "\n "))
Colin Cross4c83e5c2019-02-25 14:54:28 -0800990 }
991 return p
992}
993
Paul Duffin0eda26b92021-03-22 09:34:29 +0000994func (b baseTestingComponent) allOutputs() []string {
Colin Cross4c83e5c2019-02-25 14:54:28 -0800995 var outputFullPaths []string
Paul Duffin0eda26b92021-03-22 09:34:29 +0000996 for _, p := range b.provider.BuildParamsForTests() {
Jiakai Zhangcf61e3c2023-05-08 16:28:38 +0000997 outputFullPaths = append(outputFullPaths, allOutputs(p)...)
Colin Cross4c83e5c2019-02-25 14:54:28 -0800998 }
999 return outputFullPaths
1000}
1001
Paul Duffin31a22882021-03-22 09:29:00 +00001002// MaybeRule finds a call to ctx.Build with BuildParams.Rule set to a rule with the given name. Returns an empty
1003// BuildParams if no rule is found.
1004func (b baseTestingComponent) MaybeRule(rule string) TestingBuildParams {
Paul Duffin0eda26b92021-03-22 09:34:29 +00001005 r, _ := b.maybeBuildParamsFromRule(rule)
Paul Duffin31a22882021-03-22 09:29:00 +00001006 return r
1007}
1008
1009// Rule finds a call to ctx.Build with BuildParams.Rule set to a rule with the given name. Panics if no rule is found.
1010func (b baseTestingComponent) Rule(rule string) TestingBuildParams {
Paul Duffin0eda26b92021-03-22 09:34:29 +00001011 return b.buildParamsFromRule(rule)
Paul Duffin31a22882021-03-22 09:29:00 +00001012}
1013
1014// MaybeDescription finds a call to ctx.Build with BuildParams.Description set to a the given string. Returns an empty
1015// BuildParams if no rule is found.
1016func (b baseTestingComponent) MaybeDescription(desc string) TestingBuildParams {
Martin Stjernholm827ba622022-02-03 00:20:11 +00001017 p, _ := b.maybeBuildParamsFromDescription(desc)
1018 return p
Paul Duffin31a22882021-03-22 09:29:00 +00001019}
1020
1021// Description finds a call to ctx.Build with BuildParams.Description set to a the given string. Panics if no rule is
1022// found.
1023func (b baseTestingComponent) Description(desc string) TestingBuildParams {
Paul Duffin0eda26b92021-03-22 09:34:29 +00001024 return b.buildParamsFromDescription(desc)
Paul Duffin31a22882021-03-22 09:29:00 +00001025}
1026
1027// MaybeOutput finds a call to ctx.Build with a BuildParams.Output or BuildParams.Outputs whose String() or Rel()
1028// value matches the provided string. Returns an empty BuildParams if no rule is found.
1029func (b baseTestingComponent) MaybeOutput(file string) TestingBuildParams {
Paul Duffin0eda26b92021-03-22 09:34:29 +00001030 p, _ := b.maybeBuildParamsFromOutput(file)
Paul Duffin31a22882021-03-22 09:29:00 +00001031 return p
1032}
1033
1034// Output finds a call to ctx.Build with a BuildParams.Output or BuildParams.Outputs whose String() or Rel()
1035// value matches the provided string. Panics if no rule is found.
1036func (b baseTestingComponent) Output(file string) TestingBuildParams {
Paul Duffin0eda26b92021-03-22 09:34:29 +00001037 return b.buildParamsFromOutput(file)
Paul Duffin31a22882021-03-22 09:29:00 +00001038}
1039
1040// AllOutputs returns all 'BuildParams.Output's and 'BuildParams.Outputs's in their full path string forms.
1041func (b baseTestingComponent) AllOutputs() []string {
Paul Duffin0eda26b92021-03-22 09:34:29 +00001042 return b.allOutputs()
Paul Duffin31a22882021-03-22 09:29:00 +00001043}
1044
Colin Crossb77ffc42019-01-05 22:09:19 -08001045// TestingModule is wrapper around an android.Module that provides methods to find information about individual
1046// ctx.Build parameters for verification in tests.
Colin Crosscec81712017-07-13 14:43:27 -07001047type TestingModule struct {
Paul Duffin31a22882021-03-22 09:29:00 +00001048 baseTestingComponent
Colin Crosscec81712017-07-13 14:43:27 -07001049 module Module
1050}
1051
Colin Cross90607e92025-02-11 14:58:07 -08001052func newTestingModule(t *testing.T, config Config, module Module) TestingModule {
Paul Duffin31a22882021-03-22 09:29:00 +00001053 return TestingModule{
Colin Cross90607e92025-02-11 14:58:07 -08001054 newBaseTestingComponent(t, config, module),
Paul Duffin31a22882021-03-22 09:29:00 +00001055 module,
1056 }
1057}
1058
Colin Crossb77ffc42019-01-05 22:09:19 -08001059// Module returns the Module wrapped by the TestingModule.
Colin Crosscec81712017-07-13 14:43:27 -07001060func (m TestingModule) Module() Module {
1061 return m.module
1062}
1063
Paul Duffin97d8b402021-03-22 16:04:50 +00001064// VariablesForTestsRelativeToTop returns a copy of the Module.VariablesForTests() with every value
1065// having any temporary build dir usages replaced with paths relative to a notional top.
1066func (m TestingModule) VariablesForTestsRelativeToTop() map[string]string {
1067 return normalizeStringMapRelativeToTop(m.config, m.module.VariablesForTests())
1068}
1069
mrziwangd38e63d2024-07-15 13:43:37 -07001070// OutputFiles checks if module base outputFiles property has any output
mrziwange81e77a2024-06-13 17:02:59 -07001071// files can be used to return.
mrziwangd38e63d2024-07-15 13:43:37 -07001072// Exits the test immediately if there is an error and
mrziwange81e77a2024-06-13 17:02:59 -07001073// otherwise returns the result of calling Paths.RelativeToTop
Paul Duffin962783a2021-03-29 00:00:17 +01001074// on the returned Paths.
Yu Liu51c22312024-08-20 23:56:15 +00001075func (m TestingModule) OutputFiles(ctx *TestContext, t *testing.T, tag string) Paths {
1076 outputFiles := OtherModuleProviderOrDefault(ctx.OtherModuleProviderAdaptor(), m.Module(), OutputFilesProvider)
mrziwangabdb2932024-06-18 12:43:41 -07001077 if tag == "" && outputFiles.DefaultOutputFiles != nil {
1078 return outputFiles.DefaultOutputFiles.RelativeToTop()
1079 } else if taggedOutputFiles, hasTag := outputFiles.TaggedOutputFiles[tag]; hasTag {
mrziwangd38e63d2024-07-15 13:43:37 -07001080 return taggedOutputFiles.RelativeToTop()
mrziwange81e77a2024-06-13 17:02:59 -07001081 }
1082
mrziwangd38e63d2024-07-15 13:43:37 -07001083 t.Fatal(fmt.Errorf("No test output file has been set for tag %q", tag))
1084 return nil
Paul Duffin962783a2021-03-29 00:00:17 +01001085}
1086
Colin Cross4c83e5c2019-02-25 14:54:28 -08001087// TestingSingleton is wrapper around an android.Singleton that provides methods to find information about individual
1088// ctx.Build parameters for verification in tests.
1089type TestingSingleton struct {
Paul Duffin31a22882021-03-22 09:29:00 +00001090 baseTestingComponent
Colin Cross4c83e5c2019-02-25 14:54:28 -08001091 singleton Singleton
Colin Cross4c83e5c2019-02-25 14:54:28 -08001092}
1093
1094// Singleton returns the Singleton wrapped by the TestingSingleton.
1095func (s TestingSingleton) Singleton() Singleton {
1096 return s.singleton
1097}
1098
Logan Chien42039712018-03-12 16:29:17 +08001099func FailIfErrored(t *testing.T, errs []error) {
1100 t.Helper()
1101 if len(errs) > 0 {
1102 for _, err := range errs {
1103 t.Error(err)
1104 }
1105 t.FailNow()
1106 }
1107}
Logan Chienee97c3e2018-03-12 16:34:26 +08001108
Paul Duffinea8a3862021-03-04 17:58:33 +00001109// Fail if no errors that matched the regular expression were found.
1110//
1111// Returns true if a matching error was found, false otherwise.
1112func FailIfNoMatchingErrors(t *testing.T, pattern string, errs []error) bool {
Logan Chienee97c3e2018-03-12 16:34:26 +08001113 t.Helper()
1114
1115 matcher, err := regexp.Compile(pattern)
1116 if err != nil {
Paul Duffinea8a3862021-03-04 17:58:33 +00001117 t.Fatalf("failed to compile regular expression %q because %s", pattern, err)
Logan Chienee97c3e2018-03-12 16:34:26 +08001118 }
1119
1120 found := false
1121 for _, err := range errs {
1122 if matcher.FindStringIndex(err.Error()) != nil {
1123 found = true
1124 break
1125 }
1126 }
1127 if !found {
Steven Moreland082e2062022-08-30 01:11:11 +00001128 t.Errorf("could not match the expected error regex %q (checked %d error(s))", pattern, len(errs))
Logan Chienee97c3e2018-03-12 16:34:26 +08001129 for i, err := range errs {
Colin Crossaede88c2020-08-11 12:17:01 -07001130 t.Errorf("errs[%d] = %q", i, err)
Logan Chienee97c3e2018-03-12 16:34:26 +08001131 }
1132 }
Paul Duffinea8a3862021-03-04 17:58:33 +00001133
1134 return found
Logan Chienee97c3e2018-03-12 16:34:26 +08001135}
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -07001136
Paul Duffin91e38192019-08-05 15:07:57 +01001137func CheckErrorsAgainstExpectations(t *testing.T, errs []error, expectedErrorPatterns []string) {
1138 t.Helper()
1139
1140 if expectedErrorPatterns == nil {
1141 FailIfErrored(t, errs)
1142 } else {
1143 for _, expectedError := range expectedErrorPatterns {
1144 FailIfNoMatchingErrors(t, expectedError, errs)
1145 }
1146 if len(errs) > len(expectedErrorPatterns) {
1147 t.Errorf("additional errors found, expected %d, found %d",
1148 len(expectedErrorPatterns), len(errs))
1149 for i, expectedError := range expectedErrorPatterns {
1150 t.Errorf("expectedErrors[%d] = %s", i, expectedError)
1151 }
1152 for i, err := range errs {
1153 t.Errorf("errs[%d] = %s", i, err)
1154 }
Paul Duffinea8a3862021-03-04 17:58:33 +00001155 t.FailNow()
Paul Duffin91e38192019-08-05 15:07:57 +01001156 }
1157 }
Paul Duffin91e38192019-08-05 15:07:57 +01001158}
1159
Jingwen Chencda22c92020-11-23 00:22:30 -05001160func SetKatiEnabledForTests(config Config) {
1161 config.katiEnabled = true
Paul Duffin8c3fec42020-03-04 20:15:08 +00001162}
1163
Colin Crossaa255532020-07-03 13:18:24 -07001164func AndroidMkEntriesForTest(t *testing.T, ctx *TestContext, mod blueprint.Module) []AndroidMkEntries {
Liz Kammer6be69062022-11-04 16:06:02 -04001165 t.Helper()
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -07001166 var p AndroidMkEntriesProvider
1167 var ok bool
1168 if p, ok = mod.(AndroidMkEntriesProvider); !ok {
Justin Yunf5ed2be2024-12-18 17:50:43 +09001169 t.Error("module does not implement AndroidMkEntriesProvider: " + mod.Name())
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -07001170 }
Jiyong Park0b0e1b92019-12-03 13:24:29 +09001171
1172 entriesList := p.AndroidMkEntries()
LaMont Jonesb5099382024-01-10 23:42:36 +00001173 aconfigUpdateAndroidMkEntries(ctx, mod.(Module), &entriesList)
Jihoon Kanga3a05462024-04-05 00:36:44 +00001174 for i := range entriesList {
Colin Crossaa255532020-07-03 13:18:24 -07001175 entriesList[i].fillInEntries(ctx, mod)
Jiyong Park0b0e1b92019-12-03 13:24:29 +09001176 }
1177 return entriesList
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -07001178}
Jooyung Han12df5fb2019-07-11 16:18:47 +09001179
Yu Liue70976d2024-10-15 20:45:35 +00001180func AndroidMkInfoForTest(t *testing.T, ctx *TestContext, mod blueprint.Module) *AndroidMkProviderInfo {
1181 if runtime.GOOS == "darwin" && mod.(Module).base().Os() != Darwin {
1182 // The AndroidMkInfo provider is not set in this case.
1183 t.Skip("AndroidMkInfo provider is not set on darwin")
1184 }
1185
1186 t.Helper()
1187 var ok bool
1188 if _, ok = mod.(AndroidMkProviderInfoProducer); !ok {
Justin Yunf5ed2be2024-12-18 17:50:43 +09001189 t.Error("module does not implement AndroidMkProviderInfoProducer: " + mod.Name())
Yu Liue70976d2024-10-15 20:45:35 +00001190 }
1191
1192 info := OtherModuleProviderOrDefault(ctx, mod, AndroidMkInfoProvider)
1193 aconfigUpdateAndroidMkInfos(ctx, mod.(Module), info)
1194 info.PrimaryInfo.fillInEntries(ctx, mod)
1195 if len(info.ExtraInfo) > 0 {
1196 for _, ei := range info.ExtraInfo {
1197 ei.fillInEntries(ctx, mod)
1198 }
1199 }
1200
1201 return info
1202}
1203
Colin Crossaa255532020-07-03 13:18:24 -07001204func AndroidMkDataForTest(t *testing.T, ctx *TestContext, mod blueprint.Module) AndroidMkData {
Liz Kammer6be69062022-11-04 16:06:02 -04001205 t.Helper()
Jooyung Han12df5fb2019-07-11 16:18:47 +09001206 var p AndroidMkDataProvider
1207 var ok bool
1208 if p, ok = mod.(AndroidMkDataProvider); !ok {
Justin Yunf5ed2be2024-12-18 17:50:43 +09001209 t.Fatal("module does not implement AndroidMkDataProvider: " + mod.Name())
Jooyung Han12df5fb2019-07-11 16:18:47 +09001210 }
1211 data := p.AndroidMk()
Colin Crossaa255532020-07-03 13:18:24 -07001212 data.fillInData(ctx, mod)
LaMont Jonesb5099382024-01-10 23:42:36 +00001213 aconfigUpdateAndroidMkData(ctx, mod.(Module), &data)
Jooyung Han12df5fb2019-07-11 16:18:47 +09001214 return data
1215}
Paul Duffin9b478b02019-12-10 13:41:51 +00001216
1217// Normalize the path for testing.
1218//
1219// If the path is relative to the build directory then return the relative path
1220// to avoid tests having to deal with the dynamically generated build directory.
1221//
1222// Otherwise, return the supplied path as it is almost certainly a source path
1223// that is relative to the root of the source tree.
1224//
1225// The build and source paths should be distinguishable based on their contents.
Paul Duffin567465d2021-03-16 01:21:34 +00001226//
1227// deprecated: use PathRelativeToTop instead as it handles make install paths and differentiates
1228// between output and source properly.
Paul Duffin9b478b02019-12-10 13:41:51 +00001229func NormalizePathForTesting(path Path) string {
Paul Duffin064b70c2020-11-02 17:32:38 +00001230 if path == nil {
1231 return "<nil path>"
1232 }
Paul Duffin9b478b02019-12-10 13:41:51 +00001233 p := path.String()
1234 if w, ok := path.(WritablePath); ok {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001235 rel, err := filepath.Rel(w.getSoongOutDir(), p)
Paul Duffin9b478b02019-12-10 13:41:51 +00001236 if err != nil {
1237 panic(err)
1238 }
1239 return rel
1240 }
1241 return p
1242}
1243
Paul Duffin567465d2021-03-16 01:21:34 +00001244// NormalizePathsForTesting creates a slice of strings where each string is the result of applying
1245// NormalizePathForTesting to the corresponding Path in the input slice.
1246//
1247// deprecated: use PathsRelativeToTop instead as it handles make install paths and differentiates
1248// between output and source properly.
Paul Duffin9b478b02019-12-10 13:41:51 +00001249func NormalizePathsForTesting(paths Paths) []string {
1250 var result []string
1251 for _, path := range paths {
1252 relative := NormalizePathForTesting(path)
1253 result = append(result, relative)
1254 }
1255 return result
1256}
Paul Duffin567465d2021-03-16 01:21:34 +00001257
1258// PathRelativeToTop returns a string representation of the path relative to a notional top
1259// directory.
1260//
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001261// It return "<nil path>" if the supplied path is nil, otherwise it returns the result of calling
1262// Path.RelativeToTop to obtain a relative Path and then calling Path.String on that to get the
1263// string representation.
Paul Duffin567465d2021-03-16 01:21:34 +00001264func PathRelativeToTop(path Path) string {
1265 if path == nil {
1266 return "<nil path>"
1267 }
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001268 return path.RelativeToTop().String()
Paul Duffin567465d2021-03-16 01:21:34 +00001269}
1270
1271// PathsRelativeToTop creates a slice of strings where each string is the result of applying
1272// PathRelativeToTop to the corresponding Path in the input slice.
1273func PathsRelativeToTop(paths Paths) []string {
1274 var result []string
1275 for _, path := range paths {
1276 relative := PathRelativeToTop(path)
1277 result = append(result, relative)
1278 }
1279 return result
1280}
1281
1282// StringPathRelativeToTop returns a string representation of the path relative to a notional top
1283// directory.
1284//
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001285// See Path.RelativeToTop for more details as to what `relative to top` means.
Paul Duffin567465d2021-03-16 01:21:34 +00001286//
1287// This is provided for processing paths that have already been converted into a string, e.g. paths
1288// in AndroidMkEntries structures. As a result it needs to be supplied the soong output dir against
1289// which it can try and relativize paths. PathRelativeToTop must be used for process Path objects.
1290func StringPathRelativeToTop(soongOutDir string, path string) string {
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001291 ensureTestOnly()
Paul Duffin567465d2021-03-16 01:21:34 +00001292
1293 // A relative path must be a source path so leave it as it is.
1294 if !filepath.IsAbs(path) {
1295 return path
1296 }
1297
1298 // Check to see if the path is relative to the soong out dir.
1299 rel, isRel, err := maybeRelErr(soongOutDir, path)
1300 if err != nil {
1301 panic(err)
1302 }
1303
1304 if isRel {
Colin Cross3b1c6842024-07-26 11:52:57 -07001305 if strings.HasSuffix(soongOutDir, testOutSoongSubDir) {
1306 // The path is in the soong out dir so indicate that in the relative path.
1307 return filepath.Join(TestOutSoongDir, rel)
1308 } else {
1309 // Handle the PathForArbitraryOutput case
1310 return filepath.Join(testOutDir, rel)
1311
1312 }
Paul Duffin567465d2021-03-16 01:21:34 +00001313 }
1314
1315 // Check to see if the path is relative to the top level out dir.
1316 outDir := filepath.Dir(soongOutDir)
1317 rel, isRel, err = maybeRelErr(outDir, path)
1318 if err != nil {
1319 panic(err)
1320 }
1321
1322 if isRel {
1323 // The path is in the out dir so indicate that in the relative path.
1324 return filepath.Join("out", rel)
1325 }
1326
1327 // This should never happen.
1328 panic(fmt.Errorf("internal error: absolute path %s is not relative to the out dir %s", path, outDir))
1329}
1330
1331// StringPathsRelativeToTop creates a slice of strings where each string is the result of applying
1332// StringPathRelativeToTop to the corresponding string path in the input slice.
1333//
1334// This is provided for processing paths that have already been converted into a string, e.g. paths
1335// in AndroidMkEntries structures. As a result it needs to be supplied the soong output dir against
1336// which it can try and relativize paths. PathsRelativeToTop must be used for process Paths objects.
1337func StringPathsRelativeToTop(soongOutDir string, paths []string) []string {
1338 var result []string
1339 for _, path := range paths {
1340 relative := StringPathRelativeToTop(soongOutDir, path)
1341 result = append(result, relative)
1342 }
1343 return result
1344}
Paul Duffinf53555d2021-03-29 00:21:00 +01001345
1346// StringRelativeToTop will normalize a string containing paths, e.g. ninja command, by replacing
1347// any references to the test specific temporary build directory that changes with each run to a
1348// fixed path relative to a notional top directory.
1349//
1350// This is similar to StringPathRelativeToTop except that assumes the string is a single path
1351// containing at most one instance of the temporary build directory at the start of the path while
1352// this assumes that there can be any number at any position.
1353func StringRelativeToTop(config Config, command string) string {
1354 return normalizeStringRelativeToTop(config, command)
1355}
Paul Duffin0aafcbf2021-03-29 00:56:32 +01001356
1357// StringsRelativeToTop will return a new slice such that each item in the new slice is the result
1358// of calling StringRelativeToTop on the corresponding item in the input slice.
1359func StringsRelativeToTop(config Config, command []string) []string {
1360 return normalizeStringArrayRelativeToTop(config, command)
1361}
Yu Liueae7b362023-11-16 17:05:47 -08001362
1363func EnsureListContainsSuffix(t *testing.T, result []string, expected string) {
1364 t.Helper()
1365 if !SuffixInList(result, expected) {
1366 t.Errorf("%q is not found in %v", expected, result)
1367 }
1368}
Cole Fausta963b942024-04-11 17:43:00 -07001369
1370type panickingConfigAndErrorContext struct {
1371 ctx *TestContext
1372}
1373
1374func (ctx *panickingConfigAndErrorContext) OtherModulePropertyErrorf(module Module, property, fmt string, args ...interface{}) {
1375 panic(ctx.ctx.PropertyErrorf(module, property, fmt, args...).Error())
1376}
1377
1378func (ctx *panickingConfigAndErrorContext) Config() Config {
1379 return ctx.ctx.Config()
1380}
1381
Cole Faust4e2bf9f2024-09-11 13:26:20 -07001382func (ctx *panickingConfigAndErrorContext) HasMutatorFinished(mutatorName string) bool {
1383 return ctx.ctx.HasMutatorFinished(mutatorName)
1384}
1385
Cole Faust55b56fe2024-08-23 12:06:11 -07001386func (ctx *panickingConfigAndErrorContext) otherModuleProvider(m blueprint.Module, p blueprint.AnyProviderKey) (any, bool) {
1387 return ctx.ctx.otherModuleProvider(m, p)
1388}
1389
Cole Fauste8a87832024-09-11 11:35:46 -07001390func PanickingConfigAndErrorContext(ctx *TestContext) ConfigurableEvaluatorContext {
Cole Fausta963b942024-04-11 17:43:00 -07001391 return &panickingConfigAndErrorContext{
1392 ctx: ctx,
1393 }
1394}