mirror of
https://github.com/kuhyx/utils.git
synced 2026-11-24 14:26:29 +01:00
Compare commits
No commits in common. "2005c40baa84902b7ed18abcbe9e0afb8ccbb3c8" and "62da2102d61fad093b87e394f9161dd2355e3e21" have entirely different histories.
2005c40baa
...
62da2102d6
@ -35,12 +35,9 @@ from crdt_sync._remote import RemoteNotFoundError, RemoteStore, RemoteSyncError
|
||||
from crdt_sync._store import dump_log, load_log, read_log, write_log
|
||||
from crdt_sync._sync import (
|
||||
FileSyncStateStore,
|
||||
LogCodec,
|
||||
MemorySyncStateStore,
|
||||
RevisionTracking,
|
||||
SyncState,
|
||||
SyncStateStore,
|
||||
SyncTarget,
|
||||
default_revs_path,
|
||||
revision_of,
|
||||
sync_log,
|
||||
@ -67,7 +64,6 @@ __all__ = [
|
||||
"GitHubSyncError",
|
||||
"Hlc",
|
||||
"Log",
|
||||
"LogCodec",
|
||||
"MemoryCredentialStore",
|
||||
"MemorySyncStateStore",
|
||||
"MirrorSyncClient",
|
||||
@ -76,10 +72,8 @@ __all__ = [
|
||||
"RemoteStore",
|
||||
"RemoteSyncError",
|
||||
"RepoNotFoundError",
|
||||
"RevisionTracking",
|
||||
"SyncState",
|
||||
"SyncStateStore",
|
||||
"SyncTarget",
|
||||
"credential_store_for",
|
||||
"default_revs_path",
|
||||
"dump_log",
|
||||
|
||||
@ -202,27 +202,15 @@ def _remote_revs(client: RemoteStore, revs_path: str) -> dict[str, str]:
|
||||
return get_string_map(revs_path)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _PullContext:
|
||||
"""Everything :func:`_pull_remote_logs` needs for one tick's pull.
|
||||
|
||||
A bundle rather than eight positional parameters: they are always passed
|
||||
together, from one call site, and several share a type -- exactly the
|
||||
shape where a positional mix-up is silent.
|
||||
"""
|
||||
|
||||
client: RemoteStore
|
||||
own_ids: frozenset[str]
|
||||
path_prefix: str
|
||||
filename: str
|
||||
decode: Callable[[str], Log]
|
||||
remote_revs: dict[str, str]
|
||||
state: SyncState
|
||||
|
||||
|
||||
def _pull_remote_logs(
|
||||
ctx: _PullContext,
|
||||
client: RemoteStore,
|
||||
own_ids: frozenset[str],
|
||||
path_prefix: str,
|
||||
filename: str,
|
||||
decode: Callable[[str], Log],
|
||||
remote_revs: dict[str, str],
|
||||
seen_revs: dict[str, str],
|
||||
state: SyncState,
|
||||
) -> list[Log]:
|
||||
"""Return every other device's last-pushed log, skipping this one.
|
||||
|
||||
@ -241,11 +229,11 @@ def _pull_remote_logs(
|
||||
tick can skip them.
|
||||
"""
|
||||
remote_logs: list[Log] = []
|
||||
for other_device_id in ctx.client.list_directory(ctx.path_prefix):
|
||||
if other_device_id in ctx.own_ids:
|
||||
for other_device_id in client.list_directory(path_prefix):
|
||||
if other_device_id in own_ids:
|
||||
continue
|
||||
remote_rev = ctx.remote_revs.get(other_device_id)
|
||||
if remote_rev is not None and remote_rev == ctx.state.peer_revs.get(
|
||||
remote_rev = remote_revs.get(other_device_id)
|
||||
if remote_rev is not None and remote_rev == state.peer_revs.get(
|
||||
other_device_id
|
||||
):
|
||||
# Unchanged since we last merged it, and that merge is already
|
||||
@ -254,13 +242,11 @@ def _pull_remote_logs(
|
||||
# skipped next tick.
|
||||
seen_revs[other_device_id] = remote_rev
|
||||
continue
|
||||
text = ctx.client.get_file_text(
|
||||
f"{ctx.path_prefix}/{other_device_id}/{ctx.filename}"
|
||||
)
|
||||
text = client.get_file_text(f"{path_prefix}/{other_device_id}/{filename}")
|
||||
if text is None:
|
||||
continue
|
||||
try:
|
||||
remote_logs.append(ctx.decode(text))
|
||||
remote_logs.append(decode(text))
|
||||
except (ValueError, KeyError, TypeError):
|
||||
_logger.warning(
|
||||
"Unparsable log pushed by device %r, skipping",
|
||||
@ -273,80 +259,19 @@ def _pull_remote_logs(
|
||||
return remote_logs
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SyncTarget:
|
||||
"""Which remote, which device, and where its logs live.
|
||||
|
||||
Args:
|
||||
client: An authenticated :class:`RemoteStore` -- a
|
||||
:class:`crdt_sync.GitHubSyncClient`, a
|
||||
:class:`crdt_sync.FirebaseSyncClient`, or a mirror of both.
|
||||
device_id: This device's identifier; also the directory name its own
|
||||
log is pushed under.
|
||||
path_prefix: The directory holding one subdirectory per device
|
||||
(e.g. ``"devices"``).
|
||||
legacy_device_id: The id this device pushed under before migrating to
|
||||
a persisted uuid. Treated as this device's own for skip-own
|
||||
purposes, so its pre-migration log is not pulled back and
|
||||
re-merged as a peer's. Pass ``None`` once the old path has been
|
||||
reclaimed.
|
||||
"""
|
||||
|
||||
client: RemoteStore
|
||||
device_id: str
|
||||
path_prefix: str
|
||||
legacy_device_id: str | None = None
|
||||
|
||||
@property
|
||||
def own_ids(self) -> frozenset[str]:
|
||||
"""Every id whose pushed log belongs to this device."""
|
||||
if self.legacy_device_id is None:
|
||||
return frozenset({self.device_id})
|
||||
return frozenset({self.device_id, self.legacy_device_id})
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LogCodec:
|
||||
"""How a log is turned into pushed text and back.
|
||||
|
||||
Args:
|
||||
encode: Serializes a merged log for pushing.
|
||||
decode: Parses a remote device's pushed text back into a log.
|
||||
Raising ``ValueError``, ``KeyError``, or ``TypeError`` is treated
|
||||
as a corrupt/unparsable push, and that device is skipped for
|
||||
this tick rather than aborting the whole sync.
|
||||
filename: The file name each device pushes its log as.
|
||||
commit_message: The commit message used for this device's push.
|
||||
"""
|
||||
|
||||
encode: Callable[[Log], str]
|
||||
decode: Callable[[str], Log]
|
||||
filename: str = _DEFAULT_FILENAME
|
||||
commit_message: str = "crdt_sync: update log"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RevisionTracking:
|
||||
"""Optional skip-unchanged behaviour for a tick.
|
||||
|
||||
Omit it entirely and the tick behaves exactly as it always did: fetch
|
||||
everything, push unconditionally.
|
||||
|
||||
Args:
|
||||
state_store: Persists what this device last pushed and last merged.
|
||||
revs_path: Where revisions live; defaults to
|
||||
:func:`default_revs_path`.
|
||||
"""
|
||||
|
||||
state_store: SyncStateStore | None = None
|
||||
revs_path: str | None = None
|
||||
|
||||
|
||||
def sync_log(
|
||||
target: SyncTarget,
|
||||
*,
|
||||
client: RemoteStore,
|
||||
device_id: str,
|
||||
path_prefix: str,
|
||||
local_log: Log,
|
||||
codec: LogCodec,
|
||||
revisions: RevisionTracking | None = None,
|
||||
encode: Callable[[Log], str],
|
||||
decode: Callable[[str], Log],
|
||||
filename: str = _DEFAULT_FILENAME,
|
||||
commit_message: str = "crdt_sync: update log",
|
||||
state_store: SyncStateStore | None = None,
|
||||
revs_path: str | None = None,
|
||||
legacy_device_id: str | None = None,
|
||||
) -> Log:
|
||||
"""Run one full sync tick: pull every other device's log, merge, push.
|
||||
|
||||
@ -356,12 +281,32 @@ def sync_log(
|
||||
device's own merged result to ``<path_prefix>/<device_id>/<filename>``.
|
||||
|
||||
Args:
|
||||
target: Which remote and device this tick is for.
|
||||
client: An authenticated :class:`RemoteStore` -- a
|
||||
:class:`crdt_sync.GitHubSyncClient`, a
|
||||
:class:`crdt_sync.FirebaseSyncClient`, or a mirror of both.
|
||||
device_id: This device's identifier; also the directory name its own
|
||||
log is pushed under.
|
||||
path_prefix: The directory holding one subdirectory per device
|
||||
(e.g. ``"devices"``).
|
||||
local_log: This device's current full log (including tombstones).
|
||||
codec: How to serialize and parse a log.
|
||||
revisions: Pass one to skip downloading peers that have not changed
|
||||
and skip pushing a log that has not changed. ``None`` fetches
|
||||
everything and pushes unconditionally.
|
||||
encode: Serializes a merged log for pushing.
|
||||
decode: Parses a remote device's pushed text back into a log.
|
||||
Raising ``ValueError``, ``KeyError``, or ``TypeError`` is treated
|
||||
as a corrupt/unparsable push, and that device is skipped for
|
||||
this tick rather than aborting the whole sync.
|
||||
filename: The file name each device pushes its log as.
|
||||
commit_message: The commit message used for this device's push.
|
||||
state_store: Pass one to enable revision tracking, which skips
|
||||
downloading peers that have not changed and skips pushing a log
|
||||
that has not changed. Without it the tick behaves exactly as it
|
||||
always did: fetch everything, push unconditionally.
|
||||
revs_path: Where revisions live; defaults to
|
||||
:func:`default_revs_path`.
|
||||
legacy_device_id: The id this device pushed under before migrating to
|
||||
a persisted uuid. Treated as this device's own for skip-own
|
||||
purposes, so its pre-migration log is not pulled back and
|
||||
re-merged as a peer's. Pass ``None`` once the old path has been
|
||||
reclaimed.
|
||||
|
||||
Returns:
|
||||
The merged log, as pushed.
|
||||
@ -374,83 +319,45 @@ def sync_log(
|
||||
unchanged and never be fetched again. Per-device keys make that
|
||||
failure impossible rather than merely avoided.
|
||||
"""
|
||||
tracking = revisions if revisions is not None else RevisionTracking()
|
||||
state_store = tracking.state_store
|
||||
revs = (
|
||||
tracking.revs_path
|
||||
if tracking.revs_path is not None
|
||||
else default_revs_path(target.path_prefix)
|
||||
)
|
||||
revs = revs_path if revs_path is not None else default_revs_path(path_prefix)
|
||||
state = state_store.load() if state_store is not None else SyncState()
|
||||
remote_revs = _remote_revs(target.client, revs) if state_store is not None else {}
|
||||
remote_revs = _remote_revs(client, revs) if state_store is not None else {}
|
||||
|
||||
seen_revs: dict[str, str] = {}
|
||||
merged = _merge_peers(
|
||||
_PullContext(
|
||||
client=target.client,
|
||||
own_ids=target.own_ids,
|
||||
path_prefix=target.path_prefix,
|
||||
filename=codec.filename,
|
||||
decode=codec.decode,
|
||||
remote_revs=remote_revs,
|
||||
state=state,
|
||||
),
|
||||
local_log,
|
||||
seen_revs,
|
||||
own_ids = frozenset(
|
||||
{device_id} if legacy_device_id is None else {device_id, legacy_device_id}
|
||||
)
|
||||
merged = dict(local_log)
|
||||
seen_revs: dict[str, str] = {}
|
||||
for remote_log in _pull_remote_logs(
|
||||
client,
|
||||
own_ids,
|
||||
path_prefix,
|
||||
filename,
|
||||
decode,
|
||||
remote_revs,
|
||||
seen_revs,
|
||||
state,
|
||||
):
|
||||
merged = merge_logs(merged, remote_log)
|
||||
|
||||
encoded = codec.encode(merged)
|
||||
encoded = encode(merged)
|
||||
revision = revision_of(encoded)
|
||||
if not (state_store is not None and revision == state.pushed_rev):
|
||||
_push(
|
||||
target,
|
||||
codec,
|
||||
unchanged = state_store is not None and revision == state.pushed_rev
|
||||
if not unchanged:
|
||||
client.put_file_text(
|
||||
f"{path_prefix}/{device_id}/{filename}",
|
||||
encoded,
|
||||
_RevisionMarker(revs, revision) if state_store is not None else None,
|
||||
message=commit_message,
|
||||
)
|
||||
if state_store is not None:
|
||||
# Published after the log, never before: a peer that cached
|
||||
# "seen rev X" against a log it never received would skip it
|
||||
# forever.
|
||||
client.put_file_text(
|
||||
f"{revs}/{device_id}",
|
||||
revision,
|
||||
message=commit_message,
|
||||
)
|
||||
if state_store is not None:
|
||||
state_store.save(SyncState(pushed_rev=revision, peer_revs=seen_revs))
|
||||
return merged
|
||||
|
||||
|
||||
def _merge_peers(
|
||||
ctx: _PullContext,
|
||||
local_log: Log,
|
||||
seen_revs: dict[str, str],
|
||||
) -> Log:
|
||||
"""Return ``local_log`` with every peer's pushed log merged in."""
|
||||
merged = dict(local_log)
|
||||
for remote_log in _pull_remote_logs(ctx, seen_revs):
|
||||
merged = merge_logs(merged, remote_log)
|
||||
return merged
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _RevisionMarker:
|
||||
"""The revision node a tracked push publishes after its log."""
|
||||
|
||||
revs_path: str
|
||||
revision: str
|
||||
|
||||
|
||||
def _push(
|
||||
target: SyncTarget,
|
||||
codec: LogCodec,
|
||||
encoded: str,
|
||||
marker: _RevisionMarker | None,
|
||||
) -> None:
|
||||
"""Push this device's merged log, then its revision marker."""
|
||||
target.client.put_file_text(
|
||||
f"{target.path_prefix}/{target.device_id}/{codec.filename}",
|
||||
encoded,
|
||||
message=codec.commit_message,
|
||||
)
|
||||
if marker is not None:
|
||||
# Published after the log, never before: a peer that cached
|
||||
# "seen rev X" against a log it never received would skip it
|
||||
# forever.
|
||||
target.client.put_file_text(
|
||||
f"{marker.revs_path}/{target.device_id}",
|
||||
marker.revision,
|
||||
message=codec.commit_message,
|
||||
)
|
||||
|
||||
@ -7,7 +7,6 @@ from typing import TYPE_CHECKING
|
||||
import pytest
|
||||
|
||||
from crdt_sync import Hlc
|
||||
from crdt_sync._remote import RemoteSyncError
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
@ -21,124 +20,3 @@ def make_hlc() -> Callable[..., Hlc]:
|
||||
return Hlc(wall_time_ms=wall_time_ms, counter=counter, node_id=node_id)
|
||||
|
||||
return _make
|
||||
|
||||
|
||||
class FakeStore:
|
||||
"""An in-memory remote: records its traffic, and can be told to fail.
|
||||
|
||||
One class rather than a near-copy per test module. It is the union of
|
||||
what those copies needed -- ``reads``/``writes`` for asserting on traffic
|
||||
rather than only on results, and ``failing`` for driving the error paths
|
||||
-- because the shared half was the fiddly part (the prefix slicing in
|
||||
:meth:`list_directory` and :meth:`get_string_map`) and two copies of that
|
||||
is where they drift.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
files: dict[str, str] | None = None,
|
||||
*,
|
||||
failing: bool = False,
|
||||
) -> None:
|
||||
"""Start holding ``files``, failing every call if ``failing``."""
|
||||
self.files = dict(files or {})
|
||||
self.failing = failing
|
||||
self.reads: list[str] = []
|
||||
self.writes: list[str] = []
|
||||
|
||||
def _guard(self, what: str) -> None:
|
||||
if self.failing:
|
||||
msg = f"{what} failed"
|
||||
raise RemoteSyncError(msg)
|
||||
|
||||
def list_directory(self, path: str) -> list[str]:
|
||||
"""Return the distinct first segments under ``path``."""
|
||||
self._guard("list")
|
||||
prefix = f"{path}/"
|
||||
return sorted(
|
||||
{
|
||||
key[len(prefix) :].split("/")[0]
|
||||
for key in self.files
|
||||
if key.startswith(prefix)
|
||||
}
|
||||
)
|
||||
|
||||
def get_file_text(self, path: str) -> str | None:
|
||||
"""Return the stored text, recording the read."""
|
||||
self._guard("read")
|
||||
self.reads.append(path)
|
||||
return self.files.get(path)
|
||||
|
||||
def put_file_text(self, path: str, text: str, *, message: str) -> None:
|
||||
"""Store ``text``, recording the write."""
|
||||
del message
|
||||
self._guard("write")
|
||||
self.writes.append(path)
|
||||
self.files[path] = text
|
||||
|
||||
def get_string_map(self, path: str) -> dict[str, str]:
|
||||
"""Return the direct children of ``path`` as a flat map."""
|
||||
self._guard("map read")
|
||||
prefix = f"{path}/"
|
||||
return {
|
||||
key[len(prefix) :]: value
|
||||
for key, value in self.files.items()
|
||||
if key.startswith(prefix)
|
||||
}
|
||||
|
||||
def delete_file(self, path: str, *, message: str = "") -> None:
|
||||
"""Remove ``path`` if present."""
|
||||
del message
|
||||
self._guard("delete")
|
||||
self.files.pop(path, None)
|
||||
|
||||
def can_access_remote(self) -> bool:
|
||||
"""Report health, which ``failing`` inverts."""
|
||||
return not self.failing
|
||||
|
||||
|
||||
class FakeStoreWithoutBulkRead:
|
||||
"""A store with no bulk-map read, standing in for GitHub.
|
||||
|
||||
Composes rather than subclasses :class:`FakeStore`, because a subclass
|
||||
would inherit ``get_string_map`` -- the capability this fake must lack.
|
||||
"""
|
||||
|
||||
def __init__(self, files: dict[str, str] | None = None) -> None:
|
||||
"""Wrap a plain :class:`FakeStore` holding ``files``."""
|
||||
self._inner = FakeStore(files)
|
||||
|
||||
@property
|
||||
def files(self) -> dict[str, str]:
|
||||
"""The wrapped store's contents."""
|
||||
return self._inner.files
|
||||
|
||||
@property
|
||||
def reads(self) -> list[str]:
|
||||
"""The wrapped store's recorded reads."""
|
||||
return self._inner.reads
|
||||
|
||||
@property
|
||||
def writes(self) -> list[str]:
|
||||
"""The wrapped store's recorded writes."""
|
||||
return self._inner.writes
|
||||
|
||||
def list_directory(self, path: str) -> list[str]:
|
||||
"""Delegate to the wrapped store."""
|
||||
return self._inner.list_directory(path)
|
||||
|
||||
def get_file_text(self, path: str) -> str | None:
|
||||
"""Delegate to the wrapped store."""
|
||||
return self._inner.get_file_text(path)
|
||||
|
||||
def put_file_text(self, path: str, text: str, *, message: str) -> None:
|
||||
"""Delegate to the wrapped store."""
|
||||
self._inner.put_file_text(path, text, message=message)
|
||||
|
||||
def delete_file(self, path: str, *, message: str = "") -> None:
|
||||
"""Delegate to the wrapped store."""
|
||||
self._inner.delete_file(path, message=message)
|
||||
|
||||
def can_access_remote(self) -> bool:
|
||||
"""Delegate to the wrapped store."""
|
||||
return self._inner.can_access_remote()
|
||||
|
||||
@ -6,11 +6,6 @@ newline a text editor appended), so each is asserted to name the field at
|
||||
fault rather than merely to raise.
|
||||
"""
|
||||
|
||||
# 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
|
||||
@ -46,12 +41,10 @@ class _StubRemote:
|
||||
accepts it without a suppression.
|
||||
"""
|
||||
|
||||
def list_directory(self, _path: str) -> list[str]:
|
||||
"""Report an empty remote directory."""
|
||||
def list_directory(self, path: str) -> list[str]:
|
||||
return []
|
||||
|
||||
def get_file_text(self, _path: str) -> str | None:
|
||||
"""Report the file as absent."""
|
||||
def get_file_text(self, path: str) -> str | None:
|
||||
return None
|
||||
|
||||
def put_file_text(self, path: str, text: str, *, message: str) -> None:
|
||||
@ -61,7 +54,6 @@ class _StubRemote:
|
||||
"""Accept and discard a delete."""
|
||||
|
||||
def can_access_remote(self) -> bool:
|
||||
"""Report the remote as reachable."""
|
||||
return True
|
||||
|
||||
|
||||
@ -72,7 +64,6 @@ def _write(path: Path, data: object) -> Path:
|
||||
|
||||
|
||||
def test_loads_a_valid_config(tmp_path: Path) -> None:
|
||||
"""Loads a valid config."""
|
||||
config = FirebaseConfig.load(_write(tmp_path / "firebase.json", _VALID))
|
||||
|
||||
assert config.api_key == "AIzaSyExample"
|
||||
@ -92,13 +83,11 @@ def test_ignores_the_scaffold_comment_keys(tmp_path: Path) -> None:
|
||||
|
||||
|
||||
def test_reports_a_missing_file(tmp_path: Path) -> None:
|
||||
"""Reports a missing file."""
|
||||
with pytest.raises(ConfigError, match="does not exist"):
|
||||
FirebaseConfig.load(tmp_path / "absent.json")
|
||||
|
||||
|
||||
def test_reports_unreadable_json(tmp_path: Path) -> None:
|
||||
"""Reports unreadable JSON."""
|
||||
path = tmp_path / "firebase.json"
|
||||
path.write_text("{not json", encoding="utf-8")
|
||||
|
||||
@ -107,7 +96,6 @@ def test_reports_unreadable_json(tmp_path: Path) -> None:
|
||||
|
||||
|
||||
def test_reports_a_non_object_document(tmp_path: Path) -> None:
|
||||
"""Reports a non object document."""
|
||||
with pytest.raises(ConfigError, match="must contain a JSON object"):
|
||||
FirebaseConfig.load(_write(tmp_path / "firebase.json", ["a list"]))
|
||||
|
||||
@ -122,7 +110,6 @@ def test_reports_an_unreadable_path(tmp_path: Path) -> None:
|
||||
|
||||
@pytest.mark.parametrize("field", sorted(_VALID))
|
||||
def test_names_a_missing_field(tmp_path: Path, field: str) -> None:
|
||||
"""Names a missing field."""
|
||||
incomplete = {k: v for k, v in _VALID.items() if k != field}
|
||||
|
||||
with pytest.raises(ConfigError, match=field):
|
||||
@ -130,7 +117,6 @@ def test_names_a_missing_field(tmp_path: Path, field: str) -> None:
|
||||
|
||||
|
||||
def test_names_an_empty_field(tmp_path: Path) -> None:
|
||||
"""Names an empty field."""
|
||||
with pytest.raises(ConfigError, match="uid"):
|
||||
FirebaseConfig.load(_write(tmp_path / "firebase.json", {**_VALID, "uid": " "}))
|
||||
|
||||
@ -144,7 +130,6 @@ def test_names_an_unfilled_placeholder(tmp_path: Path) -> None:
|
||||
|
||||
|
||||
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")
|
||||
@ -162,7 +147,6 @@ def test_strips_a_trailing_newline_from_the_password(tmp_path: Path) -> None:
|
||||
|
||||
|
||||
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")
|
||||
@ -172,7 +156,6 @@ def test_rejects_an_empty_password(tmp_path: Path) -> None:
|
||||
|
||||
|
||||
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")
|
||||
@ -182,7 +165,6 @@ def test_rejects_a_placeholder_password(tmp_path: Path) -> None:
|
||||
|
||||
|
||||
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()
|
||||
|
||||
@ -209,21 +191,19 @@ def test_client_signs_in_only_without_a_cached_session(
|
||||
sign_ins: list[tuple[str, str]] = []
|
||||
|
||||
class _Auth:
|
||||
def __init__(self, api_key: str, _store: object) -> None:
|
||||
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 sign_ins == []
|
||||
assert client is not None
|
||||
|
||||
|
||||
@ -231,7 +211,6 @@ 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")
|
||||
@ -239,15 +218,13 @@ def test_client_signs_in_when_there_is_no_session(
|
||||
sign_ins: list[tuple[str, str]] = []
|
||||
|
||||
class _Auth:
|
||||
def __init__(self, api_key: str, _store: object) -> None:
|
||||
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)
|
||||
@ -265,15 +242,13 @@ def test_mirror_client_makes_firebase_primary(
|
||||
github = _StubRemote()
|
||||
|
||||
class _Auth:
|
||||
def __init__(self, api_key: str, _store: object) -> None:
|
||||
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)
|
||||
@ -296,15 +271,13 @@ def test_client_loads_the_shared_config_when_none_is_given(
|
||||
)
|
||||
|
||||
class _Auth:
|
||||
def __init__(self, api_key: str, _store: object) -> None:
|
||||
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)
|
||||
|
||||
@ -69,22 +69,17 @@ def _client(*, signed_in: bool = True) -> FirebaseSyncClient:
|
||||
|
||||
|
||||
class TestKeyEscaping:
|
||||
"""Key escaping."""
|
||||
|
||||
def test_escapes_a_json_filename_into_a_legal_key(self) -> None:
|
||||
# `.` is illegal in an RTDB key, and the trailing `.json` in a REST
|
||||
# URL is the format suffix -- so the name cannot be stored verbatim.
|
||||
"""Escapes a JSON filename into a legal key."""
|
||||
assert encode_key("log.json") == "log~2Ejson"
|
||||
|
||||
def test_leaves_dot_free_device_ids_untouched(self) -> None:
|
||||
"""Leaves dot free device ids untouched."""
|
||||
assert encode_key("pc") == "pc"
|
||||
uuid = "32c28cf3-c0eb-423f-8bac-9bda9f158054"
|
||||
assert encode_key(uuid) == uuid
|
||||
|
||||
def test_escapes_every_forbidden_character_and_the_escape_char(self) -> None:
|
||||
"""Escapes every forbidden character and the escape char."""
|
||||
assert encode_key("a.b$c#d[e]f~g") == "a~2Eb~24c~23d~5Be~5Df~7Eg"
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
@ -94,29 +89,22 @@ class TestKeyEscaping:
|
||||
def test_round_trips(self, name: str) -> None:
|
||||
# A name that already looks like an escape must survive: `~` is
|
||||
# escaped first, so `log~2Ejson` is not mistaken for `log.json`.
|
||||
"""Round trips."""
|
||||
assert decode_key(encode_key(name)) == name
|
||||
|
||||
def test_escapes_each_path_segment_but_keeps_separators(self) -> None:
|
||||
"""Escapes each path segment but keeps separators."""
|
||||
assert encode_path("todo-sync/notes/abc.json") == "todo-sync/notes/abc~2Ejson"
|
||||
|
||||
def test_drops_empty_segments(self) -> None:
|
||||
"""Drops empty segments."""
|
||||
assert not encode_path("")
|
||||
assert encode_path("/a//b/") == "a/b"
|
||||
|
||||
|
||||
class TestGetFileText:
|
||||
"""Get file text."""
|
||||
|
||||
def test_returns_the_stored_text_blob(self) -> None:
|
||||
"""Returns the stored text blob."""
|
||||
with patch.object(fb.requests, "get", return_value=_response(200, '{"a":1}')):
|
||||
assert _client().get_file_text("ns/devices/pc/log.json") == '{"a":1}'
|
||||
|
||||
def test_requests_the_escaped_path_with_the_auth_token(self) -> None:
|
||||
"""Requests the escaped path with the auth token."""
|
||||
with patch.object(
|
||||
fb.requests, "get", return_value=_response(200, "{}")
|
||||
) as get_mock:
|
||||
@ -128,12 +116,10 @@ class TestGetFileText:
|
||||
def test_returns_none_for_a_path_never_written_to(self) -> None:
|
||||
# RTDB answers a missing path with literal null and a 200, so this is
|
||||
# benign "no other device has synced yet", not an error.
|
||||
"""Returns none for a path never written to."""
|
||||
with patch.object(fb.requests, "get", return_value=_response(200, None)):
|
||||
assert _client().get_file_text("ns/devices/phone/log.json") is None
|
||||
|
||||
def test_raises_when_the_value_is_not_a_text_blob(self) -> None:
|
||||
"""Raises when the value is not a text blob."""
|
||||
with (
|
||||
patch.object(fb.requests, "get", return_value=_response(200, {"a": 1})),
|
||||
pytest.raises(FirebaseSyncError, match="not the expected text blob"),
|
||||
@ -142,7 +128,6 @@ class TestGetFileText:
|
||||
|
||||
@pytest.mark.parametrize("status", [401, 403])
|
||||
def test_raises_database_not_found_when_the_rules_reject(self, status: int) -> None:
|
||||
"""Raises database not found when the rules reject."""
|
||||
with (
|
||||
patch.object(
|
||||
fb.requests, "get", return_value=_response(status, {"error": "denied"})
|
||||
@ -154,7 +139,6 @@ class TestGetFileText:
|
||||
def test_raises_a_plain_sync_error_on_any_other_non_2xx(self) -> None:
|
||||
# Spark quota exhaustion lands here. It must surface, never be
|
||||
# swallowed into a None that reads as "nothing to sync".
|
||||
"""Raises a plain sync error on any other non 2xx."""
|
||||
with (
|
||||
patch.object(
|
||||
fb.requests, "get", return_value=_response(429, {"error": "quota"})
|
||||
@ -164,7 +148,6 @@ class TestGetFileText:
|
||||
_client().get_file_text("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, "get", side_effect=requests.ConnectionError("offline")
|
||||
@ -175,10 +158,7 @@ class TestGetFileText:
|
||||
|
||||
|
||||
class TestListDirectory:
|
||||
"""List directory."""
|
||||
|
||||
def test_returns_decoded_keys_and_asks_for_a_shallow_read(self) -> None:
|
||||
"""Returns decoded keys and asks for a shallow read."""
|
||||
payload = {"pc": True, "phone": True}
|
||||
with patch.object(
|
||||
fb.requests, "get", return_value=_response(200, payload)
|
||||
@ -190,19 +170,16 @@ class TestListDirectory:
|
||||
|
||||
def test_decodes_escaped_filenames_back(self) -> None:
|
||||
# The notes app lists filenames, not device dirs: `.json` returns.
|
||||
"""Decodes escaped filenames back."""
|
||||
with patch.object(
|
||||
fb.requests, "get", return_value=_response(200, {"abc~2Ejson": True})
|
||||
):
|
||||
assert _client().list_directory("todo-sync/notes") == ["abc.json"]
|
||||
|
||||
def test_returns_empty_for_an_unwritten_prefix(self) -> None:
|
||||
"""Returns empty for an unwritten prefix."""
|
||||
with patch.object(fb.requests, "get", return_value=_response(200, None)):
|
||||
assert not _client().list_directory("ns/devices")
|
||||
|
||||
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"})
|
||||
@ -213,10 +190,7 @@ class TestListDirectory:
|
||||
|
||||
|
||||
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(
|
||||
@ -230,7 +204,6 @@ class TestPutFileText:
|
||||
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"})
|
||||
@ -240,7 +213,6 @@ class TestPutFileText:
|
||||
_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")
|
||||
@ -251,30 +223,24 @@ class TestPutFileText:
|
||||
|
||||
|
||||
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"})
|
||||
@ -285,10 +251,7 @@ class TestGetStringMap:
|
||||
|
||||
|
||||
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:
|
||||
@ -296,7 +259,6 @@ class TestDeleteFile:
|
||||
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"})
|
||||
@ -306,7 +268,6 @@ class TestDeleteFile:
|
||||
_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")
|
||||
@ -317,22 +278,17 @@ class TestDeleteFile:
|
||||
|
||||
|
||||
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")
|
||||
):
|
||||
@ -341,26 +297,20 @@ class TestCanAccessRemote:
|
||||
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")
|
||||
|
||||
@ -81,36 +81,27 @@ def _patch_post(*responses: MagicMock) -> object:
|
||||
|
||||
|
||||
class TestFirebaseCredentials:
|
||||
"""Firebase credentials."""
|
||||
|
||||
def test_round_trips_through_json(self) -> None:
|
||||
"""Round trips through JSON."""
|
||||
original = _credentials()
|
||||
restored = FirebaseCredentials.from_json(original.to_json())
|
||||
assert restored == original
|
||||
|
||||
def test_is_not_expired_inside_its_lifetime(self) -> None:
|
||||
"""Is not expired inside its lifetime."""
|
||||
assert _credentials().is_expired_at(_NOW) is False
|
||||
|
||||
def test_is_expired_once_past_expiry(self) -> None:
|
||||
"""Is expired once past expiry."""
|
||||
stale = _credentials(valid_for=dt.timedelta(minutes=-1))
|
||||
assert stale.is_expired_at(_NOW) is True
|
||||
|
||||
def test_is_expired_inside_the_refresh_skew(self) -> None:
|
||||
# A tick starting now would outlive a token with 2 minutes left, so
|
||||
# it must count as already expired.
|
||||
"""Is expired inside the refresh skew."""
|
||||
soon = _credentials(valid_for=dt.timedelta(minutes=2))
|
||||
assert soon.is_expired_at(_NOW) is True
|
||||
|
||||
|
||||
class TestSignIn:
|
||||
"""Sign in."""
|
||||
|
||||
def test_stores_the_session(self) -> None:
|
||||
"""Stores the session."""
|
||||
store = MemoryCredentialStore()
|
||||
body = {"idToken": _ID_1, "refreshToken": _REFRESH_1, "expiresIn": "3600"}
|
||||
with _patch_post(_response(200, body)):
|
||||
@ -122,7 +113,6 @@ class TestSignIn:
|
||||
assert saved.expires_at == _NOW + dt.timedelta(hours=1)
|
||||
|
||||
def test_reports_googles_reason_for_a_rejected_password(self) -> None:
|
||||
"""Reports googles reason for a rejected password."""
|
||||
body = {"error": {"message": "INVALID_LOGIN_CREDENTIALS"}}
|
||||
with (
|
||||
_patch_post(_response(400, body)),
|
||||
@ -131,7 +121,6 @@ class TestSignIn:
|
||||
_provider().sign_in("me@example.com", "wrong")
|
||||
|
||||
def test_reports_a_string_shaped_error_body(self) -> None:
|
||||
"""Reports a string shaped error body."""
|
||||
with (
|
||||
_patch_post(_response(400, {"error": "BAD_REQUEST"})),
|
||||
pytest.raises(FirebaseAuthError, match="BAD_REQUEST"),
|
||||
@ -139,7 +128,6 @@ class TestSignIn:
|
||||
_provider().sign_in("a@b.c", "x")
|
||||
|
||||
def test_survives_an_error_body_with_no_error_key(self) -> None:
|
||||
"""Survives an error body with no error key."""
|
||||
with (
|
||||
_patch_post(_response(400, {"unexpected": "shape"})),
|
||||
pytest.raises(FirebaseAuthError, match="HTTP 400"),
|
||||
@ -147,7 +135,6 @@ class TestSignIn:
|
||||
_provider().sign_in("a@b.c", "x")
|
||||
|
||||
def test_survives_a_non_dict_error_body(self) -> None:
|
||||
"""Survives a non dict error body."""
|
||||
with (
|
||||
_patch_post(_response(400, ["not", "a", "dict"])),
|
||||
pytest.raises(FirebaseAuthError, match="HTTP 400"),
|
||||
@ -155,7 +142,6 @@ class TestSignIn:
|
||||
_provider().sign_in("a@b.c", "x")
|
||||
|
||||
def test_survives_a_non_json_error_body(self) -> None:
|
||||
"""Survives a non JSON error body."""
|
||||
response = _response(502)
|
||||
response.json = MagicMock(side_effect=ValueError("not json"))
|
||||
with (
|
||||
@ -165,7 +151,6 @@ class TestSignIn:
|
||||
_provider().sign_in("a@b.c", "x")
|
||||
|
||||
def test_turns_a_network_failure_into_an_auth_error(self) -> None:
|
||||
"""Turns a network failure into an auth error."""
|
||||
with (
|
||||
patch.object(
|
||||
fa.requests, "post", side_effect=requests.ConnectionError("offline")
|
||||
@ -176,8 +161,6 @@ class TestSignIn:
|
||||
|
||||
|
||||
class TestSignInWithGoogle:
|
||||
"""Sign in with google."""
|
||||
|
||||
@staticmethod
|
||||
def _google_body(**overrides: object) -> dict[str, object]:
|
||||
body: dict[str, object] = {
|
||||
@ -191,7 +174,6 @@ class TestSignInWithGoogle:
|
||||
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")
|
||||
@ -202,7 +184,6 @@ class TestSignInWithGoogle:
|
||||
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"
|
||||
@ -211,16 +192,14 @@ class TestSignInWithGoogle:
|
||||
# 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")
|
||||
assert _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")
|
||||
@ -229,7 +208,6 @@ class TestSignInWithGoogle:
|
||||
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)
|
||||
@ -240,7 +218,6 @@ class TestSignInWithGoogle:
|
||||
# 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 (
|
||||
@ -251,7 +228,6 @@ class TestSignInWithGoogle:
|
||||
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)),
|
||||
@ -261,23 +237,18 @@ class TestSignInWithGoogle:
|
||||
|
||||
|
||||
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,
|
||||
@ -291,7 +262,6 @@ class TestIdToken:
|
||||
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"}})),
|
||||
@ -333,7 +303,6 @@ class TestIdToken:
|
||||
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 (
|
||||
@ -345,10 +314,7 @@ class TestIdToken:
|
||||
|
||||
|
||||
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
|
||||
@ -358,7 +324,6 @@ class TestSessionLifecycle:
|
||||
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
|
||||
@ -368,16 +333,12 @@ class TestSessionLifecycle:
|
||||
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()
|
||||
@ -385,31 +346,26 @@ class TestFileCredentialStore:
|
||||
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(
|
||||
@ -420,7 +376,6 @@ class TestFileCredentialStore:
|
||||
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())
|
||||
@ -429,7 +384,6 @@ class TestFileCredentialStore:
|
||||
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())
|
||||
|
||||
@ -51,21 +51,16 @@ def _patch_get_raises() -> object:
|
||||
|
||||
|
||||
class TestGetFileText:
|
||||
"""Get file text."""
|
||||
|
||||
def test_returns_decoded_content_on_success(self) -> None:
|
||||
"""Returns decoded content on success."""
|
||||
encoded = base64.b64encode(b"hello world").decode("ascii")
|
||||
with _patch_get(_response(200, {"content": encoded})):
|
||||
assert _client().get_file_text("devices/pc/log.json") == "hello world"
|
||||
|
||||
def test_returns_none_for_an_unused_path_on_a_real_repo(self) -> None:
|
||||
"""Returns none for an unused path on a real repo."""
|
||||
with _patch_get(_response(404), _response(200)):
|
||||
assert _client().get_file_text("devices/phone/log.json") is None
|
||||
|
||||
def test_raises_repo_not_found_when_the_repo_itself_is_missing(self) -> None:
|
||||
"""Raises repo not found when the repo itself is missing."""
|
||||
with (
|
||||
_patch_get(_response(404), _response(404)),
|
||||
pytest.raises(RepoNotFoundError),
|
||||
@ -73,19 +68,16 @@ class TestGetFileText:
|
||||
_client().get_file_text("devices/pc/log.json")
|
||||
|
||||
def test_raises_sync_error_on_a_non_2xx_non_404(self) -> None:
|
||||
"""Raises sync error on a non 2xx non 404."""
|
||||
with _patch_get(_response(500)), pytest.raises(GitHubSyncError):
|
||||
_client().get_file_text("devices/pc/log.json")
|
||||
|
||||
def test_raises_sync_error_on_a_network_exception(self) -> None:
|
||||
"""Raises sync error on a network exception."""
|
||||
with _patch_get_raises(), pytest.raises(GitHubSyncError):
|
||||
_client().get_file_text("devices/pc/log.json")
|
||||
|
||||
def test_treats_a_network_error_during_the_repo_check_as_repo_missing(
|
||||
self,
|
||||
) -> None:
|
||||
"""Treats a network error during the repo check as repo missing."""
|
||||
with (
|
||||
patch.object(
|
||||
_github.requests,
|
||||
@ -98,26 +90,20 @@ class TestGetFileText:
|
||||
|
||||
|
||||
class TestListDirectory:
|
||||
"""List directory."""
|
||||
|
||||
def test_returns_entry_names(self) -> None:
|
||||
"""Returns entry names."""
|
||||
payload = [{"name": "pc"}, {"name": "phone"}, {"not_a_name": "x"}]
|
||||
with _patch_get(_response(200, payload)):
|
||||
assert _client().list_directory("devices") == ["pc", "phone"]
|
||||
|
||||
def test_returns_empty_list_when_response_is_not_a_list(self) -> None:
|
||||
"""Returns empty list when response is not a list."""
|
||||
with _patch_get(_response(200, {"unexpected": "shape"})):
|
||||
assert _client().list_directory("devices") == []
|
||||
|
||||
def test_returns_empty_list_for_an_unused_path_on_a_real_repo(self) -> None:
|
||||
"""Returns empty list for an unused path on a real repo."""
|
||||
with _patch_get(_response(404), _response(200)):
|
||||
assert _client().list_directory("devices") == []
|
||||
|
||||
def test_raises_repo_not_found_when_the_repo_itself_is_missing(self) -> None:
|
||||
"""Raises repo not found when the repo itself is missing."""
|
||||
with (
|
||||
_patch_get(_response(404), _response(404)),
|
||||
pytest.raises(RepoNotFoundError),
|
||||
@ -125,16 +111,12 @@ class TestListDirectory:
|
||||
_client().list_directory("devices")
|
||||
|
||||
def test_raises_sync_error_on_a_non_2xx_non_404(self) -> None:
|
||||
"""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(
|
||||
@ -145,7 +127,6 @@ class TestPutFileText:
|
||||
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(
|
||||
@ -156,7 +137,6 @@ class TestPutFileText:
|
||||
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(
|
||||
@ -167,7 +147,6 @@ class TestPutFileText:
|
||||
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),
|
||||
@ -175,12 +154,10 @@ class TestPutFileText:
|
||||
_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(
|
||||
@ -193,7 +170,6 @@ class TestPutFileText:
|
||||
_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)),
|
||||
@ -203,20 +179,15 @@ class TestPutFileText:
|
||||
|
||||
|
||||
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
|
||||
|
||||
@ -225,17 +196,14 @@ 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
|
||||
|
||||
@ -244,13 +212,11 @@ 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)
|
||||
@ -258,10 +224,7 @@ class TestRemoteStoreContract:
|
||||
|
||||
|
||||
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)),
|
||||
@ -270,7 +233,6 @@ class TestDeleteFile:
|
||||
|
||||
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,
|
||||
@ -279,7 +241,6 @@ class TestDeleteFile:
|
||||
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)),
|
||||
@ -288,7 +249,6 @@ class TestDeleteFile:
|
||||
_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(
|
||||
|
||||
@ -13,45 +13,35 @@ if TYPE_CHECKING:
|
||||
|
||||
|
||||
class TestOrdering:
|
||||
"""Ordering."""
|
||||
|
||||
def test_greater_wall_time_wins(self, make_hlc: Callable[..., Hlc]) -> None:
|
||||
"""Greater wall time wins."""
|
||||
assert make_hlc(200) > make_hlc(100)
|
||||
|
||||
def test_equal_wall_time_greater_counter_wins(
|
||||
self, make_hlc: Callable[..., Hlc]
|
||||
) -> None:
|
||||
"""Equal wall time greater counter wins."""
|
||||
assert make_hlc(100, counter=2) > make_hlc(100, counter=1)
|
||||
|
||||
def test_equal_wall_time_and_counter_breaks_tie_on_node_id(
|
||||
self, make_hlc: Callable[..., Hlc]
|
||||
) -> None:
|
||||
"""Equal wall time and counter breaks tie on node id."""
|
||||
assert make_hlc(100, counter=1, node_id="b") > make_hlc(
|
||||
100, counter=1, node_id="a"
|
||||
)
|
||||
|
||||
def test_identical_clocks_compare_equal(self, make_hlc: Callable[..., Hlc]) -> None:
|
||||
"""Identical clocks compare equal."""
|
||||
assert make_hlc(100, counter=1, node_id="a") == make_hlc(
|
||||
100, counter=1, node_id="a"
|
||||
)
|
||||
|
||||
|
||||
class TestNewTick:
|
||||
"""New tick."""
|
||||
|
||||
def test_first_tick_has_counter_zero(self) -> None:
|
||||
"""First tick has counter zero."""
|
||||
tick = Hlc.new_tick("node-a", wall_time_ms=1000)
|
||||
assert tick == Hlc(wall_time_ms=1000, counter=0, node_id="node-a")
|
||||
|
||||
def test_advancing_wall_clock_resets_counter(
|
||||
self, make_hlc: Callable[..., Hlc]
|
||||
) -> None:
|
||||
"""Advancing wall clock resets counter."""
|
||||
previous = make_hlc(1000, counter=5)
|
||||
tick = Hlc.new_tick("node-a", previous=previous, wall_time_ms=2000)
|
||||
assert tick == Hlc(wall_time_ms=2000, counter=0, node_id="node-a")
|
||||
@ -59,7 +49,6 @@ class TestNewTick:
|
||||
def test_stalled_wall_clock_increments_counter(
|
||||
self, make_hlc: Callable[..., Hlc]
|
||||
) -> None:
|
||||
"""Stalled wall clock increments counter."""
|
||||
previous = make_hlc(1000, counter=5)
|
||||
tick = Hlc.new_tick("node-a", previous=previous, wall_time_ms=1000)
|
||||
assert tick == Hlc(wall_time_ms=1000, counter=6, node_id="node-a")
|
||||
@ -67,32 +56,26 @@ class TestNewTick:
|
||||
def test_regressed_wall_clock_still_advances_monotonically(
|
||||
self, make_hlc: Callable[..., Hlc]
|
||||
) -> None:
|
||||
"""Regressed wall clock still advances monotonically."""
|
||||
previous = make_hlc(1000, counter=5)
|
||||
tick = Hlc.new_tick("node-a", previous=previous, wall_time_ms=500)
|
||||
assert tick == Hlc(wall_time_ms=1000, counter=6, node_id="node-a")
|
||||
|
||||
def test_defaults_to_the_real_clock_when_unset(self) -> None:
|
||||
"""Defaults to the real clock when unset."""
|
||||
tick = Hlc.new_tick("node-a")
|
||||
assert tick.node_id == "node-a"
|
||||
assert tick.wall_time_ms > 0
|
||||
|
||||
|
||||
class TestStringRoundTrip:
|
||||
"""String round trip."""
|
||||
|
||||
def test_round_trips_through_to_str_and_from_str(
|
||||
self, make_hlc: Callable[..., Hlc]
|
||||
) -> None:
|
||||
"""Round trips through to str and from str."""
|
||||
original = make_hlc(1_751_000_123_456, counter=7, node_id="phone")
|
||||
assert Hlc.from_str(original.to_str()) == original
|
||||
|
||||
def test_to_str_is_lexicographically_sortable_by_wall_time(
|
||||
self, make_hlc: Callable[..., Hlc]
|
||||
) -> None:
|
||||
"""To str is lexicographically sortable by wall time."""
|
||||
earlier = make_hlc(1000)
|
||||
later = make_hlc(2000)
|
||||
assert earlier.to_str() < later.to_str()
|
||||
@ -100,22 +83,18 @@ class TestStringRoundTrip:
|
||||
def test_to_str_is_lexicographically_sortable_by_counter(
|
||||
self, make_hlc: Callable[..., Hlc]
|
||||
) -> None:
|
||||
"""To str is lexicographically sortable by counter."""
|
||||
lower = make_hlc(1000, counter=1)
|
||||
higher = make_hlc(1000, counter=200)
|
||||
assert lower.to_str() < higher.to_str()
|
||||
|
||||
def test_from_str_rejects_a_missing_z_separator(self) -> None:
|
||||
"""From str rejects a missing z separator."""
|
||||
with pytest.raises(ValueError, match="not a valid Hlc string"):
|
||||
Hlc.from_str("not-a-valid-clock-string-at-all")
|
||||
|
||||
def test_from_str_rejects_a_wrong_length_iso_prefix(self) -> None:
|
||||
"""From str rejects a wrong length iso prefix."""
|
||||
with pytest.raises(ValueError, match="not a valid Hlc string"):
|
||||
Hlc.from_str("2026-07-05T12:00:00Z-0000-node-a")
|
||||
|
||||
def test_from_str_rejects_a_missing_node_id_separator(self) -> None:
|
||||
"""From str rejects a missing node id separator."""
|
||||
with pytest.raises(ValueError, match="not a valid Hlc string"):
|
||||
Hlc.from_str("2026-07-05T12:00:00.000Z-0000")
|
||||
|
||||
@ -13,12 +13,9 @@ if TYPE_CHECKING:
|
||||
|
||||
|
||||
class TestMergeLogs:
|
||||
"""Merge logs."""
|
||||
|
||||
def test_returns_the_union_of_disjoint_ids(
|
||||
self, make_hlc: Callable[..., Hlc]
|
||||
) -> None:
|
||||
"""Returns the union of disjoint ids."""
|
||||
local = {"a": Record(id="a", fields={"text": ("a", make_hlc(100))})}
|
||||
remote = {"b": Record(id="b", fields={"text": ("b", make_hlc(100))})}
|
||||
assert merge_logs(local, remote) == {**local, **remote}
|
||||
@ -26,7 +23,6 @@ class TestMergeLogs:
|
||||
def test_merges_a_shared_id_field_by_field(
|
||||
self, make_hlc: Callable[..., Hlc]
|
||||
) -> None:
|
||||
"""Merges a shared id field by field."""
|
||||
local = {"a": Record(id="a", fields={"text": ("old", make_hlc(100))})}
|
||||
remote = {"a": Record(id="a", fields={"text": ("new", make_hlc(200))})}
|
||||
merged = merge_logs(local, remote)
|
||||
@ -35,7 +31,6 @@ class TestMergeLogs:
|
||||
def test_a_delete_on_one_side_survives_the_merge(
|
||||
self, make_hlc: Callable[..., Hlc]
|
||||
) -> None:
|
||||
"""A delete on one side survives the merge."""
|
||||
local = {
|
||||
"a": Record(id="a", fields={}, deleted=True, deleted_hlc=make_hlc(200))
|
||||
}
|
||||
@ -43,7 +38,6 @@ class TestMergeLogs:
|
||||
assert merge_logs(local, remote)["a"].deleted is True
|
||||
|
||||
def test_does_not_mutate_either_input(self, make_hlc: Callable[..., Hlc]) -> None:
|
||||
"""Does not mutate either input."""
|
||||
local = {"a": Record(id="a", fields={"text": ("a", make_hlc(100))})}
|
||||
remote = {"b": Record(id="b", fields={"text": ("b", make_hlc(100))})}
|
||||
local_before = dict(local)
|
||||
@ -54,8 +48,6 @@ class TestMergeLogs:
|
||||
|
||||
|
||||
class TestConvergenceProperties:
|
||||
"""Convergence properties."""
|
||||
|
||||
def _sample_logs(self, make_hlc: Callable[..., Hlc]) -> tuple[Log, Log]:
|
||||
a = {
|
||||
"shared": Record(
|
||||
@ -72,19 +64,16 @@ class TestConvergenceProperties:
|
||||
return a, b
|
||||
|
||||
def test_is_commutative(self, make_hlc: Callable[..., Hlc]) -> None:
|
||||
"""Is commutative."""
|
||||
a, b = self._sample_logs(make_hlc)
|
||||
assert merge_logs(a, b) == merge_logs(b, a)
|
||||
|
||||
def test_is_idempotent(self, make_hlc: Callable[..., Hlc]) -> None:
|
||||
"""Is idempotent."""
|
||||
a, _ = self._sample_logs(make_hlc)
|
||||
assert merge_logs(a, a) == a
|
||||
|
||||
def test_repeated_merge_of_the_same_remote_is_a_no_op(
|
||||
self, make_hlc: Callable[..., Hlc]
|
||||
) -> None:
|
||||
"""Repeated merge of the same remote is a no op."""
|
||||
a, b = self._sample_logs(make_hlc)
|
||||
once = merge_logs(a, b)
|
||||
twice = merge_logs(once, b)
|
||||
|
||||
@ -14,17 +14,115 @@ 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
|
||||
|
||||
|
||||
class FakeStore:
|
||||
"""A scriptable in-memory store that can be told to fail."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
files: dict[str, str] | None = None,
|
||||
*,
|
||||
failing: bool = False,
|
||||
) -> None:
|
||||
"""Start holding ``files``, failing every call if ``failing``."""
|
||||
self.files = dict(files or {})
|
||||
self.failing = failing
|
||||
self.writes: list[str] = []
|
||||
|
||||
def _guard(self, what: str) -> None:
|
||||
if self.failing:
|
||||
msg = f"{what} failed"
|
||||
raise RemoteSyncError(msg)
|
||||
|
||||
def list_directory(self, path: str) -> list[str]:
|
||||
"""Return the distinct first segments under ``path``."""
|
||||
self._guard("list")
|
||||
prefix = f"{path}/"
|
||||
return sorted(
|
||||
{
|
||||
key[len(prefix) :].split("/")[0]
|
||||
for key in self.files
|
||||
if key.startswith(prefix)
|
||||
}
|
||||
)
|
||||
|
||||
def get_file_text(self, path: str) -> str | None:
|
||||
"""Return the stored text, if any."""
|
||||
self._guard("read")
|
||||
return self.files.get(path)
|
||||
|
||||
def put_file_text(self, path: str, text: str, *, message: str) -> None:
|
||||
"""Store ``text`` at ``path``."""
|
||||
del message
|
||||
self._guard("write")
|
||||
self.writes.append(path)
|
||||
self.files[path] = text
|
||||
|
||||
def get_string_map(self, path: str) -> dict[str, str]:
|
||||
"""Return the direct children of ``path`` as a flat map."""
|
||||
self._guard("map read")
|
||||
prefix = f"{path}/"
|
||||
return {
|
||||
key[len(prefix) :]: value
|
||||
for key, value in self.files.items()
|
||||
if key.startswith(prefix)
|
||||
}
|
||||
|
||||
def delete_file(self, path: str, *, message: str = "") -> None:
|
||||
"""Remove ``path`` if present."""
|
||||
del message
|
||||
self._guard("delete")
|
||||
self.files.pop(path, None)
|
||||
|
||||
def can_access_remote(self) -> bool:
|
||||
"""Return whether this backend is currently healthy."""
|
||||
return not self.failing
|
||||
|
||||
|
||||
class FakeStoreWithoutBulkRead:
|
||||
"""A store with no bulk-map read, standing in for GitHub.
|
||||
|
||||
Composes rather than subclasses :class:`FakeStore`, because a subclass
|
||||
would inherit ``get_string_map`` -- the capability this fake must lack.
|
||||
"""
|
||||
|
||||
def __init__(self, files: dict[str, str] | None = None) -> None:
|
||||
"""Wrap a plain :class:`FakeStore` holding ``files``."""
|
||||
self._inner = FakeStore(files)
|
||||
|
||||
@property
|
||||
def files(self) -> dict[str, str]:
|
||||
"""The wrapped store's contents."""
|
||||
return self._inner.files
|
||||
|
||||
def list_directory(self, path: str) -> list[str]:
|
||||
"""Delegate to the wrapped store."""
|
||||
return self._inner.list_directory(path)
|
||||
|
||||
def get_file_text(self, path: str) -> str | None:
|
||||
"""Delegate to the wrapped store."""
|
||||
return self._inner.get_file_text(path)
|
||||
|
||||
def put_file_text(self, path: str, text: str, *, message: str) -> None:
|
||||
"""Delegate to the wrapped store."""
|
||||
self._inner.put_file_text(path, text, message=message)
|
||||
|
||||
def delete_file(self, path: str, *, message: str = "") -> None:
|
||||
"""Delegate to the wrapped store."""
|
||||
self._inner.delete_file(path, message=message)
|
||||
|
||||
def can_access_remote(self) -> bool:
|
||||
"""Delegate to the wrapped store."""
|
||||
return self._inner.can_access_remote()
|
||||
|
||||
|
||||
def _mirror(
|
||||
@ -46,10 +144,7 @@ def _mirror(
|
||||
|
||||
|
||||
class TestWrites:
|
||||
"""Writes."""
|
||||
|
||||
def test_go_to_both_backends(self) -> None:
|
||||
"""Go to both backends."""
|
||||
client, primary, mirror, _ = _mirror()
|
||||
client.put_file_text("ns/pc/log.json", "{}", message="m")
|
||||
assert primary.writes == ["ns/pc/log.json"]
|
||||
@ -58,20 +153,17 @@ class TestWrites:
|
||||
def test_a_primary_failure_fails_the_tick(self) -> None:
|
||||
# Fail-closed: the primary is authoritative, so a sync that could not
|
||||
# write it must not be reported as successful.
|
||||
"""A primary failure fails the tick."""
|
||||
client, _, _, _ = _mirror(primary_failing=True)
|
||||
with pytest.raises(RemoteSyncError):
|
||||
client.put_file_text("ns/pc/log.json", "{}", message="m")
|
||||
|
||||
def test_a_mirror_failure_is_loud_but_survivable(self) -> None:
|
||||
"""A mirror failure is loud but survivable."""
|
||||
client, primary, _, failures = _mirror(mirror_failing=True)
|
||||
client.put_file_text("ns/pc/log.json", "{}", message="m")
|
||||
assert primary.writes == ["ns/pc/log.json"]
|
||||
assert failures == ["put_file_text ns/pc/log.json"]
|
||||
|
||||
def test_deletes_behave_the_same_way(self) -> None:
|
||||
"""Deletes behave the same way."""
|
||||
client, primary, _, failures = _mirror(
|
||||
primary_files={"ns/pc/log.json": "{}"},
|
||||
mirror_files={"ns/pc/log.json": "{}"},
|
||||
@ -82,17 +174,13 @@ class TestWrites:
|
||||
assert failures == ["delete_file ns/pc/log.json"]
|
||||
|
||||
def test_a_primary_delete_failure_fails_the_tick(self) -> None:
|
||||
"""A primary delete failure fails the tick."""
|
||||
client, _, _, _ = _mirror(primary_failing=True)
|
||||
with pytest.raises(RemoteSyncError):
|
||||
client.delete_file("ns/pc/log.json")
|
||||
|
||||
|
||||
class TestReads:
|
||||
"""Reads."""
|
||||
|
||||
def test_prefer_the_primary_when_it_has_the_file(self) -> None:
|
||||
"""Prefer the primary when it has the file."""
|
||||
client, _, _, _ = _mirror(
|
||||
primary_files={"ns/pc/log.json": "from-primary"},
|
||||
mirror_files={"ns/pc/log.json": "from-mirror"},
|
||||
@ -103,17 +191,14 @@ class TestReads:
|
||||
# Why reads are not primary-only: a migrated PC must still see an
|
||||
# un-migrated phone's writes, or convergence silently becomes
|
||||
# one-directional with no error raised.
|
||||
"""Fall back to the mirror for an unmigrated device."""
|
||||
client, _, _, _ = _mirror(mirror_files={"ns/phone/log.json": "from-mirror"})
|
||||
assert client.get_file_text("ns/phone/log.json") == "from-mirror"
|
||||
|
||||
def test_return_none_when_neither_backend_has_the_file(self) -> None:
|
||||
"""Return none when neither backend has the file."""
|
||||
client, _, _, _ = _mirror()
|
||||
assert client.get_file_text("ns/nobody/log.json") is None
|
||||
|
||||
def test_a_mirror_read_failure_degrades_to_the_primary(self) -> None:
|
||||
"""A mirror read failure degrades to the primary."""
|
||||
client, _, _, failures = _mirror(mirror_failing=True)
|
||||
assert client.get_file_text("ns/pc/log.json") is None
|
||||
assert failures == ["get_file_text ns/pc/log.json"]
|
||||
@ -125,17 +210,13 @@ class TestReads:
|
||||
# mirror does not hold the file, so neither side has an answer. A
|
||||
# primary failure alone no longer fails the read -- see
|
||||
# TestPrimaryReadFallback.
|
||||
"""A primary read failure with nothing in the mirror raises."""
|
||||
client, _, _, _ = _mirror(primary_failing=True)
|
||||
with pytest.raises(RemoteSyncError):
|
||||
client.get_file_text("ns/pc/log.json")
|
||||
|
||||
|
||||
class TestListDirectory:
|
||||
"""List directory."""
|
||||
|
||||
def test_unions_devices_from_both_backends(self) -> None:
|
||||
"""Unions devices from both backends."""
|
||||
client, _, _, _ = _mirror(
|
||||
primary_files={"ns/pc/log.json": "{}"},
|
||||
mirror_files={"ns/phone/log.json": "{}"},
|
||||
@ -143,7 +224,6 @@ class TestListDirectory:
|
||||
assert sorted(client.list_directory("ns")) == ["pc", "phone"]
|
||||
|
||||
def test_does_not_duplicate_a_device_present_in_both(self) -> None:
|
||||
"""Does not duplicate a device present in both."""
|
||||
client, _, _, _ = _mirror(
|
||||
primary_files={"ns/pc/log.json": "{}"},
|
||||
mirror_files={"ns/pc/log.json": "{}"},
|
||||
@ -151,7 +231,6 @@ class TestListDirectory:
|
||||
assert client.list_directory("ns") == ["pc"]
|
||||
|
||||
def test_a_mirror_failure_degrades_to_the_primary_list(self) -> None:
|
||||
"""A mirror failure degrades to the primary list."""
|
||||
client, _, _, failures = _mirror(
|
||||
primary_files={"ns/pc/log.json": "{}"}, mirror_failing=True
|
||||
)
|
||||
@ -163,7 +242,6 @@ class TestListDirectory:
|
||||
# the mirror's devices. This used to raise, which made a primary
|
||||
# outage look like "no devices exist" -- the union read silently
|
||||
# degrading to nothing, precisely when the fallback was needed.
|
||||
"""A primary failure degrades to the mirror list."""
|
||||
client, _, _, _ = _mirror(
|
||||
primary_failing=True, mirror_files={"ns/phone/log.json": "{}"}
|
||||
)
|
||||
@ -172,7 +250,6 @@ class TestListDirectory:
|
||||
def test_both_backends_failing_raises(self) -> None:
|
||||
# With no answer from either side, fail closed: an empty list is
|
||||
# indistinguishable from "no devices", and callers act on that.
|
||||
"""Both backends failing raises."""
|
||||
client, _, _, _ = _mirror(primary_failing=True, mirror_failing=True)
|
||||
with pytest.raises(RemoteSyncError):
|
||||
client.list_directory("ns")
|
||||
@ -182,14 +259,12 @@ 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")
|
||||
@ -199,20 +274,17 @@ class TestPrimaryReadFallback:
|
||||
) -> 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")
|
||||
@ -224,7 +296,6 @@ class TestPrimaryReadFallback:
|
||||
# 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(),
|
||||
@ -235,7 +306,6 @@ class TestPrimaryReadFallback:
|
||||
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")
|
||||
@ -244,10 +314,7 @@ class TestPrimaryReadFallback:
|
||||
|
||||
|
||||
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"},
|
||||
@ -261,7 +328,6 @@ class TestRevisionMaps:
|
||||
}
|
||||
|
||||
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
|
||||
)
|
||||
@ -269,7 +335,6 @@ class TestRevisionMaps:
|
||||
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"}),
|
||||
@ -277,7 +342,6 @@ class TestRevisionMaps:
|
||||
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()
|
||||
)
|
||||
@ -285,12 +349,9 @@ class TestRevisionMaps:
|
||||
|
||||
|
||||
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)
|
||||
@ -300,24 +361,19 @@ class TestLifecycle:
|
||||
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()
|
||||
|
||||
@ -335,28 +391,20 @@ class TestEndToEndThroughSyncLog:
|
||||
}
|
||||
|
||||
sync_log(
|
||||
SyncTarget(
|
||||
client=github,
|
||||
device_id="phone",
|
||||
path_prefix="ns/devices",
|
||||
),
|
||||
log("from-phone", "node-phone"),
|
||||
LogCodec(
|
||||
decode=load_log,
|
||||
encode=dump_log,
|
||||
),
|
||||
client=github,
|
||||
device_id="phone",
|
||||
path_prefix="ns/devices",
|
||||
local_log=log("from-phone", "node-phone"),
|
||||
encode=dump_log,
|
||||
decode=load_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,
|
||||
),
|
||||
client=MirrorSyncClient(firebase, github),
|
||||
device_id="pc",
|
||||
path_prefix="ns/devices",
|
||||
local_log=log("from-pc", "node-pc"),
|
||||
encode=dump_log,
|
||||
decode=load_log,
|
||||
)
|
||||
assert {"from-phone", "from-pc"} <= set(merged)
|
||||
# The pc's merged result is mirrored back to GitHub, so the
|
||||
|
||||
@ -13,10 +13,7 @@ if TYPE_CHECKING:
|
||||
|
||||
|
||||
class TestMergeField:
|
||||
"""Merge field."""
|
||||
|
||||
def test_greater_hlc_wins(self, make_hlc: Callable[..., Hlc]) -> None:
|
||||
"""Greater HLC wins."""
|
||||
older = ("a", make_hlc(100))
|
||||
newer = ("b", make_hlc(200))
|
||||
assert merge_field(older, newer) == newer
|
||||
@ -25,7 +22,6 @@ class TestMergeField:
|
||||
def test_equal_hlc_keeps_the_first_argument(
|
||||
self, make_hlc: Callable[..., Hlc]
|
||||
) -> None:
|
||||
"""Equal HLC keeps the first argument."""
|
||||
clock = make_hlc(100)
|
||||
a = ("a", clock)
|
||||
b = ("a", clock)
|
||||
@ -33,17 +29,13 @@ class TestMergeField:
|
||||
|
||||
|
||||
class TestMergeRecord:
|
||||
"""Merge record."""
|
||||
|
||||
def test_raises_when_ids_differ(self) -> None:
|
||||
"""Raises when ids differ."""
|
||||
a = Record(id="a", fields={})
|
||||
b = Record(id="b", fields={})
|
||||
with pytest.raises(ValueError, match="different ids"):
|
||||
merge_record(a, b)
|
||||
|
||||
def test_merges_disjoint_fields(self, make_hlc: Callable[..., Hlc]) -> None:
|
||||
"""Merges disjoint fields."""
|
||||
a = Record(id="x", fields={"text": ("hello", make_hlc(100))})
|
||||
b = Record(id="x", fields={"priority": ("high", make_hlc(50))})
|
||||
merged = merge_record(a, b)
|
||||
@ -55,7 +47,6 @@ class TestMergeRecord:
|
||||
def test_shared_field_keeps_the_later_write(
|
||||
self, make_hlc: Callable[..., Hlc]
|
||||
) -> None:
|
||||
"""Shared field keeps the later write."""
|
||||
a = Record(id="x", fields={"text": ("old", make_hlc(100))})
|
||||
b = Record(id="x", fields={"text": ("new", make_hlc(200))})
|
||||
merged = merge_record(a, b)
|
||||
@ -64,14 +55,12 @@ class TestMergeRecord:
|
||||
def test_delete_is_sticky_against_an_older_non_deleted_copy(
|
||||
self, make_hlc: Callable[..., Hlc]
|
||||
) -> None:
|
||||
"""Delete is sticky against an older non deleted copy."""
|
||||
deleted = Record(id="x", fields={}, deleted=True, deleted_hlc=make_hlc(200))
|
||||
stale = Record(id="x", fields={"text": ("resurrected", make_hlc(100))})
|
||||
assert merge_record(deleted, stale).deleted is True
|
||||
assert merge_record(stale, deleted).deleted is True
|
||||
|
||||
def test_neither_side_deleted_stays_not_deleted(self) -> None:
|
||||
"""Neither side deleted stays not deleted."""
|
||||
a = Record(id="x", fields={})
|
||||
b = Record(id="x", fields={})
|
||||
merged = merge_record(a, b)
|
||||
@ -81,7 +70,6 @@ class TestMergeRecord:
|
||||
def test_both_sides_deleted_keeps_the_later_delete_clock(
|
||||
self, make_hlc: Callable[..., Hlc]
|
||||
) -> None:
|
||||
"""Both sides deleted keeps the later delete clock."""
|
||||
a = Record(id="x", fields={}, deleted=True, deleted_hlc=make_hlc(100))
|
||||
b = Record(id="x", fields={}, deleted=True, deleted_hlc=make_hlc(200))
|
||||
merged = merge_record(a, b)
|
||||
@ -90,17 +78,12 @@ class TestMergeRecord:
|
||||
def test_both_deleted_but_one_side_missing_a_clock_keeps_the_other(
|
||||
self, make_hlc: Callable[..., Hlc]
|
||||
) -> None:
|
||||
"""Both deleted but one side missing a clock keeps the other."""
|
||||
a = Record(id="x", fields={}, deleted=True, deleted_hlc=None)
|
||||
b = Record(id="x", fields={}, deleted=True, deleted_hlc=make_hlc(200))
|
||||
assert merge_record(a, b).deleted_hlc == make_hlc(200)
|
||||
# Swapping the operands is the property under test: merge_record
|
||||
# must give the same answer either way round.
|
||||
# pylint: disable-next=arguments-out-of-order
|
||||
assert merge_record(b, a).deleted_hlc == make_hlc(200)
|
||||
|
||||
def test_is_commutative(self, make_hlc: Callable[..., Hlc]) -> None:
|
||||
"""Is commutative."""
|
||||
record_a = Record(id="x", fields={"text": ("a", make_hlc(100))})
|
||||
record_b = Record(
|
||||
id="x", fields={"text": ("b", make_hlc(200)), "extra": ("e", make_hlc(1))}
|
||||
@ -108,28 +91,22 @@ class TestMergeRecord:
|
||||
assert merge_record(record_a, record_b) == merge_record(record_b, record_a)
|
||||
|
||||
def test_is_idempotent(self, make_hlc: Callable[..., Hlc]) -> None:
|
||||
"""Is idempotent."""
|
||||
record = Record(id="x", fields={"text": ("a", make_hlc(100))})
|
||||
assert merge_record(record, record) == record
|
||||
|
||||
|
||||
class TestRecordDictRoundTrip:
|
||||
"""Record dict round trip."""
|
||||
|
||||
def test_round_trips_a_record_with_fields(
|
||||
self, make_hlc: Callable[..., Hlc]
|
||||
) -> None:
|
||||
"""Round trips a record with fields."""
|
||||
record = Record(id="x", fields={"text": ("hello", make_hlc(100, node_id="pc"))})
|
||||
assert Record.from_dict(record.to_dict()) == record
|
||||
|
||||
def test_round_trips_a_deleted_record(self, make_hlc: Callable[..., Hlc]) -> None:
|
||||
"""Round trips a deleted record."""
|
||||
record = Record(id="x", fields={}, deleted=True, deleted_hlc=make_hlc(200))
|
||||
assert Record.from_dict(record.to_dict()) == record
|
||||
|
||||
def test_round_trips_a_record_with_no_delete_clock(self) -> None:
|
||||
"""Round trips a record with no delete clock."""
|
||||
record = Record(id="x", fields={}, deleted=False, deleted_hlc=None)
|
||||
assert Record.from_dict(record.to_dict()) == record
|
||||
|
||||
@ -147,7 +124,6 @@ class TestCrossLanguageWireFormat:
|
||||
"""
|
||||
|
||||
def test_matches_the_fixture_shared_with_the_dart_package(self) -> None:
|
||||
"""Matches the fixture shared with the dart package."""
|
||||
record = Record(
|
||||
id="abc123",
|
||||
fields={"text": ("hello", Hlc(wall_time_ms=100, counter=0, node_id="pc"))},
|
||||
|
||||
@ -30,33 +30,25 @@ def _sample_log(make_hlc: Callable[..., Hlc]) -> Log:
|
||||
|
||||
|
||||
class TestDumpLoad:
|
||||
"""Dump load."""
|
||||
|
||||
def test_round_trips_a_log(self, make_hlc: Callable[..., Hlc]) -> None:
|
||||
"""Round trips a log."""
|
||||
log = _sample_log(make_hlc)
|
||||
assert load_log(dump_log(log)) == log
|
||||
|
||||
def test_load_raises_on_non_json(self) -> None:
|
||||
# json.loads raises JSONDecodeError (a ValueError subclass).
|
||||
"""Load raises on non JSON."""
|
||||
with pytest.raises(json.JSONDecodeError):
|
||||
load_log("{not json")
|
||||
|
||||
def test_load_raises_typeerror_on_wrong_shape(self) -> None:
|
||||
# Valid JSON, but a list where an id->record map is expected.
|
||||
"""Load raises typeerror on wrong shape."""
|
||||
with pytest.raises(TypeError):
|
||||
load_log("[]")
|
||||
|
||||
|
||||
class TestReadWrite:
|
||||
"""Read write."""
|
||||
|
||||
def test_write_then_read_round_trips(
|
||||
self, tmp_path: Path, make_hlc: Callable[..., Hlc]
|
||||
) -> None:
|
||||
"""Write then read round trips."""
|
||||
log = _sample_log(make_hlc)
|
||||
path = tmp_path / "nested" / "log.json"
|
||||
write_log(path, log)
|
||||
@ -65,7 +57,6 @@ class TestReadWrite:
|
||||
def test_write_creates_parent_directories(
|
||||
self, tmp_path: Path, make_hlc: Callable[..., Hlc]
|
||||
) -> None:
|
||||
"""Write creates parent directories."""
|
||||
path = tmp_path / "deep" / "nested" / "log.json"
|
||||
write_log(path, _sample_log(make_hlc))
|
||||
assert path.exists()
|
||||
@ -73,24 +64,20 @@ class TestReadWrite:
|
||||
def test_write_overwrites_atomically(
|
||||
self, tmp_path: Path, make_hlc: Callable[..., Hlc]
|
||||
) -> None:
|
||||
"""Write overwrites atomically."""
|
||||
path = tmp_path / "log.json"
|
||||
write_log(path, {"a": Record(id="a", fields={})})
|
||||
write_log(path, _sample_log(make_hlc))
|
||||
assert set(read_log(path)) == {"a", "b"}
|
||||
|
||||
def test_read_of_missing_file_is_empty(self, tmp_path: Path) -> None:
|
||||
"""Read of missing file is empty."""
|
||||
assert read_log(tmp_path / "nope.json") == {}
|
||||
|
||||
def test_read_of_corrupt_file_is_empty(self, tmp_path: Path) -> None:
|
||||
"""Read of corrupt file is empty."""
|
||||
path = tmp_path / "log.json"
|
||||
path.write_text("{not json", encoding="utf-8")
|
||||
assert read_log(path) == {}
|
||||
|
||||
def test_read_of_wrong_shape_file_is_empty(self, tmp_path: Path) -> None:
|
||||
"""Read of wrong shape file is empty."""
|
||||
path = tmp_path / "log.json"
|
||||
path.write_text("[]", encoding="utf-8")
|
||||
assert read_log(path) == {}
|
||||
|
||||
@ -7,13 +7,7 @@ import logging
|
||||
from typing import TYPE_CHECKING
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from crdt_sync import (
|
||||
GitHubSyncClient,
|
||||
LogCodec,
|
||||
Record,
|
||||
SyncTarget,
|
||||
sync_log,
|
||||
)
|
||||
from crdt_sync import GitHubSyncClient, Record, sync_log
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
@ -50,26 +44,19 @@ def _mock_client(
|
||||
|
||||
|
||||
class TestSyncLog:
|
||||
"""Sync log."""
|
||||
|
||||
def test_pushes_local_log_when_no_other_devices_have_synced(
|
||||
self, make_hlc: Callable[..., Hlc]
|
||||
) -> None:
|
||||
"""Pushes local log when no other devices have synced."""
|
||||
local_log = {"a": Record(id="a", fields={"text": ("hello", make_hlc(100))})}
|
||||
client = _mock_client()
|
||||
|
||||
merged = sync_log(
|
||||
SyncTarget(
|
||||
client=client,
|
||||
device_id="pc",
|
||||
path_prefix="devices",
|
||||
),
|
||||
local_log,
|
||||
LogCodec(
|
||||
decode=_decode,
|
||||
encode=_encode,
|
||||
),
|
||||
client=client,
|
||||
device_id="pc",
|
||||
path_prefix="devices",
|
||||
local_log=local_log,
|
||||
encode=_encode,
|
||||
decode=_decode,
|
||||
)
|
||||
|
||||
assert merged == local_log
|
||||
@ -77,22 +64,17 @@ class TestSyncLog:
|
||||
assert client.put_file_text.call_args.args[0] == "devices/pc/log.json"
|
||||
|
||||
def test_skips_its_own_device_id_when_listing(self) -> None:
|
||||
"""Skips its own device id when listing."""
|
||||
client = _mock_client(
|
||||
devices=("pc", "phone"), files={"devices/phone/log.json": "{}"}
|
||||
)
|
||||
|
||||
sync_log(
|
||||
SyncTarget(
|
||||
client=client,
|
||||
device_id="pc",
|
||||
path_prefix="devices",
|
||||
),
|
||||
{},
|
||||
LogCodec(
|
||||
decode=_decode,
|
||||
encode=_encode,
|
||||
),
|
||||
client=client,
|
||||
device_id="pc",
|
||||
path_prefix="devices",
|
||||
local_log={},
|
||||
encode=_encode,
|
||||
decode=_decode,
|
||||
)
|
||||
|
||||
client.get_file_text.assert_called_once_with("devices/phone/log.json")
|
||||
@ -109,17 +91,13 @@ class TestSyncLog:
|
||||
)
|
||||
|
||||
sync_log(
|
||||
SyncTarget(
|
||||
client=client,
|
||||
device_id="new-uuid",
|
||||
legacy_device_id="pc",
|
||||
path_prefix="devices",
|
||||
),
|
||||
{},
|
||||
LogCodec(
|
||||
decode=_decode,
|
||||
encode=_encode,
|
||||
),
|
||||
client=client,
|
||||
device_id="new-uuid",
|
||||
path_prefix="devices",
|
||||
local_log={},
|
||||
encode=_encode,
|
||||
decode=_decode,
|
||||
legacy_device_id="pc",
|
||||
)
|
||||
|
||||
client.get_file_text.assert_called_once_with("devices/phone/log.json")
|
||||
@ -131,38 +109,29 @@ class TestSyncLog:
|
||||
)
|
||||
|
||||
sync_log(
|
||||
SyncTarget(
|
||||
client=client,
|
||||
device_id="new-uuid",
|
||||
path_prefix="devices",
|
||||
),
|
||||
{},
|
||||
LogCodec(
|
||||
decode=_decode,
|
||||
encode=_encode,
|
||||
),
|
||||
client=client,
|
||||
device_id="new-uuid",
|
||||
path_prefix="devices",
|
||||
local_log={},
|
||||
encode=_encode,
|
||||
decode=_decode,
|
||||
)
|
||||
|
||||
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,
|
||||
),
|
||||
client=client,
|
||||
device_id="pc",
|
||||
path_prefix="devices",
|
||||
local_log={},
|
||||
encode=_encode,
|
||||
decode=_decode,
|
||||
)
|
||||
|
||||
assert not merged
|
||||
assert merged == {}
|
||||
|
||||
def test_skips_a_device_whose_pushed_file_is_corrupt(
|
||||
self, caplog: pytest.LogCaptureFixture
|
||||
@ -177,19 +146,15 @@ class TestSyncLog:
|
||||
|
||||
with caplog.at_level(logging.WARNING):
|
||||
merged = sync_log(
|
||||
SyncTarget(
|
||||
client=client,
|
||||
device_id="pc",
|
||||
path_prefix="devices",
|
||||
),
|
||||
{},
|
||||
LogCodec(
|
||||
decode=_decode,
|
||||
encode=_encode,
|
||||
),
|
||||
client=client,
|
||||
device_id="pc",
|
||||
path_prefix="devices",
|
||||
local_log={},
|
||||
encode=_encode,
|
||||
decode=_decode,
|
||||
)
|
||||
|
||||
assert not merged
|
||||
assert merged == {}
|
||||
assert "Unparsable log" in caplog.text
|
||||
|
||||
def test_skips_a_device_whose_pushed_json_has_the_wrong_shape(self) -> None:
|
||||
@ -204,24 +169,19 @@ class TestSyncLog:
|
||||
)
|
||||
|
||||
merged = sync_log(
|
||||
SyncTarget(
|
||||
client=client,
|
||||
device_id="pc",
|
||||
path_prefix="devices",
|
||||
),
|
||||
{},
|
||||
LogCodec(
|
||||
decode=_decode,
|
||||
encode=_encode,
|
||||
),
|
||||
client=client,
|
||||
device_id="pc",
|
||||
path_prefix="devices",
|
||||
local_log={},
|
||||
encode=_encode,
|
||||
decode=_decode,
|
||||
)
|
||||
|
||||
assert not merged
|
||||
assert merged == {}
|
||||
|
||||
def test_merges_in_a_remote_devices_entries(
|
||||
self, make_hlc: Callable[..., Hlc]
|
||||
) -> None:
|
||||
"""Merges in a remote devices entries."""
|
||||
remote_log = {
|
||||
"b": Record(id="b", fields={"text": ("from phone", make_hlc(100))})
|
||||
}
|
||||
@ -231,37 +191,28 @@ class TestSyncLog:
|
||||
)
|
||||
|
||||
merged = sync_log(
|
||||
SyncTarget(
|
||||
client=client,
|
||||
device_id="pc",
|
||||
path_prefix="devices",
|
||||
),
|
||||
{},
|
||||
LogCodec(
|
||||
decode=_decode,
|
||||
encode=_encode,
|
||||
),
|
||||
client=client,
|
||||
device_id="pc",
|
||||
path_prefix="devices",
|
||||
local_log={},
|
||||
encode=_encode,
|
||||
decode=_decode,
|
||||
)
|
||||
|
||||
assert merged == remote_log
|
||||
|
||||
def test_uses_a_custom_filename_and_commit_message(self) -> None:
|
||||
"""Uses a custom filename and commit message."""
|
||||
client = _mock_client()
|
||||
|
||||
sync_log(
|
||||
SyncTarget(
|
||||
client=client,
|
||||
device_id="pc",
|
||||
path_prefix="devices",
|
||||
),
|
||||
{},
|
||||
LogCodec(
|
||||
commit_message="custom message",
|
||||
decode=_decode,
|
||||
encode=_encode,
|
||||
filename="notes.json",
|
||||
),
|
||||
client=client,
|
||||
device_id="pc",
|
||||
path_prefix="devices",
|
||||
local_log={},
|
||||
encode=_encode,
|
||||
decode=_decode,
|
||||
filename="notes.json",
|
||||
commit_message="custom message",
|
||||
)
|
||||
|
||||
client.put_file_text.assert_called_once_with(
|
||||
|
||||
@ -19,19 +19,15 @@ from crdt_sync import (
|
||||
FileSyncStateStore,
|
||||
Hlc,
|
||||
Log,
|
||||
LogCodec,
|
||||
MemorySyncStateStore,
|
||||
Record,
|
||||
RevisionTracking,
|
||||
SyncState,
|
||||
SyncTarget,
|
||||
default_revs_path,
|
||||
dump_log,
|
||||
load_log,
|
||||
revision_of,
|
||||
sync_log,
|
||||
)
|
||||
from crdt_sync.tests.conftest import FakeStore, FakeStoreWithoutBulkRead
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
@ -54,8 +50,107 @@ _encode = dump_log
|
||||
_decode = load_log
|
||||
|
||||
|
||||
FakeRemote = FakeStore
|
||||
FakeRemoteWithoutBulkRead = FakeStoreWithoutBulkRead
|
||||
class FakeRemote:
|
||||
"""An in-memory store that also serves revision maps in one read.
|
||||
|
||||
Stands in for :class:`crdt_sync.FirebaseSyncClient`, counting every call
|
||||
so tests can assert on traffic rather than only on results.
|
||||
"""
|
||||
|
||||
def __init__(self, files: dict[str, str] | None = None) -> None:
|
||||
"""Start holding ``files``, with empty call logs."""
|
||||
self.files = dict(files or {})
|
||||
self.reads: list[str] = []
|
||||
self.writes: list[str] = []
|
||||
|
||||
def list_directory(self, path: str) -> list[str]:
|
||||
"""Return the distinct first segments under ``path``."""
|
||||
prefix = f"{path}/"
|
||||
return sorted(
|
||||
{
|
||||
key[len(prefix) :].split("/")[0]
|
||||
for key in self.files
|
||||
if key.startswith(prefix)
|
||||
}
|
||||
)
|
||||
|
||||
def get_file_text(self, path: str) -> str | None:
|
||||
"""Return the stored text, recording the read."""
|
||||
self.reads.append(path)
|
||||
return self.files.get(path)
|
||||
|
||||
def put_file_text(self, path: str, text: str, *, message: str) -> None:
|
||||
"""Store ``text``, recording the write."""
|
||||
del message
|
||||
self.writes.append(path)
|
||||
self.files[path] = text
|
||||
|
||||
def get_string_map(self, path: str) -> dict[str, str]:
|
||||
"""Return the direct children of ``path`` as a flat map."""
|
||||
prefix = f"{path}/"
|
||||
return {
|
||||
key[len(prefix) :]: value
|
||||
for key, value in self.files.items()
|
||||
if key.startswith(prefix)
|
||||
}
|
||||
|
||||
def delete_file(self, path: str, *, message: str = "") -> None:
|
||||
"""Remove ``path`` if present."""
|
||||
del message
|
||||
self.files.pop(path, None)
|
||||
|
||||
def can_access_remote(self) -> bool:
|
||||
"""Always reachable."""
|
||||
return True
|
||||
|
||||
|
||||
class FakeRemoteWithoutBulkRead:
|
||||
"""A store with no bulk-map read, standing in for GitHub.
|
||||
|
||||
Revision tracking must degrade to "fetch everything", not break.
|
||||
Composes rather than subclasses :class:`FakeRemote`, because a subclass
|
||||
would inherit ``get_string_map`` -- the very capability this fake exists
|
||||
to lack.
|
||||
"""
|
||||
|
||||
def __init__(self, files: dict[str, str] | None = None) -> None:
|
||||
"""Wrap a plain :class:`FakeRemote` holding ``files``."""
|
||||
self._inner = FakeRemote(files)
|
||||
|
||||
@property
|
||||
def files(self) -> dict[str, str]:
|
||||
"""The wrapped store's contents."""
|
||||
return self._inner.files
|
||||
|
||||
@property
|
||||
def reads(self) -> list[str]:
|
||||
"""The wrapped store's read log."""
|
||||
return self._inner.reads
|
||||
|
||||
@property
|
||||
def writes(self) -> list[str]:
|
||||
"""The wrapped store's write log."""
|
||||
return self._inner.writes
|
||||
|
||||
def list_directory(self, path: str) -> list[str]:
|
||||
"""Delegate to the wrapped store."""
|
||||
return self._inner.list_directory(path)
|
||||
|
||||
def get_file_text(self, path: str) -> str | None:
|
||||
"""Delegate to the wrapped store."""
|
||||
return self._inner.get_file_text(path)
|
||||
|
||||
def put_file_text(self, path: str, text: str, *, message: str) -> None:
|
||||
"""Delegate to the wrapped store."""
|
||||
self._inner.put_file_text(path, text, message=message)
|
||||
|
||||
def delete_file(self, path: str, *, message: str = "") -> None:
|
||||
"""Delegate to the wrapped store."""
|
||||
self._inner.delete_file(path, message=message)
|
||||
|
||||
def can_access_remote(self) -> bool:
|
||||
"""Delegate to the wrapped store."""
|
||||
return self._inner.can_access_remote()
|
||||
|
||||
|
||||
def _tick(
|
||||
@ -65,84 +160,59 @@ def _tick(
|
||||
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,
|
||||
),
|
||||
client=remote,
|
||||
device_id=device_id,
|
||||
path_prefix="ns/devices",
|
||||
local_log=local or {},
|
||||
encode=_encode,
|
||||
decode=_decode,
|
||||
state_store=store,
|
||||
)
|
||||
|
||||
|
||||
class TestRevisionOf:
|
||||
"""Revision of."""
|
||||
|
||||
def test_is_stable_for_identical_content(self) -> None:
|
||||
"""Is stable for identical content."""
|
||||
assert revision_of('{"a":1}') == revision_of('{"a":1}')
|
||||
|
||||
def test_differs_for_different_content(self) -> None:
|
||||
"""Differs for different content."""
|
||||
assert revision_of('{"a":1}') != revision_of('{"a":2}')
|
||||
|
||||
|
||||
class TestDefaultRevsPath:
|
||||
"""Default revs path."""
|
||||
|
||||
def test_is_a_sibling_of_the_device_directory(self) -> None:
|
||||
"""Is a sibling of the device directory."""
|
||||
assert default_revs_path("diet-guard-sync/devices") == ("diet-guard-sync/revs")
|
||||
assert default_revs_path("todo-sync/notes") == "todo-sync/revs"
|
||||
|
||||
def test_falls_back_to_a_child_when_there_is_no_parent(self) -> None:
|
||||
"""Falls back to a child when there is no parent."""
|
||||
assert default_revs_path("ns") == "ns/revs"
|
||||
|
||||
|
||||
class TestSyncState:
|
||||
"""Sync state."""
|
||||
|
||||
def test_round_trips_through_json(self) -> None:
|
||||
"""Round trips through JSON."""
|
||||
state = SyncState(pushed_rev="abc", peer_revs={"phone": "def"})
|
||||
assert SyncState.from_json(state.to_json()) == state
|
||||
|
||||
def test_tolerates_a_missing_peer_map(self) -> None:
|
||||
"""Tolerates a missing peer map."""
|
||||
assert not SyncState.from_json({}).peer_revs
|
||||
assert SyncState.from_json({}).peer_revs == {}
|
||||
|
||||
def test_drops_malformed_peer_entries(self) -> None:
|
||||
"""Drops malformed peer entries."""
|
||||
state = SyncState.from_json({"peer_revs": {"phone": 42}})
|
||||
assert not state.peer_revs
|
||||
assert state.peer_revs == {}
|
||||
|
||||
def test_ignores_a_non_dict_peer_map(self) -> None:
|
||||
"""Ignores a non dict peer map."""
|
||||
assert not SyncState.from_json({"peer_revs": "nonsense"}).peer_revs
|
||||
assert SyncState.from_json({"peer_revs": "nonsense"}).peer_revs == {}
|
||||
|
||||
def test_ignores_a_non_string_pushed_rev(self) -> None:
|
||||
"""Ignores a non string pushed rev."""
|
||||
assert SyncState.from_json({"pushed_rev": 42}).pushed_rev is None
|
||||
|
||||
|
||||
class TestNoOpPushSuppression:
|
||||
"""No op push suppression."""
|
||||
|
||||
def test_pushes_and_publishes_a_revision_on_the_first_tick(self) -> None:
|
||||
"""Pushes and publishes a revision on the first tick."""
|
||||
remote = FakeRemote()
|
||||
_tick(remote, MemorySyncStateStore(), _log("a", "1"))
|
||||
assert remote.writes == ["ns/devices/pc/log.json", "ns/revs/pc"]
|
||||
|
||||
def test_a_second_unchanged_tick_writes_nothing(self) -> None:
|
||||
"""A second unchanged tick writes nothing."""
|
||||
remote = FakeRemote()
|
||||
store = MemorySyncStateStore()
|
||||
local = _log("a", "1")
|
||||
@ -153,7 +223,6 @@ class TestNoOpPushSuppression:
|
||||
assert not remote.writes
|
||||
|
||||
def test_a_changed_log_pushes_again(self) -> None:
|
||||
"""A changed log pushes again."""
|
||||
remote = FakeRemote()
|
||||
store = MemorySyncStateStore()
|
||||
_tick(remote, store, _log("a", "1"))
|
||||
@ -162,7 +231,6 @@ class TestNoOpPushSuppression:
|
||||
assert "ns/devices/pc/log.json" in remote.writes
|
||||
|
||||
def test_without_a_state_store_every_tick_pushes(self) -> None:
|
||||
"""Without a state store every tick pushes."""
|
||||
remote = FakeRemote()
|
||||
local = _log("a", "1")
|
||||
_tick(remote, None, local)
|
||||
@ -172,10 +240,7 @@ class TestNoOpPushSuppression:
|
||||
|
||||
|
||||
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(
|
||||
{
|
||||
@ -188,7 +253,6 @@ class TestPeerDownloadSuppression:
|
||||
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(
|
||||
{
|
||||
@ -205,7 +269,6 @@ class TestPeerDownloadSuppression:
|
||||
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(
|
||||
{
|
||||
@ -228,7 +291,6 @@ class TestPeerDownloadSuppression:
|
||||
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",
|
||||
@ -244,18 +306,15 @@ class TestPeerDownloadSuppression:
|
||||
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")),
|
||||
@ -267,12 +326,9 @@ class TestPeerDownloadSuppression:
|
||||
|
||||
|
||||
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()
|
||||
@ -284,12 +340,9 @@ class TestBackendsWithoutBulkMapReads:
|
||||
|
||||
|
||||
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(
|
||||
@ -300,55 +353,38 @@ class TestRevisionPublishingOrder:
|
||||
# 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(),
|
||||
),
|
||||
client=remote,
|
||||
device_id="pc",
|
||||
path_prefix="ns/devices",
|
||||
local_log=_log("a", "1"),
|
||||
encode=_encode,
|
||||
decode=_decode,
|
||||
state_store=MemorySyncStateStore(),
|
||||
revs_path="custom/place",
|
||||
)
|
||||
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,
|
||||
),
|
||||
client=remote,
|
||||
device_id="phone",
|
||||
path_prefix="ns/devices",
|
||||
local_log=_log("b", "from-phone", "node-phone"),
|
||||
encode=_encode,
|
||||
decode=_decode,
|
||||
state_store=phone_store,
|
||||
)
|
||||
assert {"a", "b"} <= set(phone)
|
||||
pc_after = _tick(remote, pc_store, pc)
|
||||
@ -356,23 +392,18 @@ class TestTwoDevicesConverge:
|
||||
|
||||
|
||||
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()
|
||||
@ -380,7 +411,6 @@ class TestFileSyncStateStore:
|
||||
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()
|
||||
@ -388,7 +418,6 @@ class TestFileSyncStateStore:
|
||||
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")
|
||||
@ -400,7 +429,6 @@ class TestFileSyncStateStore:
|
||||
|
||||
@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
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
[project]
|
||||
name = "crdt-sync"
|
||||
version = "0.9.0"
|
||||
version = "0.8.1"
|
||||
description = "Shared CRDT merge scheme + GitHub-Contents-API sync transport for cross-device apps"
|
||||
requires-python = ">=3.10"
|
||||
dependencies = ["requests"]
|
||||
|
||||
@ -27,11 +27,8 @@ import sys
|
||||
from crdt_sync import (
|
||||
FirebaseConfig,
|
||||
Hlc,
|
||||
LogCodec,
|
||||
MemorySyncStateStore,
|
||||
Record,
|
||||
RevisionTracking,
|
||||
SyncTarget,
|
||||
dump_log,
|
||||
firebase_client_for,
|
||||
load_log,
|
||||
@ -55,12 +52,10 @@ def main() -> int:
|
||||
|
||||
client = firebase_client_for("interop", config=FirebaseConfig.load())
|
||||
merged = sync_log(
|
||||
SyncTarget(
|
||||
client=client,
|
||||
device_id=_DEVICE_ID,
|
||||
path_prefix=_PATH_PREFIX,
|
||||
),
|
||||
{
|
||||
client=client,
|
||||
device_id=_DEVICE_ID,
|
||||
path_prefix=_PATH_PREFIX,
|
||||
local_log={
|
||||
"py-rec": Record(
|
||||
id="py-rec",
|
||||
fields={
|
||||
@ -71,13 +66,9 @@ def main() -> int:
|
||||
},
|
||||
)
|
||||
},
|
||||
LogCodec(
|
||||
decode=load_log,
|
||||
encode=dump_log,
|
||||
),
|
||||
RevisionTracking(
|
||||
state_store=MemorySyncStateStore(),
|
||||
),
|
||||
encode=dump_log,
|
||||
decode=load_log,
|
||||
state_store=MemorySyncStateStore(),
|
||||
)
|
||||
|
||||
_logger.info("python sees records: %s", sorted(merged))
|
||||
|
||||
Loading…
Reference in New Issue
Block a user