diff --git a/.claude/agents/reviewer.md b/.claude/agents/reviewer.md index f8ffd28..be9d5c6 100644 --- a/.claude/agents/reviewer.md +++ b/.claude/agents/reviewer.md @@ -95,6 +95,7 @@ Read AGENTS.md and docs/vision.md first. Read any ADR in docs/adr/ and any spec 4. **Architecture rules**, once there is code. Module boundaries, NewPipeExtractor used only in the YouTube layer, logging only through the Logger with constant messages, tags and field names and no user data, as ADR 0007 defines it, MVI with a pure reducer, playback state kept out of screen state, no hardcoded strings or colors, no GlobalScope, committed Room schema files, and, from the first public release on, a migration plus migration test for every Room schema change. - Dewfall's lint checks in `:lint-rules` enforce ADR 0007's logging rules. Flag any change to their exceptions, in LogWriterClass.kt, and ask the maintainer about it. It is a must-fix unless the same pull request updates ADR 0007 with a dated note. Also flag any lint.xml file, lint baseline, or lint setting that names a Dewfall issue, such as `disable`, a severity, or `checkOnly`, and any change that makes a Dewfall issue suppressible. - @ConstantText goes only on a String parameter that its function passes on as log text. + - Lint can't read a module's src/screenshotTest folder, so check it by hand. Every .kt file there holds only @PreviewTest wrappers whose body is one call to a preview in src/main, such as `private fun ResultsScreenshot() = ResultsPreview()`, with no logging and no other code. The only other files there are reference images under src/screenshotTest/reference/. scripts/scan_screenshot_tests.py checks this shape too. ADR 0007's note of November 21, 2026 explains why. 5. **Kotlin style.** Read every changed Kotlin file, main code and tests, against the Kotlin style rule next to the formatting commands in AGENTS.md. 6. **Tests.** New logic has tests. Unit tests never touch the network. No test was deleted, skipped or weakened. 7. **Workflow.** The work is on a branch, not main. Commit messages follow the conventional format. Before a push, the hand-off shows the pre-push gate's output for HEAD, ending with PASS, as AGENTS.md asks. A behavior change has an OpenSpec change. A hard-to-reverse decision has an ADR. docs/architecture.md is updated if the structure changed. If the work fully finishes a roadmap task, the pull request closes that task's issue on the project board. It never closes the issue of an unfinished task. diff --git a/.coderabbit.yaml b/.coderabbit.yaml index 8cbf727..041ac9c 100644 --- a/.coderabbit.yaml +++ b/.coderabbit.yaml @@ -80,6 +80,12 @@ reviews: - path: "**/src/test/**" instructions: >- Check tests against AGENTS.md's Testing rules and docs/testing.md. + - path: "**/src/screenshotTest/**" + instructions: >- + Android Lint and Dewfall's lint checks don't read this folder. It holds only @PreviewTest + wrappers whose body is one call to a preview in src/main, with no logging and no other + code, which scripts/scan_screenshot_tests.py checks. See the note of November 21, 2026 in + docs/adr/0007-how-the-app-logs.md and docs/testing.md#screenshot-tests. - path: ".github/workflows/**" instructions: >- Check workflows against the GitHub Actions rule in AGENTS.md's How to work section. diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml index d2388c5..623ee9c 100644 --- a/.github/workflows/pull-request.yml +++ b/.github/workflows/pull-request.yml @@ -1,6 +1,6 @@ # Checks every pull request to main: formatting, detekt, Android Lint with the Android API check, -# unit tests, a debug build, and the Room schema check. It runs the all-checks command from -# AGENTS.md. +# unit tests, screenshot tests, a debug build, the Room schema check, and the scan of the screenshot +# test folders. It runs the all-checks command from AGENTS.md. name: Pull request on: @@ -66,10 +66,10 @@ jobs: # --continue reports every failing check in one run. sdkDownload=false makes a missing SDK # package fail the build instead of downloading silently. - - name: Check formatting, run detekt, lint and unit tests, and build the debug APK + - name: Check formatting, run detekt, lint, unit and screenshot tests, and build the debug APK run: >- ./gradlew --continue -Pandroid.builder.sdkDownload=false - spotlessCheck detekt lint test assembleDebug + spotlessCheck detekt lint test testDebugScreenshotTestDefaultTestSuite assembleDebug # Room rewrites the schema files in core/database/schemas/ when the database changes, and the # build still passes, even when the version number stays the same. This fails when the build @@ -85,11 +85,22 @@ jobs: exit 1 fi + # Lint can't read the src/screenshotTest folders, so this checks that they hold only one-call + # preview wrappers and reference images. See docs/testing.md#screenshot-tests. It runs even + # when a step above failed. + - name: Check the screenshot test folders + if: ${{ !cancelled() }} + run: python3 -I scripts/scan_screenshot_tests.py + + # The screenshot tests' report names the images it compared. The new and diff images stay in + # the results folder, so they are uploaded too. - name: Upload the reports if: failure() uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: reports - path: "**/build/reports/" + path: | + **/build/reports/ + **/build/intermediates/*/testDebugScreenshotTestDefaultTestSuite/results/ retention-days: 7 if-no-files-found: ignore diff --git a/AGENTS.md b/AGENTS.md index 5e7a673..b86c847 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -38,9 +38,10 @@ This section is updated whenever a phase's milestone closes. | core/database/schemas/ | The Room database schemas that the build writes, one JSON file per database version | | core/youtube/src/test/resources/youtube/ | The saved YouTube responses that the YouTube layer's tests replay, which the recorder writes | | feature/ | Feature modules, two for each feature. Today the Search YouTube screen, the video screen, and the YouTube layer's debug screen, which only debug builds contain | +| feature/*-ui/src/screenshotTest/ | The screenshot tests: one-call @PreviewTest wrappers of the previews in src/main. The reference images they are compared with are in src/screenshotTestDefaultDebug/reference/ next to it. docs/testing.md#screenshot-tests explains them | | build-logic/ | Convention plugins with the build settings that every module shares | | lint-rules/ | Dewfall's own lint checks, which lint runs on every module of the app. They enforce ADR 0007's logging rules, and nothing from them ships | -| scripts/ | The pre-push gate, which checks every commit before a push, its scan of the saved YouTube responses, the maintainer subagent's guard and checkout script, and their tests. docs/testing.md#the-pre-push-gate explains the gate | +| scripts/ | The pre-push gate, which checks every commit before a push, its scan of the saved YouTube responses, the scan of the screenshot test folders, the maintainer subagent's guard and checkout script, and their tests. docs/testing.md#the-pre-push-gate explains the gate | | gradle/libs.versions.toml | The version of every plugin and library | | config/detekt/detekt.yml | detekt's settings: the changes to its default rules, and the list of Compose rules | | .editorconfig | Editor settings, with a Kotlin section that comes close to the formatter | @@ -105,7 +106,7 @@ These apply from Phase 2 on. A pull request that refines them updates this secti - Colors come from MaterialTheme color roles. Never hardcode colors. The one exception is `:app`'s launch window theme, which Android draws before Compose can read MaterialTheme, so it copies Dewfall's surface color from tokens.json, and LaunchThemeTest checks the copy. Every screen must work in light, dark and dynamic color. - Every screen draws edge to edge and handles window insets. Backgrounds may sit under the system bars, but no text or controls sit under the system bars or the display cutout. Android 16 and later give apps that target them no way to opt out. See ADR 0006. - Annotation processors for Kotlin code, such as Hilt's and Room's compilers, run through KSP. The kotlin-kapt plugin doesn't work with AGP's built-in Kotlin, and Google recommends KSP over its com.android.legacy-kapt fallback. Ask first before adding kotlin-kapt or com.android.legacy-kapt. -- Log only through the Logger from `:core:logging`, which a class receives in its constructor. Messages, tags and field names are constant text: a string literal, a `const val`, or `+` of those, never a string template. A function that passes its own String parameter on as one of them marks it @ConstantText. Never log user data, as [ADR 0007](docs/adr/0007-how-the-app-logs.md#user-data) defines it. Never call android.util.Log outside LogcatWriter in `:app`, which calls only Log.println. Never write to standard output outside ConsoleLogWriter, which writes the lines of the recorder of saved YouTube responses and of the live YouTube check in `:core:youtube`'s tests, and never write to standard error or call printStackTrace anywhere. Never use NewPipeExtractor's ExtractorLogger, and never use another logging API, such as java.util.logging. Reducers never log. Dewfall's lint checks enforce these rules in main and test sources, and nothing can suppress them. Any change to their two exceptions updates ADR 0007 in the same pull request, with a dated note. +- Log only through the Logger from `:core:logging`, which a class receives in its constructor. Messages, tags and field names are constant text: a string literal, a `const val`, or `+` of those, never a string template. A function that passes its own String parameter on as one of them marks it @ConstantText. Never log user data, as [ADR 0007](docs/adr/0007-how-the-app-logs.md#user-data) defines it. Never call android.util.Log outside LogcatWriter in `:app`, which calls only Log.println. Never write to standard output outside ConsoleLogWriter, which writes the lines of the recorder of saved YouTube responses and of the live YouTube check in `:core:youtube`'s tests, and never write to standard error or call printStackTrace anywhere. Never use NewPipeExtractor's ExtractorLogger, and never use another logging API, such as java.util.logging. Reducers never log. Dewfall's lint checks enforce these rules in main and test sources, and nothing can suppress them. Lint can't read the screenshot test folders, src/screenshotTest, so they hold only one-call wrappers of previews in src/main, and scripts/scan_screenshot_tests.py, which the gate and the pull request workflow run, checks that shape. See ADR 0007's note of November 21, 2026. Any change to the lint checks' two exceptions updates ADR 0007 in the same pull request, with a dated note. - Use coroutines and Flow. Never use GlobalScope. Inject dispatchers so tests can replace them. The one exception is viewModelScope's Main dispatcher: ViewModels take no dispatcher, and their tests replace Main with Dispatchers.setMain. - The database uses Room 3, in the androidx.room3 package. Room 2 is deprecated. - Room schemas are exported into core/database/schemas/. Commit the schema files that the build writes, and never edit them by hand. The first public release is the first GitHub release, including a pre-release, published from a version tag. A tag made only to test the release workflow, with no published release, doesn't count, and nightly APKs don't count. Until then, the database stays at version 1, and a schema change needs no migration. From the first public release on, every schema change raises the version and needs a migration and a migration test. Never use destructive migrations. @@ -113,11 +114,11 @@ These apply from Phase 2 on. A pull request that refines them updates this secti ## Testing rules - New logic ships with tests in the same pull request. -- Write tests with kotlin.test's annotations and assertions. They run on JUnit 6 in plain Kotlin/JVM modules and on JUnit 4 in Android modules. docs/testing.md explains how to test reducers and ViewModels. +- Write tests with kotlin.test's annotations and assertions. They run on JUnit 6 in plain Kotlin/JVM modules and on JUnit 4 in Android modules. docs/testing.md explains how to test reducers and ViewModels. Screenshot tests are the exception: they are @PreviewTest wrappers of previews, which the screenshot engine's own test engine runs. - ViewModel tests replace the Main dispatcher with Dispatchers.setMain before each test and reset it after. - Unit tests never touch the network. The YouTube layer is tested against saved responses. Live YouTube checks run in the scheduled CI workflow, or by hand with `./gradlew :core:youtube:liveYouTubeCheck`. Recording the saved responses is the one other step that reaches YouTube: a developer runs it by hand, and it never runs in CI. Neither runs in `./gradlew test`. docs/testing.md explains when to run each. - Emulator tests replace the YouTube layer and the player's media clients with fakes through Hilt, so they never reach YouTube either. docs/testing.md#emulator-tests explains them. -- Screens get screenshot tests in light, dark and large font. +- Screens get screenshot tests in light, dark and large font, and in dynamic color with a fixed wallpaper. docs/testing.md#screenshot-tests explains how to add, record and update them. - Never delete, skip or weaken a test to make it pass. If a test looks wrong, explain why and ask. ## Commands @@ -131,10 +132,13 @@ Run these from the repository root. The build needs JDK 17 installed, because ev - Check formatting: `./gradlew spotlessCheck`. It checks every Kotlin file and Kotlin build script in the repository, build-logic included, against ktfmt in kotlinlang style. - Fix formatting: `./gradlew spotlessApply`. It rewrites the same files in place. Run it before you commit. - Follow the Kotlin style that ktfmt doesn't decide, from [Android's Kotlin style guide](https://developer.android.com/kotlin/style-guide#braces) and [Kotlin's coding conventions](https://kotlinlang.org/docs/coding-conventions.html#loops). Every for, while and do has braces, even on one line. An if, used as a statement or an expression, skips braces only when all of it fits on one line and it has at most one else, such as `if (x) return` or `if (done) finish() else retry()`. A when branch skips them when its arrow and its whole body fit on one line, even when ktfmt wraps its conditions onto the lines above. The guide shows no branch whose conditions span lines, so that part is Dewfall's own reading. In main code, prefer for loops to forEach, unless the receiver is nullable or forEach is part of a longer call chain. Tests may use forEach. -- Run detekt: `./gradlew detekt`. It checks the Kotlin code in src/main, src/test and src/androidTest of every module, and the code in build-logic, without type resolution. Any finding fails the build. Reports go to build/reports/detekt/ in each project. -- Run Android Lint: `./gradlew lint`. It checks every module, with Dewfall's own checks from `:lint-rules` on main and test sources of every module of the app, and writes a report to build/reports/ in each of them. Any warning fails the build. In the app's plain Kotlin/JVM modules it also runs Animal Sniffer, which checks the code against the Android API at minSdk 29, because lint's own API check skips those modules. The lint checks' own tests run with `./gradlew :lint-rules:test`, which `./gradlew test` includes. +- Run detekt: `./gradlew detekt`. It checks the Kotlin code in src/main, src/test and src/androidTest of every module, and in src/screenshotTest of the modules with screenshot tests, and the code in build-logic, without type resolution. Any finding fails the build. Reports go to build/reports/detekt/ in each project. +- Run Android Lint: `./gradlew lint`. It checks every module, with Dewfall's own checks from `:lint-rules` on main and test sources of every module of the app, but not on src/screenshotTest, which it can't read, and writes a report to build/reports/ in each of them. Any warning fails the build. In the app's plain Kotlin/JVM modules it also runs Animal Sniffer, which checks the code against the Android API at minSdk 29, because lint's own API check skips those modules. The lint checks' own tests run with `./gradlew :lint-rules:test`, which `./gradlew test` includes. - Run the pre-push gate: `python3 scripts/pre_push_gate.py`. It needs Python 3.9 or later, with no packages beyond its standard library. macOS has Python 3.9 with Xcode's Command Line Tools. `--no-build` skips the build for a quick look, and the gate then ends INCOMPLETE or FAIL, never PASS. -- Run every check that the pull request workflow runs: `./gradlew spotlessCheck detekt lint test assembleDebug`. The workflow is .github/workflows/pull-request.yml. It adds `--continue`, so one run reports every failing check, and `-Pandroid.builder.sdkDownload=false`, so a missing SDK package fails the build instead of being downloaded. After the build, the workflow fails if the build changed or added files in core/database/schemas/, so commit the schema files it writes. +- Run the screenshot tests: `./gradlew testDebugScreenshotTestDefaultTestSuite`. They render each screen's previews on the JVM and compare them with the reference images. The report goes to build/reports/tests/testDebugScreenshotTestDefaultTestSuite/ in the module. `./gradlew test` doesn't run them. +- Record the screenshot tests' reference images again: `./gradlew updateDebugScreenshotTestDefaultTestSuite`, after a change to a screen that you meant. Look at every changed image before you commit it, as docs/testing.md#screenshot-tests says. +- Check the screenshot test folders: `python3 scripts/scan_screenshot_tests.py`. It checks that they hold only one-call wrappers and reference images with no text in them. +- Run every check that the pull request workflow runs: `./gradlew spotlessCheck detekt lint test testDebugScreenshotTestDefaultTestSuite assembleDebug`, then `python3 scripts/scan_screenshot_tests.py`. The workflow is .github/workflows/pull-request.yml. It adds `--continue`, so one run reports every failing check, and `-Pandroid.builder.sdkDownload=false`, so a missing SDK package fails the build instead of being downloaded. After the build, the workflow fails if the build changed or added files in core/database/schemas/, so commit the schema files it writes. - Record the saved YouTube responses again: `./gradlew :core:youtube:recordYouTubeResponses`. It sends requests to YouTube, so run it only when docs/testing.md says to. `-PyoutubeSets=SEARCH_NASA,UPLOADS_NASA` records only the sets it names. If none of them names the machine's address and the network's country, the recorder also makes VIDEO_BIG_BUCK_BUNNY's call to learn them, and writes nothing of it. - Open the YouTube layer's debug screen: install a debug build with `./gradlew :app:installDebug`, then open "Dewfall debug" in the launcher. docs/testing.md says what to check, and how to check that release builds leave the screen out. - Run the live YouTube check by hand: `./gradlew :core:youtube:liveYouTubeCheck`. It sends requests to YouTube and googlevideo.com, so run it only when docs/testing.md says to. It logs its results and writes them to core/youtube/build/live-youtube-check/results.txt, and files no issue. To run the daily workflow now instead: `gh workflow run daily-youtube-check.yml`. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 8001eff..4aa8883 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -18,7 +18,7 @@ Read [docs/vision.md](docs/vision.md). It says what the app is and what it will - Fill in the sections of the [pull request template](.github/pull_request_template.md) in the pull request description. - A pull request is merged only when every CI check passes. - CodeRabbit, an AI code review service, can comment on a pull request. A member of the dewfallapp organization asks for a review by commenting `@coderabbitai review`. Its comments are advice, and it posts no check. Merging still follows the rules above and in AGENTS.md. Its settings are in [.coderabbit.yaml](.coderabbit.yaml). -- The pull request workflow runs the same checks as `./gradlew spotlessCheck detekt lint test assembleDebug`, the all-checks command in [AGENTS.md](AGENTS.md#commands). Run it before you push. The workflow also fails when the build changed or added Room schema files in core/database/schemas/, so commit the ones the build writes. +- The pull request workflow runs the same checks as `./gradlew spotlessCheck detekt lint test testDebugScreenshotTestDefaultTestSuite assembleDebug` and `python3 scripts/scan_screenshot_tests.py`, the all-checks commands in [AGENTS.md](AGENTS.md#commands). Run them before you push. The workflow also fails when the build changed or added Room schema files in core/database/schemas/, so commit the ones the build writes. A change to a screen changes its screenshot tests' images, which you record again and review, as [docs/testing.md](docs/testing.md#screenshot-tests) says. - Run `./gradlew spotlessApply` before you commit, so the Kotlin code and build scripts pass the formatting check. ## Commit messages diff --git a/build-logic/convention/build.gradle.kts b/build-logic/convention/build.gradle.kts index 3891788..d7f8570 100644 --- a/build-logic/convention/build.gradle.kts +++ b/build-logic/convention/build.gradle.kts @@ -34,6 +34,11 @@ gradlePlugin { id = "dewfall.android.compose" implementationClass = "io.github.dewfallapp.buildlogic.AndroidComposeConventionPlugin" } + register("androidScreenshots") { + id = "dewfall.android.screenshots" + implementationClass = + "io.github.dewfallapp.buildlogic.AndroidScreenshotsConventionPlugin" + } register("androidHilt") { id = "dewfall.android.hilt" implementationClass = "io.github.dewfallapp.buildlogic.AndroidHiltConventionPlugin" diff --git a/build-logic/convention/src/main/kotlin/io/github/dewfallapp/buildlogic/AndroidScreenshotsConventionPlugin.kt b/build-logic/convention/src/main/kotlin/io/github/dewfallapp/buildlogic/AndroidScreenshotsConventionPlugin.kt new file mode 100644 index 0000000..09c9438 --- /dev/null +++ b/build-logic/convention/src/main/kotlin/io/github/dewfallapp/buildlogic/AndroidScreenshotsConventionPlugin.kt @@ -0,0 +1,70 @@ +package io.github.dewfallapp.buildlogic + +import com.android.build.api.dsl.CommonExtension +import dev.detekt.gradle.extensions.DetektExtension +import org.gradle.api.Plugin +import org.gradle.api.Project +import org.gradle.api.artifacts.VersionCatalogsExtension +import org.gradle.api.tasks.testing.Test +import org.gradle.kotlin.dsl.configure +import org.gradle.kotlin.dsl.getByType +import org.gradle.kotlin.dsl.withType + +/** + * Screenshot tests of a module's previews, with Compose Preview Screenshot Testing in an AGP test + * suite. Apply it after dewfall.android.compose. The suite renders the @PreviewTest wrappers in + * src/screenshotTest/kotlin on the JVM, with Layoutlib, and compares them with the images in + * src/screenshotTestDefaultDebug/reference. See docs/testing.md#screenshot-tests. + */ +class AndroidScreenshotsConventionPlugin : Plugin { + override fun apply(target: Project) { + with(target) { + check(pluginManager.hasPlugin("org.jetbrains.kotlin.plugin.compose")) { + "dewfall.android.screenshots needs Compose. Apply dewfall.android.compose " + + "before it in $path." + } + + val libs = extensions.getByType().named("libs") + extensions.getByType().testOptions.screenshotTests.create(SUITE) { + engineVersion = libs.findVersion("screenshot").get().requiredVersion + targetVariants.add("debug") + dependencies { + implementation.add( + project.dependencies.platform( + libs.findLibrary("androidx-compose-bom").get(), + ), + ) + implementation.add(libs.findLibrary("androidx-compose-ui-tooling").get()) + implementation.add(libs.findLibrary("screenshot-validation-api").get()) + } + } + + // The images must not depend on the machine that renders them. ICU's ListFormatter + // and other formatting follow the JVM's default locale, so the suite's JVM gets the + // British English that the YouTube layer asks for (ADR 0009), and UTC. This covers the + // check task and the task that records the images. + tasks.withType().configureEach { + if (name.endsWith(TASK_SUFFIX)) { + systemProperty("user.language", "en") + systemProperty("user.country", "GB") + systemProperty("user.timezone", "UTC") + } + } + + // detekt reads only src/main and src/test by itself. Lint can't read this folder at + // all, so scripts/scan_screenshot_tests.py checks that it holds only one-call + // wrappers. See ADR 0007's note of November 21, 2026. + extensions.configure { source.from("src/$SUITE/kotlin") } + } + } + + private companion object { + const val SUITE = "screenshotTest" + + /** + * AGP 9.5.1 names the suite's tasks testDebugScreenshotTestDefaultTestSuite and + * updateDebugScreenshotTestDefaultTestSuite. + */ + const val TASK_SUFFIX = "ScreenshotTestDefaultTestSuite" + } +} diff --git a/docs/adr/0007-how-the-app-logs.md b/docs/adr/0007-how-the-app-logs.md index 3a76981..dc6027a 100644 --- a/docs/adr/0007-how-the-app-logs.md +++ b/docs/adr/0007-how-the-app-logs.md @@ -80,6 +80,8 @@ Each issue is an error, and nothing can suppress it. Lint reports @Suppress, @Su Any change to these exceptions updates this ADR in the same pull request, with a dated note here, the way [ADR 0008](0008-youtube-layer-contract.md) records #37's exception. +Note, November 21, 2026: #45 adds screenshot tests, whose @PreviewTest functions must sit in a module's src/screenshotTest folder. Lint can't read that folder: AGP 9.5.1's lint settings cover main, unit test, Android test and test fixture sources, and nothing else. A `println` planted there passed `./gradlew lint`. So the lint checks above don't reach src/screenshotTest, which this note records as a gap in where they run, not as a third exception. Nothing in that folder may log either. To keep the gap small, the previews and their made-up data stay in src/main, where lint checks them, and src/screenshotTest holds only wrappers whose body is one call to such a preview, such as `private fun ResultsScreenshot() = ResultsPreview()`. Two things guard the rules there instead of lint. scripts/scan_screenshot_tests.py, which the pre-push gate and the pull request workflow run, fails on any line in that folder that isn't a package line, a plain import, a comment, or a part of such a wrapper, so no call fits other than the wrapper's one call to a preview, and on any file there other than those wrappers and the reference images. The reviewer subagent checks the folder too. detekt reads it, for its style and Compose rules only, which cover none of the logging rules. The maintainer approved this on November 21, 2026: first "Thin wrappers + ADR note (Recommended)", then, asked again because that option had said detekt covered the folder, "Yes, with the CI check". [testing.md](../testing.md#screenshot-tests) explains the screenshot tests. + ### Why release builds keep warnings and errors Google's guidance prefers no logcat output at all in release builds. Dewfall keeps one part of its fallback instead: release builds keep warnings and errors. The app has no crash reporting. When a user reports a problem, the WARN and ERROR lines in logcat are what they can read with adb and share. diff --git a/docs/architecture.md b/docs/architecture.md index 3c5c1c6..bf028a6 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -125,14 +125,14 @@ The Search YouTube screen is the first feature. Its pair: | Module | Folder | Type | Namespace or package | What it holds | Depends on | |---|---|---|---|---|---| | `:feature:youtube-search-logic` | feature/youtube-search-logic/ | Kotlin/JVM | io.github.dewfallapp.feature.youtubesearch.logic | YouTubeSearchState, YouTubeSearchIntent, the reducer, the length label, the line-break functions, and their tests | `:core:mvi`, `:core:model`, both as api dependencies | -| `:feature:youtube-search-ui` | feature/youtube-search-ui/ | Android library | io.github.dewfallapp.feature.youtubesearch.ui | The Compose screen and its previews, YouTubeSearchViewModel and its tests, and string resources | `:feature:youtube-search-logic`, `:core:data`, `:core:designsystem`, `:core:model`, `:core:mvi` | +| `:feature:youtube-search-ui` | feature/youtube-search-ui/ | Android library | io.github.dewfallapp.feature.youtubesearch.ui | The Compose screen and its previews, the previews' screenshot tests in src/screenshotTest with their reference images, YouTubeSearchViewModel and its tests, and string resources | `:feature:youtube-search-logic`, `:core:data`, `:core:designsystem`, `:core:model`, `:core:mvi` | The video screen, which opens from a search result, is the second. Its pair: | Module | Folder | Type | Namespace or package | What it holds | Depends on | |---|---|---|---|---|---| | `:feature:player-logic` | feature/player-logic/ | Kotlin/JVM | io.github.dewfallapp.feature.player.logic | PlayerState, PlayerIntent, the reducer, the channel's initial, which errors offer "Try again", the start decision, the shared failure rule, the playback times' text, and their tests | `:core:mvi`, `:core:model`, both as api dependencies | -| `:feature:player-ui` | feature/player-ui/ | Android library | io.github.dewfallapp.feature.player.ui | PlayerRoute, the Compose screen and its previews, the video area and its playback status, PlayerViewModel and its tests, and string resources | `:feature:player-logic`, `:core:data`, `:core:designsystem`, `:core:model`, `:core:mvi`, `:core:playback`, media3-ui-compose and media3-common-ktx | +| `:feature:player-ui` | feature/player-ui/ | Android library | io.github.dewfallapp.feature.player.ui | PlayerRoute, the Compose screen and its previews, the previews' screenshot tests in src/screenshotTest with their reference images, the video area and its playback status, PlayerViewModel and its tests, and string resources | `:feature:player-logic`, `:core:data`, `:core:designsystem`, `:core:model`, `:core:mvi`, `:core:playback`, media3-ui-compose and media3-common-ktx | The modules are named player, because #42 to #44 add playback to the same screen. The service that plays media doesn't depend on any screen, so it lives in a core module of its own, `:core:playback`. See [The player](#the-player). @@ -141,7 +141,7 @@ The YouTube layer's debug screen has a pair of its own, which `:app` adds to deb | Module | Folder | Type | Namespace or package | What it holds | Depends on | |---|---|---|---|---|---| | `:feature:youtube-debug-logic` | feature/youtube-debug-logic/ | Kotlin/JVM | io.github.dewfallapp.feature.youtubedebug.logic | YouTubeDebugState, YouTubeDebugIntent, the reducer, the summaries of each answer, and their tests | `:core:mvi`, `:core:model`, both as api dependencies | -| `:feature:youtube-debug-ui` | feature/youtube-debug-ui/ | Android library | io.github.dewfallapp.feature.youtubedebug.ui | YouTubeDebugActivity, the Compose screen and its previews, YouTubeDebugViewModel and its tests, and string resources | `:feature:youtube-debug-logic`, `:core:designsystem`, `:core:model`, `:core:mvi`, `:core:youtube` | +| `:feature:youtube-debug-ui` | feature/youtube-debug-ui/ | Android library | io.github.dewfallapp.feature.youtubedebug.ui | YouTubeDebugActivity, the Compose screen and its previews, the previews' screenshot tests in src/screenshotTest with their reference images, YouTubeDebugViewModel and its tests, and string resources | `:feature:youtube-debug-logic`, `:core:designsystem`, `:core:model`, `:core:mvi`, `:core:youtube` | `:feature:youtube-debug-ui` is the only feature module that depends on `:core:youtube`, because its job is to call the layer's functions themselves. Every real feature reaches YouTube only through repositories in `:core:data`. @@ -162,7 +162,7 @@ Every module of the app applies one of three convention plugins from build-logic Another plugin, dewfall.detekt, holds the detekt settings and adds the compose-rules plugin to detekt. The four plugins above apply it, and so does the root project, to check the code in build-logic. -Android modules that use Compose, Hilt or Room also apply the matching plugins below, after dewfall.android.application or dewfall.android.library. Today `:app`, `:core:designsystem` and every feature's `-ui` module apply dewfall.android.compose, `:app`, `:core:data` and every feature's `-ui` module apply dewfall.android.hilt, and only `:core:database` applies dewfall.android.room. `:app` also applies Kotlin's serialization plugin, for its navigation keys. See [Navigation](#navigation). +Android modules that use Compose, Hilt or Room also apply the matching plugins below, after dewfall.android.application or dewfall.android.library. Today `:app`, `:core:designsystem` and every feature's `-ui` module apply dewfall.android.compose, `:app`, `:core:data` and every feature's `-ui` module apply dewfall.android.hilt, only `:core:database` applies dewfall.android.room, and every feature's `-ui` module applies dewfall.android.screenshots. `:app` also applies Kotlin's serialization plugin, for its navigation keys. See [Navigation](#navigation). `:app` also turns on BuildConfig, which AGP 8.0 and later generate only for modules that ask ([AGP 8.0.0](https://developer.android.com/build/releases/agp-8-0-0-release-notes)). The Hilt module that provides the logger reads BuildConfig.DEBUG to pick the lowest log level. See [Logging](#logging). @@ -171,6 +171,7 @@ Android modules that use Compose, Hilt or Room also apply the matching plugins b | dewfall.android.compose | The Compose compiler plugin, Compose turned on in the Android build, the Compose BOM, and the preview annotations, with the preview tooling in debug builds only. The module adds the Compose libraries it uses, such as Material 3. | | dewfall.android.hilt | KSP, the Hilt Gradle plugin, Hilt and Hilt's compiler, with KSP warnings failing the build | | dewfall.android.room | KSP, the Room Gradle plugin, Room and Room's compiler, with KSP warnings failing the build, and the module's schemas/ folder as the place where Room writes the database schemas | +| dewfall.android.screenshots | A screenshot test suite named screenshotTest for the debug variant, with the engine version from the catalog, the Compose BOM, ui-tooling and screenshot-validation-api. It pins the suite's JVM to the locale en-GB and the time zone UTC, and adds src/screenshotTest/kotlin to detekt's sources. Apply it after dewfall.android.compose. gradle.properties turns on the two experimental flags that the suites need. See [testing.md](testing.md#screenshot-tests). | The Compose compiler is part of Kotlin, so its plugin always has the Kotlin version, and it runs inside the Kotlin compiler that AGP's built-in Kotlin provides ([Compose compiler](https://developer.android.com/develop/ui/compose/compiler)). Compose 1.12 needs compileSdk 37 and AGP 9 ([compatibility](https://developer.android.com/develop/ui/compose/compiler#agp-compatibility)). @@ -205,11 +206,11 @@ Four tools check the code. AGENTS.md lists the commands that run them. **Formatting.** Spotless runs ktfmt in kotlinlang style, with 4-space indents and lines of up to 100 characters. It covers every Kotlin file and Kotlin build script in the repository. Its settings are in the root build.gradle.kts, because build-logic and the root build scripts belong to no module. Kotlin files use LF line endings, set in .gitattributes and in the Spotless settings. ktfmt doesn't read .editorconfig. The Kotlin section there comes from ktfmt and helps the IDE's own formatter come close to it. The roadmap first named ktlint. Its last stable release, 1.8.0 from November 2025, parses Kotlin 2.2. The ktlint organization took the project over from Pinterest and supports newer Kotlin only in 2.0 alphas, which moved to new Maven coordinates ([ktlint changelog](https://github.com/ktlint/ktlint/blob/master/CHANGELOG.md)). As of Spotless 8.11.0, Spotless can't load them, because it only knows the old coordinates ([KtLintStep.java](https://github.com/diffplug/spotless/blob/gradle/8.11.0/lib/src/main/java/com/diffplug/spotless/kotlin/KtLintStep.java)). -**detekt.** detekt runs its default rules, with the changes in config/detekt/detekt.yml, on every module and on build-logic. Any finding fails the build. Each module runs the plain `detekt` task, which doesn't need compiled code. So the rules that need type resolution don't run, such as InjectDispatcher, which would back the "inject dispatchers" rule in AGENTS.md. ForbiddenImport runs without it, and rejects imports of GlobalScope. It sees only imports, so the logging rules of [ADR 0007](adr/0007-how-the-app-logs.md) are left to [Dewfall's lint checks](#dewfalls-lint-checks), which resolve each call. Suppressing a detekt finding follows the rule for compiler warnings in [Build settings](#build-settings). An import finding can only be suppressed for a whole file, because an import can't carry an annotation, and no file does that. Two brace rules back the Kotlin style rule in AGENTS.md, and neither needs type resolution. BracesOnIfStatements flags an if or if/else that spans lines without braces. It keeps its default policies, singleLine 'never' and multiLine 'always'. The 'never' policy flags braces on a one-line if, which never happens here, because ktfmt puts every braced branch on lines of its own. MandatoryBracesLoops flags a for, while or do loop without braces whose body starts on a new line. BracesOnWhenStatements stays off. Once one branch of a when spans lines, none of its policies allows braces only on the branches that span lines. Android's Kotlin style guide allows a when to mix one-line branches without braces and longer branches with them ([braces](https://developer.android.com/kotlin/style-guide#braces)). So the build doesn't catch a one-line loop without braces, a one-line if with more than one else, a when branch that needs braces, or a forEach that should be a for loop. AGENTS.md's rule and the reviewer subagent in .claude/agents/ cover those. detekt's defaults read only src/main and src/test, and the convention plugin adds src/androidTest, for the emulator tests. Variant folders, such as src/debug, aren't checked. Composable functions are named in PascalCase, as the Compose API guidelines say, so FunctionNaming ignores functions annotated with @Composable ([detekt and Compose](https://github.com/detekt/detekt/blob/v2.0.0-alpha.6/website/docs/introduction/compose.mdx)). UnusedPrivateFunction and LongParameterList need type resolution, so they don't run yet. When type resolution is turned on, they need the same page's settings for private previews and for composables with many parameters. The build uses detekt 2.0.0-alpha.6, which is an alpha. The newest stable release, 1.23.8 from February 2025, was built for Kotlin 2.0.21, Gradle 8.12.1 and AGP 8.8.1 ([compatibility table](https://detekt.dev/docs/introduction/compatibility/)). It uses a Gradle method that Gradle 10 removes, and its maintainers plan no more 1.23 releases ([detekt#8452](https://github.com/detekt/detekt/issues/8452)). Support for AGP 9's built-in Kotlin came only in the 2.0 alphas ([detekt#8320](https://github.com/detekt/detekt/issues/8320)). 2.0.0-alpha.6 is built against Kotlin 2.4.10, Gradle 9.6.1 and AGP 9.3.1, close to this build's versions ([release notes](https://github.com/detekt/detekt/releases/tag/v2.0.0-alpha.6)). Rule names and settings may still change before 2.0.0, so read the release notes before each detekt update. +**detekt.** detekt runs its default rules, with the changes in config/detekt/detekt.yml, on every module and on build-logic. Any finding fails the build. Each module runs the plain `detekt` task, which doesn't need compiled code. So the rules that need type resolution don't run, such as InjectDispatcher, which would back the "inject dispatchers" rule in AGENTS.md. ForbiddenImport runs without it, and rejects imports of GlobalScope. It sees only imports, so the logging rules of [ADR 0007](adr/0007-how-the-app-logs.md) are left to [Dewfall's lint checks](#dewfalls-lint-checks), which resolve each call. Suppressing a detekt finding follows the rule for compiler warnings in [Build settings](#build-settings). An import finding can only be suppressed for a whole file, because an import can't carry an annotation, and no file does that. Two brace rules back the Kotlin style rule in AGENTS.md, and neither needs type resolution. BracesOnIfStatements flags an if or if/else that spans lines without braces. It keeps its default policies, singleLine 'never' and multiLine 'always'. The 'never' policy flags braces on a one-line if, which never happens here, because ktfmt puts every braced branch on lines of its own. MandatoryBracesLoops flags a for, while or do loop without braces whose body starts on a new line. BracesOnWhenStatements stays off. Once one branch of a when spans lines, none of its policies allows braces only on the branches that span lines. Android's Kotlin style guide allows a when to mix one-line branches without braces and longer branches with them ([braces](https://developer.android.com/kotlin/style-guide#braces)). So the build doesn't catch a one-line loop without braces, a one-line if with more than one else, a when branch that needs braces, or a forEach that should be a for loop. AGENTS.md's rule and the reviewer subagent in .claude/agents/ cover those. detekt's defaults read only src/main and src/test, and the convention plugin adds src/androidTest, for the emulator tests. Variant folders, such as src/debug, aren't checked. dewfall.android.screenshots adds src/screenshotTest/kotlin, where the screenshot tests' wrappers are. Composable functions are named in PascalCase, as the Compose API guidelines say, so FunctionNaming ignores functions annotated with @Composable ([detekt and Compose](https://github.com/detekt/detekt/blob/v2.0.0-alpha.6/website/docs/introduction/compose.mdx)). UnusedPrivateFunction and LongParameterList need type resolution, so they don't run yet. When type resolution is turned on, they need the same page's settings for private previews and for composables with many parameters. The build uses detekt 2.0.0-alpha.6, which is an alpha. The newest stable release, 1.23.8 from February 2025, was built for Kotlin 2.0.21, Gradle 8.12.1 and AGP 8.8.1 ([compatibility table](https://detekt.dev/docs/introduction/compatibility/)). It uses a Gradle method that Gradle 10 removes, and its maintainers plan no more 1.23 releases ([detekt#8452](https://github.com/detekt/detekt/issues/8452)). Support for AGP 9's built-in Kotlin came only in the 2.0 alphas ([detekt#8320](https://github.com/detekt/detekt/issues/8320)). 2.0.0-alpha.6 is built against Kotlin 2.4.10, Gradle 9.6.1 and AGP 9.3.1, close to this build's versions ([release notes](https://github.com/detekt/detekt/releases/tag/v2.0.0-alpha.6)). Rule names and settings may still change before 2.0.0, so read the release notes before each detekt update. **detekt's Compose rules.** detekt also runs [compose-rules](https://github.com/mrmans0n/compose-rules) 0.6.7, a detekt plugin with rules for Compose code, such as "a public composable that emits UI takes a modifier parameter". dewfall.detekt adds it, so it checks every module and build-logic. The Compose section of config/detekt/detekt.yml lists every rule, as compose-rules' docs recommend ([detekt setup](https://github.com/mrmans0n/compose-rules/blob/v0.6.7/docs/detekt.md#enabling-rules)). The docs leave the four opt-in rules off. Three of them stay off: ComposableNestingDepth, PreviewNaming and UnstableCollections. Material2 is on, because it enforces the Material 3 rule in AGENTS.md. It flags any use of Material 2, the androidx.compose.material package, but not the icons in androidx.compose.material.icons, which the rule always allows. Every other rule is on. [rules.md](https://github.com/mrmans0n/compose-rules/blob/v0.6.7/docs/rules.md) explains each rule. Eight rules need type resolution, so they don't run yet: ConditionHoist, InvalidReadOnlyComposable, MissingNonRestartableComposable, MissingReadOnlyComposable, StaleRememberUpdatedStateInRemember, UnnecessaryComposable, UnnecessaryLaunchedEffect and VarsWithoutStateBacking. compose-rules' ComposableNaming checks the names of composable functions, which detekt's FunctionNaming skips. Each compose-rules release is built for one detekt version, and 0.6.7 is built for detekt 2.0.0-alpha.6 ([supported versions](https://github.com/mrmans0n/compose-rules/blob/v0.6.7/docs/detekt.md#supported-versions-matrix)). So each detekt update has to wait for a compose-rules release built for the new detekt version, and both versions change in the same pull request. Renovate puts both in one pull request, which waits for the maintainer's approval ([testing.md](testing.md#dependency-updates)). -**Android Lint.** Lint checks every module, the plain Kotlin/JVM ones through the com.android.lint plugin. It also runs [Dewfall's lint checks](#dewfalls-lint-checks) on main and test sources. Any warning fails the build. Each module checks only its own code. The checks that look up versions or library data on the network are off, so lint gives the same result on every run. AndroidLint.kt in build-logic lists them. Renovate's pull requests bring new versions instead ([testing.md](testing.md#dependency-updates)). The app's manifest suppresses two checks until the tasks that fix them are done: DataExtractionRules (#68) and MissingApplicationIcon (#120). Lint also runs the checks that libraries ship in their AARs. Compose BOM 2026.09.00 brings Lifecycle 2.9.4 into `:core:designsystem`. The checks in lifecycle-runtime 2.9.4's lint.jar call `KtLightModifierList.getKotlinOrigin()`, which the Kotlin compiler in AGP 9.5's lint no longer has. Lint then skips UnsafeLifecycleWhenUsage and RepeatOnLifecycleWrongUsage and reports ObsoleteLintCustomCheck, which fails the build, as it did on November 20, 2026. So a constraint in that module raises Lifecycle to the catalog's version, whose checks load, and which the app ships anyway. Lifecycle's lint checks stopped making that call in May 2025 ([androidx 5a836f5](https://github.com/androidx/androidx/commit/5a836f50695c2e8ad93c363ceb42e97ca29f03f8)), and the first release line with the change is 2.10.0, from its first alpha in July 2025 to its stable release in November 2025. The 2.9 line kept the old call, up to 2.9.4 in September 2025 ([Lifecycle releases](https://developer.android.com/jetpack/androidx/releases/lifecycle)). So the constraint can go once Compose brings 2.10.0 or later on its own. `./gradlew -q :core:designsystem:dependencies --configuration debugRuntimeClasspath` shows the version it brings. +**Android Lint.** Lint checks every module, the plain Kotlin/JVM ones through the com.android.lint plugin. It also runs [Dewfall's lint checks](#dewfalls-lint-checks) on main and test sources. Lint can't read the screenshot test folders, src/screenshotTest, which hold only one-call wrappers that scripts/scan_screenshot_tests.py checks instead, as [ADR 0007](adr/0007-how-the-app-logs.md#the-lint-checks)'s note of November 21, 2026 says. Any warning fails the build. Each module checks only its own code. The checks that look up versions or library data on the network are off, so lint gives the same result on every run. AndroidLint.kt in build-logic lists them. Renovate's pull requests bring new versions instead ([testing.md](testing.md#dependency-updates)). The app's manifest suppresses two checks until the tasks that fix them are done: DataExtractionRules (#68) and MissingApplicationIcon (#120). Lint also runs the checks that libraries ship in their AARs. Compose BOM 2026.09.00 brings Lifecycle 2.9.4 into `:core:designsystem`. The checks in lifecycle-runtime 2.9.4's lint.jar call `KtLightModifierList.getKotlinOrigin()`, which the Kotlin compiler in AGP 9.5's lint no longer has. Lint then skips UnsafeLifecycleWhenUsage and RepeatOnLifecycleWrongUsage and reports ObsoleteLintCustomCheck, which fails the build, as it did on November 20, 2026. So a constraint in that module raises Lifecycle to the catalog's version, whose checks load, and which the app ships anyway. Lifecycle's lint checks stopped making that call in May 2025 ([androidx 5a836f5](https://github.com/androidx/androidx/commit/5a836f50695c2e8ad93c363ceb42e97ca29f03f8)), and the first release line with the change is 2.10.0, from its first alpha in July 2025 to its stable release in November 2025. The 2.9 line kept the old call, up to 2.9.4 in September 2025 ([Lifecycle releases](https://developer.android.com/jetpack/androidx/releases/lifecycle)). So the constraint can go once Compose brings 2.10.0 or later on its own. `./gradlew -q :core:designsystem:dependencies --configuration debugRuntimeClasspath` shows the version it brings. **The Android API check.** The plain Kotlin/JVM modules compile and run their tests against the full JDK, so a call to a Java API that Android 10 lacks passes there and fails on a phone ([ADR 0006](adr/0006-platform-and-android-versions.md)). Lint can't catch this in these modules. AGP runs lint one module at a time, and lint's API check skips any module that isn't Android ([ApiDetector](https://android.googlesource.com/platform/tools/base/+/refs/heads/mirror-goog-studio-main/lint/libs/lint-checks/src/main/java/com/android/tools/lint/checks/ApiDetector.kt)). So [Animal Sniffer](https://github.com/xvik/gradle-animalsniffer-plugin) checks each of these modules' compiled classes against a [Gummy Bears](https://github.com/open-toast/gummy-bears) signature of the Android API. The signature's API level comes from the minSdk in build-logic, so the check follows it. `./gradlew lint` runs it too. @@ -228,7 +229,7 @@ That last point matters for Kotlin's string templates, such as the toString of a `:lint-rules` holds Dewfall's own lint checks, which enforce the logging rules of [ADR 0007](adr/0007-how-the-app-logs.md). The ADR lists the five issues and the two exceptions. Lint runs them on every module of the app, because the three module plugins add `:lint-rules` to each module's `lintChecks` configuration ([Add build dependencies](https://developer.android.com/build/dependencies)). That configuration only feeds lint, so nothing from `:lint-rules` reaches the app. `./gradlew :app:dependencies --configuration releaseRuntimeClasspath` doesn't list it, and neither does the debug classpath. - **Why lint and not detekt.** This build runs detekt without type resolution, so detekt sees only names and imports. Lint resolves each call, so it catches a fully qualified call, an import alias and a callable reference such as `Log::println`. -- **Test sources.** Lint skips test sources by default, except for issues that ask for them ([Lint](https://developer.android.com/reference/tools/gradle-api/9.5/com/android/build/api/dsl/Lint)). Each Dewfall issue asks for them, so it runs on src/test, where the recorder of saved YouTube responses and the live YouTube check live. The build leaves `checkTestSources` off, so lint's own checks still skip tests. AGP already analyzes each module's tests in a task of its own, such as lintAnalyzeJvmTest, so no task is added. +- **Test sources.** Lint skips test sources by default, except for issues that ask for them ([Lint](https://developer.android.com/reference/tools/gradle-api/9.5/com/android/build/api/dsl/Lint)). Each Dewfall issue asks for them, so it runs on src/test, where the recorder of saved YouTube responses and the live YouTube check live. AGP's lint has no setting for screenshot test sources, so no Dewfall issue runs on src/screenshotTest. A `println` planted there passed `./gradlew lint` with AGP 9.5.1 on November 21, 2026. That folder holds only one-call wrappers, which scripts/scan_screenshot_tests.py checks, as [testing.md](testing.md#screenshot-tests) explains. The build leaves `checkTestSources` off, so lint's own checks still skip tests. AGP already analyzes each module's tests in a task of its own, such as lintAnalyzeJvmTest, so no task is added. - **Nothing can suppress them.** Each issue has an empty list of suppress names, as "Can I make my lint check not suppressible?" in lint's [FAQ](https://github.com/googlesamples/android-custom-lint-rules/blob/5751b4f0b7d6c5af67b990e7e06571179baa1e07/docs/api-guide/faq.md.html) describes. Lint then reports @Suppress, @SuppressLint, `//noinspection` and a `disable` setting for the issue as errors of their own, and ignores the issue in lint.xml, in a severity setting and in `checkOnly`. The two exceptions live in LogWriterClass.kt, and each allows only what its writer needs: Log.println in LogcatWriter, and standard output in ConsoleLogWriter. Changing them updates ADR 0007 in the same pull request. - **@ConstantText.** `:core:logging` marks Logger's messages, withTag's area and every LogField name with @ConstantText. DewfallLogTextNotConstant finds the arguments through lint's annotation handling, which maps named arguments and reads the annotation from compiled classes, as `:core:youtube` sees `:core:logging`. A function that passes its own String parameter on as log text marks it too, such as ResultField in the live YouTube check, and its callers are checked instead. - **Versions.** Lint's libraries add 23 to AGP's major version, so AGP 9.5.1 comes with lint 32.5.1 ([custom lint rules](https://github.com/googlesamples/android-custom-lint-rules/blob/5751b4f0b7d6c5af67b990e7e06571179baa1e07/README.md#lint-version)). dewfall.lint.rules derives lint-api's and lint-tests' version from the catalog's AGP version, so they have no catalog entry, and Renovate's AGP update moves them too. The issue registry reports lint's current API level, so lint never calls the checks out of date. diff --git a/docs/testing.md b/docs/testing.md index ade64c9..a8b9741 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -16,7 +16,7 @@ Fast tests run on every change. They cover: - The theme against the design tokens. [architecture.md](architecture.md#the-theme) explains the check. - Dewfall's lint checks, with lint-tests. See [Dewfall's lint checks](#dewfalls-lint-checks). - Background jobs. -- Screenshot tests of each screen, in light, dark and large font. +- Screenshot tests of each screen, in light, dark and large font, and in dynamic color with a fixed wallpaper. See [Screenshot tests](#screenshot-tests). Unit tests never touch the network. @@ -40,13 +40,13 @@ The project uses four GitHub Actions workflows, plus Renovate's weekly update pu ### The pull request workflow -Workflow 1 is .github/workflows/pull-request.yml. Today it runs one job, Checks, with the all-checks command from [AGENTS.md](../AGENTS.md#commands): formatting, detekt, Android Lint with the Android API check, unit tests, and a debug build. After the build, it checks that the Room schemas are committed. Screenshot tests join it when the task that adds them is done. Database migration tests need an emulator, so the task that adds them decides which workflow runs them. +Workflow 1 is .github/workflows/pull-request.yml. Today it runs one job, Checks, with the all-checks command from [AGENTS.md](../AGENTS.md#commands): formatting, detekt, Android Lint with the Android API check, unit tests, [screenshot tests](#screenshot-tests), and a debug build. After the build, it checks that the Room schemas are committed, and runs scripts/scan_screenshot_tests.py on the screenshot test folders. Database migration tests need an emulator, so the task that adds them decides which workflow runs them. - It also runs on every push to main. Those runs fill the Gradle cache, which pull request runs and the other workflows only read. Workflow 2 runs the emulator tests, as [The emulator tests workflow](#the-emulator-tests-workflow) describes. The nightly APK isn't built yet. - It adds `--continue` to the command, so one run reports every failing check. - It installs the Android SDK packages the build needs, and turns off AGP's automatic SDK downloads, so a missing package fails the build. - After the Gradle command, a step fails when the build changed or added files in core/database/schemas/. It runs even when the Gradle command failed. See [Database migration tests](#database-migration-tests). -- When the job fails, it uploads the build/reports/ folder of every project as an artifact called reports, kept for 7 days. +- When the job fails, it uploads the build/reports/ folder of every project as an artifact called reports, kept for 7 days. The artifact also holds each module's build/intermediates/debug/testDebugScreenshotTestDefaultTestSuite/results/ folder, with the new and diff images of the screenshot tests, which their report names but doesn't hold. - It caches Gradle with setup-gradle's basic caching, which is MIT licensed, because the default, enhanced caching, loads a proprietary component ([DISTRIBUTION.md](https://github.com/gradle/actions/blob/v6.4.0/DISTRIBUTION.md)). - A repository ruleset named main protects the branch. It requires a pull request, allows only merge commits, and requires the check named Checks to pass on a branch that's up to date with main. It blocks force pushes and deletion, and nobody can bypass it, maintainers included. The ruleset requires the check by its name, so renaming the job blocks merging until the ruleset is updated. - The repository allows only GitHub's own actions and gradle/actions/setup-gradle, and requires every action to be pinned to a full commit SHA. A new action needs the allow list changed in the repository settings first. @@ -196,6 +196,7 @@ In a public repository, GitHub turns off scheduled workflows when the repository - **Pre-releases.** Renovate offers a pre-release only when the current version is a pre-release with the same major, minor and patch numbers. So detekt moves from one 2.0.0 alpha to the next or to 2.0.0, and every other dependency gets stable releases only ([ignoreUnstable](https://docs.renovatebot.com/configuration-options/#ignoreunstable)). - **Titles.** Gradle updates start with "build:" and Actions updates with "ci:", as the commit message rule in AGENTS.md asks. - **Up to date with main.** The ruleset requires a branch that's up to date with main, and Renovate rebases its open pull requests when main moves. To rebase one now, tick the rebase box in its description. Don't press "Update branch". Renovate would then treat the pull request as edited by someone else and stop updating it. +- **Screenshot images.** An update of the Compose BOM, Media3, AGP or the screenshot engine can change how the screens render, so the screenshot tests fail with no change to the app. renovate.json gives those pull requests a note. Read each changed image in the report. If the change comes from the update and every screen still looks right, record the images again on the Mac, as [Screenshot tests](#screenshot-tests) says, and push them to Renovate's branch, which then shows under "PR Edited (Blocked)", as the next item describes. Renovate offers the engine only as 0.0.1-alphaNN versions, because it is a pre-release, and an engine version may need a newer AGP. - **Fixing a pull request.** Some updates need a change before Checks passes. A ktfmt update can change the formatting, a Kotlin or library update can deprecate an API the code uses, an AGP update can need new build tools, and a NewPipeExtractor update can need the saved YouTube responses recorded again. Push the fix to Renovate's branch. Renovate then leaves the branch alone and lists it under "PR Edited (Blocked)" on the Dependency Dashboard. For ktfmt and AGP updates, the pull request's description names the usual fix. - **Keeping a fixed pull request up to date.** You can't bring Renovate's commit up to date yourself. Merging main adds a merge commit, which the [pre-push gate](#the-pre-push-gate) rejects, and the gate exempts Renovate's commits from its identity rule only while they sit unchanged on the remote branch, so a Renovate commit that you rebased yourself fails it. Instead, tick the pull request's box under "PR Edited (Blocked)" on the Dependency Dashboard, or the rebase box in its description, which Renovate's notice on an edited pull request points at. Either one asks for the rebuild ([branch/index.ts](https://github.com/renovatebot/renovate/blob/44.140.0/lib/workers/repository/update/branch/index.ts#L363)). Renovate then rebuilds its commit on main and drops the fix, so push the fix again, as in #188, the AGP 9.5.1 update. - **A pull request that Renovate won't rebase.** You can open a pull request early from "Pending Status Checks", either under AGENTS.md's security exception or for a NewPipeExtractor breakage fix, which often needs the saved responses recorded again. Renovate doesn't rebase it while its `renovate/stability-days` check is pending, so it falls behind main. Renovate's code lets only an unpend request override pending checks, not a rebase request ([branch/index.ts](https://github.com/renovatebot/renovate/blob/44.140.0/lib/workers/repository/update/branch/index.ts#L314-L315)). So tick the pull request's box under "Pending Status Checks" again, the same box that opened it. If the pull request already carries a fix, such as newly recorded saved responses, Renovate may rebuild the branch and drop it, so push the fix again. As of November 20, 2026, nobody has tried this on a pull request that already exists, so if the box does nothing, make the same update as your own commit in a new pull request and merge that one. Then close Renovate's pull request by hand, and put no closing word before its number in the new description. #195 replaced #191, the Gradle 9.9.2 update, this way. @@ -216,6 +217,8 @@ Run these from the repository root. AGENTS.md lists the command that runs every | Every unit test | `./gradlew test` | | One plain Kotlin/JVM module's tests | `./gradlew :core:mvi:test` | | One Android module's tests | `./gradlew :core:data:testDebugUnitTest` | +| The screenshot tests | `./gradlew testDebugScreenshotTestDefaultTestSuite`. `./gradlew test` doesn't run them. | +| The screenshot tests of one module | `./gradlew :feature:player-ui:testDebugScreenshotTestDefaultTestSuite` | | One test class | Add `--tests` with the class name, such as `./gradlew :core:mvi:test --tests "io.github.dewfallapp.core.mvi.counter.CounterReducerTest"` | | The emulator tests, on one emulator or phone | `ANDROID_SERIAL= ./gradlew :app:connectedDebugAndroidTest`. See [Running them](#running-them). | @@ -225,7 +228,7 @@ Each module writes an HTML report to build/reports/tests/test/index.html in a pl - Use kotlin.test's annotations and assertions, such as kotlin.test.Test, BeforeTest, AfterTest and assertEquals. They run on JUnit 6 in plain Kotlin/JVM modules and on JUnit 4 in Android modules, so a test reads the same in both. [architecture.md](architecture.md#build-settings) explains why there are two. - Name each local test in src/test/ with backticks, as a sentence about what it checks, such as `` `increment adds one` ``. detekt's naming rule skips test folders. Don't do this in src/androidTest/: Android runs method names with spaces only from API level 30, and the minimum is 29 ([Kotlin coding conventions](https://kotlinlang.org/docs/coding-conventions.html#names-for-test-methods)). -- Put tests in the src/test/ folder of the module whose code they test. +- Put tests in the src/test/ folder of the module whose code they test. Screenshot tests are the exception: their wrappers go in src/screenshotTest/kotlin/, as [Screenshot tests](#screenshot-tests) says. ### Reducers @@ -257,7 +260,7 @@ A class that logs receives a Logger in its constructor, as [architecture.md](arc - Check log lines only where logging is the behavior under test, such as a warning that a class must write when a retry fails. Compare the message and the fields, not stack frames, which change whenever the code moves. - Tests never read logcat. LogcatWriter's own tests pass a function in place of Log.println, because android.util.Log has no working code in local unit tests. -- Tests follow the logging rules too. Lint checks test sources with Dewfall's checks, so a println, a printStackTrace or a message built from a template fails `./gradlew lint` in a test as well. Only ConsoleLogWriter, in `:core:youtube`'s tests, writes to standard output, and it never writes to standard error. See [Dewfall's lint checks](#dewfalls-lint-checks). +- Tests follow the logging rules too. Lint checks test sources with Dewfall's checks, so a println, a printStackTrace or a message built from a template fails `./gradlew lint` in a test as well. Lint can't read the screenshot test folders, src/screenshotTest, so scripts/scan_screenshot_tests.py checks them instead. Only ConsoleLogWriter, in `:core:youtube`'s tests, writes to standard output, and it never writes to standard error. See [Dewfall's lint checks](#dewfalls-lint-checks). ## Dewfall's lint checks @@ -704,7 +707,7 @@ scripts/pre_push_gate.py checks every commit that a push would send, before the python3 scripts/pre_push_gate.py ``` -It fetches origin, then checks every commit in origin/main..HEAD, not just the last one, then the build. It ends with PASS only when every check passed. It prints the names of the rules that failed, with each commit's hash and subject, and never an identity or a value it found. +It fetches origin, then checks every commit in origin/main..HEAD, not just the last one, then the build. Two of its checks run scans of their own: scripts/scan_saved_responses.py on the saved YouTube responses, and scripts/scan_screenshot_tests.py on the screenshot test folders. It ends with PASS only when every check passed. It prints the names of the rules that failed, with each commit's hash and subject, and never an identity or a value it found. | Check | Fails when | |---|---| @@ -714,6 +717,7 @@ It fetches origin, then checks every commit in origin/main..HEAD, not just the l | Messages | A subject doesn't start with one of the conventional types in AGENTS.md, a message has a trailer, such as a co-author line, or a closing word, such as "closes", comes before an issue's number or link. The pull request's description closes issues, never a commit. | | Secrets | A commit adds or changes a local.properties, .env, keystore or key file, or a line with a private key, a GitHub token, an AWS access key or a Google API key. | | Saved responses | A commit changes core/youtube/src/test/resources/youtube/, and its own copy of the folder fails the scan below. | +| Screenshot tests | A commit adds or changes a file in a src/screenshotTest* folder, and its own copy of those folders fails scripts/scan_screenshot_tests.py. See [Screenshot tests](#screenshot-tests). | | Nothing uncommitted | The folder has a change or a file that no commit holds, which the build would check although the push doesn't send it. | | The build | The pull request workflow's command, with `--continue` and `-Pandroid.builder.sdkDownload=false`, fails, or changes a file, such as a Room schema. | @@ -740,7 +744,94 @@ It reads every file, with JSON's `\uXXXX` and `\/` escapes undone, then decodes ## Screenshot tests -TODO +Screenshot tests render each screen's previews and compare them, pixel for pixel, with reference images committed in the repository. They run on the computer's JVM, with no emulator. Google's [Screenshot testing](https://developer.android.com/training/testing/ui-tests/screenshot) page calls screenshot testing "the recommended way to verify visual attributes in Compose UIs". + +### The tool + +The tests use Google's Compose Preview Screenshot Testing, through the screenshot test suites that AGP 9.5.1 has built in ([Screenshot testing with test suites](https://developer.android.com/studio/preview/compose-screenshot-testing-with-testsuites)). The suite renders previews with Layoutlib, the renderer of Android Studio's previews. It needs no Gradle plugin of its own. The standalone plugin is the older way: its own page says it is "no longer maintained", and the test-suites page calls it "deprecated". These facts were checked on November 21, 2026. + +- **The engine.** The suite runs engine 0.0.1-alpha17, whose version is `screenshot` in gradle/libs.versions.toml, shared with the @PreviewTest annotation's artifact, screenshot-validation-api. It is an alpha. Google's [release notes](https://developer.android.com/studio/preview/compose-screenshot-testing-release-notes) stopped at alpha16 on November 21, 2026, so alpha17's changes are unlisted. Its POM's Last-Modified header on Google's Maven repository says October 30, 2026. Every artifact it brings is test only, and none ships. The maintainer approved it on November 21, 2026, for #45. +- **Guava.** The engine's classpath has Guava 33.4.0-jre, which has the high-severity advisory [GHSA-xxph-c9ww-hj94](https://github.com/advisories/GHSA-xxph-c9ww-hj94), fixed in 33.7.2 (checked on November 21, 2026). The advisory is about deserializing untrusted data, which a test of our own previews doesn't do, and AGP's own build classpath runs the same version (`./gradlew buildEnvironment`). The maintainer accepted it on November 21, 2026, with no constraint. The constraint in `:core:playback` covers the app that ships. +- **The flags.** gradle.properties turns on `android.experimental.enableScreenshotTest` and `android.experimental.testSuiteSupport`, which the suites need. Each build prints a warning that they are experimental. +- **The task names.** AGP 9.5.1 names the tasks `testDebugScreenshotTestDefaultTestSuite` and `updateDebugScreenshotTestDefaultTestSuite`. The test-suites page gives the pattern `test{SuiteName}{Target}{Variant}TestSuite`, which is a different order (checked on November 21, 2026). If an AGP update renames them, renovate.json's note lists every file that names them. +- **The setup.** The convention plugin dewfall.android.screenshots creates the suite, named screenshotTest, for the debug variant, and the three `-ui` modules apply it. [architecture.md](architecture.md#build-settings) describes it. +- **Android Studio.** The test-suites page says Studio runs and records these tests from Android Studio Rabbit 1 Canary 4 on. Whether Studio shows the previews through the wrappers in src/screenshotTest, now that the previews in src/main have no @Preview, is still to be confirmed in a real Studio. + +### What gets tested + +Each `-ui` module's previews file in src/main, such as YouTubeSearchPreviews.kt, holds internal preview functions with made-up data and a fixed clock. The module's src/screenshotTest/kotlin/ folder holds one wrapper for each of them, in a file such as YouTubeSearchScreenshots.kt: + +```kotlin +@PreviewTest +@Preview(name = "Light") +@Preview( + name = "Dark", + uiMode = Configuration.UI_MODE_NIGHT_YES or Configuration.UI_MODE_TYPE_NORMAL, +) +@Preview(name = "LargeFont", fontScale = 2f) +@Composable +private fun ResultsScreenshot() = ResultsPreview() +``` + +Each @Preview annotation makes one image. Every screen has a light, a dark and a large font image (font scale 2) of at least one state, and each state keeps the variants its previews had before the tests, so the images stay few, as Google's page advises. The previews' names have no spaces, because the engine puts them in the images' file names. + +**Why wrappers.** Lint can't read src/screenshotTest, so Dewfall's lint checks of the logging rules don't reach it. The previews' code stays in src/main, where lint reads it, and the wrappers hold no code beyond their one call to a preview. scripts/scan_screenshot_tests.py, which the pre-push gate and the pull request workflow run, checks that every file there is such a wrapper, and fails on anything else. It allows only a package line, plain imports, `//` comments, and wrappers whose function is exactly `private fun Screenshot() = Preview()`, written either one part to a line or all on one line, as ktfmt writes one that fits. The only other files it allows are the reference images. detekt reads the folder for its style and Compose rules. [ADR 0007](adr/0007-how-the-app-logs.md#the-lint-checks)'s note of November 21, 2026 records this. + +**Dynamic color.** On a phone, dynamic color comes from the wallpaper, so a test can't use it. The previews pass `DewfallTheme(dynamicColor = false)`, so the light, dark and large font images show Dewfall's own palette and don't depend on Layoutlib's default wallpaper. Each screen's main state also has a preview with dynamic color on, whose wrapper makes a DynamicLight and a DynamicDark image with `wallpaper = Wallpapers.BLUE_DOMINATED_EXAMPLE`, as ThemePreviews.kt does. Layoutlib turns that fixed wallpaper into a fixed palette, and a color that a screen hardcodes stands out against the blue. + +**The same image on every machine.** A test fails on any pixel that differs, so nothing in an image may depend on the machine or the moment: + +- The suite's JVM runs with the locale en-GB and the time zone UTC, which dewfall.android.screenshots sets on the check task and the recording task. Without them, the debug screen's list of counts, which ICU's ListFormatter joins, read "LIVE: 0, and UPCOMING: 0" on a Mac set to US English and "LIVE: 0 and UPCOMING: 0" in British English. +- The previews pass a fixed clock to the screens. +- The video screen's made-up player holds its position with `PositionSupplier.getConstant`. Given a plain number, SimpleBasePlayer moves a playing position on with the clock, and the first images showed the Mac's uptime as the position. +- The search field has focus, and a cursor blinks with the clock, so the Search YouTube previews turn blinking off with `LocalCursorBlinkEnabled`. + +A difference in text or content, such as a word, a comma, a moved element or an indicator's frame, is never settled with a tolerance. It means something like the above is still unfixed, and the fix goes there. + +**What the images can't show.** Layoutlib draws no system bars, even with `showSystemUi = true`, so the images can't show whether text sits under them. The insets stay checked by hand on a phone. The video area draws nothing in Layoutlib, so it shows as an empty box. + +### Running them + +```bash +./gradlew testDebugScreenshotTestDefaultTestSuite +``` + +Add a module's path to run one module's tests, such as `./gradlew :feature:player-ui:testDebugScreenshotTestDefaultTestSuite`. `./gradlew test` doesn't run them. The pull request workflow and the pre-push gate do. The report goes to build/reports/tests/testDebugScreenshotTestDefaultTestSuite/index.html in each module. + +### Recording and updating the images + +After a change to a screen that you meant, record its images again: + +```bash +./gradlew updateDebugScreenshotTestDefaultTestSuite +``` + +```bash +python3 scripts/scan_screenshot_tests.py +``` + +The images go to src/screenshotTestDefaultDebug/reference/ in each module, in a folder for the wrapper file under the package's folders, named after the wrapper, the preview's name and a hash of its settings, such as feature/youtube-search-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/youtubesearch/ui/YouTubeSearchScreenshotsKt/ResultsScreenshot_Light_b29dc7a7_0.png. Then: + +1. Before you commit, look at every changed image: `git status` lists them, and your image viewer opens them. A change you didn't mean is a bug to fix, not an image to commit. After the push, GitHub shows each image's old and new versions side by side in the pull request, for the review. +2. Check that the scan above passed. It fails on any chunk of a PNG file other than the image data, such as text or a time, and on image data whose zlib stream holds anything beyond the pixels that IHDR describes, so no image carries the name of the machine or a folder. The engine writes only the IHDR, IDAT and IEND chunks, in 8-bit RGBA that isn't interlaced. +3. Commit the images with the change that caused them. + +To add a screen or a state, add an internal preview to the previews file in src/main, then a wrapper in src/screenshotTest, then record. Renaming a wrapper or a preview's name changes the image's file name, so record again and delete the old image. Add a preview only when it shows something the others don't. The images take about 4 MB today, and every recording of a changed image adds a whole new copy to Git's history, which the folders' size doesn't show. If the folders pass 20 MB, or the history's PNG objects grow fast, such as after Renovate updates of the Compose BOM, Media3 or AGP, revisit this: fewer variants, or Git LFS, as Google's page suggests. + +### When a test fails + +The task often prints "WARN: Slow render action 0/3" with a TimeoutException's stack trace, when Layoutlib takes a while on a busy machine. It is a warning, and the test still passes or fails on its image alone, so it isn't a failure by itself. The task's output names each image that didn't match, with its difference as a percentage, and the paths of the reference, new and diff images. The new and diff images are in the module's build/intermediates/debug/testDebugScreenshotTestDefaultTestSuite/results/ folder. In CI, the reports artifact holds both, as [The pull request workflow](#the-pull-request-workflow) says. + +1. Look at the diff image and the new image. +2. If the screen changed by mistake, fix the code. +3. If the change is one you meant, record the images again, as above. +4. If the app didn't change at all, look for what else did: an update of a library, the JDK, macOS or the Mac itself can move pixels, as Google's page warns. Read the diff. Record again only when the app is unchanged and the new image is right, and say in the pull request why the images changed. + +### The Mac and Linux + +The images are recorded on a Mac with Apple silicon, and the pull request workflow checks them on Ubuntu on x86-64. Google's page warns that the two can render differently. The suite sets no tolerance, so the check stays pixel for pixel. Any tolerance above zero, set with `imageDifferenceThreshold` in dewfall.android.screenshots, needs the maintainer's approval first. It is a fraction, so 0.0001f allows 0.01 percent of the pixels to differ. A real change can be that small: one digit of the position text is about 0.008 percent of a phone image. Recording the images only on Linux instead, which Google's page calls taking screenshots on a server, would fail the gate on the Mac whenever the two render differently, because the gate runs the same check. While they match, as below, images recorded on either one pass on both. + +On November 21, 2026, #45's first run on the runners ([run 44936455307](https://github.com/dewfallapp/dewfall/actions/runs/44936455307), on an earlier push of #45, commit 755fe20, ubuntu-26.04) matched all 41 images recorded on the Mac pixel for pixel, so no tolerance was needed. The images didn't change after that push, and every later run of the pull request workflow on #45 that finished passed the same check. Layoutlib's text and shapes come out the same on both. Its native code comes from a file of layoutlib-runtime for each system, such as layoutlib-runtime-16.1.0-jdk17-linux.jar and -mac-arm.jar, which AGP picks by the host. If a later update makes the two differ, the check fails on one of them, and the maintainer decides what to do, as above. ## Database migration tests diff --git a/feature/player-ui/build.gradle.kts b/feature/player-ui/build.gradle.kts index dac19f4..e3709a8 100644 --- a/feature/player-ui/build.gradle.kts +++ b/feature/player-ui/build.gradle.kts @@ -1,6 +1,7 @@ plugins { id("dewfall.android.library") id("dewfall.android.compose") + id("dewfall.android.screenshots") id("dewfall.android.hilt") } diff --git a/feature/player-ui/src/main/kotlin/io/github/dewfallapp/feature/player/ui/PlayerPreviewParts.kt b/feature/player-ui/src/main/kotlin/io/github/dewfallapp/feature/player/ui/PlayerPreviewParts.kt new file mode 100644 index 0000000..69c6369 --- /dev/null +++ b/feature/player-ui/src/main/kotlin/io/github/dewfallapp/feature/player/ui/PlayerPreviewParts.kt @@ -0,0 +1,118 @@ +@file:OptIn(UnstableApi::class) + +package io.github.dewfallapp.feature.player.ui + +import android.os.Looper +import androidx.annotation.OptIn +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import androidx.media3.common.C +import androidx.media3.common.MediaItem +import androidx.media3.common.Player +import androidx.media3.common.SimpleBasePlayer +import androidx.media3.common.SimpleBasePlayer.PositionSupplier +import androidx.media3.common.util.UnstableApi +import com.google.common.util.concurrent.Futures +import com.google.common.util.concurrent.ListenableFuture +import io.github.dewfallapp.core.designsystem.theme.DewfallTheme +import io.github.dewfallapp.core.model.PublishedTime +import io.github.dewfallapp.feature.player.logic.PlayerState +import io.github.dewfallapp.feature.player.logic.VideoPage +import java.time.ZoneId +import kotlin.time.Duration.Companion.hours +import kotlin.time.Instant + +// What PlayerPreviews.kt's previews share: a made-up video, never a real one, a fixed clock, so +// they don't change with the date, a made-up player, and the screen in Dewfall's theme. + +private val previewNow = Instant.parse("2027-03-15T10:30:00Z") +private val previewZone = ZoneId.of("UTC") + +internal val previewPage = + VideoPage( + title = "How reading rooms were lit before electric lamps", + channelName = "Larkspur Lectures", + channelInitial = "L", + description = + "A walk through four nineteenth-century reading rooms and the ways their builders " + + "brought daylight deep inside: high clerestory windows, pale plaster, and desks " + + "turned to face north so no shadow fell across the page.\n\n" + + "Recorded on location, with a floor plan for each room.", + published = PublishedTime(previewNow - 7.hours, isApproximate = false), + isLive = false, + ) + +/** The length of the made-up video, 1:14:02, and where it plays, 18:24, as in the frames. */ +private const val PREVIEW_DURATION_US = 4_442_000_000L +internal const val PREVIEW_POSITION_MS = 1_104_000L +private const val MICROS_PER_MILLI = 1000L + +/** + * A made-up player in a fixed state, for the previews. It has one item, whose ID is no real + * playback ID. + */ +internal class PreviewPlayer( + playing: Boolean, + playbackState: Int = Player.STATE_READY, + live: Boolean = false, +) : SimpleBasePlayer(Looper.getMainLooper()) { + private val fixedState = + State.Builder() + .setAvailableCommands(Player.Commands.Builder().addAllCommands().build()) + .setPlayWhenReady(playing, Player.PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST) + .setPlaybackState(playbackState) + .setPlaylist( + listOf( + MediaItemData.Builder("preview") + .setDurationUs(if (live) C.TIME_UNSET else PREVIEW_DURATION_US) + .setIsDynamic(live) + .setLiveConfiguration(if (live) MediaItem.LiveConfiguration.UNSET else null) + .build(), + ), + ) + // A constant position. Given a plain number, SimpleBasePlayer moves a playing position + // on with the clock, so each render would show another time. + .setContentPositionMs( + PositionSupplier.getConstant( + when (playbackState) { + Player.STATE_ENDED -> PREVIEW_DURATION_US / MICROS_PER_MILLI + else -> PREVIEW_POSITION_MS + }, + ), + ) + .build() + + override fun getState(): State = fixedState + + /** ContentFrame hands the player its surface. The made-up player shows nothing on it. */ + override fun handleSetVideoOutput(videoOutput: Any): ListenableFuture<*> = + Futures.immediateVoidFuture() + + override fun handleClearVideoOutput(videoOutput: Any?): ListenableFuture<*> = + Futures.immediateVoidFuture() +} + +/** + * The video screen in [state], with [video] in its video area, at the fixed clock. Dewfall's own + * palette, unless [dynamicColor] asks for the wallpaper's. + */ +@Composable +internal fun PlayerScreenPreview( + state: PlayerState, + dynamicColor: Boolean = false, + video: () -> VideoAreaContent, +) { + val content = remember { video() } + DewfallTheme(dynamicColor = dynamicColor) { + PlayerScreen( + state = state, + now = previewNow, + zone = previewZone, + onIntent = {}, + onClose = {}, + videoArea = { modifier -> + VideoArea(content = content, onPlay = {}, onTryAgain = {}, modifier = modifier) + }, + ) + } +} diff --git a/feature/player-ui/src/main/kotlin/io/github/dewfallapp/feature/player/ui/PlayerPreviews.kt b/feature/player-ui/src/main/kotlin/io/github/dewfallapp/feature/player/ui/PlayerPreviews.kt index 2bc5961..e878932 100644 --- a/feature/player-ui/src/main/kotlin/io/github/dewfallapp/feature/player/ui/PlayerPreviews.kt +++ b/feature/player-ui/src/main/kotlin/io/github/dewfallapp/feature/player/ui/PlayerPreviews.kt @@ -1,179 +1,62 @@ -@file:OptIn(UnstableApi::class) - package io.github.dewfallapp.feature.player.ui -import android.content.res.Configuration -import android.os.Looper -import androidx.annotation.OptIn import androidx.compose.runtime.Composable -import androidx.compose.runtime.remember -import androidx.compose.ui.tooling.preview.Preview -import androidx.media3.common.C -import androidx.media3.common.MediaItem import androidx.media3.common.Player -import androidx.media3.common.SimpleBasePlayer -import androidx.media3.common.util.UnstableApi -import com.google.common.util.concurrent.Futures -import com.google.common.util.concurrent.ListenableFuture -import io.github.dewfallapp.core.designsystem.theme.DewfallTheme import io.github.dewfallapp.core.model.PlaybackFailure -import io.github.dewfallapp.core.model.PublishedTime import io.github.dewfallapp.core.model.YouTubeError import io.github.dewfallapp.feature.player.logic.DetailsArea import io.github.dewfallapp.feature.player.logic.PlayerState -import io.github.dewfallapp.feature.player.logic.VideoPage -import java.time.ZoneId -import kotlin.time.Duration.Companion.hours -import kotlin.time.Instant - -// Previews with a made-up video, never a real one, and a fixed clock, so they don't change with the -// date. - -private val previewNow = Instant.parse("2027-03-15T10:30:00Z") -private val previewZone = ZoneId.of("UTC") - -private val previewPage = - VideoPage( - title = "How reading rooms were lit before electric lamps", - channelName = "Larkspur Lectures", - channelInitial = "L", - description = - "A walk through four nineteenth-century reading rooms and the ways their builders " + - "brought daylight deep inside: high clerestory windows, pale plaster, and desks " + - "turned to face north so no shadow fell across the page.\n\n" + - "Recorded on location, with a floor plan for each room.", - published = PublishedTime(previewNow - 7.hours, isApproximate = false), - isLive = false, - ) - -/** The length of the made-up video, 1:14:02, and where it plays, 18:24, as in the frames. */ -private const val PREVIEW_DURATION_US = 4_442_000_000L -private const val PREVIEW_POSITION_MS = 1_104_000L -private const val MICROS_PER_MILLI = 1000L - -/** - * A made-up player in a fixed state, for the previews. It has one item, whose ID is no real - * playback ID. - */ -private class PreviewPlayer( - playing: Boolean, - playbackState: Int = Player.STATE_READY, - live: Boolean = false, -) : SimpleBasePlayer(Looper.getMainLooper()) { - private val fixedState = - State.Builder() - .setAvailableCommands(Player.Commands.Builder().addAllCommands().build()) - .setPlayWhenReady(playing, Player.PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST) - .setPlaybackState(playbackState) - .setPlaylist( - listOf( - MediaItemData.Builder("preview") - .setDurationUs(if (live) C.TIME_UNSET else PREVIEW_DURATION_US) - .setIsDynamic(live) - .setLiveConfiguration(if (live) MediaItem.LiveConfiguration.UNSET else null) - .build(), - ), - ) - .setContentPositionMs( - when (playbackState) { - Player.STATE_ENDED -> PREVIEW_DURATION_US / MICROS_PER_MILLI - else -> PREVIEW_POSITION_MS - }, - ) - .build() - override fun getState(): State = fixedState +// Previews of the video screen, with the made-up video and player in PlayerPreviewParts.kt. The +// @PreviewTest wrappers in src/screenshotTest carry their @Preview annotations and render them as +// screenshot tests. They use Dewfall's own palette, so the images don't depend on a wallpaper, +// except the dynamic color preview, whose wrappers name a fixed one. See +// docs/testing.md#screenshot-tests. - /** ContentFrame hands the player its surface. The made-up player shows nothing on it. */ - override fun handleSetVideoOutput(videoOutput: Any): ListenableFuture<*> = - Futures.immediateVoidFuture() - - override fun handleClearVideoOutput(videoOutput: Any?): ListenableFuture<*> = - Futures.immediateVoidFuture() -} +private val shownPage = PlayerState(DetailsArea.Shown(previewPage)) @Composable -private fun Preview(state: PlayerState, video: () -> VideoAreaContent) { - val content = remember { video() } - DewfallTheme { - PlayerScreen( - state = state, - now = previewNow, - zone = previewZone, - onIntent = {}, - onClose = {}, - videoArea = { modifier -> - VideoArea(content = content, onPlay = {}, onTryAgain = {}, modifier = modifier) - }, - ) - } +internal fun PlayingPreview() { + PlayerScreenPreview(shownPage) { VideoAreaContent.Playing(PreviewPlayer(playing = true)) } } -private val shownPage = PlayerState(DetailsArea.Shown(previewPage)) - -@Preview(name = "Light") -@Preview( - name = "Dark", - uiMode = Configuration.UI_MODE_NIGHT_YES or Configuration.UI_MODE_TYPE_NORMAL, -) -@Preview(name = "Large font", fontScale = 2f) -@Preview(name = "Tablet", widthDp = 1280, heightDp = 800) @Composable -private fun PlayingPreview() { - Preview(shownPage) { VideoAreaContent.Playing(PreviewPlayer(playing = true)) } +internal fun PlayingDynamicPreview() { + PlayerScreenPreview(shownPage, dynamicColor = true) { + VideoAreaContent.Playing(PreviewPlayer(playing = true)) + } } -@Preview(name = "Light") -@Preview( - name = "Dark", - uiMode = Configuration.UI_MODE_NIGHT_YES or Configuration.UI_MODE_TYPE_NORMAL, -) @Composable -private fun PausedPreview() { - Preview(shownPage) { VideoAreaContent.Playing(PreviewPlayer(playing = false)) } +internal fun PausedPreview() { + PlayerScreenPreview(shownPage) { VideoAreaContent.Playing(PreviewPlayer(playing = false)) } } -@Preview(name = "Light") @Composable -private fun EndedPreview() { - Preview(shownPage) { +internal fun EndedPreview() { + PlayerScreenPreview(shownPage) { VideoAreaContent.Playing(PreviewPlayer(playing = true, Player.STATE_ENDED)) } } -@Preview(name = "Light") -@Preview(name = "Large font", fontScale = 2f) @Composable -private fun WaitingForPlayPreview() { - Preview(shownPage) { VideoAreaContent.Waiting(PREVIEW_POSITION_MS) } +internal fun WaitingForPlayPreview() { + PlayerScreenPreview(shownPage) { VideoAreaContent.Waiting(PREVIEW_POSITION_MS) } } -@Preview(name = "Light") -@Preview( - name = "Dark", - uiMode = Configuration.UI_MODE_NIGHT_YES or Configuration.UI_MODE_TYPE_NORMAL, -) -@Preview(name = "Large font", fontScale = 2f) -@Preview(name = "Tablet", widthDp = 1280, heightDp = 800) @Composable -private fun NotDecodablePreview() { - Preview(shownPage) { VideoAreaContent.Failed(PlaybackFailure.NOT_DECODABLE) } +internal fun NotDecodablePreview() { + PlayerScreenPreview(shownPage) { VideoAreaContent.Failed(PlaybackFailure.NOT_DECODABLE) } } -@Preview(name = "Light") @Composable -private fun StoppedPlayingPreview() { - Preview(shownPage) { VideoAreaContent.Failed(PlaybackFailure.OTHER) } +internal fun StoppedPlayingPreview() { + PlayerScreenPreview(shownPage) { VideoAreaContent.Failed(PlaybackFailure.OTHER) } } -@Preview(name = "Light") -@Preview( - name = "Dark", - uiMode = Configuration.UI_MODE_NIGHT_YES or Configuration.UI_MODE_TYPE_NORMAL, -) @Composable -private fun LiveWithNoDescriptionPreview() { - Preview( +internal fun LiveWithNoDescriptionPreview() { + PlayerScreenPreview( state = PlayerState( DetailsArea.Shown( @@ -190,32 +73,24 @@ private fun LiveWithNoDescriptionPreview() { ) } -@Preview(name = "Light") @Composable -private fun LoadingPreview() { - Preview(PlayerState(DetailsArea.Loading(1))) { +internal fun LoadingPreview() { + PlayerScreenPreview(PlayerState(DetailsArea.Loading(1))) { VideoAreaContent.Playing(PreviewPlayer(playing = true, Player.STATE_BUFFERING)) } } -@Preview(name = "Light") -@Preview( - name = "Dark", - uiMode = Configuration.UI_MODE_NIGHT_YES or Configuration.UI_MODE_TYPE_NORMAL, -) -@Preview(name = "Large font", fontScale = 2f) @Composable -private fun NetworkFailurePreview() { +internal fun NetworkFailurePreview() { // Playback failed the same way, so the video area shows no second message. - Preview(PlayerState(DetailsArea.Failed(1, YouTubeError.NETWORK))) { + PlayerScreenPreview(PlayerState(DetailsArea.Failed(1, YouTubeError.NETWORK))) { VideoAreaContent.Playing(null) } } -@Preview(name = "Light") @Composable -private fun UnavailablePreview() { - Preview(PlayerState(DetailsArea.Failed(1, YouTubeError.UNAVAILABLE))) { +internal fun UnavailablePreview() { + PlayerScreenPreview(PlayerState(DetailsArea.Failed(1, YouTubeError.UNAVAILABLE))) { VideoAreaContent.Playing(null) } } diff --git a/feature/player-ui/src/screenshotTest/kotlin/io/github/dewfallapp/feature/player/ui/PlayerScreenshots.kt b/feature/player-ui/src/screenshotTest/kotlin/io/github/dewfallapp/feature/player/ui/PlayerScreenshots.kt new file mode 100644 index 0000000..a15985c --- /dev/null +++ b/feature/player-ui/src/screenshotTest/kotlin/io/github/dewfallapp/feature/player/ui/PlayerScreenshots.kt @@ -0,0 +1,87 @@ +package io.github.dewfallapp.feature.player.ui + +import android.content.res.Configuration +import androidx.compose.runtime.Composable +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.tooling.preview.Wallpapers +import com.android.tools.screenshot.PreviewTest + +@PreviewTest +@Preview(name = "Light") +@Preview( + name = "Dark", + uiMode = Configuration.UI_MODE_NIGHT_YES or Configuration.UI_MODE_TYPE_NORMAL, +) +@Preview(name = "LargeFont", fontScale = 2f) +@Preview(name = "Tablet", widthDp = 1280, heightDp = 800) +@Composable +private fun PlayingScreenshot() = PlayingPreview() + +@PreviewTest +@Preview(name = "DynamicLight", wallpaper = Wallpapers.BLUE_DOMINATED_EXAMPLE) +@Preview( + name = "DynamicDark", + uiMode = Configuration.UI_MODE_NIGHT_YES or Configuration.UI_MODE_TYPE_NORMAL, + wallpaper = Wallpapers.BLUE_DOMINATED_EXAMPLE, +) +@Composable +private fun PlayingDynamicScreenshot() = PlayingDynamicPreview() + +@PreviewTest +@Preview(name = "Light") +@Preview( + name = "Dark", + uiMode = Configuration.UI_MODE_NIGHT_YES or Configuration.UI_MODE_TYPE_NORMAL, +) +@Composable +private fun PausedScreenshot() = PausedPreview() + +@PreviewTest @Preview(name = "Light") @Composable private fun EndedScreenshot() = EndedPreview() + +@PreviewTest +@Preview(name = "Light") +@Preview(name = "LargeFont", fontScale = 2f) +@Composable +private fun WaitingForPlayScreenshot() = WaitingForPlayPreview() + +@PreviewTest +@Preview(name = "Light") +@Preview( + name = "Dark", + uiMode = Configuration.UI_MODE_NIGHT_YES or Configuration.UI_MODE_TYPE_NORMAL, +) +@Preview(name = "LargeFont", fontScale = 2f) +@Preview(name = "Tablet", widthDp = 1280, heightDp = 800) +@Composable +private fun NotDecodableScreenshot() = NotDecodablePreview() + +@PreviewTest +@Preview(name = "Light") +@Composable +private fun StoppedPlayingScreenshot() = StoppedPlayingPreview() + +@PreviewTest +@Preview(name = "Light") +@Preview( + name = "Dark", + uiMode = Configuration.UI_MODE_NIGHT_YES or Configuration.UI_MODE_TYPE_NORMAL, +) +@Composable +private fun LiveWithNoDescriptionScreenshot() = LiveWithNoDescriptionPreview() + +@PreviewTest @Preview(name = "Light") @Composable private fun LoadingScreenshot() = LoadingPreview() + +@PreviewTest +@Preview(name = "Light") +@Preview( + name = "Dark", + uiMode = Configuration.UI_MODE_NIGHT_YES or Configuration.UI_MODE_TYPE_NORMAL, +) +@Preview(name = "LargeFont", fontScale = 2f) +@Composable +private fun NetworkFailureScreenshot() = NetworkFailurePreview() + +@PreviewTest +@Preview(name = "Light") +@Composable +private fun UnavailableScreenshot() = UnavailablePreview() diff --git a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/EndedScreenshot_Light_b29dc7a7_0.png b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/EndedScreenshot_Light_b29dc7a7_0.png new file mode 100644 index 0000000..24971fc Binary files /dev/null and b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/EndedScreenshot_Light_b29dc7a7_0.png differ diff --git a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/LiveWithNoDescriptionScreenshot_Dark_d19fbf1f_0.png b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/LiveWithNoDescriptionScreenshot_Dark_d19fbf1f_0.png new file mode 100644 index 0000000..41fa0c9 Binary files /dev/null and b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/LiveWithNoDescriptionScreenshot_Dark_d19fbf1f_0.png differ diff --git a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/LiveWithNoDescriptionScreenshot_Light_b29dc7a7_0.png b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/LiveWithNoDescriptionScreenshot_Light_b29dc7a7_0.png new file mode 100644 index 0000000..18e9b77 Binary files /dev/null and b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/LiveWithNoDescriptionScreenshot_Light_b29dc7a7_0.png differ diff --git a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/LoadingScreenshot_Light_b29dc7a7_0.png b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/LoadingScreenshot_Light_b29dc7a7_0.png new file mode 100644 index 0000000..0397efd Binary files /dev/null and b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/LoadingScreenshot_Light_b29dc7a7_0.png differ diff --git a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/NetworkFailureScreenshot_Dark_d19fbf1f_0.png b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/NetworkFailureScreenshot_Dark_d19fbf1f_0.png new file mode 100644 index 0000000..c0e45f0 Binary files /dev/null and b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/NetworkFailureScreenshot_Dark_d19fbf1f_0.png differ diff --git a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/NetworkFailureScreenshot_LargeFont_04aa6175_0.png b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/NetworkFailureScreenshot_LargeFont_04aa6175_0.png new file mode 100644 index 0000000..6f7c016 Binary files /dev/null and b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/NetworkFailureScreenshot_LargeFont_04aa6175_0.png differ diff --git a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/NetworkFailureScreenshot_Light_b29dc7a7_0.png b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/NetworkFailureScreenshot_Light_b29dc7a7_0.png new file mode 100644 index 0000000..81e48ab Binary files /dev/null and b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/NetworkFailureScreenshot_Light_b29dc7a7_0.png differ diff --git a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/NotDecodableScreenshot_Dark_d19fbf1f_0.png b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/NotDecodableScreenshot_Dark_d19fbf1f_0.png new file mode 100644 index 0000000..e6dbc99 Binary files /dev/null and b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/NotDecodableScreenshot_Dark_d19fbf1f_0.png differ diff --git a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/NotDecodableScreenshot_LargeFont_04aa6175_0.png b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/NotDecodableScreenshot_LargeFont_04aa6175_0.png new file mode 100644 index 0000000..38b18fe Binary files /dev/null and b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/NotDecodableScreenshot_LargeFont_04aa6175_0.png differ diff --git a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/NotDecodableScreenshot_Light_b29dc7a7_0.png b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/NotDecodableScreenshot_Light_b29dc7a7_0.png new file mode 100644 index 0000000..0e982ca Binary files /dev/null and b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/NotDecodableScreenshot_Light_b29dc7a7_0.png differ diff --git a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/NotDecodableScreenshot_Tablet_f32bdb34_0.png b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/NotDecodableScreenshot_Tablet_f32bdb34_0.png new file mode 100644 index 0000000..0e4f554 Binary files /dev/null and b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/NotDecodableScreenshot_Tablet_f32bdb34_0.png differ diff --git a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/PausedScreenshot_Dark_d19fbf1f_0.png b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/PausedScreenshot_Dark_d19fbf1f_0.png new file mode 100644 index 0000000..a9c3679 Binary files /dev/null and b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/PausedScreenshot_Dark_d19fbf1f_0.png differ diff --git a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/PausedScreenshot_Light_b29dc7a7_0.png b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/PausedScreenshot_Light_b29dc7a7_0.png new file mode 100644 index 0000000..85ba815 Binary files /dev/null and b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/PausedScreenshot_Light_b29dc7a7_0.png differ diff --git a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/PlayingDynamicScreenshot_DynamicDark_18383af3_0.png b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/PlayingDynamicScreenshot_DynamicDark_18383af3_0.png new file mode 100644 index 0000000..d896236 Binary files /dev/null and b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/PlayingDynamicScreenshot_DynamicDark_18383af3_0.png differ diff --git a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/PlayingDynamicScreenshot_DynamicLight_4c0cf872_0.png b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/PlayingDynamicScreenshot_DynamicLight_4c0cf872_0.png new file mode 100644 index 0000000..5f84aa3 Binary files /dev/null and b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/PlayingDynamicScreenshot_DynamicLight_4c0cf872_0.png differ diff --git a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/PlayingScreenshot_Dark_d19fbf1f_0.png b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/PlayingScreenshot_Dark_d19fbf1f_0.png new file mode 100644 index 0000000..bee1b24 Binary files /dev/null and b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/PlayingScreenshot_Dark_d19fbf1f_0.png differ diff --git a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/PlayingScreenshot_LargeFont_04aa6175_0.png b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/PlayingScreenshot_LargeFont_04aa6175_0.png new file mode 100644 index 0000000..2820360 Binary files /dev/null and b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/PlayingScreenshot_LargeFont_04aa6175_0.png differ diff --git a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/PlayingScreenshot_Light_b29dc7a7_0.png b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/PlayingScreenshot_Light_b29dc7a7_0.png new file mode 100644 index 0000000..61aeb91 Binary files /dev/null and b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/PlayingScreenshot_Light_b29dc7a7_0.png differ diff --git a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/PlayingScreenshot_Tablet_f32bdb34_0.png b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/PlayingScreenshot_Tablet_f32bdb34_0.png new file mode 100644 index 0000000..a4e3715 Binary files /dev/null and b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/PlayingScreenshot_Tablet_f32bdb34_0.png differ diff --git a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/StoppedPlayingScreenshot_Light_b29dc7a7_0.png b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/StoppedPlayingScreenshot_Light_b29dc7a7_0.png new file mode 100644 index 0000000..4f8416e Binary files /dev/null and b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/StoppedPlayingScreenshot_Light_b29dc7a7_0.png differ diff --git a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/UnavailableScreenshot_Light_b29dc7a7_0.png b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/UnavailableScreenshot_Light_b29dc7a7_0.png new file mode 100644 index 0000000..42febd6 Binary files /dev/null and b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/UnavailableScreenshot_Light_b29dc7a7_0.png differ diff --git a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/WaitingForPlayScreenshot_LargeFont_04aa6175_0.png b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/WaitingForPlayScreenshot_LargeFont_04aa6175_0.png new file mode 100644 index 0000000..27ab1db Binary files /dev/null and b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/WaitingForPlayScreenshot_LargeFont_04aa6175_0.png differ diff --git a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/WaitingForPlayScreenshot_Light_b29dc7a7_0.png b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/WaitingForPlayScreenshot_Light_b29dc7a7_0.png new file mode 100644 index 0000000..2e3b440 Binary files /dev/null and b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/WaitingForPlayScreenshot_Light_b29dc7a7_0.png differ diff --git a/feature/youtube-debug-ui/build.gradle.kts b/feature/youtube-debug-ui/build.gradle.kts index fed04c8..dc37f85 100644 --- a/feature/youtube-debug-ui/build.gradle.kts +++ b/feature/youtube-debug-ui/build.gradle.kts @@ -1,6 +1,7 @@ plugins { id("dewfall.android.library") id("dewfall.android.compose") + id("dewfall.android.screenshots") id("dewfall.android.hilt") } diff --git a/feature/youtube-debug-ui/src/main/kotlin/io/github/dewfallapp/feature/youtubedebug/ui/YouTubeDebugPreviews.kt b/feature/youtube-debug-ui/src/main/kotlin/io/github/dewfallapp/feature/youtubedebug/ui/YouTubeDebugPreviews.kt index 88ff692..f5ff814 100644 --- a/feature/youtube-debug-ui/src/main/kotlin/io/github/dewfallapp/feature/youtubedebug/ui/YouTubeDebugPreviews.kt +++ b/feature/youtube-debug-ui/src/main/kotlin/io/github/dewfallapp/feature/youtubedebug/ui/YouTubeDebugPreviews.kt @@ -1,8 +1,6 @@ package io.github.dewfallapp.feature.youtubedebug.ui -import android.content.res.Configuration import androidx.compose.runtime.Composable -import androidx.compose.ui.tooling.preview.Preview import io.github.dewfallapp.core.designsystem.theme.DewfallTheme import io.github.dewfallapp.core.model.AudioTrackKind import io.github.dewfallapp.core.model.PublishedTime @@ -25,22 +23,26 @@ import io.github.dewfallapp.feature.youtubedebug.logic.YouTubeDebugState import kotlin.time.Duration import kotlin.time.Instant -// Previews of the debug screen, in light, dark and large font, with made-up answers. Dewfall's -// own palette keeps them the same on every machine. +// Previews of the debug screen with made-up answers. The @PreviewTest wrappers in +// src/screenshotTest carry their @Preview annotations, in light, dark and large font, and render +// them as screenshot tests. Dewfall's own palette keeps them the same on every machine, except the +// dynamic color preview, whose wrappers name a fixed wallpaper. See +// docs/testing.md#screenshot-tests. -@Preview(name = "Light") -@Preview( - name = "Dark", - uiMode = Configuration.UI_MODE_NIGHT_YES or Configuration.UI_MODE_TYPE_NORMAL, -) -@Preview(name = "Large font", fontScale = 2f) @Composable -private fun YouTubeDebugScreenPreview() { +internal fun YouTubeDebugScreenPreview() { DewfallTheme(dynamicColor = false) { YouTubeDebugScreen(state = previewState(), onIntent = {}) } } +@Composable +internal fun YouTubeDebugScreenDynamicPreview() { + DewfallTheme(dynamicColor = true) { + YouTubeDebugScreen(state = previewState(), onIntent = {}) + } +} + private fun previewState(): YouTubeDebugState = YouTubeDebugState( search = Section(input = "forest", status = CallStatus.Succeeded(previewSearch())), diff --git a/feature/youtube-debug-ui/src/screenshotTest/kotlin/io/github/dewfallapp/feature/youtubedebug/ui/YouTubeDebugScreenshots.kt b/feature/youtube-debug-ui/src/screenshotTest/kotlin/io/github/dewfallapp/feature/youtubedebug/ui/YouTubeDebugScreenshots.kt new file mode 100644 index 0000000..2caf81e --- /dev/null +++ b/feature/youtube-debug-ui/src/screenshotTest/kotlin/io/github/dewfallapp/feature/youtubedebug/ui/YouTubeDebugScreenshots.kt @@ -0,0 +1,27 @@ +package io.github.dewfallapp.feature.youtubedebug.ui + +import android.content.res.Configuration +import androidx.compose.runtime.Composable +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.tooling.preview.Wallpapers +import com.android.tools.screenshot.PreviewTest + +@PreviewTest +@Preview(name = "Light") +@Preview( + name = "Dark", + uiMode = Configuration.UI_MODE_NIGHT_YES or Configuration.UI_MODE_TYPE_NORMAL, +) +@Preview(name = "LargeFont", fontScale = 2f) +@Composable +private fun YouTubeDebugScreenScreenshot() = YouTubeDebugScreenPreview() + +@PreviewTest +@Preview(name = "DynamicLight", wallpaper = Wallpapers.BLUE_DOMINATED_EXAMPLE) +@Preview( + name = "DynamicDark", + uiMode = Configuration.UI_MODE_NIGHT_YES or Configuration.UI_MODE_TYPE_NORMAL, + wallpaper = Wallpapers.BLUE_DOMINATED_EXAMPLE, +) +@Composable +private fun YouTubeDebugScreenDynamicScreenshot() = YouTubeDebugScreenDynamicPreview() diff --git a/feature/youtube-debug-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/youtubedebug/ui/YouTubeDebugScreenshotsKt/YouTubeDebugScreenDynamicScreenshot_DynamicDark_18383af3_0.png b/feature/youtube-debug-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/youtubedebug/ui/YouTubeDebugScreenshotsKt/YouTubeDebugScreenDynamicScreenshot_DynamicDark_18383af3_0.png new file mode 100644 index 0000000..967e4d1 Binary files /dev/null and b/feature/youtube-debug-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/youtubedebug/ui/YouTubeDebugScreenshotsKt/YouTubeDebugScreenDynamicScreenshot_DynamicDark_18383af3_0.png differ diff --git a/feature/youtube-debug-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/youtubedebug/ui/YouTubeDebugScreenshotsKt/YouTubeDebugScreenDynamicScreenshot_DynamicLight_4c0cf872_0.png b/feature/youtube-debug-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/youtubedebug/ui/YouTubeDebugScreenshotsKt/YouTubeDebugScreenDynamicScreenshot_DynamicLight_4c0cf872_0.png new file mode 100644 index 0000000..bdde048 Binary files /dev/null and b/feature/youtube-debug-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/youtubedebug/ui/YouTubeDebugScreenshotsKt/YouTubeDebugScreenDynamicScreenshot_DynamicLight_4c0cf872_0.png differ diff --git a/feature/youtube-debug-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/youtubedebug/ui/YouTubeDebugScreenshotsKt/YouTubeDebugScreenScreenshot_Dark_d19fbf1f_0.png b/feature/youtube-debug-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/youtubedebug/ui/YouTubeDebugScreenshotsKt/YouTubeDebugScreenScreenshot_Dark_d19fbf1f_0.png new file mode 100644 index 0000000..6bef2f7 Binary files /dev/null and b/feature/youtube-debug-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/youtubedebug/ui/YouTubeDebugScreenshotsKt/YouTubeDebugScreenScreenshot_Dark_d19fbf1f_0.png differ diff --git a/feature/youtube-debug-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/youtubedebug/ui/YouTubeDebugScreenshotsKt/YouTubeDebugScreenScreenshot_LargeFont_04aa6175_0.png b/feature/youtube-debug-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/youtubedebug/ui/YouTubeDebugScreenshotsKt/YouTubeDebugScreenScreenshot_LargeFont_04aa6175_0.png new file mode 100644 index 0000000..1c7ae08 Binary files /dev/null and b/feature/youtube-debug-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/youtubedebug/ui/YouTubeDebugScreenshotsKt/YouTubeDebugScreenScreenshot_LargeFont_04aa6175_0.png differ diff --git a/feature/youtube-debug-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/youtubedebug/ui/YouTubeDebugScreenshotsKt/YouTubeDebugScreenScreenshot_Light_b29dc7a7_0.png b/feature/youtube-debug-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/youtubedebug/ui/YouTubeDebugScreenshotsKt/YouTubeDebugScreenScreenshot_Light_b29dc7a7_0.png new file mode 100644 index 0000000..c67db2b Binary files /dev/null and b/feature/youtube-debug-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/youtubedebug/ui/YouTubeDebugScreenshotsKt/YouTubeDebugScreenScreenshot_Light_b29dc7a7_0.png differ diff --git a/feature/youtube-search-ui/build.gradle.kts b/feature/youtube-search-ui/build.gradle.kts index 6b8f97a..7910ea7 100644 --- a/feature/youtube-search-ui/build.gradle.kts +++ b/feature/youtube-search-ui/build.gradle.kts @@ -1,6 +1,7 @@ plugins { id("dewfall.android.library") id("dewfall.android.compose") + id("dewfall.android.screenshots") id("dewfall.android.hilt") } diff --git a/feature/youtube-search-ui/src/main/kotlin/io/github/dewfallapp/feature/youtubesearch/ui/YouTubeSearchPreviews.kt b/feature/youtube-search-ui/src/main/kotlin/io/github/dewfallapp/feature/youtubesearch/ui/YouTubeSearchPreviews.kt index 78cbc09..82d1667 100644 --- a/feature/youtube-search-ui/src/main/kotlin/io/github/dewfallapp/feature/youtubesearch/ui/YouTubeSearchPreviews.kt +++ b/feature/youtube-search-ui/src/main/kotlin/io/github/dewfallapp/feature/youtubesearch/ui/YouTubeSearchPreviews.kt @@ -1,9 +1,9 @@ package io.github.dewfallapp.feature.youtubesearch.ui -import android.content.res.Configuration import androidx.compose.foundation.text.input.rememberTextFieldState import androidx.compose.runtime.Composable -import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.ui.platform.LocalCursorBlinkEnabled import io.github.dewfallapp.core.designsystem.theme.DewfallTheme import io.github.dewfallapp.core.model.PublishedTime import io.github.dewfallapp.core.model.VideoId @@ -19,7 +19,10 @@ import kotlin.time.Duration.Companion.minutes import kotlin.time.Instant // Previews with made-up videos, never real ones, and a fixed clock, so they don't change with the -// date. +// date. The @PreviewTest wrappers in src/screenshotTest carry their @Preview annotations and +// render them as screenshot tests. They use Dewfall's own palette, so the images don't depend on a +// wallpaper, except the dynamic color preview, whose wrappers name a fixed one. See +// docs/testing.md#screenshot-tests. private val previewNow = Instant.parse("2027-03-15T10:30:00Z") private val previewZone = ZoneId.of("UTC") @@ -80,63 +83,57 @@ private val previewRows = ) @Composable -private fun Preview(state: YouTubeSearchState, text: String = "") { - DewfallTheme { - YouTubeSearchScreen( - state = state, - textFieldState = rememberTextFieldState(text), - now = previewNow, - zone = previewZone, - onIntent = {}, - onOpenVideo = {}, - ) +private fun Preview(state: YouTubeSearchState, text: String = "", dynamicColor: Boolean = false) { + // The search field takes focus, and its cursor blinks with the clock, so a screenshot would + // catch it on or off depending on how long the render took. A steady cursor draws the same + // every time. + CompositionLocalProvider(LocalCursorBlinkEnabled provides false) { + DewfallTheme(dynamicColor = dynamicColor) { + YouTubeSearchScreen( + state = state, + textFieldState = rememberTextFieldState(text), + now = previewNow, + zone = previewZone, + onIntent = {}, + onOpenVideo = {}, + ) + } } } -@Preview(name = "Light") -@Preview( - name = "Dark", - uiMode = Configuration.UI_MODE_NIGHT_YES or Configuration.UI_MODE_TYPE_NORMAL, -) -@Preview(name = "Large font", fontScale = 2f) -@Preview(name = "Tablet", widthDp = 1280, heightDp = 800) @Composable -private fun ResultsPreview() { +internal fun ResultsPreview() { Preview(YouTubeSearchState(1, ResultsArea.Results(sourdough, previewRows)), text = "sourdough") } -@Preview(name = "Light") -@Preview( - name = "Dark", - uiMode = Configuration.UI_MODE_NIGHT_YES or Configuration.UI_MODE_TYPE_NORMAL, -) @Composable -private fun BeforeTheFirstSearchPreview() { +internal fun ResultsDynamicPreview() { + Preview( + YouTubeSearchState(1, ResultsArea.Results(sourdough, previewRows)), + text = "sourdough", + dynamicColor = true, + ) +} + +@Composable +internal fun BeforeTheFirstSearchPreview() { Preview(YouTubeSearchState()) } -@Preview(name = "Light") -@Preview(name = "Large font", fontScale = 2f) @Composable -private fun NoResultsPreview() { +internal fun NoResultsPreview() { Preview(YouTubeSearchState(1, ResultsArea.NoResults(sourdough)), text = "sourdough") } -@Preview(name = "Light") -@Preview( - name = "Dark", - uiMode = Configuration.UI_MODE_NIGHT_YES or Configuration.UI_MODE_TYPE_NORMAL, -) @Composable -private fun FailedPreview() { +internal fun FailedPreview() { Preview( YouTubeSearchState(1, ResultsArea.Failed(sourdough, YouTubeError.NETWORK)), text = "sourdough", ) } -@Preview(name = "Light") @Composable -private fun LoadingPreview() { +internal fun LoadingPreview() { Preview(YouTubeSearchState(1, ResultsArea.Loading(sourdough)), text = "sourdough") } diff --git a/feature/youtube-search-ui/src/screenshotTest/kotlin/io/github/dewfallapp/feature/youtubesearch/ui/YouTubeSearchScreenshots.kt b/feature/youtube-search-ui/src/screenshotTest/kotlin/io/github/dewfallapp/feature/youtubesearch/ui/YouTubeSearchScreenshots.kt new file mode 100644 index 0000000..68c61fb --- /dev/null +++ b/feature/youtube-search-ui/src/screenshotTest/kotlin/io/github/dewfallapp/feature/youtubesearch/ui/YouTubeSearchScreenshots.kt @@ -0,0 +1,54 @@ +package io.github.dewfallapp.feature.youtubesearch.ui + +import android.content.res.Configuration +import androidx.compose.runtime.Composable +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.tooling.preview.Wallpapers +import com.android.tools.screenshot.PreviewTest + +@PreviewTest +@Preview(name = "Light") +@Preview( + name = "Dark", + uiMode = Configuration.UI_MODE_NIGHT_YES or Configuration.UI_MODE_TYPE_NORMAL, +) +@Preview(name = "LargeFont", fontScale = 2f) +@Preview(name = "Tablet", widthDp = 1280, heightDp = 800) +@Composable +private fun ResultsScreenshot() = ResultsPreview() + +@PreviewTest +@Preview(name = "DynamicLight", wallpaper = Wallpapers.BLUE_DOMINATED_EXAMPLE) +@Preview( + name = "DynamicDark", + uiMode = Configuration.UI_MODE_NIGHT_YES or Configuration.UI_MODE_TYPE_NORMAL, + wallpaper = Wallpapers.BLUE_DOMINATED_EXAMPLE, +) +@Composable +private fun ResultsDynamicScreenshot() = ResultsDynamicPreview() + +@PreviewTest +@Preview(name = "Light") +@Preview( + name = "Dark", + uiMode = Configuration.UI_MODE_NIGHT_YES or Configuration.UI_MODE_TYPE_NORMAL, +) +@Composable +private fun BeforeTheFirstSearchScreenshot() = BeforeTheFirstSearchPreview() + +@PreviewTest +@Preview(name = "Light") +@Preview(name = "LargeFont", fontScale = 2f) +@Composable +private fun NoResultsScreenshot() = NoResultsPreview() + +@PreviewTest +@Preview(name = "Light") +@Preview( + name = "Dark", + uiMode = Configuration.UI_MODE_NIGHT_YES or Configuration.UI_MODE_TYPE_NORMAL, +) +@Composable +private fun FailedScreenshot() = FailedPreview() + +@PreviewTest @Preview(name = "Light") @Composable private fun LoadingScreenshot() = LoadingPreview() diff --git a/feature/youtube-search-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/youtubesearch/ui/YouTubeSearchScreenshotsKt/BeforeTheFirstSearchScreenshot_Dark_d19fbf1f_0.png b/feature/youtube-search-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/youtubesearch/ui/YouTubeSearchScreenshotsKt/BeforeTheFirstSearchScreenshot_Dark_d19fbf1f_0.png new file mode 100644 index 0000000..e1b2f8e Binary files /dev/null and b/feature/youtube-search-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/youtubesearch/ui/YouTubeSearchScreenshotsKt/BeforeTheFirstSearchScreenshot_Dark_d19fbf1f_0.png differ diff --git a/feature/youtube-search-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/youtubesearch/ui/YouTubeSearchScreenshotsKt/BeforeTheFirstSearchScreenshot_Light_b29dc7a7_0.png b/feature/youtube-search-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/youtubesearch/ui/YouTubeSearchScreenshotsKt/BeforeTheFirstSearchScreenshot_Light_b29dc7a7_0.png new file mode 100644 index 0000000..b9b7603 Binary files /dev/null and b/feature/youtube-search-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/youtubesearch/ui/YouTubeSearchScreenshotsKt/BeforeTheFirstSearchScreenshot_Light_b29dc7a7_0.png differ diff --git a/feature/youtube-search-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/youtubesearch/ui/YouTubeSearchScreenshotsKt/FailedScreenshot_Dark_d19fbf1f_0.png b/feature/youtube-search-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/youtubesearch/ui/YouTubeSearchScreenshotsKt/FailedScreenshot_Dark_d19fbf1f_0.png new file mode 100644 index 0000000..aa61217 Binary files /dev/null and b/feature/youtube-search-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/youtubesearch/ui/YouTubeSearchScreenshotsKt/FailedScreenshot_Dark_d19fbf1f_0.png differ diff --git a/feature/youtube-search-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/youtubesearch/ui/YouTubeSearchScreenshotsKt/FailedScreenshot_Light_b29dc7a7_0.png b/feature/youtube-search-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/youtubesearch/ui/YouTubeSearchScreenshotsKt/FailedScreenshot_Light_b29dc7a7_0.png new file mode 100644 index 0000000..7fa2aa8 Binary files /dev/null and b/feature/youtube-search-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/youtubesearch/ui/YouTubeSearchScreenshotsKt/FailedScreenshot_Light_b29dc7a7_0.png differ diff --git a/feature/youtube-search-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/youtubesearch/ui/YouTubeSearchScreenshotsKt/LoadingScreenshot_Light_b29dc7a7_0.png b/feature/youtube-search-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/youtubesearch/ui/YouTubeSearchScreenshotsKt/LoadingScreenshot_Light_b29dc7a7_0.png new file mode 100644 index 0000000..82c7baa Binary files /dev/null and b/feature/youtube-search-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/youtubesearch/ui/YouTubeSearchScreenshotsKt/LoadingScreenshot_Light_b29dc7a7_0.png differ diff --git a/feature/youtube-search-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/youtubesearch/ui/YouTubeSearchScreenshotsKt/NoResultsScreenshot_LargeFont_04aa6175_0.png b/feature/youtube-search-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/youtubesearch/ui/YouTubeSearchScreenshotsKt/NoResultsScreenshot_LargeFont_04aa6175_0.png new file mode 100644 index 0000000..c4c9217 Binary files /dev/null and b/feature/youtube-search-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/youtubesearch/ui/YouTubeSearchScreenshotsKt/NoResultsScreenshot_LargeFont_04aa6175_0.png differ diff --git a/feature/youtube-search-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/youtubesearch/ui/YouTubeSearchScreenshotsKt/NoResultsScreenshot_Light_b29dc7a7_0.png b/feature/youtube-search-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/youtubesearch/ui/YouTubeSearchScreenshotsKt/NoResultsScreenshot_Light_b29dc7a7_0.png new file mode 100644 index 0000000..e2def58 Binary files /dev/null and b/feature/youtube-search-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/youtubesearch/ui/YouTubeSearchScreenshotsKt/NoResultsScreenshot_Light_b29dc7a7_0.png differ diff --git a/feature/youtube-search-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/youtubesearch/ui/YouTubeSearchScreenshotsKt/ResultsDynamicScreenshot_DynamicDark_18383af3_0.png b/feature/youtube-search-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/youtubesearch/ui/YouTubeSearchScreenshotsKt/ResultsDynamicScreenshot_DynamicDark_18383af3_0.png new file mode 100644 index 0000000..3baa480 Binary files /dev/null and b/feature/youtube-search-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/youtubesearch/ui/YouTubeSearchScreenshotsKt/ResultsDynamicScreenshot_DynamicDark_18383af3_0.png differ diff --git a/feature/youtube-search-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/youtubesearch/ui/YouTubeSearchScreenshotsKt/ResultsDynamicScreenshot_DynamicLight_4c0cf872_0.png b/feature/youtube-search-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/youtubesearch/ui/YouTubeSearchScreenshotsKt/ResultsDynamicScreenshot_DynamicLight_4c0cf872_0.png new file mode 100644 index 0000000..d9aef1f Binary files /dev/null and b/feature/youtube-search-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/youtubesearch/ui/YouTubeSearchScreenshotsKt/ResultsDynamicScreenshot_DynamicLight_4c0cf872_0.png differ diff --git a/feature/youtube-search-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/youtubesearch/ui/YouTubeSearchScreenshotsKt/ResultsScreenshot_Dark_d19fbf1f_0.png b/feature/youtube-search-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/youtubesearch/ui/YouTubeSearchScreenshotsKt/ResultsScreenshot_Dark_d19fbf1f_0.png new file mode 100644 index 0000000..3c3099d Binary files /dev/null and b/feature/youtube-search-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/youtubesearch/ui/YouTubeSearchScreenshotsKt/ResultsScreenshot_Dark_d19fbf1f_0.png differ diff --git a/feature/youtube-search-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/youtubesearch/ui/YouTubeSearchScreenshotsKt/ResultsScreenshot_LargeFont_04aa6175_0.png b/feature/youtube-search-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/youtubesearch/ui/YouTubeSearchScreenshotsKt/ResultsScreenshot_LargeFont_04aa6175_0.png new file mode 100644 index 0000000..84d249e Binary files /dev/null and b/feature/youtube-search-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/youtubesearch/ui/YouTubeSearchScreenshotsKt/ResultsScreenshot_LargeFont_04aa6175_0.png differ diff --git a/feature/youtube-search-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/youtubesearch/ui/YouTubeSearchScreenshotsKt/ResultsScreenshot_Light_b29dc7a7_0.png b/feature/youtube-search-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/youtubesearch/ui/YouTubeSearchScreenshotsKt/ResultsScreenshot_Light_b29dc7a7_0.png new file mode 100644 index 0000000..a6880a0 Binary files /dev/null and b/feature/youtube-search-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/youtubesearch/ui/YouTubeSearchScreenshotsKt/ResultsScreenshot_Light_b29dc7a7_0.png differ diff --git a/feature/youtube-search-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/youtubesearch/ui/YouTubeSearchScreenshotsKt/ResultsScreenshot_Tablet_f32bdb34_0.png b/feature/youtube-search-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/youtubesearch/ui/YouTubeSearchScreenshotsKt/ResultsScreenshot_Tablet_f32bdb34_0.png new file mode 100644 index 0000000..894f5b6 Binary files /dev/null and b/feature/youtube-search-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/youtubesearch/ui/YouTubeSearchScreenshotsKt/ResultsScreenshot_Tablet_f32bdb34_0.png differ diff --git a/gradle.properties b/gradle.properties index 549442e..a2a196b 100644 --- a/gradle.properties +++ b/gradle.properties @@ -8,3 +8,9 @@ org.gradle.configuration-cache=true org.gradle.java.installations.auto-download=false kotlin.code.style=official + +# Screenshot tests run in AGP's screenshot test suites, which need both experimental flags. Each +# build prints a warning that they are experimental. See docs/testing.md#screenshot-tests and +# https://developer.android.com/studio/preview/compose-screenshot-testing-with-testsuites +android.experimental.enableScreenshotTest=true +android.experimental.testSuiteSupport=true diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 19fd597..71750bc 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -49,6 +49,11 @@ androidxTestExtJunit = "1.3.0" # The maintainer approved declaring it on November 21, 2026, for #46. androidxTestEspresso = "3.7.0" kotlinxSerialization = "1.11.0" +# Compose Preview Screenshot Testing, which AGP's screenshot test suites run. The engine and +# screenshot-validation-api share this version, so Renovate moves them together. Test only, never +# ships. The maintainer approved it on November 21, 2026, for #45. See +# docs/testing.md#screenshot-tests. +screenshot = "0.0.1-alpha17" # NewPipeExtractor's releases are only on JitPack, so settings.gradle.kts adds JitPack for # TeamNewPipe's group alone. See docs/architecture.md#build-settings. newpipeExtractor = "v0.27.1" @@ -136,6 +141,10 @@ androidx-test-ext-junit = { module = "androidx.test.ext:junit", version.ref = "a androidx-test-espresso-core = { module = "androidx.test.espresso:espresso-core", version.ref = "androidxTestEspresso" } hilt-android-testing = { module = "com.google.dagger:hilt-android-testing", version.ref = "hilt" } +# The @PreviewTest annotation for screenshot tests. dewfall.android.screenshots adds it to the +# screenshot test suite, whose engine has the same version. See docs/testing.md#screenshot-tests. +screenshot-validation-api = { module = "com.android.tools.screenshot:screenshot-validation-api", version.ref = "screenshot" } + # A detekt plugin. The detekt convention plugin in build-logic adds it to detekt in every project. compose-rules-detekt = { module = "io.nlopez.compose.rules:detekt", version.ref = "composeRules" } diff --git a/renovate.json b/renovate.json index 5aad645..8f00f37 100644 --- a/renovate.json +++ b/renovate.json @@ -52,9 +52,21 @@ "matchPackageNames": ["/^com\\.android\\.(application|library):/", "com.android.tools.build:gradle"], "prBodyNotes": [ "If the build fails on a missing build-tools package, update the SDK steps in .github/workflows/pull-request.yml and .github/workflows/emulator-tests.yml and the Commands section of AGENTS.md on this branch.", - "lint-api and lint-tests follow AGP, at AGP's version plus 23. Check that :lint-rules' Kotlin apiVersion in build-logic is still no newer than the kotlin-stdlib that the new lint-api POM names. See docs/testing.md#dependency-updates." + "lint-api and lint-tests follow AGP, at AGP's version plus 23. Check that :lint-rules' Kotlin apiVersion in build-logic is still no newer than the kotlin-stdlib that the new lint-api POM names. See docs/testing.md#dependency-updates.", + "AGP 9.5.1 names the screenshot tests' tasks testDebugScreenshotTestDefaultTestSuite and updateDebugScreenshotTestDefaultTestSuite, unlike Google's page. If this AGP renames them, change them together in .github/workflows/pull-request.yml, BUILD_COMMAND in scripts/pre_push_gate.py, AGENTS.md, CONTRIBUTING.md, docs/testing.md, renovate.json and the task suffix in build-logic's AndroidScreenshotsConventionPlugin.kt." ] }, + { + "description": "Compose, Media3, AGP and the screenshot engine draw the screens that the screenshot tests compare, so an update can change the images without any change to the app.", + "matchPackageNames": [ + "androidx.compose:compose-bom", + "/^androidx\\.media3:/", + "com.android.tools.screenshot:screenshot-validation-api", + "/^com\\.android\\.(application|library):/", + "com.android.tools.build:gradle" + ], + "prBodyNotes": ["If testDebugScreenshotTestDefaultTestSuite fails, open its report and look at each changed image. If the change comes from this update and every screen still looks right, record the images again on the Mac with ./gradlew updateDebugScreenshotTestDefaultTestSuite, run python3 scripts/scan_screenshot_tests.py, and push them to this branch. See docs/testing.md#screenshot-tests."] + }, { "description": "Spotless downloads ktfmt, and ktfmt 0.65 and later need Spotless 8.10.4 or later to load their org.jetbrains.kotlinx coordinates, so both change in one pull request. A ktfmt update can change the formatting.", "matchPackageNames": ["/^com\\.diffplug\\.spotless:/", "org.jetbrains.kotlinx:ktfmt"], diff --git a/scripts/pre_push_gate.py b/scripts/pre_push_gate.py index 60b1020..0baf279 100644 --- a/scripts/pre_push_gate.py +++ b/scripts/pre_push_gate.py @@ -17,7 +17,9 @@ - no commit adds a local.properties, .env, keystore or key file, or a line that holds a private key, a GitHub token, an AWS access key or a Google API key; - each commit that changes the saved YouTube responses passes - scan_saved_responses.py, on that commit's own files. + scan_saved_responses.py, on that commit's own files; +- each commit that changes a screenshot test folder, src/screenshotTest*, + passes scan_screenshot_tests.py, on that commit's own files. Then it checks that nothing is left uncommitted, runs the pull request workflow's command, and checks again that the build changed no file. Its own @@ -54,6 +56,7 @@ sys.path.insert(0, SCRIPTS) import scan_saved_responses # noqa: E402 +import scan_screenshot_tests # noqa: E402 SAVED_RESPONSES = "core/youtube/src/test/resources/youtube" BUILD_COMMAND = [ @@ -62,6 +65,7 @@ "detekt", "lint", "test", + "testDebugScreenshotTestDefaultTestSuite", "assembleDebug", "--continue", "-Pandroid.builder.sdkDownload=false", @@ -186,6 +190,32 @@ def saved_files(commit): yield relative, data +def screenshot_files(commit): + """Each (path, bytes, is_link) of [commit]'s screenshot test folders, read from Git itself. + + Anything other than a plain file, such as a symbolic link or a submodule, counts as a link, + which the scan refuses. + """ + listing = subprocess.run( + ["git", "ls-tree", "-r", "-z", commit], capture_output=True, check=True + ).stdout + for entry in listing.split(b"\0"): + if not entry: + continue + meta, raw_path = entry.split(b"\t", 1) + mode, kind, blob = meta.split(b" ") + path = raw_path.decode("utf-8", errors="replace") + if not scan_screenshot_tests.SCREENSHOT_FOLDER.search(path): + continue + if kind != b"blob" or mode not in (b"100644", b"100755"): + yield path, b"", True + continue + data = subprocess.run( + ["git", "cat-file", "blob", blob.decode()], capture_output=True, check=True + ).stdout + yield path, data, False + + def scan_commit(commit): """The findings of the saved-response scan on [commit]'s own files, and how many it read.""" return scan_saved_responses.scan_files(saved_files(commit)) @@ -232,6 +262,11 @@ def check_commit(commit, local, global_email, on_remote_branch): problems.append("SAVED_RESPONSE no file was read") for relative, line, depth, kind, key in findings: problems.append(f"SAVED_RESPONSE {relative}:{line} depth={depth} {kind} {key}") + # A commit that only deletes from the folders adds nothing to check. + if any(scan_screenshot_tests.SCREENSHOT_FOLDER.search(path) for path in paths): + findings, _ = scan_screenshot_tests.check_files(screenshot_files(commit)) + for path, location, rule in findings: + problems.append(f"SCREENSHOT_TEST {path}:{location} {rule}") return problems diff --git a/scripts/scan_screenshot_tests.py b/scripts/scan_screenshot_tests.py new file mode 100644 index 0000000..1fde223 --- /dev/null +++ b/scripts/scan_screenshot_tests.py @@ -0,0 +1,323 @@ +#!/usr/bin/env python3 +"""Checks that the screenshot test folders hold only what they are meant to. + +Lint can't read a module's src/screenshotTest folder, so Dewfall's lint checks +of ADR 0007's logging rules don't reach it. That folder holds only one-call +wrappers of previews that live in src/main, where lint does read them. This +script checks that shape, so no code beyond each wrapper's one call to a preview, +a logging call included, can sit in the folder. ADR 0007's note of November 21, 2026 and +docs/testing.md#screenshot-tests explain why. + +It allows only these files in a module's src/screenshotTest* folders: +- .kt files under src/screenshotTest/kotlin/; +- .png files under a src/screenshotTest/reference/ folder, where the + screenshot tests keep their reference images. + +Each .kt file may hold only blank lines, // comment lines, one package line, +plain imports without an alias, and wrappers. A wrapper is @PreviewTest, then +one or more @Preview annotations, then @Composable, then exactly +`private fun Screenshot() = Preview()`, each on a line of its own, +or all on one line, as ktfmt writes a wrapper that fits. An annotation's arguments, +on one line or several, are each ` = `, where a value is a string +literal with no $ and no backslash, a number, true or false, or dotted names +joined by ` or `. + +Each .png file must start with PNG's signature and hold only the chunks IHDR, +IDAT and IEND, each with a correct CRC, with one IHDR, first, and nothing after +IEND. Palette images are refused, as a palette could hold unused bytes. The IDAT +chunks' zlib stream must end exactly where their data ends, and give exactly the +bytes that IHDR describes, for an image that isn't interlaced. +So no image can carry text, a time or private data, such as the name of the +machine that recorded it. + +It fails closed: a file it can't decode or parse, a .kt file with a control or +line separator character other than a line feed, such as a carriage return, a +symbolic link, any other file, or an error of its own fails the check. It +prints each finding as the file, the line or chunk number, and the rule, never +the line itself, and exits with 1 if it found anything or read no file at all. + +Usage: scan_screenshot_tests.py [repository root, by default the current folder] +""" + +import os +import re +import struct +import sys +import unicodedata +import zlib + +# A module's screenshot test folders: src/screenshotTest for the wrappers, and +# src/screenshotTest for each variant's reference images. +# It matches the folder itself too, so a link in its place is caught. It ignores case, because +# a Mac's disk does and Gradle would compile src/ScreenshotTest there. Such a folder then fails, +# as its files don't match the exact paths below. +SCREENSHOT_FOLDER = re.compile(r"(^|/)src/screenshotTest[^/]*(/|$)", re.IGNORECASE) +KOTLIN_FILE = re.compile(r"(^|/)src/screenshotTest/kotlin/.+\.kt$") +REFERENCE_IMAGE = re.compile(r"(^|/)src/screenshotTest[A-Za-z0-9]+/reference/.+\.png$") + +# Folders that hold build output or tools, never sources. A screenshot folder +# itself is read in full, whatever its subfolders are named. +SKIPPED_FOLDERS = {".git", ".gradle", ".idea", ".kotlin", "build", "node_modules"} + +NAME = r"[A-Za-z_][A-Za-z0-9_]*" +DOTTED = NAME + r"(\." + NAME + r")*" +PACKAGE_LINE = re.compile(r"package [a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)*") +IMPORT_LINE = re.compile(r"import " + DOTTED) +COMMENT_LINE = re.compile(r"//.*") +VALUE = ( + r'("[^"$\\]*"' + r"|-?[0-9]+(\.[0-9]+)?[fFL]?" + r"|true|false" + r"|" + DOTTED + r"( or " + DOTTED + r")*)" +) +ARGUMENT = r"[a-zA-Z]+ = " + VALUE +ONE_LINE_PREVIEW = re.compile(r"@Preview\((" + ARGUMENT + r"(, " + ARGUMENT + r")*)?\)") +ARGUMENT_LINE = re.compile(r" " + ARGUMENT + r",?") +FUNCTION = r"private fun (?P[A-Z][A-Za-z0-9]*)Screenshot\(\) = (?P=name)Preview\(\)" +WRAPPER = re.compile(FUNCTION) +# ktfmt puts a wrapper on one line when it fits, annotations included. +ONE_LINE_WRAPPER = re.compile( + r"@PreviewTest( " + ONE_LINE_PREVIEW.pattern + r")+ @Composable " + FUNCTION +) + +PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n" +# No PLTE: a palette could hold bytes that an RGBA image never uses, and the engine writes none. +PNG_CHUNKS = {b"IHDR", b"IDAT", b"IEND"} +# Samples per pixel for each PNG colour type, and the bit depths it allows. +PNG_COLOUR_TYPES = { + 0: (1, {1, 2, 4, 8, 16}), + 2: (3, {8, 16}), + 4: (2, {8, 16}), + 6: (4, {8, 16}), +} +# A bound on the pixel data, so a crafted image can't expand without limit. A 3360 x 2100 +# tablet image in 8-bit RGBA is about 28 MB. +PNG_MAX_PIXEL_BYTES = 256 * 1024 * 1024 + + +def check_kotlin(text): + """The (line number, rule) of each problem in a wrapper file's [text].""" + # Kotlin also breaks lines at a lone \r, so a line that looks like a comment here could + # hold code there. Any control or separator character other than \n fails, before the + # text is split into lines. + for number, line in enumerate(text.split("\n"), start=1): + if any(unicodedata.category(c) in ("Cc", "Zl", "Zp") for c in line): + return [(number, "CONTROL_CHARACTER")] + problems = [] + # top: between wrappers. after_test: after @PreviewTest. in_preview: inside a + # @Preview( that spans lines. after_preview: after a whole @Preview. + # after_composable: after @Composable, waiting for the wrapper's function. + state = "top" + seen_package = False + seen_declaration = False + for number, line in enumerate(text.split("\n"), start=1): + if state == "in_preview": + if line == ")": + state = "after_preview" + elif not ARGUMENT_LINE.fullmatch(line): + problems.append((number, "PREVIEW_ARGUMENT_NOT_ALLOWED")) + continue + if state == "top": + if line == "" or COMMENT_LINE.fullmatch(line): + continue + if PACKAGE_LINE.fullmatch(line): + if seen_package or seen_declaration: + problems.append((number, "PACKAGE_NOT_FIRST")) + seen_package = True + elif IMPORT_LINE.fullmatch(line): + if seen_declaration: + problems.append((number, "IMPORT_AFTER_WRAPPER")) + elif line == "@PreviewTest": + seen_declaration = True + state = "after_test" + elif ONE_LINE_WRAPPER.fullmatch(line): + seen_declaration = True + else: + problems.append((number, "LINE_NOT_ALLOWED")) + continue + if state in ("after_test", "after_preview"): + if ONE_LINE_PREVIEW.fullmatch(line): + state = "after_preview" + elif line == "@Preview(": + state = "in_preview" + elif line == "@Composable" and state == "after_preview": + state = "after_composable" + else: + problems.append((number, "WRAPPER_ANNOTATION_NOT_ALLOWED")) + state = "top" + continue + if state == "after_composable": + if not WRAPPER.fullmatch(line): + problems.append((number, "WRAPPER_NOT_ONE_CALL")) + state = "top" + if state != "top": + problems.append((number, "WRAPPER_NOT_FINISHED")) + return problems + + +def expected_pixel_bytes(header): + """How many bytes IHDR's [header] says the decompressed image data holds, or None.""" + if len(header) != 13: + return None + width, height, depth, colour, compression, filtering, interlace = struct.unpack( + ">IIBBBBB", header + ) + samples, depths = PNG_COLOUR_TYPES.get(colour, (0, set())) + # Interlaced images are refused, because the engine writes none and their size is harder + # to check. + if depth not in depths or (compression, filtering, interlace) != (0, 0, 0): + return None + return height * (1 + (width * samples * depth + 7) // 8) + + +def pixel_problem(header, pixels): + """The rule that the image data [pixels], joined from every IDAT, breaks, or None. + + The zlib stream must end exactly where the data ends, and give exactly the bytes that IHDR + describes, so no text can hide after the stream or after the pixels. + """ + expected = expected_pixel_bytes(header) + if expected is None or expected > PNG_MAX_PIXEL_BYTES: + return "PNG_HEADER_NOT_ALLOWED" + stream = zlib.decompressobj() + produced = 0 + try: + produced += len(stream.decompress(pixels, expected + 1)) + while stream.unconsumed_tail and produced <= expected: + produced += len(stream.decompress(stream.unconsumed_tail, expected + 1 - produced)) + except zlib.error: + return "PNG_PIXELS_NOT_ZLIB" + if not stream.eof or stream.unused_data or stream.unconsumed_tail or produced != expected: + return "PNG_PIXELS_NOT_EXACT" + return None + + +def check_png(data): + """The (chunk number, rule) of each problem in a reference image's [data].""" + if not data.startswith(PNG_SIGNATURE): + return [(0, "NOT_A_PNG")] + position = len(PNG_SIGNATURE) + number = 0 + problems = [] + header = b"" + pixels = [] + while True: + number += 1 + if position + 8 > len(data): + return problems + [(number, "PNG_TRUNCATED")] + length, kind = struct.unpack(">I4s", data[position : position + 8]) + end = position + 8 + length + 4 + if end > len(data): + return problems + [(number, "PNG_TRUNCATED")] + body = data[position + 8 : position + 8 + length] + (crc,) = struct.unpack(">I", data[position + 8 + length : end]) + if zlib.crc32(kind + body) != crc: + problems.append((number, "PNG_BAD_CRC")) + if kind not in PNG_CHUNKS: + # A chunk's type is four letters, which name the kind of chunk, never its data. + shown = kind.decode("ascii") if kind.isalpha() else "?" + problems.append((number, "PNG_CHUNK_NOT_ALLOWED " + shown)) + elif (number == 1) != (kind == b"IHDR"): + problems.append((number, "PNG_IHDR_NOT_FIRST_AND_ONLY")) + if kind == b"IHDR" and number == 1: + header = body + elif kind == b"IDAT": + pixels.append(body) + position = end + if kind == b"IEND": + if position != len(data): + problems.append((number, "PNG_DATA_AFTER_IEND")) + rule = pixel_problem(header, b"".join(pixels)) + if rule: + problems.append((0, rule)) + return problems + + +def check_file(path, data, is_link=False): + """The (location, rule) of each problem in the file at repository [path].""" + if is_link: + return [(0, "SYMBOLIC_LINK")] + if KOTLIN_FILE.search(path): + try: + text = data.decode("utf-8") + except UnicodeDecodeError: + return [(0, "NOT_UTF8")] + return check_kotlin(text) + if REFERENCE_IMAGE.search(path): + return check_png(data) + return [(0, "FILE_NOT_ALLOWED")] + + +def check_files(files): + """The findings in [files], (path, bytes, is_link) triples, sorted, and how many it read.""" + findings = [] + count = 0 + for path, data, is_link in files: + count += 1 + for location, rule in check_file(path, data, is_link): + findings.append((path, location, rule)) + return sorted(findings), count + + +def repository_files(root): + """Each (path, bytes, is_link) under every screenshot folder below [root].""" + def stop(error): + # os.walk skips a folder it can't list unless told otherwise, which would let the scan + # pass without reading it. + raise error + + for directory, folders, names in os.walk(root, onerror=stop): + relative = os.path.relpath(directory, root) + relative = "" if relative == "." else relative.replace(os.sep, "/") + "/" + if SCREENSHOT_FOLDER.search(relative): + # Inside a screenshot folder: read everything, links included. + entries = sorted(folders + names) + folders[:] = [ + name for name in folders if not os.path.islink(os.path.join(directory, name)) + ] + for name in entries: + full = os.path.join(directory, name) + if os.path.islink(full): + yield relative + name, b"", True + elif os.path.isfile(full): + with open(full, "rb") as file: + yield relative + name, file.read(), False + continue + for name in sorted(folders + names): + # os.walk doesn't follow a linked folder, and lists a link to nothing as a file, so a + # linked screenshot folder would otherwise go unread. + if SCREENSHOT_FOLDER.search(relative + name + "/") and os.path.islink( + os.path.join(directory, name) + ): + yield relative + name, b"", True + # A folder below the root with a .git entry is another repository or another worktree, + # such as the ones under .claude/worktrees/, whose files aren't this checkout's. + folders[:] = sorted( + name + for name in folders + if (name not in SKIPPED_FOLDERS or SCREENSHOT_FOLDER.search(relative + name + "/")) + and not os.path.lexists(os.path.join(directory, name, ".git")) + ) + + +def main(arguments): + root = arguments[0] if arguments else "." + try: + findings, count = check_files(repository_files(root)) + except Exception as error: # noqa: BLE001 - any error must fail the check, never pass it. + print(f"FAIL the scan stopped: {type(error).__name__}") + return 1 + for path, location, rule in findings: + print(f"{path}:{location} {rule}") + if count == 0: + print("FAIL no screenshot test file was found") + return 1 + if findings: + print(f"FAIL {len(findings)} problems in {count} files") + return 1 + print(f"PASS {count} files") + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/scripts/tests/test_gate_with_git.py b/scripts/tests/test_gate_with_git.py index 0856733..b373e32 100644 --- a/scripts/tests/test_gate_with_git.py +++ b/scripts/tests/test_gate_with_git.py @@ -21,6 +21,7 @@ LOCAL = ("A Maintainer", "maintainer@example.com") SAVED = pre_push_gate.SAVED_RESPONSES +SCREENSHOT_KOTLIN = "feature/x-ui/src/screenshotTest/kotlin/a/b/XScreenshots.kt" class GitRepository: @@ -148,6 +149,58 @@ def test_a_commit_that_deletes_the_saved_responses_passes(self): self.assertEqual([], self.problems_of(commit)) + def test_a_commit_that_changes_screenshot_tests_is_scanned(self): + self.repository.write(SCREENSHOT_KOTLIN, 'package a.b\n\nprintln("x")\n') + commit = self.repository.commit("test: add a screenshot test") + + self.assertEqual( + [f"SCREENSHOT_TEST {SCREENSHOT_KOTLIN}:3 LINE_NOT_ALLOWED"], self.problems_of(commit) + ) + + def test_a_commit_with_good_screenshot_wrappers_passes(self): + self.repository.write( + SCREENSHOT_KOTLIN, + "package a.b\n\n@PreviewTest\n@Preview(name = \"Light\")\n@Composable\n" + "private fun AScreenshot() = APreview()\n", + ) + commit = self.repository.commit("test: add a screenshot test") + + self.assertEqual([], self.problems_of(commit)) + + def test_a_commit_that_leaves_screenshot_tests_alone_isnt_scanned(self): + # This file would fail the scan, so a scan of the second commit would show. + self.repository.write(SCREENSHOT_KOTLIN, 'println("x")\n') + self.repository.commit("test: plant a call") + self.repository.write("docs/notes.md", "Notes\n") + commit = self.repository.commit("docs: add notes") + + self.assertEqual([], self.problems_of(commit)) + + def test_a_linked_screenshot_file_is_refused(self): + self.repository.write("elsewhere/B.kt", 'println("x")\n') + link = os.path.join(self.repository.path, SCREENSHOT_KOTLIN) + os.makedirs(os.path.dirname(link)) + os.symlink(os.path.join(self.repository.path, "elsewhere/B.kt"), link) + commit = self.repository.commit("test: link a screenshot test") + + self.assertEqual( + [f"SCREENSHOT_TEST {SCREENSHOT_KOTLIN}:0 SYMBOLIC_LINK"], self.problems_of(commit) + ) + + def test_a_link_in_place_of_a_screenshot_folder_is_refused(self): + self.repository.write("elsewhere/kotlin/a/B.kt", 'println("x")\n') + folder = os.path.join(self.repository.path, "feature/x-ui/src") + os.makedirs(folder) + os.symlink( + os.path.join(self.repository.path, "elsewhere"), os.path.join(folder, "screenshotTest") + ) + commit = self.repository.commit("test: link a screenshot folder") + + self.assertEqual( + ["SCREENSHOT_TEST feature/x-ui/src/screenshotTest:0 SYMBOLIC_LINK"], + self.problems_of(commit), + ) + def test_a_secret_file_is_refused(self): self.repository.write("local.properties", "sdk.dir=/somewhere\n") commit = self.repository.commit("chore: add a file") diff --git a/scripts/tests/test_scan_screenshot_tests.py b/scripts/tests/test_scan_screenshot_tests.py new file mode 100644 index 0000000..d47bede --- /dev/null +++ b/scripts/tests/test_scan_screenshot_tests.py @@ -0,0 +1,490 @@ +"""Tests of scan_screenshot_tests.py: the allowed shapes pass, and everything else fails. + +Each test builds the files it checks, in memory or in a temporary folder. +""" + +import contextlib +import io +import os +import struct +import sys +import tempfile +import unittest +import zlib + +sys.dont_write_bytecode = True +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")) + +import scan_screenshot_tests as scan # noqa: E402 + +KOTLIN = "feature/x-ui/src/screenshotTest/kotlin/a/b/XScreenshots.kt" +IMAGE = "feature/x-ui/src/screenshotTestDefaultDebug/reference/a/b/XScreenshotsKt/A_Light_0.png" + +GOOD_WRAPPERS = """package io.github.dewfallapp.feature.x.ui + +// A comment line. +import android.content.res.Configuration +import androidx.compose.runtime.Composable +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.tooling.preview.Wallpapers +import com.android.tools.screenshot.PreviewTest + +@PreviewTest +@Preview(name = "Light") +@Preview( + name = "Dark", + uiMode = Configuration.UI_MODE_NIGHT_YES or Configuration.UI_MODE_TYPE_NORMAL, +) +@Preview(name = "LargeFont", fontScale = 2f) +@Preview(name = "Tablet", widthDp = 1280, heightDp = 800, showSystemUi = false) +@Preview(name = "DynamicLight", wallpaper = Wallpapers.BLUE_DOMINATED_EXAMPLE) +@Composable +private fun ResultsScreenshot() = ResultsPreview() + +@PreviewTest @Preview(name = "Light") @Composable private fun EndedScreenshot() = EndedPreview() +""" + +WRAPPER_HEAD = """package a.b + +@PreviewTest +@Preview(name = "Light") +@Composable +""" + + +def chunk(kind, data): + return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data)) + + +HEADER = chunk(b"IHDR", struct.pack(">IIBBBBB", 1, 1, 8, 2, 0, 0, 0)) +PIXELS = chunk(b"IDAT", zlib.compress(b"\x00\x00\x00\x00")) +END = chunk(b"IEND", b"") + + +def png(*chunks): + return scan.PNG_SIGNATURE + b"".join(chunks) + + +GOOD_PNG = png(HEADER, PIXELS, END) + + +def kotlin_rules(text): + return [rule for _, rule in scan.check_kotlin(text)] + + +def file_rules(path, data, is_link=False): + return [rule for _, rule in scan.check_file(path, data, is_link)] + + +class KotlinTest(unittest.TestCase): + def test_wrappers_in_both_layouts_pass(self): + self.assertEqual([], kotlin_rules(GOOD_WRAPPERS)) + + def test_an_empty_file_passes(self): + self.assertEqual([], kotlin_rules("")) + + def test_a_logging_call_on_its_own_line_fails(self): + for line in [ + 'println("x")', + 'Log.d("tag", "x")', + "Thread.dumpStack()", + 'val logger = System.getLogger("x")', + 'private val log = java.util.logging.Logger.getLogger("x")', + ]: + with self.subTest(line=line): + text = "package a.b\n\n" + line + "\n" + self.assertEqual(["LINE_NOT_ALLOWED"], kotlin_rules(text)) + + def test_a_callable_reference_fails(self): + text = WRAPPER_HEAD + "private fun AScreenshot() = listOf(1).forEach(::println)\n" + + self.assertEqual(["WRAPPER_NOT_ONE_CALL"], kotlin_rules(text)) + + def test_a_block_body_fails(self): + text = WRAPPER_HEAD + 'private fun AScreenshot() {\n println("x")\n APreview()\n}\n' + + self.assertEqual( + ["WRAPPER_NOT_ONE_CALL", "LINE_NOT_ALLOWED", "LINE_NOT_ALLOWED", "LINE_NOT_ALLOWED"], + kotlin_rules(text), + ) + + def test_a_call_with_arguments_fails(self): + self.assertEqual( + ["WRAPPER_NOT_ONE_CALL"], + kotlin_rules(WRAPPER_HEAD + "private fun AScreenshot() = APreview(1)\n"), + ) + + def test_a_call_to_another_preview_fails(self): + self.assertEqual( + ["WRAPPER_NOT_ONE_CALL"], + kotlin_rules(WRAPPER_HEAD + "private fun AScreenshot() = BPreview()\n"), + ) + + def test_a_wrapper_that_isnt_private_fails(self): + self.assertEqual( + ["WRAPPER_NOT_ONE_CALL"], + kotlin_rules(WRAPPER_HEAD + "internal fun AScreenshot() = APreview()\n"), + ) + + def test_a_one_line_wrapper_with_another_body_fails(self): + line = ( + '@PreviewTest @Preview(name = "Light") @Composable ' + "private fun AScreenshot() = run { }" + ) + + self.assertEqual(["LINE_NOT_ALLOWED"], kotlin_rules(line + "\n")) + + def test_a_string_with_a_template_or_a_backslash_fails(self): + for argument in ['name = "${x}"', 'name = "$x"', 'name = "a\\u0041"']: + with self.subTest(argument=argument): + text = "@PreviewTest\n@Preview(" + argument + ")\n@Composable\n" + text += "private fun AScreenshot() = APreview()\n" + self.assertEqual( + ["WRAPPER_ANNOTATION_NOT_ALLOWED", "LINE_NOT_ALLOWED"], kotlin_rules(text)[:2] + ) + + def test_a_call_in_an_annotation_argument_fails(self): + text = "@PreviewTest\n@Preview(\n name = name(),\n)\n@Composable\n" + text += "private fun AScreenshot() = APreview()\n" + + self.assertEqual(["PREVIEW_ARGUMENT_NOT_ALLOWED"], kotlin_rules(text)) + + def test_an_import_alias_or_a_wildcard_import_fails(self): + for line in ["import a.b.C as D", "import a.b.*"]: + with self.subTest(line=line): + self.assertEqual(["LINE_NOT_ALLOWED"], kotlin_rules(line + "\n")) + + def test_a_file_annotation_fails(self): + self.assertEqual(["LINE_NOT_ALLOWED"], kotlin_rules('@file:Suppress("x")\npackage a.b\n')) + + def test_a_wrapper_without_preview_test_fails(self): + text = '@Preview(name = "Light")\n@Composable\nprivate fun AScreenshot() = APreview()\n' + + self.assertEqual(["LINE_NOT_ALLOWED"] * 3, kotlin_rules(text)) + + def test_a_wrapper_without_a_preview_fails(self): + text = "@PreviewTest\n@Composable\nprivate fun AScreenshot() = APreview()\n" + + self.assertEqual(["WRAPPER_ANNOTATION_NOT_ALLOWED", "LINE_NOT_ALLOWED"], kotlin_rules(text)) + + def test_an_annotation_left_open_fails(self): + self.assertEqual(["WRAPPER_NOT_FINISHED"], kotlin_rules("@PreviewTest\n@Preview(")) + self.assertEqual( + ["PREVIEW_ARGUMENT_NOT_ALLOWED", "WRAPPER_NOT_FINISHED"], + kotlin_rules("@PreviewTest\n@Preview(\n"), + ) + self.assertEqual(["WRAPPER_NOT_FINISHED"], kotlin_rules("@PreviewTest")) + self.assertEqual(["WRAPPER_ANNOTATION_NOT_ALLOWED"], kotlin_rules("@PreviewTest\n")) + + def test_a_second_package_or_a_late_import_fails(self): + self.assertEqual(["PACKAGE_NOT_FIRST"], kotlin_rules("package a\npackage b\n")) + text = WRAPPER_HEAD + "private fun AScreenshot() = APreview()\nimport a.B\n" + self.assertEqual(["IMPORT_AFTER_WRAPPER"], kotlin_rules(text)) + + def test_windows_line_endings_fail(self): + self.assertEqual(["CONTROL_CHARACTER"], kotlin_rules("package a.b\r\n")) + + def test_a_carriage_return_inside_a_comment_fails(self): + # Kotlin reads the \r as a line break, so the call after it would compile. + text = "package a.b\n\n// hi\rval x = run { println(1) }\n" + + self.assertEqual([(3, "CONTROL_CHARACTER")], scan.check_kotlin(text)) + + def test_other_control_and_separator_characters_fail(self): + for character in ["\t", "\x0b", "\x0c", "\x85", "\u2028", "\u2029", "\x00"]: + with self.subTest(character=repr(character)): + self.assertEqual( + ["CONTROL_CHARACTER"], kotlin_rules("// a" + character + "b\n") + ) + + def test_letters_outside_ascii_in_a_comment_pass(self): + self.assertEqual([], kotlin_rules("// Dew, Ros\u00e9e\n")) + + +class PngTest(unittest.TestCase): + def test_a_plain_image_passes(self): + self.assertEqual([], scan.check_png(GOOD_PNG)) + + def test_a_palette_fails(self): + data = png(HEADER, chunk(b"PLTE", b"\x00" * 3), PIXELS, END) + + self.assertEqual([(2, "PNG_CHUNK_NOT_ALLOWED PLTE")], scan.check_png(data)) + + def test_a_second_header_fails(self): + data = png(HEADER, HEADER, PIXELS, END) + + self.assertEqual([(2, "PNG_IHDR_NOT_FIRST_AND_ONLY")], scan.check_png(data)) + + def test_every_other_chunk_fails(self): + kinds = [b"tEXt", b"iTXt", b"zTXt", b"eXIf", b"tIME", b"iCCP", b"pHYs", b"PLTE", b"prVt"] + for kind in kinds: + with self.subTest(kind=kind): + data = png(HEADER, chunk(kind, b"user=someone"), PIXELS, END) + self.assertEqual( + [(2, "PNG_CHUNK_NOT_ALLOWED " + kind.decode())], scan.check_png(data) + ) + + def test_a_chunk_type_that_isnt_letters_is_not_shown(self): + data = png(HEADER, chunk(b"\x00\x01ab", b""), PIXELS, END) + + self.assertEqual([(2, "PNG_CHUNK_NOT_ALLOWED ?")], scan.check_png(data)) + + def test_a_file_without_the_signature_fails(self): + self.assertEqual([(0, "NOT_A_PNG")], scan.check_png(b"GIF89a")) + + def test_a_truncated_image_fails(self): + self.assertEqual("PNG_TRUNCATED", scan.check_png(GOOD_PNG[:-6])[-1][1]) + self.assertEqual("PNG_TRUNCATED", scan.check_png(scan.PNG_SIGNATURE + HEADER[:5])[-1][1]) + + def test_a_missing_end_fails(self): + self.assertEqual([(3, "PNG_TRUNCATED")], scan.check_png(png(HEADER, PIXELS))) + + def test_a_bad_crc_fails(self): + broken = HEADER[:-1] + bytes([HEADER[-1] ^ 1]) + + self.assertEqual([(1, "PNG_BAD_CRC")], scan.check_png(png(broken, PIXELS, END))) + + def test_data_after_the_end_fails(self): + self.assertEqual([(3, "PNG_DATA_AFTER_IEND")], scan.check_png(GOOD_PNG + b"x")) + + def test_a_first_chunk_other_than_the_header_fails(self): + self.assertEqual( + [ + (1, "PNG_IHDR_NOT_FIRST_AND_ONLY"), + (2, "PNG_IHDR_NOT_FIRST_AND_ONLY"), + (0, "PNG_HEADER_NOT_ALLOWED"), + ], + scan.check_png(png(PIXELS, HEADER, END)), + ) + + def test_bytes_after_the_zlib_stream_fail(self): + # A decoder ignores them, so text could hide there. + hidden = chunk(b"IDAT", zlib.compress(b"\x00\x00\x00\x00") + b"hostname=machine") + + self.assertEqual([(0, "PNG_PIXELS_NOT_EXACT")], scan.check_png(png(HEADER, hidden, END))) + + def test_more_or_fewer_pixel_bytes_than_the_header_says_fail(self): + for raw in [b"\x00\x00\x00\x00secret", b"\x00\x00"]: + with self.subTest(raw=raw): + data = png(HEADER, chunk(b"IDAT", zlib.compress(raw)), END) + self.assertEqual([(0, "PNG_PIXELS_NOT_EXACT")], scan.check_png(data)) + + def test_a_stream_split_over_several_chunks_passes(self): + stream = zlib.compress(b"\x00\x00\x00\x00") + data = png(HEADER, chunk(b"IDAT", stream[:3]), chunk(b"IDAT", stream[3:]), END) + + self.assertEqual([], scan.check_png(data)) + + def test_an_unfinished_or_broken_stream_fails(self): + stream = zlib.compress(b"\x00\x00\x00\x00") + unfinished = png(HEADER, chunk(b"IDAT", stream[:-4]), END) + broken = png(HEADER, chunk(b"IDAT", b"not zlib"), END) + + self.assertEqual([(0, "PNG_PIXELS_NOT_EXACT")], scan.check_png(unfinished)) + self.assertEqual([(0, "PNG_PIXELS_NOT_ZLIB")], scan.check_png(broken)) + + def test_an_interlaced_or_odd_header_fails(self): + for fields in [ + (1, 1, 8, 2, 0, 0, 1), + (1, 1, 8, 7, 0, 0, 0), + (1, 1, 3, 2, 0, 0, 0), + (1, 1, 8, 3, 0, 0, 0), + ]: + with self.subTest(fields=fields): + header = chunk(b"IHDR", struct.pack(">IIBBBBB", *fields)) + self.assertEqual( + [(0, "PNG_HEADER_NOT_ALLOWED")], scan.check_png(png(header, PIXELS, END)) + ) + + def test_an_image_too_big_to_check_fails(self): + header = chunk(b"IHDR", struct.pack(">IIBBBBB", 100_000, 100_000, 8, 6, 0, 0, 0)) + + self.assertEqual([(0, "PNG_HEADER_NOT_ALLOWED")], scan.check_png(png(header, PIXELS, END))) + + +class FileTest(unittest.TestCase): + def test_a_wrapper_file_and_an_image_pass(self): + self.assertEqual([], file_rules(KOTLIN, GOOD_WRAPPERS.encode())) + self.assertEqual([], file_rules(IMAGE, GOOD_PNG)) + + def test_files_in_the_wrong_place_fail(self): + for path in [ + "feature/x-ui/src/screenshotTest/java/a/B.java", + "feature/x-ui/src/screenshotTest/kotlin/a/B.java", + "feature/x-ui/src/screenshotTestDefaultDebug/kotlin/a/B.kt", + "feature/x-ui/src/screenshotTest/res/values/strings.xml", + "feature/x-ui/src/screenshotTest/kotlin/a/b.png", + "feature/x-ui/src/screenshotTest/reference/a.png", + "feature/x-ui/src/screenshotTestDefaultDebug/reference/a.txt", + ]: + with self.subTest(path=path): + self.assertEqual(["FILE_NOT_ALLOWED"], file_rules(path, b"")) + + def test_a_symbolic_link_fails(self): + self.assertEqual(["SYMBOLIC_LINK"], file_rules(KOTLIN, b"", is_link=True)) + + def test_a_file_that_isnt_utf8_fails(self): + self.assertEqual(["NOT_UTF8"], file_rules(KOTLIN, b"package a\n\xff\n")) + + +class RepositoryTest(unittest.TestCase): + def setUp(self): + self.folder = tempfile.TemporaryDirectory() + self.root = self.folder.name + + def tearDown(self): + self.folder.cleanup() + + def write(self, path, data): + full = os.path.join(self.root, path) + os.makedirs(os.path.dirname(full), exist_ok=True) + with open(full, "wb") as file: + file.write(data) + + def run_main(self): + output = io.StringIO() + with contextlib.redirect_stdout(output): + code = scan.main([self.root]) + return code, output.getvalue() + + def test_a_clean_repository_passes(self): + self.write(KOTLIN, GOOD_WRAPPERS.encode()) + self.write(IMAGE, GOOD_PNG) + self.write("feature/x-ui/src/main/kotlin/a/b/Logging.kt", b'println("x")\n') + self.write("feature/x-ui/build/src/screenshotTest/kotlin/a/Bad.kt", b'println("x")\n') + + code, output = self.run_main() + + self.assertEqual(0, code, output) + self.assertEqual("PASS 2 files\n", output) + + def test_a_problem_fails_and_names_the_file_and_rule_but_not_the_line(self): + self.write(KOTLIN, b'package a.b\n\nprintln("secret text")\n') + + code, output = self.run_main() + + self.assertEqual(1, code) + self.assertIn(KOTLIN + ":3 LINE_NOT_ALLOWED", output) + self.assertNotIn("secret text", output) + + def test_a_folder_named_build_inside_a_screenshot_folder_is_read(self): + self.write("feature/x-ui/src/screenshotTest/build/a.kt", b"") + + code, output = self.run_main() + + self.assertEqual(1, code) + self.assertIn("src/screenshotTest/build/a.kt:0 FILE_NOT_ALLOWED", output) + + def test_a_linked_screenshot_folder_fails(self): + self.write("elsewhere/kotlin/a/B.kt", b'println("x")\n') + os.makedirs(os.path.join(self.root, "feature/x-ui/src")) + os.symlink( + os.path.join(self.root, "elsewhere"), + os.path.join(self.root, "feature/x-ui/src/screenshotTest"), + ) + + code, output = self.run_main() + + self.assertEqual(1, code) + self.assertIn("feature/x-ui/src/screenshotTest:0 SYMBOLIC_LINK", output) + + def test_a_link_to_nothing_in_place_of_a_screenshot_folder_fails(self): + self.write(KOTLIN, GOOD_WRAPPERS.encode()) + os.makedirs(os.path.join(self.root, "feature/y-ui/src")) + os.symlink( + os.path.join(self.root, "nowhere"), + os.path.join(self.root, "feature/y-ui/src/screenshotTest"), + ) + + code, output = self.run_main() + + self.assertEqual(1, code) + self.assertIn("feature/y-ui/src/screenshotTest:0 SYMBOLIC_LINK", output) + + def test_a_linked_file_or_folder_inside_a_screenshot_folder_fails(self): + self.write(KOTLIN, GOOD_WRAPPERS.encode()) + self.write("elsewhere/B.kt", b'println("x")\n') + kotlin_folder = os.path.join(self.root, os.path.dirname(KOTLIN)) + os.symlink(os.path.join(self.root, "elsewhere/B.kt"), os.path.join(kotlin_folder, "B.kt")) + os.symlink(os.path.join(self.root, "elsewhere"), os.path.join(kotlin_folder, "more")) + + code, output = self.run_main() + + self.assertEqual(1, code) + self.assertIn("B.kt:0 SYMBOLIC_LINK", output) + self.assertIn("more:0 SYMBOLIC_LINK", output) + + def test_a_folder_it_cant_list_fails(self): + self.write(KOTLIN, GOOD_WRAPPERS.encode()) + hidden = os.path.join(self.root, "feature/y-ui/src/screenshotTest/kotlin") + os.makedirs(hidden) + os.chmod(hidden, 0) + try: + code, output = self.run_main() + finally: + os.chmod(hidden, 0o755) + + self.assertEqual(1, code) + self.assertIn("FAIL the scan stopped: PermissionError", output) + + def test_the_folder_pattern_matches_the_folder_itself_and_its_files(self): + for path in [ + "feature/x-ui/src/screenshotTest", + "feature/x-ui/src/screenshotTestDefaultDebug", + "feature/x-ui/src/screenshotTest/kotlin/a/B.kt", + "src/screenshotTest/kotlin/a/B.kt", + ]: + with self.subTest(path=path): + self.assertTrue(scan.SCREENSHOT_FOLDER.search(path)) + for path in ["feature/x-ui/src/main/kotlin/a/B.kt", "feature/x-ui/src/test/screenshotTest"]: + with self.subTest(path=path): + self.assertFalse(scan.SCREENSHOT_FOLDER.search(path)) + + def test_a_folder_named_in_other_case_is_read_and_fails(self): + self.write("feature/x-ui/src/ScreenshotTest/kotlin/a/B.kt", b'println("x")\n') + + code, output = self.run_main() + + self.assertEqual(1, code) + self.assertIn("src/ScreenshotTest/kotlin/a/B.kt:0 FILE_NOT_ALLOWED", output) + + def test_another_worktree_inside_the_root_is_left_alone(self): + self.write(KOTLIN, GOOD_WRAPPERS.encode()) + other = ".claude/worktrees/other/" + self.write(other + ".git", b"gitdir: /somewhere\n") + self.write(other + KOTLIN, b'println("x")\n') + + code, output = self.run_main() + + self.assertEqual(0, code, output) + self.assertEqual("PASS 1 files\n", output) + + def test_no_screenshot_file_fails(self): + self.write("feature/x-ui/src/main/kotlin/a/B.kt", b"") + + code, output = self.run_main() + + self.assertEqual(1, code) + self.assertIn("FAIL no screenshot test file was found", output) + + def test_an_error_fails_the_scan(self): + code, output = self.run_main_with_broken_reader() + + self.assertEqual(1, code) + self.assertIn("FAIL the scan stopped: OSError", output) + + def run_main_with_broken_reader(self): + def broken(_root): + raise OSError("unreadable") + yield # A generator, like repository_files. + + saved = scan.repository_files + scan.repository_files = broken + try: + return self.run_main() + finally: + scan.repository_files = saved + + +if __name__ == "__main__": + unittest.main()