blob: 6867537137defffe6bcb48bb6f6fd23562604b04 [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"
8
9 "github.com/google/blueprint"
10 "github.com/google/blueprint/proptools"
11)
12
13func init() {
14 RegisterTestModuleConfigBuildComponents(android.InitRegistrationContext)
15}
16
17// Register the license_kind module type.
18func RegisterTestModuleConfigBuildComponents(ctx android.RegistrationContext) {
19 ctx.RegisterModuleType("test_module_config", TestModuleConfigFactory)
Ronald Braunstein1a6e7c02024-03-14 21:14:39 +000020 ctx.RegisterModuleType("test_module_config_host", TestModuleConfigHostFactory)
Ronald Braunsteinfce43162024-02-02 12:37:20 -080021}
22
23type testModuleConfigModule struct {
24 android.ModuleBase
25 android.DefaultableModuleBase
26 base android.Module
27
28 tradefedProperties
29
30 // Our updated testConfig.
31 testConfig android.OutputPath
32 manifest android.InstallPath
33 provider tradefed.BaseTestProviderData
34}
35
Ronald Braunstein1a6e7c02024-03-14 21:14:39 +000036// Host is mostly the same as non-host, just some diffs for AddDependency and
37// AndroidMkEntries, but the properties are the same.
38type testModuleConfigHostModule struct {
39 testModuleConfigModule
40}
41
Ronald Braunsteinfce43162024-02-02 12:37:20 -080042// Properties to list in Android.bp for this module.
43type tradefedProperties struct {
44 // Module name of the base test that we will run.
45 Base *string `android:"path,arch_variant"`
46
47 // Tradefed Options to add to tradefed xml when not one of the include or exclude filter or property.
48 // Sample: [{name: "TestRunnerOptionName", value: "OptionValue" }]
49 Options []tradefed.Option
50
51 // List of tradefed include annotations to add to tradefed xml, like "android.platform.test.annotations.Presubmit".
52 // Tests will be restricted to those matching an include_annotation or include_filter.
53 Include_annotations []string
54
55 // List of tradefed include annotations to add to tradefed xml, like "android.support.test.filters.FlakyTest".
56 // Tests matching an exclude annotation or filter will be skipped.
57 Exclude_annotations []string
58
59 // List of tradefed include filters to add to tradefed xml, like "fully.qualified.class#method".
60 // Tests will be restricted to those matching an include_annotation or include_filter.
61 Include_filters []string
62
63 // List of tradefed exclude filters to add to tradefed xml, like "fully.qualified.class#method".
64 // Tests matching an exclude annotation or filter will be skipped.
65 Exclude_filters []string
66
67 // List of compatibility suites (for example "cts", "vts") that the module should be
68 // installed into.
69 Test_suites []string
70}
71
72type dependencyTag struct {
73 blueprint.BaseDependencyTag
74 name string
75}
76
77var (
Ronald Braunstein1a6e7c02024-03-14 21:14:39 +000078 testModuleConfigTag = dependencyTag{name: "TestModuleConfigBase"}
79 testModuleConfigHostTag = dependencyTag{name: "TestModuleConfigHostBase"}
80 pctx = android.NewPackageContext("android/soong/tradefed_modules")
Ronald Braunsteinfce43162024-02-02 12:37:20 -080081)
82
83func (m *testModuleConfigModule) InstallInTestcases() bool {
84 return true
85}
86
87func (m *testModuleConfigModule) DepsMutator(ctx android.BottomUpMutatorContext) {
Ronald Braunstein1a6e7c02024-03-14 21:14:39 +000088 if m.Base == nil {
89 ctx.ModuleErrorf("'base' field must be set to a 'android_test' module.")
90 return
91 }
Ronald Braunsteinfce43162024-02-02 12:37:20 -080092 ctx.AddDependency(ctx.Module(), testModuleConfigTag, *m.Base)
93}
94
95// Takes base's Tradefed Config xml file and generates a new one with the test properties
96// appeneded from this module.
97// Rewrite the name of the apk in "test-file-name" to be our module's name, rather than the original one.
98func (m *testModuleConfigModule) fixTestConfig(ctx android.ModuleContext, baseTestConfig android.Path) android.OutputPath {
99 // Test safe to do when no test_runner_options, but check for that earlier?
100 fixedConfig := android.PathForModuleOut(ctx, "test_config_fixer", ctx.ModuleName()+".config")
101 rule := android.NewRuleBuilder(pctx, ctx)
102 command := rule.Command().BuiltTool("test_config_fixer").Input(baseTestConfig).Output(fixedConfig)
103 options := m.composeOptions()
104 if len(options) == 0 {
105 ctx.ModuleErrorf("Test options must be given when using test_module_config. Set include/exclude filter or annotation.")
106 }
107 xmlTestModuleConfigSnippet, _ := json.Marshal(options)
108 escaped := proptools.NinjaAndShellEscape(string(xmlTestModuleConfigSnippet))
109 command.FlagWithArg("--test-file-name=", ctx.ModuleName()+".apk").
110 FlagWithArg("--orig-test-file-name=", *m.tradefedProperties.Base+".apk").
111 FlagWithArg("--test-runner-options=", escaped)
112 rule.Build("fix_test_config", "fix test config")
113 return fixedConfig.OutputPath
114}
115
116// Convert --exclude_filters: ["filter1", "filter2"] ->
117// [ Option{Name: "exclude-filters", Value: "filter1"}, Option{Name: "exclude-filters", Value: "filter2"},
118// ... + include + annotations ]
119func (m *testModuleConfigModule) composeOptions() []tradefed.Option {
120 options := m.Options
121 for _, e := range m.Exclude_filters {
122 options = append(options, tradefed.Option{Name: "exclude-filter", Value: e})
123 }
124 for _, i := range m.Include_filters {
125 options = append(options, tradefed.Option{Name: "include-filter", Value: i})
126 }
127 for _, e := range m.Exclude_annotations {
128 options = append(options, tradefed.Option{Name: "exclude-annotation", Value: e})
129 }
130 for _, i := range m.Include_annotations {
131 options = append(options, tradefed.Option{Name: "include-annotation", Value: i})
132 }
133 return options
134}
135
136// Files to write and where they come from:
137// 1) test_module_config.manifest
138// - Leave a trail of where we got files from in case other tools need it.
139//
140// 2) $Module.config
141// - comes from base's module.config (AndroidTest.xml), and then we add our test_options.
142// provider.TestConfig
143// [rules via soong_app_prebuilt]
144//
145// 3) $ARCH/$Module.apk
146// - comes from base
147// provider.OutputFile
148// [rules via soong_app_prebuilt]
149//
150// 4) [bases data]
151// - We copy all of bases data (like helper apks) to our install directory too.
152// Since we call AndroidMkEntries on base, it will write out LOCAL_COMPATIBILITY_SUPPORT_FILES
153// with this data and app_prebuilt.mk will generate the rules to copy it from base.
154// We have no direct rules here to add to ninja.
155//
156// If we change to symlinks, this all needs to change.
157func (m *testModuleConfigModule) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Ronald Braunstein1a6e7c02024-03-14 21:14:39 +0000158 m.validateBase(ctx, &testModuleConfigTag, "android_test", false)
159 m.generateManifestAndConfig(ctx)
Ronald Braunsteinfce43162024-02-02 12:37:20 -0800160
Ronald Braunstein1a6e7c02024-03-14 21:14:39 +0000161}
162
163// Any test suites in base should not be repeated in the derived class, except "general-tests".
164// We may restrict derived tests to only be "general-tests" as it doesn't make sense to add a slice
165// of a test to compatibility suite.
166//
167// Returns ErrorMessage, false on problems
168// Returns _, true if okay.
169func (m *testModuleConfigModule) validateTestSuites(ctx android.ModuleContext) bool {
170 if len(m.tradefedProperties.Test_suites) == 0 {
171 ctx.ModuleErrorf("At least one test-suite must be set or this won't run. Use \"general-tests\"")
172 return false
173 }
174
175 derivedSuites := make(map[string]bool)
176 // See if any suites in base is also in derived (other than general-tests)
177 for _, s := range m.tradefedProperties.Test_suites {
178 if s != "general-tests" {
179 derivedSuites[s] = true
Ronald Braunsteinfce43162024-02-02 12:37:20 -0800180 }
Ronald Braunstein1a6e7c02024-03-14 21:14:39 +0000181 }
182 if len(derivedSuites) == 0 {
183 return true
184 }
185 for _, baseSuite := range m.provider.TestSuites {
186 if derivedSuites[baseSuite] {
187 ctx.ModuleErrorf("TestSuite %s exists in the base, do not add it here", baseSuite)
188 return false
189 }
190 }
Ronald Braunsteinfce43162024-02-02 12:37:20 -0800191
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)
211
212 return module
213}
214
Ronald Braunsteinfce43162024-02-02 12:37:20 -0800215// Implements android.AndroidMkEntriesProvider
216var _ android.AndroidMkEntriesProvider = (*testModuleConfigModule)(nil)
217
218func (m *testModuleConfigModule) AndroidMkEntries() []android.AndroidMkEntries {
219 // We rely on base writing LOCAL_COMPATIBILITY_SUPPORT_FILES for its data files
220 entriesList := m.base.(android.AndroidMkEntriesProvider).AndroidMkEntries()
221 entries := &entriesList[0]
222 entries.OutputFile = android.OptionalPathForPath(m.provider.OutputFile)
223 entries.ExtraEntries = append(entries.ExtraEntries, func(ctx android.AndroidMkExtraEntriesContext, entries *android.AndroidMkEntries) {
224 entries.SetString("LOCAL_MODULE", m.Name()) // out module name, not base's
225
226 // Out update config file with extra options.
227 entries.SetPath("LOCAL_FULL_TEST_CONFIG", m.testConfig)
228 entries.SetString("LOCAL_MODULE_TAGS", "tests")
Ronald Braunsteinfce43162024-02-02 12:37:20 -0800229
230 // Don't append to base's test-suites, only use the ones we define, so clear it before
231 // appending to it.
232 entries.SetString("LOCAL_COMPATIBILITY_SUITE", "")
Ronald Braunstein1a6e7c02024-03-14 21:14:39 +0000233 entries.AddCompatibilityTestSuites(m.tradefedProperties.Test_suites...)
234
235 if len(m.provider.HostRequiredModuleNames) > 0 {
236 entries.AddStrings("LOCAL_HOST_REQUIRED_MODULES", m.provider.HostRequiredModuleNames...)
237 }
238 if len(m.provider.RequiredModuleNames) > 0 {
239 entries.AddStrings("LOCAL_REQUIRED_MODULES", m.provider.RequiredModuleNames...)
240 }
241
242 if m.provider.IsHost == false {
243 // Not needed for jar_host_test
244 //
245 // Clear the JNI symbols because they belong to base not us. Either transform the names in the string
246 // or clear the variable because we don't need it, we are copying bases libraries not generating
247 // new ones.
248 entries.SetString("LOCAL_SOONG_JNI_LIBS_SYMBOLS", "")
Ronald Braunsteinfce43162024-02-02 12:37:20 -0800249 }
250 })
251 return entriesList
252}
Ronald Braunstein1a6e7c02024-03-14 21:14:39 +0000253
254func (m *testModuleConfigHostModule) DepsMutator(ctx android.BottomUpMutatorContext) {
255 if m.Base == nil {
256 ctx.ModuleErrorf("'base' field must be set to a 'java_test_host' module")
257 return
258 }
259 ctx.AddVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), testModuleConfigHostTag, *m.Base)
260}
261
262// File to write:
263// 1) out/host/linux-x86/testcases/derived-module/test_module_config.manifest # contains base's name.
264// 2) out/host/linux-x86/testcases/derived-module/derived-module.config # Update AnroidTest.xml
265// 3) out/host/linux-x86/testcases/derived-module/base.jar
266// - written via soong_java_prebuilt.mk
267//
268// 4) out/host/linux-x86/testcases/derived-module/* # data dependencies from base.
269// - written via soong_java_prebuilt.mk
270func (m *testModuleConfigHostModule) GenerateAndroidBuildActions(ctx android.ModuleContext) {
271 m.validateBase(ctx, &testModuleConfigHostTag, "java_test_host", true)
272 m.generateManifestAndConfig(ctx)
273}
274
275// Ensure the base listed is the right type by checking that we get the expected provider data.
276// Returns false on errors and the context is updated with an error indicating the baseType expected.
277func (m *testModuleConfigModule) validateBase(ctx android.ModuleContext, depTag *dependencyTag, baseType string, baseShouldBeHost bool) {
278 ctx.VisitDirectDepsWithTag(*depTag, func(dep android.Module) {
279 if provider, ok := android.OtherModuleProvider(ctx, dep, tradefed.BaseTestProviderKey); ok {
280 if baseShouldBeHost == provider.IsHost {
281 m.base = dep
282 m.provider = provider
283 } else {
284 if baseShouldBeHost {
285 ctx.ModuleErrorf("'android_test' module used as base, but 'java_test_host' expected.")
286 } else {
287 ctx.ModuleErrorf("'java_test_host' module used as base, but 'android_test' expected.")
288 }
289 }
290 } else {
291 ctx.ModuleErrorf("'%s' module used as base but it is not a '%s' module.", *m.Base, baseType)
292 }
293 })
294}
295
296// Actions to write:
297// 1. manifest file to testcases dir
298// 2. New Module.config / AndroidTest.xml file with our options.
299func (m *testModuleConfigModule) generateManifestAndConfig(ctx android.ModuleContext) {
300 if !m.validateTestSuites(ctx) {
301 return
302 }
303 // Ensure the provider is accurate
304 if m.provider.TestConfig == nil {
305 return
306 }
307
308 // 1) A manifest file listing the base, write text to a tiny file.
309 installDir := android.PathForModuleInstall(ctx, ctx.ModuleName())
310 manifest := android.PathForModuleOut(ctx, "test_module_config.manifest")
311 android.WriteFileRule(ctx, manifest, fmt.Sprintf("{%q: %q}", "base", *m.tradefedProperties.Base))
312 // build/soong/android/androidmk.go has this comment:
313 // Assume the primary install file is last
314 // so we need to Install our file last.
315 ctx.InstallFile(installDir, manifest.Base(), manifest)
316
317 // 2) Module.config / AndroidTest.xml
318 m.testConfig = m.fixTestConfig(ctx, m.provider.TestConfig)
319}
320
321var _ android.AndroidMkEntriesProvider = (*testModuleConfigHostModule)(nil)