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(name string, matchVariations map[string]string) TestingModule { 534 modules := []Module{} 535 ctx.VisitAllModules(func(m blueprint.Module) { 536 if ctx.ModuleName(m) == name { 537 am := m.(Module) 538 amMut := am.base().commonProperties.DebugMutators 539 amVar := am.base().commonProperties.DebugVariations 540 matched := true 541 for i, mut := range amMut { 542 if wantedVar, found := matchVariations[mut]; found && amVar[i] != wantedVar { 543 matched = false 544 break 545 } 546 } 547 if matched { 548 modules = append(modules, am) 549 } 550 } 551 }) 552 553 if len(modules) == 0 { 554 // Show all the modules or module variants that do exist. 555 var allModuleNames []string 556 var allVariants []string 557 ctx.VisitAllModules(func(m blueprint.Module) { 558 allModuleNames = append(allModuleNames, ctx.ModuleName(m)) 559 if ctx.ModuleName(m) == name { 560 allVariants = append(allVariants, m.(Module).String()) 561 } 562 }) 563 564 if len(allVariants) == 0 { 565 panic(fmt.Errorf("failed to find module %q. All modules:\n %s", 566 name, strings.Join(SortedUniqueStrings(allModuleNames), "\n "))) 567 } else { 568 sort.Strings(allVariants) 569 panic(fmt.Errorf("failed to find module %q matching %v. All variants:\n %s", 570 name, matchVariations, strings.Join(allVariants, "\n "))) 571 } 572 } 573 574 if len(modules) > 1 { 575 moduleStrings := []string{} 576 for _, m := range modules { 577 moduleStrings = append(moduleStrings, m.String()) 578 } 579 sort.Strings(moduleStrings) 580 panic(fmt.Errorf("module %q has more than one variant that match %v:\n %s", 581 name, matchVariations, strings.Join(moduleStrings, "\n "))) 582 } 583 584 return newTestingModule(ctx.config, modules[0]) 585} 586 587func (ctx *TestContext) ModuleForTests(name, variant string) TestingModule { 588 var module Module 589 ctx.VisitAllModules(func(m blueprint.Module) { 590 if ctx.ModuleName(m) == name && ctx.ModuleSubDir(m) == variant { 591 module = m.(Module) 592 } 593 }) 594 595 if module == nil { 596 // find all the modules that do exist 597 var allModuleNames []string 598 var allVariants []string 599 ctx.VisitAllModules(func(m blueprint.Module) { 600 allModuleNames = append(allModuleNames, ctx.ModuleName(m)) 601 if ctx.ModuleName(m) == name { 602 allVariants = append(allVariants, ctx.ModuleSubDir(m)) 603 } 604 }) 605 sort.Strings(allVariants) 606 607 if len(allVariants) == 0 { 608 panic(fmt.Errorf("failed to find module %q. All modules:\n %s", 609 name, strings.Join(SortedUniqueStrings(allModuleNames), "\n "))) 610 } else { 611 panic(fmt.Errorf("failed to find module %q variant %q. All variants:\n %s", 612 name, variant, strings.Join(allVariants, "\n "))) 613 } 614 } 615 616 return newTestingModule(ctx.config, module) 617} 618 619func (ctx *TestContext) ModuleVariantsForTests(name string) []string { 620 var variants []string 621 ctx.VisitAllModules(func(m blueprint.Module) { 622 if ctx.ModuleName(m) == name { 623 variants = append(variants, ctx.ModuleSubDir(m)) 624 } 625 }) 626 return variants 627} 628 629// SingletonForTests returns a TestingSingleton for the singleton registered with the given name. 630func (ctx *TestContext) SingletonForTests(name string) TestingSingleton { 631 allSingletonNames := []string{} 632 for _, s := range ctx.Singletons() { 633 n := ctx.SingletonName(s) 634 if n == name { 635 return TestingSingleton{ 636 baseTestingComponent: newBaseTestingComponent(ctx.config, s.(testBuildProvider)), 637 singleton: s.(*singletonAdaptor).Singleton, 638 } 639 } 640 allSingletonNames = append(allSingletonNames, n) 641 } 642 643 panic(fmt.Errorf("failed to find singleton %q."+ 644 "\nall singletons: %v", name, allSingletonNames)) 645} 646 647type InstallMakeRule struct { 648 Target string 649 Deps []string 650 OrderOnlyDeps []string 651} 652 653func parseMkRules(t *testing.T, config Config, nodes []mkparser.Node) []InstallMakeRule { 654 var rules []InstallMakeRule 655 for _, node := range nodes { 656 if mkParserRule, ok := node.(*mkparser.Rule); ok { 657 var rule InstallMakeRule 658 659 if targets := mkParserRule.Target.Words(); len(targets) == 0 { 660 t.Fatalf("no targets for rule %s", mkParserRule.Dump()) 661 } else if len(targets) > 1 { 662 t.Fatalf("unsupported multiple targets for rule %s", mkParserRule.Dump()) 663 } else if !targets[0].Const() { 664 t.Fatalf("unsupported non-const target for rule %s", mkParserRule.Dump()) 665 } else { 666 rule.Target = normalizeStringRelativeToTop(config, targets[0].Value(nil)) 667 } 668 669 prereqList := &rule.Deps 670 for _, prereq := range mkParserRule.Prerequisites.Words() { 671 if !prereq.Const() { 672 t.Fatalf("unsupported non-const prerequisite for rule %s", mkParserRule.Dump()) 673 } 674 675 if prereq.Value(nil) == "|" { 676 prereqList = &rule.OrderOnlyDeps 677 continue 678 } 679 680 *prereqList = append(*prereqList, normalizeStringRelativeToTop(config, prereq.Value(nil))) 681 } 682 683 rules = append(rules, rule) 684 } 685 } 686 687 return rules 688} 689 690func (ctx *TestContext) InstallMakeRulesForTesting(t *testing.T) []InstallMakeRule { 691 installs := ctx.SingletonForTests("makevars").Singleton().(*makeVarsSingleton).installsForTesting 692 buf := bytes.NewBuffer(append([]byte(nil), installs...)) 693 parser := mkparser.NewParser("makevars", buf) 694 695 nodes, errs := parser.Parse() 696 if len(errs) > 0 { 697 t.Fatalf("error parsing install rules: %s", errs[0]) 698 } 699 700 return parseMkRules(t, ctx.config, nodes) 701} 702 703// MakeVarVariable provides access to make vars that will be written by the makeVarsSingleton 704type MakeVarVariable interface { 705 // Name is the name of the variable. 706 Name() string 707 708 // Value is the value of the variable. 709 Value() string 710} 711 712func (v makeVarsVariable) Name() string { 713 return v.name 714} 715 716func (v makeVarsVariable) Value() string { 717 return v.value 718} 719 720// PrepareForTestAccessingMakeVars sets up the test so that MakeVarsForTesting will work. 721var PrepareForTestAccessingMakeVars = GroupFixturePreparers( 722 PrepareForTestWithAndroidMk, 723 PrepareForTestWithMakevars, 724) 725 726// MakeVarsForTesting returns a filtered list of MakeVarVariable objects that represent the 727// variables that will be written out. 728// 729// It is necessary to use PrepareForTestAccessingMakeVars in tests that want to call this function. 730// Along with any other preparers needed to add the make vars. 731func (ctx *TestContext) MakeVarsForTesting(filter func(variable MakeVarVariable) bool) []MakeVarVariable { 732 vars := ctx.SingletonForTests("makevars").Singleton().(*makeVarsSingleton).varsForTesting 733 result := make([]MakeVarVariable, 0, len(vars)) 734 for _, v := range vars { 735 if filter(v) { 736 result = append(result, v) 737 } 738 } 739 740 return result 741} 742 743func (ctx *TestContext) Config() Config { 744 return ctx.config 745} 746 747type testBuildProvider interface { 748 BuildParamsForTests() []BuildParams 749 RuleParamsForTests() map[blueprint.Rule]blueprint.RuleParams 750} 751 752type TestingBuildParams struct { 753 BuildParams 754 RuleParams blueprint.RuleParams 755 756 config Config 757} 758 759// RelativeToTop creates a new instance of this which has had any usages of the current test's 760// temporary and test specific build directory replaced with a path relative to the notional top. 761// 762// The parts of this structure which are changed are: 763// * BuildParams 764// - Args 765// - All Path, Paths, WritablePath and WritablePaths fields. 766// 767// * RuleParams 768// - Command 769// - Depfile 770// - Rspfile 771// - RspfileContent 772// - CommandDeps 773// - CommandOrderOnly 774// 775// See PathRelativeToTop for more details. 776// 777// deprecated: this is no longer needed as TestingBuildParams are created in this form. 778func (p TestingBuildParams) RelativeToTop() TestingBuildParams { 779 // If this is not a valid params then just return it back. That will make it easy to use with the 780 // Maybe...() methods. 781 if p.Rule == nil { 782 return p 783 } 784 if p.config.config == nil { 785 return p 786 } 787 // Take a copy of the build params and replace any args that contains test specific temporary 788 // paths with paths relative to the top. 789 bparams := p.BuildParams 790 bparams.Depfile = normalizeWritablePathRelativeToTop(bparams.Depfile) 791 bparams.Output = normalizeWritablePathRelativeToTop(bparams.Output) 792 bparams.Outputs = bparams.Outputs.RelativeToTop() 793 bparams.ImplicitOutput = normalizeWritablePathRelativeToTop(bparams.ImplicitOutput) 794 bparams.ImplicitOutputs = bparams.ImplicitOutputs.RelativeToTop() 795 bparams.Input = normalizePathRelativeToTop(bparams.Input) 796 bparams.Inputs = bparams.Inputs.RelativeToTop() 797 bparams.Implicit = normalizePathRelativeToTop(bparams.Implicit) 798 bparams.Implicits = bparams.Implicits.RelativeToTop() 799 bparams.OrderOnly = bparams.OrderOnly.RelativeToTop() 800 bparams.Validation = normalizePathRelativeToTop(bparams.Validation) 801 bparams.Validations = bparams.Validations.RelativeToTop() 802 bparams.Args = normalizeStringMapRelativeToTop(p.config, bparams.Args) 803 804 // Ditto for any fields in the RuleParams. 805 rparams := p.RuleParams 806 rparams.Command = normalizeStringRelativeToTop(p.config, rparams.Command) 807 rparams.Depfile = normalizeStringRelativeToTop(p.config, rparams.Depfile) 808 rparams.Rspfile = normalizeStringRelativeToTop(p.config, rparams.Rspfile) 809 rparams.RspfileContent = normalizeStringRelativeToTop(p.config, rparams.RspfileContent) 810 rparams.CommandDeps = normalizeStringArrayRelativeToTop(p.config, rparams.CommandDeps) 811 rparams.CommandOrderOnly = normalizeStringArrayRelativeToTop(p.config, rparams.CommandOrderOnly) 812 813 return TestingBuildParams{ 814 BuildParams: bparams, 815 RuleParams: rparams, 816 } 817} 818 819func normalizeWritablePathRelativeToTop(path WritablePath) WritablePath { 820 if path == nil { 821 return nil 822 } 823 return path.RelativeToTop().(WritablePath) 824} 825 826func normalizePathRelativeToTop(path Path) Path { 827 if path == nil { 828 return nil 829 } 830 return path.RelativeToTop() 831} 832 833func allOutputs(p BuildParams) []string { 834 outputs := append(WritablePaths(nil), p.Outputs...) 835 outputs = append(outputs, p.ImplicitOutputs...) 836 if p.Output != nil { 837 outputs = append(outputs, p.Output) 838 } 839 return outputs.Strings() 840} 841 842// AllOutputs returns all 'BuildParams.Output's and 'BuildParams.Outputs's in their full path string forms. 843func (p TestingBuildParams) AllOutputs() []string { 844 return allOutputs(p.BuildParams) 845} 846 847// baseTestingComponent provides functionality common to both TestingModule and TestingSingleton. 848type baseTestingComponent struct { 849 config Config 850 provider testBuildProvider 851} 852 853func newBaseTestingComponent(config Config, provider testBuildProvider) baseTestingComponent { 854 return baseTestingComponent{config, provider} 855} 856 857// A function that will normalize a string containing paths, e.g. ninja command, by replacing 858// any references to the test specific temporary build directory that changes with each run to a 859// fixed path relative to a notional top directory. 860// 861// This is similar to StringPathRelativeToTop except that assumes the string is a single path 862// containing at most one instance of the temporary build directory at the start of the path while 863// this assumes that there can be any number at any position. 864func normalizeStringRelativeToTop(config Config, s string) string { 865 // The outDir usually looks something like: /tmp/testFoo2345/001 866 // 867 // Replace any usage of the outDir with out/soong, e.g. replace "/tmp/testFoo2345/001" with 868 // "out/soong". 869 outSoongDir := filepath.Clean(config.soongOutDir) 870 re := regexp.MustCompile(`\Q` + outSoongDir + `\E\b`) 871 s = re.ReplaceAllString(s, "out/soong") 872 873 // Replace any usage of the outDir/.. with out, e.g. replace "/tmp/testFoo2345" with 874 // "out". This must come after the previous replacement otherwise this would replace 875 // "/tmp/testFoo2345/001" with "out/001" instead of "out/soong". 876 outDir := filepath.Dir(outSoongDir) 877 re = regexp.MustCompile(`\Q` + outDir + `\E\b`) 878 s = re.ReplaceAllString(s, "out") 879 880 return s 881} 882 883// normalizeStringArrayRelativeToTop creates a new slice constructed by applying 884// normalizeStringRelativeToTop to each item in the slice. 885func normalizeStringArrayRelativeToTop(config Config, slice []string) []string { 886 newSlice := make([]string, len(slice)) 887 for i, s := range slice { 888 newSlice[i] = normalizeStringRelativeToTop(config, s) 889 } 890 return newSlice 891} 892 893// normalizeStringMapRelativeToTop creates a new map constructed by applying 894// normalizeStringRelativeToTop to each value in the map. 895func normalizeStringMapRelativeToTop(config Config, m map[string]string) map[string]string { 896 newMap := map[string]string{} 897 for k, v := range m { 898 newMap[k] = normalizeStringRelativeToTop(config, v) 899 } 900 return newMap 901} 902 903func (b baseTestingComponent) newTestingBuildParams(bparams BuildParams) TestingBuildParams { 904 return TestingBuildParams{ 905 config: b.config, 906 BuildParams: bparams, 907 RuleParams: b.provider.RuleParamsForTests()[bparams.Rule], 908 }.RelativeToTop() 909} 910 911func (b baseTestingComponent) maybeBuildParamsFromRule(rule string) (TestingBuildParams, []string) { 912 var searchedRules []string 913 buildParams := b.provider.BuildParamsForTests() 914 for _, p := range buildParams { 915 ruleAsString := p.Rule.String() 916 searchedRules = append(searchedRules, ruleAsString) 917 if strings.Contains(ruleAsString, rule) { 918 return b.newTestingBuildParams(p), searchedRules 919 } 920 } 921 return TestingBuildParams{}, searchedRules 922} 923 924func (b baseTestingComponent) buildParamsFromRule(rule string) TestingBuildParams { 925 p, searchRules := b.maybeBuildParamsFromRule(rule) 926 if p.Rule == nil { 927 panic(fmt.Errorf("couldn't find rule %q.\nall rules:\n%s", rule, strings.Join(searchRules, "\n"))) 928 } 929 return p 930} 931 932func (b baseTestingComponent) maybeBuildParamsFromDescription(desc string) (TestingBuildParams, []string) { 933 var searchedDescriptions []string 934 for _, p := range b.provider.BuildParamsForTests() { 935 searchedDescriptions = append(searchedDescriptions, p.Description) 936 if strings.Contains(p.Description, desc) { 937 return b.newTestingBuildParams(p), searchedDescriptions 938 } 939 } 940 return TestingBuildParams{}, searchedDescriptions 941} 942 943func (b baseTestingComponent) buildParamsFromDescription(desc string) TestingBuildParams { 944 p, searchedDescriptions := b.maybeBuildParamsFromDescription(desc) 945 if p.Rule == nil { 946 panic(fmt.Errorf("couldn't find description %q\nall descriptions:\n%s", desc, strings.Join(searchedDescriptions, "\n"))) 947 } 948 return p 949} 950 951func (b baseTestingComponent) maybeBuildParamsFromOutput(file string) (TestingBuildParams, []string) { 952 searchedOutputs := WritablePaths(nil) 953 for _, p := range b.provider.BuildParamsForTests() { 954 outputs := append(WritablePaths(nil), p.Outputs...) 955 outputs = append(outputs, p.ImplicitOutputs...) 956 if p.Output != nil { 957 outputs = append(outputs, p.Output) 958 } 959 for _, f := range outputs { 960 if f.String() == file || f.Rel() == file || PathRelativeToTop(f) == file { 961 return b.newTestingBuildParams(p), nil 962 } 963 searchedOutputs = append(searchedOutputs, f) 964 } 965 } 966 967 formattedOutputs := []string{} 968 for _, f := range searchedOutputs { 969 formattedOutputs = append(formattedOutputs, 970 fmt.Sprintf("%s (rel=%s)", PathRelativeToTop(f), f.Rel())) 971 } 972 973 return TestingBuildParams{}, formattedOutputs 974} 975 976func (b baseTestingComponent) buildParamsFromOutput(file string) TestingBuildParams { 977 p, searchedOutputs := b.maybeBuildParamsFromOutput(file) 978 if p.Rule == nil { 979 panic(fmt.Errorf("couldn't find output %q.\nall outputs:\n %s\n", 980 file, strings.Join(searchedOutputs, "\n "))) 981 } 982 return p 983} 984 985func (b baseTestingComponent) allOutputs() []string { 986 var outputFullPaths []string 987 for _, p := range b.provider.BuildParamsForTests() { 988 outputFullPaths = append(outputFullPaths, allOutputs(p)...) 989 } 990 return outputFullPaths 991} 992 993// MaybeRule finds a call to ctx.Build with BuildParams.Rule set to a rule with the given name. Returns an empty 994// BuildParams if no rule is found. 995func (b baseTestingComponent) MaybeRule(rule string) TestingBuildParams { 996 r, _ := b.maybeBuildParamsFromRule(rule) 997 return r 998} 999 1000// Rule finds a call to ctx.Build with BuildParams.Rule set to a rule with the given name. Panics if no rule is found. 1001func (b baseTestingComponent) Rule(rule string) TestingBuildParams { 1002 return b.buildParamsFromRule(rule) 1003} 1004 1005// MaybeDescription finds a call to ctx.Build with BuildParams.Description set to a the given string. Returns an empty 1006// BuildParams if no rule is found. 1007func (b baseTestingComponent) MaybeDescription(desc string) TestingBuildParams { 1008 p, _ := b.maybeBuildParamsFromDescription(desc) 1009 return p 1010} 1011 1012// Description finds a call to ctx.Build with BuildParams.Description set to a the given string. Panics if no rule is 1013// found. 1014func (b baseTestingComponent) Description(desc string) TestingBuildParams { 1015 return b.buildParamsFromDescription(desc) 1016} 1017 1018// MaybeOutput finds a call to ctx.Build with a BuildParams.Output or BuildParams.Outputs whose String() or Rel() 1019// value matches the provided string. Returns an empty BuildParams if no rule is found. 1020func (b baseTestingComponent) MaybeOutput(file string) TestingBuildParams { 1021 p, _ := b.maybeBuildParamsFromOutput(file) 1022 return p 1023} 1024 1025// Output finds a call to ctx.Build with a BuildParams.Output or BuildParams.Outputs whose String() or Rel() 1026// value matches the provided string. Panics if no rule is found. 1027func (b baseTestingComponent) Output(file string) TestingBuildParams { 1028 return b.buildParamsFromOutput(file) 1029} 1030 1031// AllOutputs returns all 'BuildParams.Output's and 'BuildParams.Outputs's in their full path string forms. 1032func (b baseTestingComponent) AllOutputs() []string { 1033 return b.allOutputs() 1034} 1035 1036// TestingModule is wrapper around an android.Module that provides methods to find information about individual 1037// ctx.Build parameters for verification in tests. 1038type TestingModule struct { 1039 baseTestingComponent 1040 module Module 1041} 1042 1043func newTestingModule(config Config, module Module) TestingModule { 1044 return TestingModule{ 1045 newBaseTestingComponent(config, module), 1046 module, 1047 } 1048} 1049 1050// Module returns the Module wrapped by the TestingModule. 1051func (m TestingModule) Module() Module { 1052 return m.module 1053} 1054 1055// VariablesForTestsRelativeToTop returns a copy of the Module.VariablesForTests() with every value 1056// having any temporary build dir usages replaced with paths relative to a notional top. 1057func (m TestingModule) VariablesForTestsRelativeToTop() map[string]string { 1058 return normalizeStringMapRelativeToTop(m.config, m.module.VariablesForTests()) 1059} 1060 1061// OutputFiles checks if module base outputFiles property has any output 1062// files can be used to return. 1063// Exits the test immediately if there is an error and 1064// otherwise returns the result of calling Paths.RelativeToTop 1065// on the returned Paths. 1066func (m TestingModule) OutputFiles(ctx *TestContext, t *testing.T, tag string) Paths { 1067 outputFiles := OtherModuleProviderOrDefault(ctx.OtherModuleProviderAdaptor(), m.Module(), OutputFilesProvider) 1068 if tag == "" && outputFiles.DefaultOutputFiles != nil { 1069 return outputFiles.DefaultOutputFiles.RelativeToTop() 1070 } else if taggedOutputFiles, hasTag := outputFiles.TaggedOutputFiles[tag]; hasTag { 1071 return taggedOutputFiles.RelativeToTop() 1072 } 1073 1074 t.Fatal(fmt.Errorf("No test output file has been set for tag %q", tag)) 1075 return nil 1076} 1077 1078// TestingSingleton is wrapper around an android.Singleton that provides methods to find information about individual 1079// ctx.Build parameters for verification in tests. 1080type TestingSingleton struct { 1081 baseTestingComponent 1082 singleton Singleton 1083} 1084 1085// Singleton returns the Singleton wrapped by the TestingSingleton. 1086func (s TestingSingleton) Singleton() Singleton { 1087 return s.singleton 1088} 1089 1090func FailIfErrored(t *testing.T, errs []error) { 1091 t.Helper() 1092 if len(errs) > 0 { 1093 for _, err := range errs { 1094 t.Error(err) 1095 } 1096 t.FailNow() 1097 } 1098} 1099 1100// Fail if no errors that matched the regular expression were found. 1101// 1102// Returns true if a matching error was found, false otherwise. 1103func FailIfNoMatchingErrors(t *testing.T, pattern string, errs []error) bool { 1104 t.Helper() 1105 1106 matcher, err := regexp.Compile(pattern) 1107 if err != nil { 1108 t.Fatalf("failed to compile regular expression %q because %s", pattern, err) 1109 } 1110 1111 found := false 1112 for _, err := range errs { 1113 if matcher.FindStringIndex(err.Error()) != nil { 1114 found = true 1115 break 1116 } 1117 } 1118 if !found { 1119 t.Errorf("could not match the expected error regex %q (checked %d error(s))", pattern, len(errs)) 1120 for i, err := range errs { 1121 t.Errorf("errs[%d] = %q", i, err) 1122 } 1123 } 1124 1125 return found 1126} 1127 1128func CheckErrorsAgainstExpectations(t *testing.T, errs []error, expectedErrorPatterns []string) { 1129 t.Helper() 1130 1131 if expectedErrorPatterns == nil { 1132 FailIfErrored(t, errs) 1133 } else { 1134 for _, expectedError := range expectedErrorPatterns { 1135 FailIfNoMatchingErrors(t, expectedError, errs) 1136 } 1137 if len(errs) > len(expectedErrorPatterns) { 1138 t.Errorf("additional errors found, expected %d, found %d", 1139 len(expectedErrorPatterns), len(errs)) 1140 for i, expectedError := range expectedErrorPatterns { 1141 t.Errorf("expectedErrors[%d] = %s", i, expectedError) 1142 } 1143 for i, err := range errs { 1144 t.Errorf("errs[%d] = %s", i, err) 1145 } 1146 t.FailNow() 1147 } 1148 } 1149} 1150 1151func SetKatiEnabledForTests(config Config) { 1152 config.katiEnabled = true 1153} 1154 1155func AndroidMkEntriesForTest(t *testing.T, ctx *TestContext, mod blueprint.Module) []AndroidMkEntries { 1156 t.Helper() 1157 var p AndroidMkEntriesProvider 1158 var ok bool 1159 if p, ok = mod.(AndroidMkEntriesProvider); !ok { 1160 t.Errorf("module does not implement AndroidMkEntriesProvider: " + mod.Name()) 1161 } 1162 1163 entriesList := p.AndroidMkEntries() 1164 aconfigUpdateAndroidMkEntries(ctx, mod.(Module), &entriesList) 1165 for i := range entriesList { 1166 entriesList[i].fillInEntries(ctx, mod) 1167 } 1168 return entriesList 1169} 1170 1171func AndroidMkInfoForTest(t *testing.T, ctx *TestContext, mod blueprint.Module) *AndroidMkProviderInfo { 1172 if runtime.GOOS == "darwin" && mod.(Module).base().Os() != Darwin { 1173 // The AndroidMkInfo provider is not set in this case. 1174 t.Skip("AndroidMkInfo provider is not set on darwin") 1175 } 1176 1177 t.Helper() 1178 var ok bool 1179 if _, ok = mod.(AndroidMkProviderInfoProducer); !ok { 1180 t.Errorf("module does not implement AndroidMkProviderInfoProducer: " + mod.Name()) 1181 } 1182 1183 info := OtherModuleProviderOrDefault(ctx, mod, AndroidMkInfoProvider) 1184 aconfigUpdateAndroidMkInfos(ctx, mod.(Module), info) 1185 info.PrimaryInfo.fillInEntries(ctx, mod) 1186 if len(info.ExtraInfo) > 0 { 1187 for _, ei := range info.ExtraInfo { 1188 ei.fillInEntries(ctx, mod) 1189 } 1190 } 1191 1192 return info 1193} 1194 1195func AndroidMkDataForTest(t *testing.T, ctx *TestContext, mod blueprint.Module) AndroidMkData { 1196 t.Helper() 1197 var p AndroidMkDataProvider 1198 var ok bool 1199 if p, ok = mod.(AndroidMkDataProvider); !ok { 1200 t.Fatalf("module does not implement AndroidMkDataProvider: " + mod.Name()) 1201 } 1202 data := p.AndroidMk() 1203 data.fillInData(ctx, mod) 1204 aconfigUpdateAndroidMkData(ctx, mod.(Module), &data) 1205 return data 1206} 1207 1208// Normalize the path for testing. 1209// 1210// If the path is relative to the build directory then return the relative path 1211// to avoid tests having to deal with the dynamically generated build directory. 1212// 1213// Otherwise, return the supplied path as it is almost certainly a source path 1214// that is relative to the root of the source tree. 1215// 1216// The build and source paths should be distinguishable based on their contents. 1217// 1218// deprecated: use PathRelativeToTop instead as it handles make install paths and differentiates 1219// between output and source properly. 1220func NormalizePathForTesting(path Path) string { 1221 if path == nil { 1222 return "<nil path>" 1223 } 1224 p := path.String() 1225 if w, ok := path.(WritablePath); ok { 1226 rel, err := filepath.Rel(w.getSoongOutDir(), p) 1227 if err != nil { 1228 panic(err) 1229 } 1230 return rel 1231 } 1232 return p 1233} 1234 1235// NormalizePathsForTesting creates a slice of strings where each string is the result of applying 1236// NormalizePathForTesting to the corresponding Path in the input slice. 1237// 1238// deprecated: use PathsRelativeToTop instead as it handles make install paths and differentiates 1239// between output and source properly. 1240func NormalizePathsForTesting(paths Paths) []string { 1241 var result []string 1242 for _, path := range paths { 1243 relative := NormalizePathForTesting(path) 1244 result = append(result, relative) 1245 } 1246 return result 1247} 1248 1249// PathRelativeToTop returns a string representation of the path relative to a notional top 1250// directory. 1251// 1252// It return "<nil path>" if the supplied path is nil, otherwise it returns the result of calling 1253// Path.RelativeToTop to obtain a relative Path and then calling Path.String on that to get the 1254// string representation. 1255func PathRelativeToTop(path Path) string { 1256 if path == nil { 1257 return "<nil path>" 1258 } 1259 return path.RelativeToTop().String() 1260} 1261 1262// PathsRelativeToTop creates a slice of strings where each string is the result of applying 1263// PathRelativeToTop to the corresponding Path in the input slice. 1264func PathsRelativeToTop(paths Paths) []string { 1265 var result []string 1266 for _, path := range paths { 1267 relative := PathRelativeToTop(path) 1268 result = append(result, relative) 1269 } 1270 return result 1271} 1272 1273// StringPathRelativeToTop returns a string representation of the path relative to a notional top 1274// directory. 1275// 1276// See Path.RelativeToTop for more details as to what `relative to top` means. 1277// 1278// This is provided for processing paths that have already been converted into a string, e.g. paths 1279// in AndroidMkEntries structures. As a result it needs to be supplied the soong output dir against 1280// which it can try and relativize paths. PathRelativeToTop must be used for process Path objects. 1281func StringPathRelativeToTop(soongOutDir string, path string) string { 1282 ensureTestOnly() 1283 1284 // A relative path must be a source path so leave it as it is. 1285 if !filepath.IsAbs(path) { 1286 return path 1287 } 1288 1289 // Check to see if the path is relative to the soong out dir. 1290 rel, isRel, err := maybeRelErr(soongOutDir, path) 1291 if err != nil { 1292 panic(err) 1293 } 1294 1295 if isRel { 1296 if strings.HasSuffix(soongOutDir, testOutSoongSubDir) { 1297 // The path is in the soong out dir so indicate that in the relative path. 1298 return filepath.Join(TestOutSoongDir, rel) 1299 } else { 1300 // Handle the PathForArbitraryOutput case 1301 return filepath.Join(testOutDir, rel) 1302 1303 } 1304 } 1305 1306 // Check to see if the path is relative to the top level out dir. 1307 outDir := filepath.Dir(soongOutDir) 1308 rel, isRel, err = maybeRelErr(outDir, path) 1309 if err != nil { 1310 panic(err) 1311 } 1312 1313 if isRel { 1314 // The path is in the out dir so indicate that in the relative path. 1315 return filepath.Join("out", rel) 1316 } 1317 1318 // This should never happen. 1319 panic(fmt.Errorf("internal error: absolute path %s is not relative to the out dir %s", path, outDir)) 1320} 1321 1322// StringPathsRelativeToTop creates a slice of strings where each string is the result of applying 1323// StringPathRelativeToTop to the corresponding string path in the input slice. 1324// 1325// This is provided for processing paths that have already been converted into a string, e.g. paths 1326// in AndroidMkEntries structures. As a result it needs to be supplied the soong output dir against 1327// which it can try and relativize paths. PathsRelativeToTop must be used for process Paths objects. 1328func StringPathsRelativeToTop(soongOutDir string, paths []string) []string { 1329 var result []string 1330 for _, path := range paths { 1331 relative := StringPathRelativeToTop(soongOutDir, path) 1332 result = append(result, relative) 1333 } 1334 return result 1335} 1336 1337// StringRelativeToTop will normalize a string containing paths, e.g. ninja command, by replacing 1338// any references to the test specific temporary build directory that changes with each run to a 1339// fixed path relative to a notional top directory. 1340// 1341// This is similar to StringPathRelativeToTop except that assumes the string is a single path 1342// containing at most one instance of the temporary build directory at the start of the path while 1343// this assumes that there can be any number at any position. 1344func StringRelativeToTop(config Config, command string) string { 1345 return normalizeStringRelativeToTop(config, command) 1346} 1347 1348// StringsRelativeToTop will return a new slice such that each item in the new slice is the result 1349// of calling StringRelativeToTop on the corresponding item in the input slice. 1350func StringsRelativeToTop(config Config, command []string) []string { 1351 return normalizeStringArrayRelativeToTop(config, command) 1352} 1353 1354func EnsureListContainsSuffix(t *testing.T, result []string, expected string) { 1355 t.Helper() 1356 if !SuffixInList(result, expected) { 1357 t.Errorf("%q is not found in %v", expected, result) 1358 } 1359} 1360 1361type panickingConfigAndErrorContext struct { 1362 ctx *TestContext 1363} 1364 1365func (ctx *panickingConfigAndErrorContext) OtherModulePropertyErrorf(module Module, property, fmt string, args ...interface{}) { 1366 panic(ctx.ctx.PropertyErrorf(module, property, fmt, args...).Error()) 1367} 1368 1369func (ctx *panickingConfigAndErrorContext) Config() Config { 1370 return ctx.ctx.Config() 1371} 1372 1373func (ctx *panickingConfigAndErrorContext) HasMutatorFinished(mutatorName string) bool { 1374 return ctx.ctx.HasMutatorFinished(mutatorName) 1375} 1376 1377func (ctx *panickingConfigAndErrorContext) otherModuleProvider(m blueprint.Module, p blueprint.AnyProviderKey) (any, bool) { 1378 return ctx.ctx.otherModuleProvider(m, p) 1379} 1380 1381func PanickingConfigAndErrorContext(ctx *TestContext) ConfigurableEvaluatorContext { 1382 return &panickingConfigAndErrorContext{ 1383 ctx: ctx, 1384 } 1385} 1386