blob: 18386c90c6f81f7ef2e8e07244da5345c8c02ffc [file] [log] [blame]
Colin Cross0ef08162019-05-01 15:50:51 -07001// 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
15package java
16
17import (
18 "fmt"
19 "io"
Colin Crossd2d11772019-05-30 11:17:23 -070020 "strconv"
Colin Cross0ef08162019-05-01 15:50:51 -070021 "strings"
22
23 "android/soong/android"
Colin Cross8eebb132020-01-29 20:07:03 -080024 "android/soong/java/config"
Aditya Choudhary9b593522023-10-06 19:54:58 +000025 "android/soong/testing"
Colin Cross8eebb132020-01-29 20:07:03 -080026 "android/soong/tradefed"
Liz Kammeref28a4c2022-09-23 16:50:56 -040027
Cole Faustd57e8b22022-08-11 11:59:04 -070028 "github.com/google/blueprint/proptools"
Colin Cross0ef08162019-05-01 15:50:51 -070029)
30
31func init() {
32 android.RegisterModuleType("android_robolectric_test", RobolectricTestFactory)
Colin Cross8eebb132020-01-29 20:07:03 -080033 android.RegisterModuleType("android_robolectric_runtimes", robolectricRuntimesFactory)
Colin Cross0ef08162019-05-01 15:50:51 -070034}
35
36var robolectricDefaultLibs = []string{
Colin Cross0ef08162019-05-01 15:50:51 -070037 "mockito-robolectric-prebuilt",
Krzysztof KosiƄski5a554392023-10-07 19:59:58 +000038 "truth",
Colin Cross8eebb132020-01-29 20:07:03 -080039 // TODO(ccross): this is not needed at link time
40 "junitxml",
Colin Cross0ef08162019-05-01 15:50:51 -070041}
42
Colin Cross2787e8e2021-03-05 11:16:20 -080043const robolectricCurrentLib = "Robolectric_all-target"
44const robolectricPrebuiltLibPattern = "platform-robolectric-%s-prebuilt"
45
Colin Cross3ec27ec2019-05-01 15:54:05 -070046var (
Colin Cross8eebb132020-01-29 20:07:03 -080047 roboCoverageLibsTag = dependencyTag{name: "roboCoverageLibs"}
48 roboRuntimesTag = dependencyTag{name: "roboRuntimes"}
Kevin Liucab89b52024-04-12 21:52:07 +000049 roboRuntimeOnlyTag = dependencyTag{name: "roboRuntimeOnlyTag"}
Colin Cross3ec27ec2019-05-01 15:54:05 -070050)
51
Colin Cross0ef08162019-05-01 15:50:51 -070052type robolectricProperties struct {
53 // The name of the android_app module that the tests will run against.
54 Instrumentation_for *string
55
Colin Cross3ec27ec2019-05-01 15:54:05 -070056 // Additional libraries for which coverage data should be generated
57 Coverage_libs []string
58
Colin Cross0ef08162019-05-01 15:50:51 -070059 Test_options struct {
60 // Timeout in seconds when running the tests.
Colin Cross2f9a7c82019-05-30 11:16:26 -070061 Timeout *int64
Colin Crossd2d11772019-05-30 11:17:23 -070062
63 // Number of shards to use when running the tests.
64 Shards *int64
Colin Cross0ef08162019-05-01 15:50:51 -070065 }
Colin Cross2787e8e2021-03-05 11:16:20 -080066
67 // The version number of a robolectric prebuilt to use from prebuilts/misc/common/robolectric
68 // instead of the one built from source in external/robolectric-shadows.
69 Robolectric_prebuilt_version *string
Rex Hoffman54641d22022-08-25 17:29:50 +000070
Yuichiro Hanadae42ac1c2023-12-08 09:24:40 +090071 // Use /external/robolectric rather than /external/robolectric-shadows as the version of robolectric
Rex Hoffman54641d22022-08-25 17:29:50 +000072 // to use. /external/robolectric closely tracks github's master, and will fully replace /external/robolectric-shadows
73 Upstream *bool
Kevin Liucab89b52024-04-12 21:52:07 +000074
75 // Use strict mode to limit access of Robolectric API directly. See go/roboStrictMode
76 Strict_mode *bool
Colin Cross0ef08162019-05-01 15:50:51 -070077}
78
79type robolectricTest struct {
80 Library
81
82 robolectricProperties robolectricProperties
Colin Cross8eebb132020-01-29 20:07:03 -080083 testProperties testProperties
Colin Cross0ef08162019-05-01 15:50:51 -070084
Colin Crossd2d11772019-05-30 11:17:23 -070085 libs []string
86 tests []string
Colin Cross3ec27ec2019-05-01 15:54:05 -070087
Colin Cross8eebb132020-01-29 20:07:03 -080088 manifest android.Path
89 resourceApk android.Path
90
91 combinedJar android.WritablePath
92
Colin Cross3ec27ec2019-05-01 15:54:05 -070093 roboSrcJar android.Path
Colin Cross8eebb132020-01-29 20:07:03 -080094
95 testConfig android.Path
96 data android.Paths
Colin Cross0c66bc62021-07-20 09:47:41 -070097
98 forceOSType android.OsType
99 forceArchType android.ArchType
Colin Cross0ef08162019-05-01 15:50:51 -0700100}
101
Colin Cross8eebb132020-01-29 20:07:03 -0800102func (r *robolectricTest) TestSuites() []string {
103 return r.testProperties.Test_suites
104}
105
106var _ android.TestSuiteModule = (*robolectricTest)(nil)
107
Colin Cross0ef08162019-05-01 15:50:51 -0700108func (r *robolectricTest) DepsMutator(ctx android.BottomUpMutatorContext) {
109 r.Library.DepsMutator(ctx)
110
111 if r.robolectricProperties.Instrumentation_for != nil {
112 ctx.AddVariationDependencies(nil, instrumentationForTag, String(r.robolectricProperties.Instrumentation_for))
113 } else {
114 ctx.PropertyErrorf("instrumentation_for", "missing required instrumented module")
115 }
116
Colin Cross2787e8e2021-03-05 11:16:20 -0800117 if v := String(r.robolectricProperties.Robolectric_prebuilt_version); v != "" {
118 ctx.AddVariationDependencies(nil, libTag, fmt.Sprintf(robolectricPrebuiltLibPattern, v))
Pechetty Sravania4752582024-06-28 05:19:16 +0000119 } else if !proptools.Bool(r.robolectricProperties.Strict_mode) {
Rex Hoffman54641d22022-08-25 17:29:50 +0000120 if proptools.Bool(r.robolectricProperties.Upstream) {
121 ctx.AddVariationDependencies(nil, libTag, robolectricCurrentLib+"_upstream")
122 } else {
123 ctx.AddVariationDependencies(nil, libTag, robolectricCurrentLib)
124 }
Colin Cross2787e8e2021-03-05 11:16:20 -0800125 }
126
Pechetty Sravania4752582024-06-28 05:19:16 +0000127 if proptools.Bool(r.robolectricProperties.Strict_mode) {
Kevin Liucab89b52024-04-12 21:52:07 +0000128 ctx.AddVariationDependencies(nil, roboRuntimeOnlyTag, robolectricCurrentLib+"_upstream")
129 }
130
Colin Cross0ef08162019-05-01 15:50:51 -0700131 ctx.AddVariationDependencies(nil, libTag, robolectricDefaultLibs...)
Colin Cross3ec27ec2019-05-01 15:54:05 -0700132
133 ctx.AddVariationDependencies(nil, roboCoverageLibsTag, r.robolectricProperties.Coverage_libs...)
Colin Cross8eebb132020-01-29 20:07:03 -0800134
Colin Cross5aa29a72020-09-14 19:54:47 -0700135 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(),
136 roboRuntimesTag, "robolectric-android-all-prebuilts")
Colin Cross0ef08162019-05-01 15:50:51 -0700137}
138
139func (r *robolectricTest) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Colin Cross0c66bc62021-07-20 09:47:41 -0700140 r.forceOSType = ctx.Config().BuildOS
141 r.forceArchType = ctx.Config().BuildArch
142
Cole Faust21680542022-12-07 18:18:37 -0800143 r.testConfig = tradefed.AutoGenTestConfig(ctx, tradefed.AutoGenTestConfigOptions{
144 TestConfigProp: r.testProperties.Test_config,
145 TestConfigTemplateProp: r.testProperties.Test_config_template,
146 TestSuites: r.testProperties.Test_suites,
147 AutoGenConfig: r.testProperties.Auto_gen_config,
148 DeviceTemplate: "${RobolectricTestConfigTemplate}",
149 HostTemplate: "${RobolectricTestConfigTemplate}",
150 })
Colin Cross8eebb132020-01-29 20:07:03 -0800151 r.data = android.PathsForModuleSrc(ctx, r.testProperties.Data)
152
Colin Cross3ec27ec2019-05-01 15:54:05 -0700153 roboTestConfig := android.PathForModuleGen(ctx, "robolectric").
154 Join(ctx, "com/android/tools/test_config.properties")
155
Colin Crossf521efa2023-05-19 09:47:09 -0700156 var ok bool
157 var instrumentedApp *AndroidApp
158
Colin Cross3ec27ec2019-05-01 15:54:05 -0700159 // TODO: this inserts paths to built files into the test, it should really be inserting the contents.
160 instrumented := ctx.GetDirectDepsWithTag(instrumentationForTag)
161
Colin Crossf521efa2023-05-19 09:47:09 -0700162 if len(instrumented) == 1 {
163 instrumentedApp, ok = instrumented[0].(*AndroidApp)
164 if !ok {
165 ctx.PropertyErrorf("instrumentation_for", "dependency must be an android_app")
166 }
167 } else if !ctx.Config().AllowMissingDependencies() {
Colin Cross3ec27ec2019-05-01 15:54:05 -0700168 panic(fmt.Errorf("expected exactly 1 instrumented dependency, got %d", len(instrumented)))
169 }
170
Colin Crossf521efa2023-05-19 09:47:09 -0700171 if instrumentedApp != nil {
172 r.manifest = instrumentedApp.mergedManifestFile
173 r.resourceApk = instrumentedApp.outputFile
174
175 generateRoboTestConfig(ctx, roboTestConfig, instrumentedApp)
176 r.extraResources = android.Paths{roboTestConfig}
Colin Cross3ec27ec2019-05-01 15:54:05 -0700177 }
178
Colin Cross0ef08162019-05-01 15:50:51 -0700179 r.Library.GenerateAndroidBuildActions(ctx)
180
Colin Cross3ec27ec2019-05-01 15:54:05 -0700181 roboSrcJar := android.PathForModuleGen(ctx, "robolectric", ctx.ModuleName()+".srcjar")
Colin Crossf521efa2023-05-19 09:47:09 -0700182
183 if instrumentedApp != nil {
184 r.generateRoboSrcJar(ctx, roboSrcJar, instrumentedApp)
185 r.roboSrcJar = roboSrcJar
186 }
Colin Cross3ec27ec2019-05-01 15:54:05 -0700187
Colin Cross8eebb132020-01-29 20:07:03 -0800188 roboTestConfigJar := android.PathForModuleOut(ctx, "robolectric_samedir", "samedir_config.jar")
189 generateSameDirRoboTestConfigJar(ctx, roboTestConfigJar)
190
191 combinedJarJars := android.Paths{
192 // roboTestConfigJar comes first so that its com/android/tools/test_config.properties
193 // overrides the one from r.extraResources. The r.extraResources one can be removed
194 // once the Make test runner is removed.
195 roboTestConfigJar,
196 r.outputFile,
Colin Crossf521efa2023-05-19 09:47:09 -0700197 }
198
199 if instrumentedApp != nil {
200 combinedJarJars = append(combinedJarJars, instrumentedApp.implementationAndResourcesJar)
Colin Cross0ef08162019-05-01 15:50:51 -0700201 }
Colin Crossd2d11772019-05-30 11:17:23 -0700202
Kevin Liucab89b52024-04-12 21:52:07 +0000203 handleLibDeps := func(dep android.Module, runtimeOnly bool) {
Colin Cross313aa542023-12-13 13:47:44 -0800204 m, _ := android.OtherModuleProvider(ctx, dep, JavaInfoProvider)
Kevin Liucab89b52024-04-12 21:52:07 +0000205 if !runtimeOnly {
206 r.libs = append(r.libs, ctx.OtherModuleName(dep))
207 }
Colin Crossdcf71b22021-02-01 13:59:03 -0800208 if !android.InList(ctx.OtherModuleName(dep), config.FrameworkLibraries) {
209 combinedJarJars = append(combinedJarJars, m.ImplementationAndResourcesJars...)
Colin Cross8eebb132020-01-29 20:07:03 -0800210 }
211 }
212
Liz Kammeref28a4c2022-09-23 16:50:56 -0400213 for _, dep := range ctx.GetDirectDepsWithTag(libTag) {
Kevin Liucab89b52024-04-12 21:52:07 +0000214 handleLibDeps(dep, false)
Liz Kammeref28a4c2022-09-23 16:50:56 -0400215 }
216 for _, dep := range ctx.GetDirectDepsWithTag(sdkLibTag) {
Kevin Liucab89b52024-04-12 21:52:07 +0000217 handleLibDeps(dep, false)
218 }
219 // handle the runtimeOnly tag for strict_mode
220 for _, dep := range ctx.GetDirectDepsWithTag(roboRuntimeOnlyTag) {
221 handleLibDeps(dep, true)
Liz Kammeref28a4c2022-09-23 16:50:56 -0400222 }
223
Colin Cross8eebb132020-01-29 20:07:03 -0800224 r.combinedJar = android.PathForModuleOut(ctx, "robolectric_combined", r.outputFile.Base())
225 TransformJarsToJar(ctx, r.combinedJar, "combine jars", combinedJarJars, android.OptionalPath{},
226 false, nil, nil)
227
Colin Crossd2d11772019-05-30 11:17:23 -0700228 // TODO: this could all be removed if tradefed was used as the test runner, it will find everything
229 // annotated as a test and run it.
Chaohui Wangdcbe33c2022-10-11 11:13:30 +0800230 for _, src := range r.uniqueSrcFiles {
Colin Crossd2d11772019-05-30 11:17:23 -0700231 s := src.Rel()
Chaohui Wangdcbe33c2022-10-11 11:13:30 +0800232 if !strings.HasSuffix(s, "Test.java") && !strings.HasSuffix(s, "Test.kt") {
Colin Crossd2d11772019-05-30 11:17:23 -0700233 continue
234 } else if strings.HasSuffix(s, "/BaseRobolectricTest.java") {
235 continue
Ulya Trafimovich497a0932021-07-14 16:35:33 +0100236 } else {
Colin Crossd2d11772019-05-30 11:17:23 -0700237 s = strings.TrimPrefix(s, "src/")
238 }
239 r.tests = append(r.tests, s)
240 }
Colin Cross8eebb132020-01-29 20:07:03 -0800241
Colin Crossf521efa2023-05-19 09:47:09 -0700242 installPath := android.PathForModuleInstall(ctx, r.BaseModuleName())
Colin Cross09ad3a62023-11-15 12:29:33 -0800243 var installDeps android.InstallPaths
Colin Crossf521efa2023-05-19 09:47:09 -0700244
245 if r.manifest != nil {
246 r.data = append(r.data, r.manifest)
247 installedManifest := ctx.InstallFile(installPath, ctx.ModuleName()+"-AndroidManifest.xml", r.manifest)
248 installDeps = append(installDeps, installedManifest)
249 }
250
251 if r.resourceApk != nil {
252 r.data = append(r.data, r.resourceApk)
253 installedResourceApk := ctx.InstallFile(installPath, ctx.ModuleName()+".apk", r.resourceApk)
254 installDeps = append(installDeps, installedResourceApk)
255 }
Colin Cross8eebb132020-01-29 20:07:03 -0800256
257 runtimes := ctx.GetDirectDepWithTag("robolectric-android-all-prebuilts", roboRuntimesTag)
Colin Cross8eebb132020-01-29 20:07:03 -0800258 for _, runtime := range runtimes.(*robolectricRuntimes).runtimes {
259 installDeps = append(installDeps, runtime)
260 }
Colin Crossf521efa2023-05-19 09:47:09 -0700261
262 installedConfig := ctx.InstallFile(installPath, ctx.ModuleName()+".config", r.testConfig)
263 installDeps = append(installDeps, installedConfig)
Colin Cross8eebb132020-01-29 20:07:03 -0800264
265 for _, data := range android.PathsForModuleSrc(ctx, r.testProperties.Data) {
266 installedData := ctx.InstallFile(installPath, data.Rel(), data)
267 installDeps = append(installDeps, installedData)
268 }
269
Colin Cross6301c3c2021-09-28 17:40:21 -0700270 r.installFile = ctx.InstallFile(installPath, ctx.ModuleName()+".jar", r.combinedJar, installDeps...)
Colin Cross40213022023-12-13 15:19:49 -0800271 android.SetProvider(ctx, testing.TestModuleProviderKey, testing.TestModuleProviderData{})
Colin Crossd2d11772019-05-30 11:17:23 -0700272}
273
Colin Cross8eebb132020-01-29 20:07:03 -0800274func generateRoboTestConfig(ctx android.ModuleContext, outputFile android.WritablePath,
275 instrumentedApp *AndroidApp) {
Colin Crossf1a035e2020-11-16 17:32:30 -0800276 rule := android.NewRuleBuilder(pctx, ctx)
Colin Cross8eebb132020-01-29 20:07:03 -0800277
Colin Cross3ec27ec2019-05-01 15:54:05 -0700278 manifest := instrumentedApp.mergedManifestFile
279 resourceApk := instrumentedApp.outputFile
280
Colin Cross3ec27ec2019-05-01 15:54:05 -0700281 rule.Command().Text("rm -f").Output(outputFile)
282 rule.Command().
283 Textf(`echo "android_merged_manifest=%s" >>`, manifest.String()).Output(outputFile).Text("&&").
284 Textf(`echo "android_resource_apk=%s" >>`, resourceApk.String()).Output(outputFile).
285 // Make it depend on the files to which it points so the test file's timestamp is updated whenever the
286 // contents change
287 Implicit(manifest).
288 Implicit(resourceApk)
289
Colin Crossf1a035e2020-11-16 17:32:30 -0800290 rule.Build("generate_test_config", "generate test_config.properties")
Colin Cross3ec27ec2019-05-01 15:54:05 -0700291}
292
Colin Cross8eebb132020-01-29 20:07:03 -0800293func generateSameDirRoboTestConfigJar(ctx android.ModuleContext, outputFile android.ModuleOutPath) {
Colin Crossf1a035e2020-11-16 17:32:30 -0800294 rule := android.NewRuleBuilder(pctx, ctx)
Colin Cross8eebb132020-01-29 20:07:03 -0800295
296 outputDir := outputFile.InSameDir(ctx)
297 configFile := outputDir.Join(ctx, "com/android/tools/test_config.properties")
298 rule.Temporary(configFile)
299 rule.Command().Text("rm -f").Output(outputFile).Output(configFile)
300 rule.Command().Textf("mkdir -p $(dirname %s)", configFile.String())
301 rule.Command().
302 Text("(").
303 Textf(`echo "android_merged_manifest=%s-AndroidManifest.xml" &&`, ctx.ModuleName()).
304 Textf(`echo "android_resource_apk=%s.apk"`, ctx.ModuleName()).
305 Text(") >>").Output(configFile)
306 rule.Command().
Colin Crossf1a035e2020-11-16 17:32:30 -0800307 BuiltTool("soong_zip").
Colin Cross8eebb132020-01-29 20:07:03 -0800308 FlagWithArg("-C ", outputDir.String()).
309 FlagWithInput("-f ", configFile).
310 FlagWithOutput("-o ", outputFile)
311
Colin Crossf1a035e2020-11-16 17:32:30 -0800312 rule.Build("generate_test_config_samedir", "generate test_config.properties")
Colin Cross8eebb132020-01-29 20:07:03 -0800313}
314
Colin Cross3ec27ec2019-05-01 15:54:05 -0700315func (r *robolectricTest) generateRoboSrcJar(ctx android.ModuleContext, outputFile android.WritablePath,
316 instrumentedApp *AndroidApp) {
317
Colin Cross48016d52023-06-27 09:45:26 -0700318 srcJarArgs := android.CopyOf(instrumentedApp.srcJarArgs)
Colin Cross3ec27ec2019-05-01 15:54:05 -0700319 srcJarDeps := append(android.Paths(nil), instrumentedApp.srcJarDeps...)
320
321 for _, m := range ctx.GetDirectDepsWithTag(roboCoverageLibsTag) {
Colin Cross313aa542023-12-13 13:47:44 -0800322 if dep, ok := android.OtherModuleProvider(ctx, m, JavaInfoProvider); ok {
Colin Crossdcf71b22021-02-01 13:59:03 -0800323 srcJarArgs = append(srcJarArgs, dep.SrcJarArgs...)
324 srcJarDeps = append(srcJarDeps, dep.SrcJarDeps...)
Colin Cross3ec27ec2019-05-01 15:54:05 -0700325 }
326 }
327
328 TransformResourcesToJar(ctx, outputFile, srcJarArgs, srcJarDeps)
329}
330
Jiyong Park0b0e1b92019-12-03 13:24:29 +0900331func (r *robolectricTest) AndroidMkEntries() []android.AndroidMkEntries {
332 entriesList := r.Library.AndroidMkEntries()
333 entries := &entriesList[0]
Colin Cross6301c3c2021-09-28 17:40:21 -0700334 entries.ExtraEntries = append(entries.ExtraEntries,
335 func(ctx android.AndroidMkExtraEntriesContext, entries *android.AndroidMkEntries) {
336 entries.SetBool("LOCAL_UNINSTALLABLE_MODULE", true)
nelsonli3f97ea22022-11-21 21:37:56 +0800337 entries.AddStrings("LOCAL_COMPATIBILITY_SUITE", "robolectric-tests")
Yike0fcf90a2023-02-14 12:17:32 +0800338 if r.testConfig != nil {
339 entries.SetPath("LOCAL_FULL_TEST_CONFIG", r.testConfig)
340 }
Colin Cross6301c3c2021-09-28 17:40:21 -0700341 })
Colin Cross0ef08162019-05-01 15:50:51 -0700342
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700343 entries.ExtraFooters = []android.AndroidMkExtraFootersFunc{
Jaewoong Jung02b11a62020-12-07 10:23:54 -0800344 func(w io.Writer, name, prefix, moduleDir string) {
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700345 if s := r.robolectricProperties.Test_options.Shards; s != nil && *s > 1 {
Colin Cross0a2f7192019-09-23 14:33:09 -0700346 numShards := int(*s)
347 shardSize := (len(r.tests) + numShards - 1) / numShards
348 shards := android.ShardStrings(r.tests, shardSize)
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700349 for i, shard := range shards {
350 r.writeTestRunner(w, name, "Run"+name+strconv.Itoa(i), shard)
351 }
Colin Cross0ef08162019-05-01 15:50:51 -0700352
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700353 // TODO: add rules to dist the outputs of the individual tests, or combine them together?
354 fmt.Fprintln(w, "")
355 fmt.Fprintln(w, ".PHONY:", "Run"+name)
356 fmt.Fprintln(w, "Run"+name, ": \\")
357 for i := range shards {
358 fmt.Fprintln(w, " ", "Run"+name+strconv.Itoa(i), "\\")
359 }
360 fmt.Fprintln(w, "")
361 } else {
362 r.writeTestRunner(w, name, "Run"+name, r.tests)
Colin Crossd2d11772019-05-30 11:17:23 -0700363 }
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700364 },
Colin Cross0ef08162019-05-01 15:50:51 -0700365 }
366
Jiyong Park0b0e1b92019-12-03 13:24:29 +0900367 return entriesList
Colin Cross0ef08162019-05-01 15:50:51 -0700368}
369
Colin Crossd2d11772019-05-30 11:17:23 -0700370func (r *robolectricTest) writeTestRunner(w io.Writer, module, name string, tests []string) {
371 fmt.Fprintln(w, "")
Sasha Smundak5c4729d2022-12-01 10:49:23 -0800372 fmt.Fprintln(w, "include $(CLEAR_VARS)", " # java.robolectricTest")
Colin Crossd2d11772019-05-30 11:17:23 -0700373 fmt.Fprintln(w, "LOCAL_MODULE :=", name)
Sasha Smundakdcb61292022-12-08 10:41:33 -0800374 android.AndroidMkEmitAssignList(w, "LOCAL_JAVA_LIBRARIES", []string{module}, r.libs)
Colin Crossd2d11772019-05-30 11:17:23 -0700375 fmt.Fprintln(w, "LOCAL_TEST_PACKAGE :=", String(r.robolectricProperties.Instrumentation_for))
Colin Crossf521efa2023-05-19 09:47:09 -0700376 if r.roboSrcJar != nil {
377 fmt.Fprintln(w, "LOCAL_INSTRUMENT_SRCJARS :=", r.roboSrcJar.String())
378 }
Sasha Smundakdcb61292022-12-08 10:41:33 -0800379 android.AndroidMkEmitAssignList(w, "LOCAL_ROBOTEST_FILES", tests)
Colin Crossd2d11772019-05-30 11:17:23 -0700380 if t := r.robolectricProperties.Test_options.Timeout; t != nil {
381 fmt.Fprintln(w, "LOCAL_ROBOTEST_TIMEOUT :=", *t)
382 }
Colin Cross2787e8e2021-03-05 11:16:20 -0800383 if v := String(r.robolectricProperties.Robolectric_prebuilt_version); v != "" {
384 fmt.Fprintf(w, "-include prebuilts/misc/common/robolectric/%s/run_robotests.mk\n", v)
385 } else {
386 fmt.Fprintln(w, "-include external/robolectric-shadows/run_robotests.mk")
387 }
Colin Crossd2d11772019-05-30 11:17:23 -0700388}
389
Colin Cross0ef08162019-05-01 15:50:51 -0700390// An android_robolectric_test module compiles tests against the Robolectric framework that can run on the local host
391// instead of on a device. It also generates a rule with the name of the module prefixed with "Run" that can be
392// used to run the tests. Running the tests with build rule will eventually be deprecated and replaced with atest.
Colin Crossd2d11772019-05-30 11:17:23 -0700393//
394// The test runner considers any file listed in srcs whose name ends with Test.java to be a test class, unless
395// it is named BaseRobolectricTest.java. The path to the each source file must exactly match the package
396// name, or match the package name when the prefix "src/" is removed.
Colin Cross0ef08162019-05-01 15:50:51 -0700397func RobolectricTestFactory() android.Module {
398 module := &robolectricTest{}
399
Colin Crossce6734e2020-06-15 16:09:53 -0700400 module.addHostProperties()
Colin Cross0ef08162019-05-01 15:50:51 -0700401 module.AddProperties(
Colin Crosse323f3c2019-09-17 15:34:09 -0700402 &module.Module.deviceProperties,
Colin Cross8eebb132020-01-29 20:07:03 -0800403 &module.robolectricProperties,
404 &module.testProperties)
Colin Cross0ef08162019-05-01 15:50:51 -0700405
406 module.Module.dexpreopter.isTest = true
Cole Faustd57e8b22022-08-11 11:59:04 -0700407 module.Module.linter.properties.Lint.Test = proptools.BoolPtr(true)
Colin Cross0ef08162019-05-01 15:50:51 -0700408
Colin Cross8eebb132020-01-29 20:07:03 -0800409 module.testProperties.Test_suites = []string{"robolectric-tests"}
410
Colin Cross0ef08162019-05-01 15:50:51 -0700411 InitJavaModule(module, android.DeviceSupported)
412 return module
413}
Colin Cross8eebb132020-01-29 20:07:03 -0800414
Jiyong Park87788b52020-09-01 12:37:45 +0900415func (r *robolectricTest) InstallInTestcases() bool { return true }
416func (r *robolectricTest) InstallForceOS() (*android.OsType, *android.ArchType) {
Colin Cross0c66bc62021-07-20 09:47:41 -0700417 return &r.forceOSType, &r.forceArchType
Jiyong Park87788b52020-09-01 12:37:45 +0900418}
Colin Cross8eebb132020-01-29 20:07:03 -0800419
420func robolectricRuntimesFactory() android.Module {
421 module := &robolectricRuntimes{}
422 module.AddProperties(&module.props)
Colin Cross5aa29a72020-09-14 19:54:47 -0700423 android.InitAndroidArchModule(module, android.HostSupportedNoCross, android.MultilibCommon)
Colin Cross8eebb132020-01-29 20:07:03 -0800424 return module
425}
426
427type robolectricRuntimesProperties struct {
428 Jars []string `android:"path"`
429 Lib *string
430}
431
432type robolectricRuntimes struct {
433 android.ModuleBase
434
435 props robolectricRuntimesProperties
436
437 runtimes []android.InstallPath
Colin Cross0c66bc62021-07-20 09:47:41 -0700438
439 forceOSType android.OsType
440 forceArchType android.ArchType
Colin Cross8eebb132020-01-29 20:07:03 -0800441}
442
443func (r *robolectricRuntimes) TestSuites() []string {
444 return []string{"robolectric-tests"}
445}
446
447var _ android.TestSuiteModule = (*robolectricRuntimes)(nil)
448
449func (r *robolectricRuntimes) DepsMutator(ctx android.BottomUpMutatorContext) {
Jeongik Cha816a23a2020-07-08 01:09:23 +0900450 if !ctx.Config().AlwaysUsePrebuiltSdks() && r.props.Lib != nil {
Colin Cross8eebb132020-01-29 20:07:03 -0800451 ctx.AddVariationDependencies(nil, libTag, String(r.props.Lib))
452 }
453}
454
455func (r *robolectricRuntimes) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Colin Cross5aa29a72020-09-14 19:54:47 -0700456 if ctx.Target().Os != ctx.Config().BuildOSCommonTarget.Os {
457 return
458 }
459
Colin Cross0c66bc62021-07-20 09:47:41 -0700460 r.forceOSType = ctx.Config().BuildOS
461 r.forceArchType = ctx.Config().BuildArch
462
Colin Cross8eebb132020-01-29 20:07:03 -0800463 files := android.PathsForModuleSrc(ctx, r.props.Jars)
464
465 androidAllDir := android.PathForModuleInstall(ctx, "android-all")
Colin Cross8eebb132020-01-29 20:07:03 -0800466 for _, from := range files {
467 installedRuntime := ctx.InstallFile(androidAllDir, from.Base(), from)
468 r.runtimes = append(r.runtimes, installedRuntime)
469 }
470
Jeongik Cha816a23a2020-07-08 01:09:23 +0900471 if !ctx.Config().AlwaysUsePrebuiltSdks() && r.props.Lib != nil {
Colin Cross8eebb132020-01-29 20:07:03 -0800472 runtimeFromSourceModule := ctx.GetDirectDepWithTag(String(r.props.Lib), libTag)
Jeongik Cha816a23a2020-07-08 01:09:23 +0900473 if runtimeFromSourceModule == nil {
474 if ctx.Config().AllowMissingDependencies() {
475 ctx.AddMissingDependencies([]string{String(r.props.Lib)})
476 } else {
477 ctx.PropertyErrorf("lib", "missing dependency %q", String(r.props.Lib))
478 }
479 return
480 }
Colin Cross8eebb132020-01-29 20:07:03 -0800481 runtimeFromSourceJar := android.OutputFileForModule(ctx, runtimeFromSourceModule, "")
482
Joseph Murphyc9648412021-07-20 13:58:15 -0700483 // "TREE" name is essential here because it hooks into the "TREE" name in
484 // Robolectric's SdkConfig.java that will always correspond to the NEWEST_SDK
485 // in Robolectric configs.
486 runtimeName := "android-all-current-robolectric-r0.jar"
Colin Cross8eebb132020-01-29 20:07:03 -0800487 installedRuntime := ctx.InstallFile(androidAllDir, runtimeName, runtimeFromSourceJar)
488 r.runtimes = append(r.runtimes, installedRuntime)
489 }
490}
491
Jiyong Park87788b52020-09-01 12:37:45 +0900492func (r *robolectricRuntimes) InstallInTestcases() bool { return true }
493func (r *robolectricRuntimes) InstallForceOS() (*android.OsType, *android.ArchType) {
Colin Cross0c66bc62021-07-20 09:47:41 -0700494 return &r.forceOSType, &r.forceArchType
Jiyong Park87788b52020-09-01 12:37:45 +0900495}