blob: 26f4b717660569b31655dfad08ac7c005623f845 [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"
Priyanka Advani (xWF)72853672024-09-04 20:15:58 +000019 "io"
20 "strconv"
21 "strings"
Colin Cross0ef08162019-05-01 15:50:51 -070022
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() {
Jamie Garside56f2b702024-07-09 12:00:12 +010032 RegisterRobolectricBuildComponents(android.InitRegistrationContext)
33}
34
35func RegisterRobolectricBuildComponents(ctx android.RegistrationContext) {
36 ctx.RegisterModuleType("android_robolectric_test", RobolectricTestFactory)
37 ctx.RegisterModuleType("android_robolectric_runtimes", robolectricRuntimesFactory)
Colin Cross0ef08162019-05-01 15:50:51 -070038}
39
40var robolectricDefaultLibs = []string{
Colin Cross0ef08162019-05-01 15:50:51 -070041 "mockito-robolectric-prebuilt",
Krzysztof KosiƄski5a554392023-10-07 19:59:58 +000042 "truth",
Colin Cross8eebb132020-01-29 20:07:03 -080043 // TODO(ccross): this is not needed at link time
44 "junitxml",
Colin Cross0ef08162019-05-01 15:50:51 -070045}
46
Colin Cross2787e8e2021-03-05 11:16:20 -080047const robolectricCurrentLib = "Robolectric_all-target"
48const robolectricPrebuiltLibPattern = "platform-robolectric-%s-prebuilt"
49
Colin Cross3ec27ec2019-05-01 15:54:05 -070050var (
Colin Cross8eebb132020-01-29 20:07:03 -080051 roboCoverageLibsTag = dependencyTag{name: "roboCoverageLibs"}
52 roboRuntimesTag = dependencyTag{name: "roboRuntimes"}
Kevin Liucab89b52024-04-12 21:52:07 +000053 roboRuntimeOnlyTag = dependencyTag{name: "roboRuntimeOnlyTag"}
Colin Cross3ec27ec2019-05-01 15:54:05 -070054)
55
Colin Cross0ef08162019-05-01 15:50:51 -070056type robolectricProperties struct {
57 // The name of the android_app module that the tests will run against.
58 Instrumentation_for *string
59
Colin Cross3ec27ec2019-05-01 15:54:05 -070060 // Additional libraries for which coverage data should be generated
61 Coverage_libs []string
62
Colin Cross0ef08162019-05-01 15:50:51 -070063 Test_options struct {
64 // Timeout in seconds when running the tests.
Colin Cross2f9a7c82019-05-30 11:16:26 -070065 Timeout *int64
Colin Crossd2d11772019-05-30 11:17:23 -070066
67 // Number of shards to use when running the tests.
68 Shards *int64
Colin Cross0ef08162019-05-01 15:50:51 -070069 }
Colin Cross2787e8e2021-03-05 11:16:20 -080070
71 // The version number of a robolectric prebuilt to use from prebuilts/misc/common/robolectric
72 // instead of the one built from source in external/robolectric-shadows.
73 Robolectric_prebuilt_version *string
Rex Hoffman54641d22022-08-25 17:29:50 +000074
Yuichiro Hanadae42ac1c2023-12-08 09:24:40 +090075 // Use /external/robolectric rather than /external/robolectric-shadows as the version of robolectric
Rex Hoffman54641d22022-08-25 17:29:50 +000076 // to use. /external/robolectric closely tracks github's master, and will fully replace /external/robolectric-shadows
77 Upstream *bool
Kevin Liucab89b52024-04-12 21:52:07 +000078
79 // Use strict mode to limit access of Robolectric API directly. See go/roboStrictMode
80 Strict_mode *bool
Jamie Garside56f2b702024-07-09 12:00:12 +010081
82 Jni_libs []string
Colin Cross0ef08162019-05-01 15:50:51 -070083}
84
85type robolectricTest struct {
86 Library
87
88 robolectricProperties robolectricProperties
Colin Cross8eebb132020-01-29 20:07:03 -080089 testProperties testProperties
Colin Cross0ef08162019-05-01 15:50:51 -070090
Priyanka Advani (xWF)72853672024-09-04 20:15:58 +000091 libs []string
92 tests []string
93
94 manifest android.Path
95 resourceApk android.Path
96
97 combinedJar android.WritablePath
98
99 roboSrcJar android.Path
100
Colin Cross8eebb132020-01-29 20:07:03 -0800101 testConfig android.Path
102 data android.Paths
Colin Cross0c66bc62021-07-20 09:47:41 -0700103
104 forceOSType android.OsType
105 forceArchType android.ArchType
Colin Cross0ef08162019-05-01 15:50:51 -0700106}
107
Colin Cross8eebb132020-01-29 20:07:03 -0800108func (r *robolectricTest) TestSuites() []string {
109 return r.testProperties.Test_suites
110}
111
112var _ android.TestSuiteModule = (*robolectricTest)(nil)
113
Colin Cross0ef08162019-05-01 15:50:51 -0700114func (r *robolectricTest) DepsMutator(ctx android.BottomUpMutatorContext) {
115 r.Library.DepsMutator(ctx)
116
117 if r.robolectricProperties.Instrumentation_for != nil {
118 ctx.AddVariationDependencies(nil, instrumentationForTag, String(r.robolectricProperties.Instrumentation_for))
119 } else {
120 ctx.PropertyErrorf("instrumentation_for", "missing required instrumented module")
121 }
122
Colin Cross2787e8e2021-03-05 11:16:20 -0800123 if v := String(r.robolectricProperties.Robolectric_prebuilt_version); v != "" {
Priyanka Advani (xWF)72853672024-09-04 20:15:58 +0000124 ctx.AddVariationDependencies(nil, libTag, fmt.Sprintf(robolectricPrebuiltLibPattern, v))
Kevin Liu51349b82024-06-28 15:02:12 +0000125 } else if !proptools.BoolDefault(r.robolectricProperties.Strict_mode, true) {
Rex Hoffman54641d22022-08-25 17:29:50 +0000126 if proptools.Bool(r.robolectricProperties.Upstream) {
Priyanka Advani (xWF)72853672024-09-04 20:15:58 +0000127 ctx.AddVariationDependencies(nil, libTag, robolectricCurrentLib+"_upstream")
Rex Hoffman54641d22022-08-25 17:29:50 +0000128 } else {
Priyanka Advani (xWF)72853672024-09-04 20:15:58 +0000129 ctx.AddVariationDependencies(nil, libTag, robolectricCurrentLib)
Rex Hoffman54641d22022-08-25 17:29:50 +0000130 }
Colin Cross2787e8e2021-03-05 11:16:20 -0800131 }
132
Kevin Liu51349b82024-06-28 15:02:12 +0000133 if proptools.BoolDefault(r.robolectricProperties.Strict_mode, true) {
Kevin Liucab89b52024-04-12 21:52:07 +0000134 ctx.AddVariationDependencies(nil, roboRuntimeOnlyTag, robolectricCurrentLib+"_upstream")
Kevin Liu51349b82024-06-28 15:02:12 +0000135 } else {
136 // opting out from strict mode, robolectric_non_strict_mode_permission lib should be added
Priyanka Advani (xWF)72853672024-09-04 20:15:58 +0000137 ctx.AddVariationDependencies(nil, libTag, "robolectric_non_strict_mode_permission")
Kevin Liucab89b52024-04-12 21:52:07 +0000138 }
139
Priyanka Advani (xWF)72853672024-09-04 20:15:58 +0000140 ctx.AddVariationDependencies(nil, libTag, robolectricDefaultLibs...)
Colin Cross3ec27ec2019-05-01 15:54:05 -0700141
142 ctx.AddVariationDependencies(nil, roboCoverageLibsTag, r.robolectricProperties.Coverage_libs...)
Colin Cross8eebb132020-01-29 20:07:03 -0800143
Colin Cross5aa29a72020-09-14 19:54:47 -0700144 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(),
145 roboRuntimesTag, "robolectric-android-all-prebuilts")
Jamie Garside56f2b702024-07-09 12:00:12 +0100146
147 for _, lib := range r.robolectricProperties.Jni_libs {
148 ctx.AddVariationDependencies(ctx.Config().BuildOSTarget.Variations(), jniLibTag, lib)
149 }
Colin Cross0ef08162019-05-01 15:50:51 -0700150}
151
152func (r *robolectricTest) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Colin Cross0c66bc62021-07-20 09:47:41 -0700153 r.forceOSType = ctx.Config().BuildOS
154 r.forceArchType = ctx.Config().BuildArch
155
Cole Faust21680542022-12-07 18:18:37 -0800156 r.testConfig = tradefed.AutoGenTestConfig(ctx, tradefed.AutoGenTestConfigOptions{
157 TestConfigProp: r.testProperties.Test_config,
158 TestConfigTemplateProp: r.testProperties.Test_config_template,
159 TestSuites: r.testProperties.Test_suites,
160 AutoGenConfig: r.testProperties.Auto_gen_config,
161 DeviceTemplate: "${RobolectricTestConfigTemplate}",
162 HostTemplate: "${RobolectricTestConfigTemplate}",
163 })
Colin Cross8eebb132020-01-29 20:07:03 -0800164 r.data = android.PathsForModuleSrc(ctx, r.testProperties.Data)
165
Priyanka Advani (xWF)72853672024-09-04 20:15:58 +0000166 roboTestConfig := android.PathForModuleGen(ctx, "robolectric").
167 Join(ctx, "com/android/tools/test_config.properties")
168
Colin Crossf521efa2023-05-19 09:47:09 -0700169 var ok bool
170 var instrumentedApp *AndroidApp
171
Colin Cross3ec27ec2019-05-01 15:54:05 -0700172 // TODO: this inserts paths to built files into the test, it should really be inserting the contents.
173 instrumented := ctx.GetDirectDepsWithTag(instrumentationForTag)
174
Colin Crossf521efa2023-05-19 09:47:09 -0700175 if len(instrumented) == 1 {
176 instrumentedApp, ok = instrumented[0].(*AndroidApp)
177 if !ok {
178 ctx.PropertyErrorf("instrumentation_for", "dependency must be an android_app")
179 }
180 } else if !ctx.Config().AllowMissingDependencies() {
Colin Cross3ec27ec2019-05-01 15:54:05 -0700181 panic(fmt.Errorf("expected exactly 1 instrumented dependency, got %d", len(instrumented)))
182 }
183
Colin Crossf521efa2023-05-19 09:47:09 -0700184 if instrumentedApp != nil {
Priyanka Advani (xWF)72853672024-09-04 20:15:58 +0000185 r.manifest = instrumentedApp.mergedManifestFile
186 r.resourceApk = instrumentedApp.outputFile
187
188 generateRoboTestConfig(ctx, roboTestConfig, instrumentedApp)
189 r.extraResources = android.Paths{roboTestConfig}
190 }
191
192 r.Library.GenerateAndroidBuildActions(ctx)
193
194 roboSrcJar := android.PathForModuleGen(ctx, "robolectric", ctx.ModuleName()+".srcjar")
195
196 if instrumentedApp != nil {
197 r.generateRoboSrcJar(ctx, roboSrcJar, instrumentedApp)
198 r.roboSrcJar = roboSrcJar
Colin Crossf521efa2023-05-19 09:47:09 -0700199 }
Colin Cross3ec27ec2019-05-01 15:54:05 -0700200
Colin Cross8eebb132020-01-29 20:07:03 -0800201 roboTestConfigJar := android.PathForModuleOut(ctx, "robolectric_samedir", "samedir_config.jar")
202 generateSameDirRoboTestConfigJar(ctx, roboTestConfigJar)
203
Priyanka Advani (xWF)72853672024-09-04 20:15:58 +0000204 combinedJarJars := android.Paths{
205 // roboTestConfigJar comes first so that its com/android/tools/test_config.properties
206 // overrides the one from r.extraResources. The r.extraResources one can be removed
207 // once the Make test runner is removed.
208 roboTestConfigJar,
209 r.outputFile,
Colin Cross0ef08162019-05-01 15:50:51 -0700210 }
Colin Crossd2d11772019-05-30 11:17:23 -0700211
Priyanka Advani (xWF)72853672024-09-04 20:15:58 +0000212 if instrumentedApp != nil {
213 combinedJarJars = append(combinedJarJars, instrumentedApp.implementationAndResourcesJar)
214 }
215
216 handleLibDeps := func(dep android.Module, runtimeOnly bool) {
217 if !runtimeOnly {
218 r.libs = append(r.libs, ctx.OtherModuleName(dep))
219 }
Colin Crossdcf71b22021-02-01 13:59:03 -0800220 if !android.InList(ctx.OtherModuleName(dep), config.FrameworkLibraries) {
Colin Cross7727c7f2024-07-18 15:36:32 -0700221 if m, ok := android.OtherModuleProvider(ctx, dep, JavaInfoProvider); ok {
Priyanka Advani (xWF)72853672024-09-04 20:15:58 +0000222 combinedJarJars = append(combinedJarJars, m.ImplementationAndResourcesJars...)
Colin Cross7727c7f2024-07-18 15:36:32 -0700223 }
Colin Cross8eebb132020-01-29 20:07:03 -0800224 }
225 }
226
Liz Kammeref28a4c2022-09-23 16:50:56 -0400227 for _, dep := range ctx.GetDirectDepsWithTag(libTag) {
Priyanka Advani (xWF)72853672024-09-04 20:15:58 +0000228 handleLibDeps(dep, false)
Liz Kammeref28a4c2022-09-23 16:50:56 -0400229 }
230 for _, dep := range ctx.GetDirectDepsWithTag(sdkLibTag) {
Priyanka Advani (xWF)72853672024-09-04 20:15:58 +0000231 handleLibDeps(dep, false)
Kevin Liucab89b52024-04-12 21:52:07 +0000232 }
233 // handle the runtimeOnly tag for strict_mode
234 for _, dep := range ctx.GetDirectDepsWithTag(roboRuntimeOnlyTag) {
Priyanka Advani (xWF)72853672024-09-04 20:15:58 +0000235 handleLibDeps(dep, true)
Liz Kammeref28a4c2022-09-23 16:50:56 -0400236 }
237
Priyanka Advani (xWF)72853672024-09-04 20:15:58 +0000238 r.combinedJar = android.PathForModuleOut(ctx, "robolectric_combined", r.outputFile.Base())
239 TransformJarsToJar(ctx, r.combinedJar, "combine jars", combinedJarJars, android.OptionalPath{},
240 false, nil, nil)
241
242 // TODO: this could all be removed if tradefed was used as the test runner, it will find everything
243 // annotated as a test and run it.
244 for _, src := range r.uniqueSrcFiles {
245 s := src.Rel()
246 if !strings.HasSuffix(s, "Test.java") && !strings.HasSuffix(s, "Test.kt") {
247 continue
248 } else if strings.HasSuffix(s, "/BaseRobolectricTest.java") {
249 continue
250 } else {
251 s = strings.TrimPrefix(s, "src/")
252 }
253 r.tests = append(r.tests, s)
254 }
Colin Cross8eebb132020-01-29 20:07:03 -0800255
Colin Crossf521efa2023-05-19 09:47:09 -0700256 installPath := android.PathForModuleInstall(ctx, r.BaseModuleName())
Colin Cross09ad3a62023-11-15 12:29:33 -0800257 var installDeps android.InstallPaths
Colin Crossf521efa2023-05-19 09:47:09 -0700258
Priyanka Advani (xWF)72853672024-09-04 20:15:58 +0000259 if r.manifest != nil {
260 r.data = append(r.data, r.manifest)
261 installedManifest := ctx.InstallFile(installPath, ctx.ModuleName()+"-AndroidManifest.xml", r.manifest)
Colin Crossf521efa2023-05-19 09:47:09 -0700262 installDeps = append(installDeps, installedManifest)
263 }
264
Priyanka Advani (xWF)72853672024-09-04 20:15:58 +0000265 if r.resourceApk != nil {
266 r.data = append(r.data, r.resourceApk)
267 installedResourceApk := ctx.InstallFile(installPath, ctx.ModuleName()+".apk", r.resourceApk)
Colin Crossf521efa2023-05-19 09:47:09 -0700268 installDeps = append(installDeps, installedResourceApk)
269 }
Colin Cross8eebb132020-01-29 20:07:03 -0800270
271 runtimes := ctx.GetDirectDepWithTag("robolectric-android-all-prebuilts", roboRuntimesTag)
Colin Cross8eebb132020-01-29 20:07:03 -0800272 for _, runtime := range runtimes.(*robolectricRuntimes).runtimes {
273 installDeps = append(installDeps, runtime)
274 }
Colin Crossf521efa2023-05-19 09:47:09 -0700275
276 installedConfig := ctx.InstallFile(installPath, ctx.ModuleName()+".config", r.testConfig)
277 installDeps = append(installDeps, installedConfig)
Colin Cross8eebb132020-01-29 20:07:03 -0800278
279 for _, data := range android.PathsForModuleSrc(ctx, r.testProperties.Data) {
280 installedData := ctx.InstallFile(installPath, data.Rel(), data)
281 installDeps = append(installDeps, installedData)
282 }
283
Jamie Garside56f2b702024-07-09 12:00:12 +0100284 soInstallPath := installPath.Join(ctx, getLibPath(r.forceArchType))
285 for _, jniLib := range collectTransitiveJniDeps(ctx) {
286 installJni := ctx.InstallFile(soInstallPath, jniLib.path.Base(), jniLib.path)
287 installDeps = append(installDeps, installJni)
288 }
289
Priyanka Advani (xWF)72853672024-09-04 20:15:58 +0000290 r.installFile = ctx.InstallFile(installPath, ctx.ModuleName()+".jar", r.combinedJar, installDeps...)
Colin Cross40213022023-12-13 15:19:49 -0800291 android.SetProvider(ctx, testing.TestModuleProviderKey, testing.TestModuleProviderData{})
Colin Crossd2d11772019-05-30 11:17:23 -0700292}
293
Priyanka Advani (xWF)72853672024-09-04 20:15:58 +0000294func generateRoboTestConfig(ctx android.ModuleContext, outputFile android.WritablePath,
295 instrumentedApp *AndroidApp) {
296 rule := android.NewRuleBuilder(pctx, ctx)
297
298 manifest := instrumentedApp.mergedManifestFile
299 resourceApk := instrumentedApp.outputFile
300
301 rule.Command().Text("rm -f").Output(outputFile)
302 rule.Command().
303 Textf(`echo "android_merged_manifest=%s" >>`, manifest.String()).Output(outputFile).Text("&&").
304 Textf(`echo "android_resource_apk=%s" >>`, resourceApk.String()).Output(outputFile).
305 // Make it depend on the files to which it points so the test file's timestamp is updated whenever the
306 // contents change
307 Implicit(manifest).
308 Implicit(resourceApk)
309
310 rule.Build("generate_test_config", "generate test_config.properties")
311}
312
Colin Cross8eebb132020-01-29 20:07:03 -0800313func generateSameDirRoboTestConfigJar(ctx android.ModuleContext, outputFile android.ModuleOutPath) {
Colin Crossf1a035e2020-11-16 17:32:30 -0800314 rule := android.NewRuleBuilder(pctx, ctx)
Colin Cross8eebb132020-01-29 20:07:03 -0800315
316 outputDir := outputFile.InSameDir(ctx)
317 configFile := outputDir.Join(ctx, "com/android/tools/test_config.properties")
318 rule.Temporary(configFile)
319 rule.Command().Text("rm -f").Output(outputFile).Output(configFile)
320 rule.Command().Textf("mkdir -p $(dirname %s)", configFile.String())
321 rule.Command().
322 Text("(").
323 Textf(`echo "android_merged_manifest=%s-AndroidManifest.xml" &&`, ctx.ModuleName()).
324 Textf(`echo "android_resource_apk=%s.apk"`, ctx.ModuleName()).
325 Text(") >>").Output(configFile)
326 rule.Command().
Colin Crossf1a035e2020-11-16 17:32:30 -0800327 BuiltTool("soong_zip").
Colin Cross8eebb132020-01-29 20:07:03 -0800328 FlagWithArg("-C ", outputDir.String()).
329 FlagWithInput("-f ", configFile).
330 FlagWithOutput("-o ", outputFile)
331
Colin Crossf1a035e2020-11-16 17:32:30 -0800332 rule.Build("generate_test_config_samedir", "generate test_config.properties")
Colin Cross8eebb132020-01-29 20:07:03 -0800333}
334
Priyanka Advani (xWF)72853672024-09-04 20:15:58 +0000335func (r *robolectricTest) generateRoboSrcJar(ctx android.ModuleContext, outputFile android.WritablePath,
336 instrumentedApp *AndroidApp) {
337
338 srcJarArgs := android.CopyOf(instrumentedApp.srcJarArgs)
339 srcJarDeps := append(android.Paths(nil), instrumentedApp.srcJarDeps...)
340
341 for _, m := range ctx.GetDirectDepsWithTag(roboCoverageLibsTag) {
342 if dep, ok := android.OtherModuleProvider(ctx, m, JavaInfoProvider); ok {
343 srcJarArgs = append(srcJarArgs, dep.SrcJarArgs...)
344 srcJarDeps = append(srcJarDeps, dep.SrcJarDeps...)
345 }
346 }
347
348 TransformResourcesToJar(ctx, outputFile, srcJarArgs, srcJarDeps)
349}
350
Jiyong Park0b0e1b92019-12-03 13:24:29 +0900351func (r *robolectricTest) AndroidMkEntries() []android.AndroidMkEntries {
352 entriesList := r.Library.AndroidMkEntries()
353 entries := &entriesList[0]
Colin Cross6301c3c2021-09-28 17:40:21 -0700354 entries.ExtraEntries = append(entries.ExtraEntries,
355 func(ctx android.AndroidMkExtraEntriesContext, entries *android.AndroidMkEntries) {
356 entries.SetBool("LOCAL_UNINSTALLABLE_MODULE", true)
nelsonli3f97ea22022-11-21 21:37:56 +0800357 entries.AddStrings("LOCAL_COMPATIBILITY_SUITE", "robolectric-tests")
Yike0fcf90a2023-02-14 12:17:32 +0800358 if r.testConfig != nil {
359 entries.SetPath("LOCAL_FULL_TEST_CONFIG", r.testConfig)
360 }
Colin Cross6301c3c2021-09-28 17:40:21 -0700361 })
Priyanka Advani (xWF)72853672024-09-04 20:15:58 +0000362
363 entries.ExtraFooters = []android.AndroidMkExtraFootersFunc{
364 func(w io.Writer, name, prefix, moduleDir string) {
365 if s := r.robolectricProperties.Test_options.Shards; s != nil && *s > 1 {
366 numShards := int(*s)
367 shardSize := (len(r.tests) + numShards - 1) / numShards
368 shards := android.ShardStrings(r.tests, shardSize)
369 for i, shard := range shards {
370 r.writeTestRunner(w, name, "Run"+name+strconv.Itoa(i), shard)
371 }
372
373 // TODO: add rules to dist the outputs of the individual tests, or combine them together?
374 fmt.Fprintln(w, "")
375 fmt.Fprintln(w, ".PHONY:", "Run"+name)
376 fmt.Fprintln(w, "Run"+name, ": \\")
377 for i := range shards {
378 fmt.Fprintln(w, " ", "Run"+name+strconv.Itoa(i), "\\")
379 }
380 fmt.Fprintln(w, "")
381 } else {
382 r.writeTestRunner(w, name, "Run"+name, r.tests)
383 }
384 },
385 }
386
Jiyong Park0b0e1b92019-12-03 13:24:29 +0900387 return entriesList
Colin Cross0ef08162019-05-01 15:50:51 -0700388}
389
Priyanka Advani (xWF)72853672024-09-04 20:15:58 +0000390func (r *robolectricTest) writeTestRunner(w io.Writer, module, name string, tests []string) {
391 fmt.Fprintln(w, "")
392 fmt.Fprintln(w, "include $(CLEAR_VARS)", " # java.robolectricTest")
393 fmt.Fprintln(w, "LOCAL_MODULE :=", name)
394 android.AndroidMkEmitAssignList(w, "LOCAL_JAVA_LIBRARIES", []string{module}, r.libs)
395 fmt.Fprintln(w, "LOCAL_TEST_PACKAGE :=", String(r.robolectricProperties.Instrumentation_for))
396 if r.roboSrcJar != nil {
397 fmt.Fprintln(w, "LOCAL_INSTRUMENT_SRCJARS :=", r.roboSrcJar.String())
398 }
399 android.AndroidMkEmitAssignList(w, "LOCAL_ROBOTEST_FILES", tests)
400 if t := r.robolectricProperties.Test_options.Timeout; t != nil {
401 fmt.Fprintln(w, "LOCAL_ROBOTEST_TIMEOUT :=", *t)
402 }
403 if v := String(r.robolectricProperties.Robolectric_prebuilt_version); v != "" {
404 fmt.Fprintf(w, "-include prebuilts/misc/common/robolectric/%s/run_robotests.mk\n", v)
405 } else {
406 fmt.Fprintln(w, "-include external/robolectric-shadows/run_robotests.mk")
407 }
408}
409
Colin Cross0ef08162019-05-01 15:50:51 -0700410// An android_robolectric_test module compiles tests against the Robolectric framework that can run on the local host
Priyanka Advani (xWF)72853672024-09-04 20:15:58 +0000411// instead of on a device. It also generates a rule with the name of the module prefixed with "Run" that can be
412// used to run the tests. Running the tests with build rule will eventually be deprecated and replaced with atest.
413//
414// The test runner considers any file listed in srcs whose name ends with Test.java to be a test class, unless
415// it is named BaseRobolectricTest.java. The path to the each source file must exactly match the package
416// name, or match the package name when the prefix "src/" is removed.
Colin Cross0ef08162019-05-01 15:50:51 -0700417func RobolectricTestFactory() android.Module {
418 module := &robolectricTest{}
419
Colin Crossce6734e2020-06-15 16:09:53 -0700420 module.addHostProperties()
Colin Cross0ef08162019-05-01 15:50:51 -0700421 module.AddProperties(
Colin Crosse323f3c2019-09-17 15:34:09 -0700422 &module.Module.deviceProperties,
Colin Cross8eebb132020-01-29 20:07:03 -0800423 &module.robolectricProperties,
424 &module.testProperties)
Colin Cross0ef08162019-05-01 15:50:51 -0700425
426 module.Module.dexpreopter.isTest = true
Cole Faustd57e8b22022-08-11 11:59:04 -0700427 module.Module.linter.properties.Lint.Test = proptools.BoolPtr(true)
Colin Cross0ef08162019-05-01 15:50:51 -0700428
Colin Cross8eebb132020-01-29 20:07:03 -0800429 module.testProperties.Test_suites = []string{"robolectric-tests"}
430
Colin Cross0ef08162019-05-01 15:50:51 -0700431 InitJavaModule(module, android.DeviceSupported)
432 return module
433}
Colin Cross8eebb132020-01-29 20:07:03 -0800434
Jiyong Park87788b52020-09-01 12:37:45 +0900435func (r *robolectricTest) InstallInTestcases() bool { return true }
436func (r *robolectricTest) InstallForceOS() (*android.OsType, *android.ArchType) {
Colin Cross0c66bc62021-07-20 09:47:41 -0700437 return &r.forceOSType, &r.forceArchType
Jiyong Park87788b52020-09-01 12:37:45 +0900438}
Colin Cross8eebb132020-01-29 20:07:03 -0800439
440func robolectricRuntimesFactory() android.Module {
441 module := &robolectricRuntimes{}
442 module.AddProperties(&module.props)
Colin Cross5aa29a72020-09-14 19:54:47 -0700443 android.InitAndroidArchModule(module, android.HostSupportedNoCross, android.MultilibCommon)
Colin Cross8eebb132020-01-29 20:07:03 -0800444 return module
445}
446
447type robolectricRuntimesProperties struct {
448 Jars []string `android:"path"`
449 Lib *string
450}
451
452type robolectricRuntimes struct {
453 android.ModuleBase
454
455 props robolectricRuntimesProperties
456
457 runtimes []android.InstallPath
Colin Cross0c66bc62021-07-20 09:47:41 -0700458
459 forceOSType android.OsType
460 forceArchType android.ArchType
Colin Cross8eebb132020-01-29 20:07:03 -0800461}
462
463func (r *robolectricRuntimes) TestSuites() []string {
464 return []string{"robolectric-tests"}
465}
466
467var _ android.TestSuiteModule = (*robolectricRuntimes)(nil)
468
469func (r *robolectricRuntimes) DepsMutator(ctx android.BottomUpMutatorContext) {
Jeongik Cha816a23a2020-07-08 01:09:23 +0900470 if !ctx.Config().AlwaysUsePrebuiltSdks() && r.props.Lib != nil {
Colin Cross8eebb132020-01-29 20:07:03 -0800471 ctx.AddVariationDependencies(nil, libTag, String(r.props.Lib))
472 }
473}
474
475func (r *robolectricRuntimes) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Colin Cross5aa29a72020-09-14 19:54:47 -0700476 if ctx.Target().Os != ctx.Config().BuildOSCommonTarget.Os {
477 return
478 }
479
Colin Cross0c66bc62021-07-20 09:47:41 -0700480 r.forceOSType = ctx.Config().BuildOS
481 r.forceArchType = ctx.Config().BuildArch
482
Colin Cross8eebb132020-01-29 20:07:03 -0800483 files := android.PathsForModuleSrc(ctx, r.props.Jars)
484
485 androidAllDir := android.PathForModuleInstall(ctx, "android-all")
Colin Cross8eebb132020-01-29 20:07:03 -0800486 for _, from := range files {
487 installedRuntime := ctx.InstallFile(androidAllDir, from.Base(), from)
488 r.runtimes = append(r.runtimes, installedRuntime)
489 }
490
Jeongik Cha816a23a2020-07-08 01:09:23 +0900491 if !ctx.Config().AlwaysUsePrebuiltSdks() && r.props.Lib != nil {
Colin Cross8eebb132020-01-29 20:07:03 -0800492 runtimeFromSourceModule := ctx.GetDirectDepWithTag(String(r.props.Lib), libTag)
Jeongik Cha816a23a2020-07-08 01:09:23 +0900493 if runtimeFromSourceModule == nil {
494 if ctx.Config().AllowMissingDependencies() {
495 ctx.AddMissingDependencies([]string{String(r.props.Lib)})
496 } else {
497 ctx.PropertyErrorf("lib", "missing dependency %q", String(r.props.Lib))
498 }
499 return
500 }
Colin Cross8eebb132020-01-29 20:07:03 -0800501 runtimeFromSourceJar := android.OutputFileForModule(ctx, runtimeFromSourceModule, "")
502
Joseph Murphyc9648412021-07-20 13:58:15 -0700503 // "TREE" name is essential here because it hooks into the "TREE" name in
504 // Robolectric's SdkConfig.java that will always correspond to the NEWEST_SDK
505 // in Robolectric configs.
506 runtimeName := "android-all-current-robolectric-r0.jar"
Colin Cross8eebb132020-01-29 20:07:03 -0800507 installedRuntime := ctx.InstallFile(androidAllDir, runtimeName, runtimeFromSourceJar)
508 r.runtimes = append(r.runtimes, installedRuntime)
509 }
510}
511
Jiyong Park87788b52020-09-01 12:37:45 +0900512func (r *robolectricRuntimes) InstallInTestcases() bool { return true }
513func (r *robolectricRuntimes) InstallForceOS() (*android.OsType, *android.ArchType) {
Colin Cross0c66bc62021-07-20 09:47:41 -0700514 return &r.forceOSType, &r.forceArchType
Jiyong Park87788b52020-09-01 12:37:45 +0900515}