package com.vayunmathur.lint import com.android.tools.lint.client.api.UElementHandler import com.android.tools.lint.detector.api.Category import com.android.tools.lint.detector.api.Context import com.android.tools.lint.detector.api.Detector import com.android.tools.lint.detector.api.Implementation import com.android.tools.lint.detector.api.Issue import com.android.tools.lint.detector.api.JavaContext import com.android.tools.lint.detector.api.Location import com.android.tools.lint.detector.api.Scope import com.android.tools.lint.detector.api.Severity import com.android.tools.lint.detector.api.SourceCodeScanner import org.jetbrains.uast.UElement import org.jetbrains.uast.UFile import java.io.File /** * Fixture data must be deterministic: no relative-to-now timestamps and no * unseeded randomness in `src/test` or `src/screenshotTest`. * * A screenshot fixture that reads `Clock.System.now()` renders a different * golden every day; a unit-test fixture seeded from the wall clock or an * unseeded `Random` flakes or drifts the same way. Both source sets are * scanned from disk in [afterCheckProject] rather than from the visited * sources — like [RouteScreenshotCoverageDetector], because * `src/screenshotTest` is a screenshot-test source set, not a lint-analysed * one, so its files are not guaranteed a visit. * * Banned (in fixture code): * - `Clock.System.now()`, `LocalDate.now()`, `LocalDateTime.now()`, * `Instant.now()`, `System.currentTimeMillis()` — relative-to-now values. * - `Random()` / `java.util.Random()` with no seed, `Random.Default`, and * `UUID.randomUUID()` — unseeded randomness. `Random()` is fine. * * Precision choices (deliberate; these are not fixtures): * - Comments and string literals are stripped before matching, so a KDoc * sentence mentioning `Clock.System.now()` is not a violation. * - In `src/test` only, the recognised time-*control* idioms are out of * scope: deadline/timeout polling (`deadline = System.currentTimeMillis() * + …`, `while (System.currentTimeMillis() < deadline)`, pump/await-until * helpers), elapsed-time measurement (a `started`/`before` stamp later * subtracted, or a subtraction on the same line), and freshness assertions * (`assertTrue(ts <= System.currentTimeMillis())`). They read the clock to * bound or verify real time, never to build fixture data. Screenshot * fixtures get no such exemption: a preview must never read the clock. * - `SecureRandom` is out of scope: cryptographic test fakes * (e.g. `FakeAndroidKeyStore`) must draw real key material; no assertion * may depend on its bytes. * * Fix: replace the value with a named fixed constant (e.g. * `private val FIXED_NOW = Instant.fromEpochMilliseconds(1_768_651_200_000L)`) * so the fixture reads as data. Code that genuinely must seed relative to * the system-under-test's own real clock (a repository that stamps "now" * internally, where a fixed past timestamp would turn fresh data stale) * opts out per file with: * `// FIXTURE RELATIVE-TIME EXCEPTION: `. */ class FixtureDeterminismDetector : Detector(), SourceCodeScanner { override fun getApplicableUastTypes(): List> = listOf(UFile::class.java) override fun createUastHandler(context: JavaContext): UElementHandler = object : UElementHandler() { override fun visitFile(node: UFile) { // Nothing to collect per file: the scan runs from disk in // afterCheckProject (see class KDoc). } } override fun afterCheckProject(context: Context) { for (rootName in SOURCE_SETS) { val root = File(context.project.dir, rootName) if (!root.isDirectory) continue val screenshot = rootName.contains(SHOT_MARKER) root.walkTopDown() .filter { it.isFile && (it.extension == "kt" || it.extension == "java") } .forEach { scanFile(context, it, screenshot) } } } private fun scanFile(context: Context, file: File, screenshot: Boolean) { val raw = file.readText() if (raw.contains(EXCEPTION_MARKER)) return val cleaned = stripCommentsAndStrings(raw) var offset = 0 for (line in cleaned.lineSequence()) { checkLine(context, file, raw, line, offset, screenshot) offset += line.length + 1 } } private fun checkLine( context: Context, file: File, raw: String, line: String, lineStart: Int, screenshot: Boolean, ) { if (line.isBlank()) return if (!screenshot && isTimeControlIdiom(line)) return for ((label, pattern) in BANNED) { val match = pattern.find(line) ?: continue val start = lineStart + match.range.first if (!reported.add("${file.absolutePath}:$start:$label")) continue context.report( ISSUE, Location.create(file, raw, start, start + match.value.length), "Non-deterministic fixture: `$label` reads the wall clock / unseeded " + "randomness, so this fixture changes on every run. Replace it with a " + "named fixed constant (a fixed `Instant`/epoch-millis/date, a seeded " + "`Random(seed)`, or a fixed UUID). Code that must seed relative to the " + "system-under-test's real clock opts out per file with " + "`$EXCEPTION_MARKER `.", ) } } companion object { const val EXCEPTION_MARKER = "// FIXTURE RELATIVE-TIME EXCEPTION:" /** * (file, start, label) already reported. Lint instantiates a detector * per scope (and per dependency project under checkDependencies), so * the dedup set must live on the companion to suppress per-scope * duplicate reports of the same hit within one lint JVM. */ private val reported = mutableSetOf() private val SOURCE_SETS = listOf("src/test", "src/screenshotTest") private const val SHOT_MARKER = "screenshotTest" /** Banned call shapes, matched against comment/string-stripped source. */ private val BANNED: List> = listOf( "Clock.System.now()" to Regex("""Clock\s*\.\s*System\s*\.\s*now\s*\("""), "LocalDateTime.now()" to Regex("""(? p.findAll(line).any { m -> val after = line.substring(m.range.last + 1).trimStart() .removePrefix(")").trimStart() val before = line.substring(0, m.range.first).trimEnd() (after.startsWith("-") && after.drop(1).trimStart().firstOrNull()?.isDigit() == false) || (before.endsWith("-") && before.dropLast(1).trimEnd().lastOrNull()?.isDigit() == false) } } } /** * Blank out `//`/`/* */` comments and string/char literals (including * raw `"""` strings), preserving length and newlines so offsets in * the cleaned text still map onto the raw file. */ internal fun stripCommentsAndStrings(text: String): String { val out = StringBuilder(text.length) var i = 0 while (i < text.length) { val c = text[i] val next = text.getOrNull(i + 1) when { c == '/' && next == '/' -> { while (i < text.length && text[i] != '\n') { out.append(' '); i++ } } c == '/' && next == '*' -> { out.append(" "); i += 2 while (i < text.length && !(text[i] == '*' && text.getOrNull(i + 1) == '/')) { out.append(if (text[i] == '\n') '\n' else ' '); i++ } if (i < text.length) { out.append(" "); i += 2 } } c == '"' && text.startsWith("\"\"\"", i) -> { out.append(" "); i += 3 while (i < text.length && !text.startsWith("\"\"\"", i)) { out.append(if (text[i] == '\n') '\n' else ' '); i++ } if (i < text.length) { out.append(" "); i += 3 } } c == '"' || c == '\'' -> { out.append(' '); i++ while (i < text.length && text[i] != c && text[i] != '\n') { if (text[i] == '\\' && i + 1 < text.length) { out.append(" "); i += 2 } else { out.append(' '); i++ } } if (i < text.length && text[i] == c) { out.append(' '); i++ } } else -> { out.append(c); i++ } } } return out.toString() } val ISSUE: Issue = Issue.create( id = "FixtureDeterminism", briefDescription = "Non-deterministic test/screenshot fixture (relative-now or unseeded randomness)", explanation = """ Test and screenshot fixtures must be deterministic. Reading \ `Clock.System.now()`, `LocalDate.now()`, `LocalDateTime.now()`, \ `Instant.now()` or `System.currentTimeMillis()`, or drawing from an \ unseeded `Random()`/`Random.Default`/`UUID.randomUUID()`, makes the \ fixture a function of when it runs: screenshot goldens drift daily \ and unit fixtures flake. Use a named fixed constant or a seeded \ `Random(seed)` instead. In unit tests the time-control idioms \ (deadline polling, elapsed measurement, freshness assertions) are \ not fixtures and are not flagged; screenshot fixtures are flagged \ unconditionally. A file that must seed relative to the \ system-under-test's real clock opts out with \ `// FIXTURE RELATIVE-TIME EXCEPTION: `. """.trimIndent(), category = Category.CORRECTNESS, priority = 6, severity = Severity.ERROR, implementation = Implementation( FixtureDeterminismDetector::class.java, Scope.JAVA_FILE_SCOPE, ), ) } }