blob: a8e6bfaff1a4566111583931faa58ff8b3b91a65 [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"}
Colin Cross3ec27ec2019-05-01 15:54:05 -070049)
50
Colin Cross0ef08162019-05-01 15:50:51 -070051type robolectricProperties struct {
52 // The name of the android_app module that the tests will run against.
53 Instrumentation_for *string
54
Colin Cross3ec27ec2019-05-01 15:54:05 -070055 // Additional libraries for which coverage data should be generated
56 Coverage_libs []string
57
Colin Cross0ef08162019-05-01 15:50:51 -070058 Test_options struct {
59 // Timeout in seconds when running the tests.
Colin Cross2f9a7c82019-05-30 11:16:26 -070060 Timeout *int64
Colin Crossd2d11772019-05-30 11:17:23 -070061
62 // Number of shards to use when running the tests.
63 Shards *int64
Colin Cross0ef08162019-05-01 15:50:51 -070064 }
Colin Cross2787e8e2021-03-05 11:16:20 -080065
66 // The version number of a robolectric prebuilt to use from prebuilts/misc/common/robolectric
67 // instead of the one built from source in external/robolectric-shadows.
68 Robolectric_prebuilt_version *string
Rex Hoffman54641d22022-08-25 17:29:50 +000069
70 // Use /external/robolectric rather than /external/robolectric-shadows as the version of robolectri
71 // to use. /external/robolectric closely tracks github's master, and will fully replace /external/robolectric-shadows
72 Upstream *bool
Colin Cross0ef08162019-05-01 15:50:51 -070073}
74
75type robolectricTest struct {
76 Library
77
78 robolectricProperties robolectricProperties
Colin Cross8eebb132020-01-29 20:07:03 -080079 testProperties testProperties
Colin Cross0ef08162019-05-01 15:50:51 -070080
Colin Crossd2d11772019-05-30 11:17:23 -070081 libs []string
82 tests []string
Colin Cross3ec27ec2019-05-01 15:54:05 -070083
Colin Cross8eebb132020-01-29 20:07:03 -080084 manifest android.Path
85 resourceApk android.Path
86
87 combinedJar android.WritablePath
88
Colin Cross3ec27ec2019-05-01 15:54:05 -070089 roboSrcJar android.Path
Colin Cross8eebb132020-01-29 20:07:03 -080090
91 testConfig android.Path
92 data android.Paths
Colin Cross0c66bc62021-07-20 09:47:41 -070093
94 forceOSType android.OsType
95 forceArchType android.ArchType
Colin Cross0ef08162019-05-01 15:50:51 -070096}
97
Colin Cross8eebb132020-01-29 20:07:03 -080098func (r *robolectricTest) TestSuites() []string {
99 return r.testProperties.Test_suites
100}
101
102var _ android.TestSuiteModule = (*robolectricTest)(nil)
103
Colin Cross0ef08162019-05-01 15:50:51 -0700104func (r *robolectricTest) DepsMutator(ctx android.BottomUpMutatorContext) {
105 r.Library.DepsMutator(ctx)
106
107 if r.robolectricProperties.Instrumentation_for != nil {
108 ctx.AddVariationDependencies(nil, instrumentationForTag, String(r.robolectricProperties.Instrumentation_for))
109 } else {
110 ctx.PropertyErrorf("instrumentation_for", "missing required instrumented module")
111 }
112
Colin Cross2787e8e2021-03-05 11:16:20 -0800113 if v := String(r.robolectricProperties.Robolectric_prebuilt_version); v != "" {
114 ctx.AddVariationDependencies(nil, libTag, fmt.Sprintf(robolectricPrebuiltLibPattern, v))
115 } else {
Rex Hoffman54641d22022-08-25 17:29:50 +0000116 if proptools.Bool(r.robolectricProperties.Upstream) {
117 ctx.AddVariationDependencies(nil, libTag, robolectricCurrentLib+"_upstream")
118 } else {
119 ctx.AddVariationDependencies(nil, libTag, robolectricCurrentLib)
120 }
Colin Cross2787e8e2021-03-05 11:16:20 -0800121 }
122
Colin Cross0ef08162019-05-01 15:50:51 -0700123 ctx.AddVariationDependencies(nil, libTag, robolectricDefaultLibs...)
Colin Cross3ec27ec2019-05-01 15:54:05 -0700124
125 ctx.AddVariationDependencies(nil, roboCoverageLibsTag, r.robolectricProperties.Coverage_libs...)
Colin Cross8eebb132020-01-29 20:07:03 -0800126
Colin Cross5aa29a72020-09-14 19:54:47 -0700127 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(),
128 roboRuntimesTag, "robolectric-android-all-prebuilts")
Colin Cross0ef08162019-05-01 15:50:51 -0700129}
130
131func (r *robolectricTest) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Colin Cross0c66bc62021-07-20 09:47:41 -0700132 r.forceOSType = ctx.Config().BuildOS
133 r.forceArchType = ctx.Config().BuildArch
134
Cole Faust21680542022-12-07 18:18:37 -0800135 r.testConfig = tradefed.AutoGenTestConfig(ctx, tradefed.AutoGenTestConfigOptions{
136 TestConfigProp: r.testProperties.Test_config,
137 TestConfigTemplateProp: r.testProperties.Test_config_template,
138 TestSuites: r.testProperties.Test_suites,
139 AutoGenConfig: r.testProperties.Auto_gen_config,
140 DeviceTemplate: "${RobolectricTestConfigTemplate}",
141 HostTemplate: "${RobolectricTestConfigTemplate}",
142 })
Colin Cross8eebb132020-01-29 20:07:03 -0800143 r.data = android.PathsForModuleSrc(ctx, r.testProperties.Data)
144
Colin Cross3ec27ec2019-05-01 15:54:05 -0700145 roboTestConfig := android.PathForModuleGen(ctx, "robolectric").
146 Join(ctx, "com/android/tools/test_config.properties")
147
Colin Crossf521efa2023-05-19 09:47:09 -0700148 var ok bool
149 var instrumentedApp *AndroidApp
150
Colin Cross3ec27ec2019-05-01 15:54:05 -0700151 // TODO: this inserts paths to built files into the test, it should really be inserting the contents.
152 instrumented := ctx.GetDirectDepsWithTag(instrumentationForTag)
153
Colin Crossf521efa2023-05-19 09:47:09 -0700154 if len(instrumented) == 1 {
155 instrumentedApp, ok = instrumented[0].(*AndroidApp)
156 if !ok {
157 ctx.PropertyErrorf("instrumentation_for", "dependency must be an android_app")
158 }
159 } else if !ctx.Config().AllowMissingDependencies() {
Colin Cross3ec27ec2019-05-01 15:54:05 -0700160 panic(fmt.Errorf("expected exactly 1 instrumented dependency, got %d", len(instrumented)))
161 }
162
Colin Crossf521efa2023-05-19 09:47:09 -0700163 if instrumentedApp != nil {
164 r.manifest = instrumentedApp.mergedManifestFile
165 r.resourceApk = instrumentedApp.outputFile
166
167 generateRoboTestConfig(ctx, roboTestConfig, instrumentedApp)
168 r.extraResources = android.Paths{roboTestConfig}
Colin Cross3ec27ec2019-05-01 15:54:05 -0700169 }
170
Colin Cross0ef08162019-05-01 15:50:51 -0700171 r.Library.GenerateAndroidBuildActions(ctx)
172
Colin Cross3ec27ec2019-05-01 15:54:05 -0700173 roboSrcJar := android.PathForModuleGen(ctx, "robolectric", ctx.ModuleName()+".srcjar")
Colin Crossf521efa2023-05-19 09:47:09 -0700174
175 if instrumentedApp != nil {
176 r.generateRoboSrcJar(ctx, roboSrcJar, instrumentedApp)
177 r.roboSrcJar = roboSrcJar
178 }
Colin Cross3ec27ec2019-05-01 15:54:05 -0700179
Colin Cross8eebb132020-01-29 20:07:03 -0800180 roboTestConfigJar := android.PathForModuleOut(ctx, "robolectric_samedir", "samedir_config.jar")
181 generateSameDirRoboTestConfigJar(ctx, roboTestConfigJar)
182
183 combinedJarJars := android.Paths{
184 // roboTestConfigJar comes first so that its com/android/tools/test_config.properties
185 // overrides the one from r.extraResources. The r.extraResources one can be removed
186 // once the Make test runner is removed.
187 roboTestConfigJar,
188 r.outputFile,
Colin Crossf521efa2023-05-19 09:47:09 -0700189 }
190
191 if instrumentedApp != nil {
192 combinedJarJars = append(combinedJarJars, instrumentedApp.implementationAndResourcesJar)
Colin Cross0ef08162019-05-01 15:50:51 -0700193 }
Colin Crossd2d11772019-05-30 11:17:23 -0700194
Liz Kammeref28a4c2022-09-23 16:50:56 -0400195 handleLibDeps := func(dep android.Module) {
Colin Crossdcf71b22021-02-01 13:59:03 -0800196 m := ctx.OtherModuleProvider(dep, JavaInfoProvider).(JavaInfo)
197 r.libs = append(r.libs, ctx.OtherModuleName(dep))
198 if !android.InList(ctx.OtherModuleName(dep), config.FrameworkLibraries) {
199 combinedJarJars = append(combinedJarJars, m.ImplementationAndResourcesJars...)
Colin Cross8eebb132020-01-29 20:07:03 -0800200 }
201 }
202
Liz Kammeref28a4c2022-09-23 16:50:56 -0400203 for _, dep := range ctx.GetDirectDepsWithTag(libTag) {
204 handleLibDeps(dep)
205 }
206 for _, dep := range ctx.GetDirectDepsWithTag(sdkLibTag) {
207 handleLibDeps(dep)
208 }
209
Colin Cross8eebb132020-01-29 20:07:03 -0800210 r.combinedJar = android.PathForModuleOut(ctx, "robolectric_combined", r.outputFile.Base())
211 TransformJarsToJar(ctx, r.combinedJar, "combine jars", combinedJarJars, android.OptionalPath{},
212 false, nil, nil)
213
Colin Crossd2d11772019-05-30 11:17:23 -0700214 // TODO: this could all be removed if tradefed was used as the test runner, it will find everything
215 // annotated as a test and run it.
Chaohui Wangdcbe33c2022-10-11 11:13:30 +0800216 for _, src := range r.uniqueSrcFiles {
Colin Crossd2d11772019-05-30 11:17:23 -0700217 s := src.Rel()
Chaohui Wangdcbe33c2022-10-11 11:13:30 +0800218 if !strings.HasSuffix(s, "Test.java") && !strings.HasSuffix(s, "Test.kt") {
Colin Crossd2d11772019-05-30 11:17:23 -0700219 continue
220 } else if strings.HasSuffix(s, "/BaseRobolectricTest.java") {
221 continue
Ulya Trafimovich497a0932021-07-14 16:35:33 +0100222 } else {
Colin Crossd2d11772019-05-30 11:17:23 -0700223 s = strings.TrimPrefix(s, "src/")
224 }
225 r.tests = append(r.tests, s)
226 }
Colin Cross8eebb132020-01-29 20:07:03 -0800227
Colin Crossf521efa2023-05-19 09:47:09 -0700228 installPath := android.PathForModuleInstall(ctx, r.BaseModuleName())
229 var installDeps android.Paths
230
231 if r.manifest != nil {
232 r.data = append(r.data, r.manifest)
233 installedManifest := ctx.InstallFile(installPath, ctx.ModuleName()+"-AndroidManifest.xml", r.manifest)
234 installDeps = append(installDeps, installedManifest)
235 }
236
237 if r.resourceApk != nil {
238 r.data = append(r.data, r.resourceApk)
239 installedResourceApk := ctx.InstallFile(installPath, ctx.ModuleName()+".apk", r.resourceApk)
240 installDeps = append(installDeps, installedResourceApk)
241 }
Colin Cross8eebb132020-01-29 20:07:03 -0800242
243 runtimes := ctx.GetDirectDepWithTag("robolectric-android-all-prebuilts", roboRuntimesTag)
Colin Cross8eebb132020-01-29 20:07:03 -0800244 for _, runtime := range runtimes.(*robolectricRuntimes).runtimes {
245 installDeps = append(installDeps, runtime)
246 }
Colin Crossf521efa2023-05-19 09:47:09 -0700247
248 installedConfig := ctx.InstallFile(installPath, ctx.ModuleName()+".config", r.testConfig)
249 installDeps = append(installDeps, installedConfig)
Colin Cross8eebb132020-01-29 20:07:03 -0800250
251 for _, data := range android.PathsForModuleSrc(ctx, r.testProperties.Data) {
252 installedData := ctx.InstallFile(installPath, data.Rel(), data)
253 installDeps = append(installDeps, installedData)
254 }
255
Colin Cross6301c3c2021-09-28 17:40:21 -0700256 r.installFile = ctx.InstallFile(installPath, ctx.ModuleName()+".jar", r.combinedJar, installDeps...)
Aditya Choudhary9b593522023-10-06 19:54:58 +0000257 ctx.SetProvider(testing.TestModuleProviderKey, testing.TestModuleProviderData{})
Colin Crossd2d11772019-05-30 11:17:23 -0700258}
259
Colin Cross8eebb132020-01-29 20:07:03 -0800260func generateRoboTestConfig(ctx android.ModuleContext, outputFile android.WritablePath,
261 instrumentedApp *AndroidApp) {
Colin Crossf1a035e2020-11-16 17:32:30 -0800262 rule := android.NewRuleBuilder(pctx, ctx)
Colin Cross8eebb132020-01-29 20:07:03 -0800263
Colin Cross3ec27ec2019-05-01 15:54:05 -0700264 manifest := instrumentedApp.mergedManifestFile
265 resourceApk := instrumentedApp.outputFile
266
Colin Cross3ec27ec2019-05-01 15:54:05 -0700267 rule.Command().Text("rm -f").Output(outputFile)
268 rule.Command().
269 Textf(`echo "android_merged_manifest=%s" >>`, manifest.String()).Output(outputFile).Text("&&").
270 Textf(`echo "android_resource_apk=%s" >>`, resourceApk.String()).Output(outputFile).
271 // Make it depend on the files to which it points so the test file's timestamp is updated whenever the
272 // contents change
273 Implicit(manifest).
274 Implicit(resourceApk)
275
Colin Crossf1a035e2020-11-16 17:32:30 -0800276 rule.Build("generate_test_config", "generate test_config.properties")
Colin Cross3ec27ec2019-05-01 15:54:05 -0700277}
278
Colin Cross8eebb132020-01-29 20:07:03 -0800279func generateSameDirRoboTestConfigJar(ctx android.ModuleContext, outputFile android.ModuleOutPath) {
Colin Crossf1a035e2020-11-16 17:32:30 -0800280 rule := android.NewRuleBuilder(pctx, ctx)
Colin Cross8eebb132020-01-29 20:07:03 -0800281
282 outputDir := outputFile.InSameDir(ctx)
283 configFile := outputDir.Join(ctx, "com/android/tools/test_config.properties")
284 rule.Temporary(configFile)
285 rule.Command().Text("rm -f").Output(outputFile).Output(configFile)
286 rule.Command().Textf("mkdir -p $(dirname %s)", configFile.String())
287 rule.Command().
288 Text("(").
289 Textf(`echo "android_merged_manifest=%s-AndroidManifest.xml" &&`, ctx.ModuleName()).
290 Textf(`echo "android_resource_apk=%s.apk"`, ctx.ModuleName()).
291 Text(") >>").Output(configFile)
292 rule.Command().
Colin Crossf1a035e2020-11-16 17:32:30 -0800293 BuiltTool("soong_zip").
Colin Cross8eebb132020-01-29 20:07:03 -0800294 FlagWithArg("-C ", outputDir.String()).
295 FlagWithInput("-f ", configFile).
296 FlagWithOutput("-o ", outputFile)
297
Colin Crossf1a035e2020-11-16 17:32:30 -0800298 rule.Build("generate_test_config_samedir", "generate test_config.properties")
Colin Cross8eebb132020-01-29 20:07:03 -0800299}
300
Colin Cross3ec27ec2019-05-01 15:54:05 -0700301func (r *robolectricTest) generateRoboSrcJar(ctx android.ModuleContext, outputFile android.WritablePath,
302 instrumentedApp *AndroidApp) {
303
Colin Cross48016d52023-06-27 09:45:26 -0700304 srcJarArgs := android.CopyOf(instrumentedApp.srcJarArgs)
Colin Cross3ec27ec2019-05-01 15:54:05 -0700305 srcJarDeps := append(android.Paths(nil), instrumentedApp.srcJarDeps...)
306
307 for _, m := range ctx.GetDirectDepsWithTag(roboCoverageLibsTag) {
Colin Crossdcf71b22021-02-01 13:59:03 -0800308 if ctx.OtherModuleHasProvider(m, JavaInfoProvider) {
309 dep := ctx.OtherModuleProvider(m, JavaInfoProvider).(JavaInfo)
310 srcJarArgs = append(srcJarArgs, dep.SrcJarArgs...)
311 srcJarDeps = append(srcJarDeps, dep.SrcJarDeps...)
Colin Cross3ec27ec2019-05-01 15:54:05 -0700312 }
313 }
314
315 TransformResourcesToJar(ctx, outputFile, srcJarArgs, srcJarDeps)
316}
317
Jiyong Park0b0e1b92019-12-03 13:24:29 +0900318func (r *robolectricTest) AndroidMkEntries() []android.AndroidMkEntries {
319 entriesList := r.Library.AndroidMkEntries()
320 entries := &entriesList[0]
Colin Cross6301c3c2021-09-28 17:40:21 -0700321 entries.ExtraEntries = append(entries.ExtraEntries,
322 func(ctx android.AndroidMkExtraEntriesContext, entries *android.AndroidMkEntries) {
323 entries.SetBool("LOCAL_UNINSTALLABLE_MODULE", true)
nelsonli3f97ea22022-11-21 21:37:56 +0800324 entries.AddStrings("LOCAL_COMPATIBILITY_SUITE", "robolectric-tests")
Yike0fcf90a2023-02-14 12:17:32 +0800325 if r.testConfig != nil {
326 entries.SetPath("LOCAL_FULL_TEST_CONFIG", r.testConfig)
327 }
Colin Cross6301c3c2021-09-28 17:40:21 -0700328 })
Colin Cross0ef08162019-05-01 15:50:51 -0700329
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700330 entries.ExtraFooters = []android.AndroidMkExtraFootersFunc{
Jaewoong Jung02b11a62020-12-07 10:23:54 -0800331 func(w io.Writer, name, prefix, moduleDir string) {
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700332 if s := r.robolectricProperties.Test_options.Shards; s != nil && *s > 1 {
Colin Cross0a2f7192019-09-23 14:33:09 -0700333 numShards := int(*s)
334 shardSize := (len(r.tests) + numShards - 1) / numShards
335 shards := android.ShardStrings(r.tests, shardSize)
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700336 for i, shard := range shards {
337 r.writeTestRunner(w, name, "Run"+name+strconv.Itoa(i), shard)
338 }
Colin Cross0ef08162019-05-01 15:50:51 -0700339
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700340 // TODO: add rules to dist the outputs of the individual tests, or combine them together?
341 fmt.Fprintln(w, "")
342 fmt.Fprintln(w, ".PHONY:", "Run"+name)
343 fmt.Fprintln(w, "Run"+name, ": \\")
344 for i := range shards {
345 fmt.Fprintln(w, " ", "Run"+name+strconv.Itoa(i), "\\")
346 }
347 fmt.Fprintln(w, "")
348 } else {
349 r.writeTestRunner(w, name, "Run"+name, r.tests)
Colin Crossd2d11772019-05-30 11:17:23 -0700350 }
Jaewoong Jungb0c127c2019-08-29 14:56:03 -0700351 },
Colin Cross0ef08162019-05-01 15:50:51 -0700352 }
353
Jiyong Park0b0e1b92019-12-03 13:24:29 +0900354 return entriesList
Colin Cross0ef08162019-05-01 15:50:51 -0700355}
356
Colin Crossd2d11772019-05-30 11:17:23 -0700357func (r *robolectricTest) writeTestRunner(w io.Writer, module, name string, tests []string) {
358 fmt.Fprintln(w, "")
Sasha Smundak5c4729d2022-12-01 10:49:23 -0800359 fmt.Fprintln(w, "include $(CLEAR_VARS)", " # java.robolectricTest")
Colin Crossd2d11772019-05-30 11:17:23 -0700360 fmt.Fprintln(w, "LOCAL_MODULE :=", name)
Sasha Smundakdcb61292022-12-08 10:41:33 -0800361 android.AndroidMkEmitAssignList(w, "LOCAL_JAVA_LIBRARIES", []string{module}, r.libs)
Colin Crossd2d11772019-05-30 11:17:23 -0700362 fmt.Fprintln(w, "LOCAL_TEST_PACKAGE :=", String(r.robolectricProperties.Instrumentation_for))
Colin Crossf521efa2023-05-19 09:47:09 -0700363 if r.roboSrcJar != nil {
364 fmt.Fprintln(w, "LOCAL_INSTRUMENT_SRCJARS :=", r.roboSrcJar.String())
365 }
Sasha Smundakdcb61292022-12-08 10:41:33 -0800366 android.AndroidMkEmitAssignList(w, "LOCAL_ROBOTEST_FILES", tests)
Colin Crossd2d11772019-05-30 11:17:23 -0700367 if t := r.robolectricProperties.Test_options.Timeout; t != nil {
368 fmt.Fprintln(w, "LOCAL_ROBOTEST_TIMEOUT :=", *t)
369 }
Colin Cross2787e8e2021-03-05 11:16:20 -0800370 if v := String(r.robolectricProperties.Robolectric_prebuilt_version); v != "" {
371 fmt.Fprintf(w, "-include prebuilts/misc/common/robolectric/%s/run_robotests.mk\n", v)
372 } else {
373 fmt.Fprintln(w, "-include external/robolectric-shadows/run_robotests.mk")
374 }
Colin Crossd2d11772019-05-30 11:17:23 -0700375}
376
Colin Cross0ef08162019-05-01 15:50:51 -0700377// An android_robolectric_test module compiles tests against the Robolectric framework that can run on the local host
378// instead of on a device. It also generates a rule with the name of the module prefixed with "Run" that can be
379// 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 -0700380//
381// The test runner considers any file listed in srcs whose name ends with Test.java to be a test class, unless
382// it is named BaseRobolectricTest.java. The path to the each source file must exactly match the package
383// name, or match the package name when the prefix "src/" is removed.
Colin Cross0ef08162019-05-01 15:50:51 -0700384func RobolectricTestFactory() android.Module {
385 module := &robolectricTest{}
386
Colin Crossce6734e2020-06-15 16:09:53 -0700387 module.addHostProperties()
Colin Cross0ef08162019-05-01 15:50:51 -0700388 module.AddProperties(
Colin Crosse323f3c2019-09-17 15:34:09 -0700389 &module.Module.deviceProperties,
Colin Cross8eebb132020-01-29 20:07:03 -0800390 &module.robolectricProperties,
391 &module.testProperties)
Colin Cross0ef08162019-05-01 15:50:51 -0700392
393 module.Module.dexpreopter.isTest = true
Cole Faustd57e8b22022-08-11 11:59:04 -0700394 module.Module.linter.properties.Lint.Test = proptools.BoolPtr(true)
Colin Cross0ef08162019-05-01 15:50:51 -0700395
Colin Cross8eebb132020-01-29 20:07:03 -0800396 module.testProperties.Test_suites = []string{"robolectric-tests"}
397
Colin Cross0ef08162019-05-01 15:50:51 -0700398 InitJavaModule(module, android.DeviceSupported)
399 return module
400}
Colin Cross8eebb132020-01-29 20:07:03 -0800401
Jiyong Park87788b52020-09-01 12:37:45 +0900402func (r *robolectricTest) InstallInTestcases() bool { return true }
403func (r *robolectricTest) InstallForceOS() (*android.OsType, *android.ArchType) {
Colin Cross0c66bc62021-07-20 09:47:41 -0700404 return &r.forceOSType, &r.forceArchType
Jiyong Park87788b52020-09-01 12:37:45 +0900405}
Colin Cross8eebb132020-01-29 20:07:03 -0800406
407func robolectricRuntimesFactory() android.Module {
408 module := &robolectricRuntimes{}
409 module.AddProperties(&module.props)
Colin Cross5aa29a72020-09-14 19:54:47 -0700410 android.InitAndroidArchModule(module, android.HostSupportedNoCross, android.MultilibCommon)
Colin Cross8eebb132020-01-29 20:07:03 -0800411 return module
412}
413
414type robolectricRuntimesProperties struct {
415 Jars []string `android:"path"`
416 Lib *string
417}
418
419type robolectricRuntimes struct {
420 android.ModuleBase
421
422 props robolectricRuntimesProperties
423
424 runtimes []android.InstallPath
Colin Cross0c66bc62021-07-20 09:47:41 -0700425
426 forceOSType android.OsType
427 forceArchType android.ArchType
Colin Cross8eebb132020-01-29 20:07:03 -0800428}
429
430func (r *robolectricRuntimes) TestSuites() []string {
431 return []string{"robolectric-tests"}
432}
433
434var _ android.TestSuiteModule = (*robolectricRuntimes)(nil)
435
436func (r *robolectricRuntimes) DepsMutator(ctx android.BottomUpMutatorContext) {
Jeongik Cha816a23a2020-07-08 01:09:23 +0900437 if !ctx.Config().AlwaysUsePrebuiltSdks() && r.props.Lib != nil {
Colin Cross8eebb132020-01-29 20:07:03 -0800438 ctx.AddVariationDependencies(nil, libTag, String(r.props.Lib))
439 }
440}
441
442func (r *robolectricRuntimes) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Colin Cross5aa29a72020-09-14 19:54:47 -0700443 if ctx.Target().Os != ctx.Config().BuildOSCommonTarget.Os {
444 return
445 }
446
Colin Cross0c66bc62021-07-20 09:47:41 -0700447 r.forceOSType = ctx.Config().BuildOS
448 r.forceArchType = ctx.Config().BuildArch
449
Colin Cross8eebb132020-01-29 20:07:03 -0800450 files := android.PathsForModuleSrc(ctx, r.props.Jars)
451
452 androidAllDir := android.PathForModuleInstall(ctx, "android-all")
Colin Cross8eebb132020-01-29 20:07:03 -0800453 for _, from := range files {
454 installedRuntime := ctx.InstallFile(androidAllDir, from.Base(), from)
455 r.runtimes = append(r.runtimes, installedRuntime)
456 }
457
Jeongik Cha816a23a2020-07-08 01:09:23 +0900458 if !ctx.Config().AlwaysUsePrebuiltSdks() && r.props.Lib != nil {
Colin Cross8eebb132020-01-29 20:07:03 -0800459 runtimeFromSourceModule := ctx.GetDirectDepWithTag(String(r.props.Lib), libTag)
Jeongik Cha816a23a2020-07-08 01:09:23 +0900460 if runtimeFromSourceModule == nil {
461 if ctx.Config().AllowMissingDependencies() {
462 ctx.AddMissingDependencies([]string{String(r.props.Lib)})
463 } else {
464 ctx.PropertyErrorf("lib", "missing dependency %q", String(r.props.Lib))
465 }
466 return
467 }
Colin Cross8eebb132020-01-29 20:07:03 -0800468 runtimeFromSourceJar := android.OutputFileForModule(ctx, runtimeFromSourceModule, "")
469
Joseph Murphyc9648412021-07-20 13:58:15 -0700470 // "TREE" name is essential here because it hooks into the "TREE" name in
471 // Robolectric's SdkConfig.java that will always correspond to the NEWEST_SDK
472 // in Robolectric configs.
473 runtimeName := "android-all-current-robolectric-r0.jar"
Colin Cross8eebb132020-01-29 20:07:03 -0800474 installedRuntime := ctx.InstallFile(androidAllDir, runtimeName, runtimeFromSourceJar)
475 r.runtimes = append(r.runtimes, installedRuntime)
476 }
477}
478
Jiyong Park87788b52020-09-01 12:37:45 +0900479func (r *robolectricRuntimes) InstallInTestcases() bool { return true }
480func (r *robolectricRuntimes) InstallForceOS() (*android.OsType, *android.ArchType) {
Colin Cross0c66bc62021-07-20 09:47:41 -0700481 return &r.forceOSType, &r.forceArchType
Jiyong Park87788b52020-09-01 12:37:45 +0900482}