blob: 7a04c1994cfe0f80c26c499674e9bb78e99b2edf [file] [log] [blame]
Ronald Braunsteinfce43162024-02-02 12:37:20 -08001package tradefed_modules
2
3import (
4 "android/soong/android"
5 "android/soong/tradefed"
6 "encoding/json"
7 "fmt"
Ronald Braunstein01d31bd2024-06-02 07:07:02 -07008 "io"
Ronald Braunsteina186ac02024-08-07 13:03:05 -07009 "slices"
Ronald Braunstein01d31bd2024-06-02 07:07:02 -070010 "strings"
Ronald Braunsteinfce43162024-02-02 12:37:20 -080011
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)
Ronald Braunstein1a6e7c02024-03-14 21:14:39 +000023 ctx.RegisterModuleType("test_module_config_host", TestModuleConfigHostFactory)
Ronald Braunsteinfce43162024-02-02 12:37:20 -080024}
25
26type testModuleConfigModule struct {
27 android.ModuleBase
28 android.DefaultableModuleBase
Ronald Braunsteinfce43162024-02-02 12:37:20 -080029
30 tradefedProperties
31
32 // Our updated testConfig.
33 testConfig android.OutputPath
Ronald Braunstein01d31bd2024-06-02 07:07:02 -070034 manifest android.OutputPath
Ronald Braunsteinfce43162024-02-02 12:37:20 -080035 provider tradefed.BaseTestProviderData
Ronald Braunstein01d31bd2024-06-02 07:07:02 -070036
37 supportFiles android.InstallPaths
38
39 isHost bool
Ronald Braunsteinfce43162024-02-02 12:37:20 -080040}
41
Ronald Braunstein1a6e7c02024-03-14 21:14:39 +000042// 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
Ronald Braunsteinfce43162024-02-02 12:37:20 -080048// 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 (
Ronald Braunstein1a6e7c02024-03-14 21:14:39 +000084 testModuleConfigTag = dependencyTag{name: "TestModuleConfigBase"}
85 testModuleConfigHostTag = dependencyTag{name: "TestModuleConfigHostBase"}
86 pctx = android.NewPackageContext("android/soong/tradefed_modules")
Ronald Braunsteinfce43162024-02-02 12:37:20 -080087)
88
89func (m *testModuleConfigModule) InstallInTestcases() bool {
90 return true
91}
92
93func (m *testModuleConfigModule) DepsMutator(ctx android.BottomUpMutatorContext) {
Ronald Braunstein1a6e7c02024-03-14 21:14:39 +000094 if m.Base == nil {
95 ctx.ModuleErrorf("'base' field must be set to a 'android_test' module.")
96 return
97 }
Ronald Braunsteinfce43162024-02-02 12:37:20 -080098 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.
Ronald Braunsteinfce43162024-02-02 12:37:20 -0800103func (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))
Ronald Braunstein01d31bd2024-06-02 07:07:02 -0700114 command.FlagWithArg("--test-runner-options=", escaped)
115
Ronald Braunsteinfce43162024-02-02 12:37:20 -0800116 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) {
Ronald Braunstein1a6e7c02024-03-14 21:14:39 +0000162 m.validateBase(ctx, &testModuleConfigTag, "android_test", false)
163 m.generateManifestAndConfig(ctx)
Ronald Braunsteinfce43162024-02-02 12:37:20 -0800164
Ronald Braunstein1a6e7c02024-03-14 21:14:39 +0000165}
166
Ronald Braunsteinb4a4ef92024-04-30 14:02:59 +0000167// 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.
Ronald Braunstein1a6e7c02024-03-14 21:14:39 +0000170//
Ronald Braunsteinb4a4ef92024-04-30 14:02:59 +0000171// Returns true if okay and reports errors via ModuleErrorf.
Ronald Braunstein1a6e7c02024-03-14 21:14:39 +0000172func (m *testModuleConfigModule) validateTestSuites(ctx android.ModuleContext) bool {
173 if len(m.tradefedProperties.Test_suites) == 0 {
Ronald Braunsteinb4a4ef92024-04-30 14:02:59 +0000174 ctx.ModuleErrorf("At least one test-suite must be set or this won't run. Use \"general-tests\" or \"device-tests\"")
Ronald Braunstein1a6e7c02024-03-14 21:14:39 +0000175 return false
176 }
177
Ronald Braunsteina186ac02024-08-07 13:03:05 -0700178 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
Ronald Braunstein1a6e7c02024-03-14 21:14:39 +0000192 return true
Ronald Braunsteinfce43162024-02-02 12:37:20 -0800193}
194
195func TestModuleConfigFactory() android.Module {
196 module := &testModuleConfigModule{}
197
198 module.AddProperties(&module.tradefedProperties)
199 android.InitAndroidArchModule(module, android.DeviceSupported, android.MultilibCommon)
200 android.InitDefaultableModule(module)
201
202 return module
203}
204
Ronald Braunstein1a6e7c02024-03-14 21:14:39 +0000205func TestModuleConfigHostFactory() android.Module {
206 module := &testModuleConfigHostModule{}
207
208 module.AddProperties(&module.tradefedProperties)
209 android.InitAndroidMultiTargetsArchModule(module, android.HostSupported, android.MultilibCommon)
210 android.InitDefaultableModule(module)
Ronald Braunstein01d31bd2024-06-02 07:07:02 -0700211 module.isHost = true
Ronald Braunstein1a6e7c02024-03-14 21:14:39 +0000212
213 return module
214}
215
Ronald Braunsteinfce43162024-02-02 12:37:20 -0800216// Implements android.AndroidMkEntriesProvider
217var _ android.AndroidMkEntriesProvider = (*testModuleConfigModule)(nil)
218
219func (m *testModuleConfigModule) AndroidMkEntries() []android.AndroidMkEntries {
Ronald Braunstein01d31bd2024-06-02 07:07:02 -0700220 appClass := "APPS"
221 include := "$(BUILD_SYSTEM)/soong_app_prebuilt.mk"
222 if m.isHost {
223 appClass = "JAVA_LIBRARIES"
224 include = "$(BUILD_SYSTEM)/soong_java_prebuilt.mk"
225 }
226 return []android.AndroidMkEntries{{
227 Class: appClass,
228 OutputFile: android.OptionalPathForPath(m.manifest),
229 Include: include,
230 Required: []string{*m.Base},
231 ExtraEntries: []android.AndroidMkExtraEntriesFunc{
232 func(ctx android.AndroidMkExtraEntriesContext, entries *android.AndroidMkEntries) {
233 entries.SetPath("LOCAL_FULL_TEST_CONFIG", m.testConfig)
234 entries.SetString("LOCAL_MODULE_TAGS", "tests")
235 entries.SetString("LOCAL_TEST_MODULE_CONFIG_BASE", *m.Base)
236 if m.provider.LocalSdkVersion != "" {
237 entries.SetString("LOCAL_SDK_VERSION", m.provider.LocalSdkVersion)
238 }
239 if m.provider.LocalCertificate != "" {
240 entries.SetString("LOCAL_CERTIFICATE", m.provider.LocalCertificate)
241 }
Ronald Braunsteinfce43162024-02-02 12:37:20 -0800242
Ronald Braunstein01d31bd2024-06-02 07:07:02 -0700243 entries.SetBoolIfTrue("LOCAL_IS_UNIT_TEST", m.provider.IsUnitTest)
244 entries.AddCompatibilityTestSuites(m.tradefedProperties.Test_suites...)
Ronald Braunstein5c647d82024-09-19 23:14:34 +0000245 entries.AddStrings("LOCAL_HOST_REQUIRED_MODULES", m.provider.HostRequiredModuleNames...)
Ronald Braunsteinfce43162024-02-02 12:37:20 -0800246
Ronald Braunstein01d31bd2024-06-02 07:07:02 -0700247 // The app_prebuilt_internal.mk files try create a copy of the OutputFile as an .apk.
248 // Normally, this copies the "package.apk" from the intermediate directory here.
249 // To prevent the copy of the large apk and to prevent confusion with the real .apk we
250 // link to, we set the STEM here to a bogus name and we set OutputFile to a small file (our manifest).
251 // We do this so we don't have to add more conditionals to base_rules.mk
252 // soong_java_prebult has the same issue for .jars so use this in both module types.
253 entries.SetString("LOCAL_MODULE_STEM", fmt.Sprintf("UNUSED-%s", *m.Base))
Ronald Braunstein1a6e7c02024-03-14 21:14:39 +0000254
Ronald Braunstein01d31bd2024-06-02 07:07:02 -0700255 // In normal java/app modules, the module writes LOCAL_COMPATIBILITY_SUPPORT_FILES
256 // and then base_rules.mk ends up copying each of those dependencies from .intermediates to the install directory.
257 // tasks/general-tests.mk, tasks/devices-tests.mk also use these to figure out
258 // which testcase files to put in a zip for running tests on another machine.
259 //
260 // We need our files to end up in the zip, but we don't want \.mk files to
261 // `install` files for us.
262 // So we create a new make variable to indicate these should be in the zip
263 // but not installed.
264 entries.AddStrings("LOCAL_SOONG_INSTALLED_COMPATIBILITY_SUPPORT_FILES", m.supportFiles.Strings()...)
265 },
266 },
267 // Ensure each of our supportFiles depends on the installed file in base so that our symlinks will always
268 // resolve. The provider gives us the .intermediate path for the support file in base, we change it to
269 // the installed path with a string substitution.
270 ExtraFooters: []android.AndroidMkExtraFootersFunc{
271 func(w io.Writer, name, prefix, moduleDir string) {
272 for _, f := range m.supportFiles.Strings() {
273 // convert out/.../testcases/FrameworksServicesTests_contentprotection/file1.apk
274 // to out/.../testcases/FrameworksServicesTests/file1.apk
275 basePath := strings.Replace(f, "/"+m.Name()+"/", "/"+*m.Base+"/", 1)
276 fmt.Fprintf(w, "%s: %s\n", f, basePath)
277 }
278 },
279 },
280 }}
Ronald Braunsteinfce43162024-02-02 12:37:20 -0800281}
Ronald Braunstein1a6e7c02024-03-14 21:14:39 +0000282
283func (m *testModuleConfigHostModule) DepsMutator(ctx android.BottomUpMutatorContext) {
284 if m.Base == nil {
285 ctx.ModuleErrorf("'base' field must be set to a 'java_test_host' module")
286 return
287 }
288 ctx.AddVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), testModuleConfigHostTag, *m.Base)
289}
290
291// File to write:
292// 1) out/host/linux-x86/testcases/derived-module/test_module_config.manifest # contains base's name.
293// 2) out/host/linux-x86/testcases/derived-module/derived-module.config # Update AnroidTest.xml
294// 3) out/host/linux-x86/testcases/derived-module/base.jar
295// - written via soong_java_prebuilt.mk
296//
297// 4) out/host/linux-x86/testcases/derived-module/* # data dependencies from base.
Ronald Braunstein01d31bd2024-06-02 07:07:02 -0700298// - written via our InstallSymlink
Ronald Braunstein1a6e7c02024-03-14 21:14:39 +0000299func (m *testModuleConfigHostModule) GenerateAndroidBuildActions(ctx android.ModuleContext) {
300 m.validateBase(ctx, &testModuleConfigHostTag, "java_test_host", true)
301 m.generateManifestAndConfig(ctx)
302}
303
304// Ensure the base listed is the right type by checking that we get the expected provider data.
305// Returns false on errors and the context is updated with an error indicating the baseType expected.
306func (m *testModuleConfigModule) validateBase(ctx android.ModuleContext, depTag *dependencyTag, baseType string, baseShouldBeHost bool) {
307 ctx.VisitDirectDepsWithTag(*depTag, func(dep android.Module) {
308 if provider, ok := android.OtherModuleProvider(ctx, dep, tradefed.BaseTestProviderKey); ok {
309 if baseShouldBeHost == provider.IsHost {
Ronald Braunstein1a6e7c02024-03-14 21:14:39 +0000310 m.provider = provider
311 } else {
312 if baseShouldBeHost {
313 ctx.ModuleErrorf("'android_test' module used as base, but 'java_test_host' expected.")
314 } else {
315 ctx.ModuleErrorf("'java_test_host' module used as base, but 'android_test' expected.")
316 }
317 }
318 } else {
319 ctx.ModuleErrorf("'%s' module used as base but it is not a '%s' module.", *m.Base, baseType)
320 }
321 })
322}
323
324// Actions to write:
325// 1. manifest file to testcases dir
Ronald Braunstein01d31bd2024-06-02 07:07:02 -0700326// 2. Symlink to base.apk under base's arch dir
327// 3. Symlink to all data dependencies
328// 4. New Module.config / AndroidTest.xml file with our options.
Ronald Braunstein1a6e7c02024-03-14 21:14:39 +0000329func (m *testModuleConfigModule) generateManifestAndConfig(ctx android.ModuleContext) {
Ronald Braunsteind2453462024-04-18 09:18:29 -0700330 // Keep before early returns.
331 android.SetProvider(ctx, android.TestOnlyProviderKey, android.TestModuleInformation{
332 TestOnly: true,
333 TopLevelTarget: true,
334 })
335
Ronald Braunstein1a6e7c02024-03-14 21:14:39 +0000336 if !m.validateTestSuites(ctx) {
337 return
338 }
Ronald Braunsteind2453462024-04-18 09:18:29 -0700339 // Ensure the base provider is accurate
Ronald Braunstein1a6e7c02024-03-14 21:14:39 +0000340 if m.provider.TestConfig == nil {
341 return
342 }
Ronald Braunstein1a6e7c02024-03-14 21:14:39 +0000343 // 1) A manifest file listing the base, write text to a tiny file.
344 installDir := android.PathForModuleInstall(ctx, ctx.ModuleName())
345 manifest := android.PathForModuleOut(ctx, "test_module_config.manifest")
346 android.WriteFileRule(ctx, manifest, fmt.Sprintf("{%q: %q}", "base", *m.tradefedProperties.Base))
347 // build/soong/android/androidmk.go has this comment:
348 // Assume the primary install file is last
349 // so we need to Install our file last.
350 ctx.InstallFile(installDir, manifest.Base(), manifest)
Ronald Braunstein01d31bd2024-06-02 07:07:02 -0700351 m.manifest = manifest.OutputPath
Ronald Braunstein1a6e7c02024-03-14 21:14:39 +0000352
Ronald Braunstein01d31bd2024-06-02 07:07:02 -0700353 // 2) Symlink to base.apk
354 baseApk := m.provider.OutputFile
355
356 // Typically looks like this for baseApk
357 // FrameworksServicesTests
358 // └── x86_64
359 // └── FrameworksServicesTests.apk
360 symlinkName := fmt.Sprintf("%s/%s", ctx.DeviceConfig().DeviceArch(), baseApk.Base())
361 // Only android_test, not java_host_test puts the output in the DeviceArch dir.
362 if m.provider.IsHost || ctx.DeviceConfig().DeviceArch() == "" {
363 // testcases/CtsDevicePolicyManagerTestCases
364 // ├── CtsDevicePolicyManagerTestCases.jar
365 symlinkName = baseApk.Base()
366 }
367 target := installedBaseRelativeToHere(symlinkName, *m.tradefedProperties.Base)
368 installedApk := ctx.InstallAbsoluteSymlink(installDir, symlinkName, target)
369 m.supportFiles = append(m.supportFiles, installedApk)
370
371 // 3) Symlink for all data deps
372 // And like this for data files and required modules
373 // FrameworksServicesTests
374 // ├── data
375 // │   └── broken_shortcut.xml
376 // ├── JobTestApp.apk
377 for _, f := range m.provider.InstalledFiles {
378 symlinkName := f.Rel()
379 target := installedBaseRelativeToHere(symlinkName, *m.tradefedProperties.Base)
380 installedPath := ctx.InstallAbsoluteSymlink(installDir, symlinkName, target)
381 m.supportFiles = append(m.supportFiles, installedPath)
382 }
383
384 // 4) Module.config / AndroidTest.xml
Ronald Braunstein1a6e7c02024-03-14 21:14:39 +0000385 m.testConfig = m.fixTestConfig(ctx, m.provider.TestConfig)
386}
387
388var _ android.AndroidMkEntriesProvider = (*testModuleConfigHostModule)(nil)
Ronald Braunstein01d31bd2024-06-02 07:07:02 -0700389
390// Given a relative path to a file in the current directory or a subdirectory,
391// return a relative path under our sibling directory named `base`.
392// There should be one "../" for each subdir we descend plus one to backup to "base".
393//
394// ThisDir/file1
395// ThisDir/subdir/file2
396// would return "../base/file1" or "../../subdir/file2"
397func installedBaseRelativeToHere(targetFileName string, base string) string {
398 backup := strings.Repeat("../", strings.Count(targetFileName, "/")+1)
399 return fmt.Sprintf("%s%s/%s", backup, base, targetFileName)
400}