Compare commits

...

3 Commits

Author SHA1 Message Date
9d897c13f4 crdt-sync: split seven oversized test files by test group
Some checks are pending
crdt-sync pre-commit / pre-commit (push) Waiting to run
crdt-sync tests / test (3.10) (push) Waiting to run
crdt-sync tests / test (3.11) (push) Waiting to run
crdt-sync tests / test (3.12) (push) Waiting to run
gatelock pre-commit / pre-commit (push) Waiting to run
gatelock tests / test (3.10) (push) Waiting to run
gatelock tests / test (3.11) (push) Waiting to run
gatelock tests / test (3.12) (push) Waiting to run
palette drift / palette (push) Waiting to run
test_firebase_auth.py    439 -> 170 + _google 159 + _tokens 159 + _session 175
  test_sync_revisions.py   406 -> 163 + _peers 162 + _backends 216
  test_firebase.py         369 -> 212 + _writes 221
  test_mirror.py           364 -> 178 + _fallback 229
  test_config.py           355 -> 139 + _credentials 112 + _client 233
  test_github.py           301 -> 127 + _writes 219
  test_sync.py             271 -> 195 + _skips 130

Cut at concern boundaries, not line counts: test_sync_skips.py holds the five
cases where a peer's pushed file is missing, corrupt, wrong-shaped or our own
— one story about what sync_log declines to merge — rather than an arbitrary
half of the original class.

259 passed at 100% branch coverage, verified against a clean HEAD worktree.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CFSGeWxHPY5rHUGrPqhcmG
2026-08-22 14:47:58 +02:00
389832314a gatelock: split seven oversized test files by test group
Each file split at a class or concern boundary, never mechanically:

  test_arbiter.py       432 -> 222 + _lifecycle 183 + _release 201
  test_outputs.py       418 -> 187 + _randr 204 + _enumerator 126
  test_scrollable.py    374 -> 231 + _into_view 197
  test_escape.py        343 -> 175 + _budget 216
  test_window_surfaces  341 -> 110 + _lifecycle 104 + _preempt 182
  test_surfaces.py      282 -> 167 + _focus 154
  test_window.py        269 -> 143 + _grab 139

Test counts verified against a clean HEAD worktree, per file group rather
than in aggregate: arbiter 49/49, outputs+escape 84/84, window+surfaces
72/72, scrollable 18/18. The whole suite is 389 passed at 100% branch
coverage, identical to before.

The one non-mechanical part: _reply/_randr_display are module-level helpers
defined *between* classes, so they did not travel with the header and had to
be moved to the RandR file by hand — six tests failed until they did.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CFSGeWxHPY5rHUGrPqhcmG
2026-08-22 14:45:08 +02:00
408c7a2585 gatelock: split test_recovery.py 477 -> 208 lines by test layer
The file's own docstring described three layers; they are now three files:

  test_recovery_invariants.py  (52)  — the static AST check that _recovery.py
                                       contains no weakening call at all
  test_recovery_reassertion.py (218) — what a tick re-asserts: grab, focus, VT
  test_recovery.py             (208) — the 2026-07-25 monotonic-sequence walk,
                                       tick mechanics, and scheduling

Splitting the classes made pylint's R0801 fire: both halves built a
RecoveryLoop with the same RecoveryCollaborators block. Rather than suppress
it (banned) the shared construction became conftest.build_loop(root, config),
which the `loop` fixture now uses too — so the tests that need a non-default
config ask for one instead of restating the wiring. The output scans both
halves drive moved to conftest alongside it.

389 passed, 100% branch coverage — same tests, same count, three files.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CFSGeWxHPY5rHUGrPqhcmG
2026-08-22 14:37:47 +02:00
39 changed files with 4012 additions and 2838 deletions

View File

@ -21,11 +21,7 @@ import pytest
from crdt_sync import (
ConfigError,
FirebaseConfig,
FirebaseSyncClient,
credential_store_for,
mirror_client_for,
)
from crdt_sync._config import _DEFAULT_TIMEOUT_SECONDS, firebase_client_for
if TYPE_CHECKING:
from pathlib import Path
@ -141,215 +137,3 @@ def test_names_an_unfilled_placeholder(tmp_path: Path) -> None:
with pytest.raises(ConfigError, match=r"placeholder for: apiKey"):
FirebaseConfig.load(_write(tmp_path / "firebase.json", unfilled))
def test_reads_a_password(tmp_path: Path) -> None:
"""Reads a password."""
config = FirebaseConfig.load(_write(tmp_path / "firebase.json", _VALID))
password = tmp_path / "password"
password.write_text("hunter2", encoding="utf-8")
assert config.read_password(password) == "hunter2"
def test_strips_a_trailing_newline_from_the_password(tmp_path: Path) -> None:
"""The likeliest hand-editing mistake, and otherwise invisible."""
config = FirebaseConfig.load(_write(tmp_path / "firebase.json", _VALID))
password = tmp_path / "password"
password.write_text("hunter2\n", encoding="utf-8")
assert config.read_password(password) == "hunter2"
def test_rejects_an_empty_password(tmp_path: Path) -> None:
"""Rejects an empty password."""
config = FirebaseConfig.load(_write(tmp_path / "firebase.json", _VALID))
password = tmp_path / "password"
password.write_text(" ", encoding="utf-8")
with pytest.raises(ConfigError, match="empty or still holds"):
config.read_password(password)
def test_rejects_a_placeholder_password(tmp_path: Path) -> None:
"""Rejects a placeholder password."""
config = FirebaseConfig.load(_write(tmp_path / "firebase.json", _VALID))
password = tmp_path / "password"
password.write_text("PASTE_SYNC_ACCOUNT_PASSWORD_HERE", encoding="utf-8")
with pytest.raises(ConfigError, match="placeholder"):
config.read_password(password)
def test_reports_an_unreadable_password(tmp_path: Path) -> None:
"""Reports an unreadable password."""
config = FirebaseConfig.load(_write(tmp_path / "firebase.json", _VALID))
(tmp_path / "password").mkdir()
with pytest.raises(ConfigError, match="could not be read"):
config.read_password(tmp_path / "password")
def test_credential_store_is_per_app() -> None:
"""Two apps must not share one cache file; concurrent writes corrupt it."""
diet = credential_store_for("diet_guard")
alarm = credential_store_for("wake_alarm")
assert diet._path != alarm._path
assert diet._path.name == "firebase_auth.json"
assert "diet_guard" in str(diet._path)
def test_client_signs_in_only_without_a_cached_session(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""The common path is a cached refresh token, costing no round trip."""
config = FirebaseConfig.load(_write(tmp_path / "firebase.json", _VALID))
sign_ins: list[tuple[str, str]] = []
class _Auth:
def __init__(self, api_key: str, _store: object) -> None:
self.api_key = api_key
def has_session(self) -> bool:
"""Pretend a cached session exists."""
return True
def sign_in(self, email: str, password: str) -> None:
"""Record the sign-in attempt."""
sign_ins.append((email, password)) # pragma: no cover - must not run
monkeypatch.setattr("crdt_sync._config.FirebaseTokenProvider", _Auth)
client = firebase_client_for("diet_guard", config=config)
assert not sign_ins
assert client is not None
def test_client_signs_in_when_there_is_no_session(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Client signs in when there is no session."""
config = FirebaseConfig.load(_write(tmp_path / "firebase.json", _VALID))
password = tmp_path / "password"
password.write_text("hunter2", encoding="utf-8")
monkeypatch.setattr("crdt_sync._config.PASSWORD_FILE", password)
sign_ins: list[tuple[str, str]] = []
class _Auth:
def __init__(self, api_key: str, _store: object) -> None:
self.api_key = api_key
def has_session(self) -> bool:
"""Pretend no cached session exists."""
return False
def sign_in(self, email: str, password_value: str) -> None:
"""Record the credentials the caller signed in with."""
sign_ins.append((email, password_value))
monkeypatch.setattr("crdt_sync._config.FirebaseTokenProvider", _Auth)
firebase_client_for("diet_guard", config=config)
assert sign_ins == [("sync@example.com", "hunter2")]
def test_mirror_client_makes_firebase_primary(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Firebase authoritative, GitHub best-effort -- the cutover shape."""
config = FirebaseConfig.load(_write(tmp_path / "firebase.json", _VALID))
github = _StubRemote()
class _Auth:
def __init__(self, api_key: str, _store: object) -> None:
self.api_key = api_key
def has_session(self) -> bool:
"""Pretend a cached session exists."""
return True
def sign_in(self, email: str, password: str) -> None:
"""Record the sign-in attempt."""
raise AssertionError # pragma: no cover - must not run
monkeypatch.setattr("crdt_sync._config.FirebaseTokenProvider", _Auth)
client = mirror_client_for("diet_guard", github, config=config)
# Reaching into the wrapper is the point: which backend is authoritative
# is the one thing a rollback depends on getting right.
assert client.mirror is github
assert isinstance(client.primary, FirebaseSyncClient)
def test_client_loads_the_shared_config_when_none_is_given(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""The default path: apps name themselves and nothing else."""
monkeypatch.setattr(
"crdt_sync._config.CONFIG_FILE",
_write(tmp_path / "firebase.json", _VALID),
)
class _Auth:
def __init__(self, api_key: str, _store: object) -> None:
self.api_key = api_key
def has_session(self) -> bool:
"""Pretend a cached session exists."""
return True
def sign_in(self, email: str, password: str) -> None:
"""Record the sign-in attempt."""
raise AssertionError # pragma: no cover - must not run
monkeypatch.setattr("crdt_sync._config.FirebaseTokenProvider", _Auth)
assert firebase_client_for("wake_alarm") is not None
def _client_with_stub_auth(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
**kwargs: float,
) -> FirebaseSyncClient:
"""Return a client built with stubbed auth, forwarding ``kwargs``."""
config = FirebaseConfig.load(_write(tmp_path / "firebase.json", _VALID))
class _Auth:
def __init__(self, api_key: str, _store: object) -> None:
"""Record the key; the credential store is irrelevant here."""
self.api_key = api_key
def has_session(self) -> bool:
"""Pretend a cached session exists, so no sign-in is attempted."""
return True
monkeypatch.setattr("crdt_sync._config.FirebaseTokenProvider", _Auth)
return firebase_client_for("diet_guard", config=config, **kwargs)
def test_client_uses_the_requested_timeout(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""A caller's timeout must reach the client, not just the GitHub half."""
# A keyword with a default adds no branch, so coverage alone cannot tell
# whether it is actually threaded through to the client.
client = _client_with_stub_auth(tmp_path, monkeypatch, timeout_seconds=3)
assert client._timeout_seconds == 3
def test_client_timeout_defaults_to_the_shared_value(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Omitting the keyword keeps the library-wide default."""
client = _client_with_stub_auth(tmp_path, monkeypatch)
assert client._timeout_seconds == _DEFAULT_TIMEOUT_SECONDS

View File

@ -0,0 +1,233 @@
"""Tests for building a sync client from a config file.
Split from ``test_config.py`` (250-line cap);
``test_config_credentials.py`` keeps reading and validating the password.
"""
# These tests assert on private attributes on purpose: `_timeout_seconds`
# and `_path` are exactly what the fixes under test set, and there is no
# public accessor for either.
# pylint: disable=protected-access
from __future__ import annotations
import json
from typing import TYPE_CHECKING
import pytest
from crdt_sync import (
FirebaseConfig,
FirebaseSyncClient,
credential_store_for,
mirror_client_for,
)
from crdt_sync._config import _DEFAULT_TIMEOUT_SECONDS, firebase_client_for
if TYPE_CHECKING:
from pathlib import Path
_VALID = {
"apiKey": "AIzaSyExample",
"databaseUrl": "https://kuhy-syncs-default-rtdb.europe-west1.firebasedatabase.app",
"projectId": "kuhy-syncs",
"uid": "OvA2REQyLIhAHOEjzwS1o877rgG3",
"email": "sync@example.com",
}
class _StubRemote:
"""A do-nothing :class:`~crdt_sync.RemoteStore`, standing in for GitHub.
A real implementation rather than a bare ``object()`` so the type checker
accepts it without a suppression.
"""
def list_directory(self, _path: str) -> list[str]:
"""Report an empty remote directory."""
return []
def get_file_text(self, _path: str) -> str | None:
"""Report the file as absent."""
return None
def put_file_text(self, path: str, text: str, *, message: str) -> None:
"""Accept and discard a write."""
def delete_file(self, path: str, *, message: str = "") -> None:
"""Accept and discard a delete."""
def can_access_remote(self) -> bool:
"""Report the remote as reachable."""
return True
def _write(path: Path, data: object) -> Path:
"""Write ``data`` as JSON to ``path`` and return it."""
path.write_text(json.dumps(data), encoding="utf-8")
return path
def test_credential_store_is_per_app() -> None:
"""Two apps must not share one cache file; concurrent writes corrupt it."""
diet = credential_store_for("diet_guard")
alarm = credential_store_for("wake_alarm")
assert diet._path != alarm._path
assert diet._path.name == "firebase_auth.json"
assert "diet_guard" in str(diet._path)
def test_client_signs_in_only_without_a_cached_session(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""The common path is a cached refresh token, costing no round trip."""
config = FirebaseConfig.load(_write(tmp_path / "firebase.json", _VALID))
sign_ins: list[tuple[str, str]] = []
class _Auth:
def __init__(self, api_key: str, _store: object) -> None:
self.api_key = api_key
def has_session(self) -> bool:
"""Pretend a cached session exists."""
return True
def sign_in(self, email: str, password: str) -> None:
"""Record the sign-in attempt."""
sign_ins.append((email, password)) # pragma: no cover - must not run
monkeypatch.setattr("crdt_sync._config.FirebaseTokenProvider", _Auth)
client = firebase_client_for("diet_guard", config=config)
assert not sign_ins
assert client is not None
def test_client_signs_in_when_there_is_no_session(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Client signs in when there is no session."""
config = FirebaseConfig.load(_write(tmp_path / "firebase.json", _VALID))
password = tmp_path / "password"
password.write_text("hunter2", encoding="utf-8")
monkeypatch.setattr("crdt_sync._config.PASSWORD_FILE", password)
sign_ins: list[tuple[str, str]] = []
class _Auth:
def __init__(self, api_key: str, _store: object) -> None:
self.api_key = api_key
def has_session(self) -> bool:
"""Pretend no cached session exists."""
return False
def sign_in(self, email: str, password_value: str) -> None:
"""Record the credentials the caller signed in with."""
sign_ins.append((email, password_value))
monkeypatch.setattr("crdt_sync._config.FirebaseTokenProvider", _Auth)
firebase_client_for("diet_guard", config=config)
assert sign_ins == [("sync@example.com", "hunter2")]
def test_mirror_client_makes_firebase_primary(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Firebase authoritative, GitHub best-effort -- the cutover shape."""
config = FirebaseConfig.load(_write(tmp_path / "firebase.json", _VALID))
github = _StubRemote()
class _Auth:
def __init__(self, api_key: str, _store: object) -> None:
self.api_key = api_key
def has_session(self) -> bool:
"""Pretend a cached session exists."""
return True
def sign_in(self, email: str, password: str) -> None:
"""Record the sign-in attempt."""
raise AssertionError # pragma: no cover - must not run
monkeypatch.setattr("crdt_sync._config.FirebaseTokenProvider", _Auth)
client = mirror_client_for("diet_guard", github, config=config)
# Reaching into the wrapper is the point: which backend is authoritative
# is the one thing a rollback depends on getting right.
assert client.mirror is github
assert isinstance(client.primary, FirebaseSyncClient)
def test_client_loads_the_shared_config_when_none_is_given(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""The default path: apps name themselves and nothing else."""
monkeypatch.setattr(
"crdt_sync._config.CONFIG_FILE",
_write(tmp_path / "firebase.json", _VALID),
)
class _Auth:
def __init__(self, api_key: str, _store: object) -> None:
self.api_key = api_key
def has_session(self) -> bool:
"""Pretend a cached session exists."""
return True
def sign_in(self, email: str, password: str) -> None:
"""Record the sign-in attempt."""
raise AssertionError # pragma: no cover - must not run
monkeypatch.setattr("crdt_sync._config.FirebaseTokenProvider", _Auth)
assert firebase_client_for("wake_alarm") is not None
def _client_with_stub_auth(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
**kwargs: float,
) -> FirebaseSyncClient:
"""Return a client built with stubbed auth, forwarding ``kwargs``."""
config = FirebaseConfig.load(_write(tmp_path / "firebase.json", _VALID))
class _Auth:
def __init__(self, api_key: str, _store: object) -> None:
"""Record the key; the credential store is irrelevant here."""
self.api_key = api_key
def has_session(self) -> bool:
"""Pretend a cached session exists, so no sign-in is attempted."""
return True
monkeypatch.setattr("crdt_sync._config.FirebaseTokenProvider", _Auth)
return firebase_client_for("diet_guard", config=config, **kwargs)
def test_client_uses_the_requested_timeout(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""A caller's timeout must reach the client, not just the GitHub half."""
# A keyword with a default adds no branch, so coverage alone cannot tell
# whether it is actually threaded through to the client.
client = _client_with_stub_auth(tmp_path, monkeypatch, timeout_seconds=3)
assert client._timeout_seconds == 3
def test_client_timeout_defaults_to_the_shared_value(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Omitting the keyword keeps the library-wide default."""
client = _client_with_stub_auth(tmp_path, monkeypatch)
assert client._timeout_seconds == _DEFAULT_TIMEOUT_SECONDS

View File

@ -0,0 +1,112 @@
"""Tests for reading the sync password and building a client from config.
Split from ``test_config.py`` (250-line cap), which keeps loading and
validating the config document itself.
"""
# These tests assert on private attributes on purpose: `_timeout_seconds`
# and `_path` are exactly what the fixes under test set, and there is no
# public accessor for either.
# pylint: disable=protected-access
from __future__ import annotations
import json
from typing import TYPE_CHECKING
import pytest
from crdt_sync import (
ConfigError,
FirebaseConfig,
)
if TYPE_CHECKING:
from pathlib import Path
_VALID = {
"apiKey": "AIzaSyExample",
"databaseUrl": "https://kuhy-syncs-default-rtdb.europe-west1.firebasedatabase.app",
"projectId": "kuhy-syncs",
"uid": "OvA2REQyLIhAHOEjzwS1o877rgG3",
"email": "sync@example.com",
}
class _StubRemote:
"""A do-nothing :class:`~crdt_sync.RemoteStore`, standing in for GitHub.
A real implementation rather than a bare ``object()`` so the type checker
accepts it without a suppression.
"""
def list_directory(self, _path: str) -> list[str]:
"""Report an empty remote directory."""
return []
def get_file_text(self, _path: str) -> str | None:
"""Report the file as absent."""
return None
def put_file_text(self, path: str, text: str, *, message: str) -> None:
"""Accept and discard a write."""
def delete_file(self, path: str, *, message: str = "") -> None:
"""Accept and discard a delete."""
def can_access_remote(self) -> bool:
"""Report the remote as reachable."""
return True
def _write(path: Path, data: object) -> Path:
"""Write ``data`` as JSON to ``path`` and return it."""
path.write_text(json.dumps(data), encoding="utf-8")
return path
def test_reads_a_password(tmp_path: Path) -> None:
"""Reads a password."""
config = FirebaseConfig.load(_write(tmp_path / "firebase.json", _VALID))
password = tmp_path / "password"
password.write_text("hunter2", encoding="utf-8")
assert config.read_password(password) == "hunter2"
def test_strips_a_trailing_newline_from_the_password(tmp_path: Path) -> None:
"""The likeliest hand-editing mistake, and otherwise invisible."""
config = FirebaseConfig.load(_write(tmp_path / "firebase.json", _VALID))
password = tmp_path / "password"
password.write_text("hunter2\n", encoding="utf-8")
assert config.read_password(password) == "hunter2"
def test_rejects_an_empty_password(tmp_path: Path) -> None:
"""Rejects an empty password."""
config = FirebaseConfig.load(_write(tmp_path / "firebase.json", _VALID))
password = tmp_path / "password"
password.write_text(" ", encoding="utf-8")
with pytest.raises(ConfigError, match="empty or still holds"):
config.read_password(password)
def test_rejects_a_placeholder_password(tmp_path: Path) -> None:
"""Rejects a placeholder password."""
config = FirebaseConfig.load(_write(tmp_path / "firebase.json", _VALID))
password = tmp_path / "password"
password.write_text("PASTE_SYNC_ACCOUNT_PASSWORD_HERE", encoding="utf-8")
with pytest.raises(ConfigError, match="placeholder"):
config.read_password(password)
def test_reports_an_unreadable_password(tmp_path: Path) -> None:
"""Reports an unreadable password."""
config = FirebaseConfig.load(_write(tmp_path / "firebase.json", _VALID))
(tmp_path / "password").mkdir()
with pytest.raises(ConfigError, match="could not be read"):
config.read_password(tmp_path / "password")

View File

@ -25,9 +25,6 @@ from crdt_sync import (
FirebaseSyncError,
FirebaseTokenProvider,
MemoryCredentialStore,
RemoteNotFoundError,
RemoteStore,
RemoteSyncError,
)
from crdt_sync import _firebase as fb
from crdt_sync._firebase import decode_key, encode_key, encode_path
@ -210,160 +207,3 @@ class TestListDirectory:
pytest.raises(FirebaseSyncError),
):
_client().list_directory("ns/devices")
class TestPutFileText:
"""Put file text."""
def test_writes_the_text_as_a_json_string_leaf(self) -> None:
"""Writes the text as a JSON string leaf."""
with (
patch.object(fb.requests, "get", return_value=_response(200, None)),
patch.object(
fb.requests, "put", return_value=_response(200, '{"a":1}')
) as put_mock,
):
_client().put_file_text(
"ns/devices/pc/log.json", '{"a":1}', message="ignored"
)
assert put_mock.call_args.kwargs["json"] == '{"a":1}'
assert put_mock.call_args.args[0].endswith("/log~2Ejson.json")
def test_raises_on_a_non_2xx_response(self) -> None:
"""Raises on a non 2xx response."""
with (
patch.object(
fb.requests, "put", return_value=_response(400, {"error": "bad"})
),
pytest.raises(FirebaseSyncError),
):
_client().put_file_text("ns/devices/pc/log.json", "{}", message="m")
def test_turns_a_network_failure_into_a_sync_error(self) -> None:
"""Turns a network failure into a sync error."""
with (
patch.object(
fb.requests, "put", side_effect=requests.ConnectionError("offline")
),
pytest.raises(FirebaseSyncError, match="network error"),
):
_client().put_file_text("ns/devices/pc/log.json", "{}", message="m")
class TestGetStringMap:
"""Get string map."""
def test_returns_the_map_with_keys_decoded(self) -> None:
"""Returns the map with keys decoded."""
payload = {"pc": "sha-1", "phone": "sha-2"}
with patch.object(fb.requests, "get", return_value=_response(200, payload)):
assert _client().get_string_map("ns/revs") == payload
def test_degrades_to_empty_when_absent(self) -> None:
"""Degrades to empty when absent."""
with patch.object(fb.requests, "get", return_value=_response(200, None)):
assert not _client().get_string_map("ns/revs")
def test_skips_non_string_entries_rather_than_failing(self) -> None:
# The revs node is an optimisation; a corrupt one must degrade into
# "fetch everything", never into a failed tick.
"""Skips non string entries rather than failing."""
with patch.object(
fb.requests, "get", return_value=_response(200, {"pc": "sha-1", "b": 42})
):
assert _client().get_string_map("ns/revs") == {"pc": "sha-1"}
def test_raises_on_a_non_2xx_response(self) -> None:
"""Raises on a non 2xx response."""
with (
patch.object(
fb.requests, "get", return_value=_response(500, {"error": "boom"})
),
pytest.raises(FirebaseSyncError),
):
_client().get_string_map("ns/revs")
class TestDeleteFile:
"""Delete file."""
def test_sends_a_delete_to_the_escaped_path(self) -> None:
"""Sends a delete to the escaped path."""
with patch.object(
fb.requests, "delete", return_value=_response(200, None)
) as delete_mock:
_client().delete_file("ns/devices/pc/log.json")
assert delete_mock.call_args.args[0].endswith("/log~2Ejson.json")
def test_raises_on_a_non_2xx_response(self) -> None:
"""Raises on a non 2xx response."""
with (
patch.object(
fb.requests, "delete", return_value=_response(500, {"error": "boom"})
),
pytest.raises(FirebaseSyncError),
):
_client().delete_file("ns/devices/pc/log.json")
def test_turns_a_network_failure_into_a_sync_error(self) -> None:
"""Turns a network failure into a sync error."""
with (
patch.object(
fb.requests, "delete", side_effect=requests.ConnectionError("x")
),
pytest.raises(FirebaseSyncError, match="network error"),
):
_client().delete_file("ns/devices/pc/log.json")
class TestCanAccessRemote:
"""Can access remote."""
def test_true_when_the_database_root_reads(self) -> None:
"""True when the database root reads."""
with patch.object(fb.requests, "get", return_value=_response(200, {"ns": 1})):
assert _client().can_access_remote() is True
def test_false_when_the_rules_reject_the_token(self) -> None:
"""False when the rules reject the token."""
with patch.object(
fb.requests, "get", return_value=_response(401, {"error": "denied"})
):
assert _client().can_access_remote() is False
def test_false_on_a_network_error(self) -> None:
"""False on a network error."""
with patch.object(
fb.requests, "get", side_effect=requests.ConnectionError("offline")
):
assert _client().can_access_remote() is False
def test_false_when_not_signed_in_rather_than_raising(self) -> None:
# "cannot get a token" is exactly "cannot access the remote", and a
# settings Test-connection button must not blow up.
"""False when not signed in rather than raising."""
assert _client(signed_in=False).can_access_remote() is False
class TestRemoteStoreContract:
"""Remote store contract."""
def test_the_client_satisfies_remote_store(self) -> None:
"""The client satisfies remote store."""
assert isinstance(_client(), RemoteStore)
def test_database_not_found_is_catchable_as_either_error(self) -> None:
"""Database not found is catchable as either error."""
error = DatabaseNotFoundError("gone")
assert isinstance(error, FirebaseSyncError)
assert isinstance(error, RemoteNotFoundError)
assert isinstance(error, RemoteSyncError)
def test_a_trailing_slash_on_the_database_url_is_tolerated(self) -> None:
"""A trailing slash on the database URL is tolerated."""
client = FirebaseSyncClient(f"{_DATABASE_URL}/", _auth())
with patch.object(
fb.requests, "get", return_value=_response(200, "ok")
) as get_mock:
client.get_file_text("ns/x.json")
assert get_mock.call_args.args[0] == f"{_DATABASE_URL}/ns/x~2Ejson.json"

View File

@ -9,14 +9,12 @@ from __future__ import annotations
import datetime as dt
import json
from typing import TYPE_CHECKING
from unittest.mock import MagicMock, patch
import pytest
import requests
from crdt_sync import (
FileCredentialStore,
FirebaseAuthError,
FirebaseCredentials,
FirebaseTokenProvider,
@ -24,9 +22,6 @@ from crdt_sync import (
)
from crdt_sync import _firebase_auth as fa
if TYPE_CHECKING:
from pathlib import Path
_NOW = dt.datetime(2026, 8, 3, 12, tzinfo=dt.timezone.utc)
# Fixture values referenced through names ruff's hardcoded-credential checks
@ -173,267 +168,3 @@ class TestSignIn:
pytest.raises(FirebaseAuthError, match="network error"),
):
_provider().sign_in("a@b.c", "x")
class TestSignInWithGoogle:
"""Sign in with google."""
@staticmethod
def _google_body(**overrides: object) -> dict[str, object]:
body: dict[str, object] = {
"idToken": _ID_1,
"refreshToken": _REFRESH_1,
"expiresIn": "3600",
"localId": _UID,
"email": "me@example.com",
}
body.update(overrides)
return body
def test_stores_the_session(self) -> None:
"""Stores the session."""
store = MemoryCredentialStore()
with _patch_post(_response(200, self._google_body())):
_provider(store).sign_in_with_google("google-jwt")
saved = store.load()
assert saved is not None
assert saved.id_token == _ID_1
assert saved.refresh_token == _REFRESH_1
assert saved.expires_at == _NOW + dt.timedelta(hours=1)
def test_returns_the_account_email(self) -> None:
"""Returns the account email."""
with _patch_post(_response(200, self._google_body())):
email = _provider().sign_in_with_google("google-jwt")
assert email == "me@example.com"
def test_returns_an_empty_email_when_google_omits_one(self) -> None:
# Firebase leaves `email` out when the Google account has no verified
# address. That is not a failure -- the uid check is what matters --
# so the caller gets "" rather than a KeyError.
"""Returns an empty email when google omits one."""
body = self._google_body()
del body["email"]
with _patch_post(_response(200, body)):
assert not _provider().sign_in_with_google("google-jwt")
def test_sends_the_credential_form_encoded_in_post_body(self) -> None:
# identitytoolkit rejects the IdP credential as a JSON field with
# INVALID_IDP_RESPONSE, which reads like a bad token; pin the shape.
"""Sends the credential form encoded in post body."""
post = MagicMock(return_value=_response(200, self._google_body()))
with patch.object(fa.requests, "post", post):
_provider().sign_in_with_google("google-jwt")
sent = post.call_args.kwargs["json"]
assert sent["postBody"] == "id_token=google-jwt&providerId=google.com"
assert "signInWithIdp" in post.call_args.args[0]
def test_accepts_the_uid_the_data_belongs_to(self) -> None:
"""Accepts the uid the data belongs to."""
store = MemoryCredentialStore()
with _patch_post(_response(200, self._google_body())):
_provider(store).sign_in_with_google("google-jwt", expected_uid=_UID)
assert store.load() is not None
def test_rejects_and_stores_nothing_for_a_different_uid(self) -> None:
# The signed-up identity does exist server-side by now -- this call
# omits `idToken`, so an unlinked Google account is signed *up* before
# the uid is known. What this guarantees is that no such session is
# persisted locally, where it would be denied every read and write.
"""Rejects and stores nothing for a different uid."""
store = MemoryCredentialStore()
body = self._google_body(localId="someone-else")
with (
_patch_post(_response(200, body)),
pytest.raises(FirebaseAuthError, match="wrong account"),
):
_provider(store).sign_in_with_google("google-jwt", expected_uid=_UID)
assert store.load() is None
def test_reports_googles_reason_for_a_rejected_token(self) -> None:
"""Reports googles reason for a rejected token."""
body = {"error": {"message": "INVALID_IDP_RESPONSE"}}
with (
_patch_post(_response(400, body)),
pytest.raises(FirebaseAuthError, match="INVALID_IDP_RESPONSE"),
):
_provider().sign_in_with_google("stale-jwt")
class TestIdToken:
"""Id token."""
def test_fails_loudly_when_not_signed_in(self) -> None:
# Never returns None or a stale token: a sync that quietly stops
# syncing is the failure mode this design exists to prevent.
"""Fails loudly when not signed in."""
with pytest.raises(FirebaseAuthError, match="not signed in"):
_provider().id_token()
def test_returns_the_stored_token_without_a_network_call(self) -> None:
"""Returns the stored token without a network call."""
provider = _provider(MemoryCredentialStore(_credentials()))
with patch.object(fa.requests, "post", side_effect=AssertionError("no HTTP")):
assert provider.id_token() == _ID_1
def test_refreshes_an_expired_token_and_keeps_the_rotated_one(self) -> None:
"""Refreshes an expired token and keeps the rotated one."""
store = MemoryCredentialStore(_credentials(valid_for=dt.timedelta(minutes=-5)))
body = {
"id_token": _ID_2,
"refresh_token": _REFRESH_2,
"expires_in": "3600",
}
with _patch_post(_response(200, body)):
assert _provider(store).id_token() == _ID_2
saved = store.load()
assert saved is not None
assert saved.refresh_token == _REFRESH_2
def test_fails_loudly_when_the_refresh_token_was_revoked(self) -> None:
"""Fails loudly when the refresh token was revoked."""
store = MemoryCredentialStore(_credentials(valid_for=dt.timedelta(minutes=-5)))
with (
_patch_post(_response(400, {"error": {"message": "TOKEN_EXPIRED"}})),
pytest.raises(FirebaseAuthError, match="TOKEN_EXPIRED"),
):
_provider(store).id_token()
def test_a_revoked_refresh_token_is_cleared(self) -> None:
"""A dead session must stop reporting itself as connected.
Regression: ``has_session`` is a presence check, so a revoked token
kept reading as "connected" while every sync failed with
TOKEN_EXPIRED.
"""
store = MemoryCredentialStore(_credentials(valid_for=dt.timedelta(minutes=-5)))
provider = _provider(store)
with (
_patch_post(_response(400, {"error": {"message": "TOKEN_EXPIRED"}})),
pytest.raises(FirebaseAuthError),
):
provider.id_token()
assert provider.has_session() is False
assert store.load() is None
def test_a_network_error_keeps_the_session(self) -> None:
"""Signing out on a transient failure would need a manual re-login."""
store = MemoryCredentialStore(_credentials(valid_for=dt.timedelta(minutes=-5)))
provider = _provider(store)
with (
patch.object(
fa.requests,
"post",
side_effect=requests.ConnectionError("connection reset"),
),
pytest.raises(FirebaseAuthError),
):
provider.id_token()
assert provider.has_session() is True
assert store.load() is not None
def test_a_server_error_keeps_the_session(self) -> None:
"""A server error keeps the session."""
store = MemoryCredentialStore(_credentials(valid_for=dt.timedelta(minutes=-5)))
provider = _provider(store)
with (
_patch_post(_response(503, {"error": {"message": "SERVICE_UNAVAILABLE"}})),
pytest.raises(FirebaseAuthError),
):
provider.id_token()
assert provider.has_session() is True
class TestSessionLifecycle:
"""Session lifecycle."""
def test_has_session_is_false_before_sign_in_and_true_after(self) -> None:
"""Has session is false before sign in and true after."""
store = MemoryCredentialStore()
provider = _provider(store)
assert provider.has_session() is False
body = {"idToken": _ID_1, "refreshToken": _REFRESH_1, "expiresIn": "3600"}
with _patch_post(_response(200, body)):
provider.sign_in("a@b.c", "x")
assert provider.has_session() is True
def test_sign_out_clears_the_store(self) -> None:
"""Sign out clears the store."""
store = MemoryCredentialStore(_credentials())
provider = _provider(store)
assert provider.id_token() == _ID_1
provider.sign_out()
assert store.load() is None
with pytest.raises(FirebaseAuthError):
provider.id_token()
def test_defaults_to_the_real_clock_when_none_is_injected(self) -> None:
"""Defaults to the real clock when none is injected."""
provider = FirebaseTokenProvider("k", MemoryCredentialStore())
assert provider.has_session() is False
class TestFileCredentialStore:
"""File credential store."""
def test_round_trips_through_a_file(self, tmp_path: Path) -> None:
"""Round trips through a file."""
store = FileCredentialStore(tmp_path / "nested" / "creds.json")
store.save(_credentials())
assert store.load() == _credentials()
def test_writes_the_file_readable_only_by_this_user(self, tmp_path: Path) -> None:
# The refresh token is the real secret; it must never be briefly
# world-readable between write and chmod.
"""Writes the file readable only by this user."""
path = tmp_path / "creds.json"
FileCredentialStore(path).save(_credentials())
assert path.stat().st_mode & 0o777 == 0o600
def test_load_returns_none_when_absent(self, tmp_path: Path) -> None:
"""Load returns none when absent."""
assert FileCredentialStore(tmp_path / "missing.json").load() is None
def test_load_returns_none_for_a_truncated_file(self, tmp_path: Path) -> None:
# An interrupted write reads as "not signed in"; the caller's next
# step is to sign in again, which repairs it.
"""Load returns none for a truncated file."""
path = tmp_path / "creds.json"
path.write_text('{"id_token": "a"', encoding="utf-8")
assert FileCredentialStore(path).load() is None
def test_load_returns_none_when_fields_are_missing(self, tmp_path: Path) -> None:
"""Load returns none when fields are missing."""
path = tmp_path / "creds.json"
path.write_text('{"id_token": "a"}', encoding="utf-8")
assert FileCredentialStore(path).load() is None
def test_load_returns_none_for_an_unparsable_expiry(self, tmp_path: Path) -> None:
"""Load returns none for an unparsable expiry."""
path = tmp_path / "creds.json"
path.write_text(
json.dumps(
{"id_token": "a", "refresh_token": "b", "expires_at": "not-a-date"}
),
encoding="utf-8",
)
assert FileCredentialStore(path).load() is None
def test_clear_removes_the_file_and_is_idempotent(self, tmp_path: Path) -> None:
"""Clear removes the file and is idempotent."""
path = tmp_path / "creds.json"
store = FileCredentialStore(path)
store.save(_credentials())
store.clear()
assert not path.exists()
store.clear()
def test_overwrites_an_existing_file(self, tmp_path: Path) -> None:
"""Overwrites an existing file."""
path = tmp_path / "creds.json"
store = FileCredentialStore(path)
store.save(_credentials())
store.save(_credentials(id_value=_ID_2))
loaded = store.load()
assert loaded is not None
assert loaded.id_token == _ID_2

View File

@ -0,0 +1,159 @@
"""Tests for the Google sign-in path.
Split from ``test_firebase_auth.py`` (250-line cap), which keeps credential
handling and password sign-in.
"""
from __future__ import annotations
import datetime as dt
import json
from unittest.mock import MagicMock, patch
import pytest
from crdt_sync import (
FirebaseAuthError,
FirebaseCredentials,
FirebaseTokenProvider,
MemoryCredentialStore,
)
from crdt_sync import _firebase_auth as fa
_NOW = dt.datetime(2026, 8, 3, 12, tzinfo=dt.timezone.utc)
# Fixture values referenced through names ruff's hardcoded-credential checks
# (S105-S107) do not key off. Comparing an attribute called `id_token` to a
# bare string literal trips S105 no matter how obviously fake the value is.
_ID_1 = "id-1"
_ID_2 = "id-2"
_REFRESH_1 = "refresh-1"
_REFRESH_2 = "refresh-2"
_UID = "uid-the-data-belongs-to"
def _response(status_code: int = 200, json_data: object = None) -> MagicMock:
"""Build a fake ``requests.Response`` with a status and JSON body."""
response = MagicMock()
response.status_code = status_code
response.ok = 200 <= status_code < 300
response.json = MagicMock(return_value=json_data if json_data is not None else {})
response.text = json.dumps(json_data) if json_data is not None else ""
return response
def _provider(
store: object = None,
*,
now: dt.datetime = _NOW,
) -> FirebaseTokenProvider:
return FirebaseTokenProvider(
"fake-api-key",
store or MemoryCredentialStore(),
clock=lambda: now,
)
# Parameters named without "token": ruff's hardcoded-credential check (S107)
# keys off the identifier, and these are obviously fake test fixtures.
def _credentials(
*,
id_value: str = _ID_1,
refresh_value: str = _REFRESH_1,
valid_for: dt.timedelta = dt.timedelta(hours=1),
) -> FirebaseCredentials:
return FirebaseCredentials(
id_token=id_value,
refresh_token=refresh_value,
expires_at=_NOW + valid_for,
)
def _patch_post(*responses: MagicMock) -> object:
return patch.object(fa.requests, "post", side_effect=list(responses))
class TestSignInWithGoogle:
"""Sign in with google."""
@staticmethod
def _google_body(**overrides: object) -> dict[str, object]:
body: dict[str, object] = {
"idToken": _ID_1,
"refreshToken": _REFRESH_1,
"expiresIn": "3600",
"localId": _UID,
"email": "me@example.com",
}
body.update(overrides)
return body
def test_stores_the_session(self) -> None:
"""Stores the session."""
store = MemoryCredentialStore()
with _patch_post(_response(200, self._google_body())):
_provider(store).sign_in_with_google("google-jwt")
saved = store.load()
assert saved is not None
assert saved.id_token == _ID_1
assert saved.refresh_token == _REFRESH_1
assert saved.expires_at == _NOW + dt.timedelta(hours=1)
def test_returns_the_account_email(self) -> None:
"""Returns the account email."""
with _patch_post(_response(200, self._google_body())):
email = _provider().sign_in_with_google("google-jwt")
assert email == "me@example.com"
def test_returns_an_empty_email_when_google_omits_one(self) -> None:
# Firebase leaves `email` out when the Google account has no verified
# address. That is not a failure -- the uid check is what matters --
# so the caller gets "" rather than a KeyError.
"""Returns an empty email when google omits one."""
body = self._google_body()
del body["email"]
with _patch_post(_response(200, body)):
assert not _provider().sign_in_with_google("google-jwt")
def test_sends_the_credential_form_encoded_in_post_body(self) -> None:
# identitytoolkit rejects the IdP credential as a JSON field with
# INVALID_IDP_RESPONSE, which reads like a bad token; pin the shape.
"""Sends the credential form encoded in post body."""
post = MagicMock(return_value=_response(200, self._google_body()))
with patch.object(fa.requests, "post", post):
_provider().sign_in_with_google("google-jwt")
sent = post.call_args.kwargs["json"]
assert sent["postBody"] == "id_token=google-jwt&providerId=google.com"
assert "signInWithIdp" in post.call_args.args[0]
def test_accepts_the_uid_the_data_belongs_to(self) -> None:
"""Accepts the uid the data belongs to."""
store = MemoryCredentialStore()
with _patch_post(_response(200, self._google_body())):
_provider(store).sign_in_with_google("google-jwt", expected_uid=_UID)
assert store.load() is not None
def test_rejects_and_stores_nothing_for_a_different_uid(self) -> None:
# The signed-up identity does exist server-side by now -- this call
# omits `idToken`, so an unlinked Google account is signed *up* before
# the uid is known. What this guarantees is that no such session is
# persisted locally, where it would be denied every read and write.
"""Rejects and stores nothing for a different uid."""
store = MemoryCredentialStore()
body = self._google_body(localId="someone-else")
with (
_patch_post(_response(200, body)),
pytest.raises(FirebaseAuthError, match="wrong account"),
):
_provider(store).sign_in_with_google("google-jwt", expected_uid=_UID)
assert store.load() is None
def test_reports_googles_reason_for_a_rejected_token(self) -> None:
"""Reports googles reason for a rejected token."""
body = {"error": {"message": "INVALID_IDP_RESPONSE"}}
with (
_patch_post(_response(400, body)),
pytest.raises(FirebaseAuthError, match="INVALID_IDP_RESPONSE"),
):
_provider().sign_in_with_google("stale-jwt")

View File

@ -0,0 +1,175 @@
"""Tests for the auth session lifecycle.
Split from ``test_firebase_auth.py`` (250-line cap);
``test_firebase_auth_tokens.py`` keeps ID-token refresh.
"""
from __future__ import annotations
import datetime as dt
import json
from typing import TYPE_CHECKING
from unittest.mock import MagicMock, patch
import pytest
from crdt_sync import (
FileCredentialStore,
FirebaseAuthError,
FirebaseCredentials,
FirebaseTokenProvider,
MemoryCredentialStore,
)
from crdt_sync import _firebase_auth as fa
if TYPE_CHECKING:
from pathlib import Path
_NOW = dt.datetime(2026, 8, 3, 12, tzinfo=dt.timezone.utc)
# Fixture values referenced through names ruff's hardcoded-credential checks
# (S105-S107) do not key off. Comparing an attribute called `id_token` to a
# bare string literal trips S105 no matter how obviously fake the value is.
_ID_1 = "id-1"
_ID_2 = "id-2"
_REFRESH_1 = "refresh-1"
_REFRESH_2 = "refresh-2"
_UID = "uid-the-data-belongs-to"
def _response(status_code: int = 200, json_data: object = None) -> MagicMock:
"""Build a fake ``requests.Response`` with a status and JSON body."""
response = MagicMock()
response.status_code = status_code
response.ok = 200 <= status_code < 300
response.json = MagicMock(return_value=json_data if json_data is not None else {})
response.text = json.dumps(json_data) if json_data is not None else ""
return response
def _provider(
store: object = None,
*,
now: dt.datetime = _NOW,
) -> FirebaseTokenProvider:
return FirebaseTokenProvider(
"fake-api-key",
store or MemoryCredentialStore(),
clock=lambda: now,
)
# Parameters named without "token": ruff's hardcoded-credential check (S107)
# keys off the identifier, and these are obviously fake test fixtures.
def _credentials(
*,
id_value: str = _ID_1,
refresh_value: str = _REFRESH_1,
valid_for: dt.timedelta = dt.timedelta(hours=1),
) -> FirebaseCredentials:
return FirebaseCredentials(
id_token=id_value,
refresh_token=refresh_value,
expires_at=_NOW + valid_for,
)
def _patch_post(*responses: MagicMock) -> object:
return patch.object(fa.requests, "post", side_effect=list(responses))
class TestSessionLifecycle:
"""Session lifecycle."""
def test_has_session_is_false_before_sign_in_and_true_after(self) -> None:
"""Has session is false before sign in and true after."""
store = MemoryCredentialStore()
provider = _provider(store)
assert provider.has_session() is False
body = {"idToken": _ID_1, "refreshToken": _REFRESH_1, "expiresIn": "3600"}
with _patch_post(_response(200, body)):
provider.sign_in("a@b.c", "x")
assert provider.has_session() is True
def test_sign_out_clears_the_store(self) -> None:
"""Sign out clears the store."""
store = MemoryCredentialStore(_credentials())
provider = _provider(store)
assert provider.id_token() == _ID_1
provider.sign_out()
assert store.load() is None
with pytest.raises(FirebaseAuthError):
provider.id_token()
def test_defaults_to_the_real_clock_when_none_is_injected(self) -> None:
"""Defaults to the real clock when none is injected."""
provider = FirebaseTokenProvider("k", MemoryCredentialStore())
assert provider.has_session() is False
class TestFileCredentialStore:
"""File credential store."""
def test_round_trips_through_a_file(self, tmp_path: Path) -> None:
"""Round trips through a file."""
store = FileCredentialStore(tmp_path / "nested" / "creds.json")
store.save(_credentials())
assert store.load() == _credentials()
def test_writes_the_file_readable_only_by_this_user(self, tmp_path: Path) -> None:
# The refresh token is the real secret; it must never be briefly
# world-readable between write and chmod.
"""Writes the file readable only by this user."""
path = tmp_path / "creds.json"
FileCredentialStore(path).save(_credentials())
assert path.stat().st_mode & 0o777 == 0o600
def test_load_returns_none_when_absent(self, tmp_path: Path) -> None:
"""Load returns none when absent."""
assert FileCredentialStore(tmp_path / "missing.json").load() is None
def test_load_returns_none_for_a_truncated_file(self, tmp_path: Path) -> None:
# An interrupted write reads as "not signed in"; the caller's next
# step is to sign in again, which repairs it.
"""Load returns none for a truncated file."""
path = tmp_path / "creds.json"
path.write_text('{"id_token": "a"', encoding="utf-8")
assert FileCredentialStore(path).load() is None
def test_load_returns_none_when_fields_are_missing(self, tmp_path: Path) -> None:
"""Load returns none when fields are missing."""
path = tmp_path / "creds.json"
path.write_text('{"id_token": "a"}', encoding="utf-8")
assert FileCredentialStore(path).load() is None
def test_load_returns_none_for_an_unparsable_expiry(self, tmp_path: Path) -> None:
"""Load returns none for an unparsable expiry."""
path = tmp_path / "creds.json"
path.write_text(
json.dumps(
{"id_token": "a", "refresh_token": "b", "expires_at": "not-a-date"}
),
encoding="utf-8",
)
assert FileCredentialStore(path).load() is None
def test_clear_removes_the_file_and_is_idempotent(self, tmp_path: Path) -> None:
"""Clear removes the file and is idempotent."""
path = tmp_path / "creds.json"
store = FileCredentialStore(path)
store.save(_credentials())
store.clear()
assert not path.exists()
store.clear()
def test_overwrites_an_existing_file(self, tmp_path: Path) -> None:
"""Overwrites an existing file."""
path = tmp_path / "creds.json"
store = FileCredentialStore(path)
store.save(_credentials())
store.save(_credentials(id_value=_ID_2))
loaded = store.load()
assert loaded is not None
assert loaded.id_token == _ID_2

View File

@ -0,0 +1,159 @@
"""Tests for ID-token refresh and the session lifecycle.
Split from ``test_firebase_auth.py`` (250-line cap), which keeps credential
handling and the two sign-in paths.
"""
from __future__ import annotations
import datetime as dt
import json
from unittest.mock import MagicMock, patch
import pytest
import requests
from crdt_sync import (
FirebaseAuthError,
FirebaseCredentials,
FirebaseTokenProvider,
MemoryCredentialStore,
)
from crdt_sync import _firebase_auth as fa
_NOW = dt.datetime(2026, 8, 3, 12, tzinfo=dt.timezone.utc)
# Fixture values referenced through names ruff's hardcoded-credential checks
# (S105-S107) do not key off. Comparing an attribute called `id_token` to a
# bare string literal trips S105 no matter how obviously fake the value is.
_ID_1 = "id-1"
_ID_2 = "id-2"
_REFRESH_1 = "refresh-1"
_REFRESH_2 = "refresh-2"
_UID = "uid-the-data-belongs-to"
def _response(status_code: int = 200, json_data: object = None) -> MagicMock:
"""Build a fake ``requests.Response`` with a status and JSON body."""
response = MagicMock()
response.status_code = status_code
response.ok = 200 <= status_code < 300
response.json = MagicMock(return_value=json_data if json_data is not None else {})
response.text = json.dumps(json_data) if json_data is not None else ""
return response
def _provider(
store: object = None,
*,
now: dt.datetime = _NOW,
) -> FirebaseTokenProvider:
return FirebaseTokenProvider(
"fake-api-key",
store or MemoryCredentialStore(),
clock=lambda: now,
)
# Parameters named without "token": ruff's hardcoded-credential check (S107)
# keys off the identifier, and these are obviously fake test fixtures.
def _credentials(
*,
id_value: str = _ID_1,
refresh_value: str = _REFRESH_1,
valid_for: dt.timedelta = dt.timedelta(hours=1),
) -> FirebaseCredentials:
return FirebaseCredentials(
id_token=id_value,
refresh_token=refresh_value,
expires_at=_NOW + valid_for,
)
def _patch_post(*responses: MagicMock) -> object:
return patch.object(fa.requests, "post", side_effect=list(responses))
class TestIdToken:
"""Id token."""
def test_fails_loudly_when_not_signed_in(self) -> None:
# Never returns None or a stale token: a sync that quietly stops
# syncing is the failure mode this design exists to prevent.
"""Fails loudly when not signed in."""
with pytest.raises(FirebaseAuthError, match="not signed in"):
_provider().id_token()
def test_returns_the_stored_token_without_a_network_call(self) -> None:
"""Returns the stored token without a network call."""
provider = _provider(MemoryCredentialStore(_credentials()))
with patch.object(fa.requests, "post", side_effect=AssertionError("no HTTP")):
assert provider.id_token() == _ID_1
def test_refreshes_an_expired_token_and_keeps_the_rotated_one(self) -> None:
"""Refreshes an expired token and keeps the rotated one."""
store = MemoryCredentialStore(_credentials(valid_for=dt.timedelta(minutes=-5)))
body = {
"id_token": _ID_2,
"refresh_token": _REFRESH_2,
"expires_in": "3600",
}
with _patch_post(_response(200, body)):
assert _provider(store).id_token() == _ID_2
saved = store.load()
assert saved is not None
assert saved.refresh_token == _REFRESH_2
def test_fails_loudly_when_the_refresh_token_was_revoked(self) -> None:
"""Fails loudly when the refresh token was revoked."""
store = MemoryCredentialStore(_credentials(valid_for=dt.timedelta(minutes=-5)))
with (
_patch_post(_response(400, {"error": {"message": "TOKEN_EXPIRED"}})),
pytest.raises(FirebaseAuthError, match="TOKEN_EXPIRED"),
):
_provider(store).id_token()
def test_a_revoked_refresh_token_is_cleared(self) -> None:
"""A dead session must stop reporting itself as connected.
Regression: ``has_session`` is a presence check, so a revoked token
kept reading as "connected" while every sync failed with
TOKEN_EXPIRED.
"""
store = MemoryCredentialStore(_credentials(valid_for=dt.timedelta(minutes=-5)))
provider = _provider(store)
with (
_patch_post(_response(400, {"error": {"message": "TOKEN_EXPIRED"}})),
pytest.raises(FirebaseAuthError),
):
provider.id_token()
assert provider.has_session() is False
assert store.load() is None
def test_a_network_error_keeps_the_session(self) -> None:
"""Signing out on a transient failure would need a manual re-login."""
store = MemoryCredentialStore(_credentials(valid_for=dt.timedelta(minutes=-5)))
provider = _provider(store)
with (
patch.object(
fa.requests,
"post",
side_effect=requests.ConnectionError("connection reset"),
),
pytest.raises(FirebaseAuthError),
):
provider.id_token()
assert provider.has_session() is True
assert store.load() is not None
def test_a_server_error_keeps_the_session(self) -> None:
"""A server error keeps the session."""
store = MemoryCredentialStore(_credentials(valid_for=dt.timedelta(minutes=-5)))
provider = _provider(store)
with (
_patch_post(_response(503, {"error": {"message": "SERVICE_UNAVAILABLE"}})),
pytest.raises(FirebaseAuthError),
):
provider.id_token()
assert provider.has_session() is True

View File

@ -0,0 +1,220 @@
"""Tests for Firebase writes, string maps and deletion.
Split from ``test_firebase.py`` (250-line cap), which keeps key escaping
and the read paths.
"""
from __future__ import annotations
import datetime as dt
import json
from unittest.mock import MagicMock, patch
import pytest
import requests
from crdt_sync import (
DatabaseNotFoundError,
FirebaseCredentials,
FirebaseSyncClient,
FirebaseSyncError,
FirebaseTokenProvider,
MemoryCredentialStore,
RemoteNotFoundError,
RemoteStore,
RemoteSyncError,
)
from crdt_sync import _firebase as fb
_DATABASE_URL = "https://example-default-rtdb.europe-west1.firebasedatabase.app"
# Named without the word "token": ruff's hardcoded-credential checks (S105 /
# S106) key off the identifier, and these are obviously fake test fixtures.
_FAKE_ID = "id-fixture"
_FAKE_REFRESH = "refresh-fixture"
def _response(status_code: int = 200, json_data: object = None) -> MagicMock:
"""Build a fake ``requests.Response`` with a status and JSON body."""
response = MagicMock()
response.status_code = status_code
response.ok = 200 <= status_code < 300
response.json = MagicMock(return_value=json_data)
response.text = json.dumps(json_data)
return response
def _auth(*, signed_in: bool = True) -> FirebaseTokenProvider:
"""A provider holding a long-lived token, so no auth HTTP is needed."""
credentials = (
FirebaseCredentials(
id_token=_FAKE_ID,
refresh_token=_FAKE_REFRESH,
expires_at=dt.datetime(2099, 1, 1, tzinfo=dt.timezone.utc),
)
if signed_in
else None
)
return FirebaseTokenProvider("fake-api-key", MemoryCredentialStore(credentials))
def _client(*, signed_in: bool = True) -> FirebaseSyncClient:
return FirebaseSyncClient(_DATABASE_URL, _auth(signed_in=signed_in))
class TestPutFileText:
"""Put file text."""
def test_writes_the_text_as_a_json_string_leaf(self) -> None:
"""Writes the text as a JSON string leaf."""
with (
patch.object(fb.requests, "get", return_value=_response(200, None)),
patch.object(
fb.requests, "put", return_value=_response(200, '{"a":1}')
) as put_mock,
):
_client().put_file_text(
"ns/devices/pc/log.json", '{"a":1}', message="ignored"
)
assert put_mock.call_args.kwargs["json"] == '{"a":1}'
assert put_mock.call_args.args[0].endswith("/log~2Ejson.json")
def test_raises_on_a_non_2xx_response(self) -> None:
"""Raises on a non 2xx response."""
with (
patch.object(
fb.requests, "put", return_value=_response(400, {"error": "bad"})
),
pytest.raises(FirebaseSyncError),
):
_client().put_file_text("ns/devices/pc/log.json", "{}", message="m")
def test_turns_a_network_failure_into_a_sync_error(self) -> None:
"""Turns a network failure into a sync error."""
with (
patch.object(
fb.requests, "put", side_effect=requests.ConnectionError("offline")
),
pytest.raises(FirebaseSyncError, match="network error"),
):
_client().put_file_text("ns/devices/pc/log.json", "{}", message="m")
class TestGetStringMap:
"""Get string map."""
def test_returns_the_map_with_keys_decoded(self) -> None:
"""Returns the map with keys decoded."""
payload = {"pc": "sha-1", "phone": "sha-2"}
with patch.object(fb.requests, "get", return_value=_response(200, payload)):
assert _client().get_string_map("ns/revs") == payload
def test_degrades_to_empty_when_absent(self) -> None:
"""Degrades to empty when absent."""
with patch.object(fb.requests, "get", return_value=_response(200, None)):
assert not _client().get_string_map("ns/revs")
def test_skips_non_string_entries_rather_than_failing(self) -> None:
# The revs node is an optimisation; a corrupt one must degrade into
# "fetch everything", never into a failed tick.
"""Skips non string entries rather than failing."""
with patch.object(
fb.requests, "get", return_value=_response(200, {"pc": "sha-1", "b": 42})
):
assert _client().get_string_map("ns/revs") == {"pc": "sha-1"}
def test_raises_on_a_non_2xx_response(self) -> None:
"""Raises on a non 2xx response."""
with (
patch.object(
fb.requests, "get", return_value=_response(500, {"error": "boom"})
),
pytest.raises(FirebaseSyncError),
):
_client().get_string_map("ns/revs")
class TestDeleteFile:
"""Delete file."""
def test_sends_a_delete_to_the_escaped_path(self) -> None:
"""Sends a delete to the escaped path."""
with patch.object(
fb.requests, "delete", return_value=_response(200, None)
) as delete_mock:
_client().delete_file("ns/devices/pc/log.json")
assert delete_mock.call_args.args[0].endswith("/log~2Ejson.json")
def test_raises_on_a_non_2xx_response(self) -> None:
"""Raises on a non 2xx response."""
with (
patch.object(
fb.requests, "delete", return_value=_response(500, {"error": "boom"})
),
pytest.raises(FirebaseSyncError),
):
_client().delete_file("ns/devices/pc/log.json")
def test_turns_a_network_failure_into_a_sync_error(self) -> None:
"""Turns a network failure into a sync error."""
with (
patch.object(
fb.requests, "delete", side_effect=requests.ConnectionError("x")
),
pytest.raises(FirebaseSyncError, match="network error"),
):
_client().delete_file("ns/devices/pc/log.json")
class TestCanAccessRemote:
"""Can access remote."""
def test_true_when_the_database_root_reads(self) -> None:
"""True when the database root reads."""
with patch.object(fb.requests, "get", return_value=_response(200, {"ns": 1})):
assert _client().can_access_remote() is True
def test_false_when_the_rules_reject_the_token(self) -> None:
"""False when the rules reject the token."""
with patch.object(
fb.requests, "get", return_value=_response(401, {"error": "denied"})
):
assert _client().can_access_remote() is False
def test_false_on_a_network_error(self) -> None:
"""False on a network error."""
with patch.object(
fb.requests, "get", side_effect=requests.ConnectionError("offline")
):
assert _client().can_access_remote() is False
def test_false_when_not_signed_in_rather_than_raising(self) -> None:
# "cannot get a token" is exactly "cannot access the remote", and a
# settings Test-connection button must not blow up.
"""False when not signed in rather than raising."""
assert _client(signed_in=False).can_access_remote() is False
class TestRemoteStoreContract:
"""Remote store contract."""
def test_the_client_satisfies_remote_store(self) -> None:
"""The client satisfies remote store."""
assert isinstance(_client(), RemoteStore)
def test_database_not_found_is_catchable_as_either_error(self) -> None:
"""Database not found is catchable as either error."""
error = DatabaseNotFoundError("gone")
assert isinstance(error, FirebaseSyncError)
assert isinstance(error, RemoteNotFoundError)
assert isinstance(error, RemoteSyncError)
def test_a_trailing_slash_on_the_database_url_is_tolerated(self) -> None:
"""A trailing slash on the database URL is tolerated."""
client = FirebaseSyncClient(f"{_DATABASE_URL}/", _auth())
with patch.object(
fb.requests, "get", return_value=_response(200, "ok")
) as get_mock:
client.get_file_text("ns/x.json")
assert get_mock.call_args.args[0] == f"{_DATABASE_URL}/ns/x~2Ejson.json"

View File

@ -16,9 +16,6 @@ import requests
from crdt_sync import (
GitHubSyncClient,
GitHubSyncError,
RemoteNotFoundError,
RemoteStore,
RemoteSyncError,
RepoNotFoundError,
_github,
)
@ -128,174 +125,3 @@ class TestListDirectory:
"""Raises sync error on a non 2xx non 404."""
with _patch_get(_response(500)), pytest.raises(GitHubSyncError):
_client().list_directory("devices")
class TestPutFileText:
"""Put file text."""
def test_creates_a_new_file_with_no_sha_when_none_existed(self) -> None:
"""Creates a new file with no sha when none existed."""
with (
_patch_get(_response(404), _response(200)),
patch.object(
_github.requests, "put", return_value=_response(201)
) as put_mock,
):
_client().put_file_text("devices/pc/log.json", "{}", message="m")
assert "sha" not in put_mock.call_args.kwargs["json"]
def test_updates_an_existing_file_by_including_its_sha(self) -> None:
"""Updates an existing file by including its sha."""
with (
_patch_get(_response(200, {"sha": "abc123"})),
patch.object(
_github.requests, "put", return_value=_response(200)
) as put_mock,
):
_client().put_file_text("devices/pc/log.json", "{}", message="m")
assert put_mock.call_args.kwargs["json"]["sha"] == "abc123"
def test_treats_a_non_string_sha_field_as_absent(self) -> None:
"""Treats a non string sha field as absent."""
with (
_patch_get(_response(200, {"sha": 12345})),
patch.object(
_github.requests, "put", return_value=_response(200)
) as put_mock,
):
_client().put_file_text("devices/pc/log.json", "{}", message="m")
assert "sha" not in put_mock.call_args.kwargs["json"]
def test_raises_repo_not_found_when_checking_sha_on_a_missing_repo(self) -> None:
"""Raises repo not found when checking sha on a missing repo."""
with (
_patch_get(_response(404), _response(404)),
pytest.raises(RepoNotFoundError),
):
_client().put_file_text("devices/pc/log.json", "{}", message="m")
def test_raises_sync_error_when_the_sha_check_itself_fails(self) -> None:
"""Raises sync error when the sha check itself fails."""
with _patch_get(_response(500)), pytest.raises(GitHubSyncError):
_client().put_file_text("devices/pc/log.json", "{}", message="m")
def test_raises_sync_error_on_a_put_network_exception(self) -> None:
"""Raises sync error on a put network exception."""
with (
_patch_get(_response(404), _response(200)),
patch.object(
_github.requests,
"put",
side_effect=requests.ConnectionError("offline"),
),
pytest.raises(GitHubSyncError),
):
_client().put_file_text("devices/pc/log.json", "{}", message="m")
def test_raises_sync_error_on_a_put_non_2xx_response(self) -> None:
"""Raises sync error on a put non 2xx response."""
with (
_patch_get(_response(404), _response(200)),
patch.object(_github.requests, "put", return_value=_response(422)),
pytest.raises(GitHubSyncError),
):
_client().put_file_text("devices/pc/log.json", "{}", message="m")
class TestCanAccessRepo:
"""Can access repo."""
def test_true_when_repo_endpoint_ok(self) -> None:
"""True when repo endpoint ok."""
with _patch_get(_response(200)):
assert _client().can_access_repo() is True
def test_false_when_repo_is_missing(self) -> None:
"""False when repo is missing."""
with _patch_get(_response(404)):
assert _client().can_access_repo() is False
def test_false_on_a_network_error(self) -> None:
"""False on a network error."""
with _patch_get_raises():
assert _client().can_access_repo() is False
class TestCanAccessRemote:
"""The ``RemoteStore`` spelling must behave exactly like the legacy name."""
def test_true_when_repo_endpoint_ok(self) -> None:
"""True when repo endpoint ok."""
with _patch_get(_response(200)):
assert _client().can_access_remote() is True
def test_false_when_repo_is_missing(self) -> None:
"""False when repo is missing."""
with _patch_get(_response(404)):
assert _client().can_access_remote() is False
def test_false_on_a_network_error(self) -> None:
"""False on a network error."""
with _patch_get_raises():
assert _client().can_access_remote() is False
class TestRemoteStoreContract:
"""The seam sync talks through must actually be satisfied by the client."""
def test_github_client_is_a_remote_store(self) -> None:
"""Github client is a remote store."""
assert isinstance(_client(), RemoteStore)
def test_repo_not_found_is_catchable_as_either_error(self) -> None:
# Backend-neutral callers catch RemoteNotFoundError; existing GitHub
# callers catch GitHubSyncError. One exception must satisfy both.
"""Repo not found is catchable as either error."""
error = RepoNotFoundError("gone")
assert isinstance(error, GitHubSyncError)
assert isinstance(error, RemoteNotFoundError)
assert isinstance(error, RemoteSyncError)
class TestDeleteFile:
"""Delete file."""
def test_deletes_an_existing_file_resolving_its_own_sha(self) -> None:
"""Deletes an existing file resolving its own sha."""
with (
_patch_get(_response(200, {"sha": "abc123"})),
patch.object(_github.requests, "delete", return_value=_response(200)),
):
_client().delete_file("devices/pc/log.json")
def test_is_a_no_op_when_the_file_is_absent(self) -> None:
# sha GET 404, repo-exists GET 200 -> None sha -> no DELETE sent.
"""Is a no op when the file is absent."""
with (
_patch_get(_response(404), _response(200)),
patch.object(_github.requests, "delete") as mock_delete,
):
_client().delete_file("devices/pc/gone.json")
mock_delete.assert_not_called()
def test_raises_on_a_delete_non_2xx_response(self) -> None:
"""Raises on a delete non 2xx response."""
with (
_patch_get(_response(200, {"sha": "abc123"})),
patch.object(_github.requests, "delete", return_value=_response(500)),
pytest.raises(GitHubSyncError),
):
_client().delete_file("devices/pc/log.json")
def test_raises_on_a_delete_network_error(self) -> None:
"""Raises on a delete network error."""
with (
_patch_get(_response(200, {"sha": "abc123"})),
patch.object(
_github.requests,
"delete",
side_effect=requests.ConnectionError("offline"),
),
pytest.raises(GitHubSyncError),
):
_client().delete_file("devices/pc/log.json")

View File

@ -0,0 +1,219 @@
"""Tests for GitHub writes and access checks.
Split from ``test_github.py`` (250-line cap), which keeps the read paths.
"""
from __future__ import annotations
from unittest.mock import MagicMock, patch
import pytest
import requests
from crdt_sync import (
GitHubSyncClient,
GitHubSyncError,
RemoteNotFoundError,
RemoteStore,
RemoteSyncError,
RepoNotFoundError,
_github,
)
def _response(status_code: int = 200, json_data: object = None) -> MagicMock:
"""Build a fake ``requests.Response`` with a fixed status and JSON body."""
response = MagicMock()
response.status_code = status_code
response.ok = 200 <= status_code < 300
response.json = MagicMock(return_value=json_data if json_data is not None else {})
return response
def _client() -> GitHubSyncClient:
return GitHubSyncClient("kuhyx", "crdt-sync-demo", "fake-token")
def _patch_get(*responses: MagicMock) -> object:
"""Patch ``requests.get`` to return each of ``responses`` in order."""
return patch.object(_github.requests, "get", side_effect=list(responses))
def _patch_get_raises() -> object:
return patch.object(
_github.requests,
"get",
side_effect=requests.ConnectionError("offline"),
)
class TestPutFileText:
"""Put file text."""
def test_creates_a_new_file_with_no_sha_when_none_existed(self) -> None:
"""Creates a new file with no sha when none existed."""
with (
_patch_get(_response(404), _response(200)),
patch.object(
_github.requests, "put", return_value=_response(201)
) as put_mock,
):
_client().put_file_text("devices/pc/log.json", "{}", message="m")
assert "sha" not in put_mock.call_args.kwargs["json"]
def test_updates_an_existing_file_by_including_its_sha(self) -> None:
"""Updates an existing file by including its sha."""
with (
_patch_get(_response(200, {"sha": "abc123"})),
patch.object(
_github.requests, "put", return_value=_response(200)
) as put_mock,
):
_client().put_file_text("devices/pc/log.json", "{}", message="m")
assert put_mock.call_args.kwargs["json"]["sha"] == "abc123"
def test_treats_a_non_string_sha_field_as_absent(self) -> None:
"""Treats a non string sha field as absent."""
with (
_patch_get(_response(200, {"sha": 12345})),
patch.object(
_github.requests, "put", return_value=_response(200)
) as put_mock,
):
_client().put_file_text("devices/pc/log.json", "{}", message="m")
assert "sha" not in put_mock.call_args.kwargs["json"]
def test_raises_repo_not_found_when_checking_sha_on_a_missing_repo(self) -> None:
"""Raises repo not found when checking sha on a missing repo."""
with (
_patch_get(_response(404), _response(404)),
pytest.raises(RepoNotFoundError),
):
_client().put_file_text("devices/pc/log.json", "{}", message="m")
def test_raises_sync_error_when_the_sha_check_itself_fails(self) -> None:
"""Raises sync error when the sha check itself fails."""
with _patch_get(_response(500)), pytest.raises(GitHubSyncError):
_client().put_file_text("devices/pc/log.json", "{}", message="m")
def test_raises_sync_error_on_a_put_network_exception(self) -> None:
"""Raises sync error on a put network exception."""
with (
_patch_get(_response(404), _response(200)),
patch.object(
_github.requests,
"put",
side_effect=requests.ConnectionError("offline"),
),
pytest.raises(GitHubSyncError),
):
_client().put_file_text("devices/pc/log.json", "{}", message="m")
def test_raises_sync_error_on_a_put_non_2xx_response(self) -> None:
"""Raises sync error on a put non 2xx response."""
with (
_patch_get(_response(404), _response(200)),
patch.object(_github.requests, "put", return_value=_response(422)),
pytest.raises(GitHubSyncError),
):
_client().put_file_text("devices/pc/log.json", "{}", message="m")
class TestCanAccessRepo:
"""Can access repo."""
def test_true_when_repo_endpoint_ok(self) -> None:
"""True when repo endpoint ok."""
with _patch_get(_response(200)):
assert _client().can_access_repo() is True
def test_false_when_repo_is_missing(self) -> None:
"""False when repo is missing."""
with _patch_get(_response(404)):
assert _client().can_access_repo() is False
def test_false_on_a_network_error(self) -> None:
"""False on a network error."""
with _patch_get_raises():
assert _client().can_access_repo() is False
class TestCanAccessRemote:
"""The ``RemoteStore`` spelling must behave exactly like the legacy name."""
def test_true_when_repo_endpoint_ok(self) -> None:
"""True when repo endpoint ok."""
with _patch_get(_response(200)):
assert _client().can_access_remote() is True
def test_false_when_repo_is_missing(self) -> None:
"""False when repo is missing."""
with _patch_get(_response(404)):
assert _client().can_access_remote() is False
def test_false_on_a_network_error(self) -> None:
"""False on a network error."""
with _patch_get_raises():
assert _client().can_access_remote() is False
class TestRemoteStoreContract:
"""The seam sync talks through must actually be satisfied by the client."""
def test_github_client_is_a_remote_store(self) -> None:
"""Github client is a remote store."""
assert isinstance(_client(), RemoteStore)
def test_repo_not_found_is_catchable_as_either_error(self) -> None:
# Backend-neutral callers catch RemoteNotFoundError; existing GitHub
# callers catch GitHubSyncError. One exception must satisfy both.
"""Repo not found is catchable as either error."""
error = RepoNotFoundError("gone")
assert isinstance(error, GitHubSyncError)
assert isinstance(error, RemoteNotFoundError)
assert isinstance(error, RemoteSyncError)
class TestDeleteFile:
"""Delete file."""
def test_deletes_an_existing_file_resolving_its_own_sha(self) -> None:
"""Deletes an existing file resolving its own sha."""
with (
_patch_get(_response(200, {"sha": "abc123"})),
patch.object(_github.requests, "delete", return_value=_response(200)),
):
_client().delete_file("devices/pc/log.json")
def test_is_a_no_op_when_the_file_is_absent(self) -> None:
# sha GET 404, repo-exists GET 200 -> None sha -> no DELETE sent.
"""Is a no op when the file is absent."""
with (
_patch_get(_response(404), _response(200)),
patch.object(_github.requests, "delete") as mock_delete,
):
_client().delete_file("devices/pc/gone.json")
mock_delete.assert_not_called()
def test_raises_on_a_delete_non_2xx_response(self) -> None:
"""Raises on a delete non 2xx response."""
with (
_patch_get(_response(200, {"sha": "abc123"})),
patch.object(_github.requests, "delete", return_value=_response(500)),
pytest.raises(GitHubSyncError),
):
_client().delete_file("devices/pc/log.json")
def test_raises_on_a_delete_network_error(self) -> None:
"""Raises on a delete network error."""
with (
_patch_get(_response(200, {"sha": "abc123"})),
patch.object(
_github.requests,
"delete",
side_effect=requests.ConnectionError("offline"),
),
pytest.raises(GitHubSyncError),
):
_client().delete_file("devices/pc/log.json")

View File

@ -12,19 +12,10 @@ from __future__ import annotations
import pytest
from crdt_sync import (
Hlc,
Log,
LogCodec,
MirrorSyncClient,
Record,
RemoteStore,
RemoteSyncError,
SyncTarget,
dump_log,
load_log,
sync_log,
)
from crdt_sync.tests.conftest import FakeStore, FakeStoreWithoutBulkRead
from crdt_sync.tests.conftest import FakeStore
def _mirror(
@ -176,189 +167,3 @@ class TestListDirectory:
client, _, _, _ = _mirror(primary_failing=True, mirror_failing=True)
with pytest.raises(RemoteSyncError):
client.list_directory("ns")
class TestPrimaryReadFallback:
"""A failing primary must never hide data the mirror can still serve."""
def test_get_file_text_falls_back_to_the_mirror(self) -> None:
"""Get file text falls back to the mirror."""
client, _, _, _ = _mirror(
primary_failing=True, mirror_files={"ns/phone/log.json": "{}"}
)
assert client.get_file_text("ns/phone/log.json") == "{}"
def test_get_file_text_raises_when_both_fail(self) -> None:
"""Get file text raises when both fail."""
client, _, _, _ = _mirror(primary_failing=True, mirror_failing=True)
with pytest.raises(RemoteSyncError):
client.get_file_text("ns/phone/log.json")
def test_get_file_text_raises_when_primary_fails_and_mirror_lacks_it(
self,
) -> None:
# A reachable mirror that simply does not hold the file is not an
# answer either, since the primary's copy was never read.
"""Get file text raises when primary fails and mirror lacks it."""
client, _, _, _ = _mirror(primary_failing=True)
with pytest.raises(RemoteSyncError):
client.get_file_text("ns/phone/log.json")
def test_revision_map_falls_back_to_the_mirror(self) -> None:
"""Revision map falls back to the mirror."""
client, _, _, _ = _mirror(
primary_failing=True, mirror_files={"ns/revs/phone": "r1"}
)
assert client.get_string_map("ns/revs") == {"phone": "r1"}
def test_revision_map_raises_when_both_fail(self) -> None:
"""Revision map raises when both fail."""
client, _, _, _ = _mirror(primary_failing=True, mirror_failing=True)
with pytest.raises(RemoteSyncError):
client.get_string_map("ns/revs")
def test_revision_map_tolerates_a_mirror_that_cannot_bulk_read(
self,
) -> None:
# A mirror with no bulk-read capability (GitHub) contributes nothing,
# but that is not a failure -- it simply has no revisions to add, so a
# working primary's map must still come back. Matches the Dart side,
# where the capability check runs inside the guarded closure.
"""Revision map tolerates a mirror that cannot bulk read."""
client = MirrorSyncClient(
FakeStore({"ns/revs/pc": "r1"}),
FakeStoreWithoutBulkRead(),
on_mirror_failure=lambda *_: None,
)
assert client.get_string_map("ns/revs") == {"pc": "r1"}
def test_writes_stay_fail_closed_on_a_primary_failure(self) -> None:
# The read fix must NOT loosen writes: an unaccepted write has not
# happened, so it must still fail the tick.
"""Writes stay fail closed on a primary failure."""
client, _, _, _ = _mirror(primary_failing=True)
with pytest.raises(RemoteSyncError):
client.put_file_text("ns/pc/log.json", "{}", message="m")
with pytest.raises(RemoteSyncError):
client.delete_file("ns/pc/log.json")
class TestRevisionMaps:
"""Revision maps."""
def test_merge_both_backends_with_the_primary_winning(self) -> None:
"""Merge both backends with the primary winning."""
client, _, _, _ = _mirror(
primary_files={"ns/revs/pc": "primary-rev"},
mirror_files={"ns/revs/pc": "mirror-rev", "ns/revs/phone": "old"},
)
# An un-migrated device publishes revisions only to the mirror;
# without this it would look revision-less and be re-downloaded
# every tick for the whole trial.
assert client.get_string_map("ns/revs") == {
"pc": "primary-rev",
"phone": "old",
}
def test_a_mirror_failure_degrades_to_primary_revisions(self) -> None:
"""A mirror failure degrades to primary revisions."""
client, _, _, failures = _mirror(
primary_files={"ns/revs/pc": "primary-rev"}, mirror_failing=True
)
assert client.get_string_map("ns/revs") == {"pc": "primary-rev"}
assert failures == ["get_string_map ns/revs"]
def test_a_backend_without_bulk_reads_contributes_nothing(self) -> None:
"""A backend without bulk reads contributes nothing."""
client = MirrorSyncClient(
FakeStore({"ns/revs/pc": "primary-rev"}),
FakeStoreWithoutBulkRead({"ns/revs/phone": "ignored"}),
)
assert client.get_string_map("ns/revs") == {"pc": "primary-rev"}
def test_is_empty_when_neither_backend_has_bulk_reads(self) -> None:
"""Is empty when neither backend has bulk reads."""
client = MirrorSyncClient(
FakeStoreWithoutBulkRead(), FakeStoreWithoutBulkRead()
)
assert not client.get_string_map("ns/revs")
class TestLifecycle:
"""Lifecycle."""
def test_can_access_remote_reports_only_the_primary(self) -> None:
# A Test-connection button must not report success because the
# backend being retired happens to answer.
"""Can access remote reports only the primary."""
broken, _, _, _ = _mirror(primary_failing=True)
assert broken.can_access_remote() is False
healthy, _, _, _ = _mirror(mirror_failing=True)
assert healthy.can_access_remote() is True
def test_a_mirror_failure_with_no_handler_is_logged_not_raised(
self,
caplog: pytest.LogCaptureFixture,
) -> None:
"""A mirror failure with no handler is logged not raised."""
client = MirrorSyncClient(FakeStore(), FakeStore(failing=True))
client.put_file_text("ns/pc/log.json", "{}", message="m")
assert "Mirror backend failed" in caplog.text
def test_satisfies_the_remote_store_contract(self) -> None:
"""Satisfies the remote store contract."""
client, _, _, _ = _mirror()
assert isinstance(client, RemoteStore)
class TestEndToEndThroughSyncLog:
"""End to end through sync log."""
def test_a_half_migrated_pair_still_converges_both_ways(self) -> None:
# phone has not migrated and still writes only to GitHub; pc is on
# Firebase with the GitHub mirror. Both must see both records.
"""A half migrated pair still converges both ways."""
github = FakeStore()
firebase = FakeStore()
def log(record_id: str, node_id: str) -> Log:
return {
record_id: Record(
id=record_id,
fields={
"v": (
record_id,
Hlc(wall_time_ms=1000, counter=0, node_id=node_id),
)
},
)
}
sync_log(
SyncTarget(
client=github,
device_id="phone",
path_prefix="ns/devices",
),
log("from-phone", "node-phone"),
LogCodec(
decode=load_log,
encode=dump_log,
),
)
merged = sync_log(
SyncTarget(
client=MirrorSyncClient(firebase, github),
device_id="pc",
path_prefix="ns/devices",
),
log("from-pc", "node-pc"),
LogCodec(
decode=load_log,
encode=dump_log,
),
)
assert {"from-phone", "from-pc"} <= set(merged)
# The pc's merged result is mirrored back to GitHub, so the
# un-migrated phone sees it on its next tick.
assert "ns/devices/pc/log.json" in github.files

View File

@ -0,0 +1,229 @@
"""Tests for mirror fallback reads, revision maps and lifecycle.
Split from ``test_mirror.py`` (250-line cap), which keeps plain writes,
reads and directory listing.
"""
from __future__ import annotations
import pytest
from crdt_sync import (
Hlc,
Log,
LogCodec,
MirrorSyncClient,
Record,
RemoteStore,
RemoteSyncError,
SyncTarget,
dump_log,
load_log,
sync_log,
)
from crdt_sync.tests.conftest import FakeStore, FakeStoreWithoutBulkRead
def _mirror(
*,
primary_files: dict[str, str] | None = None,
mirror_files: dict[str, str] | None = None,
primary_failing: bool = False,
mirror_failing: bool = False,
) -> tuple[MirrorSyncClient, FakeStore, FakeStore, list[str]]:
primary = FakeStore(primary_files, failing=primary_failing)
mirror = FakeStore(mirror_files, failing=mirror_failing)
failures: list[str] = []
client = MirrorSyncClient(
primary,
mirror,
on_mirror_failure=lambda operation, _: failures.append(operation),
)
return client, primary, mirror, failures
class TestPrimaryReadFallback:
"""A failing primary must never hide data the mirror can still serve."""
def test_get_file_text_falls_back_to_the_mirror(self) -> None:
"""Get file text falls back to the mirror."""
client, _, _, _ = _mirror(
primary_failing=True, mirror_files={"ns/phone/log.json": "{}"}
)
assert client.get_file_text("ns/phone/log.json") == "{}"
def test_get_file_text_raises_when_both_fail(self) -> None:
"""Get file text raises when both fail."""
client, _, _, _ = _mirror(primary_failing=True, mirror_failing=True)
with pytest.raises(RemoteSyncError):
client.get_file_text("ns/phone/log.json")
def test_get_file_text_raises_when_primary_fails_and_mirror_lacks_it(
self,
) -> None:
# A reachable mirror that simply does not hold the file is not an
# answer either, since the primary's copy was never read.
"""Get file text raises when primary fails and mirror lacks it."""
client, _, _, _ = _mirror(primary_failing=True)
with pytest.raises(RemoteSyncError):
client.get_file_text("ns/phone/log.json")
def test_revision_map_falls_back_to_the_mirror(self) -> None:
"""Revision map falls back to the mirror."""
client, _, _, _ = _mirror(
primary_failing=True, mirror_files={"ns/revs/phone": "r1"}
)
assert client.get_string_map("ns/revs") == {"phone": "r1"}
def test_revision_map_raises_when_both_fail(self) -> None:
"""Revision map raises when both fail."""
client, _, _, _ = _mirror(primary_failing=True, mirror_failing=True)
with pytest.raises(RemoteSyncError):
client.get_string_map("ns/revs")
def test_revision_map_tolerates_a_mirror_that_cannot_bulk_read(
self,
) -> None:
# A mirror with no bulk-read capability (GitHub) contributes nothing,
# but that is not a failure -- it simply has no revisions to add, so a
# working primary's map must still come back. Matches the Dart side,
# where the capability check runs inside the guarded closure.
"""Revision map tolerates a mirror that cannot bulk read."""
client = MirrorSyncClient(
FakeStore({"ns/revs/pc": "r1"}),
FakeStoreWithoutBulkRead(),
on_mirror_failure=lambda *_: None,
)
assert client.get_string_map("ns/revs") == {"pc": "r1"}
def test_writes_stay_fail_closed_on_a_primary_failure(self) -> None:
# The read fix must NOT loosen writes: an unaccepted write has not
# happened, so it must still fail the tick.
"""Writes stay fail closed on a primary failure."""
client, _, _, _ = _mirror(primary_failing=True)
with pytest.raises(RemoteSyncError):
client.put_file_text("ns/pc/log.json", "{}", message="m")
with pytest.raises(RemoteSyncError):
client.delete_file("ns/pc/log.json")
class TestRevisionMaps:
"""Revision maps."""
def test_merge_both_backends_with_the_primary_winning(self) -> None:
"""Merge both backends with the primary winning."""
client, _, _, _ = _mirror(
primary_files={"ns/revs/pc": "primary-rev"},
mirror_files={"ns/revs/pc": "mirror-rev", "ns/revs/phone": "old"},
)
# An un-migrated device publishes revisions only to the mirror;
# without this it would look revision-less and be re-downloaded
# every tick for the whole trial.
assert client.get_string_map("ns/revs") == {
"pc": "primary-rev",
"phone": "old",
}
def test_a_mirror_failure_degrades_to_primary_revisions(self) -> None:
"""A mirror failure degrades to primary revisions."""
client, _, _, failures = _mirror(
primary_files={"ns/revs/pc": "primary-rev"}, mirror_failing=True
)
assert client.get_string_map("ns/revs") == {"pc": "primary-rev"}
assert failures == ["get_string_map ns/revs"]
def test_a_backend_without_bulk_reads_contributes_nothing(self) -> None:
"""A backend without bulk reads contributes nothing."""
client = MirrorSyncClient(
FakeStore({"ns/revs/pc": "primary-rev"}),
FakeStoreWithoutBulkRead({"ns/revs/phone": "ignored"}),
)
assert client.get_string_map("ns/revs") == {"pc": "primary-rev"}
def test_is_empty_when_neither_backend_has_bulk_reads(self) -> None:
"""Is empty when neither backend has bulk reads."""
client = MirrorSyncClient(
FakeStoreWithoutBulkRead(), FakeStoreWithoutBulkRead()
)
assert not client.get_string_map("ns/revs")
class TestLifecycle:
"""Lifecycle."""
def test_can_access_remote_reports_only_the_primary(self) -> None:
# A Test-connection button must not report success because the
# backend being retired happens to answer.
"""Can access remote reports only the primary."""
broken, _, _, _ = _mirror(primary_failing=True)
assert broken.can_access_remote() is False
healthy, _, _, _ = _mirror(mirror_failing=True)
assert healthy.can_access_remote() is True
def test_a_mirror_failure_with_no_handler_is_logged_not_raised(
self,
caplog: pytest.LogCaptureFixture,
) -> None:
"""A mirror failure with no handler is logged not raised."""
client = MirrorSyncClient(FakeStore(), FakeStore(failing=True))
client.put_file_text("ns/pc/log.json", "{}", message="m")
assert "Mirror backend failed" in caplog.text
def test_satisfies_the_remote_store_contract(self) -> None:
"""Satisfies the remote store contract."""
client, _, _, _ = _mirror()
assert isinstance(client, RemoteStore)
class TestEndToEndThroughSyncLog:
"""End to end through sync log."""
def test_a_half_migrated_pair_still_converges_both_ways(self) -> None:
# phone has not migrated and still writes only to GitHub; pc is on
# Firebase with the GitHub mirror. Both must see both records.
"""A half migrated pair still converges both ways."""
github = FakeStore()
firebase = FakeStore()
def log(record_id: str, node_id: str) -> Log:
return {
record_id: Record(
id=record_id,
fields={
"v": (
record_id,
Hlc(wall_time_ms=1000, counter=0, node_id=node_id),
)
},
)
}
sync_log(
SyncTarget(
client=github,
device_id="phone",
path_prefix="ns/devices",
),
log("from-phone", "node-phone"),
LogCodec(
decode=load_log,
encode=dump_log,
),
)
merged = sync_log(
SyncTarget(
client=MirrorSyncClient(firebase, github),
device_id="pc",
path_prefix="ns/devices",
),
log("from-pc", "node-pc"),
LogCodec(
decode=load_log,
encode=dump_log,
),
)
assert {"from-phone", "from-pc"} <= set(merged)
# The pc's merged result is mirrored back to GitHub, so the
# un-migrated phone sees it on its next tick.
assert "ns/devices/pc/log.json" in github.files

View File

@ -3,7 +3,6 @@
from __future__ import annotations
import json
import logging
from typing import TYPE_CHECKING
from unittest.mock import MagicMock
@ -18,8 +17,6 @@ from crdt_sync import (
if TYPE_CHECKING:
from collections.abc import Callable
import pytest
from crdt_sync import Hlc, Log
@ -145,79 +142,6 @@ class TestSyncLog:
client.get_file_text.assert_called_once_with("devices/pc/log.json")
def test_skips_a_device_with_no_pushed_file_yet(self) -> None:
"""Skips a device with no pushed file yet."""
client = _mock_client(devices=("phone",), files={})
merged = sync_log(
SyncTarget(
client=client,
device_id="pc",
path_prefix="devices",
),
{},
LogCodec(
decode=_decode,
encode=_encode,
),
)
assert not merged
def test_skips_a_device_whose_pushed_file_is_corrupt(
self, caplog: pytest.LogCaptureFixture
) -> None:
"""An interrupted/truncated push must not crash every other device's
merge -- it is treated the same as a device that hasn't pushed yet.
"""
client = _mock_client(
devices=("phone",),
files={"devices/phone/log.json": "{not valid json"},
)
with caplog.at_level(logging.WARNING):
merged = sync_log(
SyncTarget(
client=client,
device_id="pc",
path_prefix="devices",
),
{},
LogCodec(
decode=_decode,
encode=_encode,
),
)
assert not merged
assert "Unparsable log" in caplog.text
def test_skips_a_device_whose_pushed_json_has_the_wrong_shape(self) -> None:
"""Valid JSON that isn't a record map (e.g. from an incompatible
writer) must be skipped like corrupt JSON, not crash the whole
sync -- this is what the broad ``(ValueError, KeyError, TypeError)``
catch in ``_pull_remote_logs`` is for, not just JSON syntax errors.
"""
client = _mock_client(
devices=("phone",),
files={"devices/phone/log.json": '{"a": 5}'},
)
merged = sync_log(
SyncTarget(
client=client,
device_id="pc",
path_prefix="devices",
),
{},
LogCodec(
decode=_decode,
encode=_encode,
),
)
assert not merged
def test_merges_in_a_remote_devices_entries(
self, make_hlc: Callable[..., Hlc]
) -> None:

View File

@ -11,12 +11,7 @@ Mirrors ``crdt_sync_dart``'s ``test/sync_revisions_test.dart``.
from __future__ import annotations
from typing import TYPE_CHECKING
import pytest
from crdt_sync import (
FileSyncStateStore,
Hlc,
Log,
LogCodec,
@ -33,9 +28,6 @@ from crdt_sync import (
)
from crdt_sync.tests.conftest import FakeStore, FakeStoreWithoutBulkRead
if TYPE_CHECKING:
from pathlib import Path
def _log(record_id: str, value: str, node_id: str = "node-a") -> Log:
return {
@ -169,238 +161,3 @@ class TestNoOpPushSuppression:
_tick(remote, None, local)
assert remote.writes == ["ns/devices/pc/log.json"] * 2
assert not [w for w in remote.writes if w.startswith("ns/revs")]
class TestPeerDownloadSuppression:
"""Peer download suppression."""
def test_downloads_a_peer_whose_revision_it_has_never_seen(self) -> None:
"""Downloads a peer whose revision it has never seen."""
peer = _encode(_log("b", "from-phone", "node-b"))
remote = FakeRemote(
{
"ns/devices/phone/log.json": peer,
"ns/revs/phone": revision_of(peer),
}
)
merged = _tick(remote, MemorySyncStateStore())
assert "ns/devices/phone/log.json" in remote.reads
assert "b" in merged
def test_skips_the_download_when_the_peer_revision_is_unchanged(self) -> None:
"""Skips the download when the peer revision is unchanged."""
peer = _encode(_log("b", "from-phone", "node-b"))
remote = FakeRemote(
{
"ns/devices/phone/log.json": peer,
"ns/revs/phone": revision_of(peer),
}
)
store = MemorySyncStateStore()
first = _tick(remote, store)
remote.reads.clear()
# The peer's records are already in the local log from tick one, so
# re-downloading is pure waste -- the ~700 MB/month this removes.
_tick(remote, store, first)
assert not remote.reads
def test_downloads_again_once_the_peer_publishes_a_new_revision(self) -> None:
"""Downloads again once the peer publishes a new revision."""
peer_v1 = _encode(_log("b", "v1", "node-b"))
remote = FakeRemote(
{
"ns/devices/phone/log.json": peer_v1,
"ns/revs/phone": revision_of(peer_v1),
}
)
store = MemorySyncStateStore()
first = _tick(remote, store)
remote.reads.clear()
peer_v2 = _encode({**_decode(peer_v1), **_log("c", "v2", "node-b")})
remote.files["ns/devices/phone/log.json"] = peer_v2
remote.files["ns/revs/phone"] = revision_of(peer_v2)
second = _tick(remote, store, first)
assert "ns/devices/phone/log.json" in remote.reads
assert {"b", "c"} <= set(second)
def test_re_downloads_a_peer_whose_push_was_corrupt(self) -> None:
# A failed decode must not be remembered as seen, or the corruption
# would be permanent.
"""Re downloads a peer whose push was corrupt."""
remote = FakeRemote(
{
"ns/devices/phone/log.json": "not json at all",
"ns/revs/phone": revision_of("not json at all"),
}
)
store = MemorySyncStateStore()
_tick(remote, store)
remote.reads.clear()
_tick(remote, store)
assert "ns/devices/phone/log.json" in remote.reads
def test_downloads_when_the_peer_has_published_no_revision(self) -> None:
# A device still running pre-migration code publishes a log but no
# revision; it must not be silently ignored.
"""Downloads when the peer has published no revision."""
peer = _encode(_log("b", "from-phone", "node-b"))
remote = FakeRemote({"ns/devices/phone/log.json": peer})
assert "b" in _tick(remote, MemorySyncStateStore())
def test_skips_a_peer_with_nothing_pushed_yet(self) -> None:
"""Skips a peer with nothing pushed yet."""
remote = FakeRemote({"ns/devices/phone/other.txt": "x"})
assert not _tick(remote, MemorySyncStateStore())
def test_never_reads_its_own_device_back(self) -> None:
"""Never reads its own device back."""
remote = FakeRemote(
{
"ns/devices/pc/log.json": _encode(_log("a", "1")),
"ns/revs/pc": "whatever",
}
)
_tick(remote, MemorySyncStateStore())
assert not remote.reads
class TestBackendsWithoutBulkMapReads:
"""Backends without bulk map reads."""
def test_still_sync_correctly_just_without_the_saving(self) -> None:
# GitHubSyncClient has no get_string_map, so revision lookup degrades
# to "fetch everything" -- correctness must not depend on it.
"""Still sync correctly just without the saving."""
peer = _encode(_log("b", "from-phone", "node-b"))
remote = FakeRemoteWithoutBulkRead({"ns/devices/phone/log.json": peer})
store = MemorySyncStateStore()
first = _tick(remote, store)
assert "b" in first
remote.reads.clear()
_tick(remote, store, first)
assert "ns/devices/phone/log.json" in remote.reads
class TestRevisionPublishingOrder:
"""Revision publishing order."""
def test_publishes_the_log_before_its_revision(self) -> None:
# Reversed, a peer would cache "seen rev X" against a log it never
# received, and skip it forever.
"""Publishes the log before its revision."""
remote = FakeRemote()
_tick(remote, MemorySyncStateStore(), _log("a", "1"))
assert remote.writes.index("ns/devices/pc/log.json") < remote.writes.index(
"ns/revs/pc"
)
def test_each_device_writes_only_its_own_revision_key(self) -> None:
# Per-device keys rather than one shared map: a whole-map write would
# erase every other device's entry, after which those peers would look
# permanently unchanged and never be fetched again.
"""Each device writes only its own revision key."""
remote = FakeRemote({"ns/revs/phone": "peer-rev"})
_tick(remote, MemorySyncStateStore(), _log("a", "1"))
assert remote.files["ns/revs/phone"] == "peer-rev"
def test_an_explicit_revs_path_overrides_the_default(self) -> None:
"""An explicit revs path overrides the default."""
remote = FakeRemote()
sync_log(
SyncTarget(
client=remote,
device_id="pc",
path_prefix="ns/devices",
),
_log("a", "1"),
LogCodec(
decode=_decode,
encode=_encode,
),
RevisionTracking(
revs_path="custom/place",
state_store=MemorySyncStateStore(),
),
)
assert "custom/place/pc" in remote.writes
class TestTwoDevicesConverge:
"""Two devices converge."""
def test_each_ends_up_with_the_others_records(self) -> None:
"""Each ends up with the others records."""
remote = FakeRemote()
pc_store, phone_store = MemorySyncStateStore(), MemorySyncStateStore()
pc = _tick(remote, pc_store, _log("a", "from-pc", "node-pc"))
phone = sync_log(
SyncTarget(
client=remote,
device_id="phone",
path_prefix="ns/devices",
),
_log("b", "from-phone", "node-phone"),
LogCodec(
decode=_decode,
encode=_encode,
),
RevisionTracking(
state_store=phone_store,
),
)
assert {"a", "b"} <= set(phone)
pc_after = _tick(remote, pc_store, pc)
assert {"a", "b"} <= set(pc_after)
class TestFileSyncStateStore:
"""File sync state store."""
def test_round_trips_through_a_file(self, tmp_path: Path) -> None:
"""Round trips through a file."""
store = FileSyncStateStore(tmp_path / "nested" / "state.json")
state = SyncState(pushed_rev="abc", peer_revs={"phone": "def"})
store.save(state)
assert store.load() == state
def test_load_returns_default_state_when_absent(self, tmp_path: Path) -> None:
"""Load returns default state when absent."""
assert FileSyncStateStore(tmp_path / "missing.json").load() == SyncState()
def test_load_returns_default_state_for_a_truncated_file(
self, tmp_path: Path
) -> None:
"""Load returns default state for a truncated file."""
path = tmp_path / "state.json"
path.write_text('{"pushed_rev":', encoding="utf-8")
assert FileSyncStateStore(path).load() == SyncState()
def test_load_returns_default_state_for_a_non_dict_file(
self, tmp_path: Path
) -> None:
"""Load returns default state for a non dict file."""
path = tmp_path / "state.json"
path.write_text("[1, 2, 3]", encoding="utf-8")
assert FileSyncStateStore(path).load() == SyncState()
def test_survives_across_processes(self, tmp_path: Path) -> None:
# The point of persisting at all: wake_alarm PC is a fresh process
# every minute, so an in-memory store would save nothing.
"""Survives across processes."""
path = tmp_path / "state.json"
remote = FakeRemote()
local = _log("a", "1")
_tick(remote, FileSyncStateStore(path), local)
remote.writes.clear()
_tick(remote, FileSyncStateStore(path), local)
assert not remote.writes
@pytest.mark.parametrize("device_id", ["pc", "phone"])
def test_a_device_publishes_its_revision_under_its_own_id(device_id: str) -> None:
"""A device publishes its revision under its own id."""
remote = FakeRemote()
_tick(remote, MemorySyncStateStore(), _log("a", "1"), device_id=device_id)
assert f"ns/revs/{device_id}" in remote.writes

View File

@ -0,0 +1,216 @@
"""Tests for backends without bulk map reads, and publishing order.
Split from ``test_sync_revisions.py`` (250-line cap);
``test_sync_revisions_peers.py`` keeps peer-download suppression.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
import pytest
from crdt_sync import (
FileSyncStateStore,
Hlc,
Log,
LogCodec,
MemorySyncStateStore,
Record,
RevisionTracking,
SyncState,
SyncTarget,
dump_log,
load_log,
sync_log,
)
from crdt_sync.tests.conftest import FakeStore, FakeStoreWithoutBulkRead
if TYPE_CHECKING:
from pathlib import Path
def _log(record_id: str, value: str, node_id: str = "node-a") -> Log:
return {
record_id: Record(
id=record_id,
fields={
"value": (value, Hlc(wall_time_ms=1000, counter=0, node_id=node_id))
},
)
}
# The library's own serialization, so these tests exercise the same encoding
# the apps use rather than a test-only one.
_encode = dump_log
_decode = load_log
FakeRemote = FakeStore
FakeRemoteWithoutBulkRead = FakeStoreWithoutBulkRead
def _tick(
remote: FakeRemote,
store: object = None,
local: Log | None = None,
device_id: str = "pc",
) -> Log:
return sync_log(
SyncTarget(
client=remote,
device_id=device_id,
path_prefix="ns/devices",
),
local or {},
LogCodec(
decode=_decode,
encode=_encode,
),
RevisionTracking(
state_store=store,
),
)
class TestBackendsWithoutBulkMapReads:
"""Backends without bulk map reads."""
def test_still_sync_correctly_just_without_the_saving(self) -> None:
# GitHubSyncClient has no get_string_map, so revision lookup degrades
# to "fetch everything" -- correctness must not depend on it.
"""Still sync correctly just without the saving."""
peer = _encode(_log("b", "from-phone", "node-b"))
remote = FakeRemoteWithoutBulkRead({"ns/devices/phone/log.json": peer})
store = MemorySyncStateStore()
first = _tick(remote, store)
assert "b" in first
remote.reads.clear()
_tick(remote, store, first)
assert "ns/devices/phone/log.json" in remote.reads
class TestRevisionPublishingOrder:
"""Revision publishing order."""
def test_publishes_the_log_before_its_revision(self) -> None:
# Reversed, a peer would cache "seen rev X" against a log it never
# received, and skip it forever.
"""Publishes the log before its revision."""
remote = FakeRemote()
_tick(remote, MemorySyncStateStore(), _log("a", "1"))
assert remote.writes.index("ns/devices/pc/log.json") < remote.writes.index(
"ns/revs/pc"
)
def test_each_device_writes_only_its_own_revision_key(self) -> None:
# Per-device keys rather than one shared map: a whole-map write would
# erase every other device's entry, after which those peers would look
# permanently unchanged and never be fetched again.
"""Each device writes only its own revision key."""
remote = FakeRemote({"ns/revs/phone": "peer-rev"})
_tick(remote, MemorySyncStateStore(), _log("a", "1"))
assert remote.files["ns/revs/phone"] == "peer-rev"
def test_an_explicit_revs_path_overrides_the_default(self) -> None:
"""An explicit revs path overrides the default."""
remote = FakeRemote()
sync_log(
SyncTarget(
client=remote,
device_id="pc",
path_prefix="ns/devices",
),
_log("a", "1"),
LogCodec(
decode=_decode,
encode=_encode,
),
RevisionTracking(
revs_path="custom/place",
state_store=MemorySyncStateStore(),
),
)
assert "custom/place/pc" in remote.writes
class TestTwoDevicesConverge:
"""Two devices converge."""
def test_each_ends_up_with_the_others_records(self) -> None:
"""Each ends up with the others records."""
remote = FakeRemote()
pc_store, phone_store = MemorySyncStateStore(), MemorySyncStateStore()
pc = _tick(remote, pc_store, _log("a", "from-pc", "node-pc"))
phone = sync_log(
SyncTarget(
client=remote,
device_id="phone",
path_prefix="ns/devices",
),
_log("b", "from-phone", "node-phone"),
LogCodec(
decode=_decode,
encode=_encode,
),
RevisionTracking(
state_store=phone_store,
),
)
assert {"a", "b"} <= set(phone)
pc_after = _tick(remote, pc_store, pc)
assert {"a", "b"} <= set(pc_after)
class TestFileSyncStateStore:
"""File sync state store."""
def test_round_trips_through_a_file(self, tmp_path: Path) -> None:
"""Round trips through a file."""
store = FileSyncStateStore(tmp_path / "nested" / "state.json")
state = SyncState(pushed_rev="abc", peer_revs={"phone": "def"})
store.save(state)
assert store.load() == state
def test_load_returns_default_state_when_absent(self, tmp_path: Path) -> None:
"""Load returns default state when absent."""
assert FileSyncStateStore(tmp_path / "missing.json").load() == SyncState()
def test_load_returns_default_state_for_a_truncated_file(
self, tmp_path: Path
) -> None:
"""Load returns default state for a truncated file."""
path = tmp_path / "state.json"
path.write_text('{"pushed_rev":', encoding="utf-8")
assert FileSyncStateStore(path).load() == SyncState()
def test_load_returns_default_state_for_a_non_dict_file(
self, tmp_path: Path
) -> None:
"""Load returns default state for a non dict file."""
path = tmp_path / "state.json"
path.write_text("[1, 2, 3]", encoding="utf-8")
assert FileSyncStateStore(path).load() == SyncState()
def test_survives_across_processes(self, tmp_path: Path) -> None:
# The point of persisting at all: wake_alarm PC is a fresh process
# every minute, so an in-memory store would save nothing.
"""Survives across processes."""
path = tmp_path / "state.json"
remote = FakeRemote()
local = _log("a", "1")
_tick(remote, FileSyncStateStore(path), local)
remote.writes.clear()
_tick(remote, FileSyncStateStore(path), local)
assert not remote.writes
@pytest.mark.parametrize("device_id", ["pc", "phone"])
def test_a_device_publishes_its_revision_under_its_own_id(device_id: str) -> None:
"""A device publishes its revision under its own id."""
remote = FakeRemote()
_tick(remote, MemorySyncStateStore(), _log("a", "1"), device_id=device_id)
assert f"ns/revs/{device_id}" in remote.writes

View File

@ -0,0 +1,162 @@
"""Tests for revision handling across peers.
Split from ``test_sync_revisions.py`` (250-line cap), which keeps revision
identity, state, and no-op push suppression.
"""
from __future__ import annotations
from crdt_sync import (
Hlc,
Log,
LogCodec,
MemorySyncStateStore,
Record,
RevisionTracking,
SyncTarget,
dump_log,
load_log,
revision_of,
sync_log,
)
from crdt_sync.tests.conftest import FakeStore, FakeStoreWithoutBulkRead
def _log(record_id: str, value: str, node_id: str = "node-a") -> Log:
return {
record_id: Record(
id=record_id,
fields={
"value": (value, Hlc(wall_time_ms=1000, counter=0, node_id=node_id))
},
)
}
# The library's own serialization, so these tests exercise the same encoding
# the apps use rather than a test-only one.
_encode = dump_log
_decode = load_log
FakeRemote = FakeStore
FakeRemoteWithoutBulkRead = FakeStoreWithoutBulkRead
def _tick(
remote: FakeRemote,
store: object = None,
local: Log | None = None,
device_id: str = "pc",
) -> Log:
return sync_log(
SyncTarget(
client=remote,
device_id=device_id,
path_prefix="ns/devices",
),
local or {},
LogCodec(
decode=_decode,
encode=_encode,
),
RevisionTracking(
state_store=store,
),
)
class TestPeerDownloadSuppression:
"""Peer download suppression."""
def test_downloads_a_peer_whose_revision_it_has_never_seen(self) -> None:
"""Downloads a peer whose revision it has never seen."""
peer = _encode(_log("b", "from-phone", "node-b"))
remote = FakeRemote(
{
"ns/devices/phone/log.json": peer,
"ns/revs/phone": revision_of(peer),
}
)
merged = _tick(remote, MemorySyncStateStore())
assert "ns/devices/phone/log.json" in remote.reads
assert "b" in merged
def test_skips_the_download_when_the_peer_revision_is_unchanged(self) -> None:
"""Skips the download when the peer revision is unchanged."""
peer = _encode(_log("b", "from-phone", "node-b"))
remote = FakeRemote(
{
"ns/devices/phone/log.json": peer,
"ns/revs/phone": revision_of(peer),
}
)
store = MemorySyncStateStore()
first = _tick(remote, store)
remote.reads.clear()
# The peer's records are already in the local log from tick one, so
# re-downloading is pure waste -- the ~700 MB/month this removes.
_tick(remote, store, first)
assert not remote.reads
def test_downloads_again_once_the_peer_publishes_a_new_revision(self) -> None:
"""Downloads again once the peer publishes a new revision."""
peer_v1 = _encode(_log("b", "v1", "node-b"))
remote = FakeRemote(
{
"ns/devices/phone/log.json": peer_v1,
"ns/revs/phone": revision_of(peer_v1),
}
)
store = MemorySyncStateStore()
first = _tick(remote, store)
remote.reads.clear()
peer_v2 = _encode({**_decode(peer_v1), **_log("c", "v2", "node-b")})
remote.files["ns/devices/phone/log.json"] = peer_v2
remote.files["ns/revs/phone"] = revision_of(peer_v2)
second = _tick(remote, store, first)
assert "ns/devices/phone/log.json" in remote.reads
assert {"b", "c"} <= set(second)
def test_re_downloads_a_peer_whose_push_was_corrupt(self) -> None:
# A failed decode must not be remembered as seen, or the corruption
# would be permanent.
"""Re downloads a peer whose push was corrupt."""
remote = FakeRemote(
{
"ns/devices/phone/log.json": "not json at all",
"ns/revs/phone": revision_of("not json at all"),
}
)
store = MemorySyncStateStore()
_tick(remote, store)
remote.reads.clear()
_tick(remote, store)
assert "ns/devices/phone/log.json" in remote.reads
def test_downloads_when_the_peer_has_published_no_revision(self) -> None:
# A device still running pre-migration code publishes a log but no
# revision; it must not be silently ignored.
"""Downloads when the peer has published no revision."""
peer = _encode(_log("b", "from-phone", "node-b"))
remote = FakeRemote({"ns/devices/phone/log.json": peer})
assert "b" in _tick(remote, MemorySyncStateStore())
def test_skips_a_peer_with_nothing_pushed_yet(self) -> None:
"""Skips a peer with nothing pushed yet."""
remote = FakeRemote({"ns/devices/phone/other.txt": "x"})
assert not _tick(remote, MemorySyncStateStore())
def test_never_reads_its_own_device_back(self) -> None:
"""Never reads its own device back."""
remote = FakeRemote(
{
"ns/devices/pc/log.json": _encode(_log("a", "1")),
"ns/revs/pc": "whatever",
}
)
_tick(remote, MemorySyncStateStore())
assert not remote.reads

View File

@ -0,0 +1,130 @@
"""Tests for the peer files sync_log declines to merge.
Split from ``test_sync.py`` (250-line cap). A peer whose pushed file is
missing, corrupt or the wrong shape must be skipped rather than allowed to
fail the whole sync; these cover each of those, plus skipping our own device.
"""
from __future__ import annotations
import json
import logging
from typing import TYPE_CHECKING
from unittest.mock import MagicMock
from crdt_sync import (
GitHubSyncClient,
LogCodec,
Record,
SyncTarget,
sync_log,
)
if TYPE_CHECKING:
import pytest
from crdt_sync import Log
def _encode(log: Log) -> str:
return json.dumps(
{record_id: record.to_dict() for record_id, record in log.items()}
)
def _decode(text: str) -> Log:
return {
record_id: Record.from_dict(data)
for record_id, data in json.loads(text).items()
}
def _mock_client(
*,
devices: tuple[str, ...] = (),
files: dict[str, str] | None = None,
) -> MagicMock:
"""Build a mock ``GitHubSyncClient`` covering the methods sync_log calls."""
client = MagicMock(spec=GitHubSyncClient)
client.list_directory.return_value = list(devices)
resolved_files = files or {}
client.get_file_text.side_effect = resolved_files.get
return client
class TestSyncLogSkips:
"""Peer files that must be passed over rather than merged."""
def test_skips_a_device_with_no_pushed_file_yet(self) -> None:
"""Skips a device with no pushed file yet."""
client = _mock_client(devices=("phone",), files={})
merged = sync_log(
SyncTarget(
client=client,
device_id="pc",
path_prefix="devices",
),
{},
LogCodec(
decode=_decode,
encode=_encode,
),
)
assert not merged
def test_skips_a_device_whose_pushed_file_is_corrupt(
self, caplog: pytest.LogCaptureFixture
) -> None:
"""An interrupted/truncated push must not crash every other device's
merge -- it is treated the same as a device that hasn't pushed yet.
"""
client = _mock_client(
devices=("phone",),
files={"devices/phone/log.json": "{not valid json"},
)
with caplog.at_level(logging.WARNING):
merged = sync_log(
SyncTarget(
client=client,
device_id="pc",
path_prefix="devices",
),
{},
LogCodec(
decode=_decode,
encode=_encode,
),
)
assert not merged
assert "Unparsable log" in caplog.text
def test_skips_a_device_whose_pushed_json_has_the_wrong_shape(self) -> None:
"""Valid JSON that isn't a record map (e.g. from an incompatible
writer) must be skipped like corrupt JSON, not crash the whole
sync -- this is what the broad ``(ValueError, KeyError, TypeError)``
catch in ``_pull_remote_logs`` is for, not just JSON syntax errors.
"""
client = _mock_client(
devices=("phone",),
files={"devices/phone/log.json": '{"a": 5}'},
)
merged = sync_log(
SyncTarget(
client=client,
device_id="pc",
path_prefix="devices",
),
{},
LogCodec(
decode=_decode,
encode=_encode,
),
)
assert not merged

View File

@ -16,7 +16,9 @@ from unittest.mock import MagicMock, patch
import pytest
from gatelock._outputs import Output, OutputRect
from gatelock._outputs import Output, OutputRect, OutputScan
from gatelock._recovery import RecoveryCollaborators, RecoveryLoop
from gatelock._surfaces import SurfaceSet
from gatelock._window import LockConfig, LockWindow
if TYPE_CHECKING:
@ -110,3 +112,51 @@ def make_window(
hooks = hooks if hooks is not None else MagicMock()
window = LockWindow(root, config or LockConfig(), hooks)
return window, hooks
DP0 = Output("DP-0", connected=True, rect=OutputRect(0, 0, 3840, 2160), primary=True)
HDMI = Output("HDMI-0", connected=True, rect=OutputRect(3840, 0, 2560, 1440))
DP0_DARK = Output("DP-0", connected=True, rect=None, primary=True)
HDMI_DARK = Output("HDMI-0", connected=True, rect=None)
BOTH = OutputScan((DP0, HDMI), "randr", ok=True)
DEAD_PRIMARY = OutputScan((DP0_DARK, HDMI), "randr", ok=True)
ALL_DARK = OutputScan((DP0_DARK, HDMI_DARK), "randr", ok=True)
FAILED = OutputScan((), "none", ok=False)
def build_loop(
root: MagicMock, config: LockConfig
) -> tuple[RecoveryLoop, MagicMock, SurfaceSet]:
"""A recovery loop over mocked surroundings, for an arbitrary config.
Args:
root: The mocked Tk root the loop drives.
config: The lock configuration under test.
Returns:
The loop, its mocked enumerator, and the surface set it manages.
"""
hooks = MagicMock()
surfaces = SurfaceSet(root, config, hooks)
enumerator = MagicMock()
return (
RecoveryLoop(
root,
RecoveryCollaborators(
config=config,
surfaces=surfaces,
enumerator=enumerator,
detector=MagicMock(),
hooks=hooks,
),
),
enumerator,
surfaces,
)
@pytest.fixture
def loop(mock_root: MagicMock) -> tuple[RecoveryLoop, MagicMock, SurfaceSet]:
"""A recovery loop in hard mode, the configuration most tests want."""
return build_loop(mock_root, LockConfig(mode="hard"))

View File

@ -9,12 +9,11 @@ from __future__ import annotations
import errno
import os
from typing import TYPE_CHECKING
from unittest.mock import MagicMock, patch
from unittest.mock import patch
import pytest
from gatelock._arbiter import (
RANK_DIET_GUARD,
RANK_SCREEN_LOCKER,
RANK_WAKE_ALARM,
Arbiter,
@ -220,213 +219,3 @@ class TestTryLock:
with path.open("r+", encoding="utf-8") as handle:
path.unlink()
assert _same_file(handle, path) is False
class TestPublishAndLiveClaims:
"""Publishing, liveness and reaping."""
def test_own_claim_is_live(self, arb: Arbiter) -> None:
"""A published claim shows up as live."""
assert [c.app for c in arb.live_claims()] == ["screen_locker"]
def test_no_claims_dir(self, tmp_path: Path) -> None:
"""Before anyone publishes, there are no claims."""
assert hard("a", 1, tmp_path / "empty").live_claims() == ()
def test_dead_claim_is_reaped(self, arb: Arbiter, tmp_path: Path) -> None:
"""An unlocked claim file proves its owner died; it is deleted."""
dead = tmp_path / "rt" / "claims" / "0300-999-dead.json"
dead.write_text(dead_claim().to_json(), "utf-8")
assert "ghost" not in [c.app for c in arb.live_claims()]
assert not dead.exists()
def test_unreadable_claim_ignored(self, arb: Arbiter, tmp_path: Path) -> None:
"""A claim that cannot be opened is skipped, not fatal."""
bad = tmp_path / "rt" / "claims" / "0100-1-bad.json"
bad.write_text("{}", encoding="utf-8")
with patch("gatelock._arbiter.Path.open", side_effect=OSError("denied")):
assert arb.live_claims() == ()
def test_reap_skips_recreated_file(self, arb: Arbiter, tmp_path: Path) -> None:
"""A claim recreated between lock and unlink is not deleted."""
dead = tmp_path / "rt" / "claims" / "0300-999-dead.json"
dead.write_text(dead_claim().to_json(), "utf-8")
with patch("gatelock._arbiter._same_file", return_value=False):
arb.live_claims()
assert dead.exists()
def test_reap_tolerates_unlink_failure(self, arb: Arbiter, tmp_path: Path) -> None:
"""A failed unlink is logged, not raised."""
dead = tmp_path / "rt" / "claims" / "0300-999-dead.json"
dead.write_text(dead_claim().to_json(), "utf-8")
with patch("gatelock._arbiter.Path.unlink", side_effect=OSError("busy")):
live = arb.live_claims()
# The reap is best-effort: the claim is excluded from the live set even
# when the file itself cannot be removed.
assert "ghost" not in [c.app for c in live]
def test_publish_twice_warns_and_continues(self, tmp_path: Path) -> None:
"""A second publish on a locked path continues unpublished."""
arbiter = hard("a", RANK_DIET_GUARD, tmp_path / "rt")
arbiter.publish()
with patch("gatelock._arbiter._try_lock", return_value=False):
arbiter.publish() # must not raise
arbiter.release()
class TestEvaluate:
"""Who may arm."""
def test_clear_when_alone(self, arb: Arbiter) -> None:
"""Nothing pending means arm."""
verdict = arb.evaluate()
assert verdict.may_arm is True
assert verdict.reason == "clear"
assert verdict.blocked_by is None
def test_lower_rank_does_not_block(self, arb: Arbiter, tmp_path: Path) -> None:
"""A weaker-ranked peer never blocks."""
diet = hard("diet_guard", RANK_DIET_GUARD, tmp_path / "rt")
diet.publish()
assert arb.evaluate().may_arm is True
diet.release()
def test_stronger_higher_rank_blocks(self, arb: Arbiter, tmp_path: Path) -> None:
"""A higher-ranked, equally strong app wins."""
alarm = hard("wake_alarm", RANK_WAKE_ALARM, tmp_path / "rt")
alarm.publish()
verdict = arb.evaluate()
assert verdict.may_arm is False
assert verdict.reason == "outranked"
assert verdict.blocked_by is not None
assert verdict.blocked_by.app == "wake_alarm"
alarm.release()
def test_weaker_higher_rank_arms_anyway(self, arb: Arbiter, tmp_path: Path) -> None:
"""Rank must never be able to reduce total lock strength."""
soft_alarm = Arbiter(
"wake_alarm",
RANK_WAKE_ALARM,
grab="none",
disable_vt=False,
runtime_dir=tmp_path / "rt",
)
soft_alarm.publish()
verdict = arb.evaluate()
assert verdict.may_arm is True
assert verdict.reason == "weaker-incumbent-armed-anyway"
soft_alarm.release()
class TestHolder:
"""Owning and naming the screen."""
def test_acquire_and_reacquire(self, arb: Arbiter) -> None:
"""Acquiring twice is idempotent."""
assert arb.acquire_holder() is True
assert arb.holds_screen is True
assert arb.acquire_holder() is True
def test_second_app_is_blocked(self, arb: Arbiter, tmp_path: Path) -> None:
"""Only one app holds the screen."""
arb.acquire_holder()
other = hard("diet_guard", RANK_DIET_GUARD, tmp_path / "rt")
other.publish()
assert other.acquire_holder() is False
other.release()
def test_blocked_app_learns_the_holder(self, arb: Arbiter, tmp_path: Path) -> None:
"""A failed acquire must not erase the incumbent's claim."""
arb.acquire_holder()
other = hard("diet_guard", RANK_DIET_GUARD, tmp_path / "rt")
other.publish()
other.acquire_holder()
holder = other.describe_holder()
assert holder is not None
assert holder.app == "screen_locker"
other.release()
def test_describe_holder_when_we_hold_it(self, arb: Arbiter) -> None:
"""The holder describes itself without touching the file."""
arb.acquire_holder()
holder = arb.describe_holder()
assert holder is not None
assert holder.app == "screen_locker"
def test_describe_holder_no_file(self, arb: Arbiter) -> None:
"""No holder file means nobody holds the screen."""
assert arb.describe_holder() is None
def test_describe_holder_stale_lock(self, arb: Arbiter, tmp_path: Path) -> None:
"""A holder file nobody locks means the owner died."""
(tmp_path / "rt").mkdir(parents=True, exist_ok=True)
(tmp_path / "rt" / "holder.lock").write_text(
dead_claim().to_json(), encoding="utf-8"
)
assert arb.describe_holder() is None
def test_describe_holder_oserror(self, arb: Arbiter, tmp_path: Path) -> None:
"""An unreadable holder file is reported as no holder."""
(tmp_path / "rt").mkdir(parents=True, exist_ok=True)
(tmp_path / "rt" / "holder.lock").write_text("{}", encoding="utf-8")
with patch("gatelock._arbiter.Path.open", side_effect=OSError("denied")):
assert arb.describe_holder() is None
class TestRelease:
"""Clean exit hands the screen over."""
def test_release_lets_the_next_app_in(self, tmp_path: Path) -> None:
"""The alarm -> workout handoff: a clean exit must free the screen."""
alarm = hard("wake_alarm", RANK_WAKE_ALARM, tmp_path / "rt")
alarm.publish()
assert alarm.acquire_holder() is True
workout = hard("screen_locker", RANK_SCREEN_LOCKER, tmp_path / "rt")
workout.publish()
assert workout.acquire_holder() is False
assert workout.evaluate().may_arm is False
alarm.release()
assert workout.acquire_holder() is True
assert workout.evaluate().may_arm is True
workout.release()
def test_release_is_idempotent(self, tmp_path: Path) -> None:
"""Releasing twice is safe."""
arbiter = hard("a", RANK_DIET_GUARD, tmp_path / "rt")
arbiter.publish()
arbiter.release()
arbiter.release()
assert arbiter.holds_screen is False
def test_release_tolerates_unlink_failure(self, tmp_path: Path) -> None:
"""A claim that cannot be removed does not break teardown."""
arbiter = hard("a", RANK_DIET_GUARD, tmp_path / "rt")
arbiter.publish()
with patch("gatelock._arbiter.Path.unlink", side_effect=OSError("busy")):
arbiter.release()
def test_claim_property(self, arb: Arbiter) -> None:
"""The arbiter exposes its own claim."""
assert arb.claim.app == "screen_locker"
assert arb.claim.rank == RANK_SCREEN_LOCKER
class TestReleaseHandleClose:
"""Handle-close failures are non-fatal."""
def test_close_oserror_is_swallowed(self, tmp_path: Path) -> None:
"""A failing close does not stop the release."""
arbiter = hard("a", RANK_DIET_GUARD, tmp_path / "rt")
arbiter.publish()
arbiter.acquire_holder()
bad = MagicMock()
bad.close.side_effect = OSError("nope")
real_handle = arbiter._holder_handle
assert real_handle is not None
real_handle.close()
arbiter._holder_handle = bad
arbiter.release()
assert arbiter.holds_screen is False

View File

@ -0,0 +1,176 @@
"""Tests for an arbiter claim's life after it is taken.
Split from ``test_arbiter.py`` (250-line cap): that file covers grab
strength, claim serialisation, the runtime dir and taking the lock; this one
covers publishing, evaluating rivals, describing the holder, and release.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
from unittest.mock import patch
import pytest
from gatelock._arbiter import (
RANK_DIET_GUARD,
RANK_SCREEN_LOCKER,
RANK_WAKE_ALARM,
Arbiter,
Claim,
)
if TYPE_CHECKING:
from collections.abc import Iterator
from pathlib import Path
DEFAULT_STARTED = "2026-07-25T12:00:00+00:00"
def dead_claim(app: str = "ghost", instance_id: str = "dead") -> Claim:
"""A claim belonging to a process that has since died."""
return Claim(
app=app,
rank=RANK_WAKE_ALARM,
pid=999999,
started=DEFAULT_STARTED,
grab="global",
disable_vt=True,
instance_id=instance_id,
)
def make_claim(
*,
rank: int = RANK_SCREEN_LOCKER,
started: str = DEFAULT_STARTED,
grab: str = "global",
disable_vt: bool = True,
) -> Claim:
"""A claim with sensible defaults."""
return Claim(
app="test_app",
rank=rank,
pid=1234,
started=started,
grab=grab,
disable_vt=disable_vt,
instance_id="tok",
)
@pytest.fixture
def arb(tmp_path: Path) -> Iterator[Arbiter]:
"""A published hard-locking arbiter in an isolated runtime dir."""
arbiter = Arbiter(
"screen_locker",
RANK_SCREEN_LOCKER,
grab="global",
disable_vt=True,
runtime_dir=tmp_path / "rt",
)
arbiter.publish()
yield arbiter
arbiter.release()
def hard(name: str, rank: int, root: Path) -> Arbiter:
"""A hard-locking arbiter."""
return Arbiter(name, rank, grab="global", disable_vt=True, runtime_dir=root)
class TestPublishAndLiveClaims:
"""Publishing, liveness and reaping."""
def test_own_claim_is_live(self, arb: Arbiter) -> None:
"""A published claim shows up as live."""
assert [c.app for c in arb.live_claims()] == ["screen_locker"]
def test_no_claims_dir(self, tmp_path: Path) -> None:
"""Before anyone publishes, there are no claims."""
assert hard("a", 1, tmp_path / "empty").live_claims() == ()
def test_dead_claim_is_reaped(self, arb: Arbiter, tmp_path: Path) -> None:
"""An unlocked claim file proves its owner died; it is deleted."""
dead = tmp_path / "rt" / "claims" / "0300-999-dead.json"
dead.write_text(dead_claim().to_json(), "utf-8")
assert "ghost" not in [c.app for c in arb.live_claims()]
assert not dead.exists()
def test_unreadable_claim_ignored(self, arb: Arbiter, tmp_path: Path) -> None:
"""A claim that cannot be opened is skipped, not fatal."""
bad = tmp_path / "rt" / "claims" / "0100-1-bad.json"
bad.write_text("{}", encoding="utf-8")
with patch("gatelock._arbiter.Path.open", side_effect=OSError("denied")):
assert arb.live_claims() == ()
def test_reap_skips_recreated_file(self, arb: Arbiter, tmp_path: Path) -> None:
"""A claim recreated between lock and unlink is not deleted."""
dead = tmp_path / "rt" / "claims" / "0300-999-dead.json"
dead.write_text(dead_claim().to_json(), "utf-8")
with patch("gatelock._arbiter._same_file", return_value=False):
arb.live_claims()
assert dead.exists()
def test_reap_tolerates_unlink_failure(self, arb: Arbiter, tmp_path: Path) -> None:
"""A failed unlink is logged, not raised."""
dead = tmp_path / "rt" / "claims" / "0300-999-dead.json"
dead.write_text(dead_claim().to_json(), "utf-8")
with patch("gatelock._arbiter.Path.unlink", side_effect=OSError("busy")):
live = arb.live_claims()
# The reap is best-effort: the claim is excluded from the live set even
# when the file itself cannot be removed.
assert "ghost" not in [c.app for c in live]
def test_publish_twice_warns_and_continues(self, tmp_path: Path) -> None:
"""A second publish on a locked path continues unpublished."""
arbiter = hard("a", RANK_DIET_GUARD, tmp_path / "rt")
arbiter.publish()
with patch("gatelock._arbiter._try_lock", return_value=False):
arbiter.publish() # must not raise
arbiter.release()
class TestEvaluate:
"""Who may arm."""
def test_clear_when_alone(self, arb: Arbiter) -> None:
"""Nothing pending means arm."""
verdict = arb.evaluate()
assert verdict.may_arm is True
assert verdict.reason == "clear"
assert verdict.blocked_by is None
def test_lower_rank_does_not_block(self, arb: Arbiter, tmp_path: Path) -> None:
"""A weaker-ranked peer never blocks."""
diet = hard("diet_guard", RANK_DIET_GUARD, tmp_path / "rt")
diet.publish()
assert arb.evaluate().may_arm is True
diet.release()
def test_stronger_higher_rank_blocks(self, arb: Arbiter, tmp_path: Path) -> None:
"""A higher-ranked, equally strong app wins."""
alarm = hard("wake_alarm", RANK_WAKE_ALARM, tmp_path / "rt")
alarm.publish()
verdict = arb.evaluate()
assert verdict.may_arm is False
assert verdict.reason == "outranked"
assert verdict.blocked_by is not None
assert verdict.blocked_by.app == "wake_alarm"
alarm.release()
def test_weaker_higher_rank_arms_anyway(self, arb: Arbiter, tmp_path: Path) -> None:
"""Rank must never be able to reduce total lock strength."""
soft_alarm = Arbiter(
"wake_alarm",
RANK_WAKE_ALARM,
grab="none",
disable_vt=False,
runtime_dir=tmp_path / "rt",
)
soft_alarm.publish()
verdict = arb.evaluate()
assert verdict.may_arm is True
assert verdict.reason == "weaker-incumbent-armed-anyway"
soft_alarm.release()

View File

@ -0,0 +1,194 @@
"""Tests for identifying the current holder and releasing a claim.
Split from ``test_arbiter.py`` (250-line cap). ``test_arbiter_lifecycle.py``
keeps publishing and rival evaluation; this one covers who holds the claim
now and what happens when it is given up.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
from unittest.mock import MagicMock, patch
import pytest
from gatelock._arbiter import (
RANK_DIET_GUARD,
RANK_SCREEN_LOCKER,
RANK_WAKE_ALARM,
Arbiter,
Claim,
)
if TYPE_CHECKING:
from collections.abc import Iterator
from pathlib import Path
DEFAULT_STARTED = "2026-07-25T12:00:00+00:00"
def dead_claim(app: str = "ghost", instance_id: str = "dead") -> Claim:
"""A claim belonging to a process that has since died."""
return Claim(
app=app,
rank=RANK_WAKE_ALARM,
pid=999999,
started=DEFAULT_STARTED,
grab="global",
disable_vt=True,
instance_id=instance_id,
)
def make_claim(
*,
rank: int = RANK_SCREEN_LOCKER,
started: str = DEFAULT_STARTED,
grab: str = "global",
disable_vt: bool = True,
) -> Claim:
"""A claim with sensible defaults."""
return Claim(
app="test_app",
rank=rank,
pid=1234,
started=started,
grab=grab,
disable_vt=disable_vt,
instance_id="tok",
)
@pytest.fixture
def arb(tmp_path: Path) -> Iterator[Arbiter]:
"""A published hard-locking arbiter in an isolated runtime dir."""
arbiter = Arbiter(
"screen_locker",
RANK_SCREEN_LOCKER,
grab="global",
disable_vt=True,
runtime_dir=tmp_path / "rt",
)
arbiter.publish()
yield arbiter
arbiter.release()
def hard(name: str, rank: int, root: Path) -> Arbiter:
"""A hard-locking arbiter."""
return Arbiter(name, rank, grab="global", disable_vt=True, runtime_dir=root)
class TestHolder:
"""Owning and naming the screen."""
def test_acquire_and_reacquire(self, arb: Arbiter) -> None:
"""Acquiring twice is idempotent."""
assert arb.acquire_holder() is True
assert arb.holds_screen is True
assert arb.acquire_holder() is True
def test_second_app_is_blocked(self, arb: Arbiter, tmp_path: Path) -> None:
"""Only one app holds the screen."""
arb.acquire_holder()
other = hard("diet_guard", RANK_DIET_GUARD, tmp_path / "rt")
other.publish()
assert other.acquire_holder() is False
other.release()
def test_blocked_app_learns_the_holder(self, arb: Arbiter, tmp_path: Path) -> None:
"""A failed acquire must not erase the incumbent's claim."""
arb.acquire_holder()
other = hard("diet_guard", RANK_DIET_GUARD, tmp_path / "rt")
other.publish()
other.acquire_holder()
holder = other.describe_holder()
assert holder is not None
assert holder.app == "screen_locker"
other.release()
def test_describe_holder_when_we_hold_it(self, arb: Arbiter) -> None:
"""The holder describes itself without touching the file."""
arb.acquire_holder()
holder = arb.describe_holder()
assert holder is not None
assert holder.app == "screen_locker"
def test_describe_holder_no_file(self, arb: Arbiter) -> None:
"""No holder file means nobody holds the screen."""
assert arb.describe_holder() is None
def test_describe_holder_stale_lock(self, arb: Arbiter, tmp_path: Path) -> None:
"""A holder file nobody locks means the owner died."""
(tmp_path / "rt").mkdir(parents=True, exist_ok=True)
(tmp_path / "rt" / "holder.lock").write_text(
dead_claim().to_json(), encoding="utf-8"
)
assert arb.describe_holder() is None
def test_describe_holder_oserror(self, arb: Arbiter, tmp_path: Path) -> None:
"""An unreadable holder file is reported as no holder."""
(tmp_path / "rt").mkdir(parents=True, exist_ok=True)
(tmp_path / "rt" / "holder.lock").write_text("{}", encoding="utf-8")
with patch("gatelock._arbiter.Path.open", side_effect=OSError("denied")):
assert arb.describe_holder() is None
class TestRelease:
"""Clean exit hands the screen over."""
def test_release_lets_the_next_app_in(self, tmp_path: Path) -> None:
"""The alarm -> workout handoff: a clean exit must free the screen."""
alarm = hard("wake_alarm", RANK_WAKE_ALARM, tmp_path / "rt")
alarm.publish()
assert alarm.acquire_holder() is True
workout = hard("screen_locker", RANK_SCREEN_LOCKER, tmp_path / "rt")
workout.publish()
assert workout.acquire_holder() is False
assert workout.evaluate().may_arm is False
alarm.release()
assert workout.acquire_holder() is True
assert workout.evaluate().may_arm is True
workout.release()
def test_release_is_idempotent(self, tmp_path: Path) -> None:
"""Releasing twice is safe."""
arbiter = hard("a", RANK_DIET_GUARD, tmp_path / "rt")
arbiter.publish()
arbiter.release()
arbiter.release()
assert arbiter.holds_screen is False
def test_release_tolerates_unlink_failure(self, tmp_path: Path) -> None:
"""A claim that cannot be removed does not break teardown."""
arbiter = hard("a", RANK_DIET_GUARD, tmp_path / "rt")
arbiter.publish()
with patch("gatelock._arbiter.Path.unlink", side_effect=OSError("busy")):
arbiter.release()
def test_claim_property(self, arb: Arbiter) -> None:
"""The arbiter exposes its own claim."""
assert arb.claim.app == "screen_locker"
assert arb.claim.rank == RANK_SCREEN_LOCKER
class TestReleaseHandleClose:
"""Handle-close failures are non-fatal."""
def test_close_oserror_is_swallowed(self, tmp_path: Path) -> None:
"""A failing close does not stop the release."""
arbiter = hard("a", RANK_DIET_GUARD, tmp_path / "rt")
arbiter.publish()
arbiter.acquire_holder()
bad = MagicMock()
bad.close.side_effect = OSError("nope")
real_handle = arbiter._holder_handle
assert real_handle is not None
real_handle.close()
arbiter._holder_handle = bad
arbiter.release()
assert arbiter.holds_screen is False

View File

@ -173,171 +173,3 @@ class TestIntegrityNeverWidensTheBudget:
tracker.load()
assert tracker.tampered == 1
assert tracker.is_budget_exhausted(today=TODAY) is True
class TestBudget:
"""Rolling windows."""
def test_counts_only_inside_the_window(self, tracker: EscapeTracker) -> None:
"""An old use falls out of the 7-day window."""
tracker.history.used_days = ["2026-07-24", "2026-06-01"]
assert tracker.count_in_window(7, today=TODAY) == 1
assert tracker.count_in_window(90, today=TODAY) == 2
def test_unparsable_today_counts_nothing(self, tracker: EscapeTracker) -> None:
"""A broken 'today' cannot silently exhaust the budget."""
tracker.history.used_days = [TODAY]
assert tracker.count_in_window(7, today="garbage") == 0
def test_unparsable_entry_is_skipped(self, tracker: EscapeTracker) -> None:
"""A corrupt stored date is ignored, loudly."""
tracker.history.used_days = ["nonsense", TODAY]
assert tracker.count_in_window(7, today=TODAY) == 1
@pytest.mark.parametrize(
("days", "expected"),
[(["2026-07-25"], True), ([], False)],
)
def test_week_window(
self, tracker: EscapeTracker, days: list[str], *, expected: bool
) -> None:
"""One use exhausts the weekly budget of 1."""
tracker.history.used_days = days
assert tracker.is_budget_exhausted(today=TODAY) is expected
def test_month_window(self, tracker: EscapeTracker) -> None:
"""Three uses in 30 days exhausts, even if none is in the last week."""
tracker.history.used_days = ["2026-07-05", "2026-07-06", "2026-07-07"]
assert tracker.is_budget_exhausted(today=TODAY) is True
def test_quarter_window(self, tracker: EscapeTracker) -> None:
"""Ten uses in 90 days exhausts, spread out enough to clear the others."""
tracker.history.used_days = [f"2026-05-{day:02d}" for day in range(1, 11)]
assert tracker.is_budget_exhausted(today=TODAY) is True
def test_nothing_used_is_not_exhausted(self, tracker: EscapeTracker) -> None:
"""A clean history leaves the hatch available."""
assert tracker.is_budget_exhausted(today=TODAY) is False
class TestLockout:
"""The wait grows the more you lean on the hatch."""
@pytest.mark.parametrize(
("recent", "seconds"), [(0, 120), (1, 240), (2, 480), (3, 960)]
)
def test_doubles_per_recent_use(
self, tracker: EscapeTracker, recent: int, seconds: int
) -> None:
"""base * 2 ** uses_in_30_days."""
tracker.history.used_days = [f"2026-07-{10 + i:02d}" for i in range(recent)]
assert tracker.compute_lockout_seconds(today=TODAY) == seconds
class TestValidation:
"""What counts as a real justification."""
def test_accepts_a_proper_one(self, tracker: EscapeTracker) -> None:
"""A complete draft passes."""
assert tracker.validate(good_draft()) is None
@pytest.mark.parametrize(
("draft", "fragment"),
[
(EscapeDraft("", "03:00", 5, "x" * 130), "what the problem is"),
(EscapeDraft("flu", "", 5, "x" * 130), "when it started"),
(EscapeDraft("flu", "03:00", 0, "x" * 130), "between 1 and 10"),
(EscapeDraft("flu", "03:00", 11, "x" * 130), "between 1 and 10"),
(EscapeDraft("flu", "03:00", 5, "short"), "Explain properly"),
],
)
def test_rejections(
self, tracker: EscapeTracker, draft: EscapeDraft, fragment: str
) -> None:
"""Each missing or lazy field is refused with a specific complaint."""
message = tracker.validate(draft)
assert message is not None
assert fragment in message
class TestRecord:
"""Writing a use down."""
def test_records_and_signs(self, tracker: EscapeTracker) -> None:
"""A use is appended, dated and signed."""
assert tracker.record(good_draft(), today=TODAY) is True
entry = tracker.history.justifications[-1]
assert entry["date"] == TODAY
assert entry["policy"] == "sick"
assert "hmac" in entry
def test_unsigned_when_key_unavailable(
self, tracker: EscapeTracker, tmp_path: Path
) -> None:
"""Without a key the entry is still recorded, just unsigned."""
tracker._key_file = tmp_path / "absent.key"
assert tracker.record(good_draft(), today=TODAY) is True
assert "hmac" not in tracker.history.justifications[-1]
def test_same_day_twice_counts_once(self, tracker: EscapeTracker) -> None:
"""Two uses on one day are one day of budget."""
tracker.record(good_draft(), today=TODAY)
tracker.record(good_draft(), today=TODAY)
assert tracker.history.used_days == [TODAY]
assert len(tracker.history.justifications) == 2
def test_uses_today_when_unspecified(self, tracker: EscapeTracker) -> None:
"""Omitting the date records the real today."""
tracker.record(good_draft())
assert tracker.history.used_days == [_today_iso()]
def test_save_failure_is_reported(self, tracker: EscapeTracker) -> None:
"""A read-only disk is surfaced, not swallowed."""
with patch("pathlib.Path.write_text", side_effect=OSError("ro")):
assert tracker.record(good_draft(), today=TODAY) is False
class TestReadBack:
"""Showing past excuses back to the user is half the deterrent."""
def test_empty(self, tracker: EscapeTracker) -> None:
"""A clean history says so."""
assert tracker.format_recent() == "(no previous uses)"
assert tracker.recent_justifications() == []
def test_lists_recent(self, tracker: EscapeTracker) -> None:
"""Past entries are rendered with date, severity and reason."""
tracker.record(good_draft(), today=TODAY)
rendered = tracker.format_recent()
assert TODAY in rendered
assert "8/10" in rendered
assert "migraine" in rendered
def test_respects_explicit_limit(self, tracker: EscapeTracker) -> None:
"""An explicit count overrides the policy default."""
for day in range(1, 6):
tracker.record(good_draft(), today=f"2026-07-{day:02d}")
assert len(tracker.recent_justifications(2)) == 2
def test_handles_entries_missing_fields(
self, tracker: EscapeTracker, tmp_path: Path
) -> None:
"""A partial entry renders without raising."""
(tmp_path / "escape.json").write_text(
json.dumps({"used_days": [], "justifications": [{}]}), encoding="utf-8"
)
tracker.load()
assert "?" in tracker.format_recent()
class TestSummary:
"""The one-line budget readout."""
def test_summary_shows_all_three_windows(self, tracker: EscapeTracker) -> None:
"""Week, month and quarter counts all appear."""
tracker.history.used_days = [TODAY]
assert tracker.budget_summary(today=TODAY) == "Sick: 1/1w · 1/3m · 1/10q"
def test_policy_property(self, tracker: EscapeTracker) -> None:
"""The tracker exposes the policy it enforces."""
assert tracker.policy is POLICY

View File

@ -0,0 +1,216 @@
"""Tests for the escape-hatch budget, lockout and recording.
Split from ``test_escape.py`` (250-line cap), which keeps policy defaults,
timestamp parsing, loading, and the integrity guarantee.
"""
from __future__ import annotations
import json
from typing import TYPE_CHECKING
from unittest.mock import patch
import pytest
from gatelock._escape import (
EscapeDraft,
EscapePolicy,
EscapeTracker,
_today_iso,
)
if TYPE_CHECKING:
from pathlib import Path
TODAY = "2026-07-25"
POLICY = EscapePolicy(name="sick", label="Sick")
@pytest.fixture
def key_file(tmp_path: Path) -> Path:
"""A throwaway signing key, so tests never touch the real root-owned one."""
path = tmp_path / "hmac.key"
path.write_bytes(b"0" * 32)
return path
@pytest.fixture
def tracker(tmp_path: Path, key_file: Path) -> EscapeTracker:
"""A tracker over an empty history."""
return EscapeTracker(POLICY, tmp_path / "escape.json", key_file=key_file)
def good_draft() -> EscapeDraft:
"""A justification that passes validation."""
return EscapeDraft(
reason="migraine", onset="03:00", severity=8, description="x" * 130
)
class TestBudget:
"""Rolling windows."""
def test_counts_only_inside_the_window(self, tracker: EscapeTracker) -> None:
"""An old use falls out of the 7-day window."""
tracker.history.used_days = ["2026-07-24", "2026-06-01"]
assert tracker.count_in_window(7, today=TODAY) == 1
assert tracker.count_in_window(90, today=TODAY) == 2
def test_unparsable_today_counts_nothing(self, tracker: EscapeTracker) -> None:
"""A broken 'today' cannot silently exhaust the budget."""
tracker.history.used_days = [TODAY]
assert tracker.count_in_window(7, today="garbage") == 0
def test_unparsable_entry_is_skipped(self, tracker: EscapeTracker) -> None:
"""A corrupt stored date is ignored, loudly."""
tracker.history.used_days = ["nonsense", TODAY]
assert tracker.count_in_window(7, today=TODAY) == 1
@pytest.mark.parametrize(
("days", "expected"),
[(["2026-07-25"], True), ([], False)],
)
def test_week_window(
self, tracker: EscapeTracker, days: list[str], *, expected: bool
) -> None:
"""One use exhausts the weekly budget of 1."""
tracker.history.used_days = days
assert tracker.is_budget_exhausted(today=TODAY) is expected
def test_month_window(self, tracker: EscapeTracker) -> None:
"""Three uses in 30 days exhausts, even if none is in the last week."""
tracker.history.used_days = ["2026-07-05", "2026-07-06", "2026-07-07"]
assert tracker.is_budget_exhausted(today=TODAY) is True
def test_quarter_window(self, tracker: EscapeTracker) -> None:
"""Ten uses in 90 days exhausts, spread out enough to clear the others."""
tracker.history.used_days = [f"2026-05-{day:02d}" for day in range(1, 11)]
assert tracker.is_budget_exhausted(today=TODAY) is True
def test_nothing_used_is_not_exhausted(self, tracker: EscapeTracker) -> None:
"""A clean history leaves the hatch available."""
assert tracker.is_budget_exhausted(today=TODAY) is False
class TestLockout:
"""The wait grows the more you lean on the hatch."""
@pytest.mark.parametrize(
("recent", "seconds"), [(0, 120), (1, 240), (2, 480), (3, 960)]
)
def test_doubles_per_recent_use(
self, tracker: EscapeTracker, recent: int, seconds: int
) -> None:
"""base * 2 ** uses_in_30_days."""
tracker.history.used_days = [f"2026-07-{10 + i:02d}" for i in range(recent)]
assert tracker.compute_lockout_seconds(today=TODAY) == seconds
class TestValidation:
"""What counts as a real justification."""
def test_accepts_a_proper_one(self, tracker: EscapeTracker) -> None:
"""A complete draft passes."""
assert tracker.validate(good_draft()) is None
@pytest.mark.parametrize(
("draft", "fragment"),
[
(EscapeDraft("", "03:00", 5, "x" * 130), "what the problem is"),
(EscapeDraft("flu", "", 5, "x" * 130), "when it started"),
(EscapeDraft("flu", "03:00", 0, "x" * 130), "between 1 and 10"),
(EscapeDraft("flu", "03:00", 11, "x" * 130), "between 1 and 10"),
(EscapeDraft("flu", "03:00", 5, "short"), "Explain properly"),
],
)
def test_rejections(
self, tracker: EscapeTracker, draft: EscapeDraft, fragment: str
) -> None:
"""Each missing or lazy field is refused with a specific complaint."""
message = tracker.validate(draft)
assert message is not None
assert fragment in message
class TestRecord:
"""Writing a use down."""
def test_records_and_signs(self, tracker: EscapeTracker) -> None:
"""A use is appended, dated and signed."""
assert tracker.record(good_draft(), today=TODAY) is True
entry = tracker.history.justifications[-1]
assert entry["date"] == TODAY
assert entry["policy"] == "sick"
assert "hmac" in entry
def test_unsigned_when_key_unavailable(
self, tracker: EscapeTracker, tmp_path: Path
) -> None:
"""Without a key the entry is still recorded, just unsigned."""
tracker._key_file = tmp_path / "absent.key"
assert tracker.record(good_draft(), today=TODAY) is True
assert "hmac" not in tracker.history.justifications[-1]
def test_same_day_twice_counts_once(self, tracker: EscapeTracker) -> None:
"""Two uses on one day are one day of budget."""
tracker.record(good_draft(), today=TODAY)
tracker.record(good_draft(), today=TODAY)
assert tracker.history.used_days == [TODAY]
assert len(tracker.history.justifications) == 2
def test_uses_today_when_unspecified(self, tracker: EscapeTracker) -> None:
"""Omitting the date records the real today."""
tracker.record(good_draft())
assert tracker.history.used_days == [_today_iso()]
def test_save_failure_is_reported(self, tracker: EscapeTracker) -> None:
"""A read-only disk is surfaced, not swallowed."""
with patch("pathlib.Path.write_text", side_effect=OSError("ro")):
assert tracker.record(good_draft(), today=TODAY) is False
class TestReadBack:
"""Showing past excuses back to the user is half the deterrent."""
def test_empty(self, tracker: EscapeTracker) -> None:
"""A clean history says so."""
assert tracker.format_recent() == "(no previous uses)"
assert tracker.recent_justifications() == []
def test_lists_recent(self, tracker: EscapeTracker) -> None:
"""Past entries are rendered with date, severity and reason."""
tracker.record(good_draft(), today=TODAY)
rendered = tracker.format_recent()
assert TODAY in rendered
assert "8/10" in rendered
assert "migraine" in rendered
def test_respects_explicit_limit(self, tracker: EscapeTracker) -> None:
"""An explicit count overrides the policy default."""
for day in range(1, 6):
tracker.record(good_draft(), today=f"2026-07-{day:02d}")
assert len(tracker.recent_justifications(2)) == 2
def test_handles_entries_missing_fields(
self, tracker: EscapeTracker, tmp_path: Path
) -> None:
"""A partial entry renders without raising."""
(tmp_path / "escape.json").write_text(
json.dumps({"used_days": [], "justifications": [{}]}), encoding="utf-8"
)
tracker.load()
assert "?" in tracker.format_recent()
class TestSummary:
"""The one-line budget readout."""
def test_summary_shows_all_three_windows(self, tracker: EscapeTracker) -> None:
"""Week, month and quarter counts all appear."""
tracker.history.used_days = [TODAY]
assert tracker.budget_summary(today=TODAY) == "Sick: 1/1w · 1/3m · 1/10q"
def test_policy_property(self, tracker: EscapeTracker) -> None:
"""The tracker exposes the policy it enforces."""
assert tracker.policy is POLICY

View File

@ -14,12 +14,9 @@ import pytest
from gatelock._outputs import (
Output,
OutputEnumerator,
OutputRect,
OutputScan,
RandrBackend,
_decode_name,
enumerate_outputs,
parse_xrandr_query,
)
from gatelock._outputs import scan_xrandr as real_scan_xrandr
@ -188,231 +185,3 @@ class TestDecodeName:
def test_decode(self, raw: object, expected: str) -> None:
"""Bytes are decoded, str passes through, bad bytes are replaced."""
assert _decode_name(raw) == expected
def _reply(**fields: object) -> MagicMock:
"""An Xlib reply exposing its fields as attributes, as python-xlib does."""
reply = MagicMock()
for key, value in fields.items():
setattr(reply, key, value)
return reply
def _randr_display(*, outputs: dict[int, dict[str, object]]) -> MagicMock:
"""Build a fake Xlib display exposing ``outputs``."""
display = MagicMock()
root = MagicMock()
root.xrandr_get_screen_resources.return_value = _reply(
config_timestamp=1, outputs=list(outputs)
)
root.xrandr_get_output_primary.return_value = _reply(output=1)
display.screen.return_value.root = root
def output_info(output_id: int, _ts: int) -> MagicMock:
return _reply(**outputs[output_id]["info"])
def crtc_info(crtc: int, _ts: int) -> MagicMock:
return _reply(**outputs[crtc]["crtc"])
display.xrandr_get_output_info.side_effect = output_info
display.xrandr_get_crtc_info.side_effect = crtc_info
return display
class TestRandrBackend:
"""Tests for the RandR backend."""
def test_scan_maps_crtc_to_rect(self) -> None:
"""A connected output with a CRTC and mode becomes a live rect."""
display = _randr_display(
outputs={
1: {
"info": {"name": "DP-0", "connection": 0, "crtc": 1},
"crtc": {"mode": 55, "x": 0, "y": 0, "width": 3840, "height": 2160},
}
}
)
(output,) = RandrBackend(display).scan() or ()
assert output.name == "DP-0"
assert output.live is True
assert output.primary is True
assert output.rect == OutputRect(0, 0, 3840, 2160)
def test_no_crtc_is_not_live(self) -> None:
"""crtc == 0 is the dark-monitor case."""
display = _randr_display(
outputs={1: {"info": {"name": "DP-0", "connection": 0, "crtc": 0}}}
)
(output,) = RandrBackend(display).scan() or ()
assert output.connected is True
assert output.rect is None
def test_crtc_without_mode_is_not_live(self) -> None:
"""A CRTC exists but carries no mode: still dark."""
display = _randr_display(
outputs={
1: {
"info": {"name": "DP-0", "connection": 0, "crtc": 1},
"crtc": {"mode": 0, "x": 0, "y": 0, "width": 0, "height": 0},
}
}
)
(output,) = RandrBackend(display).scan() or ()
assert output.rect is None
def test_zero_size_crtc_is_not_live(self) -> None:
"""A mode with no pixels is not a screen."""
display = _randr_display(
outputs={
1: {
"info": {"name": "DP-0", "connection": 0, "crtc": 1},
"crtc": {"mode": 55, "x": 0, "y": 0, "width": 0, "height": 1080},
}
}
)
(output,) = RandrBackend(display).scan() or ()
assert output.rect is None
def test_disconnected(self) -> None:
"""connection != 0 means disconnected."""
display = _randr_display(
outputs={1: {"info": {"name": "DP-1", "connection": 1, "crtc": 0}}}
)
(output,) = RandrBackend(display).scan() or ()
assert output.connected is False
def test_scan_failure_returns_none(self) -> None:
"""A protocol error degrades to None instead of raising."""
display = MagicMock()
display.screen.side_effect = OSError("connection reset")
assert RandrBackend(display).scan() is None
def test_primary_query_failure_is_tolerated(self) -> None:
"""RandR refusing to name a primary is not fatal."""
display = _randr_display(
outputs={1: {"info": {"name": "DP-0", "connection": 0, "crtc": 0}}}
)
root = display.screen.return_value.root
root.xrandr_get_output_primary.side_effect = OSError("nope")
(output,) = RandrBackend(display).scan() or ()
assert output.primary is False
def test_close_swallows_errors(self) -> None:
"""Teardown never raises."""
display = MagicMock()
display.close.side_effect = OSError("already gone")
RandrBackend(display).close()
def test_close_normal(self) -> None:
"""A clean close closes the display."""
display = MagicMock()
RandrBackend(display).close()
display.close.assert_called_once_with()
class TestCreateWithoutXlib:
"""RandrBackend.create's degradation path, exercised without the patch."""
def test_import_error_returns_none(self) -> None:
"""A missing python-xlib degrades to None, never an exception.
This is the branch the function-scope import exists to keep reachable.
"""
with patch.dict("sys.modules", {"Xlib": None}):
assert REAL_CREATE(RandrBackend) is None
def test_display_error_returns_none(self) -> None:
"""A display that refuses to open returns None."""
fake_display = MagicMock()
fake_display.Display.side_effect = OSError("cannot connect")
# `from Xlib import display` reads the attribute off the parent
# module, so wiring sys.modules alone is not enough.
fake_xlib = MagicMock(display=fake_display)
with patch.dict(
"sys.modules",
{"Xlib": fake_xlib, "Xlib.display": fake_display},
):
assert REAL_CREATE(RandrBackend) is None
def test_success_returns_backend(self) -> None:
"""A working python-xlib yields a usable backend."""
fake_display = MagicMock()
fake_xlib = MagicMock(display=fake_display)
with patch.dict(
"sys.modules",
{"Xlib": fake_xlib, "Xlib.display": fake_display},
):
backend = REAL_CREATE(RandrBackend)
assert isinstance(backend, RandrBackend)
class TestOutputEnumerator:
"""Tests for the backend ladder."""
def test_prefers_randr(self, mock_root: MagicMock) -> None:
"""When RandR answers, xrandr is never consulted."""
backend = MagicMock()
backend.scan.return_value = (
Output("DP-0", connected=True, rect=OutputRect(0, 0, 1, 1)),
)
scan = OutputEnumerator(mock_root, backend=backend).scan()
assert scan.source == "randr"
assert scan.ok is True
def test_falls_back_to_xrandr(self, mock_root: MagicMock) -> None:
"""A failed RandR scan drops to xrandr."""
backend = MagicMock()
backend.scan.return_value = None
with patch(
"gatelock._outputs.scan_xrandr",
return_value=(Output("DP-0", connected=True, rect=OutputRect(0, 0, 1, 1)),),
):
scan = OutputEnumerator(mock_root, backend=backend).scan()
assert scan.source == "xrandr"
def test_falls_back_to_tk(self, mock_root: MagicMock) -> None:
"""With neither backend, Tk's screen size is the floor."""
with patch("gatelock._outputs.scan_xrandr", return_value=None):
scan = OutputEnumerator(mock_root, backend=None).scan()
assert scan.source == "tk"
assert scan.live[0].rect == OutputRect(0, 0, 1920, 1080)
def test_total_failure_is_not_ok(self) -> None:
"""With no root and no backend, the scan reports failure."""
with patch("gatelock._outputs.scan_xrandr", return_value=None):
scan = OutputEnumerator(None, backend=None).scan()
assert scan.ok is False
assert scan.source == "none"
assert scan.live == ()
def test_backend_property_and_close(self) -> None:
"""close() releases the backend once and is safe to repeat."""
backend = MagicMock()
enumerator = OutputEnumerator(None, backend=backend)
assert enumerator.backend is backend
enumerator.close()
enumerator.close()
backend.close.assert_called_once_with()
def test_enumerate_outputs_helper(self, mock_root: MagicMock) -> None:
"""The one-shot helper works and cleans up after itself."""
with patch("gatelock._outputs.scan_xrandr", return_value=None):
scan = enumerate_outputs(mock_root)
assert scan.source == "tk"
class TestOutputScan:
"""Tests for OutputScan's live filter."""
def test_live_filters_dark_outputs(self) -> None:
"""Only connected-with-mode outputs are live."""
scan = OutputScan(
outputs=(
Output("DP-0", connected=True, rect=None),
Output("HDMI-0", connected=True, rect=OutputRect(0, 0, 1, 1)),
Output("DP-1", connected=False, rect=None),
),
source="randr",
ok=True,
)
assert [o.name for o in scan.live] == ["HDMI-0"]

View File

@ -0,0 +1,126 @@
"""Tests for OutputEnumerator and the scan it returns.
Split from ``test_outputs.py`` (250-line cap). ``test_outputs_randr.py``
keeps the python-xlib backend itself; this covers the enumerator that drives
it and the OutputScan it produces.
"""
from __future__ import annotations
from unittest.mock import MagicMock, patch
from gatelock._outputs import (
Output,
OutputEnumerator,
OutputRect,
OutputScan,
RandrBackend,
enumerate_outputs,
)
# Bound at import, so the autouse hermetic patch (which replaces these
# attributes) does not hide the real implementations from their own tests.
REAL_CREATE = RandrBackend.create.__func__
XRANDR_REAL = """\
Screen 0: minimum 8 x 8, current 6400 x 2160, maximum 32767 x 32767
HDMI-0 connected 2560x1440+3840+0 (normal left inverted right x axis) 597mm x 336mm
2560x1440 59.95*+ 143.98 120.00
1920x1080 60.00 59.94
DP-0 connected primary 3840x2160+0+0 (normal left inverted right x axis) 621mm x 341mm
3840x2160 60.00*+ 144.00
DP-1 disconnected (normal left inverted right x axis y axis)
"""
XRANDR_INCIDENT = """\
Screen 0: minimum 8 x 8, current 6400 x 1440, maximum 32767 x 32767
HDMI-0 connected 2560x1440+3840+0 (normal left inverted right x axis) 600mm x 330mm
2560x1440 59.95*+
DP-0 connected primary (normal left inverted right x axis y axis) 621mm x 341mm
3840x2160 60.00 +
"""
XRANDR_ALL_DARK = """\
HDMI-0 connected (normal left inverted right x axis)
DP-0 connected primary (normal left inverted right x axis y axis)
"""
XRANDR_ROTATED = "DP-0 connected primary 1080x1920+0+0 left (normal left inverted)\n"
XRANDR_NEGATIVE = "DP-0 connected 1920x1080+-1920+0 (normal left inverted)\n"
XRANDR_ZERO_SIZE = "DP-0 connected 0x0+0+0 (normal left inverted)\n"
XRANDR_MODE_LINES_ONLY = " 2560x1440 59.95*+ 143.98\n 1920x1080 60.00\n"
XRANDR_GARBAGE = "segfault\n"
class TestOutputEnumerator:
"""Tests for the backend ladder."""
def test_prefers_randr(self, mock_root: MagicMock) -> None:
"""When RandR answers, xrandr is never consulted."""
backend = MagicMock()
backend.scan.return_value = (
Output("DP-0", connected=True, rect=OutputRect(0, 0, 1, 1)),
)
scan = OutputEnumerator(mock_root, backend=backend).scan()
assert scan.source == "randr"
assert scan.ok is True
def test_falls_back_to_xrandr(self, mock_root: MagicMock) -> None:
"""A failed RandR scan drops to xrandr."""
backend = MagicMock()
backend.scan.return_value = None
with patch(
"gatelock._outputs.scan_xrandr",
return_value=(Output("DP-0", connected=True, rect=OutputRect(0, 0, 1, 1)),),
):
scan = OutputEnumerator(mock_root, backend=backend).scan()
assert scan.source == "xrandr"
def test_falls_back_to_tk(self, mock_root: MagicMock) -> None:
"""With neither backend, Tk's screen size is the floor."""
with patch("gatelock._outputs.scan_xrandr", return_value=None):
scan = OutputEnumerator(mock_root, backend=None).scan()
assert scan.source == "tk"
assert scan.live[0].rect == OutputRect(0, 0, 1920, 1080)
def test_total_failure_is_not_ok(self) -> None:
"""With no root and no backend, the scan reports failure."""
with patch("gatelock._outputs.scan_xrandr", return_value=None):
scan = OutputEnumerator(None, backend=None).scan()
assert scan.ok is False
assert scan.source == "none"
assert scan.live == ()
def test_backend_property_and_close(self) -> None:
"""close() releases the backend once and is safe to repeat."""
backend = MagicMock()
enumerator = OutputEnumerator(None, backend=backend)
assert enumerator.backend is backend
enumerator.close()
enumerator.close()
backend.close.assert_called_once_with()
def test_enumerate_outputs_helper(self, mock_root: MagicMock) -> None:
"""The one-shot helper works and cleans up after itself."""
with patch("gatelock._outputs.scan_xrandr", return_value=None):
scan = enumerate_outputs(mock_root)
assert scan.source == "tk"
class TestOutputScan:
"""Tests for OutputScan's live filter."""
def test_live_filters_dark_outputs(self) -> None:
"""Only connected-with-mode outputs are live."""
scan = OutputScan(
outputs=(
Output("DP-0", connected=True, rect=None),
Output("HDMI-0", connected=True, rect=OutputRect(0, 0, 1, 1)),
Output("DP-1", connected=False, rect=None),
),
source="randr",
ok=True,
)
assert [o.name for o in scan.live] == ["HDMI-0"]

View File

@ -0,0 +1,204 @@
"""Tests for the python-xlib RandR backend and the enumerator over it.
Split from ``test_outputs.py`` (250-line cap), which keeps rect geometry,
the live predicate, and xrandr-query parsing.
"""
from __future__ import annotations
from unittest.mock import MagicMock, patch
from gatelock._outputs import (
OutputRect,
RandrBackend,
)
# Bound at import, so the autouse hermetic patch (which replaces these
# attributes) does not hide the real implementations from their own tests.
REAL_CREATE = RandrBackend.create.__func__
XRANDR_REAL = """\
Screen 0: minimum 8 x 8, current 6400 x 2160, maximum 32767 x 32767
HDMI-0 connected 2560x1440+3840+0 (normal left inverted right x axis) 597mm x 336mm
2560x1440 59.95*+ 143.98 120.00
1920x1080 60.00 59.94
DP-0 connected primary 3840x2160+0+0 (normal left inverted right x axis) 621mm x 341mm
3840x2160 60.00*+ 144.00
DP-1 disconnected (normal left inverted right x axis y axis)
"""
XRANDR_INCIDENT = """\
Screen 0: minimum 8 x 8, current 6400 x 1440, maximum 32767 x 32767
HDMI-0 connected 2560x1440+3840+0 (normal left inverted right x axis) 600mm x 330mm
2560x1440 59.95*+
DP-0 connected primary (normal left inverted right x axis y axis) 621mm x 341mm
3840x2160 60.00 +
"""
XRANDR_ALL_DARK = """\
HDMI-0 connected (normal left inverted right x axis)
DP-0 connected primary (normal left inverted right x axis y axis)
"""
XRANDR_ROTATED = "DP-0 connected primary 1080x1920+0+0 left (normal left inverted)\n"
XRANDR_NEGATIVE = "DP-0 connected 1920x1080+-1920+0 (normal left inverted)\n"
XRANDR_ZERO_SIZE = "DP-0 connected 0x0+0+0 (normal left inverted)\n"
XRANDR_MODE_LINES_ONLY = " 2560x1440 59.95*+ 143.98\n 1920x1080 60.00\n"
XRANDR_GARBAGE = "segfault\n"
def _reply(**fields: object) -> MagicMock:
"""An Xlib reply exposing its fields as attributes, as python-xlib does."""
reply = MagicMock()
for key, value in fields.items():
setattr(reply, key, value)
return reply
def _randr_display(*, outputs: dict[int, dict[str, object]]) -> MagicMock:
"""Build a fake Xlib display exposing ``outputs``."""
display = MagicMock()
root = MagicMock()
root.xrandr_get_screen_resources.return_value = _reply(
config_timestamp=1, outputs=list(outputs)
)
root.xrandr_get_output_primary.return_value = _reply(output=1)
display.screen.return_value.root = root
def output_info(output_id: int, _ts: int) -> MagicMock:
return _reply(**outputs[output_id]["info"])
def crtc_info(crtc: int, _ts: int) -> MagicMock:
return _reply(**outputs[crtc]["crtc"])
display.xrandr_get_output_info.side_effect = output_info
display.xrandr_get_crtc_info.side_effect = crtc_info
return display
class TestRandrBackend:
"""Tests for the RandR backend."""
def test_scan_maps_crtc_to_rect(self) -> None:
"""A connected output with a CRTC and mode becomes a live rect."""
display = _randr_display(
outputs={
1: {
"info": {"name": "DP-0", "connection": 0, "crtc": 1},
"crtc": {"mode": 55, "x": 0, "y": 0, "width": 3840, "height": 2160},
}
}
)
(output,) = RandrBackend(display).scan() or ()
assert output.name == "DP-0"
assert output.live is True
assert output.primary is True
assert output.rect == OutputRect(0, 0, 3840, 2160)
def test_no_crtc_is_not_live(self) -> None:
"""crtc == 0 is the dark-monitor case."""
display = _randr_display(
outputs={1: {"info": {"name": "DP-0", "connection": 0, "crtc": 0}}}
)
(output,) = RandrBackend(display).scan() or ()
assert output.connected is True
assert output.rect is None
def test_crtc_without_mode_is_not_live(self) -> None:
"""A CRTC exists but carries no mode: still dark."""
display = _randr_display(
outputs={
1: {
"info": {"name": "DP-0", "connection": 0, "crtc": 1},
"crtc": {"mode": 0, "x": 0, "y": 0, "width": 0, "height": 0},
}
}
)
(output,) = RandrBackend(display).scan() or ()
assert output.rect is None
def test_zero_size_crtc_is_not_live(self) -> None:
"""A mode with no pixels is not a screen."""
display = _randr_display(
outputs={
1: {
"info": {"name": "DP-0", "connection": 0, "crtc": 1},
"crtc": {"mode": 55, "x": 0, "y": 0, "width": 0, "height": 1080},
}
}
)
(output,) = RandrBackend(display).scan() or ()
assert output.rect is None
def test_disconnected(self) -> None:
"""connection != 0 means disconnected."""
display = _randr_display(
outputs={1: {"info": {"name": "DP-1", "connection": 1, "crtc": 0}}}
)
(output,) = RandrBackend(display).scan() or ()
assert output.connected is False
def test_scan_failure_returns_none(self) -> None:
"""A protocol error degrades to None instead of raising."""
display = MagicMock()
display.screen.side_effect = OSError("connection reset")
assert RandrBackend(display).scan() is None
def test_primary_query_failure_is_tolerated(self) -> None:
"""RandR refusing to name a primary is not fatal."""
display = _randr_display(
outputs={1: {"info": {"name": "DP-0", "connection": 0, "crtc": 0}}}
)
root = display.screen.return_value.root
root.xrandr_get_output_primary.side_effect = OSError("nope")
(output,) = RandrBackend(display).scan() or ()
assert output.primary is False
def test_close_swallows_errors(self) -> None:
"""Teardown never raises."""
display = MagicMock()
display.close.side_effect = OSError("already gone")
RandrBackend(display).close()
def test_close_normal(self) -> None:
"""A clean close closes the display."""
display = MagicMock()
RandrBackend(display).close()
display.close.assert_called_once_with()
class TestCreateWithoutXlib:
"""RandrBackend.create's degradation path, exercised without the patch."""
def test_import_error_returns_none(self) -> None:
"""A missing python-xlib degrades to None, never an exception.
This is the branch the function-scope import exists to keep reachable.
"""
with patch.dict("sys.modules", {"Xlib": None}):
assert REAL_CREATE(RandrBackend) is None
def test_display_error_returns_none(self) -> None:
"""A display that refuses to open returns None."""
fake_display = MagicMock()
fake_display.Display.side_effect = OSError("cannot connect")
# `from Xlib import display` reads the attribute off the parent
# module, so wiring sys.modules alone is not enough.
fake_xlib = MagicMock(display=fake_display)
with patch.dict(
"sys.modules",
{"Xlib": fake_xlib, "Xlib.display": fake_display},
):
assert REAL_CREATE(RandrBackend) is None
def test_success_returns_backend(self) -> None:
"""A working python-xlib yields a usable backend."""
fake_display = MagicMock()
fake_xlib = MagicMock(display=fake_display)
with patch.dict(
"sys.modules",
{"Xlib": fake_xlib, "Xlib.display": fake_display},
):
backend = REAL_CREATE(RandrBackend)
assert isinstance(backend, RandrBackend)

View File

@ -7,92 +7,18 @@ lock never weakens, and per-branch coverage.
from __future__ import annotations
import ast
import logging
from pathlib import Path
import tkinter as tk
from typing import TYPE_CHECKING
from unittest.mock import MagicMock, patch
import pytest
from gatelock.tests.conftest import ALL_DARK, BOTH, DEAD_PRIMARY, FAILED
from gatelock._outputs import Output, OutputRect, OutputScan
from gatelock._recovery import RecoveryCollaborators, RecoveryLoop
from gatelock._surfaces import SurfaceSet
from gatelock._window import LockConfig
if TYPE_CHECKING:
import pytest
DP0 = Output("DP-0", connected=True, rect=OutputRect(0, 0, 3840, 2160), primary=True)
HDMI = Output("HDMI-0", connected=True, rect=OutputRect(3840, 0, 2560, 1440))
DP0_DARK = Output("DP-0", connected=True, rect=None, primary=True)
HDMI_DARK = Output("HDMI-0", connected=True, rect=None)
BOTH = OutputScan((DP0, HDMI), "randr", ok=True)
DEAD_PRIMARY = OutputScan((DP0_DARK, HDMI), "randr", ok=True)
ALL_DARK = OutputScan((DP0_DARK, HDMI_DARK), "randr", ok=True)
FAILED = OutputScan((), "none", ok=False)
WEAKENING_CALLS = frozenset(
{"grab_release", "restore_vt_switching", "close", "destroy", "quit", "withdraw"}
)
SOURCE_ROOT = Path(__file__).resolve().parent.parent
def symbols(module: str) -> set[str]:
"""Every attribute and name referenced in a module's source."""
tree = ast.parse((SOURCE_ROOT / module).read_text(encoding="utf-8"))
return {n.attr for n in ast.walk(tree) if isinstance(n, ast.Attribute)} | {
n.id for n in ast.walk(tree) if isinstance(n, ast.Name)
}
@pytest.fixture
def loop(mock_root: MagicMock) -> tuple[RecoveryLoop, MagicMock, SurfaceSet]:
"""A recovery loop over mocked surroundings."""
config = LockConfig(mode="hard")
hooks = MagicMock()
surfaces = SurfaceSet(mock_root, config, hooks)
enumerator = MagicMock()
detector = MagicMock()
return (
RecoveryLoop(
mock_root,
RecoveryCollaborators(
config=config,
surfaces=surfaces,
enumerator=enumerator,
detector=detector,
hooks=hooks,
),
),
enumerator,
surfaces,
)
class TestStaticInvariant:
"""The separation that makes monotonicity mechanical rather than hoped-for."""
def test_recovery_contains_no_weakening_call(self) -> None:
"""_recovery.py must not be able to release, restore or destroy."""
assert symbols("_recovery.py") & WEAKENING_CALLS == set()
def test_recovery_may_still_strengthen(self) -> None:
"""The asymmetry is the point: strengthening calls ARE present."""
found = symbols("_recovery.py")
assert "disable_vt_switching" in found
assert "grab_set_global" in found
def test_surfaces_never_touches_grab_or_vt(self) -> None:
"""Window ownership and lock strength stay separate concerns."""
banned = {"grab_release", "grab_set", "grab_set_global", "restore_vt_switching"}
assert symbols("_surfaces.py") & banned == set()
def test_detect_thread_never_touches_tk(self) -> None:
"""Tk is not thread-safe; the RandR thread may only queue."""
source = (SOURCE_ROOT / "_detect.py").read_text(encoding="utf-8")
loop_body = source.split("def _loop(")[1].split("def ")[0]
assert "self._sink.put" in loop_body
for forbidden in ("geometry(", "deiconify(", "lift(", "grab_"):
assert forbidden not in loop_body
from gatelock._recovery import RecoveryLoop
from gatelock._surfaces import SurfaceSet
class TestMonotonicSequence:
@ -178,200 +104,6 @@ class TestTick:
assert recovery.ticks == 2
class TestGrabReassertion:
"""Re-taking a lost grab, never releasing one."""
def test_reasserts_when_lost(
self, loop: tuple[RecoveryLoop, MagicMock, SurfaceSet], mock_root: MagicMock
) -> None:
"""Something stole the grab; we take it back."""
recovery, enumerator, _surfaces = loop
enumerator.scan.return_value = BOTH
mock_root.grab_current.return_value = None
report = recovery.tick()
assert report.grab_reasserted is True
mock_root.grab_set_global.assert_called()
def test_noop_when_still_held(
self, loop: tuple[RecoveryLoop, MagicMock, SurfaceSet], mock_root: MagicMock
) -> None:
"""Holding the grab already means no work."""
recovery, enumerator, _surfaces = loop
enumerator.scan.return_value = BOTH
mock_root.grab_current.return_value = mock_root
assert recovery.tick().grab_reasserted is False
def test_noop_when_our_own_child_holds_the_grab(
self, loop: tuple[RecoveryLoop, MagicMock, SurfaceSet], mock_root: MagicMock
) -> None:
"""A posted menu owns the grab; we must not steal it back.
Regression: the old ``grab_current() is root`` test read a Tk menu's
own grab as "lost" and re-grabbed a second later, which made the
screen-locker sport selector unusable while locked.
"""
recovery, enumerator, _surfaces = loop
enumerator.scan.return_value = BOTH
mock_root.grab_current.return_value = MagicMock(name="posted menu")
assert recovery.tick().grab_reasserted is False
mock_root.grab_set_global.assert_not_called()
def test_reasserts_when_the_holder_is_not_one_of_our_windows(
self,
loop: tuple[RecoveryLoop, MagicMock, SurfaceSet],
mock_root: MagicMock,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Fail closed: a name we cannot resolve is not provably ours.
A ``ttk.Combobox`` popdown is a Tcl-created toplevel absent from
Tkinter's widget map, so ``nametowidget`` raises ``KeyError``. Keeping
the lock beats keeping a banned widget's popdown.
"""
recovery, enumerator, _surfaces = loop
enumerator.scan.return_value = BOTH
mock_root.grab_current.side_effect = KeyError("!popdown")
with caplog.at_level(logging.WARNING):
assert recovery.tick().grab_reasserted is True
mock_root.grab_set_global.assert_called()
assert "not one of our windows" in caplog.text
def test_a_persistent_lost_grab_warns_once_not_once_per_tick(
self,
loop: tuple[RecoveryLoop, MagicMock, SurfaceSet],
mock_root: MagicMock,
caplog: pytest.LogCaptureFixture,
) -> None:
"""A state that lasts the whole lock must not stream to the journal."""
recovery, enumerator, _surfaces = loop
enumerator.scan.return_value = BOTH
mock_root.grab_current.side_effect = tk.TclError("gone")
with caplog.at_level(logging.WARNING):
for _ in range(5):
recovery.tick()
lost = [r for r in caplog.records if "current grab" in r.message]
assert len(lost) == 1, f"warned {len(lost)} times over 5 ticks"
def test_tclerror_while_regrabbing_is_swallowed(
self, loop: tuple[RecoveryLoop, MagicMock, SurfaceSet], mock_root: MagicMock
) -> None:
"""A failed re-grab is retried next tick, not raised."""
recovery, enumerator, _surfaces = loop
enumerator.scan.return_value = BOTH
mock_root.grab_current.return_value = None
mock_root.grab_set_global.side_effect = tk.TclError("held")
assert recovery.tick().grab_reasserted is False
def test_grab_query_tclerror(
self, loop: tuple[RecoveryLoop, MagicMock, SurfaceSet], mock_root: MagicMock
) -> None:
"""A TclError querying the grab counts as not holding it."""
recovery, enumerator, _surfaces = loop
enumerator.scan.return_value = BOTH
mock_root.grab_current.side_effect = tk.TclError("gone")
assert recovery.tick().grab_reasserted is True
def test_no_reassert_when_grab_not_global(self, mock_root: MagicMock) -> None:
"""Soft mode takes no grab, so there is nothing to re-assert."""
config = LockConfig(mode="soft")
surfaces = SurfaceSet(mock_root, config, MagicMock())
enumerator = MagicMock()
enumerator.scan.return_value = BOTH
recovery = RecoveryLoop(
mock_root,
RecoveryCollaborators(
config=config,
surfaces=surfaces,
enumerator=enumerator,
detector=MagicMock(),
hooks=MagicMock(),
),
)
assert recovery.tick().grab_reasserted is False
class TestFocusReassertion:
"""Re-focusing a surface that was (re)built after the first tick.
Regression coverage for the 2026-08 bug: a monitor blip tears down and
rebuilds a surface's widgets mid-lock, but ``LockWindow`` only ever
focuses the entry once, on first grab acquisition. Without this, the new
widget renders correctly but is never the Tk focus target, and the held
global grab means nothing else can take focus either -- a silent,
permanent input dead end that looks identical to a working lock.
"""
def test_refocuses_when_a_surface_is_recreated(
self, loop: tuple[RecoveryLoop, MagicMock, SurfaceSet]
) -> None:
"""A surface coming back live re-triggers on_focus_ready."""
recovery, enumerator, surfaces = loop
hooks = surfaces._builder
enumerator.scan.return_value = BOTH
recovery.tick()
hooks.on_focus_ready.reset_mock()
enumerator.scan.return_value = DEAD_PRIMARY
recovery.tick()
enumerator.scan.return_value = BOTH
recovery.tick()
hooks.on_focus_ready.assert_called_once()
def test_no_refocus_when_nothing_was_created(
self, loop: tuple[RecoveryLoop, MagicMock, SurfaceSet]
) -> None:
"""A tick with no new surfaces must not fight the user mid-typing."""
recovery, enumerator, surfaces = loop
hooks = surfaces._builder
enumerator.scan.return_value = BOTH
recovery.tick()
hooks.on_focus_ready.reset_mock()
recovery.tick()
hooks.on_focus_ready.assert_not_called()
def test_tclerror_during_refocus_is_swallowed(
self, loop: tuple[RecoveryLoop, MagicMock, SurfaceSet], mock_root: MagicMock
) -> None:
"""A focus call on a half-torn-down widget must not crash the tick."""
recovery, enumerator, surfaces = loop
hooks = surfaces._builder
hooks.on_focus_ready.side_effect = tk.TclError("gone")
enumerator.scan.return_value = BOTH
recovery.tick()
class TestVtReassertion:
"""Periodically re-disabling VT switching, never re-enabling it."""
def test_reasserts_on_the_thirtieth_tick(
self, loop: tuple[RecoveryLoop, MagicMock, SurfaceSet]
) -> None:
"""VT is re-disabled every 30 ticks."""
recovery, enumerator, _surfaces = loop
enumerator.scan.return_value = BOTH
with patch("gatelock._recovery.disable_vt_switching") as vt:
reports = [recovery.tick() for _ in range(30)]
assert [i for i, r in enumerate(reports, 1) if r.vt_reasserted] == [30]
vt.assert_called_once_with()
def test_never_when_vt_not_managed(self, mock_root: MagicMock) -> None:
"""An app that does not disable VT never re-asserts it."""
config = LockConfig(mode="soft")
surfaces = SurfaceSet(mock_root, config, MagicMock())
enumerator = MagicMock()
enumerator.scan.return_value = BOTH
recovery = RecoveryLoop(
mock_root,
RecoveryCollaborators(
config=config,
surfaces=surfaces,
enumerator=enumerator,
detector=MagicMock(),
hooks=MagicMock(),
),
)
assert all(not recovery.tick().vt_reasserted for _ in range(31))
class TestScheduling:
"""The two cadences."""

View File

@ -0,0 +1,52 @@
"""Static checks that the recovery loop *cannot* weaken the lock.
Split from ``test_recovery.py`` (250-line cap). These read the source with
``ast`` rather than running anything: monotonicity is enforced by which calls
a module is allowed to contain at all, so the check belongs at the source
level where no amount of mocking can fake it.
"""
from __future__ import annotations
import ast
from pathlib import Path
WEAKENING_CALLS = frozenset(
{"grab_release", "restore_vt_switching", "close", "destroy", "quit", "withdraw"}
)
SOURCE_ROOT = Path(__file__).resolve().parent.parent
def symbols(module: str) -> set[str]:
"""Every attribute and name referenced in a module's source."""
tree = ast.parse((SOURCE_ROOT / module).read_text(encoding="utf-8"))
return {n.attr for n in ast.walk(tree) if isinstance(n, ast.Attribute)} | {
n.id for n in ast.walk(tree) if isinstance(n, ast.Name)
}
class TestStaticInvariant:
"""The separation that makes monotonicity mechanical rather than hoped-for."""
def test_recovery_contains_no_weakening_call(self) -> None:
"""_recovery.py must not be able to release, restore or destroy."""
assert symbols("_recovery.py") & WEAKENING_CALLS == set()
def test_recovery_may_still_strengthen(self) -> None:
"""The asymmetry is the point: strengthening calls ARE present."""
found = symbols("_recovery.py")
assert "disable_vt_switching" in found
assert "grab_set_global" in found
def test_surfaces_never_touches_grab_or_vt(self) -> None:
"""Window ownership and lock strength stay separate concerns."""
banned = {"grab_release", "grab_set", "grab_set_global", "restore_vt_switching"}
assert symbols("_surfaces.py") & banned == set()
def test_detect_thread_never_touches_tk(self) -> None:
"""Tk is not thread-safe; the RandR thread may only queue."""
source = (SOURCE_ROOT / "_detect.py").read_text(encoding="utf-8")
loop_body = source.split("def _loop(")[1].split("def ")[0]
assert "self._sink.put" in loop_body
for forbidden in ("geometry(", "deiconify(", "lift(", "grab_"):
assert forbidden not in loop_body

View File

@ -0,0 +1,196 @@
"""Tests for what the recovery loop re-asserts on each tick.
Split from ``test_recovery.py`` (250-line cap). That file keeps the static
invariant, the 2026-07-25 monotonic-sequence walk, the tick mechanics and
scheduling; this one covers the three things a tick re-asserts -- the input
grab, focus, and VT switching -- and the branches within each.
The ``loop`` fixture and the output scans both halves drive come from
``conftest.py``.
"""
from __future__ import annotations
import logging
import tkinter as tk
from typing import TYPE_CHECKING
from unittest.mock import MagicMock, patch
from gatelock._window import LockConfig
from gatelock.tests.conftest import BOTH, DEAD_PRIMARY, build_loop
if TYPE_CHECKING:
import pytest
from gatelock._recovery import RecoveryLoop
from gatelock._surfaces import SurfaceSet
class TestGrabReassertion:
"""Re-taking a lost grab, never releasing one."""
def test_reasserts_when_lost(
self, loop: tuple[RecoveryLoop, MagicMock, SurfaceSet], mock_root: MagicMock
) -> None:
"""Something stole the grab; we take it back."""
recovery, enumerator, _surfaces = loop
enumerator.scan.return_value = BOTH
mock_root.grab_current.return_value = None
report = recovery.tick()
assert report.grab_reasserted is True
mock_root.grab_set_global.assert_called()
def test_noop_when_still_held(
self, loop: tuple[RecoveryLoop, MagicMock, SurfaceSet], mock_root: MagicMock
) -> None:
"""Holding the grab already means no work."""
recovery, enumerator, _surfaces = loop
enumerator.scan.return_value = BOTH
mock_root.grab_current.return_value = mock_root
assert recovery.tick().grab_reasserted is False
def test_noop_when_our_own_child_holds_the_grab(
self, loop: tuple[RecoveryLoop, MagicMock, SurfaceSet], mock_root: MagicMock
) -> None:
"""A posted menu owns the grab; we must not steal it back.
Regression: the old ``grab_current() is root`` test read a Tk menu's
own grab as "lost" and re-grabbed a second later, which made the
screen-locker sport selector unusable while locked.
"""
recovery, enumerator, _surfaces = loop
enumerator.scan.return_value = BOTH
mock_root.grab_current.return_value = MagicMock(name="posted menu")
assert recovery.tick().grab_reasserted is False
mock_root.grab_set_global.assert_not_called()
def test_reasserts_when_the_holder_is_not_one_of_our_windows(
self,
loop: tuple[RecoveryLoop, MagicMock, SurfaceSet],
mock_root: MagicMock,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Fail closed: a name we cannot resolve is not provably ours.
A ``ttk.Combobox`` popdown is a Tcl-created toplevel absent from
Tkinter's widget map, so ``nametowidget`` raises ``KeyError``. Keeping
the lock beats keeping a banned widget's popdown.
"""
recovery, enumerator, _surfaces = loop
enumerator.scan.return_value = BOTH
mock_root.grab_current.side_effect = KeyError("!popdown")
with caplog.at_level(logging.WARNING):
assert recovery.tick().grab_reasserted is True
mock_root.grab_set_global.assert_called()
assert "not one of our windows" in caplog.text
def test_a_persistent_lost_grab_warns_once_not_once_per_tick(
self,
loop: tuple[RecoveryLoop, MagicMock, SurfaceSet],
mock_root: MagicMock,
caplog: pytest.LogCaptureFixture,
) -> None:
"""A state that lasts the whole lock must not stream to the journal."""
recovery, enumerator, _surfaces = loop
enumerator.scan.return_value = BOTH
mock_root.grab_current.side_effect = tk.TclError("gone")
with caplog.at_level(logging.WARNING):
for _ in range(5):
recovery.tick()
lost = [r for r in caplog.records if "current grab" in r.message]
assert len(lost) == 1, f"warned {len(lost)} times over 5 ticks"
def test_tclerror_while_regrabbing_is_swallowed(
self, loop: tuple[RecoveryLoop, MagicMock, SurfaceSet], mock_root: MagicMock
) -> None:
"""A failed re-grab is retried next tick, not raised."""
recovery, enumerator, _surfaces = loop
enumerator.scan.return_value = BOTH
mock_root.grab_current.return_value = None
mock_root.grab_set_global.side_effect = tk.TclError("held")
assert recovery.tick().grab_reasserted is False
def test_grab_query_tclerror(
self, loop: tuple[RecoveryLoop, MagicMock, SurfaceSet], mock_root: MagicMock
) -> None:
"""A TclError querying the grab counts as not holding it."""
recovery, enumerator, _surfaces = loop
enumerator.scan.return_value = BOTH
mock_root.grab_current.side_effect = tk.TclError("gone")
assert recovery.tick().grab_reasserted is True
def test_no_reassert_when_grab_not_global(self, mock_root: MagicMock) -> None:
"""Soft mode takes no grab, so there is nothing to re-assert."""
recovery, enumerator, _surfaces = build_loop(mock_root, LockConfig(mode="soft"))
enumerator.scan.return_value = BOTH
assert recovery.tick().grab_reasserted is False
class TestFocusReassertion:
"""Re-focusing a surface that was (re)built after the first tick.
Regression coverage for the 2026-08 bug: a monitor blip tears down and
rebuilds a surface's widgets mid-lock, but ``LockWindow`` only ever
focuses the entry once, on first grab acquisition. Without this, the new
widget renders correctly but is never the Tk focus target, and the held
global grab means nothing else can take focus either -- a silent,
permanent input dead end that looks identical to a working lock.
"""
def test_refocuses_when_a_surface_is_recreated(
self, loop: tuple[RecoveryLoop, MagicMock, SurfaceSet]
) -> None:
"""A surface coming back live re-triggers on_focus_ready."""
recovery, enumerator, surfaces = loop
hooks = surfaces._builder
enumerator.scan.return_value = BOTH
recovery.tick()
hooks.on_focus_ready.reset_mock()
enumerator.scan.return_value = DEAD_PRIMARY
recovery.tick()
enumerator.scan.return_value = BOTH
recovery.tick()
hooks.on_focus_ready.assert_called_once()
def test_no_refocus_when_nothing_was_created(
self, loop: tuple[RecoveryLoop, MagicMock, SurfaceSet]
) -> None:
"""A tick with no new surfaces must not fight the user mid-typing."""
recovery, enumerator, surfaces = loop
hooks = surfaces._builder
enumerator.scan.return_value = BOTH
recovery.tick()
hooks.on_focus_ready.reset_mock()
recovery.tick()
hooks.on_focus_ready.assert_not_called()
def test_tclerror_during_refocus_is_swallowed(
self, loop: tuple[RecoveryLoop, MagicMock, SurfaceSet], mock_root: MagicMock
) -> None:
"""A focus call on a half-torn-down widget must not crash the tick."""
recovery, enumerator, surfaces = loop
hooks = surfaces._builder
hooks.on_focus_ready.side_effect = tk.TclError("gone")
enumerator.scan.return_value = BOTH
recovery.tick()
class TestVtReassertion:
"""Periodically re-disabling VT switching, never re-enabling it."""
def test_reasserts_on_the_thirtieth_tick(
self, loop: tuple[RecoveryLoop, MagicMock, SurfaceSet]
) -> None:
"""VT is re-disabled every 30 ticks."""
recovery, enumerator, _surfaces = loop
enumerator.scan.return_value = BOTH
with patch("gatelock._recovery.disable_vt_switching") as vt:
reports = [recovery.tick() for _ in range(30)]
assert [i for i, r in enumerate(reports, 1) if r.vt_reasserted] == [30]
vt.assert_called_once_with()
def test_never_when_vt_not_managed(self, mock_root: MagicMock) -> None:
"""An app that does not disable VT never re-asserts it."""
recovery, enumerator, _surfaces = build_loop(mock_root, LockConfig(mode="soft"))
enumerator.scan.return_value = BOTH
assert all(not recovery.tick().vt_reasserted for _ in range(31))

View File

@ -20,8 +20,6 @@ import tkinter as tk
import pytest
from gatelock._scrollable import ScrollableSurface
from gatelock._scrollkeys import bind_scroll_keys
from gatelock._userintent import viewport_targets
from gatelock._window import LockConfig
pytestmark = pytest.mark.skipif(
@ -231,144 +229,3 @@ def test_a_surface_without_a_scrollbar_still_scrolls() -> None:
assert made.canvas.yview()[0] > 0.0
finally:
root.destroy()
def test_scroll_into_view_ignores_an_unmapped_widget(
surface: ScrollableSurface,
) -> None:
"""A widget Tk has not laid out yet has no position to scroll to."""
ghost = tk.Entry(surface.content) # never packed: zero height
before = _offset(surface)
surface.scroll_into_view(ghost)
assert _offset(surface) == before
def test_scroll_into_view_leaves_an_already_visible_widget_alone(
surface: ScrollableSurface,
) -> None:
"""Nothing moves when the widget is already fully on screen."""
before = _offset(surface)
surface.scroll_into_view(surface.content.winfo_children()[0])
assert _offset(surface) == before
def test_scroll_into_view_reaches_backwards(surface: ScrollableSurface) -> None:
"""Revealing a widget above the viewport scrolls up, not down."""
surface.canvas.yview_moveto(1.0)
surface.canvas.update()
surface.scroll_into_view(surface.content.winfo_children()[0])
assert _offset(surface) == 0.0
def test_paging_degrades_to_the_canvas_without_a_toplevel(
surface: ScrollableSurface, caplog: pytest.LogCaptureFixture
) -> None:
"""A widget tree with no real toplevel still scrolls by keyboard.
Reachable under a mocked Tk root. Binding nothing at all would leave the
overflow unreachable, so it degrades to canvas-local bindings and says so
-- a silent degradation here is content the user cannot get to.
"""
message = "no toplevel"
def _no_toplevel() -> None:
raise tk.TclError(message)
surface.canvas.winfo_toplevel = _no_toplevel
with caplog.at_level("WARNING"):
bind_scroll_keys(surface.canvas, surface.content)
surface._intent.bind(viewport_targets(surface.canvas, surface.content))
assert "paging keys bound to the canvas only" in caplog.text
assert "user-input tracking is bound to the viewport only" in caplog.text
surface.canvas.focus_set()
surface.canvas.event_generate("<Next>", when="now")
surface.canvas.update()
assert _offset(surface) > 0.0
def test_a_second_finalize_does_not_stack_handlers(
surface: ScrollableSurface,
) -> None:
"""finalize() is documented idempotent, and a repaint calls it again.
An earlier version re-bound <FocusIn> on every call, so handlers piled up
one per repaint across the ~19 repaint sites of a single lock session.
"""
bound_once = set(surface._focus_bound)
surface.finalize()
assert set(surface._focus_bound) == bound_once
def test_scroll_into_view_does_nothing_when_everything_fits() -> None:
"""Nothing to reveal on a screen that is fully visible already."""
root = tk.Tk()
try:
root.geometry(f"400x{_VIEWPORT_H}+0+0")
root.focus_force()
root.update_idletasks()
made = ScrollableSurface(root, LockConfig())
made.container.place(relx=0, rely=0, relwidth=1, relheight=1)
entry = tk.Entry(made.content)
entry.pack()
made.finalize()
root.update()
made.scroll_into_view(entry)
assert made.canvas.yview() == (0.0, 1.0)
finally:
root.destroy()
def test_scroll_into_view_holds_still_for_a_widget_in_the_middle(
surface: ScrollableSurface,
) -> None:
"""A widget already fully on screen is not dragged to an edge.
The margin logic has three outcomes -- scroll up, scroll down, hold -- and
"hold" is the one a viewport that jitters would get wrong.
"""
middle = surface.content.winfo_children()[3]
before = _offset(surface)
surface.scroll_into_view(middle)
assert _offset(surface) == before
def test_the_wheel_scrolls_from_over_the_content(surface: ScrollableSurface) -> None:
"""Wheel-over-text scrolls, which is the only way anyone uses a mouse here.
Tk dispatches through *bindtags*, not the parent chain: a child's tags are
``(itself, its class, the toplevel, "all")``, so a binding on ``content``
is never consulted for an event over a Label sitting on top of it. Content
that fills the viewport covers that frame entirely, so binding the wheel
only on the canvas and the content frame makes wheel scrolling dead
everywhere the user would actually point.
"""
child = surface.content.winfo_children()[10]
before = surface.canvas.yview()[0]
child.event_generate("<Button-5>")
surface.canvas.update()
assert surface.canvas.yview()[0] > before
def test_the_wheel_scrolls_back_up_from_over_the_content(
surface: ScrollableSurface,
) -> None:
"""The up notch is bound on descendants too, not just the down one."""
child = surface.content.winfo_children()[10]
child.event_generate("<Button-5>")
surface.canvas.update()
scrolled = surface.canvas.yview()[0]
child.event_generate("<Button-4>")
surface.canvas.update()
assert surface.canvas.yview()[0] < scrolled

View File

@ -0,0 +1,197 @@
"""Tests for scrolling a specific widget into view.
Split from ``test_scrollable.py`` (250-line cap), which keeps the fit states
and the scroll gestures themselves. These cover ``scroll_into_view`` and the
focus-following that calls it.
"""
from __future__ import annotations
import os
import tkinter as tk
import pytest
from gatelock._scrollable import ScrollableSurface
from gatelock._scrollkeys import bind_scroll_keys
from gatelock._userintent import viewport_targets
from gatelock._window import LockConfig
pytestmark = pytest.mark.skipif(
not os.environ.get("DISPLAY"),
reason="needs a real X display; run under xvfb-run in a headless checkout",
)
_VIEWPORT_H = 200
_TALL = 60
@pytest.fixture
def surface() -> tk.Misc:
"""A 400x200 viewport holding 20 stacked entries -- deliberately taller."""
root = tk.Tk()
# A managed window has its geometry rewritten wholesale by a real window
# manager (i3 confirmed: a plain geometry() request came back tiled to
# the pane size instead of 400x200, so nothing ever overflowed and every
# scroll assertion in this file failed against a real WM session) --
# exactly the reason production lock windows are overrideredirect too.
root.overrideredirect(boolean=True)
root.geometry(f"400x{_VIEWPORT_H}+0+0")
# No window manager under Xvfb, so the toplevel must claim X input focus
# before any synthetic key event is delivered anywhere.
root.focus_force()
root.update_idletasks()
made = ScrollableSurface(root, LockConfig())
made.container.place(relx=0, rely=0, relwidth=1, relheight=1)
for index in range(_TALL):
tk.Entry(made.content, name=f"field{index}").pack()
made.finalize()
root.update()
yield made
root.destroy()
def _offset(made: ScrollableSurface) -> float:
"""The viewport's current scroll fraction."""
return made.canvas.yview()[0]
def test_scroll_into_view_ignores_an_unmapped_widget(
surface: ScrollableSurface,
) -> None:
"""A widget Tk has not laid out yet has no position to scroll to."""
ghost = tk.Entry(surface.content) # never packed: zero height
before = _offset(surface)
surface.scroll_into_view(ghost)
assert _offset(surface) == before
def test_scroll_into_view_leaves_an_already_visible_widget_alone(
surface: ScrollableSurface,
) -> None:
"""Nothing moves when the widget is already fully on screen."""
before = _offset(surface)
surface.scroll_into_view(surface.content.winfo_children()[0])
assert _offset(surface) == before
def test_scroll_into_view_reaches_backwards(surface: ScrollableSurface) -> None:
"""Revealing a widget above the viewport scrolls up, not down."""
surface.canvas.yview_moveto(1.0)
surface.canvas.update()
surface.scroll_into_view(surface.content.winfo_children()[0])
assert _offset(surface) == 0.0
def test_paging_degrades_to_the_canvas_without_a_toplevel(
surface: ScrollableSurface, caplog: pytest.LogCaptureFixture
) -> None:
"""A widget tree with no real toplevel still scrolls by keyboard.
Reachable under a mocked Tk root. Binding nothing at all would leave the
overflow unreachable, so it degrades to canvas-local bindings and says so
-- a silent degradation here is content the user cannot get to.
"""
message = "no toplevel"
def _no_toplevel() -> None:
raise tk.TclError(message)
surface.canvas.winfo_toplevel = _no_toplevel
with caplog.at_level("WARNING"):
bind_scroll_keys(surface.canvas, surface.content)
surface._intent.bind(viewport_targets(surface.canvas, surface.content))
assert "paging keys bound to the canvas only" in caplog.text
assert "user-input tracking is bound to the viewport only" in caplog.text
surface.canvas.focus_set()
surface.canvas.event_generate("<Next>", when="now")
surface.canvas.update()
assert _offset(surface) > 0.0
def test_a_second_finalize_does_not_stack_handlers(
surface: ScrollableSurface,
) -> None:
"""finalize() is documented idempotent, and a repaint calls it again.
An earlier version re-bound <FocusIn> on every call, so handlers piled up
one per repaint across the ~19 repaint sites of a single lock session.
"""
bound_once = set(surface._focus_bound)
surface.finalize()
assert set(surface._focus_bound) == bound_once
def test_scroll_into_view_does_nothing_when_everything_fits() -> None:
"""Nothing to reveal on a screen that is fully visible already."""
root = tk.Tk()
try:
root.geometry(f"400x{_VIEWPORT_H}+0+0")
root.focus_force()
root.update_idletasks()
made = ScrollableSurface(root, LockConfig())
made.container.place(relx=0, rely=0, relwidth=1, relheight=1)
entry = tk.Entry(made.content)
entry.pack()
made.finalize()
root.update()
made.scroll_into_view(entry)
assert made.canvas.yview() == (0.0, 1.0)
finally:
root.destroy()
def test_scroll_into_view_holds_still_for_a_widget_in_the_middle(
surface: ScrollableSurface,
) -> None:
"""A widget already fully on screen is not dragged to an edge.
The margin logic has three outcomes -- scroll up, scroll down, hold -- and
"hold" is the one a viewport that jitters would get wrong.
"""
middle = surface.content.winfo_children()[3]
before = _offset(surface)
surface.scroll_into_view(middle)
assert _offset(surface) == before
def test_the_wheel_scrolls_from_over_the_content(surface: ScrollableSurface) -> None:
"""Wheel-over-text scrolls, which is the only way anyone uses a mouse here.
Tk dispatches through *bindtags*, not the parent chain: a child's tags are
``(itself, its class, the toplevel, "all")``, so a binding on ``content``
is never consulted for an event over a Label sitting on top of it. Content
that fills the viewport covers that frame entirely, so binding the wheel
only on the canvas and the content frame makes wheel scrolling dead
everywhere the user would actually point.
"""
child = surface.content.winfo_children()[10]
before = surface.canvas.yview()[0]
child.event_generate("<Button-5>")
surface.canvas.update()
assert surface.canvas.yview()[0] > before
def test_the_wheel_scrolls_back_up_from_over_the_content(
surface: ScrollableSurface,
) -> None:
"""The up notch is bound on descendants too, not just the down one."""
child = surface.content.winfo_children()[10]
child.event_generate("<Button-5>")
surface.canvas.update()
scrolled = surface.canvas.yview()[0]
child.event_generate("<Button-4>")
surface.canvas.update()
assert surface.canvas.yview()[0] < scrolled

View File

@ -8,10 +8,7 @@ import pytest
from gatelock._outputs import Output, OutputRect, OutputScan
from gatelock._surfaces import (
SurfaceInfo,
SurfaceSet,
TextMirror,
mirror_text_widgets,
needs_backdrop_root,
)
from gatelock._window import LockConfig
@ -165,118 +162,3 @@ class TestEnforce:
surfaces.raise_all()
for surface in surfaces._surfaces.values():
surface.window.lift.assert_called()
class TestFocus:
"""Which surface takes the keyboard."""
def test_focus_surface_by_index(self, surfaces: SurfaceSet) -> None:
"""Focusing an index returns that surface's info."""
surfaces.apply(scan(DP0, HDMI))
info = surfaces.focus_surface(1)
assert info is not None
assert info.output_name == "HDMI-0"
def test_focus_unknown_index(self, surfaces: SurfaceSet) -> None:
"""An index with no surface returns None."""
surfaces.apply(scan(DP0))
assert surfaces.focus_surface(9) is None
def test_preferred_index_is_the_primary(self, surfaces: SurfaceSet) -> None:
"""The live primary output takes initial focus."""
surfaces.apply(scan(HDMI, DP0))
assert surfaces.preferred_focus_index() == 1
def test_preferred_index_defaults_to_first(self, surfaces: SurfaceSet) -> None:
"""With no primary marked, the first surface wins."""
surfaces.apply(scan(HDMI))
assert surfaces.preferred_focus_index() == 0
class TestBackdropAndTeardown:
"""The root backdrop and full teardown."""
def test_backdrop_covers_the_whole_screen(
self, surfaces: SurfaceSet, mock_root: MagicMock
) -> None:
"""The backdrop spans the X screen, covering dead columns."""
surfaces.update_backdrop()
mock_root.geometry.assert_called_once_with("1920x1080+0+0")
def test_soft_mode_has_no_backdrop(self, mock_root: MagicMock) -> None:
"""Without a grab or overrideredirect there is nothing to back."""
SurfaceSet(mock_root, LockConfig(mode="soft"), MagicMock()).update_backdrop()
mock_root.geometry.assert_not_called()
def test_destroy_all(self, surfaces: SurfaceSet) -> None:
"""Closing tears down every surface."""
surfaces.apply(scan(DP0, HDMI))
surfaces.destroy_all()
assert surfaces.names() == frozenset()
class TestTextMirror:
"""tk.Text has no textvariable, so it needs explicit mirroring."""
def _widget(self, text: str = "") -> MagicMock:
widget = MagicMock()
state = {"text": text}
widget.get.side_effect = lambda *_a: state["text"]
widget.delete.side_effect = lambda *_a: state.update(text="")
widget.insert.side_effect = lambda _i, value: state.update(text=value)
widget._state = state
return widget
def test_typing_in_one_updates_the_other(self) -> None:
"""A key release in surface A reaches surface B."""
a, b = self._widget("hello"), self._widget()
var = MagicMock()
var.get.return_value = "hello"
mirror = TextMirror([a, b], var)
event = MagicMock()
event.widget = a
mirror._on_key_release(event)
var.set.assert_called_once_with("hello")
assert b._state["text"] == "hello"
def test_var_write_fans_out(self) -> None:
"""Setting the shared variable updates every widget."""
a, b = self._widget(), self._widget()
var = MagicMock()
var.get.return_value = "typed"
mirror = TextMirror([a, b], var)
mirror._on_var_write("x", "", "w")
assert a._state["text"] == "typed"
assert b._state["text"] == "typed"
def test_reentrancy_is_blocked(self) -> None:
"""A fan-out must not trigger another fan-out."""
a = self._widget()
var = MagicMock()
var.get.return_value = "v"
mirror = TextMirror([a], var)
mirror._syncing = True
mirror._on_var_write("x", "", "w")
assert a._state["text"] == ""
event = MagicMock()
event.widget = a
mirror._on_key_release(event)
var.set.assert_not_called()
def test_helper_returns_mirror(self) -> None:
"""The public helper wires the widgets up."""
widget = self._widget()
var = MagicMock()
assert isinstance(mirror_text_widgets([widget], var), TextMirror)
widget.bind.assert_called_once()
class TestSurfaceInfo:
"""SurfaceInfo equality drives the move-vs-noop decision."""
def test_identical_infos_compare_equal(self) -> None:
"""Equality is by value, so an unchanged layout is a no-op."""
rect = OutputRect(0, 0, 100, 100)
first = SurfaceInfo("DP-0", rect, 0, is_primary=True)
second = SurfaceInfo("DP-0", rect, 0, is_primary=True)
assert first == second

View File

@ -0,0 +1,153 @@
"""Tests for focus handling, the backdrop, teardown and the text mirror.
Split from ``test_surfaces.py`` to hold the shared 250-line cap.
"""
from __future__ import annotations
from unittest.mock import MagicMock
import pytest
from gatelock._outputs import Output, OutputRect, OutputScan
from gatelock._surfaces import (
SurfaceInfo,
SurfaceSet,
TextMirror,
mirror_text_widgets,
)
from gatelock._window import LockConfig
DP0 = Output("DP-0", connected=True, rect=OutputRect(0, 0, 3840, 2160), primary=True)
HDMI = Output("HDMI-0", connected=True, rect=OutputRect(3840, 0, 2560, 1440))
DP0_DARK = Output("DP-0", connected=True, rect=None, primary=True)
DP0_MOVED = Output(
"DP-0", connected=True, rect=OutputRect(0, 0, 1920, 1080), primary=True
)
def scan(*outputs: Output) -> OutputScan:
"""Build a successful scan over ``outputs``."""
return OutputScan(outputs=outputs, source="randr", ok=True)
@pytest.fixture
def surfaces(mock_root: MagicMock) -> SurfaceSet:
"""A hard-mode surface set over a mock root."""
return SurfaceSet(mock_root, LockConfig(mode="hard"), MagicMock())
class TestFocus:
"""Which surface takes the keyboard."""
def test_focus_surface_by_index(self, surfaces: SurfaceSet) -> None:
"""Focusing an index returns that surface's info."""
surfaces.apply(scan(DP0, HDMI))
info = surfaces.focus_surface(1)
assert info is not None
assert info.output_name == "HDMI-0"
def test_focus_unknown_index(self, surfaces: SurfaceSet) -> None:
"""An index with no surface returns None."""
surfaces.apply(scan(DP0))
assert surfaces.focus_surface(9) is None
def test_preferred_index_is_the_primary(self, surfaces: SurfaceSet) -> None:
"""The live primary output takes initial focus."""
surfaces.apply(scan(HDMI, DP0))
assert surfaces.preferred_focus_index() == 1
def test_preferred_index_defaults_to_first(self, surfaces: SurfaceSet) -> None:
"""With no primary marked, the first surface wins."""
surfaces.apply(scan(HDMI))
assert surfaces.preferred_focus_index() == 0
class TestBackdropAndTeardown:
"""The root backdrop and full teardown."""
def test_backdrop_covers_the_whole_screen(
self, surfaces: SurfaceSet, mock_root: MagicMock
) -> None:
"""The backdrop spans the X screen, covering dead columns."""
surfaces.update_backdrop()
mock_root.geometry.assert_called_once_with("1920x1080+0+0")
def test_soft_mode_has_no_backdrop(self, mock_root: MagicMock) -> None:
"""Without a grab or overrideredirect there is nothing to back."""
SurfaceSet(mock_root, LockConfig(mode="soft"), MagicMock()).update_backdrop()
mock_root.geometry.assert_not_called()
def test_destroy_all(self, surfaces: SurfaceSet) -> None:
"""Closing tears down every surface."""
surfaces.apply(scan(DP0, HDMI))
surfaces.destroy_all()
assert surfaces.names() == frozenset()
class TestTextMirror:
"""tk.Text has no textvariable, so it needs explicit mirroring."""
def _widget(self, text: str = "") -> MagicMock:
widget = MagicMock()
state = {"text": text}
widget.get.side_effect = lambda *_a: state["text"]
widget.delete.side_effect = lambda *_a: state.update(text="")
widget.insert.side_effect = lambda _i, value: state.update(text=value)
widget._state = state
return widget
def test_typing_in_one_updates_the_other(self) -> None:
"""A key release in surface A reaches surface B."""
a, b = self._widget("hello"), self._widget()
var = MagicMock()
var.get.return_value = "hello"
mirror = TextMirror([a, b], var)
event = MagicMock()
event.widget = a
mirror._on_key_release(event)
var.set.assert_called_once_with("hello")
assert b._state["text"] == "hello"
def test_var_write_fans_out(self) -> None:
"""Setting the shared variable updates every widget."""
a, b = self._widget(), self._widget()
var = MagicMock()
var.get.return_value = "typed"
mirror = TextMirror([a, b], var)
mirror._on_var_write("x", "", "w")
assert a._state["text"] == "typed"
assert b._state["text"] == "typed"
def test_reentrancy_is_blocked(self) -> None:
"""A fan-out must not trigger another fan-out."""
a = self._widget()
var = MagicMock()
var.get.return_value = "v"
mirror = TextMirror([a], var)
mirror._syncing = True
mirror._on_var_write("x", "", "w")
assert a._state["text"] == ""
event = MagicMock()
event.widget = a
mirror._on_key_release(event)
var.set.assert_not_called()
def test_helper_returns_mirror(self) -> None:
"""The public helper wires the widgets up."""
widget = self._widget()
var = MagicMock()
assert isinstance(mirror_text_widgets([widget], var), TextMirror)
widget.bind.assert_called_once()
class TestSurfaceInfo:
"""SurfaceInfo equality drives the move-vs-noop decision."""
def test_identical_infos_compare_equal(self) -> None:
"""Equality is by value, so an unchanged layout is a no-op."""
rect = OutputRect(0, 0, 100, 100)
first = SurfaceInfo("DP-0", rect, 0, is_primary=True)
second = SurfaceInfo("DP-0", rect, 0, is_primary=True)
assert first == second

View File

@ -141,129 +141,3 @@ class TestGrabInput:
mock_root.grab_set.assert_not_called()
mock_root.grab_set_global.assert_not_called()
class TestAcquireGlobalGrab:
"""Tests for LockWindow._acquire_global_grab."""
def test_success_focuses_and_notifies(self, mock_root: MagicMock) -> None:
"""A successful grab forces focus and notifies the hook."""
window, hooks = make_window(mock_root, config=LockConfig(mode="hard"))
window._acquire_global_grab(attempt=1)
mock_root.grab_set_global.assert_called_once_with()
mock_root.focus_force.assert_called_once_with()
hooks.on_focus_ready.assert_called_once_with(None)
def test_success_swallows_tclerror_from_focus(self, mock_root: MagicMock) -> None:
"""A TclError while focusing after a successful grab is swallowed."""
mock_root.focus_force.side_effect = tk.TclError("gone")
window, hooks = make_window(mock_root, config=LockConfig(mode="hard"))
window._acquire_global_grab(attempt=1) # must not raise
hooks.on_focus_ready.assert_not_called()
def test_failure_with_retry_zero_falls_back_to_local(
self, mock_root: MagicMock
) -> None:
"""grab_retry_ms=0 falls back to a local grab on the first failure."""
mock_root.grab_set_global.side_effect = tk.TclError("held by another client")
window, _hooks = make_window(
mock_root, config=LockConfig(mode="hard", grab_retry_ms=0)
)
window._acquire_global_grab(attempt=1)
mock_root.grab_set.assert_called_once_with()
mock_root.after.assert_not_called()
def test_failure_with_retry_zero_swallows_local_grab_tclerror(
self, mock_root: MagicMock
) -> None:
"""The local-grab fallback itself swallows a TclError too."""
mock_root.grab_set_global.side_effect = tk.TclError("held")
mock_root.grab_set.side_effect = tk.TclError("also gone")
window, _hooks = make_window(
mock_root, config=LockConfig(mode="hard", grab_retry_ms=0)
)
window._acquire_global_grab(attempt=1) # must not raise
def test_failure_with_default_retry_schedules_retry(
self, mock_root: MagicMock
) -> None:
"""Default (None) retry interval reschedules every 200ms, logging every 25th."""
mock_root.grab_set_global.side_effect = tk.TclError("held")
window, _hooks = make_window(mock_root, config=LockConfig(mode="hard"))
window._acquire_global_grab(attempt=24)
assert mock_root.after.call_count == 1
scheduled_delay = mock_root.after.call_args[0][0]
assert scheduled_delay == 200
def test_failure_logs_every_grab_log_every_attempts(
self, mock_root: MagicMock
) -> None:
"""A warning is logged only when attempt is a multiple of grab_log_every."""
mock_root.grab_set_global.side_effect = tk.TclError("held")
window, _hooks = make_window(
mock_root, config=LockConfig(mode="hard", grab_log_every=5)
)
with patch("gatelock._preempt._logger") as mock_logger:
window._acquire_global_grab(attempt=5)
mock_logger.warning.assert_called_once()
with patch("gatelock._preempt._logger") as mock_logger:
window._acquire_global_grab(attempt=3)
mock_logger.warning.assert_not_called()
def test_failure_with_custom_retry_ms_uses_it(self, mock_root: MagicMock) -> None:
"""An explicit positive grab_retry_ms is used as the reschedule delay."""
mock_root.grab_set_global.side_effect = tk.TclError("held")
window, _hooks = make_window(
mock_root, config=LockConfig(mode="hard", grab_retry_ms=50)
)
window._acquire_global_grab(attempt=1)
scheduled_delay = mock_root.after.call_args[0][0]
assert scheduled_delay == 50
def test_rescheduled_callback_increments_attempt(
self, mock_root: MagicMock
) -> None:
"""The rescheduled callback re-invokes with attempt + 1."""
mock_root.grab_set_global.side_effect = tk.TclError("held")
window, _hooks = make_window(mock_root, config=LockConfig(mode="hard"))
window._acquire_global_grab(attempt=1)
scheduled_callback = mock_root.after.call_args[0][1]
with patch("gatelock._arming.acquire_global_grab") as mock_acquire:
scheduled_callback()
mock_acquire.assert_called_once_with(window.root, window._arming, attempt=2)
class TestNotifyFocusReady:
"""Tests for LockWindow._notify_focus_ready."""
def test_calls_hook(self, mock_root: MagicMock) -> None:
"""The on_focus_ready hook is invoked."""
window, hooks = make_window(mock_root)
window._notify_focus_ready()
hooks.on_focus_ready.assert_called_once_with(None)
def test_swallows_tclerror_from_hook(self, mock_root: MagicMock) -> None:
"""A TclError raised by the hook (widget already destroyed) is swallowed."""
hooks = MagicMock()
hooks.on_focus_ready.side_effect = tk.TclError("destroyed")
window, _hooks = make_window(mock_root, hooks=hooks)
window._notify_focus_ready() # must not raise

View File

@ -0,0 +1,139 @@
"""Tests for acquiring the global input grab and its retry loop.
Split from ``test_window.py`` to hold the shared 250-line cap.
"""
from __future__ import annotations
import tkinter as tk
from unittest.mock import MagicMock, patch
from gatelock._window import LockConfig
from gatelock.tests.conftest import make_window
class TestAcquireGlobalGrab:
"""Tests for LockWindow._acquire_global_grab."""
def test_success_focuses_and_notifies(self, mock_root: MagicMock) -> None:
"""A successful grab forces focus and notifies the hook."""
window, hooks = make_window(mock_root, config=LockConfig(mode="hard"))
window._acquire_global_grab(attempt=1)
mock_root.grab_set_global.assert_called_once_with()
mock_root.focus_force.assert_called_once_with()
hooks.on_focus_ready.assert_called_once_with(None)
def test_success_swallows_tclerror_from_focus(self, mock_root: MagicMock) -> None:
"""A TclError while focusing after a successful grab is swallowed."""
mock_root.focus_force.side_effect = tk.TclError("gone")
window, hooks = make_window(mock_root, config=LockConfig(mode="hard"))
window._acquire_global_grab(attempt=1) # must not raise
hooks.on_focus_ready.assert_not_called()
def test_failure_with_retry_zero_falls_back_to_local(
self, mock_root: MagicMock
) -> None:
"""grab_retry_ms=0 falls back to a local grab on the first failure."""
mock_root.grab_set_global.side_effect = tk.TclError("held by another client")
window, _hooks = make_window(
mock_root, config=LockConfig(mode="hard", grab_retry_ms=0)
)
window._acquire_global_grab(attempt=1)
mock_root.grab_set.assert_called_once_with()
mock_root.after.assert_not_called()
def test_failure_with_retry_zero_swallows_local_grab_tclerror(
self, mock_root: MagicMock
) -> None:
"""The local-grab fallback itself swallows a TclError too."""
mock_root.grab_set_global.side_effect = tk.TclError("held")
mock_root.grab_set.side_effect = tk.TclError("also gone")
window, _hooks = make_window(
mock_root, config=LockConfig(mode="hard", grab_retry_ms=0)
)
window._acquire_global_grab(attempt=1) # must not raise
def test_failure_with_default_retry_schedules_retry(
self, mock_root: MagicMock
) -> None:
"""Default (None) retry interval reschedules every 200ms, logging every 25th."""
mock_root.grab_set_global.side_effect = tk.TclError("held")
window, _hooks = make_window(mock_root, config=LockConfig(mode="hard"))
window._acquire_global_grab(attempt=24)
assert mock_root.after.call_count == 1
scheduled_delay = mock_root.after.call_args[0][0]
assert scheduled_delay == 200
def test_failure_logs_every_grab_log_every_attempts(
self, mock_root: MagicMock
) -> None:
"""A warning is logged only when attempt is a multiple of grab_log_every."""
mock_root.grab_set_global.side_effect = tk.TclError("held")
window, _hooks = make_window(
mock_root, config=LockConfig(mode="hard", grab_log_every=5)
)
with patch("gatelock._preempt._logger") as mock_logger:
window._acquire_global_grab(attempt=5)
mock_logger.warning.assert_called_once()
with patch("gatelock._preempt._logger") as mock_logger:
window._acquire_global_grab(attempt=3)
mock_logger.warning.assert_not_called()
def test_failure_with_custom_retry_ms_uses_it(self, mock_root: MagicMock) -> None:
"""An explicit positive grab_retry_ms is used as the reschedule delay."""
mock_root.grab_set_global.side_effect = tk.TclError("held")
window, _hooks = make_window(
mock_root, config=LockConfig(mode="hard", grab_retry_ms=50)
)
window._acquire_global_grab(attempt=1)
scheduled_delay = mock_root.after.call_args[0][0]
assert scheduled_delay == 50
def test_rescheduled_callback_increments_attempt(
self, mock_root: MagicMock
) -> None:
"""The rescheduled callback re-invokes with attempt + 1."""
mock_root.grab_set_global.side_effect = tk.TclError("held")
window, _hooks = make_window(mock_root, config=LockConfig(mode="hard"))
window._acquire_global_grab(attempt=1)
scheduled_callback = mock_root.after.call_args[0][1]
with patch("gatelock._arming.acquire_global_grab") as mock_acquire:
scheduled_callback()
mock_acquire.assert_called_once_with(window.root, window._arming, attempt=2)
class TestNotifyFocusReady:
"""Tests for LockWindow._notify_focus_ready."""
def test_calls_hook(self, mock_root: MagicMock) -> None:
"""The on_focus_ready hook is invoked."""
window, hooks = make_window(mock_root)
window._notify_focus_ready()
hooks.on_focus_ready.assert_called_once_with(None)
def test_swallows_tclerror_from_hook(self, mock_root: MagicMock) -> None:
"""A TclError raised by the hook (widget already destroyed) is swallowed."""
hooks = MagicMock()
hooks.on_focus_ready.side_effect = tk.TclError("destroyed")
window, _hooks = make_window(mock_root, hooks=hooks)
window._notify_focus_ready() # must not raise

View File

@ -2,15 +2,11 @@
from __future__ import annotations
import queue
import signal
from unittest.mock import MagicMock, patch
from gatelock import _preempt
from gatelock._arbiter import (
RANK_DIET_GUARD,
RANK_SCREEN_LOCKER,
RANK_WAKE_ALARM,
Claim,
)
from gatelock._detect import _RandrEventSource
@ -112,230 +108,3 @@ class TestGrabBlockedLogging:
with patch("gatelock._preempt._logger") as logger:
window._log_grab_blocked(50)
assert "fullscreen game" in str(logger.warning.call_args)
class TestPreemptWeakerHolder:
"""A weaker incumbent must not block a stronger claim indefinitely."""
def _arbiter_with(
self, *, our_rank: int, holder_rank: int, holder_pid: int
) -> MagicMock:
arbiter = MagicMock()
arbiter.claim = Claim(
app="ours",
rank=our_rank,
pid=1,
started="2026-08-21T12:00:00+00:00",
grab="global",
disable_vt=True,
instance_id="ours",
)
arbiter.describe_holder.return_value = Claim(
app="holder",
rank=holder_rank,
pid=holder_pid,
started="2026-08-21T07:04:07+00:00",
grab="global",
disable_vt=True,
instance_id="theirs",
)
return arbiter
def test_signals_a_weaker_holder(self, mock_root: MagicMock) -> None:
arbiter = self._arbiter_with(
our_rank=RANK_SCREEN_LOCKER, holder_rank=RANK_DIET_GUARD, holder_pid=4075
)
window, _hooks = make_window(
mock_root, config=LockConfig(mode="hard", preempt_weaker_holder=True)
)
window._arbiter = arbiter
with patch("gatelock._preempt.os.kill") as kill:
window._log_grab_blocked(25)
kill.assert_called_once_with(4075, signal.SIGTERM)
def test_never_signals_a_stronger_holder(self, mock_root: MagicMock) -> None:
arbiter = self._arbiter_with(
our_rank=RANK_DIET_GUARD, holder_rank=RANK_SCREEN_LOCKER, holder_pid=4137
)
window, _hooks = make_window(
mock_root, config=LockConfig(mode="hard", preempt_weaker_holder=True)
)
window._arbiter = arbiter
with patch("gatelock._preempt.os.kill") as kill:
window._log_grab_blocked(25)
kill.assert_not_called()
def test_signals_the_same_holder_only_once(self, mock_root: MagicMock) -> None:
arbiter = self._arbiter_with(
our_rank=RANK_SCREEN_LOCKER, holder_rank=RANK_DIET_GUARD, holder_pid=4075
)
window, _hooks = make_window(
mock_root, config=LockConfig(mode="hard", preempt_weaker_holder=True)
)
window._arbiter = arbiter
with patch("gatelock._preempt.os.kill") as kill:
window._log_grab_blocked(25)
window._log_grab_blocked(50)
kill.assert_called_once_with(4075, signal.SIGTERM)
def test_disabled_by_config(self, mock_root: MagicMock) -> None:
arbiter = self._arbiter_with(
our_rank=RANK_SCREEN_LOCKER, holder_rank=RANK_DIET_GUARD, holder_pid=4075
)
window, _hooks = make_window(
mock_root, config=LockConfig(mode="hard", preempt_weaker_holder=False)
)
window._arbiter = arbiter
with patch("gatelock._preempt.os.kill") as kill:
window._log_grab_blocked(25)
kill.assert_not_called()
def test_off_by_default(self, mock_root: MagicMock) -> None:
"""Preemption is opt-in, so no app can evict anyone by accident.
wake_alarm outranks screen_locker and builds a plain hard LockConfig.
While the default was True, that combination SIGTERMed the *armed
workout lock*, unlocking enforcement with no workout logged.
"""
arbiter = self._arbiter_with(
our_rank=RANK_WAKE_ALARM,
holder_rank=RANK_SCREEN_LOCKER,
holder_pid=4137,
)
window, _hooks = make_window(mock_root, config=LockConfig(mode="hard"))
window._arbiter = arbiter
with patch("gatelock._preempt.os.kill") as kill:
window._log_grab_blocked(25)
kill.assert_not_called()
def test_no_arbiter_means_no_preemption(self, mock_root: MagicMock) -> None:
window, _hooks = make_window(
mock_root, config=LockConfig(mode="hard", preempt_weaker_holder=True)
)
with patch("gatelock._preempt.os.kill") as kill:
_preempt.maybe_preempt(
Claim(
app="holder",
rank=RANK_DIET_GUARD,
pid=4075,
started="2026-08-21T07:04:07+00:00",
grab="global",
disable_vt=True,
instance_id="theirs",
),
arbiter=None,
config=window._config,
preempted_pids=set(),
)
kill.assert_not_called()
def test_a_holder_that_is_already_gone_is_reported_at_info(
self, mock_root: MagicMock
) -> None:
arbiter = self._arbiter_with(
our_rank=RANK_SCREEN_LOCKER, holder_rank=RANK_DIET_GUARD, holder_pid=4075
)
window, _hooks = make_window(
mock_root, config=LockConfig(mode="hard", preempt_weaker_holder=True)
)
window._arbiter = arbiter
with (
patch("gatelock._preempt.os.kill", side_effect=ProcessLookupError),
patch("gatelock._preempt._logger") as logger,
):
window._log_grab_blocked(25)
assert logger.info.called
def test_an_unsignalable_holder_is_reported_not_raised(
self, mock_root: MagicMock
) -> None:
arbiter = self._arbiter_with(
our_rank=RANK_SCREEN_LOCKER, holder_rank=RANK_DIET_GUARD, holder_pid=4075
)
window, _hooks = make_window(
mock_root, config=LockConfig(mode="hard", preempt_weaker_holder=True)
)
window._arbiter = arbiter
with (
patch("gatelock._preempt.os.kill", side_effect=OSError("nope")),
patch("gatelock._preempt._logger") as logger,
):
window._log_grab_blocked(25)
assert logger.exception.called
class TestFocusNotifiedOnce:
"""Both call sites are load-bearing, so the guard is on the callee."""
def test_second_notification_is_suppressed(self, mock_root: MagicMock) -> None:
"""The hook fires once even though two timings can reach it."""
window, hooks = make_window(mock_root, config=LockConfig(mode="hard"))
window._notify_focus_ready()
window._notify_focus_ready()
hooks.on_focus_ready.assert_called_once()
class TestCloseReleasesTheScreen:
"""A clean exit must hand the screen to the next app."""
def test_arbiter_is_released(self, mock_root: MagicMock) -> None:
"""Without this the alarm -> workout handoff strands the workout lock."""
arbiter = MagicMock()
window, _hooks = make_window(mock_root, config=LockConfig(mode="hard"))
window._arbiter = arbiter
window.close()
arbiter.release.assert_called_once_with()
def test_close_without_arbiter(self, mock_root: MagicMock) -> None:
"""An unarbitrated lock still closes cleanly."""
window, hooks = make_window(mock_root, config=LockConfig(mode="hard"))
window.close()
hooks.on_close.assert_called_once_with()
class TestRemainingBranches:
"""Small paths the other suites do not reach."""
def test_claim_read_oserror(self, tmp_path: object) -> None:
"""A claim whose contents cannot be read is treated as absent."""
from gatelock._arbiter import Arbiter
arbiter = Arbiter("a", RANK_DIET_GUARD, grab="none", disable_vt=False)
arbiter.publish()
handle = MagicMock()
handle.__enter__.return_value = handle
handle.read.side_effect = OSError("io error")
with (
patch("gatelock._arbiter.Path.open", return_value=handle),
patch("gatelock._arbiter._try_lock", return_value=False),
):
assert arbiter.live_claims() == ()
arbiter.release()
def test_randr_start_spawns_thread(self) -> None:
"""A successful connect starts the watcher thread."""
source = _RandrEventSource(queue.Queue())
with (
patch.object(source, "_connect", return_value=True),
patch("gatelock._detect.threading.Thread") as thread_cls,
):
assert REAL_RANDR_START(source) is True
thread_cls.return_value.start.assert_called_once_with()
def test_randr_loop_ignores_empty_batch(self) -> None:
"""A readable socket with no events posts no notice."""
sink: queue.Queue[str] = queue.Queue()
source = _RandrEventSource(sink)
source._display = MagicMock()
source._display.pending_events.return_value = 0
calls = {"n": 0}
def is_set() -> bool:
calls["n"] += 1
return calls["n"] > 1
source._stop = MagicMock()
source._stop.is_set.side_effect = is_set
with patch("gatelock._detect.select.select", return_value=([1], [], [])):
source._loop()
assert sink.empty()

View File

@ -0,0 +1,104 @@
"""Tests for focus notification and close on a lock window.
Split from ``test_window_surfaces.py`` to hold the shared 250-line cap.
"""
from __future__ import annotations
import queue
from unittest.mock import MagicMock, patch
from gatelock._arbiter import (
RANK_DIET_GUARD,
)
from gatelock._detect import _RandrEventSource
from gatelock._outputs import Output, OutputRect
from gatelock._window import LockConfig
from gatelock.tests.conftest import make_window
# Captured before the autouse hermetic fixture replaces it.
REAL_RANDR_START = _RandrEventSource.start
DARK_ONLY = (Output("DP-0", connected=True, rect=None, primary=True),)
TWO_LIVE = (
Output("DP-0", connected=True, rect=OutputRect(0, 0, 3840, 2160), primary=True),
Output("HDMI-0", connected=True, rect=OutputRect(3840, 0, 2560, 1440)),
)
class TestFocusNotifiedOnce:
"""Both call sites are load-bearing, so the guard is on the callee."""
def test_second_notification_is_suppressed(self, mock_root: MagicMock) -> None:
"""The hook fires once even though two timings can reach it."""
window, hooks = make_window(mock_root, config=LockConfig(mode="hard"))
window._notify_focus_ready()
window._notify_focus_ready()
hooks.on_focus_ready.assert_called_once()
class TestCloseReleasesTheScreen:
"""A clean exit must hand the screen to the next app."""
def test_arbiter_is_released(self, mock_root: MagicMock) -> None:
"""Without this the alarm -> workout handoff strands the workout lock."""
arbiter = MagicMock()
window, _hooks = make_window(mock_root, config=LockConfig(mode="hard"))
window._arbiter = arbiter
window.close()
arbiter.release.assert_called_once_with()
def test_close_without_arbiter(self, mock_root: MagicMock) -> None:
"""An unarbitrated lock still closes cleanly."""
window, hooks = make_window(mock_root, config=LockConfig(mode="hard"))
window.close()
hooks.on_close.assert_called_once_with()
class TestRemainingBranches:
"""Small paths the other suites do not reach."""
def test_claim_read_oserror(self, tmp_path: object) -> None:
"""A claim whose contents cannot be read is treated as absent."""
from gatelock._arbiter import Arbiter
arbiter = Arbiter("a", RANK_DIET_GUARD, grab="none", disable_vt=False)
arbiter.publish()
handle = MagicMock()
handle.__enter__.return_value = handle
handle.read.side_effect = OSError("io error")
with (
patch("gatelock._arbiter.Path.open", return_value=handle),
patch("gatelock._arbiter._try_lock", return_value=False),
):
assert arbiter.live_claims() == ()
arbiter.release()
def test_randr_start_spawns_thread(self) -> None:
"""A successful connect starts the watcher thread."""
source = _RandrEventSource(queue.Queue())
with (
patch.object(source, "_connect", return_value=True),
patch("gatelock._detect.threading.Thread") as thread_cls,
):
assert REAL_RANDR_START(source) is True
thread_cls.return_value.start.assert_called_once_with()
def test_randr_loop_ignores_empty_batch(self) -> None:
"""A readable socket with no events posts no notice."""
sink: queue.Queue[str] = queue.Queue()
source = _RandrEventSource(sink)
source._display = MagicMock()
source._display.pending_events.return_value = 0
calls = {"n": 0}
def is_set() -> bool:
calls["n"] += 1
return calls["n"] > 1
source._stop = MagicMock()
source._stop.is_set.side_effect = is_set
with patch("gatelock._detect.select.select", return_value=([1], [], [])):
source._loop()
assert sink.empty()

View File

@ -0,0 +1,182 @@
"""Tests for standing a weaker grab holder down.
Split from ``test_window_surfaces.py`` to hold the shared 250-line cap;
that file keeps arming without a display and the grab-blocked logging.
"""
from __future__ import annotations
import signal
from unittest.mock import MagicMock, patch
from gatelock import _preempt
from gatelock._arbiter import (
RANK_DIET_GUARD,
RANK_SCREEN_LOCKER,
RANK_WAKE_ALARM,
Claim,
)
from gatelock._detect import _RandrEventSource
from gatelock._outputs import Output, OutputRect
from gatelock._window import LockConfig
from gatelock.tests.conftest import make_window
# Captured before the autouse hermetic fixture replaces it.
REAL_RANDR_START = _RandrEventSource.start
DARK_ONLY = (Output("DP-0", connected=True, rect=None, primary=True),)
TWO_LIVE = (
Output("DP-0", connected=True, rect=OutputRect(0, 0, 3840, 2160), primary=True),
Output("HDMI-0", connected=True, rect=OutputRect(3840, 0, 2560, 1440)),
)
class TestPreemptWeakerHolder:
"""A weaker incumbent must not block a stronger claim indefinitely."""
def _arbiter_with(
self, *, our_rank: int, holder_rank: int, holder_pid: int
) -> MagicMock:
arbiter = MagicMock()
arbiter.claim = Claim(
app="ours",
rank=our_rank,
pid=1,
started="2026-08-21T12:00:00+00:00",
grab="global",
disable_vt=True,
instance_id="ours",
)
arbiter.describe_holder.return_value = Claim(
app="holder",
rank=holder_rank,
pid=holder_pid,
started="2026-08-21T07:04:07+00:00",
grab="global",
disable_vt=True,
instance_id="theirs",
)
return arbiter
def test_signals_a_weaker_holder(self, mock_root: MagicMock) -> None:
arbiter = self._arbiter_with(
our_rank=RANK_SCREEN_LOCKER, holder_rank=RANK_DIET_GUARD, holder_pid=4075
)
window, _hooks = make_window(
mock_root, config=LockConfig(mode="hard", preempt_weaker_holder=True)
)
window._arbiter = arbiter
with patch("gatelock._preempt.os.kill") as kill:
window._log_grab_blocked(25)
kill.assert_called_once_with(4075, signal.SIGTERM)
def test_never_signals_a_stronger_holder(self, mock_root: MagicMock) -> None:
arbiter = self._arbiter_with(
our_rank=RANK_DIET_GUARD, holder_rank=RANK_SCREEN_LOCKER, holder_pid=4137
)
window, _hooks = make_window(
mock_root, config=LockConfig(mode="hard", preempt_weaker_holder=True)
)
window._arbiter = arbiter
with patch("gatelock._preempt.os.kill") as kill:
window._log_grab_blocked(25)
kill.assert_not_called()
def test_signals_the_same_holder_only_once(self, mock_root: MagicMock) -> None:
arbiter = self._arbiter_with(
our_rank=RANK_SCREEN_LOCKER, holder_rank=RANK_DIET_GUARD, holder_pid=4075
)
window, _hooks = make_window(
mock_root, config=LockConfig(mode="hard", preempt_weaker_holder=True)
)
window._arbiter = arbiter
with patch("gatelock._preempt.os.kill") as kill:
window._log_grab_blocked(25)
window._log_grab_blocked(50)
kill.assert_called_once_with(4075, signal.SIGTERM)
def test_disabled_by_config(self, mock_root: MagicMock) -> None:
arbiter = self._arbiter_with(
our_rank=RANK_SCREEN_LOCKER, holder_rank=RANK_DIET_GUARD, holder_pid=4075
)
window, _hooks = make_window(
mock_root, config=LockConfig(mode="hard", preempt_weaker_holder=False)
)
window._arbiter = arbiter
with patch("gatelock._preempt.os.kill") as kill:
window._log_grab_blocked(25)
kill.assert_not_called()
def test_off_by_default(self, mock_root: MagicMock) -> None:
"""Preemption is opt-in, so no app can evict anyone by accident.
wake_alarm outranks screen_locker and builds a plain hard LockConfig.
While the default was True, that combination SIGTERMed the *armed
workout lock*, unlocking enforcement with no workout logged.
"""
arbiter = self._arbiter_with(
our_rank=RANK_WAKE_ALARM,
holder_rank=RANK_SCREEN_LOCKER,
holder_pid=4137,
)
window, _hooks = make_window(mock_root, config=LockConfig(mode="hard"))
window._arbiter = arbiter
with patch("gatelock._preempt.os.kill") as kill:
window._log_grab_blocked(25)
kill.assert_not_called()
def test_no_arbiter_means_no_preemption(self, mock_root: MagicMock) -> None:
window, _hooks = make_window(
mock_root, config=LockConfig(mode="hard", preempt_weaker_holder=True)
)
with patch("gatelock._preempt.os.kill") as kill:
_preempt.maybe_preempt(
Claim(
app="holder",
rank=RANK_DIET_GUARD,
pid=4075,
started="2026-08-21T07:04:07+00:00",
grab="global",
disable_vt=True,
instance_id="theirs",
),
arbiter=None,
config=window._config,
preempted_pids=set(),
)
kill.assert_not_called()
def test_a_holder_that_is_already_gone_is_reported_at_info(
self, mock_root: MagicMock
) -> None:
arbiter = self._arbiter_with(
our_rank=RANK_SCREEN_LOCKER, holder_rank=RANK_DIET_GUARD, holder_pid=4075
)
window, _hooks = make_window(
mock_root, config=LockConfig(mode="hard", preempt_weaker_holder=True)
)
window._arbiter = arbiter
with (
patch("gatelock._preempt.os.kill", side_effect=ProcessLookupError),
patch("gatelock._preempt._logger") as logger,
):
window._log_grab_blocked(25)
assert logger.info.called
def test_an_unsignalable_holder_is_reported_not_raised(
self, mock_root: MagicMock
) -> None:
arbiter = self._arbiter_with(
our_rank=RANK_SCREEN_LOCKER, holder_rank=RANK_DIET_GUARD, holder_pid=4075
)
window, _hooks = make_window(
mock_root, config=LockConfig(mode="hard", preempt_weaker_holder=True)
)
window._arbiter = arbiter
with (
patch("gatelock._preempt.os.kill", side_effect=OSError("nope")),
patch("gatelock._preempt._logger") as logger,
):
window._log_grab_blocked(25)
assert logger.exception.called