mirror of
https://github.com/kuhyx/testsAndMisc.git
synced 2026-11-24 12:46:18 +01:00
Compare commits
No commits in common. "dadd33f82d0d8d78493b9b3e33f8f57d968679f8" and "e3214c813cb988aa90cb769967f618d603675773" have entirely different histories.
dadd33f82d
...
e3214c813c
@ -167,41 +167,3 @@ Coverage: `meta/pyproject.toml` sets `source = ["python_pkg"]`, so a new
|
||||
sibling module is measured automatically. Confirmed: new modules show up in
|
||||
the report at 100% rather than being silently skipped. Add no new branches
|
||||
(no `if TYPE_CHECKING` guards beyond what moved, no defensive `try/except`).
|
||||
|
||||
## The seam-selection rule (settled over 8 packages)
|
||||
|
||||
Generalised from `python_pkg`; full detail in `docs/python-split-recipes.md`.
|
||||
|
||||
**A block may move if every MOD-relative patch that reaches it comes from one
|
||||
test module. If two test modules patch a shared collaborator, keep the
|
||||
collaborator and move its callers instead.** The caller resolves the name
|
||||
through its _own_ module's globals, so importing it into the new module makes
|
||||
the patch land there.
|
||||
|
||||
Corollaries that each cost a failed run to learn:
|
||||
|
||||
- **`test_X.py` needing no edit is the signal you cut in the right place.**
|
||||
It held on four of five source splits in `brother_printer`.
|
||||
- **Never blanket-`sed` a MOD.** Decide per test _by which function is under
|
||||
test_. `test_challenge_part3.py` needed 13 of its strings repointed and 4
|
||||
left alone.
|
||||
- **A mispointed patch does not always fail — it can HANG or do real work.**
|
||||
`code_tutor` spun for two minutes running a real interactive flow;
|
||||
`cups_queue` would have restarted the live CUPS daemon. Always run under
|
||||
`timeout`, and assert the targets resolve _before_ invoking pytest.
|
||||
- **When splitting a test file, copy the WHOLE preamble** (docstring, imports,
|
||||
fixture builders) into the new file and let ruff's `F401` pass prune it.
|
||||
Hand-writing the import block failed on every early attempt; the copy-then-
|
||||
prune order removed 82 imports correctly in `wsg_grabber` with none missed.
|
||||
It does **not** cover module-level `def`s and constants sitting _between_
|
||||
sections — `_make_verifier`, `_QUESTIONS`, `_logger` and
|
||||
`_SAME_FIELD_X_TOLERANCE_PX` were each left behind that way. Grep for them.
|
||||
- **Budget two cuts.** Nine of the splits landed 1–20 lines over after the
|
||||
first seam. Pure-data blocks (prompt strings, skip tables, SVG fragments)
|
||||
are the cheapest second cut and have no patch targets.
|
||||
- **Prefer a `conftest.py` fixture over a duplicated builder** — that is where
|
||||
`_make_verifier` went, and it removed a shadowing copy of `_make_live_mock`.
|
||||
|
||||
Two helper scripts are in the scratchpad, not committed (they are throwaway):
|
||||
they cut a module at a banner comment or at a named `def`/`class` and copy the
|
||||
preamble. Rewriting them takes about five minutes.
|
||||
|
||||
@ -1,87 +0,0 @@
|
||||
# Shell split recipes for the 250-line cap
|
||||
|
||||
Split out of `refactor_claude_todo_resume.md` (which is itself capped).
|
||||
Applies to `linux_configuration/` and `phone_focus_mode/`.
|
||||
|
||||
`linux_configuration` and `phone_focus_mode` have **no test suite and no
|
||||
coverage gate**, so none of the above transfers. Decision 6 governs:
|
||||
`bash -n` + `shellcheck` + `systemctl cat` path checks, and **never execute an
|
||||
enforcement script that mutates the live system or the phone.**
|
||||
|
||||
- After each split, `bash -n` and `shellcheck` the entry script _and_ every new
|
||||
lib. **Neither catches a `source` line that resolves to the wrong path** —
|
||||
both passed clean on a split whose lib was unreachable at runtime.
|
||||
- So the real check is a **stubbed run**: copy the entry script and its libs to
|
||||
a `mktemp -d`, `sed` the final `main` invocation into a `declare -F` probe,
|
||||
and run it. That executes the `source` lines and nothing else. This caught
|
||||
the bug below; no static check did.
|
||||
|
||||
### Use `${BASH_SOURCE[0]}`, not `$0`
|
||||
|
||||
The repo's existing convention is
|
||||
`SCRIPT_DIR="$(dirname "$(readlink -f "$0")")"`, which works only while the
|
||||
script is executed directly. `$0` is the **sourcing** script, so the moment an
|
||||
entry script is itself sourced, `SCRIPT_DIR` points somewhere else and the lib
|
||||
is not found. Write new ones as:
|
||||
|
||||
```bash
|
||||
SCRIPT_DIR="$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")"
|
||||
```
|
||||
|
||||
`readlink -f` is still required — it is what makes the one symlinked script
|
||||
(`/usr/local/bin/start-player2`) resolve back into the repo.
|
||||
|
||||
### Shape of a new lib (two hooks disagree unless you get this right)
|
||||
|
||||
Follow `scripts/lib/common.sh`: **shebang present, file executable.** The two
|
||||
obvious-looking alternatives each fail a hook:
|
||||
|
||||
- No shebang → `shellcheck` SC2148 ("target shell unknown").
|
||||
- Shebang but not executable → `check-shebang-scripts-are-executable`.
|
||||
|
||||
So: `#!/bin/bash`, `chmod +x`, and **no `set -euo pipefail`** — a sourced lib
|
||||
inherits the caller's strict mode, and redeclaring it is duplicated
|
||||
boilerplate that feeds jscpd. Say so in the lib's header comment.
|
||||
|
||||
- **Two live units point at repo paths** and break if a file moves or is
|
||||
renamed. `systemctl cat` them after touching either:
|
||||
- `/etc/systemd/system/dns-blocklist-refresh.service` →
|
||||
`scripts/single_use/features/setup_dns_blocker.sh refresh`
|
||||
- `/etc/systemd/system/media-organizer.service` →
|
||||
`scripts/single_use/utils/organize_downloads.sh`
|
||||
|
||||
Every other in-repo unit references an installed copy under `/usr/local/`,
|
||||
so those are only at risk if the _installer_ is what you split.
|
||||
|
||||
## Which scripts escape the repo (enumerated 2026-08-16)
|
||||
|
||||
A split is only safe if the file still resolves its libs from wherever it
|
||||
actually runs. Two ways a script leaves the repo, both silent when broken:
|
||||
|
||||
- **Copied out** — only three, all under
|
||||
`scripts/periodic_background/hosts/guard/pacman-hooks/`, installed to
|
||||
`/usr/local/share/hosts-guard/` by `hosts/guard/install_pacman_hooks.sh`.
|
||||
Splitting any of those three means the installer must copy the new libs too,
|
||||
**in the same commit** — the same trap as `phone_focus_mode/deploy.sh`.
|
||||
- **Symlinked in** — exactly one: `/usr/local/bin/start-player2` →
|
||||
`scripts/gaming/start-player2.sh`. `${BASH_SOURCE[0]%/*}` resolves to
|
||||
`/usr/local/bin` there, so a lib path must go through
|
||||
`readlink -f "${BASH_SOURCE[0]}"` first.
|
||||
|
||||
Everything else under `/usr/local/` is **generated** by an installer (heredoc
|
||||
or `cat >`), not copied, so splitting the generator is safe as long as the
|
||||
generated content is unchanged. Re-run both checks if that assumption is ever
|
||||
in doubt:
|
||||
|
||||
```bash
|
||||
find /usr/local/bin /usr/local/sbin -maxdepth 1 \( -type l -o -name '*.sh' \) \
|
||||
-exec readlink -f {} \; | grep testsAndMisc
|
||||
grep -rn -E '^\s*(sudo )?(install|cp)\s.*(SCRIPT_DIR|REPO).*/usr/local/' \
|
||||
linux_configuration --include='*.sh'
|
||||
```
|
||||
|
||||
- Prefer files that **nothing** references first — pure lint risk.
|
||||
- Watch **jscpd** on the first multi-lib commit: repeated `set -euo pipefail` +
|
||||
source-guard headers across several new libs is exactly what pushes
|
||||
duplication toward the 2% threshold, and it only fires on the real
|
||||
`git commit`.
|
||||
@ -1,19 +0,0 @@
|
||||
{
|
||||
"title": "Clear five python_pkg packages under the 250-line cap",
|
||||
"objective": "Bring token_audit, focus_policy, random_jpg, app_icons and android_ui entirely under the repo-wide 250-line cap, leaving wsg_grabber as the only python_pkg package with violations.",
|
||||
"acceptance_criteria": [
|
||||
"bash ~/utils/scripts/check_file_length.sh --all lists no file under any of the five packages.",
|
||||
"Each package reports its exact baseline pass count: token_audit 81, focus_policy 137, random_jpg 14, app_icons 44, android_ui 57.",
|
||||
"Every package keeps 100% branch coverage of its source modules.",
|
||||
"AndroidUi stays defined in driver.py, since that is the only name any android_ui test patches on it.",
|
||||
"The android_ui class split uses the mixin shape from docs/python-split-recipes.md -- ABC with abstract methods for what the concrete class supplies -- because tests call the moved methods as bound attributes of a real driver.",
|
||||
"No assertion is changed and no test is deleted, skipped or weakened.",
|
||||
"No suppression is added and no coverage exclusion is introduced."
|
||||
],
|
||||
"out_of_scope": [
|
||||
"Changing what any test asserts, or any adb command the driver issues.",
|
||||
"wsg_grabber's six test modules, which are a separate commit.",
|
||||
"Changing the public re-exports in android_ui/__init__.py or app_icons' glyph names."
|
||||
],
|
||||
"verifier": "timeout 120 env PYTHONPATH=. python3 -m pytest python_pkg/<pkg>/tests -q for each of the five (expects 81, 137, 14, 44, 57), plus bash ~/utils/scripts/check_file_length.sh --all showing none of them, plus pre-commit run --files on the touched files."
|
||||
}
|
||||
@ -1,19 +0,0 @@
|
||||
{
|
||||
"title": "Clear the six over-cap wsg_grabber test modules, finishing python_pkg",
|
||||
"objective": "Bring python_pkg/wsg_grabber's six remaining test modules under the repo-wide 250-line cap, which takes the whole of python_pkg from 50 violations at the start of this effort to zero.",
|
||||
"acceptance_criteria": [
|
||||
"bash ~/utils/scripts/check_file_length.sh --all lists no file under python_pkg at all.",
|
||||
"The wsg_grabber suite still reports exactly 277 passing tests -- the same count as before the split, proving no test was dropped or silently skipped.",
|
||||
"The package keeps 100% branch coverage of the wsg_grabber source modules.",
|
||||
"Each split file carries the whole original preamble, including its pytest fixtures, so that fixture resolution is unchanged; no fixture is redefined in a way that shadows conftest.py's autouse isolate_paths.",
|
||||
"No patch string changes: the source was split in earlier sessions and every patched name already resolves on the module each file names.",
|
||||
"No assertion is changed and no test is deleted, skipped or weakened.",
|
||||
"No suppression is added and no coverage exclusion is introduced."
|
||||
],
|
||||
"out_of_scope": [
|
||||
"Changing what any test asserts.",
|
||||
"Touching the wsg_grabber source, which earlier sessions already brought under the cap.",
|
||||
"Converting the per-module fixture builders into conftest fixtures, which would change every call site."
|
||||
],
|
||||
"verifier": "timeout 180 env PYTHONPATH=. python3 -m pytest python_pkg/wsg_grabber/tests -q (expects exactly 277 passed), plus bash ~/utils/scripts/check_file_length.sh --all showing no python_pkg entry, plus pre-commit run --files on the touched files."
|
||||
}
|
||||
@ -1,50 +0,0 @@
|
||||
{
|
||||
"intent": "Bring linux_configuration/scripts/single_use/install_joplin.sh under the 250-line cap, and establish the verified shell-split pattern for the remaining 83 files in that directory.",
|
||||
"scope": [
|
||||
"linux_configuration/scripts/single_use/install_joplin.sh (299 -> 103)",
|
||||
"linux_configuration/scripts/single_use/lib/joplin_server.sh (new)",
|
||||
"docs/shell-split-recipes.md (the pattern this split established)",
|
||||
"Non-goal: no behaviour change; no installer step was executed"
|
||||
],
|
||||
"changes": [
|
||||
"Moved setup_duckdns and setup_joplin_server, the whole --with-server half, into lib/joplin_server.sh, sourced by the entry script before main runs.",
|
||||
"The lib carries a shebang and is executable, matching scripts/lib/common.sh, and deliberately omits set -euo pipefail: it is sourced, so it inherits the caller's strict mode, and repeating the boilerplate across many new libs is what feeds jscpd's duplication threshold.",
|
||||
"SCRIPT_DIR uses ${BASH_SOURCE[0]} rather than the repo's usual $0, because $0 is the sourcing script and breaks the moment an entry script is itself sourced. readlink -f is kept, since that is what makes the one symlinked script in the repo resolve correctly.",
|
||||
"Recorded in docs/shell-split-recipes.md: the enumeration of which scripts escape the repo (three copied to /usr/local/share/hosts-guard, one symlinked), the stubbed-run verification, and the lib shape that satisfies both shellcheck and the shebang-executable hook."
|
||||
],
|
||||
"verification": [
|
||||
{
|
||||
"command": "bash -n on the entry script and the lib; shellcheck on both",
|
||||
"result": "pass",
|
||||
"evidence": "Both clean. Recorded because these are NOT sufficient: they passed on the first version of this split, whose lib was unreachable at runtime."
|
||||
},
|
||||
{
|
||||
"command": "stubbed run: copy entry + lib to a mktemp -d, sed the final `main` invocation into a `declare -F` probe, run it",
|
||||
"result": "fail then pass",
|
||||
"evidence": "First run failed with 'lib/joplin_server.sh: No such file or directory' - SCRIPT_DIR was computed from $0. Fixed to ${BASH_SOURCE[0]}; the probe then reported 'all functions defined; lib sourced correctly'. This executes the source lines and nothing else, so no installer step ran."
|
||||
},
|
||||
{
|
||||
"command": "grep for the source line and resolve its path",
|
||||
"result": "pass",
|
||||
"evidence": "install_joplin.sh:74 sources $SCRIPT_DIR/lib/joplin_server.sh, which resolves to the file that exists."
|
||||
},
|
||||
{
|
||||
"command": "pre-commit run --files <changed>",
|
||||
"result": "fail then pass",
|
||||
"evidence": "check-shebang-scripts-are-executable rejected the lib, then shellcheck SC2148 rejected removing the shebang. Resolved by matching scripts/lib/common.sh (shebang + chmod +x), which is now recorded in the recipes doc so the next 83 splits do not rediscover it."
|
||||
},
|
||||
{
|
||||
"command": "wc -l",
|
||||
"result": "pass",
|
||||
"evidence": "103 and 209 lines, both under the cap."
|
||||
}
|
||||
],
|
||||
"risks": [
|
||||
"install_joplin.sh is an installer that runs pacman/docker and writes to $HOME. It was never executed, per decision 6; the stubbed run only proves the functions are defined and the source line resolves. Whether the installer still works end-to-end is unverified and unverifiable without running it.",
|
||||
"The lib assumes the caller has defined info/warn/error and the JOPLIN_*/DUCKDNS_* variables. That holds because it is sourced after them, but it is an ordering dependency the file cannot enforce."
|
||||
],
|
||||
"rollback": [
|
||||
"git revert the commit; install_joplin.sh returns to 299 lines and the lib disappears.",
|
||||
"After rollback, re-run bash -n and shellcheck on the restored script."
|
||||
]
|
||||
}
|
||||
@ -1,48 +0,0 @@
|
||||
{
|
||||
"intent": "Clear the five smaller python_pkg packages under the 250-line cap, leaving only wsg_grabber's test modules.",
|
||||
"scope": [
|
||||
"python_pkg/android_ui/driver.py (411 -> 205) + _elements.py, _text_entry.py (new)",
|
||||
"python_pkg/android_ui/tests/test_driver.py (377 -> 211) + test_text_entry.py, test_shell_helpers.py (new)",
|
||||
"python_pkg/app_icons/glyphs.py (291 -> 93) + _glyph_art.py (new)",
|
||||
"python_pkg/token_audit/tests/test_parse.py (271 -> 209) + test_parse_events.py (new)",
|
||||
"python_pkg/focus_policy/tests/test_model.py (269 -> 148), test_export.py (255 -> 161) + two new modules",
|
||||
"python_pkg/random_jpg/tests/test_generate_jpeg.py (251 -> 138) + test_generate_jpeg_io.py (new)",
|
||||
"Non-goal: no assertion changed, no test deleted, skipped or weakened"
|
||||
],
|
||||
"changes": [
|
||||
"android_ui/driver.py needed two cuts and a class split. The UiElement dataclass, the three error types and the XML parser moved to _elements.py; the text-entry and keyboard methods became a TextEntryMixin in _text_entry.py. The mixin shape is the one docs/python-split-recipes.md settled on: an ABC declaring _run, dump and wait_for as abstract, because test_driver.py calls the moved methods as bound attributes of a real driver, so module-level functions would not have worked.",
|
||||
"AndroidUi stays in driver.py and driver re-imports the moved names, so android_ui/__init__.py's public re-exports are untouched.",
|
||||
"app_icons/glyphs.py: the twelve SVG path fragments moved to _glyph_art.py, leaving the dataclass, registry and lookup. Pure data with no patch targets.",
|
||||
"The four remaining test modules were partitioned at topic boundaries with a splitter that copies the whole preamble - docstring, imports and local fixture builders - and lets ruff prune what each half does not use."
|
||||
],
|
||||
"verification": [
|
||||
{
|
||||
"command": "timeout 120 env PYTHONPATH=. python3 -m pytest python_pkg/<pkg>/tests -q, for each of the five",
|
||||
"result": "pass",
|
||||
"evidence": "token_audit 81, focus_policy 137, random_jpg 14, app_icons 44, android_ui 57 - each identical to its baseline measured before any edit."
|
||||
},
|
||||
{
|
||||
"command": "timeout 120 env PYTHONPATH=. python3 -m pytest python_pkg/android_ui/tests -q (intermediate runs)",
|
||||
"result": "fail then pass",
|
||||
"evidence": "Three intermediate failures, all module-level globals that travelled with their code and were not in my hand-written header: _logger (used by the moved XML parser), then re and _SAME_FIELD_X_TOLERANCE_PX (used by the mixin). Same class of miss as _make_verifier and _QUESTIONS earlier - a def or constant between sections, which ruff cannot flag."
|
||||
},
|
||||
{
|
||||
"command": "bash ~/utils/scripts/check_file_length.sh --all | grep -E 'android_ui|app_icons|focus_policy|token_audit|random_jpg'",
|
||||
"result": "pass",
|
||||
"evidence": "No output - all five packages are entirely under the cap."
|
||||
},
|
||||
{
|
||||
"command": "pre-commit run --files <the touched files and artifacts>",
|
||||
"result": "fail then pass",
|
||||
"evidence": "ruff E402 and pylint C0413 on glyphs.py: I had placed the new import after the dataclass rather than in the import block. Moved; the gate then passed with ruff, ruff format, mypy, pylint, bandit and pytest-with-coverage all clean."
|
||||
}
|
||||
],
|
||||
"risks": [
|
||||
"TextEntryMixin declares wait_for with the concrete class's exact signature (timeout default 15.0). A future change to AndroidUi.wait_for that does not update the abstract declaration would pass tests but mislead type checkers and readers.",
|
||||
"driver.py imports from both _elements and _text_entry, and _text_entry imports from _elements. That order must hold; _elements must never import from driver."
|
||||
],
|
||||
"rollback": [
|
||||
"git revert the commit; the five packages return to their previous file sizes and the six new modules disappear.",
|
||||
"After rollback, re-run each package's suite and confirm the same five counts."
|
||||
]
|
||||
}
|
||||
@ -1,43 +0,0 @@
|
||||
{
|
||||
"intent": "Clear the last six over-cap test modules in python_pkg, all in wsg_grabber, finishing the package tree.",
|
||||
"scope": [
|
||||
"python_pkg/wsg_grabber/tests/test_player.py (473 -> 229) + test_player_probe.py, test_player_errors.py, test_player_socket.py",
|
||||
"python_pkg/wsg_grabber/tests/test_ui.py (453 -> 214) + test_ui_playback.py, test_ui_idle.py, test_ui_tick.py",
|
||||
"python_pkg/wsg_grabber/tests/test_app.py (429 -> 212) + test_app_undo.py, test_app_undo_history.py, test_app_undo_safety.py",
|
||||
"python_pkg/wsg_grabber/tests/test_net.py (370 -> 250) + test_net_resume.py",
|
||||
"python_pkg/wsg_grabber/tests/test_downloader.py (341 -> 228) + test_downloader_retry.py, test_downloader_outcomes.py",
|
||||
"python_pkg/wsg_grabber/tests/test_downloader_part2.py (333 -> 184) + test_downloader_lifecycle.py, test_downloader_conditional.py",
|
||||
"Non-goal: no assertion changed, no test deleted, skipped or weakened"
|
||||
],
|
||||
"changes": [
|
||||
"Partitioned all six at topic boundaries, in two passes: the first cut left five files still over, so each was cut again. Eleven new modules, named for the behaviour they cover rather than a partN suffix.",
|
||||
"Each split copies the entire original preamble - imports, local mock builders and the module's pytest fixtures - into the new file. Carrying the fixtures matters more here than in other packages: test_player, test_ui and test_app each define module-scoped fixtures (started, toolkit, session) that their tests take as parameters, and pytest resolves those lexically within the module.",
|
||||
"conftest.py's autouse isolate_paths fixture still applies to every new module unchanged, since they all sit in the same directory.",
|
||||
"No patch string changed. The wsg_grabber source was split under the cap in earlier sessions, so every patched name already resolves on the module each test file names."
|
||||
],
|
||||
"verification": [
|
||||
{
|
||||
"command": "timeout 180 env PYTHONPATH=. python3 -m pytest python_pkg/wsg_grabber/tests -q",
|
||||
"result": "pass",
|
||||
"evidence": "277 passed before the split and 277 passed after both passes - identical count. Verified after each of the two rounds, not just at the end."
|
||||
},
|
||||
{
|
||||
"command": "bash ~/utils/scripts/check_file_length.sh --all | grep python_pkg",
|
||||
"result": "pass",
|
||||
"evidence": "No output at all: every file under python_pkg is now within the 250-line cap, down from 50 violations when this effort started and 13 at the beginning of this session's python_pkg work."
|
||||
},
|
||||
{
|
||||
"command": "pre-commit run --files <the touched test files and artifacts>",
|
||||
"result": "pass",
|
||||
"evidence": "ruff pruned 82 imports the preamble copy left unused across the eleven new modules and reformatted 14 files; clean on re-run, with mypy, pylint, name-tests-test and pytest-with-coverage all passing at 100%."
|
||||
}
|
||||
],
|
||||
"risks": [
|
||||
"Copying a preamble that defines pytest fixtures duplicates those fixture definitions across the split halves. That is harmless while both halves use them, but a later edit that removes the last user in one half leaves a dead fixture ruff will not flag, since a fixture is referenced by name rather than imported.",
|
||||
"test_net.py landed at exactly 250 lines - at the cap, not under it by any margin. A single added line there will trip the gate."
|
||||
],
|
||||
"rollback": [
|
||||
"git revert the commit; the six originals return at their previous sizes and the eleven new modules disappear.",
|
||||
"After rollback, re-run the package suite and confirm it still reports 277 passed."
|
||||
]
|
||||
}
|
||||
@ -69,9 +69,205 @@ install_joplin_desktop() {
|
||||
info "Launch with: ~/.joplin/Joplin.AppImage (or 'joplin-desktop' from menu)"
|
||||
}
|
||||
|
||||
SCRIPT_DIR="$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")"
|
||||
# shellcheck source=lib/joplin_server.sh
|
||||
source "$SCRIPT_DIR/lib/joplin_server.sh"
|
||||
# ── Set up DuckDNS for stable URL ───────────────────────────────────
|
||||
setup_duckdns() {
|
||||
info "Setting up DuckDNS for stable server URL..."
|
||||
|
||||
if [[ -z "$DUCKDNS_DOMAIN" ]]; then
|
||||
echo ""
|
||||
info "Your public IP may change. DuckDNS provides a free stable hostname."
|
||||
info "1. Go to https://www.duckdns.org/ and sign in (Google/GitHub/etc.)"
|
||||
info "2. Create a subdomain (e.g. 'myjoplin' for myjoplin.duckdns.org)"
|
||||
info "3. Copy your token from the DuckDNS dashboard"
|
||||
echo ""
|
||||
read -r -p "Enter your DuckDNS subdomain (without .duckdns.org): " DUCKDNS_DOMAIN
|
||||
read -r -p "Enter your DuckDNS token: " DUCKDNS_TOKEN
|
||||
fi
|
||||
|
||||
if [[ -z "$DUCKDNS_DOMAIN" ]] || [[ -z "$DUCKDNS_TOKEN" ]]; then
|
||||
warn "DuckDNS not configured. Falling back to raw public IP (may change!)."
|
||||
return 1
|
||||
fi
|
||||
|
||||
local full_domain="${DUCKDNS_DOMAIN}.duckdns.org"
|
||||
|
||||
# Update DuckDNS now
|
||||
info "Updating DuckDNS record for ${full_domain}..."
|
||||
local result
|
||||
result=$(curl -s "https://www.duckdns.org/update?domains=${DUCKDNS_DOMAIN}&token=${DUCKDNS_TOKEN}&ip=")
|
||||
if [[ "$result" == "OK" ]]; then
|
||||
info "DuckDNS updated successfully: ${full_domain}"
|
||||
else
|
||||
warn "DuckDNS update returned: $result"
|
||||
fi
|
||||
|
||||
# Set up cron job to keep IP updated every 5 minutes
|
||||
local duckdns_script="$JOPLIN_DATA_DIR/duckdns-update.sh"
|
||||
cat >"$duckdns_script" <<DUCKEOF
|
||||
#!/usr/bin/env bash
|
||||
result=\$(curl -s "https://www.duckdns.org/update?domains=${DUCKDNS_DOMAIN}&token=${DUCKDNS_TOKEN}&ip=")
|
||||
echo "\$(date): \$result" >> "$JOPLIN_DATA_DIR/duckdns.log"
|
||||
DUCKEOF
|
||||
chmod +x "$duckdns_script"
|
||||
|
||||
# Add cron job (remove old one if exists, add new)
|
||||
(
|
||||
crontab -l 2>/dev/null | grep -v "duckdns-update.sh"
|
||||
echo "*/5 * * * * $duckdns_script"
|
||||
) | crontab -
|
||||
info "DuckDNS cron job installed (updates every 5 minutes)"
|
||||
|
||||
# Save config for future runs
|
||||
local config_file="$JOPLIN_DATA_DIR/.duckdns.conf"
|
||||
cat >"$config_file" <<CONFEOF
|
||||
DUCKDNS_DOMAIN="${DUCKDNS_DOMAIN}"
|
||||
DUCKDNS_TOKEN="${DUCKDNS_TOKEN}"
|
||||
CONFEOF
|
||||
chmod 600 "$config_file"
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
# ── Set up Joplin Server (Docker) ───────────────────────────────────
|
||||
setup_joplin_server() {
|
||||
info "Setting up Joplin Server via Docker..."
|
||||
|
||||
# Ensure Docker is installed and running
|
||||
if ! command -v docker >/dev/null 2>&1; then
|
||||
info "Installing Docker..."
|
||||
sudo pacman -S --needed --noconfirm docker docker-compose
|
||||
fi
|
||||
|
||||
if ! systemctl is-active --quiet docker; then
|
||||
info "Starting Docker service..."
|
||||
sudo systemctl enable --now docker
|
||||
fi
|
||||
|
||||
# Add user to docker group if not already a member
|
||||
if ! groups | grep -q '\bdocker\b'; then
|
||||
warn "Adding $USER to docker group (re-login required for group to take effect)."
|
||||
sudo usermod -aG docker "$USER"
|
||||
fi
|
||||
|
||||
# Create data directory
|
||||
mkdir -p "$JOPLIN_DATA_DIR"
|
||||
|
||||
local compose_file="$JOPLIN_DATA_DIR/docker-compose.yml"
|
||||
|
||||
# Load saved DuckDNS config if it exists
|
||||
if [[ -f "$JOPLIN_DATA_DIR/.duckdns.conf" ]]; then
|
||||
# shellcheck source=/dev/null
|
||||
source "$JOPLIN_DATA_DIR/.duckdns.conf"
|
||||
fi
|
||||
|
||||
# Set up DuckDNS for a stable hostname
|
||||
local server_url
|
||||
if setup_duckdns; then
|
||||
server_url="http://${DUCKDNS_DOMAIN}.duckdns.org:${JOPLIN_SERVER_PORT}"
|
||||
info "Using stable DuckDNS URL: $server_url"
|
||||
else
|
||||
# Fallback to public IP
|
||||
local host_ip
|
||||
host_ip="$(curl -s --max-time 5 ifconfig.me 2>/dev/null)"
|
||||
if [[ -z "$host_ip" ]]; then
|
||||
host_ip="$(ip -4 route get 1.1.1.1 2>/dev/null | awk '{print $7; exit}')"
|
||||
fi
|
||||
if [[ -z "$host_ip" ]]; then
|
||||
host_ip="$(hostname -I 2>/dev/null | awk '{print $1}')"
|
||||
fi
|
||||
if [[ -z "$host_ip" ]]; then
|
||||
warn "Could not detect external IP. Falling back to 0.0.0.0"
|
||||
host_ip="0.0.0.0"
|
||||
fi
|
||||
server_url="http://${host_ip}:${JOPLIN_SERVER_PORT}"
|
||||
warn "Using raw IP URL (may change!): $server_url"
|
||||
fi
|
||||
|
||||
cat >"$compose_file" <<EOF
|
||||
version: "3"
|
||||
|
||||
services:
|
||||
joplin-db:
|
||||
image: postgres:16
|
||||
container_name: joplin-db
|
||||
restart: unless-stopped
|
||||
volumes:
|
||||
- joplin-db-data:/var/lib/postgresql/data
|
||||
environment:
|
||||
POSTGRES_DB: joplin
|
||||
POSTGRES_USER: joplin
|
||||
POSTGRES_PASSWORD: changeme
|
||||
networks:
|
||||
- joplin-net
|
||||
|
||||
joplin-server:
|
||||
image: joplin/server:latest
|
||||
container_name: joplin-server
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
- joplin-db
|
||||
ports:
|
||||
- "0.0.0.0:${JOPLIN_SERVER_PORT}:22300"
|
||||
environment:
|
||||
APP_PORT: 22300
|
||||
APP_BASE_URL: "${server_url}"
|
||||
DB_CLIENT: pg
|
||||
POSTGRES_HOST: joplin-db
|
||||
POSTGRES_PORT: 5432
|
||||
POSTGRES_DATABASE: joplin
|
||||
POSTGRES_USER: joplin
|
||||
POSTGRES_PASSWORD: changeme
|
||||
networks:
|
||||
- joplin-net
|
||||
|
||||
volumes:
|
||||
joplin-db-data:
|
||||
|
||||
networks:
|
||||
joplin-net:
|
||||
EOF
|
||||
|
||||
info "Starting Joplin Server..."
|
||||
docker compose -f "$compose_file" up -d
|
||||
|
||||
echo ""
|
||||
info "Joplin Server is running at: ${server_url}"
|
||||
echo ""
|
||||
echo " Default admin credentials:"
|
||||
echo " Email: admin@localhost"
|
||||
echo " Password: admin"
|
||||
echo ""
|
||||
warn "IMPORTANT: Change the default admin password and the database"
|
||||
warn "password (POSTGRES_PASSWORD in $compose_file) immediately!"
|
||||
echo ""
|
||||
info "Firewall: opening port ${JOPLIN_SERVER_PORT}/tcp for external access..."
|
||||
if command -v ufw >/dev/null 2>&1; then
|
||||
sudo ufw allow "${JOPLIN_SERVER_PORT}/tcp" || warn "Could not configure ufw"
|
||||
elif command -v firewall-cmd >/dev/null 2>&1; then
|
||||
if sudo firewall-cmd --permanent --add-port="${JOPLIN_SERVER_PORT}/tcp" &&
|
||||
sudo firewall-cmd --reload; then
|
||||
:
|
||||
else
|
||||
warn "Could not configure firewalld"
|
||||
fi
|
||||
elif command -v iptables >/dev/null 2>&1; then
|
||||
sudo iptables -A INPUT -p tcp --dport "${JOPLIN_SERVER_PORT}" -j ACCEPT || warn "Could not configure iptables"
|
||||
else
|
||||
warn "No firewall tool found. Ensure port ${JOPLIN_SERVER_PORT}/tcp is open manually."
|
||||
fi
|
||||
echo ""
|
||||
echo " To connect Joplin desktop/Android to this server:"
|
||||
echo " 1. Open Joplin → Tools → Options → Synchronisation"
|
||||
echo " 2. Set target to 'Joplin Server'"
|
||||
echo " 3. Enter URL: ${server_url}"
|
||||
echo " 4. Enter your Joplin Server email and password"
|
||||
echo ""
|
||||
echo " Server management:"
|
||||
echo " Start: docker compose -f $compose_file up -d"
|
||||
echo " Stop: docker compose -f $compose_file down"
|
||||
echo " Logs: docker compose -f $compose_file logs -f"
|
||||
echo " Update: docker compose -f $compose_file pull && docker compose -f $compose_file up -d"
|
||||
}
|
||||
|
||||
# ── Main ─────────────────────────────────────────────────────────────
|
||||
main() {
|
||||
|
||||
@ -1,209 +0,0 @@
|
||||
#!/bin/bash
|
||||
# Joplin Server setup: DuckDNS dynamic DNS plus the Docker compose stack.
|
||||
#
|
||||
# Sourced by install_joplin.sh when it is run with --with-server; split out to
|
||||
# keep that script under the 250-line cap. Expects the caller to have defined
|
||||
# info/warn/error and the JOPLIN_* and DUCKDNS_* variables. Sourced, not run,
|
||||
# so it inherits the caller's strict mode; the shebang is for shellcheck and
|
||||
# matches scripts/lib/common.sh.
|
||||
|
||||
|
||||
# ── Set up DuckDNS for stable URL ───────────────────────────────────
|
||||
setup_duckdns() {
|
||||
info "Setting up DuckDNS for stable server URL..."
|
||||
|
||||
if [[ -z "$DUCKDNS_DOMAIN" ]]; then
|
||||
echo ""
|
||||
info "Your public IP may change. DuckDNS provides a free stable hostname."
|
||||
info "1. Go to https://www.duckdns.org/ and sign in (Google/GitHub/etc.)"
|
||||
info "2. Create a subdomain (e.g. 'myjoplin' for myjoplin.duckdns.org)"
|
||||
info "3. Copy your token from the DuckDNS dashboard"
|
||||
echo ""
|
||||
read -r -p "Enter your DuckDNS subdomain (without .duckdns.org): " DUCKDNS_DOMAIN
|
||||
read -r -p "Enter your DuckDNS token: " DUCKDNS_TOKEN
|
||||
fi
|
||||
|
||||
if [[ -z "$DUCKDNS_DOMAIN" ]] || [[ -z "$DUCKDNS_TOKEN" ]]; then
|
||||
warn "DuckDNS not configured. Falling back to raw public IP (may change!)."
|
||||
return 1
|
||||
fi
|
||||
|
||||
local full_domain="${DUCKDNS_DOMAIN}.duckdns.org"
|
||||
|
||||
# Update DuckDNS now
|
||||
info "Updating DuckDNS record for ${full_domain}..."
|
||||
local result
|
||||
result=$(curl -s "https://www.duckdns.org/update?domains=${DUCKDNS_DOMAIN}&token=${DUCKDNS_TOKEN}&ip=")
|
||||
if [[ "$result" == "OK" ]]; then
|
||||
info "DuckDNS updated successfully: ${full_domain}"
|
||||
else
|
||||
warn "DuckDNS update returned: $result"
|
||||
fi
|
||||
|
||||
# Set up cron job to keep IP updated every 5 minutes
|
||||
local duckdns_script="$JOPLIN_DATA_DIR/duckdns-update.sh"
|
||||
cat >"$duckdns_script" <<DUCKEOF
|
||||
#!/usr/bin/env bash
|
||||
result=\$(curl -s "https://www.duckdns.org/update?domains=${DUCKDNS_DOMAIN}&token=${DUCKDNS_TOKEN}&ip=")
|
||||
echo "\$(date): \$result" >> "$JOPLIN_DATA_DIR/duckdns.log"
|
||||
DUCKEOF
|
||||
chmod +x "$duckdns_script"
|
||||
|
||||
# Add cron job (remove old one if exists, add new)
|
||||
(
|
||||
crontab -l 2>/dev/null | grep -v "duckdns-update.sh"
|
||||
echo "*/5 * * * * $duckdns_script"
|
||||
) | crontab -
|
||||
info "DuckDNS cron job installed (updates every 5 minutes)"
|
||||
|
||||
# Save config for future runs
|
||||
local config_file="$JOPLIN_DATA_DIR/.duckdns.conf"
|
||||
cat >"$config_file" <<CONFEOF
|
||||
DUCKDNS_DOMAIN="${DUCKDNS_DOMAIN}"
|
||||
DUCKDNS_TOKEN="${DUCKDNS_TOKEN}"
|
||||
CONFEOF
|
||||
chmod 600 "$config_file"
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
# ── Set up Joplin Server (Docker) ───────────────────────────────────
|
||||
setup_joplin_server() {
|
||||
info "Setting up Joplin Server via Docker..."
|
||||
|
||||
# Ensure Docker is installed and running
|
||||
if ! command -v docker >/dev/null 2>&1; then
|
||||
info "Installing Docker..."
|
||||
sudo pacman -S --needed --noconfirm docker docker-compose
|
||||
fi
|
||||
|
||||
if ! systemctl is-active --quiet docker; then
|
||||
info "Starting Docker service..."
|
||||
sudo systemctl enable --now docker
|
||||
fi
|
||||
|
||||
# Add user to docker group if not already a member
|
||||
if ! groups | grep -q '\bdocker\b'; then
|
||||
warn "Adding $USER to docker group (re-login required for group to take effect)."
|
||||
sudo usermod -aG docker "$USER"
|
||||
fi
|
||||
|
||||
# Create data directory
|
||||
mkdir -p "$JOPLIN_DATA_DIR"
|
||||
|
||||
local compose_file="$JOPLIN_DATA_DIR/docker-compose.yml"
|
||||
|
||||
# Load saved DuckDNS config if it exists
|
||||
if [[ -f "$JOPLIN_DATA_DIR/.duckdns.conf" ]]; then
|
||||
# shellcheck source=/dev/null
|
||||
source "$JOPLIN_DATA_DIR/.duckdns.conf"
|
||||
fi
|
||||
|
||||
# Set up DuckDNS for a stable hostname
|
||||
local server_url
|
||||
if setup_duckdns; then
|
||||
server_url="http://${DUCKDNS_DOMAIN}.duckdns.org:${JOPLIN_SERVER_PORT}"
|
||||
info "Using stable DuckDNS URL: $server_url"
|
||||
else
|
||||
# Fallback to public IP
|
||||
local host_ip
|
||||
host_ip="$(curl -s --max-time 5 ifconfig.me 2>/dev/null)"
|
||||
if [[ -z "$host_ip" ]]; then
|
||||
host_ip="$(ip -4 route get 1.1.1.1 2>/dev/null | awk '{print $7; exit}')"
|
||||
fi
|
||||
if [[ -z "$host_ip" ]]; then
|
||||
host_ip="$(hostname -I 2>/dev/null | awk '{print $1}')"
|
||||
fi
|
||||
if [[ -z "$host_ip" ]]; then
|
||||
warn "Could not detect external IP. Falling back to 0.0.0.0"
|
||||
host_ip="0.0.0.0"
|
||||
fi
|
||||
server_url="http://${host_ip}:${JOPLIN_SERVER_PORT}"
|
||||
warn "Using raw IP URL (may change!): $server_url"
|
||||
fi
|
||||
|
||||
cat >"$compose_file" <<EOF
|
||||
version: "3"
|
||||
|
||||
services:
|
||||
joplin-db:
|
||||
image: postgres:16
|
||||
container_name: joplin-db
|
||||
restart: unless-stopped
|
||||
volumes:
|
||||
- joplin-db-data:/var/lib/postgresql/data
|
||||
environment:
|
||||
POSTGRES_DB: joplin
|
||||
POSTGRES_USER: joplin
|
||||
POSTGRES_PASSWORD: changeme
|
||||
networks:
|
||||
- joplin-net
|
||||
|
||||
joplin-server:
|
||||
image: joplin/server:latest
|
||||
container_name: joplin-server
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
- joplin-db
|
||||
ports:
|
||||
- "0.0.0.0:${JOPLIN_SERVER_PORT}:22300"
|
||||
environment:
|
||||
APP_PORT: 22300
|
||||
APP_BASE_URL: "${server_url}"
|
||||
DB_CLIENT: pg
|
||||
POSTGRES_HOST: joplin-db
|
||||
POSTGRES_PORT: 5432
|
||||
POSTGRES_DATABASE: joplin
|
||||
POSTGRES_USER: joplin
|
||||
POSTGRES_PASSWORD: changeme
|
||||
networks:
|
||||
- joplin-net
|
||||
|
||||
volumes:
|
||||
joplin-db-data:
|
||||
|
||||
networks:
|
||||
joplin-net:
|
||||
EOF
|
||||
|
||||
info "Starting Joplin Server..."
|
||||
docker compose -f "$compose_file" up -d
|
||||
|
||||
echo ""
|
||||
info "Joplin Server is running at: ${server_url}"
|
||||
echo ""
|
||||
echo " Default admin credentials:"
|
||||
echo " Email: admin@localhost"
|
||||
echo " Password: admin"
|
||||
echo ""
|
||||
warn "IMPORTANT: Change the default admin password and the database"
|
||||
warn "password (POSTGRES_PASSWORD in $compose_file) immediately!"
|
||||
echo ""
|
||||
info "Firewall: opening port ${JOPLIN_SERVER_PORT}/tcp for external access..."
|
||||
if command -v ufw >/dev/null 2>&1; then
|
||||
sudo ufw allow "${JOPLIN_SERVER_PORT}/tcp" || warn "Could not configure ufw"
|
||||
elif command -v firewall-cmd >/dev/null 2>&1; then
|
||||
if sudo firewall-cmd --permanent --add-port="${JOPLIN_SERVER_PORT}/tcp" &&
|
||||
sudo firewall-cmd --reload; then
|
||||
:
|
||||
else
|
||||
warn "Could not configure firewalld"
|
||||
fi
|
||||
elif command -v iptables >/dev/null 2>&1; then
|
||||
sudo iptables -A INPUT -p tcp --dport "${JOPLIN_SERVER_PORT}" -j ACCEPT || warn "Could not configure iptables"
|
||||
else
|
||||
warn "No firewall tool found. Ensure port ${JOPLIN_SERVER_PORT}/tcp is open manually."
|
||||
fi
|
||||
echo ""
|
||||
echo " To connect Joplin desktop/Android to this server:"
|
||||
echo " 1. Open Joplin → Tools → Options → Synchronisation"
|
||||
echo " 2. Set target to 'Joplin Server'"
|
||||
echo " 3. Enter URL: ${server_url}"
|
||||
echo " 4. Enter your Joplin Server email and password"
|
||||
echo ""
|
||||
echo " Server management:"
|
||||
echo " Start: docker compose -f $compose_file up -d"
|
||||
echo " Stop: docker compose -f $compose_file down"
|
||||
echo " Logs: docker compose -f $compose_file logs -f"
|
||||
echo " Update: docker compose -f $compose_file pull && docker compose -f $compose_file up -d"
|
||||
}
|
||||
@ -1,128 +0,0 @@
|
||||
"""The element and error types the UI driver works in, and the XML parser.
|
||||
|
||||
Split out of :mod:`python_pkg.android_ui.driver` to keep it under the 250-line
|
||||
cap. ``AndroidUi`` stays there because that is the name the tests patch;
|
||||
everything here is re-imported by ``driver`` so the package's public re-exports
|
||||
in ``__init__`` are unchanged.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import logging
|
||||
import re
|
||||
|
||||
from defusedxml.ElementTree import ParseError, fromstring
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
_BOUNDS_RE = re.compile(r"\[(\d+),(\d+)\]\[(\d+),(\d+)\]")
|
||||
|
||||
|
||||
class UiAutomationError(RuntimeError):
|
||||
"""Base class for every failure this package reports."""
|
||||
|
||||
|
||||
class ElementNotFoundError(UiAutomationError):
|
||||
"""No element matched the query."""
|
||||
|
||||
|
||||
class AmbiguousElementError(UiAutomationError):
|
||||
"""More than one element matched, so acting would be a coin flip."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class UiElement:
|
||||
"""One node from the accessibility tree."""
|
||||
|
||||
text: str
|
||||
content_desc: str
|
||||
resource_id: str
|
||||
class_name: str
|
||||
bounds: tuple[int, int, int, int]
|
||||
enabled: bool
|
||||
focused: bool
|
||||
|
||||
@property
|
||||
def label(self) -> str:
|
||||
"""The best human-facing name for this element."""
|
||||
return self.text or self.content_desc or self.resource_id
|
||||
|
||||
@property
|
||||
def center(self) -> tuple[int, int]:
|
||||
"""Tap point: the centre of the element's CURRENT bounds."""
|
||||
left, top, right, bottom = self.bounds
|
||||
return ((left + right) // 2, (top + bottom) // 2)
|
||||
|
||||
def matches(self, query: str, *, exact: bool = False) -> bool:
|
||||
"""Return True if ``query`` names this element."""
|
||||
haystacks = (self.text, self.content_desc, self.resource_id)
|
||||
if exact:
|
||||
return any(h == query for h in haystacks)
|
||||
return any(query.lower() in h.lower() for h in haystacks if h)
|
||||
|
||||
def __str__(self) -> str:
|
||||
"""Return a one-line description naming the element and its centre."""
|
||||
cls = self.class_name.rsplit(".", 1)[-1]
|
||||
x, y = self.center
|
||||
return f"{self.label!r} <{cls}> at ({x},{y})"
|
||||
|
||||
|
||||
def _escape(text: str) -> str:
|
||||
r"""Escape text for ``adb shell input text``.
|
||||
|
||||
Backslash is escaped FIRST and excluded from the loop below. Escaping it
|
||||
inside the loop double-escapes every backslash the loop itself just added
|
||||
(``&`` -> ``\\&`` -> ``\\\\&``), which silently types the wrong password.
|
||||
"""
|
||||
out = text.replace("\\", "\\\\")
|
||||
out = out.replace("%", "%%").replace(" ", "%s")
|
||||
for char in "()<>|;&*~\"'`$":
|
||||
out = out.replace(char, "\\" + char)
|
||||
return out
|
||||
|
||||
|
||||
def _parse_tree(xml: str) -> list[UiElement]:
|
||||
"""Return every labelled node in an accessibility-tree dump."""
|
||||
try:
|
||||
root = fromstring(xml)
|
||||
except ParseError as exc:
|
||||
_logger.warning(
|
||||
"UI dump is not valid XML (%s) — treating it as an empty screen; "
|
||||
"this is usually a snapshot taken mid-animation",
|
||||
exc,
|
||||
)
|
||||
return []
|
||||
|
||||
elements: list[UiElement] = []
|
||||
for node in root.iter("node"):
|
||||
bounds = _BOUNDS_RE.match(node.get("bounds", ""))
|
||||
if bounds is None:
|
||||
continue
|
||||
text = node.get("text", "")
|
||||
desc = node.get("content-desc", "")
|
||||
res = node.get("resource-id", "")
|
||||
cls = node.get("class", "")
|
||||
# An EMPTY text field has no text, content-desc or resource-id, so a
|
||||
# "must be labelled" filter drops it -- and an empty field is exactly
|
||||
# the thing a caller needs to find in order to type into it. Keep every
|
||||
# editable node regardless of label.
|
||||
if not (text or desc or res or cls.endswith("EditText")):
|
||||
continue
|
||||
elements.append(
|
||||
UiElement(
|
||||
text=text,
|
||||
content_desc=desc,
|
||||
resource_id=res,
|
||||
class_name=cls,
|
||||
bounds=(
|
||||
int(bounds.group(1)),
|
||||
int(bounds.group(2)),
|
||||
int(bounds.group(3)),
|
||||
int(bounds.group(4)),
|
||||
),
|
||||
enabled=node.get("enabled") == "true",
|
||||
focused=node.get("focused") == "true",
|
||||
)
|
||||
)
|
||||
return elements
|
||||
@ -1,145 +0,0 @@
|
||||
"""Typing into fields and driving the on-screen keyboard.
|
||||
|
||||
Split out of :mod:`python_pkg.android_ui.driver` to keep it under the 250-line
|
||||
cap. A mixin rather than module-level functions because
|
||||
``tests/test_driver.py`` calls these as bound attributes of a real driver, and
|
||||
because they need ``_run``/``dump``/``wait_for`` from the concrete class.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
import re
|
||||
import time
|
||||
|
||||
from python_pkg.android_ui._elements import (
|
||||
ElementNotFoundError,
|
||||
UiAutomationError,
|
||||
UiElement,
|
||||
_escape,
|
||||
)
|
||||
|
||||
# Horizontal slack when re-identifying a field after typing: the keyboard can
|
||||
# shift a widget vertically, but not sideways, so the left edge stays put.
|
||||
_SAME_FIELD_X_TOLERANCE_PX = 50
|
||||
|
||||
|
||||
class TextEntryMixin(ABC):
|
||||
"""The text-entry half of :class:`~python_pkg.android_ui.driver.AndroidUi`."""
|
||||
|
||||
_settle: float
|
||||
|
||||
@abstractmethod
|
||||
def _run(self, *args: str, timeout: float = 30.0) -> str:
|
||||
"""Supplied by the concrete driver: run one adb command."""
|
||||
|
||||
@abstractmethod
|
||||
def dump(self, *, retries: int = 4) -> list[UiElement]:
|
||||
"""Supplied by the concrete driver: read the current UI tree."""
|
||||
|
||||
@abstractmethod
|
||||
def wait_for(
|
||||
self, query: str, *, timeout: float = 15.0, exact: bool = False
|
||||
) -> UiElement:
|
||||
"""Supplied by the concrete driver: block until an element appears."""
|
||||
|
||||
def _clear_focused_field(self, length: int) -> None:
|
||||
"""Empty the focused field: select-all, then delete."""
|
||||
if length == 0:
|
||||
return
|
||||
# KEYCODE_MOVE_END (123) then a run of deletes is more reliable across
|
||||
# IMEs than CTRL+A, which not every keyboard honours.
|
||||
self._run("shell", "input", "keyevent", "123")
|
||||
for _ in range(length + 2):
|
||||
self._run("shell", "input", "keyevent", "67")
|
||||
time.sleep(self._settle)
|
||||
|
||||
def editable_fields(self) -> list[UiElement]:
|
||||
"""Return every editable field on screen, in top-to-bottom order.
|
||||
|
||||
An EMPTY text field carries no text, content-desc or resource-id, so
|
||||
there is nothing to name it by — yet it is precisely the element a
|
||||
caller needs to address in order to fill it in. Ordering by position
|
||||
gives a stable handle ("the second field in the sync form") that does
|
||||
not depend on a label the widget never had.
|
||||
"""
|
||||
fields = [e for e in self.dump() if e.class_name.endswith("EditText")]
|
||||
return sorted(fields, key=lambda e: (e.bounds[1], e.bounds[0]))
|
||||
|
||||
def type_into_field(self, index: int, text: str) -> None:
|
||||
"""Type ``text`` into the ``index``-th editable field on screen.
|
||||
|
||||
Verifies the field changed, exactly like :meth:`type_into`.
|
||||
"""
|
||||
fields = self.editable_fields()
|
||||
if index >= len(fields):
|
||||
msg = f"asked for editable field #{index} but the screen has {len(fields)}"
|
||||
raise ElementNotFoundError(msg)
|
||||
target = fields[index]
|
||||
before = target.text
|
||||
x, y = target.center
|
||||
self._run("shell", "input", "tap", str(x), str(y))
|
||||
time.sleep(max(self._settle, 0.8))
|
||||
# REPLACE, don't append. `input text` inserts at the cursor, so typing
|
||||
# into a field that already holds something silently concatenates --
|
||||
# producing e.g. "old@example.comnew@example.com", which is accepted by
|
||||
# the widget, passes a "did the text change?" check, and is wrong.
|
||||
self._clear_focused_field(len(before))
|
||||
self._run("shell", "input", "text", _escape(text))
|
||||
time.sleep(self._settle)
|
||||
after = self.editable_fields()
|
||||
changed = any(
|
||||
f.text != before
|
||||
and abs(f.bounds[0] - target.bounds[0]) < _SAME_FIELD_X_TOLERANCE_PX
|
||||
for f in after
|
||||
)
|
||||
if not changed:
|
||||
msg = (
|
||||
f"typed {len(text)} character(s) into editable field #{index} "
|
||||
f"but its contents did not change — the tap did not focus it"
|
||||
)
|
||||
raise UiAutomationError(msg)
|
||||
|
||||
def dismiss_keyboard(self) -> None:
|
||||
"""Close the soft keyboard WITHOUT popping the current route.
|
||||
|
||||
``KEYCODE_BACK`` is the obvious way and the wrong one: Flutter treats
|
||||
it as a route pop, so it navigates out of the screen and discards
|
||||
anything typed. ``KEYCODE_ESCAPE`` leaves the route alone but does not
|
||||
close every IME (Gboard ignores it), and a keyboard that stays up hides
|
||||
the button you are about to tap -- so the tap lands on a key instead,
|
||||
silently doing nothing useful.
|
||||
|
||||
So: ask the IME to hide, verify with ``dumpsys input_method``, and only
|
||||
then report success. Raises if the keyboard is still up, because
|
||||
"tapped a letter key" is indistinguishable from "tapped the button"
|
||||
unless somebody checks.
|
||||
"""
|
||||
for keyevent in ("111", "4"):
|
||||
if not self.keyboard_is_up():
|
||||
return
|
||||
self._run("shell", "input", "keyevent", keyevent)
|
||||
time.sleep(max(self._settle, 0.6))
|
||||
if self.keyboard_is_up():
|
||||
msg = (
|
||||
"the soft keyboard is still covering the screen after ESCAPE "
|
||||
"and BACK — any tap below it will hit a key, not your target"
|
||||
)
|
||||
raise UiAutomationError(msg)
|
||||
|
||||
def keyboard_is_up(self) -> bool:
|
||||
"""Return True while the soft keyboard is shown.
|
||||
|
||||
Without this, a caller cannot tell "the button is absent" from "the
|
||||
button is behind the keyboard", and the accessibility tree reports the
|
||||
button's laid-out position either way.
|
||||
"""
|
||||
out = self._run("shell", "dumpsys", "input_method")
|
||||
match = re.search(r"mInputShown=(\w+)", out)
|
||||
return match is not None and match.group(1) == "true"
|
||||
|
||||
def current_focus(self) -> str:
|
||||
"""Return the focused window, for asserting which screen is up."""
|
||||
out = self._run("shell", "dumpsys", "window")
|
||||
match = re.search(r"mCurrentFocus=\S+ \S+ (\S+)}", out)
|
||||
return match.group(1) if match else ""
|
||||
@ -2,24 +2,19 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import logging
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
from python_pkg.android_ui._elements import (
|
||||
AmbiguousElementError,
|
||||
ElementNotFoundError,
|
||||
UiAutomationError,
|
||||
UiElement,
|
||||
_escape,
|
||||
_parse_tree,
|
||||
)
|
||||
from python_pkg.android_ui._text_entry import TextEntryMixin
|
||||
from defusedxml.ElementTree import ParseError, fromstring
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
_BOUNDS_RE = re.compile(r"\[(\d+),(\d+)\]\[(\d+),(\d+)\]")
|
||||
_REMOTE_DUMP = "/sdcard/window_dump.xml"
|
||||
|
||||
# A tree this small is a partial render, not a real screen. Flutter reports
|
||||
@ -28,8 +23,61 @@ _REMOTE_DUMP = "/sdcard/window_dump.xml"
|
||||
# the node count is taken into account.
|
||||
_SUSPICIOUSLY_SMALL_TREE = 4
|
||||
|
||||
# Horizontal slack when re-identifying a field after typing: the keyboard can
|
||||
# shift a widget vertically, but not sideways, so the left edge stays put.
|
||||
_SAME_FIELD_X_TOLERANCE_PX = 50
|
||||
|
||||
class AndroidUi(TextEntryMixin):
|
||||
|
||||
class UiAutomationError(RuntimeError):
|
||||
"""Base class for every failure this package reports."""
|
||||
|
||||
|
||||
class ElementNotFoundError(UiAutomationError):
|
||||
"""No element matched the query."""
|
||||
|
||||
|
||||
class AmbiguousElementError(UiAutomationError):
|
||||
"""More than one element matched, so acting would be a coin flip."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class UiElement:
|
||||
"""One node from the accessibility tree."""
|
||||
|
||||
text: str
|
||||
content_desc: str
|
||||
resource_id: str
|
||||
class_name: str
|
||||
bounds: tuple[int, int, int, int]
|
||||
enabled: bool
|
||||
focused: bool
|
||||
|
||||
@property
|
||||
def label(self) -> str:
|
||||
"""The best human-facing name for this element."""
|
||||
return self.text or self.content_desc or self.resource_id
|
||||
|
||||
@property
|
||||
def center(self) -> tuple[int, int]:
|
||||
"""Tap point: the centre of the element's CURRENT bounds."""
|
||||
left, top, right, bottom = self.bounds
|
||||
return ((left + right) // 2, (top + bottom) // 2)
|
||||
|
||||
def matches(self, query: str, *, exact: bool = False) -> bool:
|
||||
"""Return True if ``query`` names this element."""
|
||||
haystacks = (self.text, self.content_desc, self.resource_id)
|
||||
if exact:
|
||||
return any(h == query for h in haystacks)
|
||||
return any(query.lower() in h.lower() for h in haystacks if h)
|
||||
|
||||
def __str__(self) -> str:
|
||||
"""Return a one-line description naming the element and its centre."""
|
||||
cls = self.class_name.rsplit(".", 1)[-1]
|
||||
x, y = self.center
|
||||
return f"{self.label!r} <{cls}> at ({x},{y})"
|
||||
|
||||
|
||||
class AndroidUi:
|
||||
"""Drives one device. Every action re-reads the tree before acting."""
|
||||
|
||||
def __init__(
|
||||
@ -132,6 +180,63 @@ class AndroidUi(TextEntryMixin):
|
||||
raise AmbiguousElementError(msg)
|
||||
return matches[0]
|
||||
|
||||
def _clear_focused_field(self, length: int) -> None:
|
||||
"""Empty the focused field: select-all, then delete."""
|
||||
if length == 0:
|
||||
return
|
||||
# KEYCODE_MOVE_END (123) then a run of deletes is more reliable across
|
||||
# IMEs than CTRL+A, which not every keyboard honours.
|
||||
self._run("shell", "input", "keyevent", "123")
|
||||
for _ in range(length + 2):
|
||||
self._run("shell", "input", "keyevent", "67")
|
||||
time.sleep(self._settle)
|
||||
|
||||
def editable_fields(self) -> list[UiElement]:
|
||||
"""Return every editable field on screen, in top-to-bottom order.
|
||||
|
||||
An EMPTY text field carries no text, content-desc or resource-id, so
|
||||
there is nothing to name it by — yet it is precisely the element a
|
||||
caller needs to address in order to fill it in. Ordering by position
|
||||
gives a stable handle ("the second field in the sync form") that does
|
||||
not depend on a label the widget never had.
|
||||
"""
|
||||
fields = [e for e in self.dump() if e.class_name.endswith("EditText")]
|
||||
return sorted(fields, key=lambda e: (e.bounds[1], e.bounds[0]))
|
||||
|
||||
def type_into_field(self, index: int, text: str) -> None:
|
||||
"""Type ``text`` into the ``index``-th editable field on screen.
|
||||
|
||||
Verifies the field changed, exactly like :meth:`type_into`.
|
||||
"""
|
||||
fields = self.editable_fields()
|
||||
if index >= len(fields):
|
||||
msg = f"asked for editable field #{index} but the screen has {len(fields)}"
|
||||
raise ElementNotFoundError(msg)
|
||||
target = fields[index]
|
||||
before = target.text
|
||||
x, y = target.center
|
||||
self._run("shell", "input", "tap", str(x), str(y))
|
||||
time.sleep(max(self._settle, 0.8))
|
||||
# REPLACE, don't append. `input text` inserts at the cursor, so typing
|
||||
# into a field that already holds something silently concatenates --
|
||||
# producing e.g. "old@example.comnew@example.com", which is accepted by
|
||||
# the widget, passes a "did the text change?" check, and is wrong.
|
||||
self._clear_focused_field(len(before))
|
||||
self._run("shell", "input", "text", _escape(text))
|
||||
time.sleep(self._settle)
|
||||
after = self.editable_fields()
|
||||
changed = any(
|
||||
f.text != before
|
||||
and abs(f.bounds[0] - target.bounds[0]) < _SAME_FIELD_X_TOLERANCE_PX
|
||||
for f in after
|
||||
)
|
||||
if not changed:
|
||||
msg = (
|
||||
f"typed {len(text)} character(s) into editable field #{index} "
|
||||
f"but its contents did not change — the tap did not focus it"
|
||||
)
|
||||
raise UiAutomationError(msg)
|
||||
|
||||
def wait_for(
|
||||
self, query: str, *, timeout: float = 15.0, exact: bool = False
|
||||
) -> UiElement:
|
||||
@ -200,3 +305,107 @@ class AndroidUi(TextEntryMixin):
|
||||
f"did not change — the tap probably did not focus the field"
|
||||
)
|
||||
raise UiAutomationError(msg)
|
||||
|
||||
def dismiss_keyboard(self) -> None:
|
||||
"""Close the soft keyboard WITHOUT popping the current route.
|
||||
|
||||
``KEYCODE_BACK`` is the obvious way and the wrong one: Flutter treats
|
||||
it as a route pop, so it navigates out of the screen and discards
|
||||
anything typed. ``KEYCODE_ESCAPE`` leaves the route alone but does not
|
||||
close every IME (Gboard ignores it), and a keyboard that stays up hides
|
||||
the button you are about to tap -- so the tap lands on a key instead,
|
||||
silently doing nothing useful.
|
||||
|
||||
So: ask the IME to hide, verify with ``dumpsys input_method``, and only
|
||||
then report success. Raises if the keyboard is still up, because
|
||||
"tapped a letter key" is indistinguishable from "tapped the button"
|
||||
unless somebody checks.
|
||||
"""
|
||||
for keyevent in ("111", "4"):
|
||||
if not self.keyboard_is_up():
|
||||
return
|
||||
self._run("shell", "input", "keyevent", keyevent)
|
||||
time.sleep(max(self._settle, 0.6))
|
||||
if self.keyboard_is_up():
|
||||
msg = (
|
||||
"the soft keyboard is still covering the screen after ESCAPE "
|
||||
"and BACK — any tap below it will hit a key, not your target"
|
||||
)
|
||||
raise UiAutomationError(msg)
|
||||
|
||||
def keyboard_is_up(self) -> bool:
|
||||
"""Return True while the soft keyboard is shown.
|
||||
|
||||
Without this, a caller cannot tell "the button is absent" from "the
|
||||
button is behind the keyboard", and the accessibility tree reports the
|
||||
button's laid-out position either way.
|
||||
"""
|
||||
out = self._run("shell", "dumpsys", "input_method")
|
||||
match = re.search(r"mInputShown=(\w+)", out)
|
||||
return match is not None and match.group(1) == "true"
|
||||
|
||||
def current_focus(self) -> str:
|
||||
"""Return the focused window, for asserting which screen is up."""
|
||||
out = self._run("shell", "dumpsys", "window")
|
||||
match = re.search(r"mCurrentFocus=\S+ \S+ (\S+)}", out)
|
||||
return match.group(1) if match else ""
|
||||
|
||||
|
||||
def _escape(text: str) -> str:
|
||||
r"""Escape text for ``adb shell input text``.
|
||||
|
||||
Backslash is escaped FIRST and excluded from the loop below. Escaping it
|
||||
inside the loop double-escapes every backslash the loop itself just added
|
||||
(``&`` -> ``\\&`` -> ``\\\\&``), which silently types the wrong password.
|
||||
"""
|
||||
out = text.replace("\\", "\\\\")
|
||||
out = out.replace("%", "%%").replace(" ", "%s")
|
||||
for char in "()<>|;&*~\"'`$":
|
||||
out = out.replace(char, "\\" + char)
|
||||
return out
|
||||
|
||||
|
||||
def _parse_tree(xml: str) -> list[UiElement]:
|
||||
"""Return every labelled node in an accessibility-tree dump."""
|
||||
try:
|
||||
root = fromstring(xml)
|
||||
except ParseError as exc:
|
||||
_logger.warning(
|
||||
"UI dump is not valid XML (%s) — treating it as an empty screen; "
|
||||
"this is usually a snapshot taken mid-animation",
|
||||
exc,
|
||||
)
|
||||
return []
|
||||
|
||||
elements: list[UiElement] = []
|
||||
for node in root.iter("node"):
|
||||
bounds = _BOUNDS_RE.match(node.get("bounds", ""))
|
||||
if bounds is None:
|
||||
continue
|
||||
text = node.get("text", "")
|
||||
desc = node.get("content-desc", "")
|
||||
res = node.get("resource-id", "")
|
||||
cls = node.get("class", "")
|
||||
# An EMPTY text field has no text, content-desc or resource-id, so a
|
||||
# "must be labelled" filter drops it -- and an empty field is exactly
|
||||
# the thing a caller needs to find in order to type into it. Keep every
|
||||
# editable node regardless of label.
|
||||
if not (text or desc or res or cls.endswith("EditText")):
|
||||
continue
|
||||
elements.append(
|
||||
UiElement(
|
||||
text=text,
|
||||
content_desc=desc,
|
||||
resource_id=res,
|
||||
class_name=cls,
|
||||
bounds=(
|
||||
int(bounds.group(1)),
|
||||
int(bounds.group(2)),
|
||||
int(bounds.group(3)),
|
||||
int(bounds.group(4)),
|
||||
),
|
||||
enabled=node.get("enabled") == "true",
|
||||
focused=node.get("focused") == "true",
|
||||
)
|
||||
)
|
||||
return elements
|
||||
|
||||
@ -209,3 +209,169 @@ class TestTap:
|
||||
c for c in ui.device.calls if c[:3] == ("shell", "input", "keyevent")
|
||||
]
|
||||
assert keyevents, "expected the keyboard to be dismissed first"
|
||||
|
||||
|
||||
class TestKeyboard:
|
||||
def test_reports_whether_the_keyboard_is_up(self, ui: Harness) -> None:
|
||||
ui.device.keyboard_shown = True
|
||||
assert ui.ui.keyboard_is_up()
|
||||
ui.device.keyboard_shown = False
|
||||
assert not ui.ui.keyboard_is_up()
|
||||
|
||||
def test_dismiss_is_a_no_op_when_already_closed(self, ui: Harness) -> None:
|
||||
ui.ui.dismiss_keyboard()
|
||||
assert not [
|
||||
c for c in ui.device.calls if c[:3] == ("shell", "input", "keyevent")
|
||||
]
|
||||
|
||||
def test_closes_on_the_second_keyevent_when_escape_is_ignored(
|
||||
self, ui: Harness, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
# Gboard ignores ESCAPE; BACK is the fallback. Exercises the loop
|
||||
# running to completion rather than returning on the first check.
|
||||
states = iter([True, True, False])
|
||||
monkeypatch.setattr(ui.ui, "keyboard_is_up", lambda: next(states, False))
|
||||
ui.ui.dismiss_keyboard()
|
||||
sent = [
|
||||
c[3] for c in ui.device.calls if c[:3] == ("shell", "input", "keyevent")
|
||||
]
|
||||
assert sent == ["111", "4"]
|
||||
|
||||
def test_raises_when_the_keyboard_will_not_close(
|
||||
self, ui: Harness, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
# A keyboard that stays up hides the target; silently continuing would
|
||||
# tap a letter key and report success.
|
||||
monkeypatch.setattr(ui.ui, "keyboard_is_up", lambda: True)
|
||||
with pytest.raises(drv.UiAutomationError, match="still covering"):
|
||||
ui.ui.dismiss_keyboard()
|
||||
|
||||
|
||||
class TestTyping:
|
||||
def test_verifies_the_field_actually_changed(self, ui: Harness) -> None:
|
||||
empty = _node(cls="android.widget.EditText", bounds="[0,0][100,50]")
|
||||
filled = _node(
|
||||
"typed@example.com",
|
||||
cls="android.widget.EditText",
|
||||
bounds="[0,0][100,50]",
|
||||
)
|
||||
ui.device.trees = [_tree(empty), _tree(filled)]
|
||||
ui.ui.type_into_field(0, "typed@example.com")
|
||||
|
||||
def test_raises_when_the_tap_did_not_focus_the_field(self, ui: Harness) -> None:
|
||||
# The observed failure: keystrokes go nowhere and NOTHING errors.
|
||||
empty = _tree(_node(cls="android.widget.EditText", bounds="[0,0][100,50]"))
|
||||
ui.device.trees = [empty]
|
||||
with pytest.raises(drv.UiAutomationError, match="did not change"):
|
||||
ui.ui.type_into_field(0, "typed@example.com")
|
||||
|
||||
def test_clears_a_filled_field_before_typing(self, ui: Harness) -> None:
|
||||
# `input text` inserts at the cursor: typing over "old" would produce
|
||||
# "oldnew", which passes a naive "did it change?" check and is wrong.
|
||||
before = _node("old", cls="android.widget.EditText", bounds="[0,0][100,50]")
|
||||
after = _node("new", cls="android.widget.EditText", bounds="[0,0][100,50]")
|
||||
ui.device.trees = [_tree(before), _tree(after)]
|
||||
ui.ui.type_into_field(0, "new")
|
||||
deletes = [
|
||||
c
|
||||
for c in ui.device.calls
|
||||
if c[:3] == ("shell", "input", "keyevent") and c[3] == "67"
|
||||
]
|
||||
assert deletes, "expected the field to be cleared first"
|
||||
|
||||
def test_refuses_an_index_the_screen_does_not_have(self, ui: Harness) -> None:
|
||||
ui.device.trees = [_tree(_node(cls="android.widget.EditText"))]
|
||||
with pytest.raises(drv.ElementNotFoundError, match="has 1"):
|
||||
ui.ui.type_into_field(4, "x")
|
||||
|
||||
def test_editable_fields_are_ordered_top_to_bottom(self, ui: Harness) -> None:
|
||||
lower = _node(cls="android.widget.EditText", bounds="[0,300][100,350]")
|
||||
upper = _node(cls="android.widget.EditText", bounds="[0,100][100,150]")
|
||||
ui.device.trees = [_tree(lower, upper)]
|
||||
assert [f.bounds[1] for f in ui.ui.editable_fields()] == [100, 300]
|
||||
|
||||
def test_type_into_named_field_verifies_too(self, ui: Harness) -> None:
|
||||
before = _node(
|
||||
desc="Email", cls="android.widget.EditText", bounds="[0,0][100,50]"
|
||||
)
|
||||
after = _node(
|
||||
"x@y.z", desc="Email", cls="android.widget.EditText", bounds="[0,0][100,50]"
|
||||
)
|
||||
ui.device.trees = [_tree(before), _tree(before), _tree(after)]
|
||||
ui.ui.type_into("Email", "x@y.z")
|
||||
|
||||
def test_type_into_named_field_raises_when_unchanged(self, ui: Harness) -> None:
|
||||
node = _node(desc="Email", cls="android.widget.EditText")
|
||||
ui.device.trees = [_tree(node)]
|
||||
with pytest.raises(drv.UiAutomationError, match="did not change"):
|
||||
ui.ui.type_into("Email", "x@y.z")
|
||||
|
||||
|
||||
class TestEscape:
|
||||
def test_spaces_become_percent_s(self) -> None:
|
||||
assert drv._escape("a b") == "a%sb"
|
||||
|
||||
def test_shell_metacharacters_are_escaped(self) -> None:
|
||||
assert drv._escape("a&b") == r"a\&b"
|
||||
|
||||
def test_percent_is_escaped_first(self) -> None:
|
||||
assert drv._escape("100%") == "100%%"
|
||||
|
||||
|
||||
class TestCurrentFocus:
|
||||
def test_returns_the_focused_activity(self, ui: Harness) -> None:
|
||||
assert ui.ui.current_focus() == "com.example/com.example.Main"
|
||||
|
||||
def test_empty_when_nothing_matches(
|
||||
self, ui: Harness, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
monkeypatch.setattr(ui.ui, "_run", lambda *a, **k: "no focus here")
|
||||
assert ui.ui.current_focus() == ""
|
||||
|
||||
|
||||
class TestRun:
|
||||
def test_serial_is_passed_through(self, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
seen: dict[str, list[str]] = {}
|
||||
|
||||
class _Done:
|
||||
returncode = 0
|
||||
stdout = "ok"
|
||||
stderr = ""
|
||||
|
||||
def _fake_run(cmd: list[str], **_kwargs: object) -> _Done:
|
||||
seen["cmd"] = cmd
|
||||
return _Done()
|
||||
|
||||
monkeypatch.setattr(f"{MOD}.subprocess.run", _fake_run)
|
||||
drv.AndroidUi(serial="ABC123")._run("devices")
|
||||
assert seen["cmd"][:3] == ["adb", "-s", "ABC123"]
|
||||
|
||||
def test_nonzero_exit_raises_with_stderr(
|
||||
self, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
class _Done:
|
||||
returncode = 1
|
||||
stdout = ""
|
||||
stderr = "device offline"
|
||||
|
||||
monkeypatch.setattr(f"{MOD}.subprocess.run", lambda *a, **k: _Done())
|
||||
with pytest.raises(drv.UiAutomationError, match="device offline"):
|
||||
drv.AndroidUi()._run("devices")
|
||||
|
||||
def test_timeout_raises(self, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
def _boom(*_a: object, **_k: object) -> None:
|
||||
raise drv.subprocess.TimeoutExpired(cmd="adb", timeout=1)
|
||||
|
||||
monkeypatch.setattr(f"{MOD}.subprocess.run", _boom)
|
||||
with pytest.raises(drv.UiAutomationError, match="timed out"):
|
||||
drv.AndroidUi()._run("devices")
|
||||
|
||||
def test_unreadable_dump_raises(
|
||||
self, ui: Harness, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
def _no_write(*_a: object, **_k: object) -> str:
|
||||
return ""
|
||||
|
||||
monkeypatch.setattr(ui.ui, "_run", _no_write)
|
||||
with pytest.raises(drv.UiAutomationError, match="could not read"):
|
||||
ui.ui._dump_once()
|
||||
|
||||
@ -1,158 +0,0 @@
|
||||
"""Tests for shell escaping, focus reads and the adb runner."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from typing import NamedTuple
|
||||
|
||||
import pytest
|
||||
|
||||
from python_pkg.android_ui import driver as drv
|
||||
|
||||
MOD = "python_pkg.android_ui.driver"
|
||||
|
||||
|
||||
def _node(text: str = "", **attrs: str) -> str:
|
||||
"""Render one ``<node>`` element for a fake dump.
|
||||
|
||||
``attrs`` accepts ``desc``, ``res``, ``cls``, ``bounds``, ``enabled`` and
|
||||
``focused``; each falls back to a representative default.
|
||||
"""
|
||||
return (
|
||||
f'<node text="{text}" content-desc="{attrs.get("desc", "")}" '
|
||||
f'resource-id="{attrs.get("res", "")}" '
|
||||
f'class="{attrs.get("cls", "android.widget.TextView")}" '
|
||||
f'bounds="{attrs.get("bounds", "[0,0][100,50]")}" '
|
||||
f'enabled="{attrs.get("enabled", "true")}" '
|
||||
f'focused="{attrs.get("focused", "false")}"/>'
|
||||
)
|
||||
|
||||
|
||||
def _tree(*nodes: str) -> str:
|
||||
"""Wrap ``nodes`` in a hierarchy document."""
|
||||
return f"<?xml version='1.0'?><hierarchy rotation='0'>{''.join(nodes)}</hierarchy>"
|
||||
|
||||
|
||||
class FakeDevice:
|
||||
"""Scripted stand-in for adb, recording every command it is given."""
|
||||
|
||||
def __init__(self, trees: list[str] | None = None) -> None:
|
||||
self.trees = trees or [_tree(_node("Connect"))]
|
||||
self.calls: list[tuple[str, ...]] = []
|
||||
self.keyboard_shown = False
|
||||
self.pulled = 0
|
||||
|
||||
def run(self, *args: str, timeout: float = 30.0) -> str:
|
||||
"""Answer an adb invocation."""
|
||||
del timeout
|
||||
self.calls.append(args)
|
||||
if args[:2] == ("shell", "dumpsys") and args[2] == "input_method":
|
||||
return f"mInputShown={'true' if self.keyboard_shown else 'false'}"
|
||||
if args[:2] == ("shell", "dumpsys") and args[2] == "window":
|
||||
return "mCurrentFocus=Window{ab12 u0 com.example/com.example.Main}"
|
||||
if args[0] == "pull":
|
||||
index = min(self.pulled, len(self.trees) - 1)
|
||||
self.pulled += 1
|
||||
Path(args[2]).write_text(self.trees[index], encoding="utf-8")
|
||||
if args[:3] == ("shell", "input", "keyevent") and args[3] in {"111", "4"}:
|
||||
self.keyboard_shown = False
|
||||
return ""
|
||||
|
||||
def taps(self) -> list[tuple[int, int]]:
|
||||
"""Return every tap coordinate, in order."""
|
||||
return [
|
||||
(int(c[3]), int(c[4]))
|
||||
for c in self.calls
|
||||
if c[:3] == ("shell", "input", "tap")
|
||||
]
|
||||
|
||||
|
||||
class Harness(NamedTuple):
|
||||
"""A driver plus the fake device backing it.
|
||||
|
||||
Returned as a pair rather than by bolting the device onto the driver, so
|
||||
the test needs no attribute that production code does not have.
|
||||
"""
|
||||
|
||||
ui: drv.AndroidUi
|
||||
device: FakeDevice
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def ui(monkeypatch: pytest.MonkeyPatch) -> Harness:
|
||||
"""An :class:`AndroidUi` wired to a :class:`FakeDevice`."""
|
||||
device = FakeDevice()
|
||||
instance = drv.AndroidUi(settle_seconds=0.0)
|
||||
monkeypatch.setattr(instance, "_run", device.run)
|
||||
monkeypatch.setattr(f"{MOD}.time.sleep", lambda _s: None)
|
||||
return Harness(ui=instance, device=device)
|
||||
|
||||
|
||||
class TestEscape:
|
||||
def test_spaces_become_percent_s(self) -> None:
|
||||
assert drv._escape("a b") == "a%sb"
|
||||
|
||||
def test_shell_metacharacters_are_escaped(self) -> None:
|
||||
assert drv._escape("a&b") == r"a\&b"
|
||||
|
||||
def test_percent_is_escaped_first(self) -> None:
|
||||
assert drv._escape("100%") == "100%%"
|
||||
|
||||
|
||||
class TestCurrentFocus:
|
||||
def test_returns_the_focused_activity(self, ui: Harness) -> None:
|
||||
assert ui.ui.current_focus() == "com.example/com.example.Main"
|
||||
|
||||
def test_empty_when_nothing_matches(
|
||||
self, ui: Harness, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
monkeypatch.setattr(ui.ui, "_run", lambda *a, **k: "no focus here")
|
||||
assert ui.ui.current_focus() == ""
|
||||
|
||||
|
||||
class TestRun:
|
||||
def test_serial_is_passed_through(self, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
seen: dict[str, list[str]] = {}
|
||||
|
||||
class _Done:
|
||||
returncode = 0
|
||||
stdout = "ok"
|
||||
stderr = ""
|
||||
|
||||
def _fake_run(cmd: list[str], **_kwargs: object) -> _Done:
|
||||
seen["cmd"] = cmd
|
||||
return _Done()
|
||||
|
||||
monkeypatch.setattr(f"{MOD}.subprocess.run", _fake_run)
|
||||
drv.AndroidUi(serial="ABC123")._run("devices")
|
||||
assert seen["cmd"][:3] == ["adb", "-s", "ABC123"]
|
||||
|
||||
def test_nonzero_exit_raises_with_stderr(
|
||||
self, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
class _Done:
|
||||
returncode = 1
|
||||
stdout = ""
|
||||
stderr = "device offline"
|
||||
|
||||
monkeypatch.setattr(f"{MOD}.subprocess.run", lambda *a, **k: _Done())
|
||||
with pytest.raises(drv.UiAutomationError, match="device offline"):
|
||||
drv.AndroidUi()._run("devices")
|
||||
|
||||
def test_timeout_raises(self, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
def _boom(*_a: object, **_k: object) -> None:
|
||||
raise drv.subprocess.TimeoutExpired(cmd="adb", timeout=1)
|
||||
|
||||
monkeypatch.setattr(f"{MOD}.subprocess.run", _boom)
|
||||
with pytest.raises(drv.UiAutomationError, match="timed out"):
|
||||
drv.AndroidUi()._run("devices")
|
||||
|
||||
def test_unreadable_dump_raises(
|
||||
self, ui: Harness, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
def _no_write(*_a: object, **_k: object) -> str:
|
||||
return ""
|
||||
|
||||
monkeypatch.setattr(ui.ui, "_run", _no_write)
|
||||
with pytest.raises(drv.UiAutomationError, match="could not read"):
|
||||
ui.ui._dump_once()
|
||||
@ -1,184 +0,0 @@
|
||||
"""Tests for the keyboard and text-entry half of the driver."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from typing import NamedTuple
|
||||
|
||||
import pytest
|
||||
|
||||
from python_pkg.android_ui import driver as drv
|
||||
|
||||
MOD = "python_pkg.android_ui.driver"
|
||||
|
||||
|
||||
def _node(text: str = "", **attrs: str) -> str:
|
||||
"""Render one ``<node>`` element for a fake dump.
|
||||
|
||||
``attrs`` accepts ``desc``, ``res``, ``cls``, ``bounds``, ``enabled`` and
|
||||
``focused``; each falls back to a representative default.
|
||||
"""
|
||||
return (
|
||||
f'<node text="{text}" content-desc="{attrs.get("desc", "")}" '
|
||||
f'resource-id="{attrs.get("res", "")}" '
|
||||
f'class="{attrs.get("cls", "android.widget.TextView")}" '
|
||||
f'bounds="{attrs.get("bounds", "[0,0][100,50]")}" '
|
||||
f'enabled="{attrs.get("enabled", "true")}" '
|
||||
f'focused="{attrs.get("focused", "false")}"/>'
|
||||
)
|
||||
|
||||
|
||||
def _tree(*nodes: str) -> str:
|
||||
"""Wrap ``nodes`` in a hierarchy document."""
|
||||
return f"<?xml version='1.0'?><hierarchy rotation='0'>{''.join(nodes)}</hierarchy>"
|
||||
|
||||
|
||||
class FakeDevice:
|
||||
"""Scripted stand-in for adb, recording every command it is given."""
|
||||
|
||||
def __init__(self, trees: list[str] | None = None) -> None:
|
||||
self.trees = trees or [_tree(_node("Connect"))]
|
||||
self.calls: list[tuple[str, ...]] = []
|
||||
self.keyboard_shown = False
|
||||
self.pulled = 0
|
||||
|
||||
def run(self, *args: str, timeout: float = 30.0) -> str:
|
||||
"""Answer an adb invocation."""
|
||||
del timeout
|
||||
self.calls.append(args)
|
||||
if args[:2] == ("shell", "dumpsys") and args[2] == "input_method":
|
||||
return f"mInputShown={'true' if self.keyboard_shown else 'false'}"
|
||||
if args[:2] == ("shell", "dumpsys") and args[2] == "window":
|
||||
return "mCurrentFocus=Window{ab12 u0 com.example/com.example.Main}"
|
||||
if args[0] == "pull":
|
||||
index = min(self.pulled, len(self.trees) - 1)
|
||||
self.pulled += 1
|
||||
Path(args[2]).write_text(self.trees[index], encoding="utf-8")
|
||||
if args[:3] == ("shell", "input", "keyevent") and args[3] in {"111", "4"}:
|
||||
self.keyboard_shown = False
|
||||
return ""
|
||||
|
||||
def taps(self) -> list[tuple[int, int]]:
|
||||
"""Return every tap coordinate, in order."""
|
||||
return [
|
||||
(int(c[3]), int(c[4]))
|
||||
for c in self.calls
|
||||
if c[:3] == ("shell", "input", "tap")
|
||||
]
|
||||
|
||||
|
||||
class Harness(NamedTuple):
|
||||
"""A driver plus the fake device backing it.
|
||||
|
||||
Returned as a pair rather than by bolting the device onto the driver, so
|
||||
the test needs no attribute that production code does not have.
|
||||
"""
|
||||
|
||||
ui: drv.AndroidUi
|
||||
device: FakeDevice
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def ui(monkeypatch: pytest.MonkeyPatch) -> Harness:
|
||||
"""An :class:`AndroidUi` wired to a :class:`FakeDevice`."""
|
||||
device = FakeDevice()
|
||||
instance = drv.AndroidUi(settle_seconds=0.0)
|
||||
monkeypatch.setattr(instance, "_run", device.run)
|
||||
monkeypatch.setattr(f"{MOD}.time.sleep", lambda _s: None)
|
||||
return Harness(ui=instance, device=device)
|
||||
|
||||
|
||||
class TestKeyboard:
|
||||
def test_reports_whether_the_keyboard_is_up(self, ui: Harness) -> None:
|
||||
ui.device.keyboard_shown = True
|
||||
assert ui.ui.keyboard_is_up()
|
||||
ui.device.keyboard_shown = False
|
||||
assert not ui.ui.keyboard_is_up()
|
||||
|
||||
def test_dismiss_is_a_no_op_when_already_closed(self, ui: Harness) -> None:
|
||||
ui.ui.dismiss_keyboard()
|
||||
assert not [
|
||||
c for c in ui.device.calls if c[:3] == ("shell", "input", "keyevent")
|
||||
]
|
||||
|
||||
def test_closes_on_the_second_keyevent_when_escape_is_ignored(
|
||||
self, ui: Harness, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
# Gboard ignores ESCAPE; BACK is the fallback. Exercises the loop
|
||||
# running to completion rather than returning on the first check.
|
||||
states = iter([True, True, False])
|
||||
monkeypatch.setattr(ui.ui, "keyboard_is_up", lambda: next(states, False))
|
||||
ui.ui.dismiss_keyboard()
|
||||
sent = [
|
||||
c[3] for c in ui.device.calls if c[:3] == ("shell", "input", "keyevent")
|
||||
]
|
||||
assert sent == ["111", "4"]
|
||||
|
||||
def test_raises_when_the_keyboard_will_not_close(
|
||||
self, ui: Harness, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
# A keyboard that stays up hides the target; silently continuing would
|
||||
# tap a letter key and report success.
|
||||
monkeypatch.setattr(ui.ui, "keyboard_is_up", lambda: True)
|
||||
with pytest.raises(drv.UiAutomationError, match="still covering"):
|
||||
ui.ui.dismiss_keyboard()
|
||||
|
||||
|
||||
class TestTyping:
|
||||
def test_verifies_the_field_actually_changed(self, ui: Harness) -> None:
|
||||
empty = _node(cls="android.widget.EditText", bounds="[0,0][100,50]")
|
||||
filled = _node(
|
||||
"typed@example.com",
|
||||
cls="android.widget.EditText",
|
||||
bounds="[0,0][100,50]",
|
||||
)
|
||||
ui.device.trees = [_tree(empty), _tree(filled)]
|
||||
ui.ui.type_into_field(0, "typed@example.com")
|
||||
|
||||
def test_raises_when_the_tap_did_not_focus_the_field(self, ui: Harness) -> None:
|
||||
# The observed failure: keystrokes go nowhere and NOTHING errors.
|
||||
empty = _tree(_node(cls="android.widget.EditText", bounds="[0,0][100,50]"))
|
||||
ui.device.trees = [empty]
|
||||
with pytest.raises(drv.UiAutomationError, match="did not change"):
|
||||
ui.ui.type_into_field(0, "typed@example.com")
|
||||
|
||||
def test_clears_a_filled_field_before_typing(self, ui: Harness) -> None:
|
||||
# `input text` inserts at the cursor: typing over "old" would produce
|
||||
# "oldnew", which passes a naive "did it change?" check and is wrong.
|
||||
before = _node("old", cls="android.widget.EditText", bounds="[0,0][100,50]")
|
||||
after = _node("new", cls="android.widget.EditText", bounds="[0,0][100,50]")
|
||||
ui.device.trees = [_tree(before), _tree(after)]
|
||||
ui.ui.type_into_field(0, "new")
|
||||
deletes = [
|
||||
c
|
||||
for c in ui.device.calls
|
||||
if c[:3] == ("shell", "input", "keyevent") and c[3] == "67"
|
||||
]
|
||||
assert deletes, "expected the field to be cleared first"
|
||||
|
||||
def test_refuses_an_index_the_screen_does_not_have(self, ui: Harness) -> None:
|
||||
ui.device.trees = [_tree(_node(cls="android.widget.EditText"))]
|
||||
with pytest.raises(drv.ElementNotFoundError, match="has 1"):
|
||||
ui.ui.type_into_field(4, "x")
|
||||
|
||||
def test_editable_fields_are_ordered_top_to_bottom(self, ui: Harness) -> None:
|
||||
lower = _node(cls="android.widget.EditText", bounds="[0,300][100,350]")
|
||||
upper = _node(cls="android.widget.EditText", bounds="[0,100][100,150]")
|
||||
ui.device.trees = [_tree(lower, upper)]
|
||||
assert [f.bounds[1] for f in ui.ui.editable_fields()] == [100, 300]
|
||||
|
||||
def test_type_into_named_field_verifies_too(self, ui: Harness) -> None:
|
||||
before = _node(
|
||||
desc="Email", cls="android.widget.EditText", bounds="[0,0][100,50]"
|
||||
)
|
||||
after = _node(
|
||||
"x@y.z", desc="Email", cls="android.widget.EditText", bounds="[0,0][100,50]"
|
||||
)
|
||||
ui.device.trees = [_tree(before), _tree(before), _tree(after)]
|
||||
ui.ui.type_into("Email", "x@y.z")
|
||||
|
||||
def test_type_into_named_field_raises_when_unchanged(self, ui: Harness) -> None:
|
||||
node = _node(desc="Email", cls="android.widget.EditText")
|
||||
ui.device.trees = [_tree(node)]
|
||||
with pytest.raises(drv.UiAutomationError, match="did not change"):
|
||||
ui.ui.type_into("Email", "x@y.z")
|
||||
@ -1,220 +0,0 @@
|
||||
"""The SVG path fragments each glyph is drawn from.
|
||||
|
||||
Split out of :mod:`python_pkg.app_icons.glyphs` to keep it under the 250-line
|
||||
cap. Pure data: :mod:`glyphs` keeps the Glyph dataclass, the registry and the
|
||||
lookup, so no caller or test needs to know these moved.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
_CLOUD_DOWN = """\
|
||||
<g transform="translate(296,196) scale(18)" stroke-width="4">
|
||||
<path d="M19.35 10.04C18.67 6.59 15.64 4 12 4 9.11 4 6.6 5.64 5.35 8.04 \
|
||||
2.34 8.36 0 10.91 0 14c0 3.31 2.69 6 6 6h13c2.76 0 5-2.24 5-5 \
|
||||
0-2.64-2.05-4.78-4.65-4.96z"/>
|
||||
</g>
|
||||
<path d="M 512 628 L 512 744"/>
|
||||
<path d="M 444 676 L 512 744 L 580 676"/>"""
|
||||
|
||||
# Bar, two plates and two collars. Plate spacing is well above the minimum
|
||||
# negative space so the bar does not fill in at launcher size.
|
||||
_BARBELL = """\
|
||||
<path d="M 268 512 L 756 512"/>
|
||||
<path d="M 364 356 L 364 668"/>
|
||||
<path d="M 660 356 L 660 668"/>
|
||||
<path d="M 268 432 L 268 592"/>
|
||||
<path d="M 756 432 L 756 592"/>"""
|
||||
|
||||
# Plain clock face. Deliberately no bell "ears": at launcher size they read as
|
||||
# noise rather than as an alarm clock.
|
||||
_CLOCK = """\
|
||||
<circle cx="512" cy="512" r="244"/>
|
||||
<path d="M 512 512 L 512 350"/>
|
||||
<path d="M 512 512 L 636 512"/>"""
|
||||
|
||||
# Shield outline guarding filled cutlery. The fork is paired with a knife on
|
||||
# purpose: a lone three-tine fork reads as a trident at small sizes.
|
||||
_SHIELD_CUTLERY = """\
|
||||
<path d="M 512 275 L 752 366 L 752 544 C 752 655 646 723 512 753 \
|
||||
C 378 723 272 655 272 544 L 272 366 Z"/>
|
||||
<g transform="translate(356,362) scale(13)" fill="{{ACCENT}}" stroke="none">
|
||||
<path d="M11 9H9V2H7v7H5V2H3v7c0 2.12 1.66 3.84 3.75 3.97V22h2.5v-9.03\
|
||||
C11.34 12.84 13 11.12 13 9V2h-2v7z"/>
|
||||
<path d="M16 12h2.5v10H21V2c-2.76 0-5 2.24-5 5v5z"/>
|
||||
</g>"""
|
||||
|
||||
# Two ticked-off list rows. More specific to a notes/todo app than a lone
|
||||
# checkmark, and still legible at 48dp.
|
||||
_CHECKLIST = """\
|
||||
<path d="M 272 372 L 346 446 L 478 314"/>
|
||||
<path d="M 594 400 L 752 400"/>
|
||||
<path d="M 272 620 L 346 694 L 478 562"/>
|
||||
<path d="M 594 648 L 752 648"/>"""
|
||||
|
||||
# A branching decision tree: one node splitting into two. Reads as "decompose
|
||||
# a problem into parts", the move every one of the 25 thinking tools makes in
|
||||
# some form -- an issue tree most literally, but also a fishbone's ribs and a
|
||||
# 2x2's quadrants.
|
||||
#
|
||||
# Nodes are hollow circles rather than filled dots: at 48dp a filled dot and
|
||||
# the 72px stroke merge into a blob, while the ring keeps visible negative
|
||||
# space (r=78 leaves 156-72=84px of interior).
|
||||
#
|
||||
# Two levels of branching were tried first (7 nodes) and rejected: the
|
||||
# generator's safe-box check flagged it as overflowing by ~170px, and at icon
|
||||
# size the doubled connectors closed up into a solid mass. One clean split
|
||||
# survives the launcher mask and still reads as a tree rather than a Y-fork,
|
||||
# because the square shoulders and vertical drops keep the hierarchy legible.
|
||||
_DECISION_TREE = """\
|
||||
<circle cx="512" cy="300" r="78"/>
|
||||
<path d="M 512 378 L 512 452"/>
|
||||
<path d="M 346 452 L 678 452"/>
|
||||
<path d="M 346 452 L 346 528"/>
|
||||
<path d="M 678 452 L 678 528"/>
|
||||
<circle cx="346" cy="606" r="78"/>
|
||||
<circle cx="678" cy="606" r="78"/>"""
|
||||
|
||||
# Two interlocking stadium (pill-ring) outlines, both rotated -45 deg and
|
||||
# offset along the anti-diagonal so their strokes overlap in the middle --
|
||||
# reads as both "habit-stacking" (linked items) and "don't break the chain".
|
||||
# Ring height is tall enough that the 72px stroke leaves a genuinely hollow
|
||||
# interior (height - 2*stroke-width well above MIN_NEGATIVE_SPACE); a
|
||||
# shorter ring's stroke fills the interior solid and reads as a blob.
|
||||
_CHAIN_LINK = """\
|
||||
<g transform="translate(467,557) rotate(-45) translate(-150,-110)">
|
||||
<rect x="0" y="0" width="300" height="220" rx="110" ry="110"/>
|
||||
</g>
|
||||
<g transform="translate(557,467) rotate(-45) translate(-150,-110)">
|
||||
<rect x="0" y="0" width="300" height="220" rx="110" ry="110"/>
|
||||
</g>"""
|
||||
|
||||
|
||||
# An isometric storage carton: hexagonal silhouette plus the three edges that
|
||||
# meet at the near-top corner (one down the front, two up the top face).
|
||||
#
|
||||
# A front-on rectangle with a lid seam was tried first and rejected — a seam
|
||||
# plus a divider reads as a browser window or a table header, not a box. The
|
||||
# isometric form has no such collision anywhere else in the family, and it is
|
||||
# the shape people already recognise as "a package of stuff".
|
||||
#
|
||||
# Geometry: a regular hexagon, centre (512,512), circumradius 240, pointy top
|
||||
# and bottom. Opposite faces sit 208px apart, leaving 136px of hollow once the
|
||||
# 72px stroke is drawn — comfortably past MIN_NEGATIVE_SPACE, so no face fills
|
||||
# in at 48dp. Rendered ink is 488x552, inside SAFE_BOX on both axes.
|
||||
_STORAGE_BOX = """\
|
||||
<path d="M 512 272 L 720 392 L 720 632 L 512 752 L 304 632 L 304 392 Z"/>
|
||||
<path d="M 512 512 L 512 752"/>
|
||||
<path d="M 512 512 L 304 392"/>
|
||||
<path d="M 512 512 L 720 392"/>"""
|
||||
|
||||
|
||||
# A till receipt with a torn bottom edge and a perforation down the middle:
|
||||
# one bill, two shares.
|
||||
#
|
||||
# Filled rather than stroked, which is what makes the tear possible at all. A
|
||||
# stroked receipt cannot have a fine ragged edge: at the family's 72px stroke,
|
||||
# a zigzag needs ~200px pitch to keep adjacent up-strokes MIN_NEGATIVE_SPACE
|
||||
# apart, and two teeth that coarse read as a ribbon or a pair of bookmarks,
|
||||
# not as a torn receipt. A filled silhouette is not bound by that rule, so the
|
||||
# teeth can be small enough to read as a real tear — the "prefer a filled
|
||||
# silhouette when a stroked outline reads ambiguously" case.
|
||||
#
|
||||
# The split is a perforation, not a divider. A full-height divider cuts the
|
||||
# silhouette into two separate shapes and the receipt read is lost (the same
|
||||
# bookmarks failure); a dotted tear line says "split here" while leaving one
|
||||
# intact receipt. Drawn with fill-rule="evenodd" so the dots are true holes,
|
||||
# not charcoal-painted ones — icon_foreground and icon_monochrome are rendered
|
||||
# on transparency, where a painted hole would show as a blob and, on the
|
||||
# monochrome layer, in the wrong colour entirely.
|
||||
#
|
||||
# Geometry: body x 312..712, y 282..752, six teeth 46px deep off a root at
|
||||
# y=706. Four holes of r=30 on the centreline at y=350/446/542/638. Every gap
|
||||
# is at the family budget: 36px of accent between holes (96px pitch, 60px
|
||||
# diameter), 38px above the first and below the last. Ink is 400x470, inside
|
||||
# SAFE_BOX on both axes.
|
||||
_RECEIPT_SPLIT = """\
|
||||
<path fill="{{ACCENT}}" fill-rule="evenodd" stroke="none" d="\
|
||||
M 312 282 L 712 282 L 712 706 L 678 752 L 645 706 L 612 752 L 578 706 \
|
||||
L 545 752 L 512 706 L 478 752 L 445 706 L 412 752 L 378 706 L 345 752 \
|
||||
L 312 706 Z \
|
||||
M 482 350 A 30 30 0 1 0 542 350 A 30 30 0 1 0 482 350 Z \
|
||||
M 482 446 A 30 30 0 1 0 542 446 A 30 30 0 1 0 482 446 Z \
|
||||
M 482 542 A 30 30 0 1 0 542 542 A 30 30 0 1 0 482 542 Z \
|
||||
M 482 638 A 30 30 0 1 0 542 638 A 30 30 0 1 0 482 638 Z"/>"""
|
||||
|
||||
|
||||
# A dip-pen nib: the character sheet is a thing you write on, and the game is
|
||||
# set in the Romantic era, so the nib carries both the app and the period.
|
||||
#
|
||||
# Filled rather than stroked. A stroked almond outline plus a stroked vent hole
|
||||
# leaves only ~20px of charcoal between the two strokes at the family's 72px
|
||||
# weight — under MIN_NEGATIVE_SPACE, so the nib fills in solid at 48dp. Filled,
|
||||
# the vent and the slit become true holes and the budget is spent on gaps
|
||||
# instead of on stroke.
|
||||
#
|
||||
# A d20 was the obvious alternative and was rejected: this system rolls k6, and
|
||||
# a 20-sided outline is a mess of short strokes at launcher size. A front-on
|
||||
# die with pips collides with `storage-box` (both read as "boxy thing with
|
||||
# marks"). Nothing else in the family is a tall pointed shape.
|
||||
#
|
||||
# The top edge is flat, not pointed. A symmetric almond — pointed at both ends
|
||||
# — with a round hole in the upper half is a map pin, which is exactly what the
|
||||
# first draft rendered as. The flat shoulder is where a real nib clips into the
|
||||
# holder, and it is what stops the map-pin read.
|
||||
#
|
||||
# Geometry: shoulder (420,312)-(604,312), waist bowing out to ~x=400/624 around
|
||||
# y=456, converging to the tip at (512,812) — ink 224x500, inside SAFE_BOX on
|
||||
# both axes. Vent circle r=40 at (512,470) clears the outline by ~61px; the
|
||||
# slit stops at y=700, leaving ~41px to the outline near the tip and 70px to
|
||||
# the vent above. Every gap is over the 36px budget. fill-rule="evenodd" keeps
|
||||
# both holes true holes — icon_foreground and icon_monochrome render on
|
||||
# transparency, where a painted hole would show as a blob and in the wrong
|
||||
# colour.
|
||||
_QUILL_NIB = """\
|
||||
<path fill="{{ACCENT}}" fill-rule="evenodd" stroke="none" d="\
|
||||
M 420 312 L 604 312 Q 626 470 596 570 L 512 812 L 428 570 \
|
||||
Q 398 470 420 312 Z \
|
||||
M 472 470 A 40 40 0 1 0 552 470 A 40 40 0 1 0 472 470 Z \
|
||||
M 512 700 L 492 580 L 532 580 Z"/>"""
|
||||
|
||||
|
||||
# A blacksmith's anvil: OctoForge is a GitHub client, and the forge is the
|
||||
# name. Filled rather than stroked, for the same reason as the nib — a stroked
|
||||
# anvil outline is a long thin horn plus a narrow waist, and at the family's
|
||||
# 72px weight the waist closes up solid at 48dp.
|
||||
#
|
||||
# The obvious alternatives were rejected: an octopus (the Octocat) is both
|
||||
# GitHub trade dress and a tangle of thin curves that blurs at launcher size,
|
||||
# and a hammer alone collides with nothing in the family but reads as a generic
|
||||
# tool rather than a forge. The anvil silhouette is unmistakable and shares no
|
||||
# shape language with the other nine glyphs.
|
||||
#
|
||||
# Geometry: the body is a face slab (x=336..768, y=316..420), a waist
|
||||
# (x=444..596, y=420..592) and a flared foot (x=304..716, y=592..708) — total
|
||||
# ink 512x392 including the horn, inside SAFE_BOX once the renderer scales it.
|
||||
#
|
||||
# The horn is what makes this an anvil rather than an I-beam, so it is a
|
||||
# separate wedge projecting left off the face, not a rounded corner on it: it
|
||||
# leaves the slab at full 104px depth (x=336) and tapers to a 40px blunt tip
|
||||
# at x=256, dropping the underside from y=420 to y=392 on the way. A sharp
|
||||
# point would disappear at 48dp; 40px is above MIN_NEGATIVE_SPACE so it
|
||||
# survives. The first two drafts folded the taper into the slab's left end and
|
||||
# both read as a bump.
|
||||
_ANVIL = """\
|
||||
<path fill="{{ACCENT}}" stroke="none" d="\
|
||||
M 768 316 L 768 420 L 596 420 \
|
||||
Q 592 512 592 592 L 716 592 L 716 708 L 304 708 L 304 592 L 428 592 \
|
||||
Q 428 512 424 420 L 336 420 \
|
||||
L 256 392 Q 248 376 256 360 L 336 316 Z"/>"""
|
||||
|
||||
# Three rising bars with a plotted point above the tallest -- a day-by-day log
|
||||
# that adds up to a trend, which is what a life tracker is. The bars are
|
||||
# strokes rather than filled rects so the glyph keeps one stroke weight
|
||||
# throughout; at a 168px pitch the 72px strokes leave 96px gaps, well above
|
||||
# MIN_NEGATIVE_SPACE. The marker sits on its own row clear of the bar caps,
|
||||
# and is hollow so it reads as a data point rather than a full stop.
|
||||
_TRACK_BARS = """\
|
||||
<path d="M 320 700 L 320 556"/>
|
||||
<path d="M 488 700 L 488 460"/>
|
||||
<path d="M 656 700 L 656 364"/>
|
||||
<circle cx="656" cy="252" r="40" fill="none"/>"""
|
||||
@ -16,21 +16,6 @@ from __future__ import annotations
|
||||
from dataclasses import dataclass
|
||||
from typing import Final
|
||||
|
||||
from python_pkg.app_icons._glyph_art import (
|
||||
_ANVIL,
|
||||
_BARBELL,
|
||||
_CHAIN_LINK,
|
||||
_CHECKLIST,
|
||||
_CLOCK,
|
||||
_CLOUD_DOWN,
|
||||
_DECISION_TREE,
|
||||
_QUILL_NIB,
|
||||
_RECEIPT_SPLIT,
|
||||
_SHIELD_CUTLERY,
|
||||
_STORAGE_BOX,
|
||||
_TRACK_BARS,
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Glyph:
|
||||
@ -49,6 +34,218 @@ class Glyph:
|
||||
|
||||
# A cloud silhouette outline with a download arrow underneath: a client that
|
||||
# pulls files off a remote dufs server.
|
||||
_CLOUD_DOWN = """\
|
||||
<g transform="translate(296,196) scale(18)" stroke-width="4">
|
||||
<path d="M19.35 10.04C18.67 6.59 15.64 4 12 4 9.11 4 6.6 5.64 5.35 8.04 \
|
||||
2.34 8.36 0 10.91 0 14c0 3.31 2.69 6 6 6h13c2.76 0 5-2.24 5-5 \
|
||||
0-2.64-2.05-4.78-4.65-4.96z"/>
|
||||
</g>
|
||||
<path d="M 512 628 L 512 744"/>
|
||||
<path d="M 444 676 L 512 744 L 580 676"/>"""
|
||||
|
||||
# Bar, two plates and two collars. Plate spacing is well above the minimum
|
||||
# negative space so the bar does not fill in at launcher size.
|
||||
_BARBELL = """\
|
||||
<path d="M 268 512 L 756 512"/>
|
||||
<path d="M 364 356 L 364 668"/>
|
||||
<path d="M 660 356 L 660 668"/>
|
||||
<path d="M 268 432 L 268 592"/>
|
||||
<path d="M 756 432 L 756 592"/>"""
|
||||
|
||||
# Plain clock face. Deliberately no bell "ears": at launcher size they read as
|
||||
# noise rather than as an alarm clock.
|
||||
_CLOCK = """\
|
||||
<circle cx="512" cy="512" r="244"/>
|
||||
<path d="M 512 512 L 512 350"/>
|
||||
<path d="M 512 512 L 636 512"/>"""
|
||||
|
||||
# Shield outline guarding filled cutlery. The fork is paired with a knife on
|
||||
# purpose: a lone three-tine fork reads as a trident at small sizes.
|
||||
_SHIELD_CUTLERY = """\
|
||||
<path d="M 512 275 L 752 366 L 752 544 C 752 655 646 723 512 753 \
|
||||
C 378 723 272 655 272 544 L 272 366 Z"/>
|
||||
<g transform="translate(356,362) scale(13)" fill="{{ACCENT}}" stroke="none">
|
||||
<path d="M11 9H9V2H7v7H5V2H3v7c0 2.12 1.66 3.84 3.75 3.97V22h2.5v-9.03\
|
||||
C11.34 12.84 13 11.12 13 9V2h-2v7z"/>
|
||||
<path d="M16 12h2.5v10H21V2c-2.76 0-5 2.24-5 5v5z"/>
|
||||
</g>"""
|
||||
|
||||
# Two ticked-off list rows. More specific to a notes/todo app than a lone
|
||||
# checkmark, and still legible at 48dp.
|
||||
_CHECKLIST = """\
|
||||
<path d="M 272 372 L 346 446 L 478 314"/>
|
||||
<path d="M 594 400 L 752 400"/>
|
||||
<path d="M 272 620 L 346 694 L 478 562"/>
|
||||
<path d="M 594 648 L 752 648"/>"""
|
||||
|
||||
# A branching decision tree: one node splitting into two. Reads as "decompose
|
||||
# a problem into parts", the move every one of the 25 thinking tools makes in
|
||||
# some form -- an issue tree most literally, but also a fishbone's ribs and a
|
||||
# 2x2's quadrants.
|
||||
#
|
||||
# Nodes are hollow circles rather than filled dots: at 48dp a filled dot and
|
||||
# the 72px stroke merge into a blob, while the ring keeps visible negative
|
||||
# space (r=78 leaves 156-72=84px of interior).
|
||||
#
|
||||
# Two levels of branching were tried first (7 nodes) and rejected: the
|
||||
# generator's safe-box check flagged it as overflowing by ~170px, and at icon
|
||||
# size the doubled connectors closed up into a solid mass. One clean split
|
||||
# survives the launcher mask and still reads as a tree rather than a Y-fork,
|
||||
# because the square shoulders and vertical drops keep the hierarchy legible.
|
||||
_DECISION_TREE = """\
|
||||
<circle cx="512" cy="300" r="78"/>
|
||||
<path d="M 512 378 L 512 452"/>
|
||||
<path d="M 346 452 L 678 452"/>
|
||||
<path d="M 346 452 L 346 528"/>
|
||||
<path d="M 678 452 L 678 528"/>
|
||||
<circle cx="346" cy="606" r="78"/>
|
||||
<circle cx="678" cy="606" r="78"/>"""
|
||||
|
||||
# Two interlocking stadium (pill-ring) outlines, both rotated -45 deg and
|
||||
# offset along the anti-diagonal so their strokes overlap in the middle --
|
||||
# reads as both "habit-stacking" (linked items) and "don't break the chain".
|
||||
# Ring height is tall enough that the 72px stroke leaves a genuinely hollow
|
||||
# interior (height - 2*stroke-width well above MIN_NEGATIVE_SPACE); a
|
||||
# shorter ring's stroke fills the interior solid and reads as a blob.
|
||||
_CHAIN_LINK = """\
|
||||
<g transform="translate(467,557) rotate(-45) translate(-150,-110)">
|
||||
<rect x="0" y="0" width="300" height="220" rx="110" ry="110"/>
|
||||
</g>
|
||||
<g transform="translate(557,467) rotate(-45) translate(-150,-110)">
|
||||
<rect x="0" y="0" width="300" height="220" rx="110" ry="110"/>
|
||||
</g>"""
|
||||
|
||||
|
||||
# An isometric storage carton: hexagonal silhouette plus the three edges that
|
||||
# meet at the near-top corner (one down the front, two up the top face).
|
||||
#
|
||||
# A front-on rectangle with a lid seam was tried first and rejected — a seam
|
||||
# plus a divider reads as a browser window or a table header, not a box. The
|
||||
# isometric form has no such collision anywhere else in the family, and it is
|
||||
# the shape people already recognise as "a package of stuff".
|
||||
#
|
||||
# Geometry: a regular hexagon, centre (512,512), circumradius 240, pointy top
|
||||
# and bottom. Opposite faces sit 208px apart, leaving 136px of hollow once the
|
||||
# 72px stroke is drawn — comfortably past MIN_NEGATIVE_SPACE, so no face fills
|
||||
# in at 48dp. Rendered ink is 488x552, inside SAFE_BOX on both axes.
|
||||
_STORAGE_BOX = """\
|
||||
<path d="M 512 272 L 720 392 L 720 632 L 512 752 L 304 632 L 304 392 Z"/>
|
||||
<path d="M 512 512 L 512 752"/>
|
||||
<path d="M 512 512 L 304 392"/>
|
||||
<path d="M 512 512 L 720 392"/>"""
|
||||
|
||||
|
||||
# A till receipt with a torn bottom edge and a perforation down the middle:
|
||||
# one bill, two shares.
|
||||
#
|
||||
# Filled rather than stroked, which is what makes the tear possible at all. A
|
||||
# stroked receipt cannot have a fine ragged edge: at the family's 72px stroke,
|
||||
# a zigzag needs ~200px pitch to keep adjacent up-strokes MIN_NEGATIVE_SPACE
|
||||
# apart, and two teeth that coarse read as a ribbon or a pair of bookmarks,
|
||||
# not as a torn receipt. A filled silhouette is not bound by that rule, so the
|
||||
# teeth can be small enough to read as a real tear — the "prefer a filled
|
||||
# silhouette when a stroked outline reads ambiguously" case.
|
||||
#
|
||||
# The split is a perforation, not a divider. A full-height divider cuts the
|
||||
# silhouette into two separate shapes and the receipt read is lost (the same
|
||||
# bookmarks failure); a dotted tear line says "split here" while leaving one
|
||||
# intact receipt. Drawn with fill-rule="evenodd" so the dots are true holes,
|
||||
# not charcoal-painted ones — icon_foreground and icon_monochrome are rendered
|
||||
# on transparency, where a painted hole would show as a blob and, on the
|
||||
# monochrome layer, in the wrong colour entirely.
|
||||
#
|
||||
# Geometry: body x 312..712, y 282..752, six teeth 46px deep off a root at
|
||||
# y=706. Four holes of r=30 on the centreline at y=350/446/542/638. Every gap
|
||||
# is at the family budget: 36px of accent between holes (96px pitch, 60px
|
||||
# diameter), 38px above the first and below the last. Ink is 400x470, inside
|
||||
# SAFE_BOX on both axes.
|
||||
_RECEIPT_SPLIT = """\
|
||||
<path fill="{{ACCENT}}" fill-rule="evenodd" stroke="none" d="\
|
||||
M 312 282 L 712 282 L 712 706 L 678 752 L 645 706 L 612 752 L 578 706 \
|
||||
L 545 752 L 512 706 L 478 752 L 445 706 L 412 752 L 378 706 L 345 752 \
|
||||
L 312 706 Z \
|
||||
M 482 350 A 30 30 0 1 0 542 350 A 30 30 0 1 0 482 350 Z \
|
||||
M 482 446 A 30 30 0 1 0 542 446 A 30 30 0 1 0 482 446 Z \
|
||||
M 482 542 A 30 30 0 1 0 542 542 A 30 30 0 1 0 482 542 Z \
|
||||
M 482 638 A 30 30 0 1 0 542 638 A 30 30 0 1 0 482 638 Z"/>"""
|
||||
|
||||
|
||||
# A dip-pen nib: the character sheet is a thing you write on, and the game is
|
||||
# set in the Romantic era, so the nib carries both the app and the period.
|
||||
#
|
||||
# Filled rather than stroked. A stroked almond outline plus a stroked vent hole
|
||||
# leaves only ~20px of charcoal between the two strokes at the family's 72px
|
||||
# weight — under MIN_NEGATIVE_SPACE, so the nib fills in solid at 48dp. Filled,
|
||||
# the vent and the slit become true holes and the budget is spent on gaps
|
||||
# instead of on stroke.
|
||||
#
|
||||
# A d20 was the obvious alternative and was rejected: this system rolls k6, and
|
||||
# a 20-sided outline is a mess of short strokes at launcher size. A front-on
|
||||
# die with pips collides with `storage-box` (both read as "boxy thing with
|
||||
# marks"). Nothing else in the family is a tall pointed shape.
|
||||
#
|
||||
# The top edge is flat, not pointed. A symmetric almond — pointed at both ends
|
||||
# — with a round hole in the upper half is a map pin, which is exactly what the
|
||||
# first draft rendered as. The flat shoulder is where a real nib clips into the
|
||||
# holder, and it is what stops the map-pin read.
|
||||
#
|
||||
# Geometry: shoulder (420,312)-(604,312), waist bowing out to ~x=400/624 around
|
||||
# y=456, converging to the tip at (512,812) — ink 224x500, inside SAFE_BOX on
|
||||
# both axes. Vent circle r=40 at (512,470) clears the outline by ~61px; the
|
||||
# slit stops at y=700, leaving ~41px to the outline near the tip and 70px to
|
||||
# the vent above. Every gap is over the 36px budget. fill-rule="evenodd" keeps
|
||||
# both holes true holes — icon_foreground and icon_monochrome render on
|
||||
# transparency, where a painted hole would show as a blob and in the wrong
|
||||
# colour.
|
||||
_QUILL_NIB = """\
|
||||
<path fill="{{ACCENT}}" fill-rule="evenodd" stroke="none" d="\
|
||||
M 420 312 L 604 312 Q 626 470 596 570 L 512 812 L 428 570 \
|
||||
Q 398 470 420 312 Z \
|
||||
M 472 470 A 40 40 0 1 0 552 470 A 40 40 0 1 0 472 470 Z \
|
||||
M 512 700 L 492 580 L 532 580 Z"/>"""
|
||||
|
||||
|
||||
# A blacksmith's anvil: OctoForge is a GitHub client, and the forge is the
|
||||
# name. Filled rather than stroked, for the same reason as the nib — a stroked
|
||||
# anvil outline is a long thin horn plus a narrow waist, and at the family's
|
||||
# 72px weight the waist closes up solid at 48dp.
|
||||
#
|
||||
# The obvious alternatives were rejected: an octopus (the Octocat) is both
|
||||
# GitHub trade dress and a tangle of thin curves that blurs at launcher size,
|
||||
# and a hammer alone collides with nothing in the family but reads as a generic
|
||||
# tool rather than a forge. The anvil silhouette is unmistakable and shares no
|
||||
# shape language with the other nine glyphs.
|
||||
#
|
||||
# Geometry: the body is a face slab (x=336..768, y=316..420), a waist
|
||||
# (x=444..596, y=420..592) and a flared foot (x=304..716, y=592..708) — total
|
||||
# ink 512x392 including the horn, inside SAFE_BOX once the renderer scales it.
|
||||
#
|
||||
# The horn is what makes this an anvil rather than an I-beam, so it is a
|
||||
# separate wedge projecting left off the face, not a rounded corner on it: it
|
||||
# leaves the slab at full 104px depth (x=336) and tapers to a 40px blunt tip
|
||||
# at x=256, dropping the underside from y=420 to y=392 on the way. A sharp
|
||||
# point would disappear at 48dp; 40px is above MIN_NEGATIVE_SPACE so it
|
||||
# survives. The first two drafts folded the taper into the slab's left end and
|
||||
# both read as a bump.
|
||||
_ANVIL = """\
|
||||
<path fill="{{ACCENT}}" stroke="none" d="\
|
||||
M 768 316 L 768 420 L 596 420 \
|
||||
Q 592 512 592 592 L 716 592 L 716 708 L 304 708 L 304 592 L 428 592 \
|
||||
Q 428 512 424 420 L 336 420 \
|
||||
L 256 392 Q 248 376 256 360 L 336 316 Z"/>"""
|
||||
|
||||
# Three rising bars with a plotted point above the tallest -- a day-by-day log
|
||||
# that adds up to a trend, which is what a life tracker is. The bars are
|
||||
# strokes rather than filled rects so the glyph keeps one stroke weight
|
||||
# throughout; at a 168px pitch the 72px strokes leave 96px gaps, well above
|
||||
# MIN_NEGATIVE_SPACE. The marker sits on its own row clear of the bar caps,
|
||||
# and is hollow so it reads as a data point rather than a full stop.
|
||||
_TRACK_BARS = """\
|
||||
<path d="M 320 700 L 320 556"/>
|
||||
<path d="M 488 700 L 488 460"/>
|
||||
<path d="M 656 700 L 656 364"/>
|
||||
<circle cx="656" cy="252" r="40" fill="none"/>"""
|
||||
|
||||
|
||||
GLYPHS: Final[dict[str, Glyph]] = {
|
||||
glyph.name: glyph
|
||||
|
||||
@ -12,6 +12,7 @@ import datetime as dt
|
||||
from python_pkg.focus_policy.export import (
|
||||
ENFORCER_PACKAGE,
|
||||
policy_to_dict,
|
||||
policy_to_json,
|
||||
)
|
||||
from python_pkg.focus_policy.model import CurfewWindow, FocusPolicy, HomeLocation
|
||||
|
||||
@ -158,3 +159,97 @@ def test_private_dns_host_is_exported_for_pinning() -> None:
|
||||
# (PRIVATE_DNS_SET_ERROR_HOST_NOT_SERVING).
|
||||
assert payload["private_dns_host"] == ""
|
||||
assert payload["vpn_lockdown"] is True
|
||||
|
||||
|
||||
def test_always_blocked_is_a_subset_of_blockable() -> None:
|
||||
"""An always-blocked system app the sweep cannot see would silently no-op.
|
||||
|
||||
The runner filters FLAG_SYSTEM packages out of ``installedPackages``
|
||||
unless they are opted in, so the decision layer would never receive them.
|
||||
"""
|
||||
payload = policy_to_dict(_policy())
|
||||
|
||||
assert set(payload["always_blocked_packages"]) <= set(
|
||||
payload["blockable_system_packages"],
|
||||
)
|
||||
|
||||
|
||||
def test_always_blocked_never_contradicts_the_allowlist() -> None:
|
||||
"""Allowing a package wins over always-blocking it.
|
||||
|
||||
The asset must not state both at once; the subtraction keeps the two
|
||||
fields consistent no matter what config.sh says.
|
||||
"""
|
||||
payload = policy_to_dict(
|
||||
_policy(
|
||||
allowed_packages=frozenset(
|
||||
{"pl.mbank", "com.launcher", "com.android.chrome"},
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
assert "com.android.chrome" not in payload["always_blocked_packages"]
|
||||
assert "com.android.chrome" in payload["allowed_packages"]
|
||||
|
||||
|
||||
def test_a_prefix_allowance_also_wins_over_always_blocking() -> None:
|
||||
"""Allowance is no longer exact-only, so the check must not be either.
|
||||
|
||||
Subtracting just ``allowed_packages`` left a package allowed by prefix
|
||||
still emitted as always-blocked, so the asset stated both at once and the
|
||||
runner's behaviour depended on which check it applied first.
|
||||
"""
|
||||
payload = policy_to_dict(
|
||||
_policy(
|
||||
allowed_packages=frozenset({"pl.mbank", "com.launcher"}),
|
||||
allowed_prefixes=("com.android.chrome",),
|
||||
),
|
||||
)
|
||||
|
||||
assert "com.android.chrome" not in payload["always_blocked_packages"]
|
||||
|
||||
|
||||
def test_the_real_distraction_apps_stay_always_blocked() -> None:
|
||||
"""The filter must not quietly un-block what the app exists to block."""
|
||||
payload = policy_to_dict(_policy())
|
||||
|
||||
assert "com.google.android.youtube" in payload["always_blocked_packages"]
|
||||
assert "com.android.chrome" in payload["always_blocked_packages"]
|
||||
|
||||
|
||||
def test_lists_are_sorted_for_stable_diffs() -> None:
|
||||
"""Sorted output keeps a committed asset's diff meaningful."""
|
||||
payload = policy_to_dict(_policy())
|
||||
|
||||
for key in (
|
||||
"allowed_packages",
|
||||
"night_allowed_packages",
|
||||
"never_disable_prefixes",
|
||||
"workout_unblock_domains",
|
||||
"browser_packages",
|
||||
):
|
||||
assert payload[key] == sorted(payload[key])
|
||||
|
||||
|
||||
def test_curfew_is_rendered_as_wall_clock_strings() -> None:
|
||||
"""Kotlin parses `HH:MM`, not an ISO time."""
|
||||
assert policy_to_dict(_policy())["curfew"] == {"start": "23:00", "end": "05:00"}
|
||||
|
||||
|
||||
def test_absent_curfew_renders_as_null() -> None:
|
||||
"""A policy with no curfew must not fabricate one."""
|
||||
assert policy_to_dict(_policy(curfew=None))["curfew"] is None
|
||||
|
||||
|
||||
def test_redact_home_blanks_coordinates_but_keeps_geometry() -> None:
|
||||
"""A committed asset discloses the radius, never the location."""
|
||||
payload = policy_to_json(_policy(), redact_home=True)
|
||||
|
||||
assert '"latitude": null' in payload
|
||||
assert '"longitude": null' in payload
|
||||
assert '"radius_m": 150.0' in payload
|
||||
|
||||
|
||||
def test_coordinates_survive_when_not_redacted() -> None:
|
||||
"""The provisioning path still needs the real values."""
|
||||
assert '"latitude": 52.2297' in policy_to_json(_policy())
|
||||
|
||||
@ -1,135 +0,0 @@
|
||||
"""Cross-checks between the always-blocked set and the allowlist."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as dt
|
||||
|
||||
from python_pkg.focus_policy.export import (
|
||||
policy_to_dict,
|
||||
policy_to_json,
|
||||
)
|
||||
from python_pkg.focus_policy.model import CurfewWindow, FocusPolicy, HomeLocation
|
||||
|
||||
_DEFAULT_CURFEW = CurfewWindow(start=dt.time(23, 0), end=dt.time(5, 0))
|
||||
|
||||
|
||||
def _policy(
|
||||
*,
|
||||
# The launcher must be allowed or the model rejects the policy outright.
|
||||
allowed_packages: frozenset[str] = frozenset({"pl.mbank", "com.launcher"}),
|
||||
night_allowed_packages: frozenset[str] = frozenset({"pl.mbank", "com.launcher"}),
|
||||
curfew: CurfewWindow | None = _DEFAULT_CURFEW,
|
||||
never_disable_prefixes: tuple[str, ...] = ("com.android.",),
|
||||
allowed_prefixes: tuple[str, ...] = (),
|
||||
) -> FocusPolicy:
|
||||
"""Build a policy with the enforcer deliberately absent from both lists."""
|
||||
return FocusPolicy(
|
||||
home=HomeLocation(
|
||||
latitude=52.2297,
|
||||
longitude=21.0122,
|
||||
radius_m=150.0,
|
||||
hysteresis_m=30.0,
|
||||
),
|
||||
curfew=curfew,
|
||||
launcher_package="com.launcher",
|
||||
allowed_packages=allowed_packages,
|
||||
allowed_prefixes=allowed_prefixes,
|
||||
night_allowed_packages=night_allowed_packages,
|
||||
never_disable_prefixes=never_disable_prefixes,
|
||||
workout_unblock_domains=frozenset({"youtube.com"}),
|
||||
browser_packages=frozenset({"org.mozilla.firefox"}),
|
||||
)
|
||||
|
||||
|
||||
def test_always_blocked_is_a_subset_of_blockable() -> None:
|
||||
"""An always-blocked system app the sweep cannot see would silently no-op.
|
||||
|
||||
The runner filters FLAG_SYSTEM packages out of ``installedPackages``
|
||||
unless they are opted in, so the decision layer would never receive them.
|
||||
"""
|
||||
payload = policy_to_dict(_policy())
|
||||
|
||||
assert set(payload["always_blocked_packages"]) <= set(
|
||||
payload["blockable_system_packages"],
|
||||
)
|
||||
|
||||
|
||||
def test_always_blocked_never_contradicts_the_allowlist() -> None:
|
||||
"""Allowing a package wins over always-blocking it.
|
||||
|
||||
The asset must not state both at once; the subtraction keeps the two
|
||||
fields consistent no matter what config.sh says.
|
||||
"""
|
||||
payload = policy_to_dict(
|
||||
_policy(
|
||||
allowed_packages=frozenset(
|
||||
{"pl.mbank", "com.launcher", "com.android.chrome"},
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
assert "com.android.chrome" not in payload["always_blocked_packages"]
|
||||
assert "com.android.chrome" in payload["allowed_packages"]
|
||||
|
||||
|
||||
def test_a_prefix_allowance_also_wins_over_always_blocking() -> None:
|
||||
"""Allowance is no longer exact-only, so the check must not be either.
|
||||
|
||||
Subtracting just ``allowed_packages`` left a package allowed by prefix
|
||||
still emitted as always-blocked, so the asset stated both at once and the
|
||||
runner's behaviour depended on which check it applied first.
|
||||
"""
|
||||
payload = policy_to_dict(
|
||||
_policy(
|
||||
allowed_packages=frozenset({"pl.mbank", "com.launcher"}),
|
||||
allowed_prefixes=("com.android.chrome",),
|
||||
),
|
||||
)
|
||||
|
||||
assert "com.android.chrome" not in payload["always_blocked_packages"]
|
||||
|
||||
|
||||
def test_the_real_distraction_apps_stay_always_blocked() -> None:
|
||||
"""The filter must not quietly un-block what the app exists to block."""
|
||||
payload = policy_to_dict(_policy())
|
||||
|
||||
assert "com.google.android.youtube" in payload["always_blocked_packages"]
|
||||
assert "com.android.chrome" in payload["always_blocked_packages"]
|
||||
|
||||
|
||||
def test_lists_are_sorted_for_stable_diffs() -> None:
|
||||
"""Sorted output keeps a committed asset's diff meaningful."""
|
||||
payload = policy_to_dict(_policy())
|
||||
|
||||
for key in (
|
||||
"allowed_packages",
|
||||
"night_allowed_packages",
|
||||
"never_disable_prefixes",
|
||||
"workout_unblock_domains",
|
||||
"browser_packages",
|
||||
):
|
||||
assert payload[key] == sorted(payload[key])
|
||||
|
||||
|
||||
def test_curfew_is_rendered_as_wall_clock_strings() -> None:
|
||||
"""Kotlin parses `HH:MM`, not an ISO time."""
|
||||
assert policy_to_dict(_policy())["curfew"] == {"start": "23:00", "end": "05:00"}
|
||||
|
||||
|
||||
def test_absent_curfew_renders_as_null() -> None:
|
||||
"""A policy with no curfew must not fabricate one."""
|
||||
assert policy_to_dict(_policy(curfew=None))["curfew"] is None
|
||||
|
||||
|
||||
def test_redact_home_blanks_coordinates_but_keeps_geometry() -> None:
|
||||
"""A committed asset discloses the radius, never the location."""
|
||||
payload = policy_to_json(_policy(), redact_home=True)
|
||||
|
||||
assert '"latitude": null' in payload
|
||||
assert '"longitude": null' in payload
|
||||
assert '"radius_m": 150.0' in payload
|
||||
|
||||
|
||||
def test_coordinates_survive_when_not_redacted() -> None:
|
||||
"""The provisioning path still needs the real values."""
|
||||
assert '"latitude": 52.2297' in policy_to_json(_policy())
|
||||
@ -146,3 +146,124 @@ class TestCurfewWindow:
|
||||
"""A non-wrapping window is a plain half-open interval."""
|
||||
window = CurfewWindow(start=time(9, 0), end=time(17, 0))
|
||||
assert window.contains(moment) is expected
|
||||
|
||||
|
||||
class TestFocusPolicy:
|
||||
"""Allow/deny decisions and the invariants that keep the phone usable."""
|
||||
|
||||
def test_rejects_launcher_outside_allowlist(self) -> None:
|
||||
"""A policy that blocks its own launcher would leave no home screen."""
|
||||
with pytest.raises(PolicyError, match="no home screen"):
|
||||
_policy(launcher_package="com.missing")
|
||||
|
||||
def test_accepts_launcher_inside_allowlist(self) -> None:
|
||||
"""The guard permits a launcher that is actually allowed."""
|
||||
assert _policy(launcher_package="com.launcher").launcher_package
|
||||
|
||||
def test_rejects_night_packages_absent_from_day_list(self) -> None:
|
||||
"""A night allowance for a day-blocked package is contradictory."""
|
||||
with pytest.raises(PolicyError, match="subset"):
|
||||
_policy(night_allowed_packages=frozenset({"com.unknown"}))
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("package", "expected"),
|
||||
[
|
||||
("com.android.settings", True),
|
||||
("com.android.providers", True),
|
||||
("com.android.providers.telephony", True),
|
||||
("com.android.providersomething", False),
|
||||
("com.good", False),
|
||||
],
|
||||
)
|
||||
def test_protection_matches_whole_labels_only(
|
||||
self,
|
||||
package: str,
|
||||
*,
|
||||
expected: bool,
|
||||
) -> None:
|
||||
"""Prefix protection covers subpackages but not lookalike names.
|
||||
|
||||
``com.android.providers.telephony`` must be protected; the unrelated
|
||||
``com.android.providersomething`` must not be swept in by a bare
|
||||
string prefix test.
|
||||
"""
|
||||
assert _policy().is_protected(package) is expected
|
||||
|
||||
def test_protected_packages_are_allowed_even_during_curfew(self) -> None:
|
||||
"""Core system packages survive the strictest state."""
|
||||
policy = _policy()
|
||||
assert policy.is_allowed("com.android.settings", during_curfew=True)
|
||||
|
||||
def test_curfew_narrows_the_allowlist(self) -> None:
|
||||
"""Day-allowed apps can still be blocked at night."""
|
||||
policy = _policy()
|
||||
assert policy.is_allowed("com.good")
|
||||
assert not policy.is_allowed("com.good", during_curfew=True)
|
||||
assert policy.is_allowed("pl.mbank", during_curfew=True)
|
||||
|
||||
def test_unknown_package_is_blocked(self) -> None:
|
||||
"""Anything not explicitly allowed is denied."""
|
||||
assert not _policy().is_allowed("com.evil")
|
||||
|
||||
def test_allowed_prefix_covers_a_family_of_packages(self) -> None:
|
||||
"""Tachiyomi ships every source as its own apk.
|
||||
|
||||
An exact list goes stale the moment a new extension is installed, which
|
||||
looks exactly like a bug from the phone.
|
||||
"""
|
||||
policy = _policy(allowed_prefixes=("eu.kanade.tachiyomi",))
|
||||
assert policy.is_allowed("eu.kanade.tachiyomi")
|
||||
assert policy.is_allowed("eu.kanade.tachiyomi.sy")
|
||||
assert policy.is_allowed("eu.kanade.tachiyomi.extension.all.mangadex")
|
||||
|
||||
def test_allowed_prefix_matches_whole_labels_only(self) -> None:
|
||||
"""A bare string prefix would allow an unrelated package."""
|
||||
policy = _policy(allowed_prefixes=("eu.kanade.tachiyomi",))
|
||||
assert not policy.is_allowed("eu.kanade.tachiyomisomething")
|
||||
|
||||
def test_a_day_only_prefix_is_blocked_during_curfew(self) -> None:
|
||||
"""The night list narrows the prefixes too, not just the packages."""
|
||||
policy = _policy(allowed_prefixes=("eu.kanade.tachiyomi",))
|
||||
assert policy.is_allowed("eu.kanade.tachiyomi.sy")
|
||||
assert not policy.is_allowed("eu.kanade.tachiyomi.sy", during_curfew=True)
|
||||
|
||||
def test_a_night_prefix_survives_the_curfew(self) -> None:
|
||||
"""Manga is deliberately available at night (chosen 2026-08-14)."""
|
||||
policy = _policy(
|
||||
allowed_prefixes=("eu.kanade.tachiyomi",),
|
||||
night_allowed_prefixes=("eu.kanade.tachiyomi",),
|
||||
)
|
||||
assert policy.is_allowed("eu.kanade.tachiyomi.sy", during_curfew=True)
|
||||
assert policy.is_allowed(
|
||||
"eu.kanade.tachiyomi.extension.all.mangadex",
|
||||
during_curfew=True,
|
||||
)
|
||||
|
||||
def test_night_prefixes_must_be_a_subset_of_day_prefixes(self) -> None:
|
||||
"""The curfew tightens the day policy; it must never widen it."""
|
||||
with pytest.raises(PolicyError, match="night_allowed_prefixes"):
|
||||
_policy(night_allowed_prefixes=("eu.kanade.tachiyomi",))
|
||||
|
||||
def test_is_curfew_active_without_window_is_false(self) -> None:
|
||||
"""A policy with no curfew is never in curfew."""
|
||||
assert not _policy().is_curfew_active(time(23, 30))
|
||||
|
||||
def test_is_curfew_active_with_window(self) -> None:
|
||||
"""A configured window drives the curfew state."""
|
||||
policy = _policy(curfew=CurfewWindow(start=time(23, 0), end=time(5, 0)))
|
||||
assert policy.is_curfew_active(time(23, 30))
|
||||
assert not policy.is_curfew_active(time(12, 0))
|
||||
|
||||
def test_packages_to_block_ignores_uninstalled(self) -> None:
|
||||
"""Only packages present on the device can be blocked."""
|
||||
policy = _policy()
|
||||
installed = frozenset({"com.good", "com.evil", "com.android.settings"})
|
||||
assert policy.packages_to_block(installed) == frozenset({"com.evil"})
|
||||
|
||||
def test_packages_to_block_during_curfew(self) -> None:
|
||||
"""The curfew list is applied when the curfew flag is set."""
|
||||
policy = _policy()
|
||||
installed = frozenset({"com.good", "pl.mbank"})
|
||||
assert policy.packages_to_block(installed, during_curfew=True) == frozenset(
|
||||
{"com.good"},
|
||||
)
|
||||
|
||||
@ -1,168 +0,0 @@
|
||||
"""Tests for the FocusPolicy aggregate."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import time
|
||||
|
||||
import pytest
|
||||
|
||||
from python_pkg.focus_policy.model import (
|
||||
CurfewWindow,
|
||||
FocusPolicy,
|
||||
HomeLocation,
|
||||
PolicyError,
|
||||
)
|
||||
|
||||
HOME = HomeLocation(latitude=52.2297, longitude=21.0122)
|
||||
METRES_PER_DEGREE_LAT = 111_320.0
|
||||
|
||||
|
||||
def _policy(
|
||||
*,
|
||||
allowed_packages: frozenset[str] | None = None,
|
||||
night_allowed_packages: frozenset[str] | None = None,
|
||||
curfew: CurfewWindow | None = None,
|
||||
launcher_package: str | None = None,
|
||||
allowed_prefixes: tuple[str, ...] = (),
|
||||
night_allowed_prefixes: tuple[str, ...] = (),
|
||||
) -> FocusPolicy:
|
||||
"""Build a small policy, overriding individual fields per test."""
|
||||
return FocusPolicy(
|
||||
home=HOME,
|
||||
allowed_packages=(
|
||||
frozenset({"com.good", "pl.mbank", "com.launcher"})
|
||||
if allowed_packages is None
|
||||
else allowed_packages
|
||||
),
|
||||
night_allowed_packages=(
|
||||
frozenset({"pl.mbank"})
|
||||
if night_allowed_packages is None
|
||||
else night_allowed_packages
|
||||
),
|
||||
never_disable_prefixes=("com.android.providers", "com.android.settings"),
|
||||
curfew=curfew,
|
||||
launcher_package=launcher_package,
|
||||
allowed_prefixes=allowed_prefixes,
|
||||
night_allowed_prefixes=night_allowed_prefixes,
|
||||
)
|
||||
|
||||
|
||||
class TestFocusPolicy:
|
||||
"""Allow/deny decisions and the invariants that keep the phone usable."""
|
||||
|
||||
def test_rejects_launcher_outside_allowlist(self) -> None:
|
||||
"""A policy that blocks its own launcher would leave no home screen."""
|
||||
with pytest.raises(PolicyError, match="no home screen"):
|
||||
_policy(launcher_package="com.missing")
|
||||
|
||||
def test_accepts_launcher_inside_allowlist(self) -> None:
|
||||
"""The guard permits a launcher that is actually allowed."""
|
||||
assert _policy(launcher_package="com.launcher").launcher_package
|
||||
|
||||
def test_rejects_night_packages_absent_from_day_list(self) -> None:
|
||||
"""A night allowance for a day-blocked package is contradictory."""
|
||||
with pytest.raises(PolicyError, match="subset"):
|
||||
_policy(night_allowed_packages=frozenset({"com.unknown"}))
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("package", "expected"),
|
||||
[
|
||||
("com.android.settings", True),
|
||||
("com.android.providers", True),
|
||||
("com.android.providers.telephony", True),
|
||||
("com.android.providersomething", False),
|
||||
("com.good", False),
|
||||
],
|
||||
)
|
||||
def test_protection_matches_whole_labels_only(
|
||||
self,
|
||||
package: str,
|
||||
*,
|
||||
expected: bool,
|
||||
) -> None:
|
||||
"""Prefix protection covers subpackages but not lookalike names.
|
||||
|
||||
``com.android.providers.telephony`` must be protected; the unrelated
|
||||
``com.android.providersomething`` must not be swept in by a bare
|
||||
string prefix test.
|
||||
"""
|
||||
assert _policy().is_protected(package) is expected
|
||||
|
||||
def test_protected_packages_are_allowed_even_during_curfew(self) -> None:
|
||||
"""Core system packages survive the strictest state."""
|
||||
policy = _policy()
|
||||
assert policy.is_allowed("com.android.settings", during_curfew=True)
|
||||
|
||||
def test_curfew_narrows_the_allowlist(self) -> None:
|
||||
"""Day-allowed apps can still be blocked at night."""
|
||||
policy = _policy()
|
||||
assert policy.is_allowed("com.good")
|
||||
assert not policy.is_allowed("com.good", during_curfew=True)
|
||||
assert policy.is_allowed("pl.mbank", during_curfew=True)
|
||||
|
||||
def test_unknown_package_is_blocked(self) -> None:
|
||||
"""Anything not explicitly allowed is denied."""
|
||||
assert not _policy().is_allowed("com.evil")
|
||||
|
||||
def test_allowed_prefix_covers_a_family_of_packages(self) -> None:
|
||||
"""Tachiyomi ships every source as its own apk.
|
||||
|
||||
An exact list goes stale the moment a new extension is installed, which
|
||||
looks exactly like a bug from the phone.
|
||||
"""
|
||||
policy = _policy(allowed_prefixes=("eu.kanade.tachiyomi",))
|
||||
assert policy.is_allowed("eu.kanade.tachiyomi")
|
||||
assert policy.is_allowed("eu.kanade.tachiyomi.sy")
|
||||
assert policy.is_allowed("eu.kanade.tachiyomi.extension.all.mangadex")
|
||||
|
||||
def test_allowed_prefix_matches_whole_labels_only(self) -> None:
|
||||
"""A bare string prefix would allow an unrelated package."""
|
||||
policy = _policy(allowed_prefixes=("eu.kanade.tachiyomi",))
|
||||
assert not policy.is_allowed("eu.kanade.tachiyomisomething")
|
||||
|
||||
def test_a_day_only_prefix_is_blocked_during_curfew(self) -> None:
|
||||
"""The night list narrows the prefixes too, not just the packages."""
|
||||
policy = _policy(allowed_prefixes=("eu.kanade.tachiyomi",))
|
||||
assert policy.is_allowed("eu.kanade.tachiyomi.sy")
|
||||
assert not policy.is_allowed("eu.kanade.tachiyomi.sy", during_curfew=True)
|
||||
|
||||
def test_a_night_prefix_survives_the_curfew(self) -> None:
|
||||
"""Manga is deliberately available at night (chosen 2026-08-14)."""
|
||||
policy = _policy(
|
||||
allowed_prefixes=("eu.kanade.tachiyomi",),
|
||||
night_allowed_prefixes=("eu.kanade.tachiyomi",),
|
||||
)
|
||||
assert policy.is_allowed("eu.kanade.tachiyomi.sy", during_curfew=True)
|
||||
assert policy.is_allowed(
|
||||
"eu.kanade.tachiyomi.extension.all.mangadex",
|
||||
during_curfew=True,
|
||||
)
|
||||
|
||||
def test_night_prefixes_must_be_a_subset_of_day_prefixes(self) -> None:
|
||||
"""The curfew tightens the day policy; it must never widen it."""
|
||||
with pytest.raises(PolicyError, match="night_allowed_prefixes"):
|
||||
_policy(night_allowed_prefixes=("eu.kanade.tachiyomi",))
|
||||
|
||||
def test_is_curfew_active_without_window_is_false(self) -> None:
|
||||
"""A policy with no curfew is never in curfew."""
|
||||
assert not _policy().is_curfew_active(time(23, 30))
|
||||
|
||||
def test_is_curfew_active_with_window(self) -> None:
|
||||
"""A configured window drives the curfew state."""
|
||||
policy = _policy(curfew=CurfewWindow(start=time(23, 0), end=time(5, 0)))
|
||||
assert policy.is_curfew_active(time(23, 30))
|
||||
assert not policy.is_curfew_active(time(12, 0))
|
||||
|
||||
def test_packages_to_block_ignores_uninstalled(self) -> None:
|
||||
"""Only packages present on the device can be blocked."""
|
||||
policy = _policy()
|
||||
installed = frozenset({"com.good", "com.evil", "com.android.settings"})
|
||||
assert policy.packages_to_block(installed) == frozenset({"com.evil"})
|
||||
|
||||
def test_packages_to_block_during_curfew(self) -> None:
|
||||
"""The curfew list is applied when the curfew flag is set."""
|
||||
policy = _policy()
|
||||
installed = frozenset({"com.good", "pl.mbank"})
|
||||
assert policy.packages_to_block(installed, during_curfew=True) == frozenset(
|
||||
{"com.good"},
|
||||
)
|
||||
@ -2,6 +2,7 @@
|
||||
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
from unittest.mock import patch
|
||||
|
||||
from PIL import Image
|
||||
import pytest
|
||||
@ -10,7 +11,9 @@ from python_pkg.random_jpg.generate_jpeg import (
|
||||
MAX_IMAGE_SIZE,
|
||||
ImageConfig,
|
||||
_create_random_image,
|
||||
_save_image,
|
||||
generate_bloated_jpeg,
|
||||
main,
|
||||
)
|
||||
|
||||
|
||||
@ -133,3 +136,116 @@ class TestCreateRandomImage:
|
||||
for x in range(20):
|
||||
for y in range(20):
|
||||
assert pixels[x, y] == (255, 0, 0)
|
||||
|
||||
|
||||
class TestSaveImage:
|
||||
"""Tests for _save_image function."""
|
||||
|
||||
def test_creates_output_folder(self) -> None:
|
||||
"""Test that output folder is created if it doesn't exist."""
|
||||
with tempfile.TemporaryDirectory() as tmp_dir:
|
||||
new_folder = Path(tmp_dir) / "new_subfolder"
|
||||
image = Image.new("RGB", (10, 10))
|
||||
config = ImageConfig(
|
||||
size=10,
|
||||
color_list=["#FF0000"],
|
||||
block_size=10,
|
||||
output_path="image.jpeg",
|
||||
quality=90,
|
||||
)
|
||||
|
||||
_save_image(image, config, 1, str(new_folder))
|
||||
|
||||
assert new_folder.exists()
|
||||
|
||||
def test_saves_with_correct_quality(self) -> None:
|
||||
"""Test image is saved with specified quality."""
|
||||
with tempfile.TemporaryDirectory() as tmp_dir:
|
||||
image = Image.new("RGB", (10, 10), color=(255, 0, 0))
|
||||
config = ImageConfig(
|
||||
size=10,
|
||||
color_list=["#FF0000"],
|
||||
block_size=10,
|
||||
output_path="image.jpeg",
|
||||
quality=50,
|
||||
)
|
||||
|
||||
result_path = _save_image(image, config, 1, tmp_dir)
|
||||
|
||||
assert Path(result_path).exists()
|
||||
|
||||
|
||||
class TestMain:
|
||||
"""Tests for main CLI function."""
|
||||
|
||||
def test_main_generates_image_with_defaults(self) -> None:
|
||||
"""Test main generates image with default arguments."""
|
||||
with (
|
||||
tempfile.TemporaryDirectory() as tmp_dir,
|
||||
patch("sys.argv", ["generate_jpeg.py"]),
|
||||
patch(
|
||||
"python_pkg.random_jpg.generate_jpeg.generate_bloated_jpeg"
|
||||
) as mock_gen,
|
||||
):
|
||||
mock_gen.return_value = f"{tmp_dir}/test.jpeg"
|
||||
main()
|
||||
|
||||
mock_gen.assert_called_once()
|
||||
call_args = mock_gen.call_args
|
||||
config = call_args[0][0]
|
||||
assert config.size == 1000
|
||||
assert config.block_size == 4
|
||||
assert config.quality == 100
|
||||
|
||||
def test_main_respects_num_images_argument(self) -> None:
|
||||
"""Test main generates multiple images when specified."""
|
||||
with (
|
||||
tempfile.TemporaryDirectory() as tmp_dir,
|
||||
patch("sys.argv", ["generate_jpeg.py", "-n", "3"]),
|
||||
patch(
|
||||
"python_pkg.random_jpg.generate_jpeg.generate_bloated_jpeg"
|
||||
) as mock_gen,
|
||||
):
|
||||
mock_gen.return_value = f"{tmp_dir}/test.jpeg"
|
||||
main()
|
||||
|
||||
assert mock_gen.call_count == 3
|
||||
|
||||
def test_main_uses_custom_size(self) -> None:
|
||||
"""Test main respects custom size argument."""
|
||||
with (
|
||||
tempfile.TemporaryDirectory() as tmp_dir,
|
||||
patch("sys.argv", ["generate_jpeg.py", "-s", "500", "-b", "5"]),
|
||||
patch(
|
||||
"python_pkg.random_jpg.generate_jpeg.generate_bloated_jpeg"
|
||||
) as mock_gen,
|
||||
):
|
||||
mock_gen.return_value = f"{tmp_dir}/test.jpeg"
|
||||
main()
|
||||
|
||||
config = mock_gen.call_args[0][0]
|
||||
assert config.size == 500
|
||||
assert config.block_size == 5
|
||||
|
||||
def test_main_uses_custom_colors(self) -> None:
|
||||
"""Test main respects custom color list."""
|
||||
with (
|
||||
tempfile.TemporaryDirectory() as tmp_dir,
|
||||
patch("sys.argv", ["generate_jpeg.py", "-c", "#AABBCC", "#112233"]),
|
||||
patch(
|
||||
"python_pkg.random_jpg.generate_jpeg.generate_bloated_jpeg"
|
||||
) as mock_gen,
|
||||
):
|
||||
mock_gen.return_value = f"{tmp_dir}/test.jpeg"
|
||||
main()
|
||||
|
||||
config = mock_gen.call_args[0][0]
|
||||
assert config.color_list == ["#AABBCC", "#112233"]
|
||||
|
||||
|
||||
class TestConstants:
|
||||
"""Tests for module constants."""
|
||||
|
||||
def test_max_image_size(self) -> None:
|
||||
"""Test MAX_IMAGE_SIZE constant value."""
|
||||
assert MAX_IMAGE_SIZE == 1000
|
||||
|
||||
@ -1,127 +0,0 @@
|
||||
"""Tests for saving generated images and the CLI entry point."""
|
||||
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
from unittest.mock import patch
|
||||
|
||||
from PIL import Image
|
||||
|
||||
from python_pkg.random_jpg.generate_jpeg import (
|
||||
MAX_IMAGE_SIZE,
|
||||
ImageConfig,
|
||||
_save_image,
|
||||
main,
|
||||
)
|
||||
|
||||
|
||||
class TestSaveImage:
|
||||
"""Tests for _save_image function."""
|
||||
|
||||
def test_creates_output_folder(self) -> None:
|
||||
"""Test that output folder is created if it doesn't exist."""
|
||||
with tempfile.TemporaryDirectory() as tmp_dir:
|
||||
new_folder = Path(tmp_dir) / "new_subfolder"
|
||||
image = Image.new("RGB", (10, 10))
|
||||
config = ImageConfig(
|
||||
size=10,
|
||||
color_list=["#FF0000"],
|
||||
block_size=10,
|
||||
output_path="image.jpeg",
|
||||
quality=90,
|
||||
)
|
||||
|
||||
_save_image(image, config, 1, str(new_folder))
|
||||
|
||||
assert new_folder.exists()
|
||||
|
||||
def test_saves_with_correct_quality(self) -> None:
|
||||
"""Test image is saved with specified quality."""
|
||||
with tempfile.TemporaryDirectory() as tmp_dir:
|
||||
image = Image.new("RGB", (10, 10), color=(255, 0, 0))
|
||||
config = ImageConfig(
|
||||
size=10,
|
||||
color_list=["#FF0000"],
|
||||
block_size=10,
|
||||
output_path="image.jpeg",
|
||||
quality=50,
|
||||
)
|
||||
|
||||
result_path = _save_image(image, config, 1, tmp_dir)
|
||||
|
||||
assert Path(result_path).exists()
|
||||
|
||||
|
||||
class TestMain:
|
||||
"""Tests for main CLI function."""
|
||||
|
||||
def test_main_generates_image_with_defaults(self) -> None:
|
||||
"""Test main generates image with default arguments."""
|
||||
with (
|
||||
tempfile.TemporaryDirectory() as tmp_dir,
|
||||
patch("sys.argv", ["generate_jpeg.py"]),
|
||||
patch(
|
||||
"python_pkg.random_jpg.generate_jpeg.generate_bloated_jpeg"
|
||||
) as mock_gen,
|
||||
):
|
||||
mock_gen.return_value = f"{tmp_dir}/test.jpeg"
|
||||
main()
|
||||
|
||||
mock_gen.assert_called_once()
|
||||
call_args = mock_gen.call_args
|
||||
config = call_args[0][0]
|
||||
assert config.size == 1000
|
||||
assert config.block_size == 4
|
||||
assert config.quality == 100
|
||||
|
||||
def test_main_respects_num_images_argument(self) -> None:
|
||||
"""Test main generates multiple images when specified."""
|
||||
with (
|
||||
tempfile.TemporaryDirectory() as tmp_dir,
|
||||
patch("sys.argv", ["generate_jpeg.py", "-n", "3"]),
|
||||
patch(
|
||||
"python_pkg.random_jpg.generate_jpeg.generate_bloated_jpeg"
|
||||
) as mock_gen,
|
||||
):
|
||||
mock_gen.return_value = f"{tmp_dir}/test.jpeg"
|
||||
main()
|
||||
|
||||
assert mock_gen.call_count == 3
|
||||
|
||||
def test_main_uses_custom_size(self) -> None:
|
||||
"""Test main respects custom size argument."""
|
||||
with (
|
||||
tempfile.TemporaryDirectory() as tmp_dir,
|
||||
patch("sys.argv", ["generate_jpeg.py", "-s", "500", "-b", "5"]),
|
||||
patch(
|
||||
"python_pkg.random_jpg.generate_jpeg.generate_bloated_jpeg"
|
||||
) as mock_gen,
|
||||
):
|
||||
mock_gen.return_value = f"{tmp_dir}/test.jpeg"
|
||||
main()
|
||||
|
||||
config = mock_gen.call_args[0][0]
|
||||
assert config.size == 500
|
||||
assert config.block_size == 5
|
||||
|
||||
def test_main_uses_custom_colors(self) -> None:
|
||||
"""Test main respects custom color list."""
|
||||
with (
|
||||
tempfile.TemporaryDirectory() as tmp_dir,
|
||||
patch("sys.argv", ["generate_jpeg.py", "-c", "#AABBCC", "#112233"]),
|
||||
patch(
|
||||
"python_pkg.random_jpg.generate_jpeg.generate_bloated_jpeg"
|
||||
) as mock_gen,
|
||||
):
|
||||
mock_gen.return_value = f"{tmp_dir}/test.jpeg"
|
||||
main()
|
||||
|
||||
config = mock_gen.call_args[0][0]
|
||||
assert config.color_list == ["#AABBCC", "#112233"]
|
||||
|
||||
|
||||
class TestConstants:
|
||||
"""Tests for module constants."""
|
||||
|
||||
def test_max_image_size(self) -> None:
|
||||
"""Test MAX_IMAGE_SIZE constant value."""
|
||||
assert MAX_IMAGE_SIZE == 1000
|
||||
@ -4,13 +4,14 @@ import json
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import pytest
|
||||
|
||||
from python_pkg.token_audit import parse
|
||||
from python_pkg.token_audit.model import ToolCall, Turn
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def _assistant(
|
||||
usage: dict[str, int] | None = None,
|
||||
@ -206,3 +207,65 @@ def test_usage_keeps_only_integer_fields(tmp_path: Path) -> None:
|
||||
def test_sidechain_flag_is_preserved(tmp_path: Path) -> None:
|
||||
path = _write(tmp_path, [_assistant(usage={"output_tokens": 1}, sidechain=True)])
|
||||
assert parse.load_session(path).turns[0].is_sidechain
|
||||
|
||||
|
||||
def test_iter_events_preserves_order(tmp_path: Path) -> None:
|
||||
records = [
|
||||
_assistant(
|
||||
content=[
|
||||
{
|
||||
"type": "tool_use",
|
||||
"id": "a",
|
||||
"name": "Read",
|
||||
"input": {"file_path": "/i.png"},
|
||||
},
|
||||
],
|
||||
),
|
||||
{
|
||||
"message": {
|
||||
"content": [
|
||||
{"type": "tool_result", "tool_use_id": "a", "content": "xxxx"}
|
||||
]
|
||||
}
|
||||
},
|
||||
_assistant(usage={"output_tokens": 1}),
|
||||
]
|
||||
kinds = [k for k, _ in parse.iter_events(_write(tmp_path, records))]
|
||||
assert kinds == ["tool", "turn"]
|
||||
|
||||
|
||||
def test_events_carry_expected_types(tmp_path: Path) -> None:
|
||||
records = [
|
||||
_assistant(
|
||||
content=[
|
||||
{"type": "tool_use", "id": "a", "name": "Read", "input": {}},
|
||||
],
|
||||
),
|
||||
{"message": {"content": [{"type": "tool_result", "tool_use_id": "a"}]}},
|
||||
_assistant(usage={"output_tokens": 1}),
|
||||
]
|
||||
events = dict(parse.iter_events(_write(tmp_path, records)))
|
||||
assert isinstance(events["tool"], ToolCall)
|
||||
assert isinstance(events["turn"], Turn)
|
||||
|
||||
|
||||
def test_find_transcripts_filters_by_window(tmp_path: Path) -> None:
|
||||
project = tmp_path / "proj"
|
||||
project.mkdir()
|
||||
old = project / "old.jsonl"
|
||||
new = project / "new.jsonl"
|
||||
old.write_text("{}", encoding="utf-8")
|
||||
new.write_text("{}", encoding="utf-8")
|
||||
import os
|
||||
|
||||
os.utime(old, (1000, 1000))
|
||||
os.utime(new, (50_000, 50_000))
|
||||
|
||||
assert parse.find_transcripts(tmp_path, since=10_000) == [new]
|
||||
assert parse.find_transcripts(tmp_path, since=0, until=2000) == [old]
|
||||
assert len(parse.find_transcripts(tmp_path, since=0)) == 2
|
||||
|
||||
|
||||
@pytest.mark.parametrize("payload", [None, "abcdefgh"])
|
||||
def test_result_tokens_handles_missing_content(payload: str | None) -> None:
|
||||
assert parse._result_tokens({"content": payload}) >= 0
|
||||
|
||||
@ -1,106 +0,0 @@
|
||||
"""Tests for token_audit event iteration and transcript discovery."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import pytest
|
||||
|
||||
from python_pkg.token_audit import parse
|
||||
from python_pkg.token_audit.model import ToolCall, Turn
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def _assistant(
|
||||
usage: dict[str, int] | None = None,
|
||||
content: list[dict[str, object]] | None = None,
|
||||
cwd: str = "/home/kuhy/demo",
|
||||
*,
|
||||
sidechain: bool = False,
|
||||
) -> dict[str, object]:
|
||||
message: dict[str, object] = {"model": "claude-opus-5"}
|
||||
if usage is not None:
|
||||
message["usage"] = usage
|
||||
if content is not None:
|
||||
message["content"] = content
|
||||
return {
|
||||
"type": "assistant",
|
||||
"cwd": cwd,
|
||||
"isSidechain": sidechain,
|
||||
"message": message,
|
||||
}
|
||||
|
||||
|
||||
def _write(tmp_path: Path, records: list[object], name: str = "sess.jsonl") -> Path:
|
||||
path = tmp_path / name
|
||||
path.write_text(
|
||||
"\n".join(json.dumps(r) if isinstance(r, dict) else r for r in records),
|
||||
encoding="utf-8",
|
||||
)
|
||||
return path
|
||||
|
||||
|
||||
def test_iter_events_preserves_order(tmp_path: Path) -> None:
|
||||
records = [
|
||||
_assistant(
|
||||
content=[
|
||||
{
|
||||
"type": "tool_use",
|
||||
"id": "a",
|
||||
"name": "Read",
|
||||
"input": {"file_path": "/i.png"},
|
||||
},
|
||||
],
|
||||
),
|
||||
{
|
||||
"message": {
|
||||
"content": [
|
||||
{"type": "tool_result", "tool_use_id": "a", "content": "xxxx"}
|
||||
]
|
||||
}
|
||||
},
|
||||
_assistant(usage={"output_tokens": 1}),
|
||||
]
|
||||
kinds = [k for k, _ in parse.iter_events(_write(tmp_path, records))]
|
||||
assert kinds == ["tool", "turn"]
|
||||
|
||||
|
||||
def test_events_carry_expected_types(tmp_path: Path) -> None:
|
||||
records = [
|
||||
_assistant(
|
||||
content=[
|
||||
{"type": "tool_use", "id": "a", "name": "Read", "input": {}},
|
||||
],
|
||||
),
|
||||
{"message": {"content": [{"type": "tool_result", "tool_use_id": "a"}]}},
|
||||
_assistant(usage={"output_tokens": 1}),
|
||||
]
|
||||
events = dict(parse.iter_events(_write(tmp_path, records)))
|
||||
assert isinstance(events["tool"], ToolCall)
|
||||
assert isinstance(events["turn"], Turn)
|
||||
|
||||
|
||||
def test_find_transcripts_filters_by_window(tmp_path: Path) -> None:
|
||||
project = tmp_path / "proj"
|
||||
project.mkdir()
|
||||
old = project / "old.jsonl"
|
||||
new = project / "new.jsonl"
|
||||
old.write_text("{}", encoding="utf-8")
|
||||
new.write_text("{}", encoding="utf-8")
|
||||
import os
|
||||
|
||||
os.utime(old, (1000, 1000))
|
||||
os.utime(new, (50_000, 50_000))
|
||||
|
||||
assert parse.find_transcripts(tmp_path, since=10_000) == [new]
|
||||
assert parse.find_transcripts(tmp_path, since=0, until=2000) == [old]
|
||||
assert len(parse.find_transcripts(tmp_path, since=0)) == 2
|
||||
|
||||
|
||||
@pytest.mark.parametrize("payload", [None, "abcdefgh"])
|
||||
def test_result_tokens_handles_missing_content(payload: str | None) -> None:
|
||||
assert parse._result_tokens({"content": payload}) >= 0
|
||||
@ -16,6 +16,7 @@ from python_pkg.wsg_grabber import (
|
||||
paths,
|
||||
review,
|
||||
store,
|
||||
store_verdicts,
|
||||
)
|
||||
from python_pkg.wsg_grabber.models import RemoteFile, Verdict
|
||||
from python_pkg.wsg_grabber.states import FileState
|
||||
@ -209,3 +210,220 @@ def test_open_session_recovers_interrupted_downloads() -> None:
|
||||
assert store.pending_downloads(built.conn) == 1
|
||||
finally:
|
||||
built.shutdown()
|
||||
|
||||
|
||||
def test_undo_puts_a_kept_file_back_in_the_queue(session: app.Session) -> None:
|
||||
"""The misclick this exists for: kept something you meant to pass."""
|
||||
_downloaded(session)
|
||||
state = session.commit(app.initial_state(session), Verdict.KEEP)
|
||||
assert (paths.keep_dir() / "clip.webm").exists()
|
||||
|
||||
state = session.undo(state)
|
||||
assert not (paths.keep_dir() / "clip.webm").exists()
|
||||
assert (paths.incoming_dir() / "clip.webm").exists()
|
||||
assert store.state_of(session.conn, _MD5) is FileState.READY
|
||||
assert state.kept == 0
|
||||
assert state.current is not None
|
||||
assert state.current.md5 == _MD5
|
||||
|
||||
|
||||
def test_undo_puts_a_passed_file_back(session: app.Session) -> None:
|
||||
_downloaded(session)
|
||||
state = session.commit(app.initial_state(session), Verdict.SKIP)
|
||||
assert (paths.trash_dir() / "clip.webm").exists()
|
||||
|
||||
state = session.undo(state)
|
||||
assert (paths.incoming_dir() / "clip.webm").exists()
|
||||
assert not (paths.trash_dir() / "clip.webm").exists()
|
||||
assert state.passed == 0
|
||||
|
||||
|
||||
def test_undo_survives_a_collision_rename(session: app.Session) -> None:
|
||||
"""A verdict may have renamed the file; undo must follow the real name."""
|
||||
_downloaded(session)
|
||||
(paths.trash_dir() / "clip.webm").write_bytes(b"older")
|
||||
state = session.commit(app.initial_state(session), Verdict.SKIP)
|
||||
assert (paths.trash_dir() / "clip-2.webm").exists()
|
||||
|
||||
state = session.undo(state)
|
||||
assert (paths.incoming_dir() / "clip.webm").read_bytes() == b"video"
|
||||
assert (paths.trash_dir() / "clip.webm").read_bytes() == b"older"
|
||||
assert not (paths.trash_dir() / "clip-2.webm").exists()
|
||||
|
||||
|
||||
def test_undo_steps_back_through_several_verdicts(session: app.Session) -> None:
|
||||
for index in range(3):
|
||||
store.record_files(
|
||||
session.conn,
|
||||
[
|
||||
RemoteFile(
|
||||
md5=f"M{index}",
|
||||
tim=index,
|
||||
ext=".webm",
|
||||
orig_name=f"v{index}",
|
||||
fsize=5,
|
||||
width=1,
|
||||
height=1,
|
||||
thread_no=1,
|
||||
post_no=index,
|
||||
),
|
||||
],
|
||||
)
|
||||
(paths.incoming_dir() / f"v{index}.webm").write_bytes(b"video")
|
||||
store.mark_downloaded(session.conn, f"M{index}", f"v{index}.webm")
|
||||
|
||||
state = app.initial_state(session)
|
||||
for _ in range(3):
|
||||
state = session.commit(state, Verdict.SKIP)
|
||||
assert state.passed == 3
|
||||
|
||||
for expected in ("M2", "M1", "M0"):
|
||||
state = session.undo(state)
|
||||
assert state.current is not None
|
||||
assert state.current.md5 == expected
|
||||
assert state.passed == 0
|
||||
assert not review.can_undo(state)
|
||||
|
||||
|
||||
def test_undo_with_nothing_to_undo_is_a_no_op(session: app.Session) -> None:
|
||||
state = app.initial_state(session)
|
||||
assert session.undo(state) is state
|
||||
|
||||
|
||||
def test_undo_gives_up_gracefully_when_the_file_was_removed(
|
||||
session: app.Session,
|
||||
) -> None:
|
||||
"""You may have emptied trash/ by hand; undo must not wedge on it."""
|
||||
_downloaded(session)
|
||||
state = session.commit(app.initial_state(session), Verdict.SKIP)
|
||||
(paths.trash_dir() / "clip.webm").unlink()
|
||||
|
||||
state = session.undo(state)
|
||||
assert not review.can_undo(state)
|
||||
assert store.state_of(session.conn, _MD5) is FileState.PASSED
|
||||
|
||||
|
||||
def test_undo_survives_quitting_and_reopening(session: app.Session) -> None:
|
||||
"""The whole point of persisting the trail: undo is not lost on exit."""
|
||||
_downloaded(session)
|
||||
session.commit(app.initial_state(session), Verdict.SKIP)
|
||||
assert (paths.trash_dir() / "clip.webm").exists()
|
||||
session.conn.close()
|
||||
|
||||
# a brand new session, as if the reviewer had been restarted
|
||||
reopened = app.Session(
|
||||
conn=db.open_index(paths.db_path()),
|
||||
events=queue.SimpleQueue(),
|
||||
stop=threading.Event(),
|
||||
)
|
||||
try:
|
||||
fresh = app.initial_state(reopened)
|
||||
assert fresh.undoable == 1
|
||||
restored = reopened.undo(fresh)
|
||||
assert (paths.incoming_dir() / "clip.webm").exists()
|
||||
assert store.state_of(reopened.conn, _MD5) is FileState.READY
|
||||
assert restored.current is not None
|
||||
assert restored.current.md5 == _MD5
|
||||
assert restored.undoable == 0
|
||||
finally:
|
||||
reopened.conn.close()
|
||||
|
||||
|
||||
def test_the_undo_trail_is_unbounded(session: app.Session) -> None:
|
||||
"""Any number of last verdicts, not a fixed window."""
|
||||
total = 25
|
||||
for index in range(total):
|
||||
store.record_files(
|
||||
session.conn,
|
||||
[
|
||||
RemoteFile(
|
||||
md5=f"U{index:02d}",
|
||||
tim=index,
|
||||
ext=".webm",
|
||||
orig_name=f"u{index:02d}",
|
||||
fsize=5,
|
||||
width=1,
|
||||
height=1,
|
||||
thread_no=1,
|
||||
post_no=index,
|
||||
),
|
||||
],
|
||||
)
|
||||
(paths.incoming_dir() / f"u{index:02d}.webm").write_bytes(b"video")
|
||||
store.mark_downloaded(session.conn, f"U{index:02d}", f"u{index:02d}.webm")
|
||||
|
||||
state = app.initial_state(session)
|
||||
for _ in range(total):
|
||||
state = session.commit(state, Verdict.SKIP)
|
||||
assert state.passed == total
|
||||
assert store_verdicts.reviewed_count(session.conn) == total
|
||||
|
||||
for index in reversed(range(total)):
|
||||
state = session.undo(state)
|
||||
assert state.current is not None
|
||||
assert state.current.md5 == f"U{index:02d}"
|
||||
assert state.passed == 0
|
||||
assert store_verdicts.reviewed_count(session.conn) == 0
|
||||
assert len(list(paths.trash_dir().iterdir())) == 0
|
||||
|
||||
|
||||
def test_undo_never_overwrites_a_file_sitting_in_incoming(
|
||||
session: app.Session,
|
||||
) -> None:
|
||||
"""A verdict must never be reversed on top of another video.
|
||||
|
||||
Path.replace clobbers silently, so undo picks a collision-free name the
|
||||
same way commit does.
|
||||
"""
|
||||
_downloaded(session)
|
||||
state = session.commit(app.initial_state(session), Verdict.KEEP)
|
||||
# something else now occupies the name the file used to have
|
||||
(paths.incoming_dir() / "clip.webm").write_bytes(b"DO NOT DESTROY ME")
|
||||
|
||||
session.undo(state)
|
||||
|
||||
assert (paths.incoming_dir() / "clip.webm").read_bytes() == b"DO NOT DESTROY ME"
|
||||
assert (paths.incoming_dir() / "clip-2.webm").read_bytes() == b"video"
|
||||
row = session.conn.execute(
|
||||
"SELECT local_name FROM files WHERE md5 = ?",
|
||||
(_MD5,),
|
||||
).fetchone()
|
||||
assert row["local_name"] == "clip-2.webm"
|
||||
|
||||
|
||||
def test_a_missing_file_never_clobbers_an_existing_verdict(
|
||||
session: app.Session,
|
||||
) -> None:
|
||||
"""Two reviewers on one index must not corrupt each other's undo trail."""
|
||||
_downloaded(session)
|
||||
state = app.initial_state(session)
|
||||
session.commit(state, Verdict.KEEP)
|
||||
assert store_verdicts.reviewed_count(session.conn) == 1
|
||||
|
||||
# the same item, still queued in a second reviewer, whose file is now gone
|
||||
session.missing(state)
|
||||
|
||||
assert store.state_of(session.conn, _MD5) is FileState.KEPT
|
||||
assert store_verdicts.reviewed_count(session.conn) == 1
|
||||
|
||||
|
||||
def test_open_session_closes_the_index_if_the_worker_cannot_start() -> None:
|
||||
with (
|
||||
patch.object(downloader, "start", side_effect=RuntimeError("no thread")),
|
||||
pytest.raises(RuntimeError),
|
||||
):
|
||||
app.open_session()
|
||||
# a second open must succeed, which it cannot if the first leaked a handle
|
||||
with patch.object(downloader, "start", return_value=MagicMock()):
|
||||
again = app.open_session()
|
||||
again.shutdown()
|
||||
|
||||
|
||||
def test_a_worker_that_outlives_the_join_is_not_silently_forgotten(
|
||||
session: app.Session,
|
||||
) -> None:
|
||||
worker = MagicMock()
|
||||
worker.is_alive.return_value = True
|
||||
session.worker = worker
|
||||
session.shutdown()
|
||||
assert session.worker is worker # handle kept so the failure is visible
|
||||
|
||||
@ -1,106 +0,0 @@
|
||||
"""Tests for undoing verdicts in a review session."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import queue
|
||||
import threading
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import pytest
|
||||
|
||||
from python_pkg.wsg_grabber import (
|
||||
app,
|
||||
db,
|
||||
paths,
|
||||
store,
|
||||
)
|
||||
from python_pkg.wsg_grabber.models import RemoteFile, Verdict
|
||||
from python_pkg.wsg_grabber.states import FileState
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Iterator
|
||||
|
||||
_MD5 = "Nz9OEKdMuMZEdYE6eLTKmA=="
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def session() -> Iterator[app.Session]:
|
||||
"""Build a session over a sandboxed index, with no worker running.
|
||||
|
||||
Yields:
|
||||
app.Session: Session whose connection is closed afterwards.
|
||||
"""
|
||||
paths.ensure_dirs()
|
||||
conn = db.open_index(paths.db_path())
|
||||
built = app.Session(conn=conn, events=queue.SimpleQueue(), stop=threading.Event())
|
||||
try:
|
||||
yield built
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def _downloaded(session: app.Session, name: str = "clip") -> None:
|
||||
"""Put one downloaded, unreviewed file into the index and on disk.
|
||||
|
||||
Args:
|
||||
session: The session to populate.
|
||||
name: Local filename stem.
|
||||
"""
|
||||
store.record_files(
|
||||
session.conn,
|
||||
[
|
||||
RemoteFile(
|
||||
md5=_MD5,
|
||||
tim=1,
|
||||
ext=".webm",
|
||||
orig_name=name,
|
||||
fsize=5,
|
||||
width=4,
|
||||
height=3,
|
||||
thread_no=7,
|
||||
post_no=1,
|
||||
),
|
||||
],
|
||||
)
|
||||
local = f"{name}.webm"
|
||||
(paths.incoming_dir() / local).write_bytes(b"video")
|
||||
store.mark_downloaded(session.conn, _MD5, local)
|
||||
|
||||
|
||||
def test_undo_puts_a_kept_file_back_in_the_queue(session: app.Session) -> None:
|
||||
"""The misclick this exists for: kept something you meant to pass."""
|
||||
_downloaded(session)
|
||||
state = session.commit(app.initial_state(session), Verdict.KEEP)
|
||||
assert (paths.keep_dir() / "clip.webm").exists()
|
||||
|
||||
state = session.undo(state)
|
||||
assert not (paths.keep_dir() / "clip.webm").exists()
|
||||
assert (paths.incoming_dir() / "clip.webm").exists()
|
||||
assert store.state_of(session.conn, _MD5) is FileState.READY
|
||||
assert state.kept == 0
|
||||
assert state.current is not None
|
||||
assert state.current.md5 == _MD5
|
||||
|
||||
|
||||
def test_undo_puts_a_passed_file_back(session: app.Session) -> None:
|
||||
_downloaded(session)
|
||||
state = session.commit(app.initial_state(session), Verdict.SKIP)
|
||||
assert (paths.trash_dir() / "clip.webm").exists()
|
||||
|
||||
state = session.undo(state)
|
||||
assert (paths.incoming_dir() / "clip.webm").exists()
|
||||
assert not (paths.trash_dir() / "clip.webm").exists()
|
||||
assert state.passed == 0
|
||||
|
||||
|
||||
def test_undo_survives_a_collision_rename(session: app.Session) -> None:
|
||||
"""A verdict may have renamed the file; undo must follow the real name."""
|
||||
_downloaded(session)
|
||||
(paths.trash_dir() / "clip.webm").write_bytes(b"older")
|
||||
state = session.commit(app.initial_state(session), Verdict.SKIP)
|
||||
assert (paths.trash_dir() / "clip-2.webm").exists()
|
||||
|
||||
state = session.undo(state)
|
||||
assert (paths.incoming_dir() / "clip.webm").read_bytes() == b"video"
|
||||
assert (paths.trash_dir() / "clip.webm").read_bytes() == b"older"
|
||||
assert not (paths.trash_dir() / "clip-2.webm").exists()
|
||||
@ -1,185 +0,0 @@
|
||||
"""Tests for stepping back through several verdicts."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import queue
|
||||
import threading
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import pytest
|
||||
|
||||
from python_pkg.wsg_grabber import (
|
||||
app,
|
||||
db,
|
||||
paths,
|
||||
review,
|
||||
store,
|
||||
store_verdicts,
|
||||
)
|
||||
from python_pkg.wsg_grabber.models import RemoteFile, Verdict
|
||||
from python_pkg.wsg_grabber.states import FileState
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Iterator
|
||||
|
||||
_MD5 = "Nz9OEKdMuMZEdYE6eLTKmA=="
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def session() -> Iterator[app.Session]:
|
||||
"""Build a session over a sandboxed index, with no worker running.
|
||||
|
||||
Yields:
|
||||
app.Session: Session whose connection is closed afterwards.
|
||||
"""
|
||||
paths.ensure_dirs()
|
||||
conn = db.open_index(paths.db_path())
|
||||
built = app.Session(conn=conn, events=queue.SimpleQueue(), stop=threading.Event())
|
||||
try:
|
||||
yield built
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def _downloaded(session: app.Session, name: str = "clip") -> None:
|
||||
"""Put one downloaded, unreviewed file into the index and on disk.
|
||||
|
||||
Args:
|
||||
session: The session to populate.
|
||||
name: Local filename stem.
|
||||
"""
|
||||
store.record_files(
|
||||
session.conn,
|
||||
[
|
||||
RemoteFile(
|
||||
md5=_MD5,
|
||||
tim=1,
|
||||
ext=".webm",
|
||||
orig_name=name,
|
||||
fsize=5,
|
||||
width=4,
|
||||
height=3,
|
||||
thread_no=7,
|
||||
post_no=1,
|
||||
),
|
||||
],
|
||||
)
|
||||
local = f"{name}.webm"
|
||||
(paths.incoming_dir() / local).write_bytes(b"video")
|
||||
store.mark_downloaded(session.conn, _MD5, local)
|
||||
|
||||
|
||||
def test_undo_steps_back_through_several_verdicts(session: app.Session) -> None:
|
||||
for index in range(3):
|
||||
store.record_files(
|
||||
session.conn,
|
||||
[
|
||||
RemoteFile(
|
||||
md5=f"M{index}",
|
||||
tim=index,
|
||||
ext=".webm",
|
||||
orig_name=f"v{index}",
|
||||
fsize=5,
|
||||
width=1,
|
||||
height=1,
|
||||
thread_no=1,
|
||||
post_no=index,
|
||||
),
|
||||
],
|
||||
)
|
||||
(paths.incoming_dir() / f"v{index}.webm").write_bytes(b"video")
|
||||
store.mark_downloaded(session.conn, f"M{index}", f"v{index}.webm")
|
||||
|
||||
state = app.initial_state(session)
|
||||
for _ in range(3):
|
||||
state = session.commit(state, Verdict.SKIP)
|
||||
assert state.passed == 3
|
||||
|
||||
for expected in ("M2", "M1", "M0"):
|
||||
state = session.undo(state)
|
||||
assert state.current is not None
|
||||
assert state.current.md5 == expected
|
||||
assert state.passed == 0
|
||||
assert not review.can_undo(state)
|
||||
|
||||
|
||||
def test_undo_with_nothing_to_undo_is_a_no_op(session: app.Session) -> None:
|
||||
state = app.initial_state(session)
|
||||
assert session.undo(state) is state
|
||||
|
||||
|
||||
def test_undo_gives_up_gracefully_when_the_file_was_removed(
|
||||
session: app.Session,
|
||||
) -> None:
|
||||
"""You may have emptied trash/ by hand; undo must not wedge on it."""
|
||||
_downloaded(session)
|
||||
state = session.commit(app.initial_state(session), Verdict.SKIP)
|
||||
(paths.trash_dir() / "clip.webm").unlink()
|
||||
|
||||
state = session.undo(state)
|
||||
assert not review.can_undo(state)
|
||||
assert store.state_of(session.conn, _MD5) is FileState.PASSED
|
||||
|
||||
|
||||
def test_undo_survives_quitting_and_reopening(session: app.Session) -> None:
|
||||
"""The whole point of persisting the trail: undo is not lost on exit."""
|
||||
_downloaded(session)
|
||||
session.commit(app.initial_state(session), Verdict.SKIP)
|
||||
assert (paths.trash_dir() / "clip.webm").exists()
|
||||
session.conn.close()
|
||||
|
||||
# a brand new session, as if the reviewer had been restarted
|
||||
reopened = app.Session(
|
||||
conn=db.open_index(paths.db_path()),
|
||||
events=queue.SimpleQueue(),
|
||||
stop=threading.Event(),
|
||||
)
|
||||
try:
|
||||
fresh = app.initial_state(reopened)
|
||||
assert fresh.undoable == 1
|
||||
restored = reopened.undo(fresh)
|
||||
assert (paths.incoming_dir() / "clip.webm").exists()
|
||||
assert store.state_of(reopened.conn, _MD5) is FileState.READY
|
||||
assert restored.current is not None
|
||||
assert restored.current.md5 == _MD5
|
||||
assert restored.undoable == 0
|
||||
finally:
|
||||
reopened.conn.close()
|
||||
|
||||
|
||||
def test_the_undo_trail_is_unbounded(session: app.Session) -> None:
|
||||
"""Any number of last verdicts, not a fixed window."""
|
||||
total = 25
|
||||
for index in range(total):
|
||||
store.record_files(
|
||||
session.conn,
|
||||
[
|
||||
RemoteFile(
|
||||
md5=f"U{index:02d}",
|
||||
tim=index,
|
||||
ext=".webm",
|
||||
orig_name=f"u{index:02d}",
|
||||
fsize=5,
|
||||
width=1,
|
||||
height=1,
|
||||
thread_no=1,
|
||||
post_no=index,
|
||||
),
|
||||
],
|
||||
)
|
||||
(paths.incoming_dir() / f"u{index:02d}.webm").write_bytes(b"video")
|
||||
store.mark_downloaded(session.conn, f"U{index:02d}", f"u{index:02d}.webm")
|
||||
|
||||
state = app.initial_state(session)
|
||||
for _ in range(total):
|
||||
state = session.commit(state, Verdict.SKIP)
|
||||
assert state.passed == total
|
||||
assert store_verdicts.reviewed_count(session.conn) == total
|
||||
|
||||
for index in reversed(range(total)):
|
||||
state = session.undo(state)
|
||||
assert state.current is not None
|
||||
assert state.current.md5 == f"U{index:02d}"
|
||||
assert state.passed == 0
|
||||
assert store_verdicts.reviewed_count(session.conn) == 0
|
||||
assert len(list(paths.trash_dir().iterdir())) == 0
|
||||
@ -1,132 +0,0 @@
|
||||
"""Tests that undo never clobbers an existing file."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import queue
|
||||
import threading
|
||||
from typing import TYPE_CHECKING
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from python_pkg.wsg_grabber import (
|
||||
app,
|
||||
db,
|
||||
downloader,
|
||||
paths,
|
||||
store,
|
||||
store_verdicts,
|
||||
)
|
||||
from python_pkg.wsg_grabber.models import RemoteFile, Verdict
|
||||
from python_pkg.wsg_grabber.states import FileState
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Iterator
|
||||
|
||||
_MD5 = "Nz9OEKdMuMZEdYE6eLTKmA=="
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def session() -> Iterator[app.Session]:
|
||||
"""Build a session over a sandboxed index, with no worker running.
|
||||
|
||||
Yields:
|
||||
app.Session: Session whose connection is closed afterwards.
|
||||
"""
|
||||
paths.ensure_dirs()
|
||||
conn = db.open_index(paths.db_path())
|
||||
built = app.Session(conn=conn, events=queue.SimpleQueue(), stop=threading.Event())
|
||||
try:
|
||||
yield built
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def _downloaded(session: app.Session, name: str = "clip") -> None:
|
||||
"""Put one downloaded, unreviewed file into the index and on disk.
|
||||
|
||||
Args:
|
||||
session: The session to populate.
|
||||
name: Local filename stem.
|
||||
"""
|
||||
store.record_files(
|
||||
session.conn,
|
||||
[
|
||||
RemoteFile(
|
||||
md5=_MD5,
|
||||
tim=1,
|
||||
ext=".webm",
|
||||
orig_name=name,
|
||||
fsize=5,
|
||||
width=4,
|
||||
height=3,
|
||||
thread_no=7,
|
||||
post_no=1,
|
||||
),
|
||||
],
|
||||
)
|
||||
local = f"{name}.webm"
|
||||
(paths.incoming_dir() / local).write_bytes(b"video")
|
||||
store.mark_downloaded(session.conn, _MD5, local)
|
||||
|
||||
|
||||
def test_undo_never_overwrites_a_file_sitting_in_incoming(
|
||||
session: app.Session,
|
||||
) -> None:
|
||||
"""A verdict must never be reversed on top of another video.
|
||||
|
||||
Path.replace clobbers silently, so undo picks a collision-free name the
|
||||
same way commit does.
|
||||
"""
|
||||
_downloaded(session)
|
||||
state = session.commit(app.initial_state(session), Verdict.KEEP)
|
||||
# something else now occupies the name the file used to have
|
||||
(paths.incoming_dir() / "clip.webm").write_bytes(b"DO NOT DESTROY ME")
|
||||
|
||||
session.undo(state)
|
||||
|
||||
assert (paths.incoming_dir() / "clip.webm").read_bytes() == b"DO NOT DESTROY ME"
|
||||
assert (paths.incoming_dir() / "clip-2.webm").read_bytes() == b"video"
|
||||
row = session.conn.execute(
|
||||
"SELECT local_name FROM files WHERE md5 = ?",
|
||||
(_MD5,),
|
||||
).fetchone()
|
||||
assert row["local_name"] == "clip-2.webm"
|
||||
|
||||
|
||||
def test_a_missing_file_never_clobbers_an_existing_verdict(
|
||||
session: app.Session,
|
||||
) -> None:
|
||||
"""Two reviewers on one index must not corrupt each other's undo trail."""
|
||||
_downloaded(session)
|
||||
state = app.initial_state(session)
|
||||
session.commit(state, Verdict.KEEP)
|
||||
assert store_verdicts.reviewed_count(session.conn) == 1
|
||||
|
||||
# the same item, still queued in a second reviewer, whose file is now gone
|
||||
session.missing(state)
|
||||
|
||||
assert store.state_of(session.conn, _MD5) is FileState.KEPT
|
||||
assert store_verdicts.reviewed_count(session.conn) == 1
|
||||
|
||||
|
||||
def test_open_session_closes_the_index_if_the_worker_cannot_start() -> None:
|
||||
with (
|
||||
patch.object(downloader, "start", side_effect=RuntimeError("no thread")),
|
||||
pytest.raises(RuntimeError),
|
||||
):
|
||||
app.open_session()
|
||||
# a second open must succeed, which it cannot if the first leaked a handle
|
||||
with patch.object(downloader, "start", return_value=MagicMock()):
|
||||
again = app.open_session()
|
||||
again.shutdown()
|
||||
|
||||
|
||||
def test_a_worker_that_outlives_the_join_is_not_silently_forgotten(
|
||||
session: app.Session,
|
||||
) -> None:
|
||||
worker = MagicMock()
|
||||
worker.is_alive.return_value = True
|
||||
session.worker = worker
|
||||
session.shutdown()
|
||||
assert session.worker is worker # handle kept so the failure is visible
|
||||
@ -15,13 +15,18 @@ import pytest
|
||||
|
||||
from python_pkg.wsg_grabber import db, downloader, net, store, store_threads
|
||||
from python_pkg.wsg_grabber.models import (
|
||||
Downloaded,
|
||||
DownloadEvent,
|
||||
DownloadResult,
|
||||
FileReady,
|
||||
Indexed,
|
||||
JsonResponse,
|
||||
Outcome,
|
||||
RemoteFile,
|
||||
TaskKind,
|
||||
ThreadRef,
|
||||
)
|
||||
from python_pkg.wsg_grabber.states import FileState
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Iterator
|
||||
@ -221,3 +226,116 @@ def test_a_board_without_an_archive_is_tolerated(
|
||||
side_effect=[_json([]), _json(None, not_found=True)],
|
||||
):
|
||||
assert worker.run_once() is TaskKind.SCAN
|
||||
|
||||
|
||||
def test_a_completed_download_is_renamed_and_announced(
|
||||
deps: downloader.WorkerDeps,
|
||||
) -> None:
|
||||
worker = downloader.Worker(deps)
|
||||
store.record_files(deps.conn, [_remote()])
|
||||
|
||||
def fake_download(_session: object, transfer: net.Transfer) -> DownloadResult:
|
||||
transfer.part_path.write_bytes(_BODY)
|
||||
return DownloadResult(outcome=Outcome.COMPLETED, bytes_done=len(_BODY))
|
||||
|
||||
with patch.object(net, "download", side_effect=fake_download):
|
||||
assert worker.run_once() is TaskKind.DOWNLOAD
|
||||
|
||||
events = _drain(deps.events)
|
||||
ready = [event for event in events if isinstance(event, FileReady)]
|
||||
assert len(ready) == 1
|
||||
assert ready[0].item.md5 == _MD5
|
||||
assert ready[0].item.path.exists()
|
||||
assert not ready[0].item.path.name.endswith(".part")
|
||||
assert ready[0].item.orig_name == "clip.webm"
|
||||
assert any(isinstance(event, Downloaded) for event in events)
|
||||
assert worker.downloaded == 1
|
||||
assert store.counts(deps.conn)[FileState.READY.value] == 1
|
||||
|
||||
|
||||
def test_a_404_is_terminal_and_never_retried(deps: downloader.WorkerDeps) -> None:
|
||||
"""This is what stops a fallen-off thread being re-fetched every run."""
|
||||
worker = downloader.Worker(deps)
|
||||
store.record_files(deps.conn, [_remote()])
|
||||
with patch.object(
|
||||
net,
|
||||
"download",
|
||||
return_value=DownloadResult(outcome=Outcome.NOT_FOUND, bytes_done=0),
|
||||
):
|
||||
worker.run_once()
|
||||
assert store.counts(deps.conn)[FileState.GONE.value] == 1
|
||||
assert store.pending_downloads(deps.conn) == 0
|
||||
|
||||
|
||||
def test_a_transient_failure_is_retried(deps: downloader.WorkerDeps) -> None:
|
||||
worker = downloader.Worker(deps)
|
||||
store.record_files(deps.conn, [_remote()])
|
||||
with patch.object(
|
||||
net,
|
||||
"download",
|
||||
return_value=DownloadResult(outcome=Outcome.TRANSIENT, bytes_done=0),
|
||||
):
|
||||
worker.run_once()
|
||||
assert store.counts(deps.conn)[FileState.FAILED.value] == 1
|
||||
assert store.pending_downloads(deps.conn) == 1
|
||||
|
||||
|
||||
def test_a_transient_failure_gives_up_after_the_attempt_budget(
|
||||
deps: downloader.WorkerDeps,
|
||||
) -> None:
|
||||
worker = downloader.Worker(deps)
|
||||
store.record_files(deps.conn, [_remote()])
|
||||
with patch.object(
|
||||
net,
|
||||
"download",
|
||||
return_value=DownloadResult(outcome=Outcome.TRANSIENT, bytes_done=0),
|
||||
):
|
||||
for _ in range(3):
|
||||
worker.run_once()
|
||||
assert store.counts(deps.conn)[FileState.GONE.value] == 1
|
||||
|
||||
|
||||
def test_a_retry_after_pauses_the_worker(deps: downloader.WorkerDeps) -> None:
|
||||
worker = downloader.Worker(deps)
|
||||
store.record_files(deps.conn, [_remote()])
|
||||
with (
|
||||
patch.object(
|
||||
net,
|
||||
"download",
|
||||
return_value=DownloadResult(
|
||||
outcome=Outcome.TRANSIENT,
|
||||
bytes_done=0,
|
||||
retry_after=5.0,
|
||||
),
|
||||
),
|
||||
patch.object(deps.stop, "wait") as waited,
|
||||
):
|
||||
worker.run_once()
|
||||
assert any(call.args and call.args[0] == 5.0 for call in waited.call_args_list)
|
||||
|
||||
|
||||
def test_a_checksum_mismatch_marks_the_file_corrupt(
|
||||
deps: downloader.WorkerDeps,
|
||||
) -> None:
|
||||
worker = downloader.Worker(deps)
|
||||
store.record_files(deps.conn, [_remote()])
|
||||
with patch.object(
|
||||
net,
|
||||
"download",
|
||||
return_value=DownloadResult(outcome=Outcome.CHECKSUM_MISMATCH, bytes_done=0),
|
||||
):
|
||||
worker.run_once()
|
||||
assert store.counts(deps.conn)[FileState.CORRUPT.value] == 1
|
||||
|
||||
|
||||
def test_an_aborted_download_stays_resumable(deps: downloader.WorkerDeps) -> None:
|
||||
worker = downloader.Worker(deps)
|
||||
store.record_files(deps.conn, [_remote()])
|
||||
with patch.object(
|
||||
net,
|
||||
"download",
|
||||
return_value=DownloadResult(outcome=Outcome.ABORTED, bytes_done=4),
|
||||
):
|
||||
worker.run_once()
|
||||
assert store.counts(deps.conn)[FileState.FAILED.value] == 1
|
||||
assert store.pending_downloads(deps.conn) == 1
|
||||
|
||||
@ -1,168 +0,0 @@
|
||||
"""Tests for conditional board fetches and stored stamps."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import queue
|
||||
import threading
|
||||
from typing import TYPE_CHECKING
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from python_pkg.wsg_grabber import db, downloader, net, store_threads
|
||||
from python_pkg.wsg_grabber.constants import THREADS_URL
|
||||
from python_pkg.wsg_grabber.models import (
|
||||
DownloadEvent,
|
||||
JsonResponse,
|
||||
RemoteFile,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Iterator
|
||||
from pathlib import Path
|
||||
|
||||
_MD5 = "Nz9OEKdMuMZEdYE6eLTKmA=="
|
||||
_BODY = b"video bytes"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def deps(tmp_path: Path) -> Iterator[downloader.WorkerDeps]:
|
||||
"""Build worker dependencies backed by a sandboxed index.
|
||||
|
||||
Args:
|
||||
tmp_path: Per-test temporary directory.
|
||||
|
||||
Yields:
|
||||
downloader.WorkerDeps: Ready dependencies; resources closed after.
|
||||
"""
|
||||
incoming = tmp_path / "incoming"
|
||||
incoming.mkdir()
|
||||
conn = db.open_index(tmp_path / "index.db")
|
||||
session = MagicMock()
|
||||
built = downloader.WorkerDeps(
|
||||
conn=conn,
|
||||
session=session,
|
||||
incoming=incoming,
|
||||
events=queue.SimpleQueue(),
|
||||
stop=threading.Event(),
|
||||
include_archive=False,
|
||||
)
|
||||
try:
|
||||
yield built
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def _json(
|
||||
payload: object,
|
||||
*,
|
||||
last_modified: str | None = None,
|
||||
not_modified: bool = False,
|
||||
not_found: bool = False,
|
||||
) -> JsonResponse:
|
||||
"""Build a JsonResponse with sensible defaults.
|
||||
|
||||
Args:
|
||||
payload: Decoded body.
|
||||
last_modified: Header value the response carried.
|
||||
not_modified: Whether the server answered 304.
|
||||
not_found: Whether the thread has gone.
|
||||
|
||||
Returns:
|
||||
JsonResponse: Response double.
|
||||
"""
|
||||
return JsonResponse(
|
||||
payload=payload,
|
||||
last_modified=last_modified,
|
||||
not_modified=not_modified,
|
||||
not_found=not_found,
|
||||
)
|
||||
|
||||
|
||||
def _remote(md5: str = _MD5, tim: int = 1) -> RemoteFile:
|
||||
"""Build a RemoteFile.
|
||||
|
||||
Args:
|
||||
md5: Identity.
|
||||
tim: CDN stem.
|
||||
|
||||
Returns:
|
||||
RemoteFile: Fixture value.
|
||||
"""
|
||||
return RemoteFile(
|
||||
md5=md5,
|
||||
tim=tim,
|
||||
ext=".webm",
|
||||
orig_name="clip",
|
||||
fsize=len(_BODY),
|
||||
width=480,
|
||||
height=360,
|
||||
thread_no=7,
|
||||
post_no=tim,
|
||||
)
|
||||
|
||||
|
||||
def _drain(events: queue.SimpleQueue[DownloadEvent]) -> list[DownloadEvent]:
|
||||
"""Pull everything currently queued.
|
||||
|
||||
Args:
|
||||
events: Queue to empty.
|
||||
|
||||
Returns:
|
||||
list[DownloadEvent]: Events in order.
|
||||
"""
|
||||
out: list[DownloadEvent] = []
|
||||
while not events.empty():
|
||||
out.append(events.get_nowait())
|
||||
return out
|
||||
|
||||
|
||||
def test_the_board_endpoints_are_fetched_conditionally(
|
||||
deps: downloader.WorkerDeps,
|
||||
) -> None:
|
||||
"""Without this an idle reviewer re-fetches the board unconditionally forever."""
|
||||
deps.include_archive = True
|
||||
worker = downloader.Worker(deps)
|
||||
stamp = "Mon, 27 Jul 2026 10:00:00 GMT"
|
||||
with patch.object(
|
||||
net,
|
||||
"get_json",
|
||||
return_value=_json([], last_modified=stamp),
|
||||
) as fake:
|
||||
worker.run_once()
|
||||
sent_first = [call.args[2] for call in fake.call_args_list]
|
||||
worker._catalog_fresh = False
|
||||
fake.reset_mock()
|
||||
worker.run_once()
|
||||
sent_again = [call.args[2] for call in fake.call_args_list]
|
||||
|
||||
assert sent_first == [None, None] # nothing stored yet
|
||||
assert sent_again == [stamp, stamp] # the stamp goes back
|
||||
|
||||
|
||||
def test_a_304_on_the_board_keeps_the_stored_stamp(
|
||||
deps: downloader.WorkerDeps,
|
||||
) -> None:
|
||||
worker = downloader.Worker(deps)
|
||||
stamp = "Mon, 27 Jul 2026 10:00:00 GMT"
|
||||
with patch.object(net, "get_json", return_value=_json([], last_modified=stamp)):
|
||||
worker.run_once()
|
||||
with patch.object(net, "get_json", return_value=_json(None, not_modified=True)):
|
||||
worker._catalog_fresh = False
|
||||
worker.run_once()
|
||||
assert store_threads.cached_last_modified(deps.conn, THREADS_URL) == stamp
|
||||
|
||||
|
||||
def test_a_worker_that_cannot_build_its_resources_reports_it(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""Otherwise the reviewer waits on downloads that will never come."""
|
||||
reported: list[str] = []
|
||||
thread = downloader.start(
|
||||
lambda: (_ for _ in ()).throw(OSError("no database")),
|
||||
reported.append,
|
||||
)
|
||||
thread.join(timeout=5)
|
||||
assert not thread.is_alive()
|
||||
assert reported
|
||||
assert "no database" in reported[0]
|
||||
@ -1,219 +0,0 @@
|
||||
"""Tests for worker idle announcements and shutdown."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import queue
|
||||
import threading
|
||||
import time
|
||||
from typing import TYPE_CHECKING, cast
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from python_pkg.wsg_grabber import db, downloader, net
|
||||
from python_pkg.wsg_grabber.constants import IDLE_RESCAN_S
|
||||
from python_pkg.wsg_grabber.models import (
|
||||
DownloadEvent,
|
||||
JsonResponse,
|
||||
RemoteFile,
|
||||
ScanFinished,
|
||||
TaskKind,
|
||||
WorkerFailed,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Iterator
|
||||
from pathlib import Path
|
||||
|
||||
_MD5 = "Nz9OEKdMuMZEdYE6eLTKmA=="
|
||||
_BODY = b"video bytes"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def deps(tmp_path: Path) -> Iterator[downloader.WorkerDeps]:
|
||||
"""Build worker dependencies backed by a sandboxed index.
|
||||
|
||||
Args:
|
||||
tmp_path: Per-test temporary directory.
|
||||
|
||||
Yields:
|
||||
downloader.WorkerDeps: Ready dependencies; resources closed after.
|
||||
"""
|
||||
incoming = tmp_path / "incoming"
|
||||
incoming.mkdir()
|
||||
conn = db.open_index(tmp_path / "index.db")
|
||||
session = MagicMock()
|
||||
built = downloader.WorkerDeps(
|
||||
conn=conn,
|
||||
session=session,
|
||||
incoming=incoming,
|
||||
events=queue.SimpleQueue(),
|
||||
stop=threading.Event(),
|
||||
include_archive=False,
|
||||
)
|
||||
try:
|
||||
yield built
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def _json(
|
||||
payload: object,
|
||||
*,
|
||||
last_modified: str | None = None,
|
||||
not_modified: bool = False,
|
||||
not_found: bool = False,
|
||||
) -> JsonResponse:
|
||||
"""Build a JsonResponse with sensible defaults.
|
||||
|
||||
Args:
|
||||
payload: Decoded body.
|
||||
last_modified: Header value the response carried.
|
||||
not_modified: Whether the server answered 304.
|
||||
not_found: Whether the thread has gone.
|
||||
|
||||
Returns:
|
||||
JsonResponse: Response double.
|
||||
"""
|
||||
return JsonResponse(
|
||||
payload=payload,
|
||||
last_modified=last_modified,
|
||||
not_modified=not_modified,
|
||||
not_found=not_found,
|
||||
)
|
||||
|
||||
|
||||
def _remote(md5: str = _MD5, tim: int = 1) -> RemoteFile:
|
||||
"""Build a RemoteFile.
|
||||
|
||||
Args:
|
||||
md5: Identity.
|
||||
tim: CDN stem.
|
||||
|
||||
Returns:
|
||||
RemoteFile: Fixture value.
|
||||
"""
|
||||
return RemoteFile(
|
||||
md5=md5,
|
||||
tim=tim,
|
||||
ext=".webm",
|
||||
orig_name="clip",
|
||||
fsize=len(_BODY),
|
||||
width=480,
|
||||
height=360,
|
||||
thread_no=7,
|
||||
post_no=tim,
|
||||
)
|
||||
|
||||
|
||||
def _drain(events: queue.SimpleQueue[DownloadEvent]) -> list[DownloadEvent]:
|
||||
"""Pull everything currently queued.
|
||||
|
||||
Args:
|
||||
events: Queue to empty.
|
||||
|
||||
Returns:
|
||||
list[DownloadEvent]: Events in order.
|
||||
"""
|
||||
out: list[DownloadEvent] = []
|
||||
while not events.empty():
|
||||
out.append(events.get_nowait())
|
||||
return out
|
||||
|
||||
|
||||
def test_idle_announces_completion_exactly_once(
|
||||
deps: downloader.WorkerDeps,
|
||||
) -> None:
|
||||
worker = downloader.Worker(deps)
|
||||
with patch.object(net, "get_json", return_value=_json([])):
|
||||
worker.run_once()
|
||||
with patch.object(deps.stop, "wait"):
|
||||
assert worker.run_once() is TaskKind.IDLE
|
||||
assert worker.run_once() is TaskKind.IDLE
|
||||
finished = [e for e in _drain(deps.events) if isinstance(e, ScanFinished)]
|
||||
assert len(finished) == 1
|
||||
|
||||
|
||||
def test_the_board_is_rescanned_after_the_quiet_period(
|
||||
deps: downloader.WorkerDeps,
|
||||
) -> None:
|
||||
"""A finished sweep goes quiet, then polls again for new content."""
|
||||
worker = downloader.Worker(deps)
|
||||
with patch.object(net, "get_json", return_value=_json([])):
|
||||
worker.run_once()
|
||||
with patch.object(deps.stop, "wait"):
|
||||
assert worker.run_once() is TaskKind.IDLE
|
||||
with patch(
|
||||
"python_pkg.wsg_grabber.downloader.time.monotonic",
|
||||
return_value=time.monotonic() + IDLE_RESCAN_S + 1,
|
||||
):
|
||||
assert worker.run_once() is TaskKind.IDLE
|
||||
# the quiet period has elapsed, so the next step walks the board again
|
||||
assert worker.run_once() is TaskKind.SCAN
|
||||
finished = [e for e in _drain(deps.events) if isinstance(e, ScanFinished)]
|
||||
assert len(finished) == 1
|
||||
|
||||
|
||||
def test_rate_limiting_waits_between_requests(
|
||||
deps: downloader.WorkerDeps,
|
||||
) -> None:
|
||||
worker = downloader.Worker(deps)
|
||||
listing = [{"threads": [{"no": 7, "last_modified": 100}]}]
|
||||
with (
|
||||
patch.object(
|
||||
net,
|
||||
"get_json",
|
||||
side_effect=[_json(listing), _json({"posts": []})],
|
||||
),
|
||||
patch.object(deps.stop, "wait") as waited,
|
||||
):
|
||||
worker.run_once() # the first request is free
|
||||
worker.run_once() # the second must be spaced out
|
||||
delays = [call.args[0] for call in waited.call_args_list if call.args]
|
||||
assert delays
|
||||
assert max(delays) <= 1.0
|
||||
|
||||
|
||||
def test_run_reports_a_crash_and_closes_resources(
|
||||
deps: downloader.WorkerDeps,
|
||||
) -> None:
|
||||
worker = downloader.Worker(deps)
|
||||
with patch.object(worker, "run_once", side_effect=RuntimeError("kaput")):
|
||||
worker.run()
|
||||
events = _drain(deps.events)
|
||||
assert any(
|
||||
isinstance(event, WorkerFailed) and event.message == "kaput" for event in events
|
||||
)
|
||||
cast("MagicMock", deps.session).close.assert_called_once()
|
||||
|
||||
|
||||
def test_run_exits_cleanly_when_stopped(deps: downloader.WorkerDeps) -> None:
|
||||
deps.stop.set()
|
||||
worker = downloader.Worker(deps)
|
||||
worker.run()
|
||||
assert _drain(deps.events) == []
|
||||
cast("MagicMock", deps.session).close.assert_called_once()
|
||||
|
||||
|
||||
@pytest.mark.timeout(10)
|
||||
def test_start_runs_and_joins_a_real_thread(tmp_path: Path) -> None:
|
||||
"""The one test that starts a thread; it must stop on demand."""
|
||||
incoming = tmp_path / "incoming"
|
||||
incoming.mkdir()
|
||||
stop = threading.Event()
|
||||
stop.set()
|
||||
|
||||
def build() -> downloader.WorkerDeps:
|
||||
"""Open the connection on the worker thread, which must own it."""
|
||||
return downloader.WorkerDeps(
|
||||
conn=db.open_index(tmp_path / "index.db"),
|
||||
session=MagicMock(),
|
||||
incoming=incoming,
|
||||
events=queue.SimpleQueue(),
|
||||
stop=stop,
|
||||
include_archive=False,
|
||||
)
|
||||
|
||||
thread = downloader.start(build)
|
||||
thread.join(timeout=5)
|
||||
assert not thread.is_alive()
|
||||
@ -1,161 +0,0 @@
|
||||
"""Tests for how completed and failed downloads are recorded."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import queue
|
||||
import threading
|
||||
from typing import TYPE_CHECKING
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from python_pkg.wsg_grabber import db, downloader, net, store
|
||||
from python_pkg.wsg_grabber.models import (
|
||||
Downloaded,
|
||||
DownloadEvent,
|
||||
DownloadResult,
|
||||
FileReady,
|
||||
JsonResponse,
|
||||
Outcome,
|
||||
RemoteFile,
|
||||
TaskKind,
|
||||
)
|
||||
from python_pkg.wsg_grabber.states import FileState
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Iterator
|
||||
from pathlib import Path
|
||||
|
||||
_MD5 = "Nz9OEKdMuMZEdYE6eLTKmA=="
|
||||
_BODY = b"video bytes"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def deps(tmp_path: Path) -> Iterator[downloader.WorkerDeps]:
|
||||
"""Build worker dependencies backed by a sandboxed index.
|
||||
|
||||
Args:
|
||||
tmp_path: Per-test temporary directory.
|
||||
|
||||
Yields:
|
||||
downloader.WorkerDeps: Ready dependencies; resources closed after.
|
||||
"""
|
||||
incoming = tmp_path / "incoming"
|
||||
incoming.mkdir()
|
||||
conn = db.open_index(tmp_path / "index.db")
|
||||
session = MagicMock()
|
||||
built = downloader.WorkerDeps(
|
||||
conn=conn,
|
||||
session=session,
|
||||
incoming=incoming,
|
||||
events=queue.SimpleQueue(),
|
||||
stop=threading.Event(),
|
||||
include_archive=False,
|
||||
)
|
||||
try:
|
||||
yield built
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def _json(
|
||||
payload: object,
|
||||
*,
|
||||
last_modified: str | None = None,
|
||||
not_modified: bool = False,
|
||||
not_found: bool = False,
|
||||
) -> JsonResponse:
|
||||
"""Build a JsonResponse with sensible defaults.
|
||||
|
||||
Args:
|
||||
payload: Decoded body.
|
||||
last_modified: Header value the response carried.
|
||||
not_modified: Whether the server answered 304.
|
||||
not_found: Whether the thread has gone.
|
||||
|
||||
Returns:
|
||||
JsonResponse: Response double.
|
||||
"""
|
||||
return JsonResponse(
|
||||
payload=payload,
|
||||
last_modified=last_modified,
|
||||
not_modified=not_modified,
|
||||
not_found=not_found,
|
||||
)
|
||||
|
||||
|
||||
def _remote(md5: str = _MD5, tim: int = 1) -> RemoteFile:
|
||||
"""Build a RemoteFile.
|
||||
|
||||
Args:
|
||||
md5: Identity.
|
||||
tim: CDN stem.
|
||||
|
||||
Returns:
|
||||
RemoteFile: Fixture value.
|
||||
"""
|
||||
return RemoteFile(
|
||||
md5=md5,
|
||||
tim=tim,
|
||||
ext=".webm",
|
||||
orig_name="clip",
|
||||
fsize=len(_BODY),
|
||||
width=480,
|
||||
height=360,
|
||||
thread_no=7,
|
||||
post_no=tim,
|
||||
)
|
||||
|
||||
|
||||
def _drain(events: queue.SimpleQueue[DownloadEvent]) -> list[DownloadEvent]:
|
||||
"""Pull everything currently queued.
|
||||
|
||||
Args:
|
||||
events: Queue to empty.
|
||||
|
||||
Returns:
|
||||
list[DownloadEvent]: Events in order.
|
||||
"""
|
||||
out: list[DownloadEvent] = []
|
||||
while not events.empty():
|
||||
out.append(events.get_nowait())
|
||||
return out
|
||||
|
||||
|
||||
def test_a_completed_download_is_renamed_and_announced(
|
||||
deps: downloader.WorkerDeps,
|
||||
) -> None:
|
||||
worker = downloader.Worker(deps)
|
||||
store.record_files(deps.conn, [_remote()])
|
||||
|
||||
def fake_download(_session: object, transfer: net.Transfer) -> DownloadResult:
|
||||
transfer.part_path.write_bytes(_BODY)
|
||||
return DownloadResult(outcome=Outcome.COMPLETED, bytes_done=len(_BODY))
|
||||
|
||||
with patch.object(net, "download", side_effect=fake_download):
|
||||
assert worker.run_once() is TaskKind.DOWNLOAD
|
||||
|
||||
events = _drain(deps.events)
|
||||
ready = [event for event in events if isinstance(event, FileReady)]
|
||||
assert len(ready) == 1
|
||||
assert ready[0].item.md5 == _MD5
|
||||
assert ready[0].item.path.exists()
|
||||
assert not ready[0].item.path.name.endswith(".part")
|
||||
assert ready[0].item.orig_name == "clip.webm"
|
||||
assert any(isinstance(event, Downloaded) for event in events)
|
||||
assert worker.downloaded == 1
|
||||
assert store.counts(deps.conn)[FileState.READY.value] == 1
|
||||
|
||||
|
||||
def test_a_404_is_terminal_and_never_retried(deps: downloader.WorkerDeps) -> None:
|
||||
"""This is what stops a fallen-off thread being re-fetched every run."""
|
||||
worker = downloader.Worker(deps)
|
||||
store.record_files(deps.conn, [_remote()])
|
||||
with patch.object(
|
||||
net,
|
||||
"download",
|
||||
return_value=DownloadResult(outcome=Outcome.NOT_FOUND, bytes_done=0),
|
||||
):
|
||||
worker.run_once()
|
||||
assert store.counts(deps.conn)[FileState.GONE.value] == 1
|
||||
assert store.pending_downloads(deps.conn) == 0
|
||||
@ -8,19 +8,24 @@ from __future__ import annotations
|
||||
|
||||
import queue
|
||||
import threading
|
||||
from typing import TYPE_CHECKING
|
||||
import time
|
||||
from typing import TYPE_CHECKING, cast
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from python_pkg.wsg_grabber import db, downloader, net, store
|
||||
from python_pkg.wsg_grabber import db, downloader, net, store, store_threads
|
||||
from python_pkg.wsg_grabber.constants import IDLE_RESCAN_S, THREADS_URL
|
||||
from python_pkg.wsg_grabber.models import (
|
||||
DownloadEvent,
|
||||
DownloadResult,
|
||||
JsonResponse,
|
||||
Outcome,
|
||||
RemoteFile,
|
||||
ScanFinished,
|
||||
TaskKind,
|
||||
ThreadRef,
|
||||
WorkerFailed,
|
||||
)
|
||||
from python_pkg.wsg_grabber.states import FileState
|
||||
|
||||
@ -177,3 +182,152 @@ def test_an_already_downloaded_file_survives_upstream_deletion(
|
||||
with patch.object(net, "get_json", return_value=_json(thread)):
|
||||
worker._fetch_thread(ThreadRef(7, 100))
|
||||
assert store.state_of(deps.conn, _MD5) is FileState.READY
|
||||
|
||||
|
||||
def test_idle_announces_completion_exactly_once(
|
||||
deps: downloader.WorkerDeps,
|
||||
) -> None:
|
||||
worker = downloader.Worker(deps)
|
||||
with patch.object(net, "get_json", return_value=_json([])):
|
||||
worker.run_once()
|
||||
with patch.object(deps.stop, "wait"):
|
||||
assert worker.run_once() is TaskKind.IDLE
|
||||
assert worker.run_once() is TaskKind.IDLE
|
||||
finished = [e for e in _drain(deps.events) if isinstance(e, ScanFinished)]
|
||||
assert len(finished) == 1
|
||||
|
||||
|
||||
def test_the_board_is_rescanned_after_the_quiet_period(
|
||||
deps: downloader.WorkerDeps,
|
||||
) -> None:
|
||||
"""A finished sweep goes quiet, then polls again for new content."""
|
||||
worker = downloader.Worker(deps)
|
||||
with patch.object(net, "get_json", return_value=_json([])):
|
||||
worker.run_once()
|
||||
with patch.object(deps.stop, "wait"):
|
||||
assert worker.run_once() is TaskKind.IDLE
|
||||
with patch(
|
||||
"python_pkg.wsg_grabber.downloader.time.monotonic",
|
||||
return_value=time.monotonic() + IDLE_RESCAN_S + 1,
|
||||
):
|
||||
assert worker.run_once() is TaskKind.IDLE
|
||||
# the quiet period has elapsed, so the next step walks the board again
|
||||
assert worker.run_once() is TaskKind.SCAN
|
||||
finished = [e for e in _drain(deps.events) if isinstance(e, ScanFinished)]
|
||||
assert len(finished) == 1
|
||||
|
||||
|
||||
def test_rate_limiting_waits_between_requests(
|
||||
deps: downloader.WorkerDeps,
|
||||
) -> None:
|
||||
worker = downloader.Worker(deps)
|
||||
listing = [{"threads": [{"no": 7, "last_modified": 100}]}]
|
||||
with (
|
||||
patch.object(
|
||||
net,
|
||||
"get_json",
|
||||
side_effect=[_json(listing), _json({"posts": []})],
|
||||
),
|
||||
patch.object(deps.stop, "wait") as waited,
|
||||
):
|
||||
worker.run_once() # the first request is free
|
||||
worker.run_once() # the second must be spaced out
|
||||
delays = [call.args[0] for call in waited.call_args_list if call.args]
|
||||
assert delays
|
||||
assert max(delays) <= 1.0
|
||||
|
||||
|
||||
def test_run_reports_a_crash_and_closes_resources(
|
||||
deps: downloader.WorkerDeps,
|
||||
) -> None:
|
||||
worker = downloader.Worker(deps)
|
||||
with patch.object(worker, "run_once", side_effect=RuntimeError("kaput")):
|
||||
worker.run()
|
||||
events = _drain(deps.events)
|
||||
assert any(
|
||||
isinstance(event, WorkerFailed) and event.message == "kaput" for event in events
|
||||
)
|
||||
cast("MagicMock", deps.session).close.assert_called_once()
|
||||
|
||||
|
||||
def test_run_exits_cleanly_when_stopped(deps: downloader.WorkerDeps) -> None:
|
||||
deps.stop.set()
|
||||
worker = downloader.Worker(deps)
|
||||
worker.run()
|
||||
assert _drain(deps.events) == []
|
||||
cast("MagicMock", deps.session).close.assert_called_once()
|
||||
|
||||
|
||||
@pytest.mark.timeout(10)
|
||||
def test_start_runs_and_joins_a_real_thread(tmp_path: Path) -> None:
|
||||
"""The one test that starts a thread; it must stop on demand."""
|
||||
incoming = tmp_path / "incoming"
|
||||
incoming.mkdir()
|
||||
stop = threading.Event()
|
||||
stop.set()
|
||||
|
||||
def build() -> downloader.WorkerDeps:
|
||||
"""Open the connection on the worker thread, which must own it."""
|
||||
return downloader.WorkerDeps(
|
||||
conn=db.open_index(tmp_path / "index.db"),
|
||||
session=MagicMock(),
|
||||
incoming=incoming,
|
||||
events=queue.SimpleQueue(),
|
||||
stop=stop,
|
||||
include_archive=False,
|
||||
)
|
||||
|
||||
thread = downloader.start(build)
|
||||
thread.join(timeout=5)
|
||||
assert not thread.is_alive()
|
||||
|
||||
|
||||
def test_the_board_endpoints_are_fetched_conditionally(
|
||||
deps: downloader.WorkerDeps,
|
||||
) -> None:
|
||||
"""Without this an idle reviewer re-fetches the board unconditionally forever."""
|
||||
deps.include_archive = True
|
||||
worker = downloader.Worker(deps)
|
||||
stamp = "Mon, 27 Jul 2026 10:00:00 GMT"
|
||||
with patch.object(
|
||||
net,
|
||||
"get_json",
|
||||
return_value=_json([], last_modified=stamp),
|
||||
) as fake:
|
||||
worker.run_once()
|
||||
sent_first = [call.args[2] for call in fake.call_args_list]
|
||||
worker._catalog_fresh = False
|
||||
fake.reset_mock()
|
||||
worker.run_once()
|
||||
sent_again = [call.args[2] for call in fake.call_args_list]
|
||||
|
||||
assert sent_first == [None, None] # nothing stored yet
|
||||
assert sent_again == [stamp, stamp] # the stamp goes back
|
||||
|
||||
|
||||
def test_a_304_on_the_board_keeps_the_stored_stamp(
|
||||
deps: downloader.WorkerDeps,
|
||||
) -> None:
|
||||
worker = downloader.Worker(deps)
|
||||
stamp = "Mon, 27 Jul 2026 10:00:00 GMT"
|
||||
with patch.object(net, "get_json", return_value=_json([], last_modified=stamp)):
|
||||
worker.run_once()
|
||||
with patch.object(net, "get_json", return_value=_json(None, not_modified=True)):
|
||||
worker._catalog_fresh = False
|
||||
worker.run_once()
|
||||
assert store_threads.cached_last_modified(deps.conn, THREADS_URL) == stamp
|
||||
|
||||
|
||||
def test_a_worker_that_cannot_build_its_resources_reports_it(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""Otherwise the reviewer waits on downloads that will never come."""
|
||||
reported: list[str] = []
|
||||
thread = downloader.start(
|
||||
lambda: (_ for _ in ()).throw(OSError("no database")),
|
||||
reported.append,
|
||||
)
|
||||
thread.join(timeout=5)
|
||||
assert not thread.is_alive()
|
||||
assert reported
|
||||
assert "no database" in reported[0]
|
||||
|
||||
@ -1,193 +0,0 @@
|
||||
"""Tests for retrying and resuming interrupted downloads."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import queue
|
||||
import threading
|
||||
from typing import TYPE_CHECKING
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from python_pkg.wsg_grabber import db, downloader, net, store
|
||||
from python_pkg.wsg_grabber.models import (
|
||||
DownloadEvent,
|
||||
DownloadResult,
|
||||
JsonResponse,
|
||||
Outcome,
|
||||
RemoteFile,
|
||||
)
|
||||
from python_pkg.wsg_grabber.states import FileState
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Iterator
|
||||
from pathlib import Path
|
||||
|
||||
_MD5 = "Nz9OEKdMuMZEdYE6eLTKmA=="
|
||||
_BODY = b"video bytes"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def deps(tmp_path: Path) -> Iterator[downloader.WorkerDeps]:
|
||||
"""Build worker dependencies backed by a sandboxed index.
|
||||
|
||||
Args:
|
||||
tmp_path: Per-test temporary directory.
|
||||
|
||||
Yields:
|
||||
downloader.WorkerDeps: Ready dependencies; resources closed after.
|
||||
"""
|
||||
incoming = tmp_path / "incoming"
|
||||
incoming.mkdir()
|
||||
conn = db.open_index(tmp_path / "index.db")
|
||||
session = MagicMock()
|
||||
built = downloader.WorkerDeps(
|
||||
conn=conn,
|
||||
session=session,
|
||||
incoming=incoming,
|
||||
events=queue.SimpleQueue(),
|
||||
stop=threading.Event(),
|
||||
include_archive=False,
|
||||
)
|
||||
try:
|
||||
yield built
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def _json(
|
||||
payload: object,
|
||||
*,
|
||||
last_modified: str | None = None,
|
||||
not_modified: bool = False,
|
||||
not_found: bool = False,
|
||||
) -> JsonResponse:
|
||||
"""Build a JsonResponse with sensible defaults.
|
||||
|
||||
Args:
|
||||
payload: Decoded body.
|
||||
last_modified: Header value the response carried.
|
||||
not_modified: Whether the server answered 304.
|
||||
not_found: Whether the thread has gone.
|
||||
|
||||
Returns:
|
||||
JsonResponse: Response double.
|
||||
"""
|
||||
return JsonResponse(
|
||||
payload=payload,
|
||||
last_modified=last_modified,
|
||||
not_modified=not_modified,
|
||||
not_found=not_found,
|
||||
)
|
||||
|
||||
|
||||
def _remote(md5: str = _MD5, tim: int = 1) -> RemoteFile:
|
||||
"""Build a RemoteFile.
|
||||
|
||||
Args:
|
||||
md5: Identity.
|
||||
tim: CDN stem.
|
||||
|
||||
Returns:
|
||||
RemoteFile: Fixture value.
|
||||
"""
|
||||
return RemoteFile(
|
||||
md5=md5,
|
||||
tim=tim,
|
||||
ext=".webm",
|
||||
orig_name="clip",
|
||||
fsize=len(_BODY),
|
||||
width=480,
|
||||
height=360,
|
||||
thread_no=7,
|
||||
post_no=tim,
|
||||
)
|
||||
|
||||
|
||||
def _drain(events: queue.SimpleQueue[DownloadEvent]) -> list[DownloadEvent]:
|
||||
"""Pull everything currently queued.
|
||||
|
||||
Args:
|
||||
events: Queue to empty.
|
||||
|
||||
Returns:
|
||||
list[DownloadEvent]: Events in order.
|
||||
"""
|
||||
out: list[DownloadEvent] = []
|
||||
while not events.empty():
|
||||
out.append(events.get_nowait())
|
||||
return out
|
||||
|
||||
|
||||
def test_a_transient_failure_is_retried(deps: downloader.WorkerDeps) -> None:
|
||||
worker = downloader.Worker(deps)
|
||||
store.record_files(deps.conn, [_remote()])
|
||||
with patch.object(
|
||||
net,
|
||||
"download",
|
||||
return_value=DownloadResult(outcome=Outcome.TRANSIENT, bytes_done=0),
|
||||
):
|
||||
worker.run_once()
|
||||
assert store.counts(deps.conn)[FileState.FAILED.value] == 1
|
||||
assert store.pending_downloads(deps.conn) == 1
|
||||
|
||||
|
||||
def test_a_transient_failure_gives_up_after_the_attempt_budget(
|
||||
deps: downloader.WorkerDeps,
|
||||
) -> None:
|
||||
worker = downloader.Worker(deps)
|
||||
store.record_files(deps.conn, [_remote()])
|
||||
with patch.object(
|
||||
net,
|
||||
"download",
|
||||
return_value=DownloadResult(outcome=Outcome.TRANSIENT, bytes_done=0),
|
||||
):
|
||||
for _ in range(3):
|
||||
worker.run_once()
|
||||
assert store.counts(deps.conn)[FileState.GONE.value] == 1
|
||||
|
||||
|
||||
def test_a_retry_after_pauses_the_worker(deps: downloader.WorkerDeps) -> None:
|
||||
worker = downloader.Worker(deps)
|
||||
store.record_files(deps.conn, [_remote()])
|
||||
with (
|
||||
patch.object(
|
||||
net,
|
||||
"download",
|
||||
return_value=DownloadResult(
|
||||
outcome=Outcome.TRANSIENT,
|
||||
bytes_done=0,
|
||||
retry_after=5.0,
|
||||
),
|
||||
),
|
||||
patch.object(deps.stop, "wait") as waited,
|
||||
):
|
||||
worker.run_once()
|
||||
assert any(call.args and call.args[0] == 5.0 for call in waited.call_args_list)
|
||||
|
||||
|
||||
def test_a_checksum_mismatch_marks_the_file_corrupt(
|
||||
deps: downloader.WorkerDeps,
|
||||
) -> None:
|
||||
worker = downloader.Worker(deps)
|
||||
store.record_files(deps.conn, [_remote()])
|
||||
with patch.object(
|
||||
net,
|
||||
"download",
|
||||
return_value=DownloadResult(outcome=Outcome.CHECKSUM_MISMATCH, bytes_done=0),
|
||||
):
|
||||
worker.run_once()
|
||||
assert store.counts(deps.conn)[FileState.CORRUPT.value] == 1
|
||||
|
||||
|
||||
def test_an_aborted_download_stays_resumable(deps: downloader.WorkerDeps) -> None:
|
||||
worker = downloader.Worker(deps)
|
||||
store.record_files(deps.conn, [_remote()])
|
||||
with patch.object(
|
||||
net,
|
||||
"download",
|
||||
return_value=DownloadResult(outcome=Outcome.ABORTED, bytes_done=4),
|
||||
):
|
||||
worker.run_once()
|
||||
assert store.counts(deps.conn)[FileState.FAILED.value] == 1
|
||||
assert store.pending_downloads(deps.conn) == 1
|
||||
@ -248,3 +248,123 @@ def test_a_server_ignoring_range_restarts_rather_than_appending(
|
||||
result = net.download(session, transfer)
|
||||
assert result.outcome is Outcome.COMPLETED
|
||||
assert part.read_bytes() == _BODY
|
||||
|
||||
|
||||
def test_an_oversized_leftover_is_discarded_before_requesting(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
part = tmp_path / "1.webm.part"
|
||||
part.write_bytes(b"x" * 9999)
|
||||
session = MagicMock()
|
||||
session.get.return_value = _response(200, body=_BODY)
|
||||
transfer = net.Transfer(
|
||||
url="https://i.4cdn.org/wsg/1.webm",
|
||||
part_path=part,
|
||||
expected_md5=net.digest_of(_BODY),
|
||||
expected_size=len(_BODY),
|
||||
should_stop=lambda: False,
|
||||
)
|
||||
result = net.download(session, transfer)
|
||||
assert "Range" not in session.get.call_args.kwargs["headers"]
|
||||
assert result.outcome is Outcome.COMPLETED
|
||||
|
||||
|
||||
def test_a_rejected_range_restarts_from_zero(tmp_path: Path) -> None:
|
||||
part = tmp_path / "1.webm.part"
|
||||
part.write_bytes(_BODY[:100])
|
||||
session = MagicMock()
|
||||
session.get.return_value = _response(416)
|
||||
transfer = net.Transfer(
|
||||
url="https://i.4cdn.org/wsg/1.webm",
|
||||
part_path=part,
|
||||
expected_md5=net.digest_of(_BODY),
|
||||
expected_size=len(_BODY),
|
||||
should_stop=lambda: False,
|
||||
)
|
||||
result = net.download(session, transfer)
|
||||
assert result.outcome is Outcome.TRANSIENT
|
||||
assert not part.exists()
|
||||
|
||||
|
||||
def test_shutdown_aborts_mid_stream_and_keeps_the_partial(tmp_path: Path) -> None:
|
||||
"""Stopping must be immediate and must leave a resumable .part behind."""
|
||||
session = MagicMock()
|
||||
response = _response(200)
|
||||
response.iter_content.return_value = [b"a" * 10, b"b" * 10, b"c" * 10]
|
||||
session.get.return_value = response
|
||||
transfer = net.Transfer(
|
||||
url="https://i.4cdn.org/wsg/1.webm",
|
||||
part_path=tmp_path / "1.webm.part",
|
||||
expected_md5="whatever" + "=" * 16,
|
||||
expected_size=30,
|
||||
should_stop=lambda: True,
|
||||
)
|
||||
result = net.download(session, transfer)
|
||||
assert result.outcome is Outcome.ABORTED
|
||||
|
||||
|
||||
def test_empty_chunks_are_skipped(tmp_path: Path) -> None:
|
||||
"""requests yields keep-alive chunks; they must not corrupt the digest."""
|
||||
session = MagicMock()
|
||||
response = _response(200)
|
||||
response.iter_content.return_value = [b"", _BODY, b""]
|
||||
session.get.return_value = response
|
||||
result = net.download(session, _transfer(tmp_path))
|
||||
assert result.outcome is Outcome.COMPLETED
|
||||
|
||||
|
||||
def test_size_of_missing_file_is_zero(tmp_path: Path) -> None:
|
||||
assert net.size_of(tmp_path / "nope") == 0
|
||||
|
||||
|
||||
def test_a_compressed_body_is_refused(tmp_path: Path) -> None:
|
||||
"""We ask for identity; requests would silently expand a gzip bomb."""
|
||||
session = MagicMock()
|
||||
session.get.return_value = _response(
|
||||
200,
|
||||
body=_BODY,
|
||||
headers={"Content-Encoding": "gzip"},
|
||||
)
|
||||
result = net.download(session, _transfer(tmp_path))
|
||||
assert result.outcome is Outcome.TRANSIENT
|
||||
assert result.message is not None
|
||||
assert "Content-Encoding" in result.message
|
||||
|
||||
|
||||
def test_a_body_larger_than_advertised_is_abandoned(tmp_path: Path) -> None:
|
||||
"""A server that lies about its size must not fill the disk."""
|
||||
session = MagicMock()
|
||||
response = _response(200)
|
||||
response.iter_content.return_value = [b"x" * (1024 * 1024)] * 4
|
||||
session.get.return_value = response
|
||||
transfer = net.Transfer(
|
||||
url="https://i.4cdn.org/wsg/1.webm",
|
||||
part_path=tmp_path / "1.webm.part",
|
||||
expected_md5=net.digest_of(_BODY),
|
||||
expected_size=16,
|
||||
should_stop=lambda: False,
|
||||
)
|
||||
result = net.download(session, transfer)
|
||||
assert result.outcome is Outcome.TRANSIENT
|
||||
assert not transfer.part_path.exists()
|
||||
|
||||
|
||||
def test_an_unknown_size_is_not_treated_as_over_budget(tmp_path: Path) -> None:
|
||||
"""fsize 0 means the API did not say; that must not block the download."""
|
||||
session = MagicMock()
|
||||
session.get.return_value = _response(200, body=_BODY)
|
||||
result = net.download(session, _transfer(tmp_path, size=0))
|
||||
assert result.outcome is Outcome.COMPLETED
|
||||
|
||||
|
||||
def test_an_oversized_api_response_is_refused() -> None:
|
||||
session = MagicMock()
|
||||
response = _response(200)
|
||||
response.content = b"[" + b"1," * 20_000_000 + b"1]"
|
||||
session.get.return_value = response
|
||||
with pytest.raises(ValueError, match="exceeded"):
|
||||
net.get_json(session, "https://a.4cdn.org/wsg/threads.json")
|
||||
|
||||
|
||||
def test_the_api_session_refuses_compression() -> None:
|
||||
assert API_HEADERS["Accept-Encoding"] == "identity"
|
||||
|
||||
@ -1,184 +0,0 @@
|
||||
"""Tests for resuming and discarding partial downloads."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from python_pkg.wsg_grabber import net
|
||||
from python_pkg.wsg_grabber.constants import API_HEADERS
|
||||
from python_pkg.wsg_grabber.models import Outcome
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
_BODY = b"fake webm bytes, but real bytes" * 40
|
||||
|
||||
|
||||
def _response(
|
||||
status: int = 200,
|
||||
*,
|
||||
body: bytes = b"",
|
||||
headers: dict[str, str] | None = None,
|
||||
text: str = "",
|
||||
) -> MagicMock:
|
||||
"""Build a stand-in for a requests Response.
|
||||
|
||||
Args:
|
||||
status: HTTP status code.
|
||||
body: Payload streamed by ``iter_content``.
|
||||
headers: Response headers.
|
||||
text: Body for JSON decoding.
|
||||
|
||||
Returns:
|
||||
MagicMock: Response double.
|
||||
"""
|
||||
response = MagicMock()
|
||||
response.status_code = status
|
||||
response.headers = headers or {}
|
||||
response.text = text
|
||||
response.content = text.encode("utf-8")
|
||||
response.iter_content.return_value = [body] if body else []
|
||||
return response
|
||||
|
||||
|
||||
def _transfer(tmp_path: Path, *, md5: str | None = None, size: int = 0) -> net.Transfer:
|
||||
"""Build a Transfer pointing at a sandboxed part file.
|
||||
|
||||
Args:
|
||||
tmp_path: Per-test temporary directory.
|
||||
md5: Expected digest; defaults to the real digest of ``_BODY``.
|
||||
size: Expected file size.
|
||||
|
||||
Returns:
|
||||
net.Transfer: Transfer description.
|
||||
"""
|
||||
return net.Transfer(
|
||||
url="https://i.4cdn.org/wsg/1.webm",
|
||||
part_path=tmp_path / "1.webm.part",
|
||||
expected_md5=md5 if md5 is not None else net.digest_of(_BODY),
|
||||
expected_size=size,
|
||||
should_stop=lambda: False,
|
||||
)
|
||||
|
||||
|
||||
def test_an_oversized_leftover_is_discarded_before_requesting(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
part = tmp_path / "1.webm.part"
|
||||
part.write_bytes(b"x" * 9999)
|
||||
session = MagicMock()
|
||||
session.get.return_value = _response(200, body=_BODY)
|
||||
transfer = net.Transfer(
|
||||
url="https://i.4cdn.org/wsg/1.webm",
|
||||
part_path=part,
|
||||
expected_md5=net.digest_of(_BODY),
|
||||
expected_size=len(_BODY),
|
||||
should_stop=lambda: False,
|
||||
)
|
||||
result = net.download(session, transfer)
|
||||
assert "Range" not in session.get.call_args.kwargs["headers"]
|
||||
assert result.outcome is Outcome.COMPLETED
|
||||
|
||||
|
||||
def test_a_rejected_range_restarts_from_zero(tmp_path: Path) -> None:
|
||||
part = tmp_path / "1.webm.part"
|
||||
part.write_bytes(_BODY[:100])
|
||||
session = MagicMock()
|
||||
session.get.return_value = _response(416)
|
||||
transfer = net.Transfer(
|
||||
url="https://i.4cdn.org/wsg/1.webm",
|
||||
part_path=part,
|
||||
expected_md5=net.digest_of(_BODY),
|
||||
expected_size=len(_BODY),
|
||||
should_stop=lambda: False,
|
||||
)
|
||||
result = net.download(session, transfer)
|
||||
assert result.outcome is Outcome.TRANSIENT
|
||||
assert not part.exists()
|
||||
|
||||
|
||||
def test_shutdown_aborts_mid_stream_and_keeps_the_partial(tmp_path: Path) -> None:
|
||||
"""Stopping must be immediate and must leave a resumable .part behind."""
|
||||
session = MagicMock()
|
||||
response = _response(200)
|
||||
response.iter_content.return_value = [b"a" * 10, b"b" * 10, b"c" * 10]
|
||||
session.get.return_value = response
|
||||
transfer = net.Transfer(
|
||||
url="https://i.4cdn.org/wsg/1.webm",
|
||||
part_path=tmp_path / "1.webm.part",
|
||||
expected_md5="whatever" + "=" * 16,
|
||||
expected_size=30,
|
||||
should_stop=lambda: True,
|
||||
)
|
||||
result = net.download(session, transfer)
|
||||
assert result.outcome is Outcome.ABORTED
|
||||
|
||||
|
||||
def test_empty_chunks_are_skipped(tmp_path: Path) -> None:
|
||||
"""requests yields keep-alive chunks; they must not corrupt the digest."""
|
||||
session = MagicMock()
|
||||
response = _response(200)
|
||||
response.iter_content.return_value = [b"", _BODY, b""]
|
||||
session.get.return_value = response
|
||||
result = net.download(session, _transfer(tmp_path))
|
||||
assert result.outcome is Outcome.COMPLETED
|
||||
|
||||
|
||||
def test_size_of_missing_file_is_zero(tmp_path: Path) -> None:
|
||||
assert net.size_of(tmp_path / "nope") == 0
|
||||
|
||||
|
||||
def test_a_compressed_body_is_refused(tmp_path: Path) -> None:
|
||||
"""We ask for identity; requests would silently expand a gzip bomb."""
|
||||
session = MagicMock()
|
||||
session.get.return_value = _response(
|
||||
200,
|
||||
body=_BODY,
|
||||
headers={"Content-Encoding": "gzip"},
|
||||
)
|
||||
result = net.download(session, _transfer(tmp_path))
|
||||
assert result.outcome is Outcome.TRANSIENT
|
||||
assert result.message is not None
|
||||
assert "Content-Encoding" in result.message
|
||||
|
||||
|
||||
def test_a_body_larger_than_advertised_is_abandoned(tmp_path: Path) -> None:
|
||||
"""A server that lies about its size must not fill the disk."""
|
||||
session = MagicMock()
|
||||
response = _response(200)
|
||||
response.iter_content.return_value = [b"x" * (1024 * 1024)] * 4
|
||||
session.get.return_value = response
|
||||
transfer = net.Transfer(
|
||||
url="https://i.4cdn.org/wsg/1.webm",
|
||||
part_path=tmp_path / "1.webm.part",
|
||||
expected_md5=net.digest_of(_BODY),
|
||||
expected_size=16,
|
||||
should_stop=lambda: False,
|
||||
)
|
||||
result = net.download(session, transfer)
|
||||
assert result.outcome is Outcome.TRANSIENT
|
||||
assert not transfer.part_path.exists()
|
||||
|
||||
|
||||
def test_an_unknown_size_is_not_treated_as_over_budget(tmp_path: Path) -> None:
|
||||
"""fsize 0 means the API did not say; that must not block the download."""
|
||||
session = MagicMock()
|
||||
session.get.return_value = _response(200, body=_BODY)
|
||||
result = net.download(session, _transfer(tmp_path, size=0))
|
||||
assert result.outcome is Outcome.COMPLETED
|
||||
|
||||
|
||||
def test_an_oversized_api_response_is_refused() -> None:
|
||||
session = MagicMock()
|
||||
response = _response(200)
|
||||
response.content = b"[" + b"1," * 20_000_000 + b"1]"
|
||||
session.get.return_value = response
|
||||
with pytest.raises(ValueError, match="exceeded"):
|
||||
net.get_json(session, "https://a.4cdn.org/wsg/threads.json")
|
||||
|
||||
|
||||
def test_the_api_session_refuses_compression() -> None:
|
||||
assert API_HEADERS["Accept-Encoding"] == "identity"
|
||||
@ -14,7 +14,7 @@ from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from python_pkg.wsg_grabber import player
|
||||
from python_pkg.wsg_grabber import logs, player
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Iterator
|
||||
@ -227,3 +227,247 @@ def test_the_player_never_sets_geometry() -> None:
|
||||
argv = player.build_argv(1, Path("sock"))
|
||||
assert not any(arg.startswith("--geometry") for arg in argv)
|
||||
assert not hasattr(player.MpvPlayer, "resize")
|
||||
|
||||
|
||||
def test_probe_reports_what_mpv_is_doing(
|
||||
started: tuple[player.MpvPlayer, MagicMock, MagicMock],
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""The answer that settles a 'it froze on one video' report."""
|
||||
mpv, _process, _sock = started
|
||||
reply = _socket_mock()
|
||||
reply.recv.return_value = (
|
||||
b'{"request_id": 9001, "data": "value", "error": "success"}\n'
|
||||
)
|
||||
reply.__enter__ = lambda self: self
|
||||
reply.__exit__ = lambda *_a: False
|
||||
with patch("python_pkg.wsg_grabber.player.socket.socket", return_value=reply):
|
||||
result = mpv.probe()
|
||||
assert set(result) == {
|
||||
"path",
|
||||
"pause",
|
||||
"core-idle",
|
||||
"eof-reached",
|
||||
"playback-time",
|
||||
"width",
|
||||
"height",
|
||||
}
|
||||
assert result["path"] == "value"
|
||||
|
||||
|
||||
def test_probe_records_a_failure_rather_than_raising(
|
||||
started: tuple[player.MpvPlayer, MagicMock, MagicMock],
|
||||
) -> None:
|
||||
mpv, _process, _sock = started
|
||||
with patch(
|
||||
"python_pkg.wsg_grabber.player.socket.socket",
|
||||
side_effect=ConnectionRefusedError("gone"),
|
||||
):
|
||||
result = mpv.probe()
|
||||
assert all(str(value).startswith("error:") for value in result.values())
|
||||
|
||||
|
||||
def test_probe_survives_a_socket_that_closes_early(
|
||||
started: tuple[player.MpvPlayer, MagicMock, MagicMock],
|
||||
) -> None:
|
||||
mpv, _process, _sock = started
|
||||
reply = _socket_mock()
|
||||
reply.recv.return_value = b""
|
||||
reply.__enter__ = lambda self: self
|
||||
reply.__exit__ = lambda *_a: False
|
||||
with patch("python_pkg.wsg_grabber.player.socket.socket", return_value=reply):
|
||||
result = mpv.probe()
|
||||
assert result["path"] == "error: socket closed"
|
||||
|
||||
|
||||
def test_probe_ignores_unrelated_traffic_on_the_socket(
|
||||
started: tuple[player.MpvPlayer, MagicMock, MagicMock],
|
||||
) -> None:
|
||||
"""mpv pushes async events down the socket; they must not be mistaken
|
||||
for the reply, and a partial line must not crash the reader."""
|
||||
mpv, _process, _sock = started
|
||||
reply = _socket_mock()
|
||||
reply.recv.side_effect = [
|
||||
b'{"event": "property-change"}\nnot json\n',
|
||||
b'{"request_id": 9001, "data": 42}\n',
|
||||
] * 10
|
||||
reply.__enter__ = lambda self: self
|
||||
reply.__exit__ = lambda *_a: False
|
||||
with patch("python_pkg.wsg_grabber.player.socket.socket", return_value=reply):
|
||||
assert mpv.probe()["path"] == 42
|
||||
|
||||
|
||||
def test_a_failed_send_is_logged_not_swallowed(
|
||||
started: tuple[player.MpvPlayer, MagicMock, MagicMock],
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""A dead socket must not make a frozen reviewer look like a working one."""
|
||||
mpv, _process, sock = started
|
||||
sock.sendall.side_effect = BrokenPipeError("gone")
|
||||
log = logs.start("debug")
|
||||
try:
|
||||
mpv.play(tmp_path / "clip.webm")
|
||||
finally:
|
||||
logs.stop()
|
||||
recorded = [
|
||||
json.loads(line)
|
||||
for line in log.read_text(encoding="utf-8").splitlines()
|
||||
if line
|
||||
]
|
||||
assert any(r["event"] == "player.send_failed" for r in recorded)
|
||||
assert any(r["level"] == "error" for r in recorded)
|
||||
|
||||
|
||||
def test_the_socket_is_drained_so_mpv_keeps_accepting_commands(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""The regression that made the reviewer freeze on one video.
|
||||
|
||||
mpv pushes events down the same socket; a client that never reads lets the
|
||||
buffer fill, at which point mpv stops reading commands while still looking
|
||||
perfectly alive.
|
||||
"""
|
||||
ipc = tmp_path / "mpv.sock"
|
||||
process = MagicMock()
|
||||
process.poll.return_value = None
|
||||
sock = _socket_mock()
|
||||
seen: list[int] = []
|
||||
|
||||
def recv(size: int) -> bytes:
|
||||
seen.append(size)
|
||||
return b'{"event":"property-change"}\n' if len(seen) < 3 else b""
|
||||
|
||||
sock.recv.side_effect = recv
|
||||
|
||||
with (
|
||||
patch("python_pkg.wsg_grabber.player.subprocess.Popen", return_value=process),
|
||||
patch("python_pkg.wsg_grabber.player.socket.socket", return_value=sock),
|
||||
patch(
|
||||
"python_pkg.wsg_grabber.player.time.sleep",
|
||||
side_effect=lambda _s: ipc.write_bytes(b""),
|
||||
),
|
||||
):
|
||||
mpv = player.MpvPlayer(1, ipc)
|
||||
mpv._reader.join(timeout=5)
|
||||
mpv.close()
|
||||
|
||||
assert seen, "the reader never read from the socket"
|
||||
assert not mpv._reader.is_alive()
|
||||
|
||||
|
||||
def test_the_reader_stops_on_a_socket_error(tmp_path: Path) -> None:
|
||||
ipc = tmp_path / "mpv.sock"
|
||||
process = MagicMock()
|
||||
process.poll.return_value = None
|
||||
sock = _socket_mock()
|
||||
sock.recv.side_effect = ConnectionResetError("gone")
|
||||
with (
|
||||
patch("python_pkg.wsg_grabber.player.subprocess.Popen", return_value=process),
|
||||
patch("python_pkg.wsg_grabber.player.socket.socket", return_value=sock),
|
||||
patch(
|
||||
"python_pkg.wsg_grabber.player.time.sleep",
|
||||
side_effect=lambda _s: ipc.write_bytes(b""),
|
||||
),
|
||||
):
|
||||
mpv = player.MpvPlayer(1, ipc)
|
||||
mpv._reader.join(timeout=5)
|
||||
assert not mpv._reader.is_alive()
|
||||
mpv.close()
|
||||
|
||||
|
||||
def test_the_reader_keeps_going_through_read_timeouts(tmp_path: Path) -> None:
|
||||
"""A quiet socket must not be mistaken for a closed one."""
|
||||
ipc = tmp_path / "mpv.sock"
|
||||
process = MagicMock()
|
||||
process.poll.return_value = None
|
||||
sock = _socket_mock()
|
||||
calls = {"n": 0}
|
||||
|
||||
def recv(_size: int) -> bytes:
|
||||
calls["n"] += 1
|
||||
if calls["n"] < 3:
|
||||
raise TimeoutError
|
||||
return b""
|
||||
|
||||
sock.recv.side_effect = recv
|
||||
with (
|
||||
patch("python_pkg.wsg_grabber.player.subprocess.Popen", return_value=process),
|
||||
patch("python_pkg.wsg_grabber.player.socket.socket", return_value=sock),
|
||||
patch(
|
||||
"python_pkg.wsg_grabber.player.time.sleep",
|
||||
side_effect=lambda _s: ipc.write_bytes(b""),
|
||||
),
|
||||
):
|
||||
mpv = player.MpvPlayer(1, ipc)
|
||||
mpv._reader.join(timeout=5)
|
||||
mpv.close()
|
||||
assert calls["n"] >= 3
|
||||
|
||||
|
||||
def test_mpv_errors_are_logged_rather_than_discarded(
|
||||
started: tuple[player.MpvPlayer, MagicMock, MagicMock],
|
||||
) -> None:
|
||||
"""A file mpv cannot decode should be visible, not just look stuck."""
|
||||
mpv, _process, _sock = started
|
||||
log = logs.start("debug")
|
||||
try:
|
||||
mpv._note_errors(
|
||||
b'{"error":"success"}\n'
|
||||
b"\n"
|
||||
b"garbage\n"
|
||||
b'{"request_id":1,"error":"loadfile failed"}\n',
|
||||
)
|
||||
finally:
|
||||
logs.stop()
|
||||
recorded = [
|
||||
json.loads(line)
|
||||
for line in log.read_text(encoding="utf-8").splitlines()
|
||||
if line
|
||||
]
|
||||
failures = [r for r in recorded if r["event"] == "player.reply_error"]
|
||||
assert len(failures) == 1
|
||||
assert failures[0]["detail"] == "loadfile failed"
|
||||
|
||||
|
||||
def test_socket_stand_ins_always_report_eof() -> None:
|
||||
"""The contract that keeps the reader thread from becoming a busy loop.
|
||||
|
||||
A mock whose recv() returns a MagicMock is truthy and instant, so the drain
|
||||
loop spins and the mock's recorded-call list grows without bound -- 21 GB
|
||||
and an OOM kill, in the incident this guards against.
|
||||
"""
|
||||
assert _socket_mock().recv(65536) == b""
|
||||
|
||||
|
||||
def test_the_reader_returns_promptly_once_asked_to_stop(
|
||||
started: tuple[player.MpvPlayer, MagicMock, MagicMock],
|
||||
) -> None:
|
||||
"""Shutdown must not wait on another read."""
|
||||
mpv, _process, sock = started
|
||||
sock.recv.reset_mock()
|
||||
mpv._stopping.set()
|
||||
mpv._drain()
|
||||
sock.recv.assert_not_called()
|
||||
|
||||
|
||||
def test_a_refused_connection_does_not_leak_the_socket(tmp_path: Path) -> None:
|
||||
"""A stale socket file makes connect() fail; nothing may be left open."""
|
||||
ipc = tmp_path / "stale.sock"
|
||||
process = MagicMock()
|
||||
sock = _socket_mock()
|
||||
sock.connect.side_effect = ConnectionRefusedError("stale")
|
||||
|
||||
with (
|
||||
patch("python_pkg.wsg_grabber.player.subprocess.Popen", return_value=process),
|
||||
patch("python_pkg.wsg_grabber.player.socket.socket", return_value=sock),
|
||||
patch(
|
||||
"python_pkg.wsg_grabber.player.time.sleep",
|
||||
side_effect=lambda _s: ipc.write_bytes(b""),
|
||||
),
|
||||
pytest.raises(ConnectionRefusedError),
|
||||
):
|
||||
player.MpvPlayer(1, ipc)
|
||||
|
||||
sock.close.assert_called_once()
|
||||
process.kill.assert_called_once()
|
||||
process.wait.assert_called_once() # reaped, not left a zombie
|
||||
|
||||
@ -1,219 +0,0 @@
|
||||
"""Tests for how the player reports IPC failures."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import TYPE_CHECKING
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from python_pkg.wsg_grabber import logs, player
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Iterator
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def _socket_mock(**kwargs: object) -> MagicMock:
|
||||
"""Build a socket stand-in whose reader thread terminates immediately.
|
||||
|
||||
An unconfigured MagicMock returns a MagicMock from recv(), which is truthy
|
||||
and instant, so the drain loop spins as fast as the CPU allows -- and
|
||||
MagicMock records every call, so memory grows without bound. That once
|
||||
reached 21 GB and took the machine down, hence this helper: every socket
|
||||
mock yields EOF unless a test deliberately says otherwise.
|
||||
|
||||
Args:
|
||||
**kwargs: Attributes to set on the mock.
|
||||
|
||||
Returns:
|
||||
MagicMock: Socket double.
|
||||
"""
|
||||
sock = MagicMock()
|
||||
sock.recv.return_value = b""
|
||||
for name, value in kwargs.items():
|
||||
setattr(sock, name, value)
|
||||
return sock
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _safe_sockets() -> Iterator[None]:
|
||||
"""Stop a stray socket mock from turning the drain loop into a busy loop.
|
||||
|
||||
``MpvPlayer`` runs a reader thread that calls ``recv`` until EOF. An
|
||||
unconfigured MagicMock returns a MagicMock -- truthy, instant, and it
|
||||
records every call -- so the loop spins and memory grows without bound.
|
||||
That once reached 21 GB and OOM-killed the machine. Defaulting the module's
|
||||
socket factory to something that reports EOF means a test has to opt into
|
||||
the hazard deliberately.
|
||||
|
||||
Yields:
|
||||
None: Control returns to the test.
|
||||
"""
|
||||
with patch(
|
||||
"python_pkg.wsg_grabber.player.socket.socket",
|
||||
side_effect=lambda *_a, **_k: _socket_mock(),
|
||||
):
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def started(tmp_path: Path) -> Iterator[tuple[player.MpvPlayer, MagicMock, MagicMock]]:
|
||||
"""Construct an MpvPlayer with its process and socket mocked out.
|
||||
|
||||
Args:
|
||||
tmp_path: Per-test temporary directory.
|
||||
|
||||
Yields:
|
||||
tuple: The player, its process mock and its socket mock.
|
||||
"""
|
||||
ipc = tmp_path / "mpv.sock"
|
||||
process = MagicMock()
|
||||
process.poll.return_value = None
|
||||
sock = _socket_mock()
|
||||
|
||||
def create_socket(_seconds: float) -> None:
|
||||
"""Stand in for mpv finally creating its control socket."""
|
||||
ipc.write_bytes(b"")
|
||||
|
||||
# __init__ unlinks any stale socket first, so it has to appear *during*
|
||||
# the wait rather than being pre-created.
|
||||
with (
|
||||
patch("python_pkg.wsg_grabber.player.subprocess.Popen", return_value=process),
|
||||
patch("python_pkg.wsg_grabber.player.socket.socket", return_value=sock),
|
||||
patch("python_pkg.wsg_grabber.player.time.sleep", side_effect=create_socket),
|
||||
):
|
||||
yield player.MpvPlayer(1234, ipc), process, sock
|
||||
|
||||
|
||||
def test_a_failed_send_is_logged_not_swallowed(
|
||||
started: tuple[player.MpvPlayer, MagicMock, MagicMock],
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""A dead socket must not make a frozen reviewer look like a working one."""
|
||||
mpv, _process, sock = started
|
||||
sock.sendall.side_effect = BrokenPipeError("gone")
|
||||
log = logs.start("debug")
|
||||
try:
|
||||
mpv.play(tmp_path / "clip.webm")
|
||||
finally:
|
||||
logs.stop()
|
||||
recorded = [
|
||||
json.loads(line)
|
||||
for line in log.read_text(encoding="utf-8").splitlines()
|
||||
if line
|
||||
]
|
||||
assert any(r["event"] == "player.send_failed" for r in recorded)
|
||||
assert any(r["level"] == "error" for r in recorded)
|
||||
|
||||
|
||||
def test_the_socket_is_drained_so_mpv_keeps_accepting_commands(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""The regression that made the reviewer freeze on one video.
|
||||
|
||||
mpv pushes events down the same socket; a client that never reads lets the
|
||||
buffer fill, at which point mpv stops reading commands while still looking
|
||||
perfectly alive.
|
||||
"""
|
||||
ipc = tmp_path / "mpv.sock"
|
||||
process = MagicMock()
|
||||
process.poll.return_value = None
|
||||
sock = _socket_mock()
|
||||
seen: list[int] = []
|
||||
|
||||
def recv(size: int) -> bytes:
|
||||
seen.append(size)
|
||||
return b'{"event":"property-change"}\n' if len(seen) < 3 else b""
|
||||
|
||||
sock.recv.side_effect = recv
|
||||
|
||||
with (
|
||||
patch("python_pkg.wsg_grabber.player.subprocess.Popen", return_value=process),
|
||||
patch("python_pkg.wsg_grabber.player.socket.socket", return_value=sock),
|
||||
patch(
|
||||
"python_pkg.wsg_grabber.player.time.sleep",
|
||||
side_effect=lambda _s: ipc.write_bytes(b""),
|
||||
),
|
||||
):
|
||||
mpv = player.MpvPlayer(1, ipc)
|
||||
mpv._reader.join(timeout=5)
|
||||
mpv.close()
|
||||
|
||||
assert seen, "the reader never read from the socket"
|
||||
assert not mpv._reader.is_alive()
|
||||
|
||||
|
||||
def test_the_reader_stops_on_a_socket_error(tmp_path: Path) -> None:
|
||||
ipc = tmp_path / "mpv.sock"
|
||||
process = MagicMock()
|
||||
process.poll.return_value = None
|
||||
sock = _socket_mock()
|
||||
sock.recv.side_effect = ConnectionResetError("gone")
|
||||
with (
|
||||
patch("python_pkg.wsg_grabber.player.subprocess.Popen", return_value=process),
|
||||
patch("python_pkg.wsg_grabber.player.socket.socket", return_value=sock),
|
||||
patch(
|
||||
"python_pkg.wsg_grabber.player.time.sleep",
|
||||
side_effect=lambda _s: ipc.write_bytes(b""),
|
||||
),
|
||||
):
|
||||
mpv = player.MpvPlayer(1, ipc)
|
||||
mpv._reader.join(timeout=5)
|
||||
assert not mpv._reader.is_alive()
|
||||
mpv.close()
|
||||
|
||||
|
||||
def test_the_reader_keeps_going_through_read_timeouts(tmp_path: Path) -> None:
|
||||
"""A quiet socket must not be mistaken for a closed one."""
|
||||
ipc = tmp_path / "mpv.sock"
|
||||
process = MagicMock()
|
||||
process.poll.return_value = None
|
||||
sock = _socket_mock()
|
||||
calls = {"n": 0}
|
||||
|
||||
def recv(_size: int) -> bytes:
|
||||
calls["n"] += 1
|
||||
if calls["n"] < 3:
|
||||
raise TimeoutError
|
||||
return b""
|
||||
|
||||
sock.recv.side_effect = recv
|
||||
with (
|
||||
patch("python_pkg.wsg_grabber.player.subprocess.Popen", return_value=process),
|
||||
patch("python_pkg.wsg_grabber.player.socket.socket", return_value=sock),
|
||||
patch(
|
||||
"python_pkg.wsg_grabber.player.time.sleep",
|
||||
side_effect=lambda _s: ipc.write_bytes(b""),
|
||||
),
|
||||
):
|
||||
mpv = player.MpvPlayer(1, ipc)
|
||||
mpv._reader.join(timeout=5)
|
||||
mpv.close()
|
||||
assert calls["n"] >= 3
|
||||
|
||||
|
||||
def test_mpv_errors_are_logged_rather_than_discarded(
|
||||
started: tuple[player.MpvPlayer, MagicMock, MagicMock],
|
||||
) -> None:
|
||||
"""A file mpv cannot decode should be visible, not just look stuck."""
|
||||
mpv, _process, _sock = started
|
||||
log = logs.start("debug")
|
||||
try:
|
||||
mpv._note_errors(
|
||||
b'{"error":"success"}\n'
|
||||
b"\n"
|
||||
b"garbage\n"
|
||||
b'{"request_id":1,"error":"loadfile failed"}\n',
|
||||
)
|
||||
finally:
|
||||
logs.stop()
|
||||
recorded = [
|
||||
json.loads(line)
|
||||
for line in log.read_text(encoding="utf-8").splitlines()
|
||||
if line
|
||||
]
|
||||
failures = [r for r in recorded if r["event"] == "player.reply_error"]
|
||||
assert len(failures) == 1
|
||||
assert failures[0]["detail"] == "loadfile failed"
|
||||
@ -1,154 +0,0 @@
|
||||
"""Tests for probing what mpv is doing over its IPC socket."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from python_pkg.wsg_grabber import player
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Iterator
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def _socket_mock(**kwargs: object) -> MagicMock:
|
||||
"""Build a socket stand-in whose reader thread terminates immediately.
|
||||
|
||||
An unconfigured MagicMock returns a MagicMock from recv(), which is truthy
|
||||
and instant, so the drain loop spins as fast as the CPU allows -- and
|
||||
MagicMock records every call, so memory grows without bound. That once
|
||||
reached 21 GB and took the machine down, hence this helper: every socket
|
||||
mock yields EOF unless a test deliberately says otherwise.
|
||||
|
||||
Args:
|
||||
**kwargs: Attributes to set on the mock.
|
||||
|
||||
Returns:
|
||||
MagicMock: Socket double.
|
||||
"""
|
||||
sock = MagicMock()
|
||||
sock.recv.return_value = b""
|
||||
for name, value in kwargs.items():
|
||||
setattr(sock, name, value)
|
||||
return sock
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _safe_sockets() -> Iterator[None]:
|
||||
"""Stop a stray socket mock from turning the drain loop into a busy loop.
|
||||
|
||||
``MpvPlayer`` runs a reader thread that calls ``recv`` until EOF. An
|
||||
unconfigured MagicMock returns a MagicMock -- truthy, instant, and it
|
||||
records every call -- so the loop spins and memory grows without bound.
|
||||
That once reached 21 GB and OOM-killed the machine. Defaulting the module's
|
||||
socket factory to something that reports EOF means a test has to opt into
|
||||
the hazard deliberately.
|
||||
|
||||
Yields:
|
||||
None: Control returns to the test.
|
||||
"""
|
||||
with patch(
|
||||
"python_pkg.wsg_grabber.player.socket.socket",
|
||||
side_effect=lambda *_a, **_k: _socket_mock(),
|
||||
):
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def started(tmp_path: Path) -> Iterator[tuple[player.MpvPlayer, MagicMock, MagicMock]]:
|
||||
"""Construct an MpvPlayer with its process and socket mocked out.
|
||||
|
||||
Args:
|
||||
tmp_path: Per-test temporary directory.
|
||||
|
||||
Yields:
|
||||
tuple: The player, its process mock and its socket mock.
|
||||
"""
|
||||
ipc = tmp_path / "mpv.sock"
|
||||
process = MagicMock()
|
||||
process.poll.return_value = None
|
||||
sock = _socket_mock()
|
||||
|
||||
def create_socket(_seconds: float) -> None:
|
||||
"""Stand in for mpv finally creating its control socket."""
|
||||
ipc.write_bytes(b"")
|
||||
|
||||
# __init__ unlinks any stale socket first, so it has to appear *during*
|
||||
# the wait rather than being pre-created.
|
||||
with (
|
||||
patch("python_pkg.wsg_grabber.player.subprocess.Popen", return_value=process),
|
||||
patch("python_pkg.wsg_grabber.player.socket.socket", return_value=sock),
|
||||
patch("python_pkg.wsg_grabber.player.time.sleep", side_effect=create_socket),
|
||||
):
|
||||
yield player.MpvPlayer(1234, ipc), process, sock
|
||||
|
||||
|
||||
def test_probe_reports_what_mpv_is_doing(
|
||||
started: tuple[player.MpvPlayer, MagicMock, MagicMock],
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""The answer that settles a 'it froze on one video' report."""
|
||||
mpv, _process, _sock = started
|
||||
reply = _socket_mock()
|
||||
reply.recv.return_value = (
|
||||
b'{"request_id": 9001, "data": "value", "error": "success"}\n'
|
||||
)
|
||||
reply.__enter__ = lambda self: self
|
||||
reply.__exit__ = lambda *_a: False
|
||||
with patch("python_pkg.wsg_grabber.player.socket.socket", return_value=reply):
|
||||
result = mpv.probe()
|
||||
assert set(result) == {
|
||||
"path",
|
||||
"pause",
|
||||
"core-idle",
|
||||
"eof-reached",
|
||||
"playback-time",
|
||||
"width",
|
||||
"height",
|
||||
}
|
||||
assert result["path"] == "value"
|
||||
|
||||
|
||||
def test_probe_records_a_failure_rather_than_raising(
|
||||
started: tuple[player.MpvPlayer, MagicMock, MagicMock],
|
||||
) -> None:
|
||||
mpv, _process, _sock = started
|
||||
with patch(
|
||||
"python_pkg.wsg_grabber.player.socket.socket",
|
||||
side_effect=ConnectionRefusedError("gone"),
|
||||
):
|
||||
result = mpv.probe()
|
||||
assert all(str(value).startswith("error:") for value in result.values())
|
||||
|
||||
|
||||
def test_probe_survives_a_socket_that_closes_early(
|
||||
started: tuple[player.MpvPlayer, MagicMock, MagicMock],
|
||||
) -> None:
|
||||
mpv, _process, _sock = started
|
||||
reply = _socket_mock()
|
||||
reply.recv.return_value = b""
|
||||
reply.__enter__ = lambda self: self
|
||||
reply.__exit__ = lambda *_a: False
|
||||
with patch("python_pkg.wsg_grabber.player.socket.socket", return_value=reply):
|
||||
result = mpv.probe()
|
||||
assert result["path"] == "error: socket closed"
|
||||
|
||||
|
||||
def test_probe_ignores_unrelated_traffic_on_the_socket(
|
||||
started: tuple[player.MpvPlayer, MagicMock, MagicMock],
|
||||
) -> None:
|
||||
"""mpv pushes async events down the socket; they must not be mistaken
|
||||
for the reply, and a partial line must not crash the reader."""
|
||||
mpv, _process, _sock = started
|
||||
reply = _socket_mock()
|
||||
reply.recv.side_effect = [
|
||||
b'{"event": "property-change"}\nnot json\n',
|
||||
b'{"request_id": 9001, "data": 42}\n',
|
||||
] * 10
|
||||
reply.__enter__ = lambda self: self
|
||||
reply.__exit__ = lambda *_a: False
|
||||
with patch("python_pkg.wsg_grabber.player.socket.socket", return_value=reply):
|
||||
assert mpv.probe()["path"] == 42
|
||||
@ -1,130 +0,0 @@
|
||||
"""Tests for the socket stand-ins and connection teardown."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from python_pkg.wsg_grabber import player
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Iterator
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def _socket_mock(**kwargs: object) -> MagicMock:
|
||||
"""Build a socket stand-in whose reader thread terminates immediately.
|
||||
|
||||
An unconfigured MagicMock returns a MagicMock from recv(), which is truthy
|
||||
and instant, so the drain loop spins as fast as the CPU allows -- and
|
||||
MagicMock records every call, so memory grows without bound. That once
|
||||
reached 21 GB and took the machine down, hence this helper: every socket
|
||||
mock yields EOF unless a test deliberately says otherwise.
|
||||
|
||||
Args:
|
||||
**kwargs: Attributes to set on the mock.
|
||||
|
||||
Returns:
|
||||
MagicMock: Socket double.
|
||||
"""
|
||||
sock = MagicMock()
|
||||
sock.recv.return_value = b""
|
||||
for name, value in kwargs.items():
|
||||
setattr(sock, name, value)
|
||||
return sock
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _safe_sockets() -> Iterator[None]:
|
||||
"""Stop a stray socket mock from turning the drain loop into a busy loop.
|
||||
|
||||
``MpvPlayer`` runs a reader thread that calls ``recv`` until EOF. An
|
||||
unconfigured MagicMock returns a MagicMock -- truthy, instant, and it
|
||||
records every call -- so the loop spins and memory grows without bound.
|
||||
That once reached 21 GB and OOM-killed the machine. Defaulting the module's
|
||||
socket factory to something that reports EOF means a test has to opt into
|
||||
the hazard deliberately.
|
||||
|
||||
Yields:
|
||||
None: Control returns to the test.
|
||||
"""
|
||||
with patch(
|
||||
"python_pkg.wsg_grabber.player.socket.socket",
|
||||
side_effect=lambda *_a, **_k: _socket_mock(),
|
||||
):
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def started(tmp_path: Path) -> Iterator[tuple[player.MpvPlayer, MagicMock, MagicMock]]:
|
||||
"""Construct an MpvPlayer with its process and socket mocked out.
|
||||
|
||||
Args:
|
||||
tmp_path: Per-test temporary directory.
|
||||
|
||||
Yields:
|
||||
tuple: The player, its process mock and its socket mock.
|
||||
"""
|
||||
ipc = tmp_path / "mpv.sock"
|
||||
process = MagicMock()
|
||||
process.poll.return_value = None
|
||||
sock = _socket_mock()
|
||||
|
||||
def create_socket(_seconds: float) -> None:
|
||||
"""Stand in for mpv finally creating its control socket."""
|
||||
ipc.write_bytes(b"")
|
||||
|
||||
# __init__ unlinks any stale socket first, so it has to appear *during*
|
||||
# the wait rather than being pre-created.
|
||||
with (
|
||||
patch("python_pkg.wsg_grabber.player.subprocess.Popen", return_value=process),
|
||||
patch("python_pkg.wsg_grabber.player.socket.socket", return_value=sock),
|
||||
patch("python_pkg.wsg_grabber.player.time.sleep", side_effect=create_socket),
|
||||
):
|
||||
yield player.MpvPlayer(1234, ipc), process, sock
|
||||
|
||||
|
||||
def test_socket_stand_ins_always_report_eof() -> None:
|
||||
"""The contract that keeps the reader thread from becoming a busy loop.
|
||||
|
||||
A mock whose recv() returns a MagicMock is truthy and instant, so the drain
|
||||
loop spins and the mock's recorded-call list grows without bound -- 21 GB
|
||||
and an OOM kill, in the incident this guards against.
|
||||
"""
|
||||
assert _socket_mock().recv(65536) == b""
|
||||
|
||||
|
||||
def test_the_reader_returns_promptly_once_asked_to_stop(
|
||||
started: tuple[player.MpvPlayer, MagicMock, MagicMock],
|
||||
) -> None:
|
||||
"""Shutdown must not wait on another read."""
|
||||
mpv, _process, sock = started
|
||||
sock.recv.reset_mock()
|
||||
mpv._stopping.set()
|
||||
mpv._drain()
|
||||
sock.recv.assert_not_called()
|
||||
|
||||
|
||||
def test_a_refused_connection_does_not_leak_the_socket(tmp_path: Path) -> None:
|
||||
"""A stale socket file makes connect() fail; nothing may be left open."""
|
||||
ipc = tmp_path / "stale.sock"
|
||||
process = MagicMock()
|
||||
sock = _socket_mock()
|
||||
sock.connect.side_effect = ConnectionRefusedError("stale")
|
||||
|
||||
with (
|
||||
patch("python_pkg.wsg_grabber.player.subprocess.Popen", return_value=process),
|
||||
patch("python_pkg.wsg_grabber.player.socket.socket", return_value=sock),
|
||||
patch(
|
||||
"python_pkg.wsg_grabber.player.time.sleep",
|
||||
side_effect=lambda _s: ipc.write_bytes(b""),
|
||||
),
|
||||
pytest.raises(ConnectionRefusedError),
|
||||
):
|
||||
player.MpvPlayer(1, ipc)
|
||||
|
||||
sock.close.assert_called_once()
|
||||
process.kill.assert_called_once()
|
||||
process.wait.assert_called_once() # reaped, not left a zombie
|
||||
@ -24,6 +24,7 @@ from python_pkg.wsg_grabber.constants import (
|
||||
UNDO_KEYS,
|
||||
)
|
||||
from python_pkg.wsg_grabber.models import (
|
||||
ReviewCommand,
|
||||
ReviewedItem,
|
||||
ReviewItem,
|
||||
Verdict,
|
||||
@ -211,3 +212,242 @@ def test_the_buttons_call_the_same_handlers(
|
||||
window.attach_player(MagicMock())
|
||||
window.on_keep()
|
||||
assert recorder.commit.call_args.args[0] is Verdict.KEEP
|
||||
|
||||
|
||||
def test_apply_plays_and_labels(toolkit: MagicMock, tmp_path: Path) -> None:
|
||||
window, _ = _window(review.initial_state(0, []))
|
||||
player = MagicMock()
|
||||
window.attach_player(player)
|
||||
path = tmp_path / "x.webm"
|
||||
path.write_bytes(b"v")
|
||||
|
||||
window.apply(
|
||||
ReviewCommand(
|
||||
play=path,
|
||||
stop=False,
|
||||
status="status text",
|
||||
title="title text",
|
||||
filename="file text",
|
||||
verdicts_enabled=True,
|
||||
undo_enabled=False,
|
||||
quit_app=False,
|
||||
),
|
||||
)
|
||||
player.play.assert_called_once_with(path)
|
||||
_mock(window.widgets.status).configure.assert_called_with(text="status text")
|
||||
_mock(window.widgets.filename).configure.assert_called_with(text="file text")
|
||||
_mock(window.widgets.root).title.assert_called_with("title text")
|
||||
_mock(window.widgets.keep).configure.assert_called_with(state="normal")
|
||||
|
||||
|
||||
def test_the_same_video_is_only_loaded_once(
|
||||
toolkit: MagicMock,
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""refresh() runs every tick; re-sending loadfile restarts the video."""
|
||||
window, _ = _window(review.initial_state(1, [_item(tmp_path)]))
|
||||
player = MagicMock()
|
||||
window.attach_player(player)
|
||||
assert player.play.call_count == 1
|
||||
|
||||
for _ in range(10):
|
||||
window.tick()
|
||||
assert player.play.call_count == 1
|
||||
|
||||
|
||||
def test_advancing_loads_the_next_video(toolkit: MagicMock, tmp_path: Path) -> None:
|
||||
state = review.initial_state(2, [_item(tmp_path, "a"), _item(tmp_path, "b")])
|
||||
window, _ = _window(state)
|
||||
player = MagicMock()
|
||||
window.attach_player(player)
|
||||
window.on_keep()
|
||||
assert player.play.call_count == 2
|
||||
assert player.play.call_args.args[0].name == "b.webm"
|
||||
|
||||
|
||||
def test_stopping_lets_the_same_video_load_again(
|
||||
toolkit: MagicMock,
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
item = _item(tmp_path)
|
||||
window, _ = _window(review.initial_state(1, [item]))
|
||||
player = MagicMock()
|
||||
window.attach_player(player)
|
||||
window.apply(
|
||||
ReviewCommand(
|
||||
play=None,
|
||||
stop=True,
|
||||
status="s",
|
||||
title="t",
|
||||
filename="f",
|
||||
verdicts_enabled=False,
|
||||
undo_enabled=False,
|
||||
quit_app=False,
|
||||
),
|
||||
)
|
||||
player.stop.assert_called_once()
|
||||
window.refresh()
|
||||
assert player.play.call_count == 2
|
||||
|
||||
|
||||
def test_apply_stops_and_disables_when_idle(toolkit: MagicMock) -> None:
|
||||
window, _ = _window(review.initial_state(0, []))
|
||||
player = MagicMock()
|
||||
window.attach_player(player)
|
||||
window.apply(
|
||||
ReviewCommand(
|
||||
play=None,
|
||||
stop=True,
|
||||
status="s",
|
||||
title="t",
|
||||
filename="f",
|
||||
verdicts_enabled=False,
|
||||
undo_enabled=False,
|
||||
quit_app=False,
|
||||
),
|
||||
)
|
||||
# nothing was playing, so there is nothing to stop; the buttons still go dead
|
||||
player.stop.assert_not_called()
|
||||
_mock(window.widgets.keep).configure.assert_called_with(state="disabled")
|
||||
|
||||
|
||||
def test_apply_quits_when_told_to(toolkit: MagicMock) -> None:
|
||||
window, recorder = _window(review.initial_state(0, []))
|
||||
window.apply(
|
||||
ReviewCommand(
|
||||
play=None,
|
||||
stop=False,
|
||||
status="s",
|
||||
title="t",
|
||||
filename="f",
|
||||
verdicts_enabled=False,
|
||||
undo_enabled=False,
|
||||
quit_app=True,
|
||||
),
|
||||
)
|
||||
recorder.shutdown.assert_called_once()
|
||||
|
||||
|
||||
def test_playing_without_a_player_is_a_no_op(
|
||||
toolkit: MagicMock,
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
window, _ = _window(review.initial_state(1, [_item(tmp_path)]))
|
||||
window.refresh()
|
||||
|
||||
|
||||
def test_a_video_that_vanished_is_skipped(
|
||||
toolkit: MagicMock,
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""A file can disappear between download and review; don't hang on it."""
|
||||
first = _item(tmp_path, "a")
|
||||
state = review.initial_state(2, [first, _item(tmp_path, "b")])
|
||||
window, recorder = _window(state)
|
||||
first.path.unlink()
|
||||
player = MagicMock()
|
||||
window.attach_player(player)
|
||||
|
||||
recorder.missing.assert_called_once()
|
||||
assert window.state.current is not None
|
||||
assert window.state.current.md5 == "b-md5"
|
||||
|
||||
|
||||
def test_tick_drains_events_and_reschedules(toolkit: MagicMock) -> None:
|
||||
from python_pkg.wsg_grabber.models import Indexed
|
||||
|
||||
events: queue.SimpleQueue[DownloadEvent] = queue.SimpleQueue()
|
||||
events.put(Indexed(known=42))
|
||||
window, _ = _window(review.initial_state(0, []), events)
|
||||
window.tick()
|
||||
assert window.state.indexed == 42
|
||||
_mock(window.widgets.root).after.assert_called_once()
|
||||
assert _mock(window.widgets.root).after.call_args.args[1] == window.tick
|
||||
|
||||
|
||||
def test_drain_on_an_empty_queue_is_harmless(toolkit: MagicMock) -> None:
|
||||
window, _ = _window(review.initial_state(0, []))
|
||||
window.drain()
|
||||
assert window.state.indexed == 0
|
||||
|
||||
|
||||
def test_shutdown_cancels_the_tick_and_closes_the_player(
|
||||
toolkit: MagicMock,
|
||||
) -> None:
|
||||
"""A leaked after-callback or an orphan mpv would outlive the window."""
|
||||
window, recorder = _window(review.initial_state(0, []))
|
||||
player = MagicMock()
|
||||
window.attach_player(player)
|
||||
window.tick()
|
||||
window.shutdown()
|
||||
_mock(window.widgets.root).after_cancel.assert_called_once()
|
||||
player.close.assert_called_once()
|
||||
recorder.shutdown.assert_called_once()
|
||||
_mock(window.widgets.root).destroy.assert_called_once()
|
||||
|
||||
|
||||
def test_shutdown_without_a_pending_tick(toolkit: MagicMock) -> None:
|
||||
window, _ = _window(review.initial_state(0, []))
|
||||
window.shutdown()
|
||||
_mock(window.widgets.root).after_cancel.assert_not_called()
|
||||
|
||||
|
||||
def test_video_wid_realises_the_window_first(toolkit: MagicMock) -> None:
|
||||
window, _ = _window(review.initial_state(0, []))
|
||||
_mock(window.widgets.video).winfo_id.return_value = 4321
|
||||
assert window.video_wid() == 4321
|
||||
_mock(window.widgets.root).update.assert_called()
|
||||
|
||||
|
||||
def test_run_starts_ticking_then_enters_the_loop(toolkit: MagicMock) -> None:
|
||||
window, _ = _window(review.initial_state(0, []))
|
||||
window.run()
|
||||
_mock(window.widgets.root).mainloop.assert_called_once()
|
||||
_mock(window.widgets.root).after.assert_called_once()
|
||||
|
||||
|
||||
def test_undo_takes_back_the_last_verdict(
|
||||
toolkit: MagicMock,
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""The misclick case: passed something you meant to keep."""
|
||||
state = review.initial_state(2, [_item(tmp_path, "a"), _item(tmp_path, "b")])
|
||||
window, recorder = _window(state)
|
||||
player = MagicMock()
|
||||
window.attach_player(player)
|
||||
|
||||
window.on_pass()
|
||||
assert window.state.current is not None
|
||||
assert window.state.current.md5 == "b-md5"
|
||||
assert window.state.passed == 1
|
||||
|
||||
window.on_undo()
|
||||
recorder.undo.assert_called_once()
|
||||
assert window.state.current is not None
|
||||
assert window.state.current.md5 == "a-md5"
|
||||
assert window.state.passed == 0
|
||||
# and the video that was on screen is not lost
|
||||
assert [item.md5 for item in window.state.pending] == ["b-md5"]
|
||||
|
||||
|
||||
def test_the_undo_shortcut_is_wired(toolkit: MagicMock, tmp_path: Path) -> None:
|
||||
state = review.initial_state(1, [_item(tmp_path)])
|
||||
window, recorder = _window(state)
|
||||
window.attach_player(MagicMock())
|
||||
window.on_keep()
|
||||
bound = _mock(window.widgets.root).bind.call_args_list
|
||||
handlers = {call.args[0]: call.args[1] for call in bound}
|
||||
handlers[UNDO_KEYS[0]](object())
|
||||
recorder.undo.assert_called_once()
|
||||
|
||||
|
||||
def test_the_undo_button_is_disabled_until_there_is_something_to_undo(
|
||||
toolkit: MagicMock,
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
state = review.initial_state(1, [_item(tmp_path)])
|
||||
window, _ = _window(state)
|
||||
window.attach_player(MagicMock())
|
||||
assert _mock(window.widgets.undo).configure.call_args.kwargs["state"] == "disabled"
|
||||
window.on_keep()
|
||||
assert _mock(window.widgets.undo).configure.call_args.kwargs["state"] == "normal"
|
||||
|
||||
@ -1,204 +0,0 @@
|
||||
"""Tests for the review window when the queue runs dry."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import queue
|
||||
from typing import TYPE_CHECKING, cast
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from python_pkg.wsg_grabber import review, ui
|
||||
from python_pkg.wsg_grabber.models import (
|
||||
ReviewCommand,
|
||||
ReviewedItem,
|
||||
ReviewItem,
|
||||
Verdict,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Iterator
|
||||
from pathlib import Path
|
||||
|
||||
from python_pkg.wsg_grabber.models import DownloadEvent
|
||||
from python_pkg.wsg_grabber.review import SessionState
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def toolkit() -> Iterator[MagicMock]:
|
||||
"""Replace tkinter in the ui module's namespace.
|
||||
|
||||
Yields:
|
||||
MagicMock: The stand-in toolkit.
|
||||
"""
|
||||
fake = MagicMock()
|
||||
# a fresh mock per widget, else status and filename are the same object
|
||||
fake.Frame.side_effect = lambda *_a, **_k: MagicMock()
|
||||
fake.Label.side_effect = lambda *_a, **_k: MagicMock()
|
||||
fake.Button.side_effect = lambda *_a, **_k: MagicMock()
|
||||
fake.BOTH = "both"
|
||||
fake.X = "x"
|
||||
fake.LEFT = "left"
|
||||
fake.RIGHT = "right"
|
||||
fake.BOTTOM = "bottom"
|
||||
with patch.object(ui, "tk", fake):
|
||||
yield fake
|
||||
|
||||
|
||||
def _mock(widget: object) -> MagicMock:
|
||||
"""View a mocked widget as the MagicMock it really is.
|
||||
|
||||
The Widgets dataclass is typed with real Tk classes, so mypy will not let
|
||||
the tests reach ``call_args`` without this.
|
||||
|
||||
Args:
|
||||
widget: The stand-in widget.
|
||||
|
||||
Returns:
|
||||
MagicMock: The same object, typed for assertions.
|
||||
"""
|
||||
return cast("MagicMock", widget)
|
||||
|
||||
|
||||
def _item(tmp_path: Path, name: str = "a") -> ReviewItem:
|
||||
"""Build a ReviewItem backed by a real file.
|
||||
|
||||
Args:
|
||||
tmp_path: Per-test temporary directory.
|
||||
name: Distinguishes items.
|
||||
|
||||
Returns:
|
||||
ReviewItem: Fixture value.
|
||||
"""
|
||||
path = tmp_path / f"{name}.webm"
|
||||
path.write_bytes(b"video")
|
||||
return ReviewItem(
|
||||
md5=f"{name}-md5",
|
||||
path=path,
|
||||
orig_name=f"{name}.webm",
|
||||
fsize=5,
|
||||
width=4,
|
||||
height=3,
|
||||
)
|
||||
|
||||
|
||||
def _callbacks() -> tuple[ui.Callbacks, MagicMock]:
|
||||
"""Build callbacks that record what the window asked for.
|
||||
|
||||
Returns:
|
||||
tuple: The callbacks and the recorder behind them.
|
||||
"""
|
||||
recorder = MagicMock()
|
||||
_undone: dict[str, ReviewedItem | None] = {"item": None}
|
||||
|
||||
def commit(state: SessionState, choice: Verdict) -> SessionState:
|
||||
recorder.commit(choice)
|
||||
if state.current is not None:
|
||||
_undone["item"] = ReviewedItem(
|
||||
item=state.current,
|
||||
choice=choice,
|
||||
reviewed_name=state.current.path.name,
|
||||
)
|
||||
return review.on_verdict(state, choice)
|
||||
|
||||
def missing(state: SessionState) -> SessionState:
|
||||
recorder.missing()
|
||||
return review.on_missing_locally(state)
|
||||
|
||||
def undo(state: SessionState) -> SessionState:
|
||||
recorder.undo()
|
||||
action = _undone["item"]
|
||||
if action is None or not review.can_undo(state):
|
||||
return state
|
||||
return review.on_undo(state, action)
|
||||
|
||||
return (
|
||||
ui.Callbacks(
|
||||
commit=commit,
|
||||
missing=missing,
|
||||
undo=undo,
|
||||
shutdown=recorder.shutdown,
|
||||
),
|
||||
recorder,
|
||||
)
|
||||
|
||||
|
||||
def _window(
|
||||
state: SessionState,
|
||||
events: queue.SimpleQueue[DownloadEvent] | None = None,
|
||||
) -> tuple[ui.ReviewWindow, MagicMock]:
|
||||
"""Build a window over a mocked toolkit.
|
||||
|
||||
Args:
|
||||
state: Starting state.
|
||||
events: Optional event queue.
|
||||
|
||||
Returns:
|
||||
tuple: The window and the callback recorder.
|
||||
"""
|
||||
callbacks, recorder = _callbacks()
|
||||
window = ui.ReviewWindow(state, events or queue.SimpleQueue(), callbacks)
|
||||
return window, recorder
|
||||
|
||||
|
||||
def test_apply_stops_and_disables_when_idle(toolkit: MagicMock) -> None:
|
||||
window, _ = _window(review.initial_state(0, []))
|
||||
player = MagicMock()
|
||||
window.attach_player(player)
|
||||
window.apply(
|
||||
ReviewCommand(
|
||||
play=None,
|
||||
stop=True,
|
||||
status="s",
|
||||
title="t",
|
||||
filename="f",
|
||||
verdicts_enabled=False,
|
||||
undo_enabled=False,
|
||||
quit_app=False,
|
||||
),
|
||||
)
|
||||
# nothing was playing, so there is nothing to stop; the buttons still go dead
|
||||
player.stop.assert_not_called()
|
||||
_mock(window.widgets.keep).configure.assert_called_with(state="disabled")
|
||||
|
||||
|
||||
def test_apply_quits_when_told_to(toolkit: MagicMock) -> None:
|
||||
window, recorder = _window(review.initial_state(0, []))
|
||||
window.apply(
|
||||
ReviewCommand(
|
||||
play=None,
|
||||
stop=False,
|
||||
status="s",
|
||||
title="t",
|
||||
filename="f",
|
||||
verdicts_enabled=False,
|
||||
undo_enabled=False,
|
||||
quit_app=True,
|
||||
),
|
||||
)
|
||||
recorder.shutdown.assert_called_once()
|
||||
|
||||
|
||||
def test_playing_without_a_player_is_a_no_op(
|
||||
toolkit: MagicMock,
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
window, _ = _window(review.initial_state(1, [_item(tmp_path)]))
|
||||
window.refresh()
|
||||
|
||||
|
||||
def test_a_video_that_vanished_is_skipped(
|
||||
toolkit: MagicMock,
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""A file can disappear between download and review; don't hang on it."""
|
||||
first = _item(tmp_path, "a")
|
||||
state = review.initial_state(2, [first, _item(tmp_path, "b")])
|
||||
window, recorder = _window(state)
|
||||
first.path.unlink()
|
||||
player = MagicMock()
|
||||
window.attach_player(player)
|
||||
|
||||
recorder.missing.assert_called_once()
|
||||
assert window.state.current is not None
|
||||
assert window.state.current.md5 == "b-md5"
|
||||
@ -1,217 +0,0 @@
|
||||
"""Tests for the review window's playback and advance behaviour."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import queue
|
||||
from typing import TYPE_CHECKING, cast
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from python_pkg.wsg_grabber import review, ui
|
||||
from python_pkg.wsg_grabber.models import (
|
||||
ReviewCommand,
|
||||
ReviewedItem,
|
||||
ReviewItem,
|
||||
Verdict,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Iterator
|
||||
from pathlib import Path
|
||||
|
||||
from python_pkg.wsg_grabber.models import DownloadEvent
|
||||
from python_pkg.wsg_grabber.review import SessionState
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def toolkit() -> Iterator[MagicMock]:
|
||||
"""Replace tkinter in the ui module's namespace.
|
||||
|
||||
Yields:
|
||||
MagicMock: The stand-in toolkit.
|
||||
"""
|
||||
fake = MagicMock()
|
||||
# a fresh mock per widget, else status and filename are the same object
|
||||
fake.Frame.side_effect = lambda *_a, **_k: MagicMock()
|
||||
fake.Label.side_effect = lambda *_a, **_k: MagicMock()
|
||||
fake.Button.side_effect = lambda *_a, **_k: MagicMock()
|
||||
fake.BOTH = "both"
|
||||
fake.X = "x"
|
||||
fake.LEFT = "left"
|
||||
fake.RIGHT = "right"
|
||||
fake.BOTTOM = "bottom"
|
||||
with patch.object(ui, "tk", fake):
|
||||
yield fake
|
||||
|
||||
|
||||
def _mock(widget: object) -> MagicMock:
|
||||
"""View a mocked widget as the MagicMock it really is.
|
||||
|
||||
The Widgets dataclass is typed with real Tk classes, so mypy will not let
|
||||
the tests reach ``call_args`` without this.
|
||||
|
||||
Args:
|
||||
widget: The stand-in widget.
|
||||
|
||||
Returns:
|
||||
MagicMock: The same object, typed for assertions.
|
||||
"""
|
||||
return cast("MagicMock", widget)
|
||||
|
||||
|
||||
def _item(tmp_path: Path, name: str = "a") -> ReviewItem:
|
||||
"""Build a ReviewItem backed by a real file.
|
||||
|
||||
Args:
|
||||
tmp_path: Per-test temporary directory.
|
||||
name: Distinguishes items.
|
||||
|
||||
Returns:
|
||||
ReviewItem: Fixture value.
|
||||
"""
|
||||
path = tmp_path / f"{name}.webm"
|
||||
path.write_bytes(b"video")
|
||||
return ReviewItem(
|
||||
md5=f"{name}-md5",
|
||||
path=path,
|
||||
orig_name=f"{name}.webm",
|
||||
fsize=5,
|
||||
width=4,
|
||||
height=3,
|
||||
)
|
||||
|
||||
|
||||
def _callbacks() -> tuple[ui.Callbacks, MagicMock]:
|
||||
"""Build callbacks that record what the window asked for.
|
||||
|
||||
Returns:
|
||||
tuple: The callbacks and the recorder behind them.
|
||||
"""
|
||||
recorder = MagicMock()
|
||||
_undone: dict[str, ReviewedItem | None] = {"item": None}
|
||||
|
||||
def commit(state: SessionState, choice: Verdict) -> SessionState:
|
||||
recorder.commit(choice)
|
||||
if state.current is not None:
|
||||
_undone["item"] = ReviewedItem(
|
||||
item=state.current,
|
||||
choice=choice,
|
||||
reviewed_name=state.current.path.name,
|
||||
)
|
||||
return review.on_verdict(state, choice)
|
||||
|
||||
def missing(state: SessionState) -> SessionState:
|
||||
recorder.missing()
|
||||
return review.on_missing_locally(state)
|
||||
|
||||
def undo(state: SessionState) -> SessionState:
|
||||
recorder.undo()
|
||||
action = _undone["item"]
|
||||
if action is None or not review.can_undo(state):
|
||||
return state
|
||||
return review.on_undo(state, action)
|
||||
|
||||
return (
|
||||
ui.Callbacks(
|
||||
commit=commit,
|
||||
missing=missing,
|
||||
undo=undo,
|
||||
shutdown=recorder.shutdown,
|
||||
),
|
||||
recorder,
|
||||
)
|
||||
|
||||
|
||||
def _window(
|
||||
state: SessionState,
|
||||
events: queue.SimpleQueue[DownloadEvent] | None = None,
|
||||
) -> tuple[ui.ReviewWindow, MagicMock]:
|
||||
"""Build a window over a mocked toolkit.
|
||||
|
||||
Args:
|
||||
state: Starting state.
|
||||
events: Optional event queue.
|
||||
|
||||
Returns:
|
||||
tuple: The window and the callback recorder.
|
||||
"""
|
||||
callbacks, recorder = _callbacks()
|
||||
window = ui.ReviewWindow(state, events or queue.SimpleQueue(), callbacks)
|
||||
return window, recorder
|
||||
|
||||
|
||||
def test_apply_plays_and_labels(toolkit: MagicMock, tmp_path: Path) -> None:
|
||||
window, _ = _window(review.initial_state(0, []))
|
||||
player = MagicMock()
|
||||
window.attach_player(player)
|
||||
path = tmp_path / "x.webm"
|
||||
path.write_bytes(b"v")
|
||||
|
||||
window.apply(
|
||||
ReviewCommand(
|
||||
play=path,
|
||||
stop=False,
|
||||
status="status text",
|
||||
title="title text",
|
||||
filename="file text",
|
||||
verdicts_enabled=True,
|
||||
undo_enabled=False,
|
||||
quit_app=False,
|
||||
),
|
||||
)
|
||||
player.play.assert_called_once_with(path)
|
||||
_mock(window.widgets.status).configure.assert_called_with(text="status text")
|
||||
_mock(window.widgets.filename).configure.assert_called_with(text="file text")
|
||||
_mock(window.widgets.root).title.assert_called_with("title text")
|
||||
_mock(window.widgets.keep).configure.assert_called_with(state="normal")
|
||||
|
||||
|
||||
def test_the_same_video_is_only_loaded_once(
|
||||
toolkit: MagicMock,
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""refresh() runs every tick; re-sending loadfile restarts the video."""
|
||||
window, _ = _window(review.initial_state(1, [_item(tmp_path)]))
|
||||
player = MagicMock()
|
||||
window.attach_player(player)
|
||||
assert player.play.call_count == 1
|
||||
|
||||
for _ in range(10):
|
||||
window.tick()
|
||||
assert player.play.call_count == 1
|
||||
|
||||
|
||||
def test_advancing_loads_the_next_video(toolkit: MagicMock, tmp_path: Path) -> None:
|
||||
state = review.initial_state(2, [_item(tmp_path, "a"), _item(tmp_path, "b")])
|
||||
window, _ = _window(state)
|
||||
player = MagicMock()
|
||||
window.attach_player(player)
|
||||
window.on_keep()
|
||||
assert player.play.call_count == 2
|
||||
assert player.play.call_args.args[0].name == "b.webm"
|
||||
|
||||
|
||||
def test_stopping_lets_the_same_video_load_again(
|
||||
toolkit: MagicMock,
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
item = _item(tmp_path)
|
||||
window, _ = _window(review.initial_state(1, [item]))
|
||||
player = MagicMock()
|
||||
window.attach_player(player)
|
||||
window.apply(
|
||||
ReviewCommand(
|
||||
play=None,
|
||||
stop=True,
|
||||
status="s",
|
||||
title="t",
|
||||
filename="f",
|
||||
verdicts_enabled=False,
|
||||
undo_enabled=False,
|
||||
quit_app=False,
|
||||
),
|
||||
)
|
||||
player.stop.assert_called_once()
|
||||
window.refresh()
|
||||
assert player.play.call_count == 2
|
||||
@ -1,243 +0,0 @@
|
||||
"""Tests for the window's event-drain tick and shutdown."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import queue
|
||||
from typing import TYPE_CHECKING, cast
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from python_pkg.wsg_grabber import review, ui
|
||||
from python_pkg.wsg_grabber.constants import (
|
||||
UNDO_KEYS,
|
||||
)
|
||||
from python_pkg.wsg_grabber.models import (
|
||||
ReviewedItem,
|
||||
ReviewItem,
|
||||
Verdict,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Iterator
|
||||
from pathlib import Path
|
||||
|
||||
from python_pkg.wsg_grabber.models import DownloadEvent
|
||||
from python_pkg.wsg_grabber.review import SessionState
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def toolkit() -> Iterator[MagicMock]:
|
||||
"""Replace tkinter in the ui module's namespace.
|
||||
|
||||
Yields:
|
||||
MagicMock: The stand-in toolkit.
|
||||
"""
|
||||
fake = MagicMock()
|
||||
# a fresh mock per widget, else status and filename are the same object
|
||||
fake.Frame.side_effect = lambda *_a, **_k: MagicMock()
|
||||
fake.Label.side_effect = lambda *_a, **_k: MagicMock()
|
||||
fake.Button.side_effect = lambda *_a, **_k: MagicMock()
|
||||
fake.BOTH = "both"
|
||||
fake.X = "x"
|
||||
fake.LEFT = "left"
|
||||
fake.RIGHT = "right"
|
||||
fake.BOTTOM = "bottom"
|
||||
with patch.object(ui, "tk", fake):
|
||||
yield fake
|
||||
|
||||
|
||||
def _mock(widget: object) -> MagicMock:
|
||||
"""View a mocked widget as the MagicMock it really is.
|
||||
|
||||
The Widgets dataclass is typed with real Tk classes, so mypy will not let
|
||||
the tests reach ``call_args`` without this.
|
||||
|
||||
Args:
|
||||
widget: The stand-in widget.
|
||||
|
||||
Returns:
|
||||
MagicMock: The same object, typed for assertions.
|
||||
"""
|
||||
return cast("MagicMock", widget)
|
||||
|
||||
|
||||
def _item(tmp_path: Path, name: str = "a") -> ReviewItem:
|
||||
"""Build a ReviewItem backed by a real file.
|
||||
|
||||
Args:
|
||||
tmp_path: Per-test temporary directory.
|
||||
name: Distinguishes items.
|
||||
|
||||
Returns:
|
||||
ReviewItem: Fixture value.
|
||||
"""
|
||||
path = tmp_path / f"{name}.webm"
|
||||
path.write_bytes(b"video")
|
||||
return ReviewItem(
|
||||
md5=f"{name}-md5",
|
||||
path=path,
|
||||
orig_name=f"{name}.webm",
|
||||
fsize=5,
|
||||
width=4,
|
||||
height=3,
|
||||
)
|
||||
|
||||
|
||||
def _callbacks() -> tuple[ui.Callbacks, MagicMock]:
|
||||
"""Build callbacks that record what the window asked for.
|
||||
|
||||
Returns:
|
||||
tuple: The callbacks and the recorder behind them.
|
||||
"""
|
||||
recorder = MagicMock()
|
||||
_undone: dict[str, ReviewedItem | None] = {"item": None}
|
||||
|
||||
def commit(state: SessionState, choice: Verdict) -> SessionState:
|
||||
recorder.commit(choice)
|
||||
if state.current is not None:
|
||||
_undone["item"] = ReviewedItem(
|
||||
item=state.current,
|
||||
choice=choice,
|
||||
reviewed_name=state.current.path.name,
|
||||
)
|
||||
return review.on_verdict(state, choice)
|
||||
|
||||
def missing(state: SessionState) -> SessionState:
|
||||
recorder.missing()
|
||||
return review.on_missing_locally(state)
|
||||
|
||||
def undo(state: SessionState) -> SessionState:
|
||||
recorder.undo()
|
||||
action = _undone["item"]
|
||||
if action is None or not review.can_undo(state):
|
||||
return state
|
||||
return review.on_undo(state, action)
|
||||
|
||||
return (
|
||||
ui.Callbacks(
|
||||
commit=commit,
|
||||
missing=missing,
|
||||
undo=undo,
|
||||
shutdown=recorder.shutdown,
|
||||
),
|
||||
recorder,
|
||||
)
|
||||
|
||||
|
||||
def _window(
|
||||
state: SessionState,
|
||||
events: queue.SimpleQueue[DownloadEvent] | None = None,
|
||||
) -> tuple[ui.ReviewWindow, MagicMock]:
|
||||
"""Build a window over a mocked toolkit.
|
||||
|
||||
Args:
|
||||
state: Starting state.
|
||||
events: Optional event queue.
|
||||
|
||||
Returns:
|
||||
tuple: The window and the callback recorder.
|
||||
"""
|
||||
callbacks, recorder = _callbacks()
|
||||
window = ui.ReviewWindow(state, events or queue.SimpleQueue(), callbacks)
|
||||
return window, recorder
|
||||
|
||||
|
||||
def test_tick_drains_events_and_reschedules(toolkit: MagicMock) -> None:
|
||||
from python_pkg.wsg_grabber.models import Indexed
|
||||
|
||||
events: queue.SimpleQueue[DownloadEvent] = queue.SimpleQueue()
|
||||
events.put(Indexed(known=42))
|
||||
window, _ = _window(review.initial_state(0, []), events)
|
||||
window.tick()
|
||||
assert window.state.indexed == 42
|
||||
_mock(window.widgets.root).after.assert_called_once()
|
||||
assert _mock(window.widgets.root).after.call_args.args[1] == window.tick
|
||||
|
||||
|
||||
def test_drain_on_an_empty_queue_is_harmless(toolkit: MagicMock) -> None:
|
||||
window, _ = _window(review.initial_state(0, []))
|
||||
window.drain()
|
||||
assert window.state.indexed == 0
|
||||
|
||||
|
||||
def test_shutdown_cancels_the_tick_and_closes_the_player(
|
||||
toolkit: MagicMock,
|
||||
) -> None:
|
||||
"""A leaked after-callback or an orphan mpv would outlive the window."""
|
||||
window, recorder = _window(review.initial_state(0, []))
|
||||
player = MagicMock()
|
||||
window.attach_player(player)
|
||||
window.tick()
|
||||
window.shutdown()
|
||||
_mock(window.widgets.root).after_cancel.assert_called_once()
|
||||
player.close.assert_called_once()
|
||||
recorder.shutdown.assert_called_once()
|
||||
_mock(window.widgets.root).destroy.assert_called_once()
|
||||
|
||||
|
||||
def test_shutdown_without_a_pending_tick(toolkit: MagicMock) -> None:
|
||||
window, _ = _window(review.initial_state(0, []))
|
||||
window.shutdown()
|
||||
_mock(window.widgets.root).after_cancel.assert_not_called()
|
||||
|
||||
|
||||
def test_video_wid_realises_the_window_first(toolkit: MagicMock) -> None:
|
||||
window, _ = _window(review.initial_state(0, []))
|
||||
_mock(window.widgets.video).winfo_id.return_value = 4321
|
||||
assert window.video_wid() == 4321
|
||||
_mock(window.widgets.root).update.assert_called()
|
||||
|
||||
|
||||
def test_run_starts_ticking_then_enters_the_loop(toolkit: MagicMock) -> None:
|
||||
window, _ = _window(review.initial_state(0, []))
|
||||
window.run()
|
||||
_mock(window.widgets.root).mainloop.assert_called_once()
|
||||
_mock(window.widgets.root).after.assert_called_once()
|
||||
|
||||
|
||||
def test_undo_takes_back_the_last_verdict(
|
||||
toolkit: MagicMock,
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""The misclick case: passed something you meant to keep."""
|
||||
state = review.initial_state(2, [_item(tmp_path, "a"), _item(tmp_path, "b")])
|
||||
window, recorder = _window(state)
|
||||
player = MagicMock()
|
||||
window.attach_player(player)
|
||||
|
||||
window.on_pass()
|
||||
assert window.state.current is not None
|
||||
assert window.state.current.md5 == "b-md5"
|
||||
assert window.state.passed == 1
|
||||
|
||||
window.on_undo()
|
||||
recorder.undo.assert_called_once()
|
||||
assert window.state.current is not None
|
||||
assert window.state.current.md5 == "a-md5"
|
||||
assert window.state.passed == 0
|
||||
# and the video that was on screen is not lost
|
||||
assert [item.md5 for item in window.state.pending] == ["b-md5"]
|
||||
|
||||
|
||||
def test_the_undo_shortcut_is_wired(toolkit: MagicMock, tmp_path: Path) -> None:
|
||||
state = review.initial_state(1, [_item(tmp_path)])
|
||||
window, recorder = _window(state)
|
||||
window.attach_player(MagicMock())
|
||||
window.on_keep()
|
||||
bound = _mock(window.widgets.root).bind.call_args_list
|
||||
handlers = {call.args[0]: call.args[1] for call in bound}
|
||||
handlers[UNDO_KEYS[0]](object())
|
||||
recorder.undo.assert_called_once()
|
||||
|
||||
|
||||
def test_the_undo_button_is_disabled_until_there_is_something_to_undo(
|
||||
toolkit: MagicMock,
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
state = review.initial_state(1, [_item(tmp_path)])
|
||||
window, _ = _window(state)
|
||||
window.attach_player(MagicMock())
|
||||
assert _mock(window.widgets.undo).configure.call_args.kwargs["state"] == "disabled"
|
||||
window.on_keep()
|
||||
assert _mock(window.widgets.undo).configure.call_args.kwargs["state"] == "normal"
|
||||
@ -6,45 +6,27 @@
|
||||
|
||||
## Where things stand
|
||||
|
||||
**142 files** over 250 lines (was 183). Everything is committed and pushed to
|
||||
`main` at `4b2cd0c`; the tree is clean.
|
||||
**183 files** over 250 lines (was 198). Everything is committed and pushed to
|
||||
`main` at `9e688c5`; the tree is clean. The three unrelated edits an earlier
|
||||
handoff warned about (`README.md`, the two `analysis_options.yaml`) are gone.
|
||||
|
||||
**`python_pkg/` is DONE — 50 violations → 0.** Do not reopen it. Cleared in
|
||||
this order, one package per tranche, pushing after each: `brother_printer`
|
||||
(15→0, suite pinned at 402), `code_tutor` (13→0, 216→217), then `android_ui`,
|
||||
`app_icons`, `token_audit`, `focus_policy`, `random_jpg` (57/44/81/137/14),
|
||||
then `wsg_grabber`'s six test modules (277).
|
||||
Done already (do not redo):
|
||||
|
||||
Earlier sessions had already done: the `~/utils` exemptions, the
|
||||
`no-inline-python` hook, `CLAUDE.md`, `poker-stakes/`, and every `wsg_grabber`
|
||||
**source** file.
|
||||
- `~/utils`: `plans/` + `sessions/` exempted from the cap (`specs/` still capped)
|
||||
- `17b20e5` new `no-inline-python` pre-commit hook + its one violation
|
||||
- `004b4b0` `CLAUDE.md` 259 → 141
|
||||
- `72a5e28` + `73b85f5` `poker-stakes/` tracked, then 4 violations → 0
|
||||
- `77c6d9f`…`d86965f` **every `wsg_grabber` source file** — `catalog` 251→175,
|
||||
`cli` 282→247, `review` 330→196, `net` 335→109, `store` 382→202,
|
||||
`downloader` 420→238, `player` 373→235, `ui` 398→242
|
||||
- `e03fbd1` `wsg_grabber/tests/test_review.py` 297 → 112 + two new modules
|
||||
- `2832b78` `brother_printer/display.py` 427 → 342 — **partial, still a
|
||||
violation.** Extracted `_supply.py` + `_severity.py` and deduped the
|
||||
toner/drum bars. The last ~92 lines were blocked on `mock.patch` pinning,
|
||||
which the decision below now unblocks.
|
||||
|
||||
`git log --oneline --grep='cap'` is the authoritative list.
|
||||
|
||||
## What is left
|
||||
|
||||
| Directory | Count |
|
||||
| ------------------------------------- | ------------ |
|
||||
| `linux_configuration` | 84 |
|
||||
| `phone_focus_mode` | 13 (do LAST) |
|
||||
| `kcd2_dice_solver` | 12 |
|
||||
| `focus_owner` | 11 |
|
||||
| `billsplit` | 6 |
|
||||
| `reverse_survivors` / `meta` / `docs` | 4 each |
|
||||
| `.github` / `bucket_catch` | 2 each |
|
||||
|
||||
Within `linux_configuration` the bulk is `scripts/single_use/` (39 across
|
||||
`features`/`utils`/`fixes`), then `scripts/periodic_background/` (10) and
|
||||
`tests/` (4).
|
||||
|
||||
## The seam-selection rule
|
||||
|
||||
Settled over eight `python_pkg` packages and written up in
|
||||
`docs/python-split-recipes.md` under "The seam-selection rule". In one line:
|
||||
**a block may move if every patch reaching it comes from one test module; if
|
||||
two modules patch a shared collaborator, keep the collaborator and move its
|
||||
callers.** Read the doc before splitting anything with tests.
|
||||
|
||||
## The live worklist
|
||||
|
||||
Do not work from a list in this file — it goes stale. Run:
|
||||
@ -54,14 +36,18 @@ bash ~/utils/scripts/check_file_length.sh --all
|
||||
```
|
||||
|
||||
**Every count in this file is a snapshot and will be wrong by the time you read
|
||||
it. Run the script.** The table above is a snapshot at `4b2cd0c`, quoted only
|
||||
to tell you where the bulk sits, never to work from.
|
||||
it. Run the script.** As of `ac02a23` the shape was `linux_configuration` 84,
|
||||
`python_pkg` 41, `phone_focus_mode` 13, `kcd2_dice_solver` 12, `focus_owner`
|
||||
11, `billsplit` 6, `reverse_survivors`/`meta`/`docs` 4 each,
|
||||
`.github`/`bucket_catch` 2 each — quoted only to tell you where the bulk sits,
|
||||
never to work from.
|
||||
|
||||
**Do the source files in a package before its tests.** Proven on `wsg_grabber`
|
||||
and again on all seven `python_pkg` packages: the test files then split along
|
||||
seams the source already established, instead of you inventing a new boundary
|
||||
for them. On `brother_printer` this meant four of the five source splits needed
|
||||
**no test edit at all**.
|
||||
Within `python_pkg`: `brother_printer` 15, `code_tutor` 13, `wsg_grabber` 6
|
||||
(tests only), then singles.
|
||||
|
||||
**Do the source files in a package before its tests.** Proven on `wsg_grabber`:
|
||||
the test files then split along seams the source already established, instead
|
||||
of you inventing a new boundary for them.
|
||||
|
||||
## Decisions already made (do not re-ask)
|
||||
|
||||
@ -82,14 +68,6 @@ for them. On `brother_printer` this meant four of the five source splits needed
|
||||
stalled on `brother_printer` because of it.
|
||||
9. Per-commit gate is `pre-commit run --files <changed>`; the real `git commit`
|
||||
is the full gate (it adds jscpd). Push per directory tranche, not per commit.
|
||||
10. **When a seam splits code covered by a per-file-ignore, fix the lint —
|
||||
do not copy the ignore onto the new file** (user's call, 2026-08-16).
|
||||
Done for `code_tutor/cli.py`: `S607` fixed with `shutil.which`, `PERF203`
|
||||
by extracting the probe so the poll loop carries no `try`/`except`. Both
|
||||
entries deleted from `meta/pyproject.toml`; the repo now has two fewer
|
||||
suppressions. The `which()` fix added a branch, so a covering test was
|
||||
written (216 → 217) rather than excluding it. Expect the same question on
|
||||
any remaining per-file-ignore you split through — ask, don't assume.
|
||||
|
||||
## The constraint that will bite you
|
||||
|
||||
@ -115,19 +93,13 @@ Plus `.github/workflows/file-length.yml` modelled on
|
||||
`.utils`), scoped to changed files. Then prove it fails: stage a deliberately
|
||||
251-line file, confirm `git commit` aborts, delete it.
|
||||
|
||||
## Language recipes
|
||||
## Python split recipes
|
||||
|
||||
- `docs/python-split-recipes.md` — the `__all__` re-export form, the `TC001`
|
||||
trap that lints clean and breaks at runtime, the mixin shape for splitting a
|
||||
class, what the tests pin in place, and the coverage behaviour of new sibling
|
||||
modules. `python_pkg` is done, so this now matters only if a stray `.py`
|
||||
turns up outside it.
|
||||
- `docs/shell-split-recipes.md` — **read this before the first
|
||||
`linux_configuration` split.** What replaces the pass count when there is no
|
||||
test suite, the two live systemd units that point at repo paths, and the
|
||||
jscpd trap on the first multi-lib commit.
|
||||
|
||||
Each rule in both cost a failed gate run or a revert to establish.
|
||||
`docs/python-split-recipes.md` holds the settled Python rules: the `__all__`
|
||||
re-export form, the `TC001` trap that lints clean and breaks at runtime, the
|
||||
mixin shape for splitting a class, what the tests pin in place, and the
|
||||
coverage behaviour of new sibling modules. **Read it before the first Python
|
||||
split** — each rule there cost a failed gate run or a revert to establish.
|
||||
|
||||
## Split recipes
|
||||
|
||||
|
||||
Loading…
Reference in New Issue
Block a user