Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
dependencies ▾

Modern-Apps.git / build-logic / src / main / kotlin / TestCoverage.kt

TestCoverage.kt245 lines · 11.8 KiBRaw
1/**
2 * Shared test-coverage infrastructure for `common-conventions-app` and
3 * `common-conventions-library`, kept here so the two convention plugins cannot drift:
4 * - [MERGED_COVERAGE_EXCLUDES]: class-file patterns stripped from every merged coverage
5 * report. AGP's own `createDevUnitTestCoverageReport` / `createDebugUnitTestCoverageReport`
6 * tasks are AGP-internal `JacocoReportTask`s with **no excludes support** (verified against
7 * AGP 9.5.0-alpha09: the task exposes the class file collection as-is), so the conventions
8 * register their own Gradle `JacocoReport` task ([MERGED_COVERAGE_TASK]) which does.
9 * - [ROBOLECTRIC_DEFAULT_SDK]: documented next to the properties file that carries it.
10 * - [mergedCoverageClassDirs]: the class files the merged report analyzes.
11 */
12
13import java.io.File
14import java.io.Serializable
15import org.gradle.api.file.FileCollection
16import org.gradle.api.specs.Spec
17
18/** Task name of the per-module merged (unit + instrumented) JaCoCo report. */
19const val MERGED_COVERAGE_TASK = "createMergedCoverageReport"
20
21/**
22 * Unit-test variant each convention's merged report is built from: apps and
23 * libraries both test `dev` (`testDevUnitTest`, AGP `testBuildType = "dev"`).
24 * Libraries define a real `dev` build type mirroring the app one (see
25 * common-conventions-library), so app `dev` builds consume library `dev`
26 * variants by exact name match and library unit tests share those outputs.
27 */
28const val APP_UNIT_TEST_VARIANT = "dev"
29const val LIBRARY_UNIT_TEST_VARIANT = "dev"
30
31/** Stable output location of the merged report, relative to the module build directory. */
32const val MERGED_COVERAGE_XML_PATH = "reports/coverage/merged/report.xml"
33const val MERGED_COVERAGE_HTML_PATH = "reports/coverage/merged/html"
34
35/**
36 * JaCoCo version used to *render* merged reports. Must read the .exec/.ec execution data
37 * written by AGP 9.5's coverage agent (JaCoCo 0.8.14); report rendering within the same
38 * 0.8.x family is compatible.
39 */
40const val MERGED_COVERAGE_JACOCO_VERSION = "0.8.14"
41
42/**
43 * Robolectric default SDK, mirrored in `build-logic/shared-test-resources/robolectric.properties`
44 * (which is the mechanism that actually applies it; this constant only documents the intent
45 * next to the coverage/task wiring).
46 */
47const val ROBOLECTRIC_DEFAULT_SDK = 34
48
49/**
50 * Modules whose merged coverage report is suppressed entirely.
51 *
52 * `:library:aosp-stubs` is compile-only: its classes are `@SystemApi`/hidden-API
53 * stubs that consumers depend on with `compileOnly`, they are never packaged
54 * into an APK, and at runtime the framework's real implementations replace
55 * them (see that module's `build.gradle.kts`). Its stub bodies either throw
56 * `RuntimeException("stub")` or are signature-only shells, so a coverage
57 * percentage for it can only measure how much of a compile-time fiction the
58 * tests exercised — the number has no runtime meaning, and chasing it would
59 * mean writing tests that assert stubs throw, forever, for 37 classes.
60 *
61 * This is deliberately a module list, not a class-file pattern: a broad
62 * `android/...` exclude would also hide real code in any module that ever
63 * legitimately shadows a framework package. `:library:locationprovider`
64 * is also compile-only stubs but is NOT listed: it has a real test suite
65 * pinning the stub contract its consumers subclass against, so its report
66 * stays meaningful and counted.
67 *
68 * The suppression lives in `common-conventions-library` (the only convention
69 * that registers a merged report for these modules) as an `onlyIf` on the
70 * report task: with no report file, coverage tooling treats the module as
71 * not-a-coverage-module rather than as 0%.
72 */
73val COMPILE_ONLY_STUB_MODULES: Set<String> = setOf(":library:aosp-stubs")
74
75/**
76 * Class-file excludes applied to every merged coverage report.
77 *
78 * JaCoCo file-tree excludes are purely name-based, which settles two of the requested cases:
79 * - `*$Companion` is **not** excluded: companion objects hold real code (e.g. factory methods
80 * and default noop implementations), and there is no way to exclude "only empty" companions
81 * with a name pattern. They count as normal code.
82 * - `*Preview*` composables are **not** excluded by annotation: JaCoCo cannot filter by
83 * annotation. This is moot in practice — screenshot previews live in the `screenshotTest`
84 * source set, which never enters the report's class directories. Keep `@Preview`
85 * functions out of `src/main` and they stay out of coverage.
86 */
87val MERGED_COVERAGE_EXCLUDES = listOf(
88 // Generated Android code: R, BuildConfig, Manifest.
89 "**/R.class",
90 "**/R\$*.class",
91 "**/BuildConfig.class",
92 "**/BuildConfig\$*.class",
93 "**/Manifest.class",
94 "**/Manifest\$*.class",
95 // View/Data Binding (Compose-first repo, but harmless where present).
96 "**/databinding/**",
97 "**/*Binding.class",
98 "**/*Binding\$*.class",
99 "**/DataBinderMapperImpl.class",
100 // Room/KSP generated implementations.
101 "**/*_Impl.class",
102 "**/*_Impl\$*.class",
103 // kotlinx.serialization generated serializers.
104 "**/*\$\$serializer.class",
105 "**/*\$\$serializer\$*.class",
106 // Compose compiler singletons (remember/composable caches, no coverable logic).
107 "**/ComposableSingletons\$*.class",
108 // Hilt/Dagger generated code (no Hilt/Dagger in the repo today; future-proofing).
109 "**/Hilt_*.class",
110 "**/*_Hilt*.class",
111 "**/Dagger*.class",
112 "**/*_Factory.class",
113 "**/*_MembersInjector.class",
114 // protobuf-lite generated outer classes. Kept as belt-and-braces: the precise
115 // protoc rule is ProtoGeneratedClassFilter below (every class whose top-level
116 // type has a generated source); this pattern still catches an outer class if
117 // its generated-source root was not scanned (e.g. a future variant layout).
118 "**/*OuterClass*.class",
119 // AIDL-generated stubs.
120 "**/*\$Stub*.class",
121)
122
123/**
124 * Keeps protoc output out of merged coverage: a class file is dropped when its
125 * top-level type has a generated source under the module's proto output roots
126 * (`build/generated/source/proto` and
127 * `build/generated/java/generate<Variant>Proto`). This is the same rule the
128 * CI zero-coverage fallback applies (location_share_server
129 * `scripts/test-run.sh`: "drop every class whose top-level type has a generated
130 * .java source"), so modules with tests and modules without agree on what
131 * counts. Protoc message/builder/or-builder/grpc classes are pure generated
132 * plumbing with no hand-written logic; counting them drowned real coverage
133 * (repo-wide ~587k missed + ~75k covered instructions at the time of writing).
134 *
135 * Why not name patterns (`*Protos*`, `*Proto$*`, proto-package globs)? They are both
136 * too broad and too narrow: `communicate` has hand-written `*Protocol` classes
137 * (`SignalProtocol`, `WhatsAppProtocol*`) one suffix away from `*Proto*`, and
138 * hand-written code may legitimately live in a `proto` package later, while
139 * GAL/grpc types (`AbsoluteEvent`, `AppServiceGrpc`) match no proto name
140 * pattern at all. Source presence is exact: only types protoc actually emitted
141 * are excluded, so no hand-written class can be caught. Verified on
142 * `communicate`, `auto/protocol` and `appstore`: the excluded top-level set is
143 * exactly the generated-source set, and no `src/main` class is in it.
144 *
145 * Laziness / configuration cache: the filter stores only the build directory
146 * and variant (both serializable) and scans the generated sources on first use,
147 * i.e. at report execution time, after the compile tasks have produced them.
148 * Nothing is read from disk while configuring, and the [Spec] itself is
149 * serializable, so the report task stays configuration-cache compatible
150 * (verified by running the report twice: the second run reuses the cache).
151 * The generated roots contain one source-set directory (`java`, plus `grpc` /
152 * `grpckt` for grpc modules); the class relative path is the source path minus
153 * that segment and its extension, so `.../java/com/foo/Bar.java` (and
154 * `.../grpc/com/foo/BarGrpc.java`, `.../grpckt/... .kt`) excludes
155 * `com/foo/Bar.class` and `com/foo/Bar$*.class`. Unknown class-dir layouts keep
156 * the file: exclusion must never guess.
157 */
158class ProtoGeneratedClassFilter(
159 private val buildDir: File,
160 private val variantCap: String,
161) : Spec<File>, Serializable {
162
163 @Transient
164 private var generatedTopLevels: Set<String>? = null
165
166 override fun isSatisfiedBy(element: File): Boolean {
167 if (!element.name.endsWith(".class")) return true
168 val path = element.path.replace('\\', '/')
169 val marker = "/classes/"
170 val idx = path.lastIndexOf(marker)
171 if (idx < 0) return true
172 val rel = path.substring(idx + marker.length).removeSuffix(".class")
173 val topLevel = rel.substringBefore('$')
174 return topLevel !in generatedTopLevels()
175 }
176
177 private fun generatedTopLevels(): Set<String> {
178 generatedTopLevels?.let { return it }
179 val found = mutableSetOf<String>()
180 val roots = listOf(
181 File(buildDir, "generated/source/proto"),
182 File(buildDir, "generated/java/generate${variantCap}Proto"),
183 )
184 for (root in roots) {
185 if (!root.isDirectory) continue
186 root.walkTopDown().forEach { file ->
187 if (!file.isFile) return@forEach
188 if (file.extension != "java" && file.extension != "kt") return@forEach
189 val rel = file.toRelativeString(root).replace('\\', '/')
190 val parts = rel.split('/')
191 if (parts.size < 2) return@forEach
192 val stripped = if (parts[0] == "java" || parts[0] == "grpc" || parts[0] == "grpckt") {
193 parts.drop(1).joinToString("/")
194 } else {
195 rel
196 }
197 found += stripped.removeSuffix(".java").removeSuffix(".kt")
198 }
199 }
200 generatedTopLevels = found
201 return found
202 }
203
204 companion object {
205 private const val serialVersionUID = 1L
206 }
207}
208
209/**
210 * This module's own compiled classes for [variant], before AGP's offline JaCoCo
211 * instrumentation (JaCoCo can only render from original classes), minus
212 * [MERGED_COVERAGE_EXCLUDES] and minus protoc-generated classes
213 * ([ProtoGeneratedClassFilter]). Covers Kotlin and javac output; dependency
214 * classes never appear here, so no package filter is needed.
215 */
216fun org.gradle.api.Project.mergedCoverageClassDirs(variant: String): FileCollection {
217 val cap = variant.replaceFirstChar { it.uppercase() }
218 val tree = files(
219 layout.buildDirectory.dir("intermediates/built_in_kotlinc/$variant/compile${cap}Kotlin/classes"),
220 layout.buildDirectory.dir("intermediates/javac/$variant/compile${cap}JavaWithJavac/classes"),
221 ).builtBy("compile${cap}Kotlin", "compile${cap}JavaWithJavac").asFileTree.matching {
222 MERGED_COVERAGE_EXCLUDES.forEach { exclude(it) }
223 }
224 // Only the build-dir path is captured here (configuration time); the
225 // generated-source scan happens lazily when JaCoCo resolves the files.
226 val buildDirFile = layout.buildDirectory.asFile.get()
227 return tree.filter(ProtoGeneratedClassFilter(buildDirFile, cap))
228}
229
230/**
231 * Robolectric defines classes in its sandbox loader without a code-source location, and
232 * JaCoCo skips such classes by default, so Robolectric-run code reported 0% coverage. AGP
233 * attaches Gradle's JacocoTaskExtension to unit Test tasks; flip it on there.
234 * `jdk.internal.*` must stay excluded or JaCoCo instruments JDK internals and the JVM crashes.
235 */
236fun org.gradle.api.Project.includeRobolectricClassesInCoverage() {
237 afterEvaluate {
238 tasks.withType(org.gradle.api.tasks.testing.Test::class.java).configureEach {
239 extensions.findByType(org.gradle.testing.jacoco.plugins.JacocoTaskExtension::class.java)?.apply {
240 isIncludeNoLocationClasses = true
241 excludes = (excludes.orEmpty() + "jdk.internal.*").distinct()
242 }
243 }
244 }
245}