• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Copyright 2017 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package android
16
17import (
18	"bytes"
19	"fmt"
20	"path/filepath"
21	"regexp"
22	"runtime"
23	"sort"
24	"strings"
25	"sync"
26	"testing"
27
28	mkparser "android/soong/androidmk/parser"
29
30	"github.com/google/blueprint"
31	"github.com/google/blueprint/proptools"
32)
33
34func newTestContextForFixture(config Config) *TestContext {
35	ctx := &TestContext{
36		Context: &Context{blueprint.NewContext(), config},
37	}
38
39	ctx.postDeps = append(ctx.postDeps, registerPathDepsMutator)
40
41	ctx.SetFs(ctx.config.fs)
42	if ctx.config.mockBpList != "" {
43		ctx.SetModuleListFile(ctx.config.mockBpList)
44	}
45
46	return ctx
47}
48
49func 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
59var PrepareForTestWithArchMutator = GroupFixturePreparers(
60	// 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
83var PrepareForTestWithLicenses = GroupFixturePreparers(
84	FixtureRegisterWithContext(RegisterLicenseKindBuildComponents),
85	FixtureRegisterWithContext(RegisterLicenseBuildComponents),
86	FixtureRegisterWithContext(registerLicenseMutators),
87)
88
89var PrepareForTestWithGenNotice = FixtureRegisterWithContext(RegisterGenNoticeBuildComponents)
90
91func 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
121var PrepareForTestWithNamespace = FixtureRegisterWithContext(func(ctx RegistrationContext) {
122	registerNamespaceBuildComponents(ctx)
123	ctx.PreArchMutators(RegisterNamespaceMutator)
124})
125
126var PrepareForTestWithMakevars = FixtureRegisterWithContext(func(ctx RegistrationContext) {
127	ctx.RegisterSingletonType("makevars", makeVarsSingletonFunc)
128})
129
130var PrepareForTestVintfFragmentModules = FixtureRegisterWithContext(func(ctx RegistrationContext) {
131	registerVintfFragmentComponents(ctx)
132})
133
134// 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(
147	// Sorted alphabetically as the actual order does not matter as tests automatically enforce the
148	// correct order.
149	PrepareForTestWithArchMutator,
150	PrepareForTestWithComponentsMutator,
151	PrepareForTestWithDefaults,
152	PrepareForTestWithFilegroup,
153	PrepareForTestWithOverrides,
154	PrepareForTestWithPackageModule,
155	PrepareForTestWithPrebuilts,
156	PrepareForTestWithVisibility,
157	PrepareForTestVintfFragmentModules,
158)
159
160// 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
167// 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
178// Prepares a test that disallows non-existent paths.
179var PrepareForTestDisallowNonExistentPaths = FixtureModifyConfig(func(config Config) {
180	config.TestAllowNonExistentPaths = false
181})
182
183// 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
193// 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
213func NewTestArchContext(config Config) *TestContext {
214	ctx := NewTestContext(config)
215	ctx.preDeps = append(ctx.preDeps, registerArchMutator)
216	return ctx
217}
218
219type TestContext struct {
220	*Context
221	preArch, preDeps, postDeps, postApex, finalDeps []RegisterMutatorFunc
222	NameResolver                                    *NameResolver
223
224	// The list of singletons registered for the test.
225	singletons sortableComponents
226
227	// The order in which the mutators and singletons will be run in this test
228	// context; for debugging.
229	mutatorOrder, singletonOrder []string
230}
231
232func (ctx *TestContext) PreArchMutators(f RegisterMutatorFunc) {
233	ctx.preArch = append(ctx.preArch, f)
234}
235
236func (ctx *TestContext) HardCodedPreArchMutators(f RegisterMutatorFunc) {
237	// Register mutator function as normal for testing.
238	ctx.PreArchMutators(f)
239}
240
241func (ctx *TestContext) otherModuleProvider(m blueprint.Module, p blueprint.AnyProviderKey) (any, bool) {
242	return ctx.Context.ModuleProvider(m, p)
243}
244
245func (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
253func (ctx *TestContext) PostApexMutators(f RegisterMutatorFunc) {
254	ctx.postApex = append(ctx.postApex, f)
255}
256
257func (ctx *TestContext) FinalDepsMutators(f RegisterMutatorFunc) {
258	ctx.finalDeps = append(ctx.finalDeps, f)
259}
260
261func (ctx *TestContext) OtherModuleProviderAdaptor() OtherModuleProviderContext {
262	return NewOtherModuleProviderAdaptor(func(module blueprint.Module, provider blueprint.AnyProviderKey) (any, bool) {
263		return ctx.otherModuleProvider(module, provider)
264	})
265}
266
267func (ctx *TestContext) OtherModulePropertyErrorf(module Module, property string, fmt_ string, args ...interface{}) {
268	panic(fmt.Sprintf(fmt_, args...))
269}
270
271// 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
441
442	// The order of singletons
443	singletonOrder registeredComponentOrder
444}
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)
454
455		// Create an ordering from the globally registered singletons.
456		globallyRegisteredSingletons := collateGloballyRegisteredSingletons()
457		s.singletonOrder = registeredComponentOrderFromExistingOrder("singleton", globallyRegisteredSingletons)
458	})
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
474func (ctx *TestContext) Register() {
475	globalOrder := globallyRegisteredComponentsOrder()
476
477	mutators := collateRegisteredMutators(ctx.preArch, ctx.preDeps, ctx.postDeps, ctx.postApex, ctx.finalDeps)
478	// Ensure that the mutators used in the test are in the same order as they are used at runtime.
479	globalOrder.mutatorOrder.enforceOrdering(mutators)
480	mutators.registerAll(ctx.Context)
481
482	// 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)
484	ctx.singletons.registerAll(ctx.Context)
485
486	// Save the sorted components order away to make them easy to access while debugging.
487	ctx.mutatorOrder = componentsToNames(mutators)
488	ctx.singletonOrder = componentsToNames(singletons)
489}
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)
501}
502
503func (ctx *TestContext) RegisterModuleType(name string, factory ModuleFactory) {
504	ctx.Context.RegisterModuleType(name, ModuleFactoryAdaptor(factory))
505}
506
507func (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
513func (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
519func (ctx *TestContext) RegisterSingletonType(name string, factory SingletonFactory) {
520	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))
525}
526
527// 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.
533func (ctx *TestContext) ModuleVariantForTests(t *testing.T, name string, matchVariations map[string]string) TestingModule {
534	t.Helper()
535	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 {
566			t.Fatalf("failed to find module %q. All modules:\n  %s",
567				name, strings.Join(SortedUniqueStrings(allModuleNames), "\n  "))
568		} else {
569			sort.Strings(allVariants)
570			t.Fatalf("failed to find module %q matching %v. All variants:\n  %s",
571				name, matchVariations, strings.Join(allVariants, "\n  "))
572		}
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)
581		t.Fatalf("module %q has more than one variant that match %v:\n  %s",
582			name, matchVariations, strings.Join(moduleStrings, "\n  "))
583	}
584
585	return newTestingModule(t, ctx.config, modules[0])
586}
587
588func (ctx *TestContext) ModuleForTests(t *testing.T, name, variant string) TestingModule {
589	t.Helper()
590	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 {
598		// find all the modules that do exist
599		var allModuleNames []string
600		var allVariants []string
601		ctx.VisitAllModules(func(m blueprint.Module) {
602			allModuleNames = append(allModuleNames, ctx.ModuleName(m))
603			if ctx.ModuleName(m) == name {
604				allVariants = append(allVariants, ctx.ModuleSubDir(m))
605			}
606		})
607		sort.Strings(allVariants)
608
609		if len(allVariants) == 0 {
610			t.Fatalf("failed to find module %q. All modules:\n  %s",
611				name, strings.Join(SortedUniqueStrings(allModuleNames), "\n  "))
612		} else {
613			t.Fatalf("failed to find module %q variant %q. All variants:\n  %s",
614				name, variant, strings.Join(allVariants, "\n  "))
615		}
616	}
617
618	return newTestingModule(t, ctx.config, module)
619}
620
621func (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
631// SingletonForTests returns a TestingSingleton for the singleton registered with the given name.
632func (ctx *TestContext) SingletonForTests(t *testing.T, name string) TestingSingleton {
633	t.Helper()
634	allSingletonNames := []string{}
635	for _, s := range ctx.Singletons() {
636		n := ctx.SingletonName(s)
637		if n == name {
638			return TestingSingleton{
639				baseTestingComponent: newBaseTestingComponent(t, ctx.config, s.(testBuildProvider)),
640				singleton:            s.(*singletonAdaptor).Singleton,
641			}
642		}
643		allSingletonNames = append(allSingletonNames, n)
644	}
645
646	t.Fatalf("failed to find singleton %q."+
647		"\nall singletons: %v", name, allSingletonNames)
648
649	return TestingSingleton{}
650}
651
652type InstallMakeRule struct {
653	Target        string
654	Deps          []string
655	OrderOnlyDeps []string
656}
657
658func parseMkRules(t *testing.T, config Config, nodes []mkparser.Node) []InstallMakeRule {
659	t.Helper()
660	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 {
697	t.Helper()
698	installs := ctx.SingletonForTests(t, "makevars").Singleton().(*makeVarsSingleton).installsForTesting
699	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
710// 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.
738func (ctx *TestContext) MakeVarsForTesting(t *testing.T, filter func(variable MakeVarVariable) bool) []MakeVarVariable {
739	t.Helper()
740	vars := ctx.SingletonForTests(t, "makevars").Singleton().(*makeVarsSingleton).varsForTesting
741	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
751func (ctx *TestContext) Config() Config {
752	return ctx.config
753}
754
755type testBuildProvider interface {
756	BuildParamsForTests() []BuildParams
757	RuleParamsForTests() map[blueprint.Rule]blueprint.RuleParams
758}
759
760type TestingBuildParams struct {
761	BuildParams
762	RuleParams blueprint.RuleParams
763
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
772//   - Args
773//   - All Path, Paths, WritablePath and WritablePaths fields.
774//
775// * RuleParams
776//   - Command
777//   - Depfile
778//   - Rspfile
779//   - RspfileContent
780//   - CommandDeps
781//   - CommandOrderOnly
782//
783// See PathRelativeToTop for more details.
784//
785// deprecated: this is no longer needed as TestingBuildParams are created in this form.
786func (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 {
793		return p
794	}
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
798	bparams.Depfile = normalizeWritablePathRelativeToTop(bparams.Depfile)
799	bparams.Output = normalizeWritablePathRelativeToTop(bparams.Output)
800	bparams.Outputs = bparams.Outputs.RelativeToTop()
801	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()
810	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)
818	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	}
825}
826
827func 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
841func 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
855// baseTestingComponent provides functionality common to both TestingModule and TestingSingleton.
856type baseTestingComponent struct {
857	t        *testing.T
858	config   Config
859	provider testBuildProvider
860}
861
862func newBaseTestingComponent(t *testing.T, config Config, provider testBuildProvider) baseTestingComponent {
863	return baseTestingComponent{t, config, provider}
864}
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 {
874	// The outDir usually looks something like: /tmp/testFoo2345/001
875	//
876	// Replace any usage of the outDir with out/soong, e.g. replace "/tmp/testFoo2345/001" with
877	// "out/soong".
878	outSoongDir := filepath.Clean(config.soongOutDir)
879	re := regexp.MustCompile(`\Q` + outSoongDir + `\E\b`)
880	s = re.ReplaceAllString(s, "out/soong")
881
882	// Replace any usage of the outDir/.. with out, e.g. replace "/tmp/testFoo2345" with
883	// "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
910}
911
912func (b baseTestingComponent) newTestingBuildParams(bparams BuildParams) TestingBuildParams {
913	return TestingBuildParams{
914		config:      b.config,
915		BuildParams: bparams,
916		RuleParams:  b.provider.RuleParamsForTests()[bparams.Rule],
917	}.RelativeToTop()
918}
919
920func (b baseTestingComponent) maybeBuildParamsFromRule(rule string) (TestingBuildParams, []string) {
921	var searchedRules []string
922	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) {
927			return b.newTestingBuildParams(p), searchedRules
928		}
929	}
930	return TestingBuildParams{}, searchedRules
931}
932
933func (b baseTestingComponent) buildParamsFromRule(rule string) TestingBuildParams {
934	b.t.Helper()
935	p, searchRules := b.maybeBuildParamsFromRule(rule)
936	if p.Rule == nil {
937		b.t.Fatalf("couldn't find rule %q.\nall rules:\n%s", rule, strings.Join(searchRules, "\n"))
938	}
939	return p
940}
941
942func (b baseTestingComponent) maybeBuildParamsFromDescription(desc string) (TestingBuildParams, []string) {
943	var searchedDescriptions []string
944	for _, p := range b.provider.BuildParamsForTests() {
945		searchedDescriptions = append(searchedDescriptions, p.Description)
946		if strings.Contains(p.Description, desc) {
947			return b.newTestingBuildParams(p), searchedDescriptions
948		}
949	}
950	return TestingBuildParams{}, searchedDescriptions
951}
952
953func (b baseTestingComponent) buildParamsFromDescription(desc string) TestingBuildParams {
954	b.t.Helper()
955	p, searchedDescriptions := b.maybeBuildParamsFromDescription(desc)
956	if p.Rule == nil {
957		b.t.Fatalf("couldn't find description %q\nall descriptions:\n%s", desc, strings.Join(searchedDescriptions, "\n"))
958	}
959	return p
960}
961
962func (b baseTestingComponent) maybeBuildParamsFromOutput(file string) (TestingBuildParams, []string) {
963	searchedOutputs := WritablePaths(nil)
964	for _, p := range b.provider.BuildParamsForTests() {
965		outputs := append(WritablePaths(nil), p.Outputs...)
966		outputs = append(outputs, p.ImplicitOutputs...)
967		if p.Output != nil {
968			outputs = append(outputs, p.Output)
969		}
970		for _, f := range outputs {
971			if f.String() == file || f.Rel() == file || PathRelativeToTop(f) == file {
972				return b.newTestingBuildParams(p), nil
973			}
974			searchedOutputs = append(searchedOutputs, f)
975		}
976	}
977
978	formattedOutputs := []string{}
979	for _, f := range searchedOutputs {
980		formattedOutputs = append(formattedOutputs,
981			fmt.Sprintf("%s (rel=%s)", PathRelativeToTop(f), f.Rel()))
982	}
983
984	return TestingBuildParams{}, formattedOutputs
985}
986
987func (b baseTestingComponent) buildParamsFromOutput(file string) TestingBuildParams {
988	b.t.Helper()
989	p, searchedOutputs := b.maybeBuildParamsFromOutput(file)
990	if p.Rule == nil {
991		b.t.Fatalf("couldn't find output %q.\nall outputs:\n    %s\n",
992			file, strings.Join(searchedOutputs, "\n    "))
993	}
994	return p
995}
996
997func (b baseTestingComponent) allOutputs() []string {
998	var outputFullPaths []string
999	for _, p := range b.provider.BuildParamsForTests() {
1000		outputFullPaths = append(outputFullPaths, allOutputs(p)...)
1001	}
1002	return outputFullPaths
1003}
1004
1005// MaybeRule finds a call to ctx.Build with BuildParams.Rule set to a rule with the given name.  Returns an empty
1006// BuildParams if no rule is found.
1007func (b baseTestingComponent) MaybeRule(rule string) TestingBuildParams {
1008	r, _ := b.maybeBuildParamsFromRule(rule)
1009	return r
1010}
1011
1012// Rule finds a call to ctx.Build with BuildParams.Rule set to a rule with the given name.  Panics if no rule is found.
1013func (b baseTestingComponent) Rule(rule string) TestingBuildParams {
1014	b.t.Helper()
1015	return b.buildParamsFromRule(rule)
1016}
1017
1018// MaybeDescription finds a call to ctx.Build with BuildParams.Description set to a the given string.  Returns an empty
1019// BuildParams if no rule is found.
1020func (b baseTestingComponent) MaybeDescription(desc string) TestingBuildParams {
1021	p, _ := b.maybeBuildParamsFromDescription(desc)
1022	return p
1023}
1024
1025// Description finds a call to ctx.Build with BuildParams.Description set to a the given string.  Panics if no rule is
1026// found.
1027func (b baseTestingComponent) Description(desc string) TestingBuildParams {
1028	b.t.Helper()
1029	return b.buildParamsFromDescription(desc)
1030}
1031
1032// MaybeOutput finds a call to ctx.Build with a BuildParams.Output or BuildParams.Outputs whose String() or Rel()
1033// value matches the provided string.  Returns an empty BuildParams if no rule is found.
1034func (b baseTestingComponent) MaybeOutput(file string) TestingBuildParams {
1035	p, _ := b.maybeBuildParamsFromOutput(file)
1036	return p
1037}
1038
1039// Output finds a call to ctx.Build with a BuildParams.Output or BuildParams.Outputs whose String() or Rel()
1040// value matches the provided string.  Panics if no rule is found.
1041func (b baseTestingComponent) Output(file string) TestingBuildParams {
1042	b.t.Helper()
1043	return b.buildParamsFromOutput(file)
1044}
1045
1046// AllOutputs returns all 'BuildParams.Output's and 'BuildParams.Outputs's in their full path string forms.
1047func (b baseTestingComponent) AllOutputs() []string {
1048	return b.allOutputs()
1049}
1050
1051// TestingModule is wrapper around an android.Module that provides methods to find information about individual
1052// ctx.Build parameters for verification in tests.
1053type TestingModule struct {
1054	baseTestingComponent
1055	module Module
1056}
1057
1058func newTestingModule(t *testing.T, config Config, module Module) TestingModule {
1059	return TestingModule{
1060		newBaseTestingComponent(t, config, module),
1061		module,
1062	}
1063}
1064
1065// Module returns the Module wrapped by the TestingModule.
1066func (m TestingModule) Module() Module {
1067	return m.module
1068}
1069
1070// VariablesForTestsRelativeToTop returns a copy of the Module.VariablesForTests() with every value
1071// having any temporary build dir usages replaced with paths relative to a notional top.
1072func (m TestingModule) VariablesForTestsRelativeToTop() map[string]string {
1073	return normalizeStringMapRelativeToTop(m.config, m.module.VariablesForTests())
1074}
1075
1076// OutputFiles checks if module base outputFiles property has any output
1077// files can be used to return.
1078// Exits the test immediately if there is an error and
1079// otherwise returns the result of calling Paths.RelativeToTop
1080// on the returned Paths.
1081func (m TestingModule) OutputFiles(ctx *TestContext, t *testing.T, tag string) Paths {
1082	outputFiles := OtherModuleProviderOrDefault(ctx.OtherModuleProviderAdaptor(), m.Module(), OutputFilesProvider)
1083	if tag == "" && outputFiles.DefaultOutputFiles != nil {
1084		return outputFiles.DefaultOutputFiles.RelativeToTop()
1085	} else if taggedOutputFiles, hasTag := outputFiles.TaggedOutputFiles[tag]; hasTag {
1086		return taggedOutputFiles.RelativeToTop()
1087	}
1088
1089	t.Fatal(fmt.Errorf("No test output file has been set for tag %q", tag))
1090	return nil
1091}
1092
1093// TestingSingleton is wrapper around an android.Singleton that provides methods to find information about individual
1094// ctx.Build parameters for verification in tests.
1095type TestingSingleton struct {
1096	baseTestingComponent
1097	singleton Singleton
1098}
1099
1100// Singleton returns the Singleton wrapped by the TestingSingleton.
1101func (s TestingSingleton) Singleton() Singleton {
1102	return s.singleton
1103}
1104
1105func FailIfErrored(t *testing.T, errs []error) {
1106	t.Helper()
1107	if len(errs) > 0 {
1108		for _, err := range errs {
1109			t.Error(err)
1110		}
1111		t.FailNow()
1112	}
1113}
1114
1115// Fail if no errors that matched the regular expression were found.
1116//
1117// Returns true if a matching error was found, false otherwise.
1118func FailIfNoMatchingErrors(t *testing.T, pattern string, errs []error) bool {
1119	t.Helper()
1120
1121	matcher, err := regexp.Compile(pattern)
1122	if err != nil {
1123		t.Fatalf("failed to compile regular expression %q because %s", pattern, err)
1124	}
1125
1126	found := false
1127	for _, err := range errs {
1128		if matcher.FindStringIndex(err.Error()) != nil {
1129			found = true
1130			break
1131		}
1132	}
1133	if !found {
1134		t.Errorf("could not match the expected error regex %q (checked %d error(s))", pattern, len(errs))
1135		for i, err := range errs {
1136			t.Errorf("errs[%d] = %q", i, err)
1137		}
1138	}
1139
1140	return found
1141}
1142
1143func CheckErrorsAgainstExpectations(t *testing.T, errs []error, expectedErrorPatterns []string) {
1144	t.Helper()
1145
1146	if expectedErrorPatterns == nil {
1147		FailIfErrored(t, errs)
1148	} else {
1149		for _, expectedError := range expectedErrorPatterns {
1150			FailIfNoMatchingErrors(t, expectedError, errs)
1151		}
1152		if len(errs) > len(expectedErrorPatterns) {
1153			t.Errorf("additional errors found, expected %d, found %d",
1154				len(expectedErrorPatterns), len(errs))
1155			for i, expectedError := range expectedErrorPatterns {
1156				t.Errorf("expectedErrors[%d] = %s", i, expectedError)
1157			}
1158			for i, err := range errs {
1159				t.Errorf("errs[%d] = %s", i, err)
1160			}
1161			t.FailNow()
1162		}
1163	}
1164}
1165
1166func SetKatiEnabledForTests(config Config) {
1167	config.katiEnabled = true
1168}
1169
1170func AndroidMkEntriesForTest(t *testing.T, ctx *TestContext, mod Module) []AndroidMkEntries {
1171	t.Helper()
1172	var p AndroidMkEntriesProvider
1173	var ok bool
1174	if p, ok = mod.(AndroidMkEntriesProvider); !ok {
1175		t.Error("module does not implement AndroidMkEntriesProvider: " + mod.Name())
1176	}
1177
1178	entriesList := p.AndroidMkEntries()
1179	aconfigUpdateAndroidMkEntries(ctx, mod, &entriesList)
1180	for i := range entriesList {
1181		entriesList[i].fillInEntries(ctx, mod)
1182	}
1183	return entriesList
1184}
1185
1186func AndroidMkInfoForTest(t *testing.T, ctx *TestContext, mod Module) *AndroidMkProviderInfo {
1187	if runtime.GOOS == "darwin" && mod.base().Os() != Darwin {
1188		// The AndroidMkInfo provider is not set in this case.
1189		t.Skip("AndroidMkInfo provider is not set on darwin")
1190	}
1191
1192	t.Helper()
1193	var ok bool
1194	if _, ok = mod.(AndroidMkProviderInfoProducer); !ok {
1195		t.Error("module does not implement AndroidMkProviderInfoProducer: " + mod.Name())
1196	}
1197
1198	info := OtherModuleProviderOrDefault(ctx, mod, AndroidMkInfoProvider)
1199	aconfigUpdateAndroidMkInfos(ctx, mod, info)
1200	commonInfo := OtherModulePointerProviderOrDefault(ctx, mod, CommonModuleInfoProvider)
1201	info.PrimaryInfo.fillInEntries(ctx, mod, commonInfo)
1202	if len(info.ExtraInfo) > 0 {
1203		for _, ei := range info.ExtraInfo {
1204			ei.fillInEntries(ctx, mod, commonInfo)
1205		}
1206	}
1207
1208	return info
1209}
1210
1211func AndroidMkDataForTest(t *testing.T, ctx *TestContext, mod Module) AndroidMkData {
1212	t.Helper()
1213	var p AndroidMkDataProvider
1214	var ok bool
1215	if p, ok = mod.(AndroidMkDataProvider); !ok {
1216		t.Fatal("module does not implement AndroidMkDataProvider: " + mod.Name())
1217	}
1218	data := p.AndroidMk()
1219	data.fillInData(ctx, mod)
1220	aconfigUpdateAndroidMkData(ctx, mod, &data)
1221	return data
1222}
1223
1224// Normalize the path for testing.
1225//
1226// If the path is relative to the build directory then return the relative path
1227// to avoid tests having to deal with the dynamically generated build directory.
1228//
1229// Otherwise, return the supplied path as it is almost certainly a source path
1230// that is relative to the root of the source tree.
1231//
1232// The build and source paths should be distinguishable based on their contents.
1233//
1234// deprecated: use PathRelativeToTop instead as it handles make install paths and differentiates
1235// between output and source properly.
1236func NormalizePathForTesting(path Path) string {
1237	if path == nil {
1238		return "<nil path>"
1239	}
1240	p := path.String()
1241	if w, ok := path.(WritablePath); ok {
1242		rel, err := filepath.Rel(w.getSoongOutDir(), p)
1243		if err != nil {
1244			panic(err)
1245		}
1246		return rel
1247	}
1248	return p
1249}
1250
1251// NormalizePathsForTesting creates a slice of strings where each string is the result of applying
1252// NormalizePathForTesting to the corresponding Path in the input slice.
1253//
1254// deprecated: use PathsRelativeToTop instead as it handles make install paths and differentiates
1255// between output and source properly.
1256func NormalizePathsForTesting(paths Paths) []string {
1257	var result []string
1258	for _, path := range paths {
1259		relative := NormalizePathForTesting(path)
1260		result = append(result, relative)
1261	}
1262	return result
1263}
1264
1265// PathRelativeToTop returns a string representation of the path relative to a notional top
1266// directory.
1267//
1268// It return "<nil path>" if the supplied path is nil, otherwise it returns the result of calling
1269// Path.RelativeToTop to obtain a relative Path and then calling Path.String on that to get the
1270// string representation.
1271func PathRelativeToTop(path Path) string {
1272	if path == nil {
1273		return "<nil path>"
1274	}
1275	return path.RelativeToTop().String()
1276}
1277
1278// PathsRelativeToTop creates a slice of strings where each string is the result of applying
1279// PathRelativeToTop to the corresponding Path in the input slice.
1280func PathsRelativeToTop(paths Paths) []string {
1281	var result []string
1282	for _, path := range paths {
1283		relative := PathRelativeToTop(path)
1284		result = append(result, relative)
1285	}
1286	return result
1287}
1288
1289// StringPathRelativeToTop returns a string representation of the path relative to a notional top
1290// directory.
1291//
1292// See Path.RelativeToTop for more details as to what `relative to top` means.
1293//
1294// This is provided for processing paths that have already been converted into a string, e.g. paths
1295// in AndroidMkEntries structures. As a result it needs to be supplied the soong output dir against
1296// which it can try and relativize paths. PathRelativeToTop must be used for process Path objects.
1297func StringPathRelativeToTop(soongOutDir string, path string) string {
1298	ensureTestOnly()
1299
1300	// A relative path must be a source path so leave it as it is.
1301	if !filepath.IsAbs(path) {
1302		return path
1303	}
1304
1305	// Check to see if the path is relative to the soong out dir.
1306	rel, isRel, err := maybeRelErr(soongOutDir, path)
1307	if err != nil {
1308		panic(err)
1309	}
1310
1311	if isRel {
1312		if strings.HasSuffix(soongOutDir, testOutSoongSubDir) {
1313			// The path is in the soong out dir so indicate that in the relative path.
1314			return filepath.Join(TestOutSoongDir, rel)
1315		} else {
1316			// Handle the PathForArbitraryOutput case
1317			return filepath.Join(testOutDir, rel)
1318
1319		}
1320	}
1321
1322	// Check to see if the path is relative to the top level out dir.
1323	outDir := filepath.Dir(soongOutDir)
1324	rel, isRel, err = maybeRelErr(outDir, path)
1325	if err != nil {
1326		panic(err)
1327	}
1328
1329	if isRel {
1330		// The path is in the out dir so indicate that in the relative path.
1331		return filepath.Join("out", rel)
1332	}
1333
1334	// This should never happen.
1335	panic(fmt.Errorf("internal error: absolute path %s is not relative to the out dir %s", path, outDir))
1336}
1337
1338// StringPathsRelativeToTop creates a slice of strings where each string is the result of applying
1339// StringPathRelativeToTop to the corresponding string path in the input slice.
1340//
1341// This is provided for processing paths that have already been converted into a string, e.g. paths
1342// in AndroidMkEntries structures. As a result it needs to be supplied the soong output dir against
1343// which it can try and relativize paths. PathsRelativeToTop must be used for process Paths objects.
1344func StringPathsRelativeToTop(soongOutDir string, paths []string) []string {
1345	var result []string
1346	for _, path := range paths {
1347		relative := StringPathRelativeToTop(soongOutDir, path)
1348		result = append(result, relative)
1349	}
1350	return result
1351}
1352
1353// StringRelativeToTop will normalize a string containing paths, e.g. ninja command, by replacing
1354// any references to the test specific temporary build directory that changes with each run to a
1355// fixed path relative to a notional top directory.
1356//
1357// This is similar to StringPathRelativeToTop except that assumes the string is a single path
1358// containing at most one instance of the temporary build directory at the start of the path while
1359// this assumes that there can be any number at any position.
1360func StringRelativeToTop(config Config, command string) string {
1361	return normalizeStringRelativeToTop(config, command)
1362}
1363
1364// StringsRelativeToTop will return a new slice such that each item in the new slice is the result
1365// of calling StringRelativeToTop on the corresponding item in the input slice.
1366func StringsRelativeToTop(config Config, command []string) []string {
1367	return normalizeStringArrayRelativeToTop(config, command)
1368}
1369
1370func EnsureListContainsSuffix(t *testing.T, result []string, expected string) {
1371	t.Helper()
1372	if !SuffixInList(result, expected) {
1373		t.Errorf("%q is not found in %v", expected, result)
1374	}
1375}
1376
1377type panickingConfigAndErrorContext struct {
1378	ctx *TestContext
1379}
1380
1381func (ctx *panickingConfigAndErrorContext) OtherModulePropertyErrorf(module Module, property, fmt string, args ...interface{}) {
1382	panic(ctx.ctx.PropertyErrorf(module, property, fmt, args...).Error())
1383}
1384
1385func (ctx *panickingConfigAndErrorContext) Config() Config {
1386	return ctx.ctx.Config()
1387}
1388
1389func (ctx *panickingConfigAndErrorContext) HasMutatorFinished(mutatorName string) bool {
1390	return ctx.ctx.HasMutatorFinished(mutatorName)
1391}
1392
1393func (ctx *panickingConfigAndErrorContext) otherModuleProvider(m blueprint.Module, p blueprint.AnyProviderKey) (any, bool) {
1394	return ctx.ctx.otherModuleProvider(m, p)
1395}
1396
1397func PanickingConfigAndErrorContext(ctx *TestContext) ConfigurableEvaluatorContext {
1398	return &panickingConfigAndErrorContext{
1399		ctx: ctx,
1400	}
1401}
1402