Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / lint-rules / src / main / java / com / vayunmathur / lint / FixtureDeterminismDetector.kt
FixtureDeterminismDetector.kt248 lines · 12.2 KiBRaw
| 1 | package com.vayunmathur.lint |
| 2 | |
| 3 | import com.android.tools.lint.client.api.UElementHandler |
| 4 | import com.android.tools.lint.detector.api.Category |
| 5 | import com.android.tools.lint.detector.api.Context |
| 6 | import com.android.tools.lint.detector.api.Detector |
| 7 | import com.android.tools.lint.detector.api.Implementation |
| 8 | import com.android.tools.lint.detector.api.Issue |
| 9 | import com.android.tools.lint.detector.api.JavaContext |
| 10 | import com.android.tools.lint.detector.api.Location |
| 11 | import com.android.tools.lint.detector.api.Scope |
| 12 | import com.android.tools.lint.detector.api.Severity |
| 13 | import com.android.tools.lint.detector.api.SourceCodeScanner |
| 14 | import org.jetbrains.uast.UElement |
| 15 | import org.jetbrains.uast.UFile |
| 16 | import java.io.File |
| 17 | |
| 18 | /** |
| 19 | * Fixture data must be deterministic: no relative-to-now timestamps and no |
| 20 | * unseeded randomness in `src/test` or `src/screenshotTest`. |
| 21 | * |
| 22 | * A screenshot fixture that reads `Clock.System.now()` renders a different |
| 23 | * golden every day; a unit-test fixture seeded from the wall clock or an |
| 24 | * unseeded `Random` flakes or drifts the same way. Both source sets are |
| 25 | * scanned from disk in [afterCheckProject] rather than from the visited |
| 26 | * sources — like [RouteScreenshotCoverageDetector], because |
| 27 | * `src/screenshotTest` is a screenshot-test source set, not a lint-analysed |
| 28 | * one, so its files are not guaranteed a visit. |
| 29 | * |
| 30 | * Banned (in fixture code): |
| 31 | * - `Clock.System.now()`, `LocalDate.now()`, `LocalDateTime.now()`, |
| 32 | * `Instant.now()`, `System.currentTimeMillis()` — relative-to-now values. |
| 33 | * - `Random()` / `java.util.Random()` with no seed, `Random.Default`, and |
| 34 | * `UUID.randomUUID()` — unseeded randomness. `Random(<seed>)` is fine. |
| 35 | * |
| 36 | * Precision choices (deliberate; these are not fixtures): |
| 37 | * - Comments and string literals are stripped before matching, so a KDoc |
| 38 | * sentence mentioning `Clock.System.now()` is not a violation. |
| 39 | * - In `src/test` only, the recognised time-*control* idioms are out of |
| 40 | * scope: deadline/timeout polling (`deadline = System.currentTimeMillis() |
| 41 | * + …`, `while (System.currentTimeMillis() < deadline)`, pump/await-until |
| 42 | * helpers), elapsed-time measurement (a `started`/`before` stamp later |
| 43 | * subtracted, or a subtraction on the same line), and freshness assertions |
| 44 | * (`assertTrue(ts <= System.currentTimeMillis())`). They read the clock to |
| 45 | * bound or verify real time, never to build fixture data. Screenshot |
| 46 | * fixtures get no such exemption: a preview must never read the clock. |
| 47 | * - `SecureRandom` is out of scope: cryptographic test fakes |
| 48 | * (e.g. `FakeAndroidKeyStore`) must draw real key material; no assertion |
| 49 | * may depend on its bytes. |
| 50 | * |
| 51 | * Fix: replace the value with a named fixed constant (e.g. |
| 52 | * `private val FIXED_NOW = Instant.fromEpochMilliseconds(1_768_651_200_000L)`) |
| 53 | * so the fixture reads as data. Code that genuinely must seed relative to |
| 54 | * the system-under-test's own real clock (a repository that stamps "now" |
| 55 | * internally, where a fixed past timestamp would turn fresh data stale) |
| 56 | * opts out per file with: |
| 57 | * `// FIXTURE RELATIVE-TIME EXCEPTION: <reason>`. |
| 58 | */ |
| 59 | class FixtureDeterminismDetector : Detector(), SourceCodeScanner { |
| 60 | |
| 61 | override fun getApplicableUastTypes(): List<Class<out UElement>> = |
| 62 | listOf(UFile::class.java) |
| 63 | |
| 64 | override fun createUastHandler(context: JavaContext): UElementHandler = |
| 65 | object : UElementHandler() { |
| 66 | override fun visitFile(node: UFile) { |
| 67 | // Nothing to collect per file: the scan runs from disk in |
| 68 | // afterCheckProject (see class KDoc). |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | override fun afterCheckProject(context: Context) { |
| 73 | for (rootName in SOURCE_SETS) { |
| 74 | val root = File(context.project.dir, rootName) |
| 75 | if (!root.isDirectory) continue |
| 76 | val screenshot = rootName.contains(SHOT_MARKER) |
| 77 | root.walkTopDown() |
| 78 | .filter { it.isFile && (it.extension == "kt" || it.extension == "java") } |
| 79 | .forEach { scanFile(context, it, screenshot) } |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | private fun scanFile(context: Context, file: File, screenshot: Boolean) { |
| 84 | val raw = file.readText() |
| 85 | if (raw.contains(EXCEPTION_MARKER)) return |
| 86 | val cleaned = stripCommentsAndStrings(raw) |
| 87 | var offset = 0 |
| 88 | for (line in cleaned.lineSequence()) { |
| 89 | checkLine(context, file, raw, line, offset, screenshot) |
| 90 | offset += line.length + 1 |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | private fun checkLine( |
| 95 | context: Context, |
| 96 | file: File, |
| 97 | raw: String, |
| 98 | line: String, |
| 99 | lineStart: Int, |
| 100 | screenshot: Boolean, |
| 101 | ) { |
| 102 | if (line.isBlank()) return |
| 103 | if (!screenshot && isTimeControlIdiom(line)) return |
| 104 | for ((label, pattern) in BANNED) { |
| 105 | val match = pattern.find(line) ?: continue |
| 106 | val start = lineStart + match.range.first |
| 107 | if (!reported.add("${file.absolutePath}:$start:$label")) continue |
| 108 | context.report( |
| 109 | ISSUE, |
| 110 | Location.create(file, raw, start, start + match.value.length), |
| 111 | "Non-deterministic fixture: `$label` reads the wall clock / unseeded " + |
| 112 | "randomness, so this fixture changes on every run. Replace it with a " + |
| 113 | "named fixed constant (a fixed `Instant`/epoch-millis/date, a seeded " + |
| 114 | "`Random(seed)`, or a fixed UUID). Code that must seed relative to the " + |
| 115 | "system-under-test's real clock opts out per file with " + |
| 116 | "`$EXCEPTION_MARKER <reason>`.", |
| 117 | ) |
| 118 | } |
| 119 | } |
| 120 | |
| 121 | companion object { |
| 122 | const val EXCEPTION_MARKER = "// FIXTURE RELATIVE-TIME EXCEPTION:" |
| 123 | |
| 124 | /** |
| 125 | * (file, start, label) already reported. Lint instantiates a detector |
| 126 | * per scope (and per dependency project under checkDependencies), so |
| 127 | * the dedup set must live on the companion to suppress per-scope |
| 128 | * duplicate reports of the same hit within one lint JVM. |
| 129 | */ |
| 130 | private val reported = mutableSetOf<String>() |
| 131 | |
| 132 | private val SOURCE_SETS = listOf("src/test", "src/screenshotTest") |
| 133 | private const val SHOT_MARKER = "screenshotTest" |
| 134 | |
| 135 | /** Banned call shapes, matched against comment/string-stripped source. */ |
| 136 | private val BANNED: List<Pair<String, Regex>> = listOf( |
| 137 | "Clock.System.now()" to Regex("""Clock\s*\.\s*System\s*\.\s*now\s*\("""), |
| 138 | "LocalDateTime.now()" to Regex("""(?<!\w)LocalDateTime\s*\.\s*now\s*\("""), |
| 139 | "LocalDate.now()" to Regex("""(?<!\w)LocalDate\s*\.\s*now\s*\("""), |
| 140 | "Instant.now()" to Regex("""(?<!\w)Instant\s*\.\s*now\s*\("""), |
| 141 | "System.currentTimeMillis()" to Regex("""System\s*\.\s*currentTimeMillis\s*\("""), |
| 142 | "UUID.randomUUID()" to Regex("""UUID\s*\.\s*randomUUID\s*\("""), |
| 143 | "Random() unseeded" to Regex("""(?<![\w.])Random\s*\(\s*\)|Random\s*\.\s*Default"""), |
| 144 | ) |
| 145 | |
| 146 | private val DEADLINE_WORDS = listOf("deadline", "pumpmainuntil", "await", "until(") |
| 147 | private val ELAPSED_STARTERS = |
| 148 | Regex("""\bval\s+(start|started|before|t0|begin|elapsed)\w*\s*=""") |
| 149 | |
| 150 | /** |
| 151 | * The non-fixture time-control idioms of `src/test` (see class KDoc): |
| 152 | * deadline/timeout polling, elapsed measurement, freshness asserts. |
| 153 | * Line-based by design — a banned call spread over a statement that |
| 154 | * only becomes a deadline several lines later is reported, and the |
| 155 | * file marker is the escape for that rare shape. |
| 156 | */ |
| 157 | internal fun isTimeControlIdiom(line: String): Boolean { |
| 158 | val lower = line.lowercase() |
| 159 | if (DEADLINE_WORDS.any { it in lower }) return true |
| 160 | val trimmed = line.trimStart() |
| 161 | if (trimmed.startsWith("while") || trimmed.startsWith("if (") || trimmed.startsWith("if(")) return true |
| 162 | if ("assert" in lower || "check(" in lower || "require(" in lower) return true |
| 163 | if (ELAPSED_STARTERS.containsMatchIn(line)) return true |
| 164 | // Elapsed subtraction on one line: `now() - started` or |
| 165 | // `started - now()` (an identifier on the other side). A numeric |
| 166 | // offset (`now() - 60_000L`, `now() - 10.minutes`) is a |
| 167 | // relative-to-now fixture value, not a measurement: still banned. |
| 168 | return BANNED.any { (_, p) -> |
| 169 | p.findAll(line).any { m -> |
| 170 | val after = line.substring(m.range.last + 1).trimStart() |
| 171 | .removePrefix(")").trimStart() |
| 172 | val before = line.substring(0, m.range.first).trimEnd() |
| 173 | (after.startsWith("-") && after.drop(1).trimStart().firstOrNull()?.isDigit() == false) || |
| 174 | (before.endsWith("-") && before.dropLast(1).trimEnd().lastOrNull()?.isDigit() == false) |
| 175 | } |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | /** |
| 180 | * Blank out `//`/`/* */` comments and string/char literals (including |
| 181 | * raw `"""` strings), preserving length and newlines so offsets in |
| 182 | * the cleaned text still map onto the raw file. |
| 183 | */ |
| 184 | internal fun stripCommentsAndStrings(text: String): String { |
| 185 | val out = StringBuilder(text.length) |
| 186 | var i = 0 |
| 187 | while (i < text.length) { |
| 188 | val c = text[i] |
| 189 | val next = text.getOrNull(i + 1) |
| 190 | when { |
| 191 | c == '/' && next == '/' -> { |
| 192 | while (i < text.length && text[i] != '\n') { out.append(' '); i++ } |
| 193 | } |
| 194 | c == '/' && next == '*' -> { |
| 195 | out.append(" "); i += 2 |
| 196 | while (i < text.length && !(text[i] == '*' && text.getOrNull(i + 1) == '/')) { |
| 197 | out.append(if (text[i] == '\n') '\n' else ' '); i++ |
| 198 | } |
| 199 | if (i < text.length) { out.append(" "); i += 2 } |
| 200 | } |
| 201 | c == '"' && text.startsWith("\"\"\"", i) -> { |
| 202 | out.append(" "); i += 3 |
| 203 | while (i < text.length && !text.startsWith("\"\"\"", i)) { |
| 204 | out.append(if (text[i] == '\n') '\n' else ' '); i++ |
| 205 | } |
| 206 | if (i < text.length) { out.append(" "); i += 3 } |
| 207 | } |
| 208 | c == '"' || c == '\'' -> { |
| 209 | out.append(' '); i++ |
| 210 | while (i < text.length && text[i] != c && text[i] != '\n') { |
| 211 | if (text[i] == '\\' && i + 1 < text.length) { out.append(" "); i += 2 } |
| 212 | else { out.append(' '); i++ } |
| 213 | } |
| 214 | if (i < text.length && text[i] == c) { out.append(' '); i++ } |
| 215 | } |
| 216 | else -> { out.append(c); i++ } |
| 217 | } |
| 218 | } |
| 219 | return out.toString() |
| 220 | } |
| 221 | |
| 222 | val ISSUE: Issue = Issue.create( |
| 223 | id = "FixtureDeterminism", |
| 224 | briefDescription = "Non-deterministic test/screenshot fixture (relative-now or unseeded randomness)", |
| 225 | explanation = """ |
| 226 | Test and screenshot fixtures must be deterministic. Reading \ |
| 227 | `Clock.System.now()`, `LocalDate.now()`, `LocalDateTime.now()`, \ |
| 228 | `Instant.now()` or `System.currentTimeMillis()`, or drawing from an \ |
| 229 | unseeded `Random()`/`Random.Default`/`UUID.randomUUID()`, makes the \ |
| 230 | fixture a function of when it runs: screenshot goldens drift daily \ |
| 231 | and unit fixtures flake. Use a named fixed constant or a seeded \ |
| 232 | `Random(seed)` instead. In unit tests the time-control idioms \ |
| 233 | (deadline polling, elapsed measurement, freshness assertions) are \ |
| 234 | not fixtures and are not flagged; screenshot fixtures are flagged \ |
| 235 | unconditionally. A file that must seed relative to the \ |
| 236 | system-under-test's real clock opts out with \ |
| 237 | `// FIXTURE RELATIVE-TIME EXCEPTION: <reason>`. |
| 238 | """.trimIndent(), |
| 239 | category = Category.CORRECTNESS, |
| 240 | priority = 6, |
| 241 | severity = Severity.ERROR, |
| 242 | implementation = Implementation( |
| 243 | FixtureDeterminismDetector::class.java, |
| 244 | Scope.JAVA_FILE_SCOPE, |
| 245 | ), |
| 246 | ) |
| 247 | } |
| 248 | } |