testing.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  1. // Copyright 2019 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 java
  15. import (
  16. "fmt"
  17. "reflect"
  18. "regexp"
  19. "sort"
  20. "strings"
  21. "testing"
  22. "android/soong/android"
  23. "android/soong/cc"
  24. "android/soong/dexpreopt"
  25. "github.com/google/blueprint"
  26. )
  27. const defaultJavaDir = "default/java"
  28. // Test fixture preparer that will register most java build components.
  29. //
  30. // Singletons and mutators should only be added here if they are needed for a majority of java
  31. // module types, otherwise they should be added under a separate preparer to allow them to be
  32. // selected only when needed to reduce test execution time.
  33. //
  34. // Module types do not have much of an overhead unless they are used so this should include as many
  35. // module types as possible. The exceptions are those module types that require mutators and/or
  36. // singletons in order to function in which case they should be kept together in a separate
  37. // preparer.
  38. var PrepareForTestWithJavaBuildComponents = android.GroupFixturePreparers(
  39. // Make sure that mutators and module types, e.g. prebuilt mutators available.
  40. android.PrepareForTestWithAndroidBuildComponents,
  41. // Make java build components available to the test.
  42. android.FixtureRegisterWithContext(registerRequiredBuildComponentsForTest),
  43. android.FixtureRegisterWithContext(registerJavaPluginBuildComponents),
  44. // Additional files needed in tests that disallow non-existent source files.
  45. // This includes files that are needed by all, or at least most, instances of a java module type.
  46. android.MockFS{
  47. // Needed for linter used by java_library.
  48. "build/soong/java/lint_defaults.txt": nil,
  49. // Needed for apps that do not provide their own.
  50. "build/make/target/product/security": nil,
  51. // Required to generate Java used-by API coverage
  52. "build/soong/scripts/gen_java_usedby_apex.sh": nil,
  53. }.AddToFixture(),
  54. )
  55. var prepareForTestWithFrameworkDeps = android.GroupFixturePreparers(
  56. // The java default module definitions.
  57. android.FixtureAddTextFile(defaultJavaDir+"/Android.bp", gatherRequiredDepsForTest()),
  58. // Additional files needed when test disallows non-existent source.
  59. android.MockFS{
  60. // Needed for framework-res
  61. defaultJavaDir + "/AndroidManifest.xml": nil,
  62. // Needed for framework
  63. defaultJavaDir + "/framework/aidl": nil,
  64. // Needed for various deps defined in GatherRequiredDepsForTest()
  65. defaultJavaDir + "/a.java": nil,
  66. // Needed for R8 rules on apps
  67. "build/make/core/proguard.flags": nil,
  68. "build/make/core/proguard_basic_keeps.flags": nil,
  69. }.AddToFixture(),
  70. )
  71. // Test fixture preparer that will define all default java modules except the
  72. // fake_tool_binary for dex2oatd.
  73. var PrepareForTestWithJavaDefaultModulesWithoutFakeDex2oatd = android.GroupFixturePreparers(
  74. // Make sure that all the module types used in the defaults are registered.
  75. PrepareForTestWithJavaBuildComponents,
  76. prepareForTestWithFrameworkDeps,
  77. // Add dexpreopt compat libs (android.test.base, etc.) and a fake dex2oatd module.
  78. dexpreopt.PrepareForTestWithDexpreoptCompatLibs,
  79. )
  80. // Test fixture preparer that will define default java modules, e.g. standard prebuilt modules.
  81. var PrepareForTestWithJavaDefaultModules = android.GroupFixturePreparers(
  82. PrepareForTestWithJavaDefaultModulesWithoutFakeDex2oatd,
  83. dexpreopt.PrepareForTestWithFakeDex2oatd,
  84. )
  85. // Provides everything needed by dexpreopt.
  86. var PrepareForTestWithDexpreopt = android.GroupFixturePreparers(
  87. PrepareForTestWithJavaDefaultModules,
  88. dexpreopt.PrepareForTestByEnablingDexpreopt,
  89. )
  90. var PrepareForTestWithOverlayBuildComponents = android.FixtureRegisterWithContext(registerOverlayBuildComponents)
  91. // Prepare a fixture to use all java module types, mutators and singletons fully.
  92. //
  93. // This should only be used by tests that want to run with as much of the build enabled as possible.
  94. var PrepareForIntegrationTestWithJava = android.GroupFixturePreparers(
  95. cc.PrepareForIntegrationTestWithCc,
  96. PrepareForTestWithJavaDefaultModules,
  97. )
  98. // Prepare a fixture with the standard files required by a java_sdk_library module.
  99. var PrepareForTestWithJavaSdkLibraryFiles = android.FixtureMergeMockFs(android.MockFS{
  100. "api/current.txt": nil,
  101. "api/removed.txt": nil,
  102. "api/system-current.txt": nil,
  103. "api/system-removed.txt": nil,
  104. "api/test-current.txt": nil,
  105. "api/test-removed.txt": nil,
  106. "api/module-lib-current.txt": nil,
  107. "api/module-lib-removed.txt": nil,
  108. "api/system-server-current.txt": nil,
  109. "api/system-server-removed.txt": nil,
  110. })
  111. // FixtureWithLastReleaseApis creates a preparer that creates prebuilt versions of the specified
  112. // modules for the `last` API release. By `last` it just means last in the list of supplied versions
  113. // and as this only provides one version it can be any value.
  114. //
  115. // This uses FixtureWithPrebuiltApis under the covers so the limitations of that apply to this.
  116. func FixtureWithLastReleaseApis(moduleNames ...string) android.FixturePreparer {
  117. return FixtureWithPrebuiltApis(map[string][]string{
  118. "30": moduleNames,
  119. })
  120. }
  121. // PrepareForTestWithPrebuiltsOfCurrentApi is a preparer that creates prebuilt versions of the
  122. // standard modules for the current version.
  123. //
  124. // This uses FixtureWithPrebuiltApis under the covers so the limitations of that apply to this.
  125. var PrepareForTestWithPrebuiltsOfCurrentApi = FixtureWithPrebuiltApis(map[string][]string{
  126. "current": {},
  127. // Can't have current on its own as it adds a prebuilt_apis module but doesn't add any
  128. // .txt files which causes the prebuilt_apis module to fail.
  129. "30": {},
  130. })
  131. var prepareForTestWithFrameworkJacocoInstrumentation = android.GroupFixturePreparers(
  132. android.FixtureMergeEnv(map[string]string{
  133. "EMMA_INSTRUMENT_FRAMEWORK": "true",
  134. }),
  135. PrepareForTestWithJacocoInstrumentation,
  136. )
  137. // PrepareForTestWithJacocoInstrumentation creates a mock jacocoagent library that can be
  138. // depended on as part of the build process for instrumented Java modules.
  139. var PrepareForTestWithJacocoInstrumentation = android.GroupFixturePreparers(
  140. android.FixtureMergeEnv(map[string]string{
  141. "EMMA_INSTRUMENT": "true",
  142. }),
  143. android.FixtureAddFile("jacocoagent/Test.java", nil),
  144. android.FixtureAddFile("jacocoagent/Android.bp", []byte(`
  145. java_library {
  146. name: "jacocoagent",
  147. host_supported: true,
  148. srcs: ["Test.java"],
  149. sdk_version: "current",
  150. }
  151. `)),
  152. )
  153. // FixtureWithPrebuiltApis creates a preparer that will define prebuilt api modules for the
  154. // specified releases and modules.
  155. //
  156. // The supplied map keys are the releases, e.g. current, 29, 30, etc. The values are a list of
  157. // modules for that release. Due to limitations in the prebuilt_apis module which this preparer
  158. // uses the set of releases must include at least one numbered release, i.e. it cannot just include
  159. // "current".
  160. //
  161. // This defines a file in the mock file system in a predefined location (prebuilts/sdk/Android.bp)
  162. // and so only one instance of this can be used in each fixture.
  163. func FixtureWithPrebuiltApis(release2Modules map[string][]string) android.FixturePreparer {
  164. return FixtureWithPrebuiltApisAndExtensions(release2Modules, nil)
  165. }
  166. func FixtureWithPrebuiltApisAndExtensions(apiLevel2Modules map[string][]string, extensionLevel2Modules map[string][]string) android.FixturePreparer {
  167. mockFS := android.MockFS{}
  168. path := "prebuilts/sdk/Android.bp"
  169. bp := fmt.Sprintf(`
  170. prebuilt_apis {
  171. name: "sdk",
  172. api_dirs: ["%s"],
  173. extensions_dir: "extensions",
  174. imports_sdk_version: "none",
  175. imports_compile_dex: true,
  176. }
  177. `, strings.Join(android.SortedStringKeys(apiLevel2Modules), `", "`))
  178. for release, modules := range apiLevel2Modules {
  179. mockFS.Merge(prebuiltApisFilesForModules([]string{release}, modules))
  180. }
  181. if extensionLevel2Modules != nil {
  182. for release, modules := range extensionLevel2Modules {
  183. mockFS.Merge(prebuiltExtensionApiFiles([]string{release}, modules))
  184. }
  185. }
  186. return android.GroupFixturePreparers(
  187. android.FixtureAddTextFile(path, bp),
  188. android.FixtureMergeMockFs(mockFS),
  189. )
  190. }
  191. func prebuiltApisFilesForModules(apiLevels []string, modules []string) map[string][]byte {
  192. libs := append([]string{"android"}, modules...)
  193. fs := make(map[string][]byte)
  194. for _, level := range apiLevels {
  195. apiLevel := android.ApiLevelForTest(level)
  196. for _, sdkKind := range []android.SdkKind{android.SdkPublic, android.SdkSystem, android.SdkModule, android.SdkSystemServer, android.SdkTest} {
  197. // A core-for-system-modules file must only be created for the sdk kind that supports it.
  198. if sdkKind == systemModuleKind(sdkKind, apiLevel) {
  199. fs[fmt.Sprintf("prebuilts/sdk/%s/%s/core-for-system-modules.jar", level, sdkKind)] = nil
  200. }
  201. for _, lib := range libs {
  202. // Create a jar file for every library.
  203. fs[fmt.Sprintf("prebuilts/sdk/%s/%s/%s.jar", level, sdkKind, lib)] = nil
  204. // No finalized API files for "current"
  205. if level != "current" {
  206. fs[fmt.Sprintf("prebuilts/sdk/%s/%s/api/%s.txt", level, sdkKind, lib)] = nil
  207. fs[fmt.Sprintf("prebuilts/sdk/%s/%s/api/%s-removed.txt", level, sdkKind, lib)] = nil
  208. }
  209. }
  210. }
  211. if level == "current" {
  212. fs["prebuilts/sdk/current/core/android.jar"] = nil
  213. }
  214. fs[fmt.Sprintf("prebuilts/sdk/%s/public/framework.aidl", level)] = nil
  215. }
  216. return fs
  217. }
  218. func prebuiltExtensionApiFiles(extensionLevels []string, modules []string) map[string][]byte {
  219. fs := make(map[string][]byte)
  220. for _, level := range extensionLevels {
  221. for _, sdkKind := range []android.SdkKind{android.SdkPublic, android.SdkSystem, android.SdkModule, android.SdkSystemServer} {
  222. for _, lib := range modules {
  223. fs[fmt.Sprintf("prebuilts/sdk/extensions/%s/%s/api/%s.txt", level, sdkKind, lib)] = nil
  224. fs[fmt.Sprintf("prebuilts/sdk/extensions/%s/%s/api/%s-removed.txt", level, sdkKind, lib)] = nil
  225. }
  226. }
  227. }
  228. return fs
  229. }
  230. // FixtureConfigureBootJars configures the boot jars in both the dexpreopt.GlobalConfig and
  231. // Config.productVariables structs. As a side effect that enables dexpreopt.
  232. func FixtureConfigureBootJars(bootJars ...string) android.FixturePreparer {
  233. artBootJars := []string{}
  234. for _, j := range bootJars {
  235. artApex := false
  236. for _, artApexName := range artApexNames {
  237. if strings.HasPrefix(j, artApexName+":") {
  238. artApex = true
  239. break
  240. }
  241. }
  242. if artApex {
  243. artBootJars = append(artBootJars, j)
  244. }
  245. }
  246. return android.GroupFixturePreparers(
  247. android.FixtureModifyProductVariables(func(variables android.FixtureProductVariables) {
  248. variables.BootJars = android.CreateTestConfiguredJarList(bootJars)
  249. }),
  250. dexpreopt.FixtureSetBootJars(bootJars...),
  251. dexpreopt.FixtureSetArtBootJars(artBootJars...),
  252. // Add a fake dex2oatd module.
  253. dexpreopt.PrepareForTestWithFakeDex2oatd,
  254. )
  255. }
  256. // FixtureConfigureApexBootJars configures the apex boot jars in both the
  257. // dexpreopt.GlobalConfig and Config.productVariables structs. As a side effect that enables
  258. // dexpreopt.
  259. func FixtureConfigureApexBootJars(bootJars ...string) android.FixturePreparer {
  260. return android.GroupFixturePreparers(
  261. android.FixtureModifyProductVariables(func(variables android.FixtureProductVariables) {
  262. variables.ApexBootJars = android.CreateTestConfiguredJarList(bootJars)
  263. }),
  264. dexpreopt.FixtureSetApexBootJars(bootJars...),
  265. // Add a fake dex2oatd module.
  266. dexpreopt.PrepareForTestWithFakeDex2oatd,
  267. )
  268. }
  269. // FixtureUseLegacyCorePlatformApi prepares the fixture by setting the exception list of those
  270. // modules that are allowed to use the legacy core platform API to be the ones supplied.
  271. func FixtureUseLegacyCorePlatformApi(moduleNames ...string) android.FixturePreparer {
  272. lookup := make(map[string]struct{})
  273. for _, moduleName := range moduleNames {
  274. lookup[moduleName] = struct{}{}
  275. }
  276. return android.FixtureModifyConfig(func(config android.Config) {
  277. // Try and set the legacyCorePlatformApiLookup in the config, the returned value will be the
  278. // actual value that is set.
  279. cached := config.Once(legacyCorePlatformApiLookupKey, func() interface{} {
  280. return lookup
  281. })
  282. // Make sure that the cached value is the one we need.
  283. if !reflect.DeepEqual(cached, lookup) {
  284. panic(fmt.Errorf("attempting to set legacyCorePlatformApiLookupKey to %q but it has already been set to %q", lookup, cached))
  285. }
  286. })
  287. }
  288. // registerRequiredBuildComponentsForTest registers the build components used by
  289. // PrepareForTestWithJavaDefaultModules.
  290. //
  291. // As functionality is moved out of here into separate FixturePreparer instances they should also
  292. // be moved into GatherRequiredDepsForTest for use by tests that have not yet switched to use test
  293. // fixtures.
  294. func registerRequiredBuildComponentsForTest(ctx android.RegistrationContext) {
  295. RegisterAARBuildComponents(ctx)
  296. RegisterAppBuildComponents(ctx)
  297. RegisterAppImportBuildComponents(ctx)
  298. RegisterAppSetBuildComponents(ctx)
  299. registerBootclasspathBuildComponents(ctx)
  300. registerBootclasspathFragmentBuildComponents(ctx)
  301. RegisterDexpreoptBootJarsComponents(ctx)
  302. RegisterDocsBuildComponents(ctx)
  303. RegisterGenRuleBuildComponents(ctx)
  304. registerJavaBuildComponents(ctx)
  305. registerPlatformBootclasspathBuildComponents(ctx)
  306. RegisterPrebuiltApisBuildComponents(ctx)
  307. RegisterRuntimeResourceOverlayBuildComponents(ctx)
  308. RegisterSdkLibraryBuildComponents(ctx)
  309. RegisterStubsBuildComponents(ctx)
  310. RegisterSystemModulesBuildComponents(ctx)
  311. registerSystemserverClasspathBuildComponents(ctx)
  312. registerLintBuildComponents(ctx)
  313. }
  314. // gatherRequiredDepsForTest gathers the module definitions used by
  315. // PrepareForTestWithJavaDefaultModules.
  316. //
  317. // As functionality is moved out of here into separate FixturePreparer instances they should also
  318. // be moved into GatherRequiredDepsForTest for use by tests that have not yet switched to use test
  319. // fixtures.
  320. func gatherRequiredDepsForTest() string {
  321. var bp string
  322. extraModules := []string{
  323. "core-lambda-stubs",
  324. "ext",
  325. "android_stubs_current",
  326. "android_system_stubs_current",
  327. "android_test_stubs_current",
  328. "android_module_lib_stubs_current",
  329. "android_system_server_stubs_current",
  330. "core.current.stubs",
  331. "legacy.core.platform.api.stubs",
  332. "stable.core.platform.api.stubs",
  333. "kotlin-stdlib",
  334. "kotlin-stdlib-jdk7",
  335. "kotlin-stdlib-jdk8",
  336. "kotlin-annotations",
  337. "stub-annotations",
  338. }
  339. for _, extra := range extraModules {
  340. bp += fmt.Sprintf(`
  341. java_library {
  342. name: "%s",
  343. srcs: ["a.java"],
  344. sdk_version: "none",
  345. system_modules: "stable-core-platform-api-stubs-system-modules",
  346. compile_dex: true,
  347. }
  348. `, extra)
  349. }
  350. bp += `
  351. java_library {
  352. name: "framework",
  353. srcs: ["a.java"],
  354. sdk_version: "none",
  355. system_modules: "stable-core-platform-api-stubs-system-modules",
  356. aidl: {
  357. export_include_dirs: ["framework/aidl"],
  358. },
  359. }
  360. android_app {
  361. name: "framework-res",
  362. sdk_version: "core_platform",
  363. }`
  364. systemModules := []string{
  365. "core-public-stubs-system-modules",
  366. "core-module-lib-stubs-system-modules",
  367. "legacy-core-platform-api-stubs-system-modules",
  368. "stable-core-platform-api-stubs-system-modules",
  369. }
  370. for _, extra := range systemModules {
  371. bp += fmt.Sprintf(`
  372. java_system_modules {
  373. name: "%[1]s",
  374. libs: ["%[1]s-lib"],
  375. }
  376. java_library {
  377. name: "%[1]s-lib",
  378. sdk_version: "none",
  379. system_modules: "none",
  380. }
  381. `, extra)
  382. }
  383. // Make sure that the dex_bootjars singleton module is instantiated for the tests.
  384. bp += `
  385. dex_bootjars {
  386. name: "dex_bootjars",
  387. }
  388. `
  389. return bp
  390. }
  391. func CheckModuleDependencies(t *testing.T, ctx *android.TestContext, name, variant string, expected []string) {
  392. t.Helper()
  393. module := ctx.ModuleForTests(name, variant).Module()
  394. deps := []string{}
  395. ctx.VisitDirectDeps(module, func(m blueprint.Module) {
  396. deps = append(deps, m.Name())
  397. })
  398. sort.Strings(deps)
  399. if actual := deps; !reflect.DeepEqual(expected, actual) {
  400. t.Errorf("expected %#q, found %#q", expected, actual)
  401. }
  402. }
  403. // CheckPlatformBootclasspathModules returns the apex:module pair for the modules depended upon by
  404. // the platform-bootclasspath module.
  405. func CheckPlatformBootclasspathModules(t *testing.T, result *android.TestResult, name string, expected []string) {
  406. t.Helper()
  407. platformBootclasspath := result.Module(name, "android_common").(*platformBootclasspathModule)
  408. pairs := ApexNamePairsFromModules(result.TestContext, platformBootclasspath.configuredModules)
  409. android.AssertDeepEquals(t, fmt.Sprintf("%s modules", "platform-bootclasspath"), expected, pairs)
  410. }
  411. func CheckClasspathFragmentProtoContentInfoProvider(t *testing.T, result *android.TestResult, generated bool, contents, outputFilename, installDir string) {
  412. t.Helper()
  413. p := result.Module("platform-bootclasspath", "android_common").(*platformBootclasspathModule)
  414. info := result.ModuleProvider(p, ClasspathFragmentProtoContentInfoProvider).(ClasspathFragmentProtoContentInfo)
  415. android.AssertBoolEquals(t, "classpath proto generated", generated, info.ClasspathFragmentProtoGenerated)
  416. android.AssertStringEquals(t, "classpath proto contents", contents, info.ClasspathFragmentProtoContents.String())
  417. android.AssertStringEquals(t, "output filepath", outputFilename, info.ClasspathFragmentProtoOutput.Base())
  418. android.AssertPathRelativeToTopEquals(t, "install filepath", installDir, info.ClasspathFragmentProtoInstallDir)
  419. }
  420. // ApexNamePairsFromModules returns the apex:module pair for the supplied modules.
  421. func ApexNamePairsFromModules(ctx *android.TestContext, modules []android.Module) []string {
  422. pairs := []string{}
  423. for _, module := range modules {
  424. pairs = append(pairs, apexNamePairFromModule(ctx, module))
  425. }
  426. return pairs
  427. }
  428. func apexNamePairFromModule(ctx *android.TestContext, module android.Module) string {
  429. name := module.Name()
  430. var apex string
  431. apexInfo := ctx.ModuleProvider(module, android.ApexInfoProvider).(android.ApexInfo)
  432. if apexInfo.IsForPlatform() {
  433. apex = "platform"
  434. } else {
  435. apex = apexInfo.InApexVariants[0]
  436. }
  437. return fmt.Sprintf("%s:%s", apex, name)
  438. }
  439. // CheckPlatformBootclasspathFragments returns the apex:module pair for the fragments depended upon
  440. // by the platform-bootclasspath module.
  441. func CheckPlatformBootclasspathFragments(t *testing.T, result *android.TestResult, name string, expected []string) {
  442. t.Helper()
  443. platformBootclasspath := result.Module(name, "android_common").(*platformBootclasspathModule)
  444. pairs := ApexNamePairsFromModules(result.TestContext, platformBootclasspath.fragments)
  445. android.AssertDeepEquals(t, fmt.Sprintf("%s fragments", "platform-bootclasspath"), expected, pairs)
  446. }
  447. func CheckHiddenAPIRuleInputs(t *testing.T, message string, expected string, hiddenAPIRule android.TestingBuildParams) {
  448. t.Helper()
  449. inputs := android.Paths{}
  450. if hiddenAPIRule.Input != nil {
  451. inputs = append(inputs, hiddenAPIRule.Input)
  452. }
  453. inputs = append(inputs, hiddenAPIRule.Inputs...)
  454. inputs = append(inputs, hiddenAPIRule.Implicits...)
  455. inputs = android.SortedUniquePaths(inputs)
  456. actual := strings.TrimSpace(strings.Join(inputs.RelativeToTop().Strings(), "\n"))
  457. re := regexp.MustCompile(`\n\s+`)
  458. expected = strings.TrimSpace(re.ReplaceAllString(expected, "\n"))
  459. if actual != expected {
  460. t.Errorf("Expected hiddenapi rule inputs - %s:\n%s\nactual inputs:\n%s", message, expected, actual)
  461. }
  462. }
  463. // Check that the merged file create by platform_compat_config_singleton has the correct inputs.
  464. func CheckMergedCompatConfigInputs(t *testing.T, result *android.TestResult, message string, expectedPaths ...string) {
  465. sourceGlobalCompatConfig := result.SingletonForTests("platform_compat_config_singleton")
  466. allOutputs := sourceGlobalCompatConfig.AllOutputs()
  467. android.AssertIntEquals(t, message+": output len", 1, len(allOutputs))
  468. output := sourceGlobalCompatConfig.Output(allOutputs[0])
  469. android.AssertPathsRelativeToTopEquals(t, message+": inputs", expectedPaths, output.Implicits)
  470. }
  471. // Register the fake APEX mutator to `android.InitRegistrationContext` as if the real mutator exists
  472. // at runtime. This must be called in `init()` of a test if the test is going to use the fake APEX
  473. // mutator. Otherwise, we will be missing the runtime mutator because "soong-apex" is not a
  474. // dependency, which will cause an inconsistency between testing and runtime mutators.
  475. func RegisterFakeRuntimeApexMutator() {
  476. registerFakeApexMutator(android.InitRegistrationContext)
  477. }
  478. var PrepareForTestWithFakeApexMutator = android.GroupFixturePreparers(
  479. android.FixtureRegisterWithContext(registerFakeApexMutator),
  480. )
  481. func registerFakeApexMutator(ctx android.RegistrationContext) {
  482. ctx.PostDepsMutators(func(ctx android.RegisterMutatorsContext) {
  483. ctx.BottomUp("apex", fakeApexMutator).Parallel()
  484. })
  485. }
  486. type apexModuleBase interface {
  487. ApexAvailable() []string
  488. }
  489. var _ apexModuleBase = (*Library)(nil)
  490. var _ apexModuleBase = (*SdkLibrary)(nil)
  491. // A fake APEX mutator that creates a platform variant and an APEX variant for modules with
  492. // `apex_available`. It helps us avoid a dependency on the real mutator defined in "soong-apex",
  493. // which will cause a cyclic dependency, and it provides an easy way to create an APEX variant for
  494. // testing without dealing with all the complexities in the real mutator.
  495. func fakeApexMutator(mctx android.BottomUpMutatorContext) {
  496. switch mctx.Module().(type) {
  497. case *Library, *SdkLibrary:
  498. if len(mctx.Module().(apexModuleBase).ApexAvailable()) > 0 {
  499. modules := mctx.CreateVariations("", "apex1000")
  500. apexInfo := android.ApexInfo{
  501. ApexVariationName: "apex1000",
  502. }
  503. mctx.SetVariationProvider(modules[1], android.ApexInfoProvider, apexInfo)
  504. }
  505. }
  506. }
  507. // Applies the given modifier on the boot image config with the given name.
  508. func FixtureModifyBootImageConfig(name string, configModifier func(*bootImageConfig)) android.FixturePreparer {
  509. return android.FixtureModifyConfig(func(androidConfig android.Config) {
  510. pathCtx := android.PathContextForTesting(androidConfig)
  511. config := genBootImageConfigRaw(pathCtx)
  512. configModifier(config[name])
  513. })
  514. }
  515. // Sets the value of `installDirOnDevice` of the boot image config with the given name.
  516. func FixtureSetBootImageInstallDirOnDevice(name string, installDir string) android.FixturePreparer {
  517. return FixtureModifyBootImageConfig(name, func(config *bootImageConfig) {
  518. config.installDirOnDevice = installDir
  519. })
  520. }