Compare commits

..

5 Commits

Author SHA1 Message Date
9a205f3ab9 Prettier-format two docs blocking push
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
Pre-commit checks / pre-commit (${{ matrix.group }}) (mypy, mypy) (push) Waiting to run
Pre-commit checks / pre-commit (${{ matrix.group }}) (pylint, pylint) (push) Waiting to run
Pre-commit checks / pre-commit (${{ matrix.group }}) (rest, ) (push) Waiting to run
Pre-commit checks / pre-commit (${{ matrix.group }}) (shellcheck, shellcheck) (push) Waiting to run
Python tests / test (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Shell tests / shell-tests (push) Waiting to run
Shell tests / lib-tests (push) Waiting to run
Shell tests / arch-tests (push) Waiting to run
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWXdzckyBH7fEbPywpr
2026-11-02 09:11:24 +01:00
adc3f72b4b sql_drills: optional focus heartbeat
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWYcmik6APnHfc9gEVy
2026-11-02 08:24:46 +01:00
ac9b0b7e97 i3blocks: focus_project block (active project)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWYcmik6APnHfc9gEVy
2026-11-02 08:20:15 +01:00
aa1cce0a8c Narrow phone-focus TODO to live checks
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWVUTaKFW8m7YrvWbzV
2026-11-02 07:57:34 +01:00
d335a3c9f2 android_ui: add scroll-to, narrow TODO
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWVUTaKFW8m7YrvWbzV
2026-11-02 07:56:57 +01:00
19 changed files with 612 additions and 2067 deletions

View File

@ -0,0 +1,11 @@
{
"title": "android-ui scroll-to",
"objective": "AndroidUi.scroll_to and android-ui scroll-to find a widget outside the viewport, fail loudly at the end of the list, and keep ambiguity an error.",
"acceptance_criteria": [
"Visible element returns with no swipe",
"Off-screen element is reached by upward swipes",
"End of list or max swipes raises ElementNotFoundError naming the query"
],
"out_of_scope": ["MCP wrapper", "Rollout to todo and dufs-cloud"],
"verifier": "pytest python_pkg/android_ui and pre-commit run --files <changed-files>"
}

View File

@ -0,0 +1,25 @@
{
"intent": "android-ui can bring a widget below the fold on screen with scroll-to.",
"scope": [
"python_pkg/android_ui: _scroll.py, driver.py, cli.py, README, tests",
"Non-goal: MCP wrapper and rollout to other repos"
],
"changes": [
"Added ScrollMixin.scroll_to (swipe up until the query matches once)",
"Added the scroll-to CLI subcommand and narrowed the TODO"
],
"verification": [
{
"command": "pytest python_pkg/android_ui --cov=python_pkg.android_ui",
"result": "pass",
"evidence": "95 passed, every android_ui module 100% covered"
},
{
"command": "pre-commit run --files <changed-files>",
"result": "pass",
"evidence": "all hooks pass"
}
],
"risks": ["Swipe distance is tuned for a 1080x2400 screen only by fraction"],
"rollback": ["git revert the commit", "Re-run pytest python_pkg/android_ui"]
}

View File

@ -0,0 +1,29 @@
{
"intent": "kuhy sees the active focus project in i3bar: a focus_project block renders the focus field daily-limits now writes to its cache.",
"scope": [
"linux_configuration/i3blocks/focus_project.sh, the [focus_project] stanza in linux_configuration/i3blocks/config, linux_configuration/tests/test_i3blocks_focus_project.sh",
"Non-goal: no focus logic here (focus_project.status() decides); daily-limits owns the cache"
],
"changes": [
"New block: `🎯 <name> <minutes>/<daily_minutes>`, green at the daily target, hidden with no project or a missing/stale/garbage cache; jq re-parse only on cache mtime change",
"Stanza has signal=11 so daily-limits can refresh it with pkill -RTMIN+11 -x i3blocks"
],
"verification": [
{
"command": "bash linux_configuration/tests/test_i3blocks_focus_project.sh",
"result": "pass",
"evidence": "focus_project block: all checks passed"
},
{
"command": "bash ~/.config/i3blocks/focus_project.sh (live cache after daily-limits.service)",
"result": "pass",
"evidence": "🎯 HackerRank prep 0/120, #F1FA8C"
}
],
"risks": [
"The running i3bar loads the stanza only after its next restart; until then the poke is harmless (i3blocks 1.5 survived an unconfigured RTMIN+11)"
],
"rollback": [
"git revert the commit and remove the symlink ~/.config/i3blocks/focus_project.sh"
]
}

View File

@ -0,0 +1,16 @@
{
"intent": "Replace the stale 2000-line phone recovery plan with its remaining live-verification steps.",
"scope": ["docs/superpowers/plans/TODO-phone-focus-recovery.md"],
"changes": [
"Plan chunks 1-7 are built in phone-focus-mode; TODO keeps Chunk 8 only"
],
"verification": [
{
"command": "bash lib/tests/test_adb_common.sh; bash lib/tests/test_monitor.sh (in ~/src/phone-focus-mode)",
"result": "pass",
"evidence": "10 passed, 82 passed; run_phone.sh --help exits 0"
}
],
"risks": ["Live phone steps stay unverified until a phone is attached"],
"rollback": ["git revert the commit"]
}

View File

@ -3,12 +3,14 @@
"scope": [
"python_pkg/sql_drills (new package, fixtures, tests, README)",
"meta/pyproject.toml: register the docker pytest marker",
"Non-goal: bumping the pinned mysql image; copying third-party problems"
"Non-goal: bumping the pinned mysql image; copying third-party problems",
"2026-11-02: show/check send an optional focus-tracker heartbeat (__main__.py, tests/conftest.py, tests/test_focus_hook.py)"
],
"changes": [
"CLI start/stop/list/show/check over one long-lived tmpfs container",
"Judge-style normaliser and line diff, unit-tested without Docker",
"12 original drills with live-verified reference solutions kept in tests only"
"12 original drills with live-verified reference solutions kept in tests only",
"_heartbeat(): soft import of focus_project; absent -> no-op, tracker error -> logged, result and exit code unchanged"
],
"verification": [
{
@ -20,11 +22,17 @@
"command": "python3 -m python_pkg.sql_drills check <id> <reference> for all 12 drills",
"result": "pass",
"evidence": "every drill prints PASS; wrong query prints a line diff, syntax error exits 2"
},
{
"command": "python3 -m pytest -q python_pkg/sql_drills/tests --cov=python_pkg.sql_drills --cov-branch",
"result": "pass",
"evidence": "61 passed, 15 live tests skipped (no container), 100% branch coverage; show 01 wrote one sql_drills heartbeat row to a scratch FOCUS_PROJECT_DATA"
}
],
"risks": [
"Local MySQL image must be pulled once; start fails with a clear error otherwise",
"A runaway query is cut off client-side after 30 s but may keep running in the container until stop"
"A runaway query is cut off client-side after 30 s but may keep running in the container until stop",
"A hanging tracker would delay show/check; the real one is a local file append"
],
"rollback": [
"git revert the commit; run python3 -m python_pkg.sql_drills stop first",

File diff suppressed because it is too large Load Diff

View File

@ -72,6 +72,13 @@ interval=30
command=~/.config/i3blocks/tutor.sh
interval=30
# Active focus project. signal=11: daily-limits sends `pkill -RTMIN+11 -x
# i3blocks` the moment the focus status changes; 30 s is only the fallback.
[focus_project]
command=~/.config/i3blocks/focus_project.sh
interval=30
signal=11
[issue_dashboard]
command=~/.config/i3blocks/issue_dashboard.sh
interval=30

View File

@ -0,0 +1,89 @@
#!/bin/bash
# ============================================================================
# Active focus project for i3blocks: `🎯 HackerRank prep 45/120` (minutes done
# today / daily target). Green once the daily target is reached, yellow while
# short of it, hidden when no project is active.
#
# Renders the `focus` field of daily-limits' cache ($XDG_RUNTIME_DIR/
# daily-limits.json, rewritten every 60 s by its user timer) and owns no
# focus logic: focus_project.status() decides. The cache is re-parsed with jq
# only when its mtime changes, so a steady-state tick forks nothing.
#
# Refresh is event-driven: the block has `signal=11` in the i3blocks config and
# daily-limits sends `pkill -RTMIN+11 -x i3blocks` the moment the focus status
# changes (the 30 s interval is only the fallback).
#
# A missing, garbage or >180 s old cache hides the block: the neighbouring
# gaming_budget block already says "⏱?" for the same cache, and old minutes
# must never be shown. Left-click opens `daily-limits --gui`.
# ============================================================================
set -euo pipefail
readonly LIMITS_CACHE="${DAILY_LIMITS_CACHE:-${XDG_RUNTIME_DIR:-/run/user/$UID}/daily-limits.json}"
readonly RENDER_CACHE="${DAILY_LIMITS_RENDER_CACHE:-${XDG_RUNTIME_DIR:-/run/user/$UID}/i3blocks-focus-project.render}"
readonly STALE_AFTER_SECONDS=180
# Dracula-ish palette, matching gaming_budget.sh.
readonly YELLOW='#F1FA8C'
readonly GREEN='#50FA7B'
emit() {
# full_text, short_text, color: the three lines i3blocks reads.
printf '%s\n%s\n%s\n' "$1" "$2" "$3"
}
# i3blocks' PATH has no ~/.local/bin, where daily-limits' install.sh puts it.
readonly DAILY_LIMITS_BIN=${DAILY_LIMITS_BIN:-$HOME/.local/bin/daily-limits}
if [[ ${BLOCK_BUTTON:-0} -eq 1 && -x $DAILY_LIMITS_BIN ]]; then
setsid -f "$DAILY_LIMITS_BIN" --gui >/dev/null 2>&1
fi
hide() {
emit '' '' "$YELLOW"
exit 0
}
# One jq pass renders four lines: generated_at, full text, short text, color.
# The name is untrusted display text: control characters become spaces so it
# can never add lines to the block's output.
render_focus() {
local rendered
rendered=$(jq -r --arg green "$GREEN" --arg yellow "$YELLOW" '
(.generated_at | if type == "number" then floor else "none" end),
(.focus | if type == "object" and (.project | type) == "string" then
(.minutes // 0 | floor) as $m
| (.daily_minutes // 0 | floor) as $d
| ((.name // .project) | tostring | gsub("[\u0001-\u001f\u007f]"; " ")) as $name
| "🎯 \($name) \($m)/\($d)", "🎯 \($m)/\($d)",
(if $d > 0 and $m >= $d then $green else $yellow end)
else "", "", $yellow end)' "$LIMITS_CACHE" 2>/dev/null) || return 1
printf '%s\n' "$rendered" >"$RENDER_CACHE"
}
[[ -r $LIMITS_CACHE ]] || hide
if [[ $LIMITS_CACHE -nt $RENDER_CACHE ]]; then
command -v jq >/dev/null 2>&1 || hide
render_focus || hide
fi
{
read -r generated_at
read -r full_text
read -r short_text
read -r color
} <"$RENDER_CACHE" || hide
if [[ -n ${NOW_EPOCH:-} ]]; then
now=$NOW_EPOCH
else
printf -v now '%(%s)T' -1
fi
[[ $generated_at =~ ^-?[0-9]+$ ]] || hide
age=$((now - generated_at))
if ((age > STALE_AFTER_SECONDS || age < -STALE_AFTER_SECONDS)); then
hide
fi
emit "$full_text" "$short_text" "$color"

View File

@ -0,0 +1,106 @@
#!/bin/bash
# Behaviour tests for the i3blocks focus_project block: it renders the `focus`
# field of daily-limits' cache ($DAILY_LIMITS_CACHE). Covers the progress text,
# green once daily_minutes is reached, hidden with no project / no focus key /
# missing, stale or garbage cache, name sanitising, the click, and the
# "re-parse only when the cache changes" contract.
set -euo pipefail
SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
REPO_DIR=$(cd -- "$SCRIPT_DIR/.." && pwd)
BLOCK="$REPO_DIR/i3blocks/focus_project.sh"
TMP_DIR=$(mktemp -d)
cleanup() {
rm -rf "$TMP_DIR"
}
trap cleanup EXIT
fail() {
printf 'FAIL: %s\n' "$1" >&2
exit 1
}
assert_eq() {
if [[ "$1" != "$2" ]]; then
fail "$3 (expected '$1', actual '$2')"
fi
}
printf '{}' | jq -e . >/dev/null 2>&1 ||
fail 'a working jq is required for the focus_project tests (pacman -S jq)'
CACHE="$TMP_DIR/daily-limits.json"
RENDER="$TMP_DIR/render"
NOW=1790000000
# write_cache GENERATED_AT FOCUS_JSON (FOCUS_JSON "" = no focus key at all)
write_cache() {
local focus=${2:+,\"focus\":$2}
printf '{"date":"2026-11-02","generated_at":%s%s}\n' "$1" "$focus" >"$CACHE"
rm -f "$RENDER"
}
focus_json() { # NAME MINUTES DAILY
jq -nc --arg n "$1" --argjson m "$2" --argjson d "$3" \
'{project:"p",name:$n,minutes:$m,daily_minutes:$d,unlock_minutes:30,ends:"2026-11-05",replaces:["leetcode"]}'
}
run_block() {
NOW_EPOCH="$NOW" DAILY_LIMITS_CACHE="$CACHE" DAILY_LIMITS_RENDER_CACHE="$RENDER" \
DAILY_LIMITS_BIN="$TMP_DIR/dl" bash "$BLOCK"
}
line() { sed -n "${1}p" <<<"$2"; }
printf 'Checking progress and colour...\n'
write_cache "$NOW" "$(focus_json 'HackerRank prep' 45 120)"
out=$(run_block)
assert_eq '🎯 HackerRank prep 45/120' "$(line 1 "$out")" 'full text'
assert_eq '🎯 45/120' "$(line 2 "$out")" 'short text'
assert_eq '#F1FA8C' "$(line 3 "$out")" 'yellow below the daily target'
write_cache "$NOW" "$(focus_json 'HackerRank prep' 120 120)"
out=$(run_block)
assert_eq '🎯 HackerRank prep 120/120' "$(line 1 "$out")" 'target reached text'
assert_eq '#50FA7B' "$(line 3 "$out")" 'green at daily_minutes'
printf 'Checking the hidden states...\n'
write_cache "$NOW" '{"project":null,"minutes":0,"daily_minutes":0}'
out=$(run_block)
assert_eq '' "$(line 1 "$out")" 'null project hides'
assert_eq '' "$(line 2 "$out")" 'null project hides short text'
write_cache "$NOW" ''
assert_eq '' "$(line 1 "$(run_block)")" 'no focus key hides'
rm -f "$CACHE" "$RENDER"
assert_eq '' "$(line 1 "$(run_block)")" 'missing cache hides (the gaming block says why)'
write_cache $((NOW - 600)) "$(focus_json 'X' 5 120)"
assert_eq '' "$(line 1 "$(run_block)")" 'a stale cache hides, never old numbers'
printf '{' >"$CACHE"
rm -f "$RENDER"
assert_eq '' "$(line 1 "$(run_block)")" 'garbage cache hides'
printf 'Checking a hostile name and a bad daily target...\n'
write_cache "$NOW" "$(focus_json $'Evil\nname<b>' 5 120)"
out=$(run_block)
assert_eq 3 "$(printf '%s\n' "$out" | wc -l)" 'three lines only'
assert_eq '🎯 Evil name<b> 5/120' "$(line 1 "$out")" 'newlines become spaces'
write_cache "$NOW" "$(focus_json 'Z' 5 0)"
assert_eq '#F1FA8C' "$(line 3 "$(run_block)")" 'daily 0 is never green'
printf 'Checking the render cache is reused...\n'
write_cache "$NOW" "$(focus_json 'Keep' 10 120)"
run_block >/dev/null
printf '%s\n' "$NOW" '🎯 CACHED 1/1' '🎯 1/1' '#50FA7B' >"$RENDER"
touch -d '+1 second' "$RENDER"
assert_eq '🎯 CACHED 1/1' "$(line 1 "$(run_block)")" 'unchanged cache is not re-parsed'
printf 'Checking a click opens the GUI...\n'
printf '#!/bin/bash\necho "$*" >>"%s/clicks"\n' "$TMP_DIR" >"$TMP_DIR/dl"
chmod +x "$TMP_DIR/dl"
BLOCK_BUTTON=1 run_block >/dev/null
for _ in 1 2 3 4 5 6 7 8 9 10; do
[[ -s "$TMP_DIR/clicks" ]] && break
sleep 0.1
done
assert_eq '--gui' "$(cat "$TMP_DIR/clicks" 2>/dev/null)" 'click runs daily-limits --gui'
printf 'focus_project block: all checks passed\n'

View File

@ -85,8 +85,9 @@ ui.wait_for("Connected.", timeout=30)
`SemanticsNode`, while this tool reads Android's `AccessibilityNodeInfo`.
Nine widget tests passed green on the build whose on-device labels had
just gone empty.
- Scrolling is not yet modelled: a widget outside the viewport is not in the
tree. Scroll with `adb shell input swipe` first, or add `scroll_to()`.
- A widget outside the viewport is not in the tree. `android-ui scroll-to
QUERY` (`AndroidUi.scroll_to`) swipes up until it appears, and stops with an
error at the end of the list or after 8 swipes. It only scrolls downward.
## One phone, many sessions

View File

@ -1,13 +1,12 @@
# Task: replace blind coordinate tapping with element-targeted Android UI automation
> **STATUS 2026-08-10: BUILT.** The tool now exists at
> `~/src/testsAndMisc/python_pkg/android_ui/` (see its README). It covers `dump` /
> `find` / `tap` / `type` / `wait` / `focus` with verified typing, ambiguity as
> an error, keyboard detection, and partial-tree retries — all exercised
> against the physical Pixel 6a. What remains from the spec below is the
> optional MCP wrapper, `scroll_to()`, and rolling it out to `~/src/todo` and
> `~/src/dufs-cloud/app`. Everything after this line is the original brief, kept
> because it records WHY each guarantee exists.
> **STATUS 2026-11-02: PARTIAL.** The CLI (`dump`/`find`/`tap`/`type`/`wait`/
> `scroll-to`/`focus`) exists at `~/src/testsAndMisc/python_pkg/android_ui/` (see
> its README). Remaining: (1) the optional MCP wrapper over the same driver;
> (2) rolling it out to `~/src/todo` and `~/src/dufs-cloud/app` (other repos,
> needs their own sessions); (3) the `## done` run on the physical Pixel 6a:
> needs kuhy, phone not connected. Everything after this line is the original
> brief, kept because it records WHY each guarantee exists.
## what

View File

@ -0,0 +1,72 @@
"""``scroll_to``: bring a widget that is outside the viewport on screen."""
from __future__ import annotations
from abc import ABC, abstractmethod
import time
from python_pkg.android_ui._elements import ElementNotFoundError, UiElement
_SWIPE_MS = "350"
# Swipe through the middle 40% of the screen: far enough to move a page, short
# enough that Flutter does not turn it into a fling that overshoots the target.
_FROM_FRAC = 0.7
_TO_FRAC = 0.3
def _snapshot(elements: list[UiElement]) -> list[tuple[str, tuple[int, ...]]]:
"""Reduce a tree to what changes when a list scrolls."""
return [(e.label, e.bounds) for e in elements]
class ScrollMixin(ABC):
"""The scrolling part of :class:`~python_pkg.android_ui.driver.AndroidUi`."""
_settle: float
@abstractmethod
def _input(self, *args: str) -> str:
"""Supplied by the concrete driver: ``input`` on the driven display."""
@abstractmethod
def dump(self, *, retries: int = 4) -> list[UiElement]:
"""Supplied by the concrete driver: read the current UI tree."""
@abstractmethod
def find(self, query: str, *, exact: bool = False) -> UiElement:
"""Supplied by the concrete driver: the single match, or raise."""
def scroll_to(
self, query: str, *, exact: bool = False, max_swipes: int = 8
) -> UiElement:
"""Swipe up until ``query`` matches exactly one element, then return it.
A widget outside the viewport is not in the accessibility tree, so
``find`` reports it missing. Stops early, naming the query, when a swipe
leaves the screen unchanged (the end of the list) rather than spinning
for ``max_swipes`` swipes. Ambiguity raises, as it does for ``find``.
"""
elements = self.dump()
for _ in range(max_swipes):
if any(e.matches(query, exact=exact) for e in elements):
return self.find(query, exact=exact)
width = max((e.bounds[2] for e in elements), default=0)
height = max((e.bounds[3] for e in elements), default=0)
x = str(width // 2)
self._input(
"swipe",
x,
str(int(height * _FROM_FRAC)),
x,
str(int(height * _TO_FRAC)),
_SWIPE_MS,
)
time.sleep(self._settle)
after = self.dump()
if _snapshot(after) == _snapshot(elements):
break
elements = after
if any(e.matches(query, exact=exact) for e in elements):
return self.find(query, exact=exact)
msg = f"scrolled looking for {query!r} but it never appeared"
raise ElementNotFoundError(msg)

View File

@ -9,6 +9,7 @@ successful no-op instead of guessing from a screenshot.
android-ui tap "Connect Firebase"
android-ui type "Sync account email" kuhy@example.com
android-ui wait "Connected to Firebase." --timeout 30
android-ui scroll-to "Offline backup" # widget below the fold
android-ui --display self tap "Save" # this session's phone_vd display
"""
@ -63,6 +64,7 @@ def _build_parser() -> argparse.ArgumentParser:
("find", "locate an element without touching it"),
("tap", "tap the element matching QUERY"),
("wait", "poll until QUERY appears"),
("scroll-to", "swipe up until QUERY is on screen"),
):
cmd = sub.add_parser(name, help=helptext)
cmd.add_argument("query")
@ -135,6 +137,8 @@ def _run(ui: AndroidUi, args: argparse.Namespace) -> None:
elif args.command == "wait":
found = ui.wait_for(args.query, timeout=args.timeout, exact=args.exact)
sys.stdout.write(f"{found}\n")
elif args.command == "scroll-to":
sys.stdout.write(f"{ui.scroll_to(args.query, exact=args.exact)}\n")
elif args.command == "type":
ui.type_into(args.query, args.text, exact=args.exact, timeout=args.timeout)
sys.stdout.write(f"typed into {args.query!r} and verified\n")

View File

@ -17,6 +17,7 @@ from python_pkg.android_ui._elements import (
_escape,
_parse_tree,
)
from python_pkg.android_ui._scroll import ScrollMixin
from python_pkg.android_ui._text_entry import TextEntryMixin
_logger = logging.getLogger(__name__)
@ -30,7 +31,7 @@ _REMOTE_DUMP = "/sdcard/window_dump.xml"
_SUSPICIOUSLY_SMALL_TREE = 4
class AndroidUi(TextEntryMixin):
class AndroidUi(ScrollMixin, TextEntryMixin):
"""Drives one device. Every action re-reads the tree before acting."""
def __init__(

View File

@ -140,6 +140,19 @@ class TestWait:
assert cli.main(["wait", "Nope"]) == 1
class TestScrollTo:
def test_prints_the_element_once_scrolled_into_view(
self, ui: MagicMock, capsys: pytest.CaptureFixture[str]
) -> None:
ui.scroll_to.return_value = _element("Offline backup")
assert cli.main(["scroll-to", "Offline backup"]) == 0
assert "Offline backup" in capsys.readouterr().out
def test_never_found_exits_non_zero(self, ui: MagicMock) -> None:
ui.scroll_to.side_effect = ElementNotFoundError("never appeared")
assert cli.main(["scroll-to", "Nope"]) == 1
class TestType:
def test_confirms_the_text_was_verified(
self, ui: MagicMock, capsys: pytest.CaptureFixture[str]

View File

@ -0,0 +1,86 @@
"""Tests for ``AndroidUi.scroll_to``: find a widget outside the viewport."""
from __future__ import annotations
import pytest
from python_pkg.android_ui import driver as drv
from python_pkg.android_ui._elements import (
AmbiguousElementError,
ElementNotFoundError,
)
from python_pkg.android_ui.tests.conftest import FakeDevice
from python_pkg.android_ui.tests.conftest import node as _node
from python_pkg.android_ui.tests.conftest import tree as _tree
MOD = "python_pkg.android_ui.driver"
_SCREEN = "[0,0][1080,2400]"
def _screen(*labels: str) -> str:
"""A screen of five filler rows (so the dump is not 'partial') plus labels."""
rows = [_node("Window", bounds=_SCREEN)]
rows += [_node(f"row{i}", bounds="[0,100][1080,200]") for i in range(4)]
rows += [_node(label, bounds="[0,1000][1080,1100]") for label in labels]
return _tree(*rows)
def _driver(
monkeypatch: pytest.MonkeyPatch, trees: list[str]
) -> tuple[drv.AndroidUi, FakeDevice]:
device = FakeDevice(trees)
instance = drv.AndroidUi(settle_seconds=0.0)
monkeypatch.setattr(instance, "_run", device.run)
monkeypatch.setattr(f"{MOD}.time.sleep", lambda _s: None)
return instance, device
def _swipes(device: FakeDevice) -> list[tuple[str, ...]]:
return [c for c in device.calls if c[4:5] == ("swipe",)]
def test_visible_element_needs_no_swipe(monkeypatch: pytest.MonkeyPatch) -> None:
ui, device = _driver(monkeypatch, [_screen("Backup")])
assert ui.scroll_to("Backup").label == "Backup"
assert _swipes(device) == []
def test_swipes_up_until_the_element_appears(monkeypatch: pytest.MonkeyPatch) -> None:
ui, device = _driver(
monkeypatch, [_screen("A"), _screen("B"), _screen("B", "Backup")]
)
assert ui.scroll_to("Backup").label == "Backup"
swipes = _swipes(device)
assert len(swipes) == 2
# finger travels upward through the middle of the screen
x1, y1, x2, y2 = (int(v) for v in swipes[0][5:9])
assert x1 == x2 == 540
assert y1 > y2
assert 0 < y2 < y1 < 2400
def test_stops_at_the_end_of_the_list(monkeypatch: pytest.MonkeyPatch) -> None:
# The screen stops changing once the list bottoms out: say so, don't spin.
ui, device = _driver(monkeypatch, [_screen("A")])
with pytest.raises(ElementNotFoundError, match="Backup"):
ui.scroll_to("Backup", max_swipes=10)
assert len(_swipes(device)) == 1
def test_gives_up_after_max_swipes(monkeypatch: pytest.MonkeyPatch) -> None:
trees = [_screen(f"item{i}") for i in range(10)]
ui, device = _driver(monkeypatch, trees)
with pytest.raises(ElementNotFoundError, match="Backup"):
ui.scroll_to("Backup", max_swipes=3)
assert len(_swipes(device)) == 3
def test_ambiguity_is_still_an_error(monkeypatch: pytest.MonkeyPatch) -> None:
ui, _ = _driver(monkeypatch, [_screen("Backup now", "Backup later")])
with pytest.raises(AmbiguousElementError):
ui.scroll_to("Backup")
def test_the_last_allowed_swipe_may_reveal_it(monkeypatch: pytest.MonkeyPatch) -> None:
ui, _ = _driver(monkeypatch, [_screen("A"), _screen("Backup")])
assert ui.scroll_to("Backup", max_swipes=1).label == "Backup"

View File

@ -3,12 +3,32 @@
from __future__ import annotations
import argparse
import importlib
import logging
from pathlib import Path
import sys
from python_pkg.sql_drills import _check, _drills, _engine
_EXIT_CODES = {"pass": 0, "fail": 1, "error": 2}
_LOG = logging.getLogger(__name__)
def _heartbeat() -> None:
"""Tell the optional focus tracker that practice is happening.
Soft dependency: absent module -> silent no-op; a tracker error is logged
(file or registry errors) and never changes the drill's result or
exit code.
"""
try:
tracker = importlib.import_module("focus_project")
except ImportError:
return
try:
tracker.record_activity("sql_drills", "heartbeat")
except OSError, ValueError:
_LOG.exception("focus tracker heartbeat failed")
def _out(line: str) -> None:
@ -44,8 +64,10 @@ def _dispatch(args: argparse.Namespace) -> int:
for drill in _drills.list_drills():
_out(f"{drill.id} {_drills.title_of(drill)}")
elif args.cmd == "show":
_heartbeat()
sys.stdout.write(_drills.render_show(_drills.get_drill(args.drill)))
else:
_heartbeat()
result = _check.run_check(_drills.get_drill(args.drill), args.sql_file)
_out(result.message)
return _EXIT_CODES[result.status]

View File

@ -0,0 +1,14 @@
"""Keep the optional focus tracker out of every test unless a test fakes it."""
from __future__ import annotations
import sys
from typing import Any, cast
import pytest
@pytest.fixture(autouse=True)
def _no_real_focus_tracker(monkeypatch: pytest.MonkeyPatch) -> None:
"""Make ``import focus_project`` fail, so no test writes live activity."""
monkeypatch.setitem(sys.modules, "focus_project", cast("Any", None))

View File

@ -0,0 +1,71 @@
"""The soft-optional focus-tracker heartbeat on ``show`` and ``check``."""
from __future__ import annotations
import logging
import sys
import types
from typing import TYPE_CHECKING, Any, cast
from unittest.mock import patch
import pytest
from python_pkg.sql_drills import __main__ as cli
from python_pkg.sql_drills import _check
if TYPE_CHECKING:
from pathlib import Path
def _fake_tracker(
monkeypatch: pytest.MonkeyPatch, *, fail: bool = False
) -> list[tuple[Any, ...]]:
calls: list[tuple[Any, ...]] = []
module = cast("Any", types.ModuleType("focus_project"))
def record_activity(*args: str) -> None:
if fail:
msg = "tracker down"
raise OSError(msg)
calls.append(args)
module.record_activity = record_activity
monkeypatch.setitem(sys.modules, "focus_project", module)
return calls
def test_show_sends_heartbeat(monkeypatch: pytest.MonkeyPatch) -> None:
calls = _fake_tracker(monkeypatch)
assert cli.main(["show", "01"]) == 0
assert calls == [("sql_drills", "heartbeat")]
def test_check_sends_heartbeat(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
calls = _fake_tracker(monkeypatch)
result = _check.CheckResult("fail", "MSG")
with patch.object(_check, "run_check", return_value=result):
assert cli.main(["check", "01", str(tmp_path / "q.sql")]) == 1
assert calls == [("sql_drills", "heartbeat")]
def test_list_sends_no_heartbeat(monkeypatch: pytest.MonkeyPatch) -> None:
calls = _fake_tracker(monkeypatch)
assert cli.main(["list"]) == 0
assert calls == []
def test_missing_tracker_changes_nothing(capsys: pytest.CaptureFixture[str]) -> None:
assert cli.main(["show", "01"]) == 0
assert "CREATE TABLE" in capsys.readouterr().out
def test_failing_tracker_is_logged_not_raised(
monkeypatch: pytest.MonkeyPatch,
caplog: pytest.LogCaptureFixture,
capsys: pytest.CaptureFixture[str],
) -> None:
_fake_tracker(monkeypatch, fail=True)
with caplog.at_level(logging.ERROR):
assert cli.main(["show", "01"]) == 0
assert "heartbeat" in caplog.text
assert "CREATE TABLE" in capsys.readouterr().out