1package tradefed_modules 2 3import ( 4 "android/soong/android" 5 "android/soong/tradefed" 6 "encoding/json" 7 "fmt" 8 "io" 9 "slices" 10 "strings" 11 12 "github.com/google/blueprint" 13 "github.com/google/blueprint/proptools" 14) 15 16func init() { 17 RegisterTestModuleConfigBuildComponents(android.InitRegistrationContext) 18} 19 20// Register the license_kind module type. 21func RegisterTestModuleConfigBuildComponents(ctx android.RegistrationContext) { 22 ctx.RegisterModuleType("test_module_config", TestModuleConfigFactory) 23 ctx.RegisterModuleType("test_module_config_host", TestModuleConfigHostFactory) 24} 25 26type testModuleConfigModule struct { 27 android.ModuleBase 28 android.DefaultableModuleBase 29 30 tradefedProperties 31 32 // Our updated testConfig. 33 testConfig android.OutputPath 34 manifest android.OutputPath 35 provider tradefed.BaseTestProviderData 36 37 supportFiles android.InstallPaths 38 39 isHost bool 40} 41 42// Host is mostly the same as non-host, just some diffs for AddDependency and 43// AndroidMkEntries, but the properties are the same. 44type testModuleConfigHostModule struct { 45 testModuleConfigModule 46} 47 48// Properties to list in Android.bp for this module. 49type tradefedProperties struct { 50 // Module name of the base test that we will run. 51 Base *string `android:"path,arch_variant"` 52 53 // Tradefed Options to add to tradefed xml when not one of the include or exclude filter or property. 54 // Sample: [{name: "TestRunnerOptionName", value: "OptionValue" }] 55 Options []tradefed.Option 56 57 // List of tradefed include annotations to add to tradefed xml, like "android.platform.test.annotations.Presubmit". 58 // Tests will be restricted to those matching an include_annotation or include_filter. 59 Include_annotations []string 60 61 // List of tradefed include annotations to add to tradefed xml, like "android.support.test.filters.FlakyTest". 62 // Tests matching an exclude annotation or filter will be skipped. 63 Exclude_annotations []string 64 65 // List of tradefed include filters to add to tradefed xml, like "fully.qualified.class#method". 66 // Tests will be restricted to those matching an include_annotation or include_filter. 67 Include_filters []string 68 69 // List of tradefed exclude filters to add to tradefed xml, like "fully.qualified.class#method". 70 // Tests matching an exclude annotation or filter will be skipped. 71 Exclude_filters []string 72 73 // List of compatibility suites (for example "cts", "vts") that the module should be 74 // installed into. 75 Test_suites []string 76} 77 78type dependencyTag struct { 79 blueprint.BaseDependencyTag 80 name string 81} 82 83var ( 84 testModuleConfigTag = dependencyTag{name: "TestModuleConfigBase"} 85 testModuleConfigHostTag = dependencyTag{name: "TestModuleConfigHostBase"} 86 pctx = android.NewPackageContext("android/soong/tradefed_modules") 87) 88 89func (m *testModuleConfigModule) InstallInTestcases() bool { 90 return true 91} 92 93func (m *testModuleConfigModule) DepsMutator(ctx android.BottomUpMutatorContext) { 94 if m.Base == nil { 95 ctx.ModuleErrorf("'base' field must be set to a 'android_test' module.") 96 return 97 } 98 ctx.AddDependency(ctx.Module(), testModuleConfigTag, *m.Base) 99} 100 101// Takes base's Tradefed Config xml file and generates a new one with the test properties 102// appeneded from this module. 103func (m *testModuleConfigModule) fixTestConfig(ctx android.ModuleContext, baseTestConfig android.Path) android.OutputPath { 104 // Test safe to do when no test_runner_options, but check for that earlier? 105 fixedConfig := android.PathForModuleOut(ctx, "test_config_fixer", ctx.ModuleName()+".config") 106 rule := android.NewRuleBuilder(pctx, ctx) 107 command := rule.Command().BuiltTool("test_config_fixer").Input(baseTestConfig).Output(fixedConfig) 108 options := m.composeOptions() 109 if len(options) == 0 { 110 ctx.ModuleErrorf("Test options must be given when using test_module_config. Set include/exclude filter or annotation.") 111 } 112 xmlTestModuleConfigSnippet, _ := json.Marshal(options) 113 escaped := proptools.NinjaAndShellEscape(string(xmlTestModuleConfigSnippet)) 114 command.FlagWithArg("--test-runner-options=", escaped) 115 116 rule.Build("fix_test_config", "fix test config") 117 return fixedConfig.OutputPath 118} 119 120// Convert --exclude_filters: ["filter1", "filter2"] -> 121// [ Option{Name: "exclude-filters", Value: "filter1"}, Option{Name: "exclude-filters", Value: "filter2"}, 122// ... + include + annotations ] 123func (m *testModuleConfigModule) composeOptions() []tradefed.Option { 124 options := m.Options 125 for _, e := range m.Exclude_filters { 126 options = append(options, tradefed.Option{Name: "exclude-filter", Value: e}) 127 } 128 for _, i := range m.Include_filters { 129 options = append(options, tradefed.Option{Name: "include-filter", Value: i}) 130 } 131 for _, e := range m.Exclude_annotations { 132 options = append(options, tradefed.Option{Name: "exclude-annotation", Value: e}) 133 } 134 for _, i := range m.Include_annotations { 135 options = append(options, tradefed.Option{Name: "include-annotation", Value: i}) 136 } 137 return options 138} 139 140// Files to write and where they come from: 141// 1) test_module_config.manifest 142// - Leave a trail of where we got files from in case other tools need it. 143// 144// 2) $Module.config 145// - comes from base's module.config (AndroidTest.xml), and then we add our test_options. 146// provider.TestConfig 147// [rules via soong_app_prebuilt] 148// 149// 3) $ARCH/$Module.apk 150// - comes from base 151// provider.OutputFile 152// [rules via soong_app_prebuilt] 153// 154// 4) [bases data] 155// - We copy all of bases data (like helper apks) to our install directory too. 156// Since we call AndroidMkEntries on base, it will write out LOCAL_COMPATIBILITY_SUPPORT_FILES 157// with this data and app_prebuilt.mk will generate the rules to copy it from base. 158// We have no direct rules here to add to ninja. 159// 160// If we change to symlinks, this all needs to change. 161func (m *testModuleConfigModule) GenerateAndroidBuildActions(ctx android.ModuleContext) { 162 m.validateBase(ctx, &testModuleConfigTag, "android_test", false) 163 m.generateManifestAndConfig(ctx) 164 165} 166 167// Ensure at least one test_suite is listed. Ideally it should be general-tests 168// or device-tests, whichever is listed in base and prefer general-tests if both are listed. 169// However this is not enforced yet. 170// 171// Returns true if okay and reports errors via ModuleErrorf. 172func (m *testModuleConfigModule) validateTestSuites(ctx android.ModuleContext) bool { 173 if len(m.tradefedProperties.Test_suites) == 0 { 174 ctx.ModuleErrorf("At least one test-suite must be set or this won't run. Use \"general-tests\" or \"device-tests\"") 175 return false 176 } 177 178 var extra_derived_suites []string 179 // Ensure all suites listed are also in base. 180 for _, s := range m.tradefedProperties.Test_suites { 181 if !slices.Contains(m.provider.TestSuites, s) { 182 extra_derived_suites = append(extra_derived_suites, s) 183 } 184 } 185 if len(extra_derived_suites) != 0 { 186 ctx.ModuleErrorf("Suites: [%s] listed but do not exist in base module: %s", 187 strings.Join(extra_derived_suites, ", "), 188 *m.tradefedProperties.Base) 189 return false 190 } 191 192 return true 193} 194 195func TestModuleConfigFactory() android.Module { 196 module := &testModuleConfigModule{} 197 198 module.AddProperties(&module.tradefedProperties) 199 android.InitAndroidArchModule(module, android.DeviceSupported, android.MultilibFirst) 200 android.InitDefaultableModule(module) 201 202 return module 203} 204 205func TestModuleConfigHostFactory() android.Module { 206 module := &testModuleConfigHostModule{} 207 208 module.AddProperties(&module.tradefedProperties) 209 android.InitAndroidMultiTargetsArchModule(module, android.HostSupported, android.MultilibCommon) 210 android.InitDefaultableModule(module) 211 module.isHost = true 212 213 return module 214} 215 216// Implements android.AndroidMkEntriesProvider 217var _ android.AndroidMkEntriesProvider = (*testModuleConfigModule)(nil) 218 219func (m *testModuleConfigModule) nativeExtraEntries(entries *android.AndroidMkEntries) { 220 // TODO(ron) provider for suffix and STEM? 221 entries.SetString("LOCAL_MODULE_SUFFIX", "") 222 // Should the stem and path use the base name or our module name? 223 entries.SetString("LOCAL_MODULE_STEM", m.provider.OutputFile.Rel()) 224 entries.SetPath("LOCAL_MODULE_PATH", m.provider.InstallDir) 225} 226 227func (m *testModuleConfigModule) javaExtraEntries(entries *android.AndroidMkEntries) { 228 // The app_prebuilt_internal.mk files try create a copy of the OutputFile as an .apk. 229 // Normally, this copies the "package.apk" from the intermediate directory here. 230 // To prevent the copy of the large apk and to prevent confusion with the real .apk we 231 // link to, we set the STEM here to a bogus name and we set OutputFile to a small file (our manifest). 232 // We do this so we don't have to add more conditionals to base_rules.mk 233 // soong_java_prebult has the same issue for .jars so use this in both module types. 234 entries.SetString("LOCAL_MODULE_STEM", fmt.Sprintf("UNUSED-%s", *m.Base)) 235 entries.SetString("LOCAL_MODULE_TAGS", "tests") 236} 237 238func (m *testModuleConfigModule) AndroidMkEntries() []android.AndroidMkEntries { 239 appClass := m.provider.MkAppClass 240 include := m.provider.MkInclude 241 return []android.AndroidMkEntries{{ 242 Class: appClass, 243 OutputFile: android.OptionalPathForPath(m.manifest), 244 Include: include, 245 Required: []string{*m.Base}, 246 ExtraEntries: []android.AndroidMkExtraEntriesFunc{ 247 func(ctx android.AndroidMkExtraEntriesContext, entries *android.AndroidMkEntries) { 248 entries.SetPath("LOCAL_FULL_TEST_CONFIG", m.testConfig) 249 entries.SetString("LOCAL_TEST_MODULE_CONFIG_BASE", *m.Base) 250 if m.provider.LocalSdkVersion != "" { 251 entries.SetString("LOCAL_SDK_VERSION", m.provider.LocalSdkVersion) 252 } 253 if m.provider.LocalCertificate != "" { 254 entries.SetString("LOCAL_CERTIFICATE", m.provider.LocalCertificate) 255 } 256 257 entries.SetBoolIfTrue("LOCAL_IS_UNIT_TEST", m.provider.IsUnitTest) 258 entries.AddCompatibilityTestSuites(m.tradefedProperties.Test_suites...) 259 entries.AddStrings("LOCAL_HOST_REQUIRED_MODULES", m.provider.HostRequiredModuleNames...) 260 261 if m.provider.MkAppClass == "NATIVE_TESTS" { 262 m.nativeExtraEntries(entries) 263 } else { 264 m.javaExtraEntries(entries) 265 } 266 267 // In normal java/app modules, the module writes LOCAL_COMPATIBILITY_SUPPORT_FILES 268 // and then base_rules.mk ends up copying each of those dependencies from .intermediates to the install directory. 269 // tasks/general-tests.mk, tasks/devices-tests.mk also use these to figure out 270 // which testcase files to put in a zip for running tests on another machine. 271 // 272 // We need our files to end up in the zip, but we don't want \.mk files to 273 // `install` files for us. 274 // So we create a new make variable to indicate these should be in the zip 275 // but not installed. 276 entries.AddStrings("LOCAL_SOONG_INSTALLED_COMPATIBILITY_SUPPORT_FILES", m.supportFiles.Strings()...) 277 }, 278 }, 279 // Ensure each of our supportFiles depends on the installed file in base so that our symlinks will always 280 // resolve. The provider gives us the .intermediate path for the support file in base, we change it to 281 // the installed path with a string substitution. 282 ExtraFooters: []android.AndroidMkExtraFootersFunc{ 283 func(w io.Writer, name, prefix, moduleDir string) { 284 for _, f := range m.supportFiles.Strings() { 285 // convert out/.../testcases/FrameworksServicesTests_contentprotection/file1.apk 286 // to out/.../testcases/FrameworksServicesTests/file1.apk 287 basePath := strings.Replace(f, "/"+m.Name()+"/", "/"+*m.Base+"/", 1) 288 fmt.Fprintf(w, "%s: %s\n", f, basePath) 289 } 290 }, 291 }, 292 }} 293} 294 295func (m *testModuleConfigHostModule) DepsMutator(ctx android.BottomUpMutatorContext) { 296 if m.Base == nil { 297 ctx.ModuleErrorf("'base' field must be set to a 'java_test_host' module") 298 return 299 } 300 ctx.AddVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), testModuleConfigHostTag, *m.Base) 301} 302 303// File to write: 304// 1) out/host/linux-x86/testcases/derived-module/test_module_config.manifest # contains base's name. 305// 2) out/host/linux-x86/testcases/derived-module/derived-module.config # Update AnroidTest.xml 306// 3) out/host/linux-x86/testcases/derived-module/base.jar 307// - written via soong_java_prebuilt.mk 308// 309// 4) out/host/linux-x86/testcases/derived-module/* # data dependencies from base. 310// - written via our InstallSymlink 311func (m *testModuleConfigHostModule) GenerateAndroidBuildActions(ctx android.ModuleContext) { 312 m.validateBase(ctx, &testModuleConfigHostTag, "java_test_host", true) 313 m.generateManifestAndConfig(ctx) 314} 315 316// Ensure the base listed is the right type by checking that we get the expected provider data. 317// Returns false on errors and the context is updated with an error indicating the baseType expected. 318func (m *testModuleConfigModule) validateBase(ctx android.ModuleContext, depTag *dependencyTag, baseType string, baseShouldBeHost bool) { 319 ctx.VisitDirectDepsWithTag(*depTag, func(dep android.Module) { 320 if provider, ok := android.OtherModuleProvider(ctx, dep, tradefed.BaseTestProviderKey); ok { 321 if baseShouldBeHost == provider.IsHost { 322 m.provider = provider 323 } else { 324 if baseShouldBeHost { 325 ctx.ModuleErrorf("'android_test' module used as base, but 'java_test_host' expected.") 326 } else { 327 ctx.ModuleErrorf("'java_test_host' module used as base, but 'android_test' expected.") 328 } 329 } 330 } else { 331 ctx.ModuleErrorf("'%s' module used as base but it is not a '%s' module.", *m.Base, baseType) 332 } 333 }) 334} 335 336// Actions to write: 337// 1. manifest file to testcases dir 338// 2. Symlink to base.apk under base's arch dir 339// 3. Symlink to all data dependencies 340// 4. New Module.config / AndroidTest.xml file with our options. 341func (m *testModuleConfigModule) generateManifestAndConfig(ctx android.ModuleContext) { 342 // Keep before early returns. 343 android.SetProvider(ctx, android.TestOnlyProviderKey, android.TestModuleInformation{ 344 TestOnly: true, 345 TopLevelTarget: true, 346 }) 347 348 if !m.validateTestSuites(ctx) { 349 return 350 } 351 // Ensure the base provider is accurate 352 if m.provider.TestConfig == nil { 353 return 354 } 355 // 1) A manifest file listing the base, write text to a tiny file. 356 installDir := android.PathForModuleInstall(ctx, ctx.ModuleName()) 357 manifest := android.PathForModuleOut(ctx, "test_module_config.manifest") 358 android.WriteFileRule(ctx, manifest, fmt.Sprintf("{%q: %q}", "base", *m.tradefedProperties.Base)) 359 // build/soong/android/androidmk.go has this comment: 360 // Assume the primary install file is last 361 // so we need to Install our file last. 362 ctx.InstallFile(installDir, manifest.Base(), manifest) 363 m.manifest = manifest.OutputPath 364 365 // 2) Symlink to base.apk 366 baseApk := m.provider.OutputFile 367 368 // Typically looks like this for baseApk 369 // FrameworksServicesTests 370 // └── x86_64 371 // └── FrameworksServicesTests.apk 372 if m.provider.MkAppClass != "NATIVE_TESTS" { 373 symlinkName := fmt.Sprintf("%s/%s", ctx.DeviceConfig().DeviceArch(), baseApk.Base()) 374 // Only android_test, not java_host_test puts the output in the DeviceArch dir. 375 if m.provider.IsHost || ctx.DeviceConfig().DeviceArch() == "" { 376 // testcases/CtsDevicePolicyManagerTestCases 377 // ├── CtsDevicePolicyManagerTestCases.jar 378 symlinkName = baseApk.Base() 379 } 380 381 target := installedBaseRelativeToHere(symlinkName, *m.tradefedProperties.Base) 382 installedApk := ctx.InstallAbsoluteSymlink(installDir, symlinkName, target) 383 m.supportFiles = append(m.supportFiles, installedApk) 384 } 385 386 // 3) Symlink for all data deps 387 // And like this for data files and required modules 388 // FrameworksServicesTests 389 // ├── data 390 // │ └── broken_shortcut.xml 391 // ├── JobTestApp.apk 392 for _, symlinkName := range m.provider.TestcaseRelDataFiles { 393 target := installedBaseRelativeToHere(symlinkName, *m.tradefedProperties.Base) 394 installedPath := ctx.InstallAbsoluteSymlink(installDir, symlinkName, target) 395 m.supportFiles = append(m.supportFiles, installedPath) 396 } 397 398 // 4) Module.config / AndroidTest.xml 399 m.testConfig = m.fixTestConfig(ctx, m.provider.TestConfig) 400 401 // 5) We provide so we can be listed in test_suites. 402 android.SetProvider(ctx, tradefed.BaseTestProviderKey, tradefed.BaseTestProviderData{ 403 TestcaseRelDataFiles: testcaseRel(m.supportFiles.Paths()), 404 OutputFile: baseApk, 405 TestConfig: m.testConfig, 406 HostRequiredModuleNames: m.provider.HostRequiredModuleNames, 407 RequiredModuleNames: m.provider.RequiredModuleNames, 408 TestSuites: m.tradefedProperties.Test_suites, 409 IsHost: m.provider.IsHost, 410 LocalCertificate: m.provider.LocalCertificate, 411 IsUnitTest: m.provider.IsUnitTest, 412 }) 413} 414 415var _ android.AndroidMkEntriesProvider = (*testModuleConfigHostModule)(nil) 416 417func testcaseRel(paths android.Paths) []string { 418 relPaths := []string{} 419 for _, p := range paths { 420 relPaths = append(relPaths, p.Rel()) 421 } 422 return relPaths 423} 424 425// Given a relative path to a file in the current directory or a subdirectory, 426// return a relative path under our sibling directory named `base`. 427// There should be one "../" for each subdir we descend plus one to backup to "base". 428// 429// ThisDir/file1 430// ThisDir/subdir/file2 431// would return "../base/file1" or "../../subdir/file2" 432func installedBaseRelativeToHere(targetFileName string, base string) string { 433 backup := strings.Repeat("../", strings.Count(targetFileName, "/")+1) 434 return fmt.Sprintf("%s%s/%s", backup, base, targetFileName) 435} 436