blob: cb22fa0dbb9d567b3ea12441bd7f03c3e59dd9ba [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))
Kevin Liu51349b82024-06-28 15:02:12 +0000119 } else if !proptools.BoolDefault(r.robolectricProperties.Strict_mode, true) {
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
Kevin Liu51349b82024-06-28 15:02:12 +0000127 if proptools.BoolDefault(r.robolectricProperties.Strict_mode, true) {
Kevin Liucab89b52024-04-12 21:52:07 +0000128 ctx.AddVariationDependencies(nil, roboRuntimeOnlyTag, robolectricCurrentLib+"_upstream")
Kevin Liu51349b82024-06-28 15:02:12 +0000129 } else {
130 // opting out from strict mode, robolectric_non_strict_mode_permission lib should be added
131 ctx.AddVariationDependencies(nil, libTag, "robolectric_non_strict_mode_permission")
Kevin Liucab89b52024-04-12 21:52:07 +0000132 }
133
Colin Cross0ef08162019-05-01 15:50:51 -0700134 ctx.AddVariationDependencies(nil, libTag, robolectricDefaultLibs...)
Colin Cross3ec27ec2019-05-01 15:54:05 -0700135
136 ctx.AddVariationDependencies(nil, roboCoverageLibsTag, r.robolectricProperties.Coverage_libs...)
Colin Cross8eebb132020-01-29 20:07:03 -0800137
Colin Cross5aa29a72020-09-14 19:54:47 -0700138 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(),
139 roboRuntimesTag, "robolectric-android-all-prebuilts")
Colin Cross0ef08162019-05-01 15:50:51 -0700140}
141
142func (r *robolectricTest) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Colin Cross0c66bc62021-07-20 09:47:41 -0700143 r.forceOSType = ctx.Config().BuildOS
144 r.forceArchType = ctx.Config().BuildArch
145
Cole Faust21680542022-12-07 18:18:37 -0800146 r.testConfig = tradefed.AutoGenTestConfig(ctx, tradefed.AutoGenTestConfigOptions{
147 TestConfigProp: r.testProperties.Test_config,
148 TestConfigTemplateProp: r.testProperties.Test_config_template,
149 TestSuites: r.testProperties.Test_suites,
150 AutoGenConfig: r.testProperties.Auto_gen_config,
151 DeviceTemplate: "${RobolectricTestConfigTemplate}",
152 HostTemplate: "${RobolectricTestConfigTemplate}",
153 })
Colin Cross8eebb132020-01-29 20:07:03 -0800154 r.data = android.PathsForModuleSrc(ctx, r.testProperties.Data)
155
Colin Cross3ec27ec2019-05-01 15:54:05 -0700156 roboTestConfig := android.PathForModuleGen(ctx, "robolectric").
157 Join(ctx, "com/android/tools/test_config.properties")
158
Colin Crossf521efa2023-05-19 09:47:09 -0700159 var ok bool
160 var instrumentedApp *AndroidApp
161
Colin Cross3ec27ec2019-05-01 15:54:05 -0700162 // TODO: this inserts paths to built files into the test, it should really be inserting the contents.
163 instrumented := ctx.GetDirectDepsWithTag(instrumentationForTag)
164
Colin Crossf521efa2023-05-19 09:47:09 -0700165 if len(instrumented) == 1 {
166 instrumentedApp, ok = instrumented[0].(*AndroidApp)
167 if !ok {
168 ctx.PropertyErrorf("instrumentation_for", "dependency must be an android_app")
169 }
170 } else if !ctx.Config().AllowMissingDependencies() {
Colin Cross3ec27ec2019-05-01 15:54:05 -0700171 panic(fmt.Errorf("expected exactly 1 instrumented dependency, got %d", len(instrumented)))
172 }
173
Colin Crossf521efa2023-05-19 09:47:09 -0700174 if instrumentedApp != nil {
175 r.manifest = instrumentedApp.mergedManifestFile
176 r.resourceApk = instrumentedApp.outputFile
177
178 generateRoboTestConfig(ctx, roboTestConfig, instrumentedApp)
179 r.extraResources = android.Paths{roboTestConfig}
Colin Cross3ec27ec2019-05-01 15:54:05 -0700180 }
181
Colin Cross0ef08162019-05-01 15:50:51 -0700182 r.Library.GenerateAndroidBuildActions(ctx)
183
Colin Cross3ec27ec2019-05-01 15:54:05 -0700184 roboSrcJar := android.PathForModuleGen(ctx, "robolectric", ctx.ModuleName()+".srcjar")
Colin Crossf521efa2023-05-19 09:47:09 -0700185
186 if instrumentedApp != nil {
187 r.generateRoboSrcJar(ctx, roboSrcJar, instrumentedApp)
188 r.roboSrcJar = roboSrcJar
189 }
Colin Cross3ec27ec2019-05-01 15:54:05 -0700190
Colin Cross8eebb132020-01-29 20:07:03 -0800191 roboTestConfigJar := android.PathForModuleOut(ctx, "robolectric_samedir", "samedir_config.jar")
192 generateSameDirRoboTestConfigJar(ctx, roboTestConfigJar)
193
194 combinedJarJars := android.Paths{
195 // roboTestConfigJar comes first so that its com/android/tools/test_config.properties
196 // overrides the one from r.extraResources. The r.extraResources one can be removed
197 // once the Make test runner is removed.
198 roboTestConfigJar,
199 r.outputFile,
Colin Crossf521efa2023-05-19 09:47:09 -0700200 }
201
202 if instrumentedApp != nil {
203 combinedJarJars = append(combinedJarJars, instrumentedApp.implementationAndResourcesJar)
Colin Cross0ef08162019-05-01 15:50:51 -0700204 }
Colin Crossd2d11772019-05-30 11:17:23 -0700205
Kevin Liucab89b52024-04-12 21:52:07 +0000206 handleLibDeps := func(dep android.Module, runtimeOnly bool) {
Colin Cross313aa542023-12-13 13:47:44 -0800207 m, _ := android.OtherModuleProvider(ctx, dep, JavaInfoProvider)
Kevin Liucab89b52024-04-12 21:52:07 +0000208 if !runtimeOnly {
209 r.libs = append(r.libs, ctx.OtherModuleName(dep))
210 }
Colin Crossdcf71b22021-02-01 13:59:03 -0800211 if !android.InList(ctx.OtherModuleName(dep), config.FrameworkLibraries) {
212 combinedJarJars = append(combinedJarJars, m.ImplementationAndResourcesJars...)
Colin Cross8eebb132020-01-29 20:07:03 -0800213 }
214 }
215
Liz Kammeref28a4c2022-09-23 16:50:56 -0400216 for _, dep := range ctx.GetDirectDepsWithTag(libTag) {
Kevin Liucab89b52024-04-12 21:52:07 +0000217 handleLibDeps(dep, false)
Liz Kammeref28a4c2022-09-23 16:50:56 -0400218 }
219 for _, dep := range ctx.GetDirectDepsWithTag(sdkLibTag) {
Kevin Liucab89b52024-04-12 21:52:07 +0000220 handleLibDeps(dep, false)
221 }
222 // handle the runtimeOnly tag for strict_mode
223 for _, dep := range ctx.GetDirectDepsWithTag(roboRuntimeOnlyTag) {
224 handleLibDeps(dep, true)
Liz Kammeref28a4c2022-09-23 16:50:56 -0400225 }
226
Colin Cross8eebb132020-01-29 20:07:03 -0800227 r.combinedJar = android.PathForModuleOut(ctx, "robolectric_combined", r.outputFile.Base())
228 TransformJarsToJar(ctx, r.combinedJar, "combine jars", combinedJarJars, android.OptionalPath{},
229 false, nil, nil)
230
Colin Crossd2d11772019-05-30 11:17:23 -0700231 // TODO: this could all be removed if tradefed was used as the test runner, it will find everything
232 // annotated as a test and run it.
Chaohui Wangdcbe33c2022-10-11 11:13:30 +0800233 for _, src := range r.uniqueSrcFiles {
Colin Crossd2d11772019-05-30 11:17:23 -0700234 s := src.Rel()
Chaohui Wangdcbe33c2022-10-11 11:13:30 +0800235 if !strings.HasSuffix(s, "Test.java") && !strings.HasSuffix(s, "Test.kt") {
Colin Crossd2d11772019-05-30 11:17:23 -0700236 continue
237 } else if strings.HasSuffix(s, "/BaseRobolectricTest.java") {
238 continue
Ulya Trafimovich497a0932021-07-14 16:35:33 +0100239 } else {
Colin Crossd2d11772019-05-30 11:17:23 -0700240 s = strings.TrimPrefix(s, "src/")
241 }
242 r.tests = append(r.tests, s)
243 }
Colin Cross8eebb132020-01-29 20:07:03 -0800244
Colin Crossf521efa2023-05-19 09:47:09 -0700245 installPath := android.PathForModuleInstall(ctx, r.BaseModuleName())
Colin Cross09ad3a62023-11-15 12:29:33 -0800246 var installDeps android.InstallPaths
Colin Crossf521efa2023-05-19 09:47:09 -0700247
248 if r.manifest != nil {
249 r.data = append(r.data, r.manifest)
250 installedManifest := ctx.InstallFile(installPath, ctx.ModuleName()+"-AndroidManifest.xml", r.manifest)
251 installDeps = append(installDeps, installedManifest)
252 }
253
254 if r.resourceApk != nil {
255 r.data = append(r.data, r.resourceApk)
256 installedResourceApk := ctx.InstallFile(installPath, ctx.ModuleName()+".apk", r.resourceApk)
257 installDeps = append(installDeps, installedResourceApk)
258 }
Colin Cross8eebb132020-01-29 20:07:03 -0800259
260 runtimes := ctx.GetDirectDepWithTag("robolectric-android-all-prebuilts", roboRuntimesTag)
Colin Cross8eebb132020-01-29 20:07:03 -0800261 for _, runtime := range runtimes.(*robolectricRuntimes).runtimes {
262 installDeps = append(installDeps, runtime)
263 }
Colin Crossf521efa2023-05-19 09:47:09 -0700264
265 installedConfig := ctx.InstallFile(installPath, ctx.ModuleName()+".config", r.testConfig)
266 installDeps = append(installDeps, installedConfig)
Colin Cross8eebb132020-01-29 20:07:03 -0800267
268 for _, data := range android.PathsForModuleSrc(ctx, r.testProperties.Data) {
269 installedData := ctx.InstallFile(installPath, data.Rel(), data)
270 installDeps = append(installDeps, installedData)
271 }
272
Colin Cross6301c3c2021-09-28 17:40:21 -0700273 r.installFile = ctx.InstallFile(installPath, ctx.ModuleName()+".jar", r.combinedJar, installDeps...)
Colin Cross40213022023-12-13 15:19:49 -0800274 android.SetProvider(ctx, testing.TestModuleProviderKey, testing.TestModuleProviderData{})
Colin Crossd2d11772019-05-30 11:17:23 -0700275}
276
Colin Cross8eebb132020-01-29 20:07:03 -0800277func generateRoboTestConfig(ctx android.ModuleContext, outputFile android.WritablePath,
278 instrumentedApp *AndroidApp) {
Colin Crossf1a035e2020-11-16 17:32:30 -0800279 rule := android.NewRuleBuilder(pctx, ctx)
Colin Cross8eebb132020-01-29 20:07:03 -0800280
Colin Cross3ec27ec2019-05-01 15:54:05 -0700281 manifest := instrumentedApp.mergedManifestFile
282 resourceApk := instrumentedApp.outputFile
283
Colin Cross3ec27ec2019-05-01 15:54:05 -0700284 rule.Command().Text("rm -f").Output(outputFile)
285 rule.Command().
286 Textf(`echo "android_merged_manifest=%s" >>`, manifest.String()).Output(outputFile).Text("&&").
287 Textf(`echo "android_resource_apk=%s" >>`, resourceApk.String()).Output(outputFile).
288 // Make it depend on the files to which it points so the test file's timestamp is updated whenever the
289 // contents change
290 Implicit(manifest).
291 Implicit(resourceApk)
292
Colin Crossf1a035e2020-11-16 17:32:30 -0800293 rule.Build("generate_test_config", "generate test_config.properties")
Colin Cross3ec27ec2019-05-01 15:54:05 -0700294}
295
Colin Cross8eebb132020-01-29 20:07:03 -0800296func generateSameDirRoboTestConfigJar(ctx android.ModuleContext, outputFile android.ModuleOutPath) {
Colin Crossf1a035e2020-11-16 17:32:30 -0800297 rule := android.NewRuleBuilder(pctx, ctx)
Colin Cross8eebb132020-01-29 20:07:03 -0800298
299 outputDir := outputFile.InSameDir(ctx)
300 configFile := outputDir.Join(ctx, "com/android/tools/test_config.properties")
301 rule.Temporary(configFile)
302 rule.Command().Text("rm -f").Output(outputFile).Output(configFile)
303 rule.Command().Textf("mkdir -p $(dirname %s)", configFile.String())
304 rule.Command().
305 Text("(").
306 Textf(`echo "android_merged_manifest=%s-AndroidManifest.xml" &&`, ctx.ModuleName()).
307 Textf(`echo "android_resource_apk=%s.apk"`, ctx.ModuleName()).
308 Text(") >>").Output(configFile)
309 rule.Command().
Colin Crossf1a035e2020-11-16 17:32:30 -0800310 BuiltTool("soong_zip").
Colin Cross8eebb132020-01-29 20:07:03 -0800311 FlagWithArg("-C ", outputDir.String()).
312 FlagWithInput("-f ", configFile).
313 FlagWithOutput("-o ", outputFile)
314
Colin Crossf1a035e2020-11-16 17:32:30 -0800315 rule.Build("generate_test_config_samedir", "generate test_config.properties")
Colin Cross8eebb132020-01-29 20:07:03 -0800316}
317
Colin Cross3ec27ec2019-05-01 15:54:05 -0700318func (r *robolectricTest) generateRoboSrcJar(ctx android.ModuleContext, outputFile android.WritablePath,
319 instrumentedApp *AndroidApp) {
320
Colin Cross48016d52023-06-27 09:45:26 -0700321 srcJarArgs := android.CopyOf(instrumentedApp.srcJarArgs)
Colin Cross3ec27ec2019-05-01 15:54:05 -0700322 srcJarDeps := append(android.Paths(nil), instrumentedApp.srcJarDeps...)
323
324 for _, m := range ctx.GetDirectDepsWithTag(roboCoverageLibsTag) {
Colin Cross313aa542023-12-13 13:47:44 -0800325 if dep, ok := android.OtherModuleProvider(ctx, m, JavaInfoProvider); ok {
Colin Crossdcf71b22021-02-01 13:59:03 -0800326 srcJarArgs = append(srcJarArgs, dep.SrcJarArgs...)
327 srcJarDeps = append(srcJarDeps, dep.SrcJarDeps...)
Colin Cross3ec27ec2019-05-01 15:54:05 -0700328 }
329 }
330
331 TransformResourcesToJar(ctx, outputFile, srcJarArgs, srcJarDeps)
332}
333
Jiyong Park0b0e1b92019-12-03 13:24:29 +0900334func (r *robolectricTest) AndroidMkEntries() []android.AndroidMkEntries {
335 entriesList := r.Library.AndroidMkEntries()
336 entries := &entriesList[0]
Colin Cross6301c3c2021-09-28 17:40:21 -0700337 entries.ExtraEntries = append(entries.ExtraEntries,
338 func(ctx android.AndroidMkExtraEntriesContext, entries *android.AndroidMkEntries) {
339 entries.SetBool("LOCAL_UNINSTALLABLE_MODULE", true)
nelsonli3f97ea22022-11-21 21:37:56 +0800340 entries.AddStrings("LOCAL_COMPATIBILITY_SUITE", "robolectric-tests")
Yike0fcf90a2023-02-14 12:17:32 +0800341 if r.testConfig != nil {
342 entries.SetPath("LOCAL_FULL_TEST_CONFIG", r.testConfig)
343 }
Colin Cross6301c3c2021-09-28 17:40:21 -0700344 })
Colin Cross0ef08162019-05-01 15:50:51 -0700345
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700346 entries.ExtraFooters = []android.AndroidMkExtraFootersFunc{
Jaewoong Jung02b11a62020-12-07 10:23:54 -0800347 func(w io.Writer, name, prefix, moduleDir string) {
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700348 if s := r.robolectricProperties.Test_options.Shards; s != nil && *s > 1 {
Colin Cross0a2f7192019-09-23 14:33:09 -0700349 numShards := int(*s)
350 shardSize := (len(r.tests) + numShards - 1) / numShards
351 shards := android.ShardStrings(r.tests, shardSize)
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700352 for i, shard := range shards {
353 r.writeTestRunner(w, name, "Run"+name+strconv.Itoa(i), shard)
354 }
Colin Cross0ef08162019-05-01 15:50:51 -0700355
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700356 // TODO: add rules to dist the outputs of the individual tests, or combine them together?
357 fmt.Fprintln(w, "")
358 fmt.Fprintln(w, ".PHONY:", "Run"+name)
359 fmt.Fprintln(w, "Run"+name, ": \\")
360 for i := range shards {
361 fmt.Fprintln(w, " ", "Run"+name+strconv.Itoa(i), "\\")
362 }
363 fmt.Fprintln(w, "")
364 } else {
365 r.writeTestRunner(w, name, "Run"+name, r.tests)
Colin Crossd2d11772019-05-30 11:17:23 -0700366 }
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700367 },
Colin Cross0ef08162019-05-01 15:50:51 -0700368 }
369
Jiyong Park0b0e1b92019-12-03 13:24:29 +0900370 return entriesList
Colin Cross0ef08162019-05-01 15:50:51 -0700371}
372
Colin Crossd2d11772019-05-30 11:17:23 -0700373func (r *robolectricTest) writeTestRunner(w io.Writer, module, name string, tests []string) {
374 fmt.Fprintln(w, "")
Sasha Smundak5c4729d2022-12-01 10:49:23 -0800375 fmt.Fprintln(w, "include $(CLEAR_VARS)", " # java.robolectricTest")
Colin Crossd2d11772019-05-30 11:17:23 -0700376 fmt.Fprintln(w, "LOCAL_MODULE :=", name)
Sasha Smundakdcb61292022-12-08 10:41:33 -0800377 android.AndroidMkEmitAssignList(w, "LOCAL_JAVA_LIBRARIES", []string{module}, r.libs)
Colin Crossd2d11772019-05-30 11:17:23 -0700378 fmt.Fprintln(w, "LOCAL_TEST_PACKAGE :=", String(r.robolectricProperties.Instrumentation_for))
Colin Crossf521efa2023-05-19 09:47:09 -0700379 if r.roboSrcJar != nil {
380 fmt.Fprintln(w, "LOCAL_INSTRUMENT_SRCJARS :=", r.roboSrcJar.String())
381 }
Sasha Smundakdcb61292022-12-08 10:41:33 -0800382 android.AndroidMkEmitAssignList(w, "LOCAL_ROBOTEST_FILES", tests)
Colin Crossd2d11772019-05-30 11:17:23 -0700383 if t := r.robolectricProperties.Test_options.Timeout; t != nil {
384 fmt.Fprintln(w, "LOCAL_ROBOTEST_TIMEOUT :=", *t)
385 }
Colin Cross2787e8e2021-03-05 11:16:20 -0800386 if v := String(r.robolectricProperties.Robolectric_prebuilt_version); v != "" {
387 fmt.Fprintf(w, "-include prebuilts/misc/common/robolectric/%s/run_robotests.mk\n", v)
388 } else {
389 fmt.Fprintln(w, "-include external/robolectric-shadows/run_robotests.mk")
390 }
Colin Crossd2d11772019-05-30 11:17:23 -0700391}
392
Colin Cross0ef08162019-05-01 15:50:51 -0700393// An android_robolectric_test module compiles tests against the Robolectric framework that can run on the local host
394// instead of on a device. It also generates a rule with the name of the module prefixed with "Run" that can be
395// 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 -0700396//
397// The test runner considers any file listed in srcs whose name ends with Test.java to be a test class, unless
398// it is named BaseRobolectricTest.java. The path to the each source file must exactly match the package
399// name, or match the package name when the prefix "src/" is removed.
Colin Cross0ef08162019-05-01 15:50:51 -0700400func RobolectricTestFactory() android.Module {
401 module := &robolectricTest{}
402
Colin Crossce6734e2020-06-15 16:09:53 -0700403 module.addHostProperties()
Colin Cross0ef08162019-05-01 15:50:51 -0700404 module.AddProperties(
Colin Crosse323f3c2019-09-17 15:34:09 -0700405 &module.Module.deviceProperties,
Colin Cross8eebb132020-01-29 20:07:03 -0800406 &module.robolectricProperties,
407 &module.testProperties)
Colin Cross0ef08162019-05-01 15:50:51 -0700408
409 module.Module.dexpreopter.isTest = true
Cole Faustd57e8b22022-08-11 11:59:04 -0700410 module.Module.linter.properties.Lint.Test = proptools.BoolPtr(true)
Colin Cross0ef08162019-05-01 15:50:51 -0700411
Colin Cross8eebb132020-01-29 20:07:03 -0800412 module.testProperties.Test_suites = []string{"robolectric-tests"}
413
Colin Cross0ef08162019-05-01 15:50:51 -0700414 InitJavaModule(module, android.DeviceSupported)
415 return module
416}
Colin Cross8eebb132020-01-29 20:07:03 -0800417
Jiyong Park87788b52020-09-01 12:37:45 +0900418func (r *robolectricTest) InstallInTestcases() bool { return true }
419func (r *robolectricTest) InstallForceOS() (*android.OsType, *android.ArchType) {
Colin Cross0c66bc62021-07-20 09:47:41 -0700420 return &r.forceOSType, &r.forceArchType
Jiyong Park87788b52020-09-01 12:37:45 +0900421}
Colin Cross8eebb132020-01-29 20:07:03 -0800422
423func robolectricRuntimesFactory() android.Module {
424 module := &robolectricRuntimes{}
425 module.AddProperties(&module.props)
Colin Cross5aa29a72020-09-14 19:54:47 -0700426 android.InitAndroidArchModule(module, android.HostSupportedNoCross, android.MultilibCommon)
Colin Cross8eebb132020-01-29 20:07:03 -0800427 return module
428}
429
430type robolectricRuntimesProperties struct {
431 Jars []string `android:"path"`
432 Lib *string
433}
434
435type robolectricRuntimes struct {
436 android.ModuleBase
437
438 props robolectricRuntimesProperties
439
440 runtimes []android.InstallPath
Colin Cross0c66bc62021-07-20 09:47:41 -0700441
442 forceOSType android.OsType
443 forceArchType android.ArchType
Colin Cross8eebb132020-01-29 20:07:03 -0800444}
445
446func (r *robolectricRuntimes) TestSuites() []string {
447 return []string{"robolectric-tests"}
448}
449
450var _ android.TestSuiteModule = (*robolectricRuntimes)(nil)
451
452func (r *robolectricRuntimes) DepsMutator(ctx android.BottomUpMutatorContext) {
Jeongik Cha816a23a2020-07-08 01:09:23 +0900453 if !ctx.Config().AlwaysUsePrebuiltSdks() && r.props.Lib != nil {
Colin Cross8eebb132020-01-29 20:07:03 -0800454 ctx.AddVariationDependencies(nil, libTag, String(r.props.Lib))
455 }
456}
457
458func (r *robolectricRuntimes) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Colin Cross5aa29a72020-09-14 19:54:47 -0700459 if ctx.Target().Os != ctx.Config().BuildOSCommonTarget.Os {
460 return
461 }
462
Colin Cross0c66bc62021-07-20 09:47:41 -0700463 r.forceOSType = ctx.Config().BuildOS
464 r.forceArchType = ctx.Config().BuildArch
465
Colin Cross8eebb132020-01-29 20:07:03 -0800466 files := android.PathsForModuleSrc(ctx, r.props.Jars)
467
468 androidAllDir := android.PathForModuleInstall(ctx, "android-all")
Colin Cross8eebb132020-01-29 20:07:03 -0800469 for _, from := range files {
470 installedRuntime := ctx.InstallFile(androidAllDir, from.Base(), from)
471 r.runtimes = append(r.runtimes, installedRuntime)
472 }
473
Jeongik Cha816a23a2020-07-08 01:09:23 +0900474 if !ctx.Config().AlwaysUsePrebuiltSdks() && r.props.Lib != nil {
Colin Cross8eebb132020-01-29 20:07:03 -0800475 runtimeFromSourceModule := ctx.GetDirectDepWithTag(String(r.props.Lib), libTag)
Jeongik Cha816a23a2020-07-08 01:09:23 +0900476 if runtimeFromSourceModule == nil {
477 if ctx.Config().AllowMissingDependencies() {
478 ctx.AddMissingDependencies([]string{String(r.props.Lib)})
479 } else {
480 ctx.PropertyErrorf("lib", "missing dependency %q", String(r.props.Lib))
481 }
482 return
483 }
Colin Cross8eebb132020-01-29 20:07:03 -0800484 runtimeFromSourceJar := android.OutputFileForModule(ctx, runtimeFromSourceModule, "")
485
Joseph Murphyc9648412021-07-20 13:58:15 -0700486 // "TREE" name is essential here because it hooks into the "TREE" name in
487 // Robolectric's SdkConfig.java that will always correspond to the NEWEST_SDK
488 // in Robolectric configs.
489 runtimeName := "android-all-current-robolectric-r0.jar"
Colin Cross8eebb132020-01-29 20:07:03 -0800490 installedRuntime := ctx.InstallFile(androidAllDir, runtimeName, runtimeFromSourceJar)
491 r.runtimes = append(r.runtimes, installedRuntime)
492 }
493}
494
Jiyong Park87788b52020-09-01 12:37:45 +0900495func (r *robolectricRuntimes) InstallInTestcases() bool { return true }
496func (r *robolectricRuntimes) InstallForceOS() (*android.OsType, *android.ArchType) {
Colin Cross0c66bc62021-07-20 09:47:41 -0700497 return &r.forceOSType, &r.forceArchType
Jiyong Park87788b52020-09-01 12:37:45 +0900498}