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