testing.go 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317
  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. package android
  15. import (
  16. "bytes"
  17. "fmt"
  18. "path/filepath"
  19. "regexp"
  20. "sort"
  21. "strings"
  22. "sync"
  23. "testing"
  24. mkparser "android/soong/androidmk/parser"
  25. "github.com/google/blueprint"
  26. "github.com/google/blueprint/proptools"
  27. )
  28. func newTestContextForFixture(config Config) *TestContext {
  29. ctx := &TestContext{
  30. Context: &Context{blueprint.NewContext(), config},
  31. }
  32. ctx.postDeps = append(ctx.postDeps, registerPathDepsMutator)
  33. ctx.SetFs(ctx.config.fs)
  34. if ctx.config.mockBpList != "" {
  35. ctx.SetModuleListFile(ctx.config.mockBpList)
  36. }
  37. return ctx
  38. }
  39. func NewTestContext(config Config) *TestContext {
  40. ctx := newTestContextForFixture(config)
  41. nameResolver := NewNameResolver(config)
  42. ctx.NameResolver = nameResolver
  43. ctx.SetNameInterface(nameResolver)
  44. return ctx
  45. }
  46. var PrepareForTestWithArchMutator = GroupFixturePreparers(
  47. // Configure architecture targets in the fixture config.
  48. FixtureModifyConfig(modifyTestConfigToSupportArchMutator),
  49. // Add the arch mutator to the context.
  50. FixtureRegisterWithContext(func(ctx RegistrationContext) {
  51. ctx.PreDepsMutators(registerArchMutator)
  52. }),
  53. )
  54. var PrepareForTestWithDefaults = FixtureRegisterWithContext(func(ctx RegistrationContext) {
  55. ctx.PreArchMutators(RegisterDefaultsPreArchMutators)
  56. })
  57. var PrepareForTestWithComponentsMutator = FixtureRegisterWithContext(func(ctx RegistrationContext) {
  58. ctx.PreArchMutators(RegisterComponentsMutator)
  59. })
  60. var PrepareForTestWithPrebuilts = FixtureRegisterWithContext(RegisterPrebuiltMutators)
  61. var PrepareForTestWithOverrides = FixtureRegisterWithContext(func(ctx RegistrationContext) {
  62. ctx.PostDepsMutators(RegisterOverridePostDepsMutators)
  63. })
  64. var PrepareForTestWithLicenses = GroupFixturePreparers(
  65. FixtureRegisterWithContext(RegisterLicenseKindBuildComponents),
  66. FixtureRegisterWithContext(RegisterLicenseBuildComponents),
  67. FixtureRegisterWithContext(registerLicenseMutators),
  68. )
  69. var PrepareForTestWithGenNotice = FixtureRegisterWithContext(RegisterGenNoticeBuildComponents)
  70. func registerLicenseMutators(ctx RegistrationContext) {
  71. ctx.PreArchMutators(RegisterLicensesPackageMapper)
  72. ctx.PreArchMutators(RegisterLicensesPropertyGatherer)
  73. ctx.PostDepsMutators(RegisterLicensesDependencyChecker)
  74. }
  75. var PrepareForTestWithLicenseDefaultModules = GroupFixturePreparers(
  76. FixtureAddTextFile("build/soong/licenses/Android.bp", `
  77. license {
  78. name: "Android-Apache-2.0",
  79. package_name: "Android",
  80. license_kinds: ["SPDX-license-identifier-Apache-2.0"],
  81. copyright_notice: "Copyright (C) The Android Open Source Project",
  82. license_text: ["LICENSE"],
  83. }
  84. license_kind {
  85. name: "SPDX-license-identifier-Apache-2.0",
  86. conditions: ["notice"],
  87. url: "https://spdx.org/licenses/Apache-2.0.html",
  88. }
  89. license_kind {
  90. name: "legacy_unencumbered",
  91. conditions: ["unencumbered"],
  92. }
  93. `),
  94. FixtureAddFile("build/soong/licenses/LICENSE", nil),
  95. )
  96. var PrepareForTestWithNamespace = FixtureRegisterWithContext(func(ctx RegistrationContext) {
  97. registerNamespaceBuildComponents(ctx)
  98. ctx.PreArchMutators(RegisterNamespaceMutator)
  99. })
  100. var PrepareForTestWithMakevars = FixtureRegisterWithContext(func(ctx RegistrationContext) {
  101. ctx.RegisterSingletonType("makevars", makeVarsSingletonFunc)
  102. })
  103. // Test fixture preparer that will register most java build components.
  104. //
  105. // Singletons and mutators should only be added here if they are needed for a majority of java
  106. // module types, otherwise they should be added under a separate preparer to allow them to be
  107. // selected only when needed to reduce test execution time.
  108. //
  109. // Module types do not have much of an overhead unless they are used so this should include as many
  110. // module types as possible. The exceptions are those module types that require mutators and/or
  111. // singletons in order to function in which case they should be kept together in a separate
  112. // preparer.
  113. //
  114. // The mutators in this group were chosen because they are needed by the vast majority of tests.
  115. var PrepareForTestWithAndroidBuildComponents = GroupFixturePreparers(
  116. // Sorted alphabetically as the actual order does not matter as tests automatically enforce the
  117. // correct order.
  118. PrepareForTestWithArchMutator,
  119. PrepareForTestWithComponentsMutator,
  120. PrepareForTestWithDefaults,
  121. PrepareForTestWithFilegroup,
  122. PrepareForTestWithOverrides,
  123. PrepareForTestWithPackageModule,
  124. PrepareForTestWithPrebuilts,
  125. PrepareForTestWithVisibility,
  126. )
  127. // Prepares an integration test with all build components from the android package.
  128. //
  129. // This should only be used by tests that want to run with as much of the build enabled as possible.
  130. var PrepareForIntegrationTestWithAndroid = GroupFixturePreparers(
  131. PrepareForTestWithAndroidBuildComponents,
  132. )
  133. // Prepares a test that may be missing dependencies by setting allow_missing_dependencies to
  134. // true.
  135. var PrepareForTestWithAllowMissingDependencies = GroupFixturePreparers(
  136. FixtureModifyProductVariables(func(variables FixtureProductVariables) {
  137. variables.Allow_missing_dependencies = proptools.BoolPtr(true)
  138. }),
  139. FixtureModifyContext(func(ctx *TestContext) {
  140. ctx.SetAllowMissingDependencies(true)
  141. }),
  142. )
  143. // Prepares a test that disallows non-existent paths.
  144. var PrepareForTestDisallowNonExistentPaths = FixtureModifyConfig(func(config Config) {
  145. config.TestAllowNonExistentPaths = false
  146. })
  147. func NewTestArchContext(config Config) *TestContext {
  148. ctx := NewTestContext(config)
  149. ctx.preDeps = append(ctx.preDeps, registerArchMutator)
  150. return ctx
  151. }
  152. type TestContext struct {
  153. *Context
  154. preArch, preDeps, postDeps, finalDeps []RegisterMutatorFunc
  155. bp2buildPreArch, bp2buildMutators []RegisterMutatorFunc
  156. NameResolver *NameResolver
  157. // The list of pre-singletons and singletons registered for the test.
  158. preSingletons, singletons sortableComponents
  159. // The order in which the pre-singletons, mutators and singletons will be run in this test
  160. // context; for debugging.
  161. preSingletonOrder, mutatorOrder, singletonOrder []string
  162. }
  163. func (ctx *TestContext) PreArchMutators(f RegisterMutatorFunc) {
  164. ctx.preArch = append(ctx.preArch, f)
  165. }
  166. func (ctx *TestContext) HardCodedPreArchMutators(f RegisterMutatorFunc) {
  167. // Register mutator function as normal for testing.
  168. ctx.PreArchMutators(f)
  169. }
  170. func (ctx *TestContext) ModuleProvider(m blueprint.Module, p blueprint.ProviderKey) interface{} {
  171. return ctx.Context.ModuleProvider(m, p)
  172. }
  173. func (ctx *TestContext) PreDepsMutators(f RegisterMutatorFunc) {
  174. ctx.preDeps = append(ctx.preDeps, f)
  175. }
  176. func (ctx *TestContext) PostDepsMutators(f RegisterMutatorFunc) {
  177. ctx.postDeps = append(ctx.postDeps, f)
  178. }
  179. func (ctx *TestContext) FinalDepsMutators(f RegisterMutatorFunc) {
  180. ctx.finalDeps = append(ctx.finalDeps, f)
  181. }
  182. func (ctx *TestContext) RegisterBp2BuildConfig(config Bp2BuildConversionAllowlist) {
  183. ctx.config.Bp2buildPackageConfig = config
  184. }
  185. // PreArchBp2BuildMutators adds mutators to be register for converting Android Blueprint modules
  186. // into Bazel BUILD targets that should run prior to deps and conversion.
  187. func (ctx *TestContext) PreArchBp2BuildMutators(f RegisterMutatorFunc) {
  188. ctx.bp2buildPreArch = append(ctx.bp2buildPreArch, f)
  189. }
  190. // registeredComponentOrder defines the order in which a sortableComponent type is registered at
  191. // runtime and provides support for reordering the components registered for a test in the same
  192. // way.
  193. type registeredComponentOrder struct {
  194. // The name of the component type, used for error messages.
  195. componentType string
  196. // The names of the registered components in the order in which they were registered.
  197. namesInOrder []string
  198. // Maps from the component name to its position in the runtime ordering.
  199. namesToIndex map[string]int
  200. // A function that defines the order between two named components that can be used to sort a slice
  201. // of component names into the same order as they appear in namesInOrder.
  202. less func(string, string) bool
  203. }
  204. // registeredComponentOrderFromExistingOrder takes an existing slice of sortableComponents and
  205. // creates a registeredComponentOrder that contains a less function that can be used to sort a
  206. // subset of that list of names so it is in the same order as the original sortableComponents.
  207. func registeredComponentOrderFromExistingOrder(componentType string, existingOrder sortableComponents) registeredComponentOrder {
  208. // Only the names from the existing order are needed for this so create a list of component names
  209. // in the correct order.
  210. namesInOrder := componentsToNames(existingOrder)
  211. // Populate the map from name to position in the list.
  212. nameToIndex := make(map[string]int)
  213. for i, n := range namesInOrder {
  214. nameToIndex[n] = i
  215. }
  216. // A function to use to map from a name to an index in the original order.
  217. indexOf := func(name string) int {
  218. index, ok := nameToIndex[name]
  219. if !ok {
  220. // Should never happen as tests that use components that are not known at runtime do not sort
  221. // so should never use this function.
  222. panic(fmt.Errorf("internal error: unknown %s %q should be one of %s", componentType, name, strings.Join(namesInOrder, ", ")))
  223. }
  224. return index
  225. }
  226. // The less function.
  227. less := func(n1, n2 string) bool {
  228. i1 := indexOf(n1)
  229. i2 := indexOf(n2)
  230. return i1 < i2
  231. }
  232. return registeredComponentOrder{
  233. componentType: componentType,
  234. namesInOrder: namesInOrder,
  235. namesToIndex: nameToIndex,
  236. less: less,
  237. }
  238. }
  239. // componentsToNames maps from the slice of components to a slice of their names.
  240. func componentsToNames(components sortableComponents) []string {
  241. names := make([]string, len(components))
  242. for i, c := range components {
  243. names[i] = c.componentName()
  244. }
  245. return names
  246. }
  247. // enforceOrdering enforces the supplied components are in the same order as is defined in this
  248. // object.
  249. //
  250. // If the supplied components contains any components that are not registered at runtime, i.e. test
  251. // specific components, then it is impossible to sort them into an order that both matches the
  252. // runtime and also preserves the implicit ordering defined in the test. In that case it will not
  253. // sort the components, instead it will just check that the components are in the correct order.
  254. //
  255. // Otherwise, this will sort the supplied components in place.
  256. func (o *registeredComponentOrder) enforceOrdering(components sortableComponents) {
  257. // Check to see if the list of components contains any components that are
  258. // not registered at runtime.
  259. var unknownComponents []string
  260. testOrder := componentsToNames(components)
  261. for _, name := range testOrder {
  262. if _, ok := o.namesToIndex[name]; !ok {
  263. unknownComponents = append(unknownComponents, name)
  264. break
  265. }
  266. }
  267. // If the slice contains some unknown components then it is not possible to
  268. // sort them into an order that matches the runtime while also preserving the
  269. // order expected from the test, so in that case don't sort just check that
  270. // the order of the known mutators does match.
  271. if len(unknownComponents) > 0 {
  272. // Check order.
  273. o.checkTestOrder(testOrder, unknownComponents)
  274. } else {
  275. // Sort the components.
  276. sort.Slice(components, func(i, j int) bool {
  277. n1 := components[i].componentName()
  278. n2 := components[j].componentName()
  279. return o.less(n1, n2)
  280. })
  281. }
  282. }
  283. // checkTestOrder checks that the supplied testOrder matches the one defined by this object,
  284. // panicking if it does not.
  285. func (o *registeredComponentOrder) checkTestOrder(testOrder []string, unknownComponents []string) {
  286. lastMatchingTest := -1
  287. matchCount := 0
  288. // Take a copy of the runtime order as it is modified during the comparison.
  289. runtimeOrder := append([]string(nil), o.namesInOrder...)
  290. componentType := o.componentType
  291. for i, j := 0, 0; i < len(testOrder) && j < len(runtimeOrder); {
  292. test := testOrder[i]
  293. runtime := runtimeOrder[j]
  294. if test == runtime {
  295. testOrder[i] = test + fmt.Sprintf(" <-- matched with runtime %s %d", componentType, j)
  296. runtimeOrder[j] = runtime + fmt.Sprintf(" <-- matched with test %s %d", componentType, i)
  297. lastMatchingTest = i
  298. i += 1
  299. j += 1
  300. matchCount += 1
  301. } else if _, ok := o.namesToIndex[test]; !ok {
  302. // The test component is not registered globally so assume it is the correct place, treat it
  303. // as having matched and skip it.
  304. i += 1
  305. matchCount += 1
  306. } else {
  307. // Assume that the test list is in the same order as the runtime list but the runtime list
  308. // contains some components that are not present in the tests. So, skip the runtime component
  309. // to try and find the next one that matches the current test component.
  310. j += 1
  311. }
  312. }
  313. // If every item in the test order was either test specific or matched one in the runtime then
  314. // it is in the correct order. Otherwise, it was not so fail.
  315. if matchCount != len(testOrder) {
  316. // The test component names were not all matched with a runtime component name so there must
  317. // either be a component present in the test that is not present in the runtime or they must be
  318. // in the wrong order.
  319. testOrder[lastMatchingTest+1] = testOrder[lastMatchingTest+1] + " <--- unmatched"
  320. panic(fmt.Errorf("the tests uses test specific components %q and so cannot be automatically sorted."+
  321. " Unfortunately it uses %s components in the wrong order.\n"+
  322. "test order:\n %s\n"+
  323. "runtime order\n %s\n",
  324. SortedUniqueStrings(unknownComponents),
  325. componentType,
  326. strings.Join(testOrder, "\n "),
  327. strings.Join(runtimeOrder, "\n ")))
  328. }
  329. }
  330. // registrationSorter encapsulates the information needed to ensure that the test mutators are
  331. // registered, and thereby executed, in the same order as they are at runtime.
  332. //
  333. // It MUST be populated lazily AFTER all package initialization has been done otherwise it will
  334. // only define the order for a subset of all the registered build components that are available for
  335. // the packages being tested.
  336. //
  337. // e.g if this is initialized during say the cc package initialization then any tests run in the
  338. // java package will not sort build components registered by the java package's init() functions.
  339. type registrationSorter struct {
  340. // Used to ensure that this is only created once.
  341. once sync.Once
  342. // The order of pre-singletons
  343. preSingletonOrder registeredComponentOrder
  344. // The order of mutators
  345. mutatorOrder registeredComponentOrder
  346. // The order of singletons
  347. singletonOrder registeredComponentOrder
  348. }
  349. // populate initializes this structure from globally registered build components.
  350. //
  351. // Only the first call has any effect.
  352. func (s *registrationSorter) populate() {
  353. s.once.Do(func() {
  354. // Create an ordering from the globally registered pre-singletons.
  355. s.preSingletonOrder = registeredComponentOrderFromExistingOrder("pre-singleton", preSingletons)
  356. // Created an ordering from the globally registered mutators.
  357. globallyRegisteredMutators := collateGloballyRegisteredMutators()
  358. s.mutatorOrder = registeredComponentOrderFromExistingOrder("mutator", globallyRegisteredMutators)
  359. // Create an ordering from the globally registered singletons.
  360. globallyRegisteredSingletons := collateGloballyRegisteredSingletons()
  361. s.singletonOrder = registeredComponentOrderFromExistingOrder("singleton", globallyRegisteredSingletons)
  362. })
  363. }
  364. // Provides support for enforcing the same order in which build components are registered globally
  365. // to the order in which they are registered during tests.
  366. //
  367. // MUST only be accessed via the globallyRegisteredComponentsOrder func.
  368. var globalRegistrationSorter registrationSorter
  369. // globallyRegisteredComponentsOrder returns the globalRegistrationSorter after ensuring it is
  370. // correctly populated.
  371. func globallyRegisteredComponentsOrder() *registrationSorter {
  372. globalRegistrationSorter.populate()
  373. return &globalRegistrationSorter
  374. }
  375. func (ctx *TestContext) Register() {
  376. globalOrder := globallyRegisteredComponentsOrder()
  377. // Ensure that the pre-singletons used in the test are in the same order as they are used at
  378. // runtime.
  379. globalOrder.preSingletonOrder.enforceOrdering(ctx.preSingletons)
  380. ctx.preSingletons.registerAll(ctx.Context)
  381. mutators := collateRegisteredMutators(ctx.preArch, ctx.preDeps, ctx.postDeps, ctx.finalDeps)
  382. // Ensure that the mutators used in the test are in the same order as they are used at runtime.
  383. globalOrder.mutatorOrder.enforceOrdering(mutators)
  384. mutators.registerAll(ctx.Context)
  385. // Ensure that the singletons used in the test are in the same order as they are used at runtime.
  386. globalOrder.singletonOrder.enforceOrdering(ctx.singletons)
  387. ctx.singletons.registerAll(ctx.Context)
  388. // Save the sorted components order away to make them easy to access while debugging.
  389. ctx.preSingletonOrder = componentsToNames(preSingletons)
  390. ctx.mutatorOrder = componentsToNames(mutators)
  391. ctx.singletonOrder = componentsToNames(singletons)
  392. }
  393. // RegisterForBazelConversion prepares a test context for bp2build conversion.
  394. func (ctx *TestContext) RegisterForBazelConversion() {
  395. ctx.config.BuildMode = Bp2build
  396. RegisterMutatorsForBazelConversion(ctx.Context, ctx.bp2buildPreArch)
  397. }
  398. // RegisterForApiBazelConversion prepares a test context for API bp2build conversion.
  399. func (ctx *TestContext) RegisterForApiBazelConversion() {
  400. ctx.config.BuildMode = ApiBp2build
  401. RegisterMutatorsForApiBazelConversion(ctx.Context, ctx.bp2buildPreArch)
  402. }
  403. func (ctx *TestContext) ParseFileList(rootDir string, filePaths []string) (deps []string, errs []error) {
  404. // This function adapts the old style ParseFileList calls that are spread throughout the tests
  405. // to the new style that takes a config.
  406. return ctx.Context.ParseFileList(rootDir, filePaths, ctx.config)
  407. }
  408. func (ctx *TestContext) ParseBlueprintsFiles(rootDir string) (deps []string, errs []error) {
  409. // This function adapts the old style ParseBlueprintsFiles calls that are spread throughout the
  410. // tests to the new style that takes a config.
  411. return ctx.Context.ParseBlueprintsFiles(rootDir, ctx.config)
  412. }
  413. func (ctx *TestContext) RegisterModuleType(name string, factory ModuleFactory) {
  414. ctx.Context.RegisterModuleType(name, ModuleFactoryAdaptor(factory))
  415. }
  416. func (ctx *TestContext) RegisterSingletonModuleType(name string, factory SingletonModuleFactory) {
  417. s, m := SingletonModuleFactoryAdaptor(name, factory)
  418. ctx.RegisterSingletonType(name, s)
  419. ctx.RegisterModuleType(name, m)
  420. }
  421. func (ctx *TestContext) RegisterParallelSingletonModuleType(name string, factory SingletonModuleFactory) {
  422. s, m := SingletonModuleFactoryAdaptor(name, factory)
  423. ctx.RegisterParallelSingletonType(name, s)
  424. ctx.RegisterModuleType(name, m)
  425. }
  426. func (ctx *TestContext) RegisterSingletonType(name string, factory SingletonFactory) {
  427. ctx.singletons = append(ctx.singletons, newSingleton(name, factory, false))
  428. }
  429. func (ctx *TestContext) RegisterParallelSingletonType(name string, factory SingletonFactory) {
  430. ctx.singletons = append(ctx.singletons, newSingleton(name, factory, true))
  431. }
  432. func (ctx *TestContext) RegisterPreSingletonType(name string, factory SingletonFactory) {
  433. ctx.preSingletons = append(ctx.preSingletons, newPreSingleton(name, factory))
  434. }
  435. // ModuleVariantForTests selects a specific variant of the module with the given
  436. // name by matching the variations map against the variations of each module
  437. // variant. A module variant matches the map if every variation that exists in
  438. // both have the same value. Both the module and the map are allowed to have
  439. // extra variations that the other doesn't have. Panics if not exactly one
  440. // module variant matches.
  441. func (ctx *TestContext) ModuleVariantForTests(name string, matchVariations map[string]string) TestingModule {
  442. modules := []Module{}
  443. ctx.VisitAllModules(func(m blueprint.Module) {
  444. if ctx.ModuleName(m) == name {
  445. am := m.(Module)
  446. amMut := am.base().commonProperties.DebugMutators
  447. amVar := am.base().commonProperties.DebugVariations
  448. matched := true
  449. for i, mut := range amMut {
  450. if wantedVar, found := matchVariations[mut]; found && amVar[i] != wantedVar {
  451. matched = false
  452. break
  453. }
  454. }
  455. if matched {
  456. modules = append(modules, am)
  457. }
  458. }
  459. })
  460. if len(modules) == 0 {
  461. // Show all the modules or module variants that do exist.
  462. var allModuleNames []string
  463. var allVariants []string
  464. ctx.VisitAllModules(func(m blueprint.Module) {
  465. allModuleNames = append(allModuleNames, ctx.ModuleName(m))
  466. if ctx.ModuleName(m) == name {
  467. allVariants = append(allVariants, m.(Module).String())
  468. }
  469. })
  470. if len(allVariants) == 0 {
  471. panic(fmt.Errorf("failed to find module %q. All modules:\n %s",
  472. name, strings.Join(SortedUniqueStrings(allModuleNames), "\n ")))
  473. } else {
  474. sort.Strings(allVariants)
  475. panic(fmt.Errorf("failed to find module %q matching %v. All variants:\n %s",
  476. name, matchVariations, strings.Join(allVariants, "\n ")))
  477. }
  478. }
  479. if len(modules) > 1 {
  480. moduleStrings := []string{}
  481. for _, m := range modules {
  482. moduleStrings = append(moduleStrings, m.String())
  483. }
  484. sort.Strings(moduleStrings)
  485. panic(fmt.Errorf("module %q has more than one variant that match %v:\n %s",
  486. name, matchVariations, strings.Join(moduleStrings, "\n ")))
  487. }
  488. return newTestingModule(ctx.config, modules[0])
  489. }
  490. func (ctx *TestContext) ModuleForTests(name, variant string) TestingModule {
  491. var module Module
  492. ctx.VisitAllModules(func(m blueprint.Module) {
  493. if ctx.ModuleName(m) == name && ctx.ModuleSubDir(m) == variant {
  494. module = m.(Module)
  495. }
  496. })
  497. if module == nil {
  498. // find all the modules that do exist
  499. var allModuleNames []string
  500. var allVariants []string
  501. ctx.VisitAllModules(func(m blueprint.Module) {
  502. allModuleNames = append(allModuleNames, ctx.ModuleName(m))
  503. if ctx.ModuleName(m) == name {
  504. allVariants = append(allVariants, ctx.ModuleSubDir(m))
  505. }
  506. })
  507. sort.Strings(allVariants)
  508. if len(allVariants) == 0 {
  509. panic(fmt.Errorf("failed to find module %q. All modules:\n %s",
  510. name, strings.Join(SortedUniqueStrings(allModuleNames), "\n ")))
  511. } else {
  512. panic(fmt.Errorf("failed to find module %q variant %q. All variants:\n %s",
  513. name, variant, strings.Join(allVariants, "\n ")))
  514. }
  515. }
  516. return newTestingModule(ctx.config, module)
  517. }
  518. func (ctx *TestContext) ModuleVariantsForTests(name string) []string {
  519. var variants []string
  520. ctx.VisitAllModules(func(m blueprint.Module) {
  521. if ctx.ModuleName(m) == name {
  522. variants = append(variants, ctx.ModuleSubDir(m))
  523. }
  524. })
  525. return variants
  526. }
  527. // SingletonForTests returns a TestingSingleton for the singleton registered with the given name.
  528. func (ctx *TestContext) SingletonForTests(name string) TestingSingleton {
  529. allSingletonNames := []string{}
  530. for _, s := range ctx.Singletons() {
  531. n := ctx.SingletonName(s)
  532. if n == name {
  533. return TestingSingleton{
  534. baseTestingComponent: newBaseTestingComponent(ctx.config, s.(testBuildProvider)),
  535. singleton: s.(*singletonAdaptor).Singleton,
  536. }
  537. }
  538. allSingletonNames = append(allSingletonNames, n)
  539. }
  540. panic(fmt.Errorf("failed to find singleton %q."+
  541. "\nall singletons: %v", name, allSingletonNames))
  542. }
  543. type InstallMakeRule struct {
  544. Target string
  545. Deps []string
  546. OrderOnlyDeps []string
  547. }
  548. func parseMkRules(t *testing.T, config Config, nodes []mkparser.Node) []InstallMakeRule {
  549. var rules []InstallMakeRule
  550. for _, node := range nodes {
  551. if mkParserRule, ok := node.(*mkparser.Rule); ok {
  552. var rule InstallMakeRule
  553. if targets := mkParserRule.Target.Words(); len(targets) == 0 {
  554. t.Fatalf("no targets for rule %s", mkParserRule.Dump())
  555. } else if len(targets) > 1 {
  556. t.Fatalf("unsupported multiple targets for rule %s", mkParserRule.Dump())
  557. } else if !targets[0].Const() {
  558. t.Fatalf("unsupported non-const target for rule %s", mkParserRule.Dump())
  559. } else {
  560. rule.Target = normalizeStringRelativeToTop(config, targets[0].Value(nil))
  561. }
  562. prereqList := &rule.Deps
  563. for _, prereq := range mkParserRule.Prerequisites.Words() {
  564. if !prereq.Const() {
  565. t.Fatalf("unsupported non-const prerequisite for rule %s", mkParserRule.Dump())
  566. }
  567. if prereq.Value(nil) == "|" {
  568. prereqList = &rule.OrderOnlyDeps
  569. continue
  570. }
  571. *prereqList = append(*prereqList, normalizeStringRelativeToTop(config, prereq.Value(nil)))
  572. }
  573. rules = append(rules, rule)
  574. }
  575. }
  576. return rules
  577. }
  578. func (ctx *TestContext) InstallMakeRulesForTesting(t *testing.T) []InstallMakeRule {
  579. installs := ctx.SingletonForTests("makevars").Singleton().(*makeVarsSingleton).installsForTesting
  580. buf := bytes.NewBuffer(append([]byte(nil), installs...))
  581. parser := mkparser.NewParser("makevars", buf)
  582. nodes, errs := parser.Parse()
  583. if len(errs) > 0 {
  584. t.Fatalf("error parsing install rules: %s", errs[0])
  585. }
  586. return parseMkRules(t, ctx.config, nodes)
  587. }
  588. // MakeVarVariable provides access to make vars that will be written by the makeVarsSingleton
  589. type MakeVarVariable interface {
  590. // Name is the name of the variable.
  591. Name() string
  592. // Value is the value of the variable.
  593. Value() string
  594. }
  595. func (v makeVarsVariable) Name() string {
  596. return v.name
  597. }
  598. func (v makeVarsVariable) Value() string {
  599. return v.value
  600. }
  601. // PrepareForTestAccessingMakeVars sets up the test so that MakeVarsForTesting will work.
  602. var PrepareForTestAccessingMakeVars = GroupFixturePreparers(
  603. PrepareForTestWithAndroidMk,
  604. PrepareForTestWithMakevars,
  605. )
  606. // MakeVarsForTesting returns a filtered list of MakeVarVariable objects that represent the
  607. // variables that will be written out.
  608. //
  609. // It is necessary to use PrepareForTestAccessingMakeVars in tests that want to call this function.
  610. // Along with any other preparers needed to add the make vars.
  611. func (ctx *TestContext) MakeVarsForTesting(filter func(variable MakeVarVariable) bool) []MakeVarVariable {
  612. vars := ctx.SingletonForTests("makevars").Singleton().(*makeVarsSingleton).varsForTesting
  613. result := make([]MakeVarVariable, 0, len(vars))
  614. for _, v := range vars {
  615. if filter(v) {
  616. result = append(result, v)
  617. }
  618. }
  619. return result
  620. }
  621. func (ctx *TestContext) Config() Config {
  622. return ctx.config
  623. }
  624. type testBuildProvider interface {
  625. BuildParamsForTests() []BuildParams
  626. RuleParamsForTests() map[blueprint.Rule]blueprint.RuleParams
  627. }
  628. type TestingBuildParams struct {
  629. BuildParams
  630. RuleParams blueprint.RuleParams
  631. config Config
  632. }
  633. // RelativeToTop creates a new instance of this which has had any usages of the current test's
  634. // temporary and test specific build directory replaced with a path relative to the notional top.
  635. //
  636. // The parts of this structure which are changed are:
  637. // * BuildParams
  638. // - Args
  639. // - All Path, Paths, WritablePath and WritablePaths fields.
  640. //
  641. // * RuleParams
  642. // - Command
  643. // - Depfile
  644. // - Rspfile
  645. // - RspfileContent
  646. // - SymlinkOutputs
  647. // - CommandDeps
  648. // - CommandOrderOnly
  649. //
  650. // See PathRelativeToTop for more details.
  651. //
  652. // deprecated: this is no longer needed as TestingBuildParams are created in this form.
  653. func (p TestingBuildParams) RelativeToTop() TestingBuildParams {
  654. // If this is not a valid params then just return it back. That will make it easy to use with the
  655. // Maybe...() methods.
  656. if p.Rule == nil {
  657. return p
  658. }
  659. if p.config.config == nil {
  660. return p
  661. }
  662. // Take a copy of the build params and replace any args that contains test specific temporary
  663. // paths with paths relative to the top.
  664. bparams := p.BuildParams
  665. bparams.Depfile = normalizeWritablePathRelativeToTop(bparams.Depfile)
  666. bparams.Output = normalizeWritablePathRelativeToTop(bparams.Output)
  667. bparams.Outputs = bparams.Outputs.RelativeToTop()
  668. bparams.SymlinkOutput = normalizeWritablePathRelativeToTop(bparams.SymlinkOutput)
  669. bparams.SymlinkOutputs = bparams.SymlinkOutputs.RelativeToTop()
  670. bparams.ImplicitOutput = normalizeWritablePathRelativeToTop(bparams.ImplicitOutput)
  671. bparams.ImplicitOutputs = bparams.ImplicitOutputs.RelativeToTop()
  672. bparams.Input = normalizePathRelativeToTop(bparams.Input)
  673. bparams.Inputs = bparams.Inputs.RelativeToTop()
  674. bparams.Implicit = normalizePathRelativeToTop(bparams.Implicit)
  675. bparams.Implicits = bparams.Implicits.RelativeToTop()
  676. bparams.OrderOnly = bparams.OrderOnly.RelativeToTop()
  677. bparams.Validation = normalizePathRelativeToTop(bparams.Validation)
  678. bparams.Validations = bparams.Validations.RelativeToTop()
  679. bparams.Args = normalizeStringMapRelativeToTop(p.config, bparams.Args)
  680. // Ditto for any fields in the RuleParams.
  681. rparams := p.RuleParams
  682. rparams.Command = normalizeStringRelativeToTop(p.config, rparams.Command)
  683. rparams.Depfile = normalizeStringRelativeToTop(p.config, rparams.Depfile)
  684. rparams.Rspfile = normalizeStringRelativeToTop(p.config, rparams.Rspfile)
  685. rparams.RspfileContent = normalizeStringRelativeToTop(p.config, rparams.RspfileContent)
  686. rparams.SymlinkOutputs = normalizeStringArrayRelativeToTop(p.config, rparams.SymlinkOutputs)
  687. rparams.CommandDeps = normalizeStringArrayRelativeToTop(p.config, rparams.CommandDeps)
  688. rparams.CommandOrderOnly = normalizeStringArrayRelativeToTop(p.config, rparams.CommandOrderOnly)
  689. return TestingBuildParams{
  690. BuildParams: bparams,
  691. RuleParams: rparams,
  692. }
  693. }
  694. func normalizeWritablePathRelativeToTop(path WritablePath) WritablePath {
  695. if path == nil {
  696. return nil
  697. }
  698. return path.RelativeToTop().(WritablePath)
  699. }
  700. func normalizePathRelativeToTop(path Path) Path {
  701. if path == nil {
  702. return nil
  703. }
  704. return path.RelativeToTop()
  705. }
  706. func allOutputs(p BuildParams) []string {
  707. outputs := append(WritablePaths(nil), p.Outputs...)
  708. outputs = append(outputs, p.ImplicitOutputs...)
  709. if p.Output != nil {
  710. outputs = append(outputs, p.Output)
  711. }
  712. return outputs.Strings()
  713. }
  714. // AllOutputs returns all 'BuildParams.Output's and 'BuildParams.Outputs's in their full path string forms.
  715. func (p TestingBuildParams) AllOutputs() []string {
  716. return allOutputs(p.BuildParams)
  717. }
  718. // baseTestingComponent provides functionality common to both TestingModule and TestingSingleton.
  719. type baseTestingComponent struct {
  720. config Config
  721. provider testBuildProvider
  722. }
  723. func newBaseTestingComponent(config Config, provider testBuildProvider) baseTestingComponent {
  724. return baseTestingComponent{config, provider}
  725. }
  726. // A function that will normalize a string containing paths, e.g. ninja command, by replacing
  727. // any references to the test specific temporary build directory that changes with each run to a
  728. // fixed path relative to a notional top directory.
  729. //
  730. // This is similar to StringPathRelativeToTop except that assumes the string is a single path
  731. // containing at most one instance of the temporary build directory at the start of the path while
  732. // this assumes that there can be any number at any position.
  733. func normalizeStringRelativeToTop(config Config, s string) string {
  734. // The soongOutDir usually looks something like: /tmp/testFoo2345/001
  735. //
  736. // Replace any usage of the soongOutDir with out/soong, e.g. replace "/tmp/testFoo2345/001" with
  737. // "out/soong".
  738. outSoongDir := filepath.Clean(config.soongOutDir)
  739. re := regexp.MustCompile(`\Q` + outSoongDir + `\E\b`)
  740. s = re.ReplaceAllString(s, "out/soong")
  741. // Replace any usage of the soongOutDir/.. with out, e.g. replace "/tmp/testFoo2345" with
  742. // "out". This must come after the previous replacement otherwise this would replace
  743. // "/tmp/testFoo2345/001" with "out/001" instead of "out/soong".
  744. outDir := filepath.Dir(outSoongDir)
  745. re = regexp.MustCompile(`\Q` + outDir + `\E\b`)
  746. s = re.ReplaceAllString(s, "out")
  747. return s
  748. }
  749. // normalizeStringArrayRelativeToTop creates a new slice constructed by applying
  750. // normalizeStringRelativeToTop to each item in the slice.
  751. func normalizeStringArrayRelativeToTop(config Config, slice []string) []string {
  752. newSlice := make([]string, len(slice))
  753. for i, s := range slice {
  754. newSlice[i] = normalizeStringRelativeToTop(config, s)
  755. }
  756. return newSlice
  757. }
  758. // normalizeStringMapRelativeToTop creates a new map constructed by applying
  759. // normalizeStringRelativeToTop to each value in the map.
  760. func normalizeStringMapRelativeToTop(config Config, m map[string]string) map[string]string {
  761. newMap := map[string]string{}
  762. for k, v := range m {
  763. newMap[k] = normalizeStringRelativeToTop(config, v)
  764. }
  765. return newMap
  766. }
  767. func (b baseTestingComponent) newTestingBuildParams(bparams BuildParams) TestingBuildParams {
  768. return TestingBuildParams{
  769. config: b.config,
  770. BuildParams: bparams,
  771. RuleParams: b.provider.RuleParamsForTests()[bparams.Rule],
  772. }.RelativeToTop()
  773. }
  774. func (b baseTestingComponent) maybeBuildParamsFromRule(rule string) (TestingBuildParams, []string) {
  775. var searchedRules []string
  776. buildParams := b.provider.BuildParamsForTests()
  777. for _, p := range buildParams {
  778. ruleAsString := p.Rule.String()
  779. searchedRules = append(searchedRules, ruleAsString)
  780. if strings.Contains(ruleAsString, rule) {
  781. return b.newTestingBuildParams(p), searchedRules
  782. }
  783. }
  784. return TestingBuildParams{}, searchedRules
  785. }
  786. func (b baseTestingComponent) buildParamsFromRule(rule string) TestingBuildParams {
  787. p, searchRules := b.maybeBuildParamsFromRule(rule)
  788. if p.Rule == nil {
  789. panic(fmt.Errorf("couldn't find rule %q.\nall rules:\n%s", rule, strings.Join(searchRules, "\n")))
  790. }
  791. return p
  792. }
  793. func (b baseTestingComponent) maybeBuildParamsFromDescription(desc string) (TestingBuildParams, []string) {
  794. var searchedDescriptions []string
  795. for _, p := range b.provider.BuildParamsForTests() {
  796. searchedDescriptions = append(searchedDescriptions, p.Description)
  797. if strings.Contains(p.Description, desc) {
  798. return b.newTestingBuildParams(p), searchedDescriptions
  799. }
  800. }
  801. return TestingBuildParams{}, searchedDescriptions
  802. }
  803. func (b baseTestingComponent) buildParamsFromDescription(desc string) TestingBuildParams {
  804. p, searchedDescriptions := b.maybeBuildParamsFromDescription(desc)
  805. if p.Rule == nil {
  806. panic(fmt.Errorf("couldn't find description %q\nall descriptions:\n%s", desc, strings.Join(searchedDescriptions, "\n")))
  807. }
  808. return p
  809. }
  810. func (b baseTestingComponent) maybeBuildParamsFromOutput(file string) (TestingBuildParams, []string) {
  811. searchedOutputs := WritablePaths(nil)
  812. for _, p := range b.provider.BuildParamsForTests() {
  813. outputs := append(WritablePaths(nil), p.Outputs...)
  814. outputs = append(outputs, p.ImplicitOutputs...)
  815. if p.Output != nil {
  816. outputs = append(outputs, p.Output)
  817. }
  818. for _, f := range outputs {
  819. if f.String() == file || f.Rel() == file || PathRelativeToTop(f) == file {
  820. return b.newTestingBuildParams(p), nil
  821. }
  822. searchedOutputs = append(searchedOutputs, f)
  823. }
  824. }
  825. formattedOutputs := []string{}
  826. for _, f := range searchedOutputs {
  827. formattedOutputs = append(formattedOutputs,
  828. fmt.Sprintf("%s (rel=%s)", PathRelativeToTop(f), f.Rel()))
  829. }
  830. return TestingBuildParams{}, formattedOutputs
  831. }
  832. func (b baseTestingComponent) buildParamsFromOutput(file string) TestingBuildParams {
  833. p, searchedOutputs := b.maybeBuildParamsFromOutput(file)
  834. if p.Rule == nil {
  835. panic(fmt.Errorf("couldn't find output %q.\nall outputs:\n %s\n",
  836. file, strings.Join(searchedOutputs, "\n ")))
  837. }
  838. return p
  839. }
  840. func (b baseTestingComponent) allOutputs() []string {
  841. var outputFullPaths []string
  842. for _, p := range b.provider.BuildParamsForTests() {
  843. outputFullPaths = append(outputFullPaths, allOutputs(p)...)
  844. }
  845. return outputFullPaths
  846. }
  847. // MaybeRule finds a call to ctx.Build with BuildParams.Rule set to a rule with the given name. Returns an empty
  848. // BuildParams if no rule is found.
  849. func (b baseTestingComponent) MaybeRule(rule string) TestingBuildParams {
  850. r, _ := b.maybeBuildParamsFromRule(rule)
  851. return r
  852. }
  853. // Rule finds a call to ctx.Build with BuildParams.Rule set to a rule with the given name. Panics if no rule is found.
  854. func (b baseTestingComponent) Rule(rule string) TestingBuildParams {
  855. return b.buildParamsFromRule(rule)
  856. }
  857. // MaybeDescription finds a call to ctx.Build with BuildParams.Description set to a the given string. Returns an empty
  858. // BuildParams if no rule is found.
  859. func (b baseTestingComponent) MaybeDescription(desc string) TestingBuildParams {
  860. p, _ := b.maybeBuildParamsFromDescription(desc)
  861. return p
  862. }
  863. // Description finds a call to ctx.Build with BuildParams.Description set to a the given string. Panics if no rule is
  864. // found.
  865. func (b baseTestingComponent) Description(desc string) TestingBuildParams {
  866. return b.buildParamsFromDescription(desc)
  867. }
  868. // MaybeOutput finds a call to ctx.Build with a BuildParams.Output or BuildParams.Outputs whose String() or Rel()
  869. // value matches the provided string. Returns an empty BuildParams if no rule is found.
  870. func (b baseTestingComponent) MaybeOutput(file string) TestingBuildParams {
  871. p, _ := b.maybeBuildParamsFromOutput(file)
  872. return p
  873. }
  874. // Output finds a call to ctx.Build with a BuildParams.Output or BuildParams.Outputs whose String() or Rel()
  875. // value matches the provided string. Panics if no rule is found.
  876. func (b baseTestingComponent) Output(file string) TestingBuildParams {
  877. return b.buildParamsFromOutput(file)
  878. }
  879. // AllOutputs returns all 'BuildParams.Output's and 'BuildParams.Outputs's in their full path string forms.
  880. func (b baseTestingComponent) AllOutputs() []string {
  881. return b.allOutputs()
  882. }
  883. // TestingModule is wrapper around an android.Module that provides methods to find information about individual
  884. // ctx.Build parameters for verification in tests.
  885. type TestingModule struct {
  886. baseTestingComponent
  887. module Module
  888. }
  889. func newTestingModule(config Config, module Module) TestingModule {
  890. return TestingModule{
  891. newBaseTestingComponent(config, module),
  892. module,
  893. }
  894. }
  895. // Module returns the Module wrapped by the TestingModule.
  896. func (m TestingModule) Module() Module {
  897. return m.module
  898. }
  899. // VariablesForTestsRelativeToTop returns a copy of the Module.VariablesForTests() with every value
  900. // having any temporary build dir usages replaced with paths relative to a notional top.
  901. func (m TestingModule) VariablesForTestsRelativeToTop() map[string]string {
  902. return normalizeStringMapRelativeToTop(m.config, m.module.VariablesForTests())
  903. }
  904. // OutputFiles calls OutputFileProducer.OutputFiles on the encapsulated module, exits the test
  905. // immediately if there is an error and otherwise returns the result of calling Paths.RelativeToTop
  906. // on the returned Paths.
  907. func (m TestingModule) OutputFiles(t *testing.T, tag string) Paths {
  908. producer, ok := m.module.(OutputFileProducer)
  909. if !ok {
  910. t.Fatalf("%q must implement OutputFileProducer\n", m.module.Name())
  911. }
  912. paths, err := producer.OutputFiles(tag)
  913. if err != nil {
  914. t.Fatal(err)
  915. }
  916. return paths.RelativeToTop()
  917. }
  918. // TestingSingleton is wrapper around an android.Singleton that provides methods to find information about individual
  919. // ctx.Build parameters for verification in tests.
  920. type TestingSingleton struct {
  921. baseTestingComponent
  922. singleton Singleton
  923. }
  924. // Singleton returns the Singleton wrapped by the TestingSingleton.
  925. func (s TestingSingleton) Singleton() Singleton {
  926. return s.singleton
  927. }
  928. func FailIfErrored(t *testing.T, errs []error) {
  929. t.Helper()
  930. if len(errs) > 0 {
  931. for _, err := range errs {
  932. t.Error(err)
  933. }
  934. t.FailNow()
  935. }
  936. }
  937. // Fail if no errors that matched the regular expression were found.
  938. //
  939. // Returns true if a matching error was found, false otherwise.
  940. func FailIfNoMatchingErrors(t *testing.T, pattern string, errs []error) bool {
  941. t.Helper()
  942. matcher, err := regexp.Compile(pattern)
  943. if err != nil {
  944. t.Fatalf("failed to compile regular expression %q because %s", pattern, err)
  945. }
  946. found := false
  947. for _, err := range errs {
  948. if matcher.FindStringIndex(err.Error()) != nil {
  949. found = true
  950. break
  951. }
  952. }
  953. if !found {
  954. t.Errorf("could not match the expected error regex %q (checked %d error(s))", pattern, len(errs))
  955. for i, err := range errs {
  956. t.Errorf("errs[%d] = %q", i, err)
  957. }
  958. }
  959. return found
  960. }
  961. func CheckErrorsAgainstExpectations(t *testing.T, errs []error, expectedErrorPatterns []string) {
  962. t.Helper()
  963. if expectedErrorPatterns == nil {
  964. FailIfErrored(t, errs)
  965. } else {
  966. for _, expectedError := range expectedErrorPatterns {
  967. FailIfNoMatchingErrors(t, expectedError, errs)
  968. }
  969. if len(errs) > len(expectedErrorPatterns) {
  970. t.Errorf("additional errors found, expected %d, found %d",
  971. len(expectedErrorPatterns), len(errs))
  972. for i, expectedError := range expectedErrorPatterns {
  973. t.Errorf("expectedErrors[%d] = %s", i, expectedError)
  974. }
  975. for i, err := range errs {
  976. t.Errorf("errs[%d] = %s", i, err)
  977. }
  978. t.FailNow()
  979. }
  980. }
  981. }
  982. func SetKatiEnabledForTests(config Config) {
  983. config.katiEnabled = true
  984. }
  985. func SetTrimmedApexEnabledForTests(config Config) {
  986. config.productVariables.TrimmedApex = new(bool)
  987. *config.productVariables.TrimmedApex = true
  988. }
  989. func AndroidMkEntriesForTest(t *testing.T, ctx *TestContext, mod blueprint.Module) []AndroidMkEntries {
  990. t.Helper()
  991. var p AndroidMkEntriesProvider
  992. var ok bool
  993. if p, ok = mod.(AndroidMkEntriesProvider); !ok {
  994. t.Errorf("module does not implement AndroidMkEntriesProvider: " + mod.Name())
  995. }
  996. entriesList := p.AndroidMkEntries()
  997. for i, _ := range entriesList {
  998. entriesList[i].fillInEntries(ctx, mod)
  999. }
  1000. return entriesList
  1001. }
  1002. func AndroidMkDataForTest(t *testing.T, ctx *TestContext, mod blueprint.Module) AndroidMkData {
  1003. t.Helper()
  1004. var p AndroidMkDataProvider
  1005. var ok bool
  1006. if p, ok = mod.(AndroidMkDataProvider); !ok {
  1007. t.Fatalf("module does not implement AndroidMkDataProvider: " + mod.Name())
  1008. }
  1009. data := p.AndroidMk()
  1010. data.fillInData(ctx, mod)
  1011. return data
  1012. }
  1013. // Normalize the path for testing.
  1014. //
  1015. // If the path is relative to the build directory then return the relative path
  1016. // to avoid tests having to deal with the dynamically generated build directory.
  1017. //
  1018. // Otherwise, return the supplied path as it is almost certainly a source path
  1019. // that is relative to the root of the source tree.
  1020. //
  1021. // The build and source paths should be distinguishable based on their contents.
  1022. //
  1023. // deprecated: use PathRelativeToTop instead as it handles make install paths and differentiates
  1024. // between output and source properly.
  1025. func NormalizePathForTesting(path Path) string {
  1026. if path == nil {
  1027. return "<nil path>"
  1028. }
  1029. p := path.String()
  1030. if w, ok := path.(WritablePath); ok {
  1031. rel, err := filepath.Rel(w.getSoongOutDir(), p)
  1032. if err != nil {
  1033. panic(err)
  1034. }
  1035. return rel
  1036. }
  1037. return p
  1038. }
  1039. // NormalizePathsForTesting creates a slice of strings where each string is the result of applying
  1040. // NormalizePathForTesting to the corresponding Path in the input slice.
  1041. //
  1042. // deprecated: use PathsRelativeToTop instead as it handles make install paths and differentiates
  1043. // between output and source properly.
  1044. func NormalizePathsForTesting(paths Paths) []string {
  1045. var result []string
  1046. for _, path := range paths {
  1047. relative := NormalizePathForTesting(path)
  1048. result = append(result, relative)
  1049. }
  1050. return result
  1051. }
  1052. // PathRelativeToTop returns a string representation of the path relative to a notional top
  1053. // directory.
  1054. //
  1055. // It return "<nil path>" if the supplied path is nil, otherwise it returns the result of calling
  1056. // Path.RelativeToTop to obtain a relative Path and then calling Path.String on that to get the
  1057. // string representation.
  1058. func PathRelativeToTop(path Path) string {
  1059. if path == nil {
  1060. return "<nil path>"
  1061. }
  1062. return path.RelativeToTop().String()
  1063. }
  1064. // PathsRelativeToTop creates a slice of strings where each string is the result of applying
  1065. // PathRelativeToTop to the corresponding Path in the input slice.
  1066. func PathsRelativeToTop(paths Paths) []string {
  1067. var result []string
  1068. for _, path := range paths {
  1069. relative := PathRelativeToTop(path)
  1070. result = append(result, relative)
  1071. }
  1072. return result
  1073. }
  1074. // StringPathRelativeToTop returns a string representation of the path relative to a notional top
  1075. // directory.
  1076. //
  1077. // See Path.RelativeToTop for more details as to what `relative to top` means.
  1078. //
  1079. // This is provided for processing paths that have already been converted into a string, e.g. paths
  1080. // in AndroidMkEntries structures. As a result it needs to be supplied the soong output dir against
  1081. // which it can try and relativize paths. PathRelativeToTop must be used for process Path objects.
  1082. func StringPathRelativeToTop(soongOutDir string, path string) string {
  1083. ensureTestOnly()
  1084. // A relative path must be a source path so leave it as it is.
  1085. if !filepath.IsAbs(path) {
  1086. return path
  1087. }
  1088. // Check to see if the path is relative to the soong out dir.
  1089. rel, isRel, err := maybeRelErr(soongOutDir, path)
  1090. if err != nil {
  1091. panic(err)
  1092. }
  1093. if isRel {
  1094. // The path is in the soong out dir so indicate that in the relative path.
  1095. return filepath.Join("out/soong", rel)
  1096. }
  1097. // Check to see if the path is relative to the top level out dir.
  1098. outDir := filepath.Dir(soongOutDir)
  1099. rel, isRel, err = maybeRelErr(outDir, path)
  1100. if err != nil {
  1101. panic(err)
  1102. }
  1103. if isRel {
  1104. // The path is in the out dir so indicate that in the relative path.
  1105. return filepath.Join("out", rel)
  1106. }
  1107. // This should never happen.
  1108. panic(fmt.Errorf("internal error: absolute path %s is not relative to the out dir %s", path, outDir))
  1109. }
  1110. // StringPathsRelativeToTop creates a slice of strings where each string is the result of applying
  1111. // StringPathRelativeToTop to the corresponding string path in the input slice.
  1112. //
  1113. // This is provided for processing paths that have already been converted into a string, e.g. paths
  1114. // in AndroidMkEntries structures. As a result it needs to be supplied the soong output dir against
  1115. // which it can try and relativize paths. PathsRelativeToTop must be used for process Paths objects.
  1116. func StringPathsRelativeToTop(soongOutDir string, paths []string) []string {
  1117. var result []string
  1118. for _, path := range paths {
  1119. relative := StringPathRelativeToTop(soongOutDir, path)
  1120. result = append(result, relative)
  1121. }
  1122. return result
  1123. }
  1124. // StringRelativeToTop will normalize a string containing paths, e.g. ninja command, by replacing
  1125. // any references to the test specific temporary build directory that changes with each run to a
  1126. // fixed path relative to a notional top directory.
  1127. //
  1128. // This is similar to StringPathRelativeToTop except that assumes the string is a single path
  1129. // containing at most one instance of the temporary build directory at the start of the path while
  1130. // this assumes that there can be any number at any position.
  1131. func StringRelativeToTop(config Config, command string) string {
  1132. return normalizeStringRelativeToTop(config, command)
  1133. }
  1134. // StringsRelativeToTop will return a new slice such that each item in the new slice is the result
  1135. // of calling StringRelativeToTop on the corresponding item in the input slice.
  1136. func StringsRelativeToTop(config Config, command []string) []string {
  1137. return normalizeStringArrayRelativeToTop(config, command)
  1138. }