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