testing.go 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307
  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) RegisterSingletonType(name string, factory SingletonFactory) {
  422. ctx.singletons = append(ctx.singletons, newSingleton(name, factory))
  423. }
  424. func (ctx *TestContext) RegisterPreSingletonType(name string, factory SingletonFactory) {
  425. ctx.preSingletons = append(ctx.preSingletons, newPreSingleton(name, factory))
  426. }
  427. // ModuleVariantForTests selects a specific variant of the module with the given
  428. // name by matching the variations map against the variations of each module
  429. // variant. A module variant matches the map if every variation that exists in
  430. // both have the same value. Both the module and the map are allowed to have
  431. // extra variations that the other doesn't have. Panics if not exactly one
  432. // module variant matches.
  433. func (ctx *TestContext) ModuleVariantForTests(name string, matchVariations map[string]string) TestingModule {
  434. modules := []Module{}
  435. ctx.VisitAllModules(func(m blueprint.Module) {
  436. if ctx.ModuleName(m) == name {
  437. am := m.(Module)
  438. amMut := am.base().commonProperties.DebugMutators
  439. amVar := am.base().commonProperties.DebugVariations
  440. matched := true
  441. for i, mut := range amMut {
  442. if wantedVar, found := matchVariations[mut]; found && amVar[i] != wantedVar {
  443. matched = false
  444. break
  445. }
  446. }
  447. if matched {
  448. modules = append(modules, am)
  449. }
  450. }
  451. })
  452. if len(modules) == 0 {
  453. // Show all the modules or module variants that do exist.
  454. var allModuleNames []string
  455. var allVariants []string
  456. ctx.VisitAllModules(func(m blueprint.Module) {
  457. allModuleNames = append(allModuleNames, ctx.ModuleName(m))
  458. if ctx.ModuleName(m) == name {
  459. allVariants = append(allVariants, m.(Module).String())
  460. }
  461. })
  462. if len(allVariants) == 0 {
  463. panic(fmt.Errorf("failed to find module %q. All modules:\n %s",
  464. name, strings.Join(SortedUniqueStrings(allModuleNames), "\n ")))
  465. } else {
  466. sort.Strings(allVariants)
  467. panic(fmt.Errorf("failed to find module %q matching %v. All variants:\n %s",
  468. name, matchVariations, strings.Join(allVariants, "\n ")))
  469. }
  470. }
  471. if len(modules) > 1 {
  472. moduleStrings := []string{}
  473. for _, m := range modules {
  474. moduleStrings = append(moduleStrings, m.String())
  475. }
  476. sort.Strings(moduleStrings)
  477. panic(fmt.Errorf("module %q has more than one variant that match %v:\n %s",
  478. name, matchVariations, strings.Join(moduleStrings, "\n ")))
  479. }
  480. return newTestingModule(ctx.config, modules[0])
  481. }
  482. func (ctx *TestContext) ModuleForTests(name, variant string) TestingModule {
  483. var module Module
  484. ctx.VisitAllModules(func(m blueprint.Module) {
  485. if ctx.ModuleName(m) == name && ctx.ModuleSubDir(m) == variant {
  486. module = m.(Module)
  487. }
  488. })
  489. if module == nil {
  490. // find all the modules that do exist
  491. var allModuleNames []string
  492. var allVariants []string
  493. ctx.VisitAllModules(func(m blueprint.Module) {
  494. allModuleNames = append(allModuleNames, ctx.ModuleName(m))
  495. if ctx.ModuleName(m) == name {
  496. allVariants = append(allVariants, ctx.ModuleSubDir(m))
  497. }
  498. })
  499. sort.Strings(allVariants)
  500. if len(allVariants) == 0 {
  501. panic(fmt.Errorf("failed to find module %q. All modules:\n %s",
  502. name, strings.Join(SortedUniqueStrings(allModuleNames), "\n ")))
  503. } else {
  504. panic(fmt.Errorf("failed to find module %q variant %q. All variants:\n %s",
  505. name, variant, strings.Join(allVariants, "\n ")))
  506. }
  507. }
  508. return newTestingModule(ctx.config, module)
  509. }
  510. func (ctx *TestContext) ModuleVariantsForTests(name string) []string {
  511. var variants []string
  512. ctx.VisitAllModules(func(m blueprint.Module) {
  513. if ctx.ModuleName(m) == name {
  514. variants = append(variants, ctx.ModuleSubDir(m))
  515. }
  516. })
  517. return variants
  518. }
  519. // SingletonForTests returns a TestingSingleton for the singleton registered with the given name.
  520. func (ctx *TestContext) SingletonForTests(name string) TestingSingleton {
  521. allSingletonNames := []string{}
  522. for _, s := range ctx.Singletons() {
  523. n := ctx.SingletonName(s)
  524. if n == name {
  525. return TestingSingleton{
  526. baseTestingComponent: newBaseTestingComponent(ctx.config, s.(testBuildProvider)),
  527. singleton: s.(*singletonAdaptor).Singleton,
  528. }
  529. }
  530. allSingletonNames = append(allSingletonNames, n)
  531. }
  532. panic(fmt.Errorf("failed to find singleton %q."+
  533. "\nall singletons: %v", name, allSingletonNames))
  534. }
  535. type InstallMakeRule struct {
  536. Target string
  537. Deps []string
  538. OrderOnlyDeps []string
  539. }
  540. func parseMkRules(t *testing.T, config Config, nodes []mkparser.Node) []InstallMakeRule {
  541. var rules []InstallMakeRule
  542. for _, node := range nodes {
  543. if mkParserRule, ok := node.(*mkparser.Rule); ok {
  544. var rule InstallMakeRule
  545. if targets := mkParserRule.Target.Words(); len(targets) == 0 {
  546. t.Fatalf("no targets for rule %s", mkParserRule.Dump())
  547. } else if len(targets) > 1 {
  548. t.Fatalf("unsupported multiple targets for rule %s", mkParserRule.Dump())
  549. } else if !targets[0].Const() {
  550. t.Fatalf("unsupported non-const target for rule %s", mkParserRule.Dump())
  551. } else {
  552. rule.Target = normalizeStringRelativeToTop(config, targets[0].Value(nil))
  553. }
  554. prereqList := &rule.Deps
  555. for _, prereq := range mkParserRule.Prerequisites.Words() {
  556. if !prereq.Const() {
  557. t.Fatalf("unsupported non-const prerequisite for rule %s", mkParserRule.Dump())
  558. }
  559. if prereq.Value(nil) == "|" {
  560. prereqList = &rule.OrderOnlyDeps
  561. continue
  562. }
  563. *prereqList = append(*prereqList, normalizeStringRelativeToTop(config, prereq.Value(nil)))
  564. }
  565. rules = append(rules, rule)
  566. }
  567. }
  568. return rules
  569. }
  570. func (ctx *TestContext) InstallMakeRulesForTesting(t *testing.T) []InstallMakeRule {
  571. installs := ctx.SingletonForTests("makevars").Singleton().(*makeVarsSingleton).installsForTesting
  572. buf := bytes.NewBuffer(append([]byte(nil), installs...))
  573. parser := mkparser.NewParser("makevars", buf)
  574. nodes, errs := parser.Parse()
  575. if len(errs) > 0 {
  576. t.Fatalf("error parsing install rules: %s", errs[0])
  577. }
  578. return parseMkRules(t, ctx.config, nodes)
  579. }
  580. // MakeVarVariable provides access to make vars that will be written by the makeVarsSingleton
  581. type MakeVarVariable interface {
  582. // Name is the name of the variable.
  583. Name() string
  584. // Value is the value of the variable.
  585. Value() string
  586. }
  587. func (v makeVarsVariable) Name() string {
  588. return v.name
  589. }
  590. func (v makeVarsVariable) Value() string {
  591. return v.value
  592. }
  593. // PrepareForTestAccessingMakeVars sets up the test so that MakeVarsForTesting will work.
  594. var PrepareForTestAccessingMakeVars = GroupFixturePreparers(
  595. PrepareForTestWithAndroidMk,
  596. PrepareForTestWithMakevars,
  597. )
  598. // MakeVarsForTesting returns a filtered list of MakeVarVariable objects that represent the
  599. // variables that will be written out.
  600. //
  601. // It is necessary to use PrepareForTestAccessingMakeVars in tests that want to call this function.
  602. // Along with any other preparers needed to add the make vars.
  603. func (ctx *TestContext) MakeVarsForTesting(filter func(variable MakeVarVariable) bool) []MakeVarVariable {
  604. vars := ctx.SingletonForTests("makevars").Singleton().(*makeVarsSingleton).varsForTesting
  605. result := make([]MakeVarVariable, 0, len(vars))
  606. for _, v := range vars {
  607. if filter(v) {
  608. result = append(result, v)
  609. }
  610. }
  611. return result
  612. }
  613. func (ctx *TestContext) Config() Config {
  614. return ctx.config
  615. }
  616. type testBuildProvider interface {
  617. BuildParamsForTests() []BuildParams
  618. RuleParamsForTests() map[blueprint.Rule]blueprint.RuleParams
  619. }
  620. type TestingBuildParams struct {
  621. BuildParams
  622. RuleParams blueprint.RuleParams
  623. config Config
  624. }
  625. // RelativeToTop creates a new instance of this which has had any usages of the current test's
  626. // temporary and test specific build directory replaced with a path relative to the notional top.
  627. //
  628. // The parts of this structure which are changed are:
  629. // * BuildParams
  630. // - Args
  631. // - All Path, Paths, WritablePath and WritablePaths fields.
  632. //
  633. // * RuleParams
  634. // - Command
  635. // - Depfile
  636. // - Rspfile
  637. // - RspfileContent
  638. // - SymlinkOutputs
  639. // - CommandDeps
  640. // - CommandOrderOnly
  641. //
  642. // See PathRelativeToTop for more details.
  643. //
  644. // deprecated: this is no longer needed as TestingBuildParams are created in this form.
  645. func (p TestingBuildParams) RelativeToTop() TestingBuildParams {
  646. // If this is not a valid params then just return it back. That will make it easy to use with the
  647. // Maybe...() methods.
  648. if p.Rule == nil {
  649. return p
  650. }
  651. if p.config.config == nil {
  652. return p
  653. }
  654. // Take a copy of the build params and replace any args that contains test specific temporary
  655. // paths with paths relative to the top.
  656. bparams := p.BuildParams
  657. bparams.Depfile = normalizeWritablePathRelativeToTop(bparams.Depfile)
  658. bparams.Output = normalizeWritablePathRelativeToTop(bparams.Output)
  659. bparams.Outputs = bparams.Outputs.RelativeToTop()
  660. bparams.SymlinkOutput = normalizeWritablePathRelativeToTop(bparams.SymlinkOutput)
  661. bparams.SymlinkOutputs = bparams.SymlinkOutputs.RelativeToTop()
  662. bparams.ImplicitOutput = normalizeWritablePathRelativeToTop(bparams.ImplicitOutput)
  663. bparams.ImplicitOutputs = bparams.ImplicitOutputs.RelativeToTop()
  664. bparams.Input = normalizePathRelativeToTop(bparams.Input)
  665. bparams.Inputs = bparams.Inputs.RelativeToTop()
  666. bparams.Implicit = normalizePathRelativeToTop(bparams.Implicit)
  667. bparams.Implicits = bparams.Implicits.RelativeToTop()
  668. bparams.OrderOnly = bparams.OrderOnly.RelativeToTop()
  669. bparams.Validation = normalizePathRelativeToTop(bparams.Validation)
  670. bparams.Validations = bparams.Validations.RelativeToTop()
  671. bparams.Args = normalizeStringMapRelativeToTop(p.config, bparams.Args)
  672. // Ditto for any fields in the RuleParams.
  673. rparams := p.RuleParams
  674. rparams.Command = normalizeStringRelativeToTop(p.config, rparams.Command)
  675. rparams.Depfile = normalizeStringRelativeToTop(p.config, rparams.Depfile)
  676. rparams.Rspfile = normalizeStringRelativeToTop(p.config, rparams.Rspfile)
  677. rparams.RspfileContent = normalizeStringRelativeToTop(p.config, rparams.RspfileContent)
  678. rparams.SymlinkOutputs = normalizeStringArrayRelativeToTop(p.config, rparams.SymlinkOutputs)
  679. rparams.CommandDeps = normalizeStringArrayRelativeToTop(p.config, rparams.CommandDeps)
  680. rparams.CommandOrderOnly = normalizeStringArrayRelativeToTop(p.config, rparams.CommandOrderOnly)
  681. return TestingBuildParams{
  682. BuildParams: bparams,
  683. RuleParams: rparams,
  684. }
  685. }
  686. func normalizeWritablePathRelativeToTop(path WritablePath) WritablePath {
  687. if path == nil {
  688. return nil
  689. }
  690. return path.RelativeToTop().(WritablePath)
  691. }
  692. func normalizePathRelativeToTop(path Path) Path {
  693. if path == nil {
  694. return nil
  695. }
  696. return path.RelativeToTop()
  697. }
  698. func allOutputs(p BuildParams) []string {
  699. outputs := append(WritablePaths(nil), p.Outputs...)
  700. outputs = append(outputs, p.ImplicitOutputs...)
  701. if p.Output != nil {
  702. outputs = append(outputs, p.Output)
  703. }
  704. return outputs.Strings()
  705. }
  706. // AllOutputs returns all 'BuildParams.Output's and 'BuildParams.Outputs's in their full path string forms.
  707. func (p TestingBuildParams) AllOutputs() []string {
  708. return allOutputs(p.BuildParams)
  709. }
  710. // baseTestingComponent provides functionality common to both TestingModule and TestingSingleton.
  711. type baseTestingComponent struct {
  712. config Config
  713. provider testBuildProvider
  714. }
  715. func newBaseTestingComponent(config Config, provider testBuildProvider) baseTestingComponent {
  716. return baseTestingComponent{config, provider}
  717. }
  718. // A function that will normalize a string containing paths, e.g. ninja command, by replacing
  719. // any references to the test specific temporary build directory that changes with each run to a
  720. // fixed path relative to a notional top directory.
  721. //
  722. // This is similar to StringPathRelativeToTop except that assumes the string is a single path
  723. // containing at most one instance of the temporary build directory at the start of the path while
  724. // this assumes that there can be any number at any position.
  725. func normalizeStringRelativeToTop(config Config, s string) string {
  726. // The soongOutDir usually looks something like: /tmp/testFoo2345/001
  727. //
  728. // Replace any usage of the soongOutDir with out/soong, e.g. replace "/tmp/testFoo2345/001" with
  729. // "out/soong".
  730. outSoongDir := filepath.Clean(config.soongOutDir)
  731. re := regexp.MustCompile(`\Q` + outSoongDir + `\E\b`)
  732. s = re.ReplaceAllString(s, "out/soong")
  733. // Replace any usage of the soongOutDir/.. with out, e.g. replace "/tmp/testFoo2345" with
  734. // "out". This must come after the previous replacement otherwise this would replace
  735. // "/tmp/testFoo2345/001" with "out/001" instead of "out/soong".
  736. outDir := filepath.Dir(outSoongDir)
  737. re = regexp.MustCompile(`\Q` + outDir + `\E\b`)
  738. s = re.ReplaceAllString(s, "out")
  739. return s
  740. }
  741. // normalizeStringArrayRelativeToTop creates a new slice constructed by applying
  742. // normalizeStringRelativeToTop to each item in the slice.
  743. func normalizeStringArrayRelativeToTop(config Config, slice []string) []string {
  744. newSlice := make([]string, len(slice))
  745. for i, s := range slice {
  746. newSlice[i] = normalizeStringRelativeToTop(config, s)
  747. }
  748. return newSlice
  749. }
  750. // normalizeStringMapRelativeToTop creates a new map constructed by applying
  751. // normalizeStringRelativeToTop to each value in the map.
  752. func normalizeStringMapRelativeToTop(config Config, m map[string]string) map[string]string {
  753. newMap := map[string]string{}
  754. for k, v := range m {
  755. newMap[k] = normalizeStringRelativeToTop(config, v)
  756. }
  757. return newMap
  758. }
  759. func (b baseTestingComponent) newTestingBuildParams(bparams BuildParams) TestingBuildParams {
  760. return TestingBuildParams{
  761. config: b.config,
  762. BuildParams: bparams,
  763. RuleParams: b.provider.RuleParamsForTests()[bparams.Rule],
  764. }.RelativeToTop()
  765. }
  766. func (b baseTestingComponent) maybeBuildParamsFromRule(rule string) (TestingBuildParams, []string) {
  767. var searchedRules []string
  768. buildParams := b.provider.BuildParamsForTests()
  769. for _, p := range buildParams {
  770. ruleAsString := p.Rule.String()
  771. searchedRules = append(searchedRules, ruleAsString)
  772. if strings.Contains(ruleAsString, rule) {
  773. return b.newTestingBuildParams(p), searchedRules
  774. }
  775. }
  776. return TestingBuildParams{}, searchedRules
  777. }
  778. func (b baseTestingComponent) buildParamsFromRule(rule string) TestingBuildParams {
  779. p, searchRules := b.maybeBuildParamsFromRule(rule)
  780. if p.Rule == nil {
  781. panic(fmt.Errorf("couldn't find rule %q.\nall rules:\n%s", rule, strings.Join(searchRules, "\n")))
  782. }
  783. return p
  784. }
  785. func (b baseTestingComponent) maybeBuildParamsFromDescription(desc string) (TestingBuildParams, []string) {
  786. var searchedDescriptions []string
  787. for _, p := range b.provider.BuildParamsForTests() {
  788. searchedDescriptions = append(searchedDescriptions, p.Description)
  789. if strings.Contains(p.Description, desc) {
  790. return b.newTestingBuildParams(p), searchedDescriptions
  791. }
  792. }
  793. return TestingBuildParams{}, searchedDescriptions
  794. }
  795. func (b baseTestingComponent) buildParamsFromDescription(desc string) TestingBuildParams {
  796. p, searchedDescriptions := b.maybeBuildParamsFromDescription(desc)
  797. if p.Rule == nil {
  798. panic(fmt.Errorf("couldn't find description %q\nall descriptions:\n%s", desc, strings.Join(searchedDescriptions, "\n")))
  799. }
  800. return p
  801. }
  802. func (b baseTestingComponent) maybeBuildParamsFromOutput(file string) (TestingBuildParams, []string) {
  803. searchedOutputs := WritablePaths(nil)
  804. for _, p := range b.provider.BuildParamsForTests() {
  805. outputs := append(WritablePaths(nil), p.Outputs...)
  806. outputs = append(outputs, p.ImplicitOutputs...)
  807. if p.Output != nil {
  808. outputs = append(outputs, p.Output)
  809. }
  810. for _, f := range outputs {
  811. if f.String() == file || f.Rel() == file || PathRelativeToTop(f) == file {
  812. return b.newTestingBuildParams(p), nil
  813. }
  814. searchedOutputs = append(searchedOutputs, f)
  815. }
  816. }
  817. formattedOutputs := []string{}
  818. for _, f := range searchedOutputs {
  819. formattedOutputs = append(formattedOutputs,
  820. fmt.Sprintf("%s (rel=%s)", PathRelativeToTop(f), f.Rel()))
  821. }
  822. return TestingBuildParams{}, formattedOutputs
  823. }
  824. func (b baseTestingComponent) buildParamsFromOutput(file string) TestingBuildParams {
  825. p, searchedOutputs := b.maybeBuildParamsFromOutput(file)
  826. if p.Rule == nil {
  827. panic(fmt.Errorf("couldn't find output %q.\nall outputs:\n %s\n",
  828. file, strings.Join(searchedOutputs, "\n ")))
  829. }
  830. return p
  831. }
  832. func (b baseTestingComponent) allOutputs() []string {
  833. var outputFullPaths []string
  834. for _, p := range b.provider.BuildParamsForTests() {
  835. outputFullPaths = append(outputFullPaths, allOutputs(p)...)
  836. }
  837. return outputFullPaths
  838. }
  839. // MaybeRule finds a call to ctx.Build with BuildParams.Rule set to a rule with the given name. Returns an empty
  840. // BuildParams if no rule is found.
  841. func (b baseTestingComponent) MaybeRule(rule string) TestingBuildParams {
  842. r, _ := b.maybeBuildParamsFromRule(rule)
  843. return r
  844. }
  845. // Rule finds a call to ctx.Build with BuildParams.Rule set to a rule with the given name. Panics if no rule is found.
  846. func (b baseTestingComponent) Rule(rule string) TestingBuildParams {
  847. return b.buildParamsFromRule(rule)
  848. }
  849. // MaybeDescription finds a call to ctx.Build with BuildParams.Description set to a the given string. Returns an empty
  850. // BuildParams if no rule is found.
  851. func (b baseTestingComponent) MaybeDescription(desc string) TestingBuildParams {
  852. p, _ := b.maybeBuildParamsFromDescription(desc)
  853. return p
  854. }
  855. // Description finds a call to ctx.Build with BuildParams.Description set to a the given string. Panics if no rule is
  856. // found.
  857. func (b baseTestingComponent) Description(desc string) TestingBuildParams {
  858. return b.buildParamsFromDescription(desc)
  859. }
  860. // MaybeOutput finds a call to ctx.Build with a BuildParams.Output or BuildParams.Outputs whose String() or Rel()
  861. // value matches the provided string. Returns an empty BuildParams if no rule is found.
  862. func (b baseTestingComponent) MaybeOutput(file string) TestingBuildParams {
  863. p, _ := b.maybeBuildParamsFromOutput(file)
  864. return p
  865. }
  866. // Output finds a call to ctx.Build with a BuildParams.Output or BuildParams.Outputs whose String() or Rel()
  867. // value matches the provided string. Panics if no rule is found.
  868. func (b baseTestingComponent) Output(file string) TestingBuildParams {
  869. return b.buildParamsFromOutput(file)
  870. }
  871. // AllOutputs returns all 'BuildParams.Output's and 'BuildParams.Outputs's in their full path string forms.
  872. func (b baseTestingComponent) AllOutputs() []string {
  873. return b.allOutputs()
  874. }
  875. // TestingModule is wrapper around an android.Module that provides methods to find information about individual
  876. // ctx.Build parameters for verification in tests.
  877. type TestingModule struct {
  878. baseTestingComponent
  879. module Module
  880. }
  881. func newTestingModule(config Config, module Module) TestingModule {
  882. return TestingModule{
  883. newBaseTestingComponent(config, module),
  884. module,
  885. }
  886. }
  887. // Module returns the Module wrapped by the TestingModule.
  888. func (m TestingModule) Module() Module {
  889. return m.module
  890. }
  891. // VariablesForTestsRelativeToTop returns a copy of the Module.VariablesForTests() with every value
  892. // having any temporary build dir usages replaced with paths relative to a notional top.
  893. func (m TestingModule) VariablesForTestsRelativeToTop() map[string]string {
  894. return normalizeStringMapRelativeToTop(m.config, m.module.VariablesForTests())
  895. }
  896. // OutputFiles calls OutputFileProducer.OutputFiles on the encapsulated module, exits the test
  897. // immediately if there is an error and otherwise returns the result of calling Paths.RelativeToTop
  898. // on the returned Paths.
  899. func (m TestingModule) OutputFiles(t *testing.T, tag string) Paths {
  900. producer, ok := m.module.(OutputFileProducer)
  901. if !ok {
  902. t.Fatalf("%q must implement OutputFileProducer\n", m.module.Name())
  903. }
  904. paths, err := producer.OutputFiles(tag)
  905. if err != nil {
  906. t.Fatal(err)
  907. }
  908. return paths.RelativeToTop()
  909. }
  910. // TestingSingleton is wrapper around an android.Singleton that provides methods to find information about individual
  911. // ctx.Build parameters for verification in tests.
  912. type TestingSingleton struct {
  913. baseTestingComponent
  914. singleton Singleton
  915. }
  916. // Singleton returns the Singleton wrapped by the TestingSingleton.
  917. func (s TestingSingleton) Singleton() Singleton {
  918. return s.singleton
  919. }
  920. func FailIfErrored(t *testing.T, errs []error) {
  921. t.Helper()
  922. if len(errs) > 0 {
  923. for _, err := range errs {
  924. t.Error(err)
  925. }
  926. t.FailNow()
  927. }
  928. }
  929. // Fail if no errors that matched the regular expression were found.
  930. //
  931. // Returns true if a matching error was found, false otherwise.
  932. func FailIfNoMatchingErrors(t *testing.T, pattern string, errs []error) bool {
  933. t.Helper()
  934. matcher, err := regexp.Compile(pattern)
  935. if err != nil {
  936. t.Fatalf("failed to compile regular expression %q because %s", pattern, err)
  937. }
  938. found := false
  939. for _, err := range errs {
  940. if matcher.FindStringIndex(err.Error()) != nil {
  941. found = true
  942. break
  943. }
  944. }
  945. if !found {
  946. t.Errorf("could not match the expected error regex %q (checked %d error(s))", pattern, len(errs))
  947. for i, err := range errs {
  948. t.Errorf("errs[%d] = %q", i, err)
  949. }
  950. }
  951. return found
  952. }
  953. func CheckErrorsAgainstExpectations(t *testing.T, errs []error, expectedErrorPatterns []string) {
  954. t.Helper()
  955. if expectedErrorPatterns == nil {
  956. FailIfErrored(t, errs)
  957. } else {
  958. for _, expectedError := range expectedErrorPatterns {
  959. FailIfNoMatchingErrors(t, expectedError, errs)
  960. }
  961. if len(errs) > len(expectedErrorPatterns) {
  962. t.Errorf("additional errors found, expected %d, found %d",
  963. len(expectedErrorPatterns), len(errs))
  964. for i, expectedError := range expectedErrorPatterns {
  965. t.Errorf("expectedErrors[%d] = %s", i, expectedError)
  966. }
  967. for i, err := range errs {
  968. t.Errorf("errs[%d] = %s", i, err)
  969. }
  970. t.FailNow()
  971. }
  972. }
  973. }
  974. func SetKatiEnabledForTests(config Config) {
  975. config.katiEnabled = true
  976. }
  977. func SetTrimmedApexEnabledForTests(config Config) {
  978. config.productVariables.TrimmedApex = new(bool)
  979. *config.productVariables.TrimmedApex = true
  980. }
  981. func AndroidMkEntriesForTest(t *testing.T, ctx *TestContext, mod blueprint.Module) []AndroidMkEntries {
  982. t.Helper()
  983. var p AndroidMkEntriesProvider
  984. var ok bool
  985. if p, ok = mod.(AndroidMkEntriesProvider); !ok {
  986. t.Errorf("module does not implement AndroidMkEntriesProvider: " + mod.Name())
  987. }
  988. entriesList := p.AndroidMkEntries()
  989. for i, _ := range entriesList {
  990. entriesList[i].fillInEntries(ctx, mod)
  991. }
  992. return entriesList
  993. }
  994. func AndroidMkDataForTest(t *testing.T, ctx *TestContext, mod blueprint.Module) AndroidMkData {
  995. t.Helper()
  996. var p AndroidMkDataProvider
  997. var ok bool
  998. if p, ok = mod.(AndroidMkDataProvider); !ok {
  999. t.Fatalf("module does not implement AndroidMkDataProvider: " + mod.Name())
  1000. }
  1001. data := p.AndroidMk()
  1002. data.fillInData(ctx, mod)
  1003. return data
  1004. }
  1005. // Normalize the path for testing.
  1006. //
  1007. // If the path is relative to the build directory then return the relative path
  1008. // to avoid tests having to deal with the dynamically generated build directory.
  1009. //
  1010. // Otherwise, return the supplied path as it is almost certainly a source path
  1011. // that is relative to the root of the source tree.
  1012. //
  1013. // The build and source paths should be distinguishable based on their contents.
  1014. //
  1015. // deprecated: use PathRelativeToTop instead as it handles make install paths and differentiates
  1016. // between output and source properly.
  1017. func NormalizePathForTesting(path Path) string {
  1018. if path == nil {
  1019. return "<nil path>"
  1020. }
  1021. p := path.String()
  1022. if w, ok := path.(WritablePath); ok {
  1023. rel, err := filepath.Rel(w.getSoongOutDir(), p)
  1024. if err != nil {
  1025. panic(err)
  1026. }
  1027. return rel
  1028. }
  1029. return p
  1030. }
  1031. // NormalizePathsForTesting creates a slice of strings where each string is the result of applying
  1032. // NormalizePathForTesting to the corresponding Path in the input slice.
  1033. //
  1034. // deprecated: use PathsRelativeToTop instead as it handles make install paths and differentiates
  1035. // between output and source properly.
  1036. func NormalizePathsForTesting(paths Paths) []string {
  1037. var result []string
  1038. for _, path := range paths {
  1039. relative := NormalizePathForTesting(path)
  1040. result = append(result, relative)
  1041. }
  1042. return result
  1043. }
  1044. // PathRelativeToTop returns a string representation of the path relative to a notional top
  1045. // directory.
  1046. //
  1047. // It return "<nil path>" if the supplied path is nil, otherwise it returns the result of calling
  1048. // Path.RelativeToTop to obtain a relative Path and then calling Path.String on that to get the
  1049. // string representation.
  1050. func PathRelativeToTop(path Path) string {
  1051. if path == nil {
  1052. return "<nil path>"
  1053. }
  1054. return path.RelativeToTop().String()
  1055. }
  1056. // PathsRelativeToTop creates a slice of strings where each string is the result of applying
  1057. // PathRelativeToTop to the corresponding Path in the input slice.
  1058. func PathsRelativeToTop(paths Paths) []string {
  1059. var result []string
  1060. for _, path := range paths {
  1061. relative := PathRelativeToTop(path)
  1062. result = append(result, relative)
  1063. }
  1064. return result
  1065. }
  1066. // StringPathRelativeToTop returns a string representation of the path relative to a notional top
  1067. // directory.
  1068. //
  1069. // See Path.RelativeToTop for more details as to what `relative to top` means.
  1070. //
  1071. // This is provided for processing paths that have already been converted into a string, e.g. paths
  1072. // in AndroidMkEntries structures. As a result it needs to be supplied the soong output dir against
  1073. // which it can try and relativize paths. PathRelativeToTop must be used for process Path objects.
  1074. func StringPathRelativeToTop(soongOutDir string, path string) string {
  1075. ensureTestOnly()
  1076. // A relative path must be a source path so leave it as it is.
  1077. if !filepath.IsAbs(path) {
  1078. return path
  1079. }
  1080. // Check to see if the path is relative to the soong out dir.
  1081. rel, isRel, err := maybeRelErr(soongOutDir, path)
  1082. if err != nil {
  1083. panic(err)
  1084. }
  1085. if isRel {
  1086. // The path is in the soong out dir so indicate that in the relative path.
  1087. return filepath.Join("out/soong", rel)
  1088. }
  1089. // Check to see if the path is relative to the top level out dir.
  1090. outDir := filepath.Dir(soongOutDir)
  1091. rel, isRel, err = maybeRelErr(outDir, path)
  1092. if err != nil {
  1093. panic(err)
  1094. }
  1095. if isRel {
  1096. // The path is in the out dir so indicate that in the relative path.
  1097. return filepath.Join("out", rel)
  1098. }
  1099. // This should never happen.
  1100. panic(fmt.Errorf("internal error: absolute path %s is not relative to the out dir %s", path, outDir))
  1101. }
  1102. // StringPathsRelativeToTop creates a slice of strings where each string is the result of applying
  1103. // StringPathRelativeToTop to the corresponding string path in the input slice.
  1104. //
  1105. // This is provided for processing paths that have already been converted into a string, e.g. paths
  1106. // in AndroidMkEntries structures. As a result it needs to be supplied the soong output dir against
  1107. // which it can try and relativize paths. PathsRelativeToTop must be used for process Paths objects.
  1108. func StringPathsRelativeToTop(soongOutDir string, paths []string) []string {
  1109. var result []string
  1110. for _, path := range paths {
  1111. relative := StringPathRelativeToTop(soongOutDir, path)
  1112. result = append(result, relative)
  1113. }
  1114. return result
  1115. }
  1116. // StringRelativeToTop will normalize a string containing paths, e.g. ninja command, by replacing
  1117. // any references to the test specific temporary build directory that changes with each run to a
  1118. // fixed path relative to a notional top directory.
  1119. //
  1120. // This is similar to StringPathRelativeToTop except that assumes the string is a single path
  1121. // containing at most one instance of the temporary build directory at the start of the path while
  1122. // this assumes that there can be any number at any position.
  1123. func StringRelativeToTop(config Config, command string) string {
  1124. return normalizeStringRelativeToTop(config, command)
  1125. }
  1126. // StringsRelativeToTop will return a new slice such that each item in the new slice is the result
  1127. // of calling StringRelativeToTop on the corresponding item in the input slice.
  1128. func StringsRelativeToTop(config Config, command []string) []string {
  1129. return normalizeStringArrayRelativeToTop(config, command)
  1130. }