testing.go 24 KB

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