mirror of
https://github.com/kuhyx/utils.git
synced 2026-11-24 07:06:28 +01:00
Compare commits
9 Commits
a7bccb34bb
...
7637e46c6f
| Author | SHA1 | Date | |
|---|---|---|---|
| 7637e46c6f | |||
| 0861aebda9 | |||
| 6d64f9e3c9 | |||
| 1af1d3005b | |||
| d8e962fdf0 | |||
| 11fc417556 | |||
| 7dd0174fd4 | |||
| 0de2a96155 | |||
| e5a3d1eda7 |
@ -15,8 +15,6 @@ import logging
|
||||
from typing import TYPE_CHECKING
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from crdt_sync.tests.test_tool_google_id_token import (
|
||||
_CLIENT_CREDENTIAL,
|
||||
_CLIENT_ID,
|
||||
@ -27,6 +25,8 @@ from tool import google_id_token as git
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def test_main_prints_the_token_when_no_output_is_given(
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
|
||||
134
crdt-sync/crdt_sync/tests/test_tool_interop_seed.py
Normal file
134
crdt-sync/crdt_sync/tests/test_tool_interop_seed.py
Normal file
@ -0,0 +1,134 @@
|
||||
"""Tests for ``tool/interop_seed``, the Python half of the interop check.
|
||||
|
||||
Patched at the module's own boundary -- ``firebase_client_for``,
|
||||
``FirebaseConfig.load`` and ``sync_log`` -- so nothing touches Firebase. What
|
||||
is worth asserting here is not that ``sync_log`` works (``test_sync.py`` covers
|
||||
that) but that this tool hands it *exactly* the shape the Dart side looks for:
|
||||
the seed exists to make ``crdt_sync_dart/tool/interop_check.dart`` pass, and a
|
||||
drifted path prefix, device id or record id would make the two halves silently
|
||||
miss each other, which is the failure the pair exists to catch.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import TYPE_CHECKING
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from crdt_sync import Hlc, Record
|
||||
from tool import interop_seed
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Iterator
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def seeded() -> Iterator[tuple[int, MagicMock, MagicMock, MagicMock]]:
|
||||
"""Run ``main()`` with the network boundary mocked out.
|
||||
|
||||
Yields the exit code plus the three mocks whose call arguments are what
|
||||
the assertions below are actually about.
|
||||
"""
|
||||
with (
|
||||
patch.object(interop_seed, "firebase_client_for") as client_for,
|
||||
patch.object(interop_seed.FirebaseConfig, "load") as load,
|
||||
patch.object(interop_seed, "sync_log", return_value={"py-rec": None}) as synced,
|
||||
):
|
||||
code = interop_seed.main()
|
||||
yield code, synced, client_for, load
|
||||
|
||||
|
||||
def test_main_reports_success(seeded: tuple) -> None:
|
||||
"""A successful seed is exit code 0."""
|
||||
code, _, _, _ = seeded
|
||||
|
||||
assert code == 0
|
||||
|
||||
|
||||
def test_the_client_is_built_for_the_interop_app_from_the_shared_config(
|
||||
seeded: tuple,
|
||||
) -> None:
|
||||
"""The app name selects the credential cache; interop has its own."""
|
||||
_, _, client_for, load = seeded
|
||||
|
||||
load.assert_called_once_with()
|
||||
assert client_for.call_args.args == ("interop",)
|
||||
assert client_for.call_args.kwargs["config"] is load.return_value
|
||||
|
||||
|
||||
def test_the_target_matches_what_the_dart_checker_reads(seeded: tuple) -> None:
|
||||
"""The path prefix and device id the Dart half looks under.
|
||||
|
||||
``interop_check.dart`` reads ``_interop/devices``; a drift on either side
|
||||
makes the check fail as "Python wrote nothing" rather than as a mismatch.
|
||||
"""
|
||||
_, synced, client_for, _ = seeded
|
||||
target = synced.call_args.args[0]
|
||||
|
||||
assert target.path_prefix == "_interop/devices"
|
||||
assert target.device_id == "pydev"
|
||||
assert target.client is client_for.return_value
|
||||
|
||||
|
||||
def test_the_seeded_record_is_the_one_the_dart_side_asserts_on(
|
||||
seeded: tuple,
|
||||
) -> None:
|
||||
"""py-rec, with the value and Hlc the Dart checker compares against."""
|
||||
_, synced, _, _ = seeded
|
||||
records = synced.call_args.args[1]
|
||||
|
||||
assert set(records) == {"py-rec"}
|
||||
record = records["py-rec"]
|
||||
assert isinstance(record, Record)
|
||||
assert record.id == "py-rec"
|
||||
value, hlc = record.fields["value"]
|
||||
assert value == "written-by-python"
|
||||
assert hlc == Hlc(wall_time_ms=1000, counter=0, node_id="node-py")
|
||||
|
||||
|
||||
def test_the_librarys_own_codec_is_used_rather_than_a_local_one(
|
||||
seeded: tuple,
|
||||
) -> None:
|
||||
"""Reimplementing the encoding here would test the wrong thing.
|
||||
|
||||
The check is that what the real apps write is what the other language
|
||||
reads, so the codec must be the library's canonical pair.
|
||||
"""
|
||||
_, synced, _, _ = seeded
|
||||
codec = synced.call_args.args[2]
|
||||
|
||||
assert codec.decode is interop_seed.load_log
|
||||
assert codec.encode is interop_seed.dump_log
|
||||
|
||||
|
||||
def test_revision_state_is_in_memory_so_reruns_reseed(seeded: tuple) -> None:
|
||||
"""A persisted cursor would make a second run write nothing.
|
||||
|
||||
The Dart half deletes both devices' data on its way out, so the seed has
|
||||
to be repeatable; remembering a revision across runs would break that.
|
||||
"""
|
||||
_, synced, _, _ = seeded
|
||||
tracking = synced.call_args.args[3]
|
||||
|
||||
assert isinstance(tracking.state_store, interop_seed.MemorySyncStateStore)
|
||||
|
||||
|
||||
def test_main_reports_what_python_can_see_and_the_next_command(
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
"""The output is the operator's only signal that the seed landed."""
|
||||
with (
|
||||
patch.object(interop_seed, "firebase_client_for"),
|
||||
patch.object(interop_seed.FirebaseConfig, "load"),
|
||||
patch.object(
|
||||
interop_seed, "sync_log", return_value={"py-rec": None, "a": None}
|
||||
),
|
||||
caplog.at_level(logging.INFO, logger="interop-seed"),
|
||||
):
|
||||
interop_seed.main()
|
||||
|
||||
messages = [record.getMessage() for record in caplog.records]
|
||||
assert any("['a', 'py-rec']" in message for message in messages)
|
||||
assert any("dart run tool/interop_check.dart" in message for message in messages)
|
||||
196
crdt-sync/crdt_sync/tests/test_tool_link_google.py
Normal file
196
crdt-sync/crdt_sync/tests/test_tool_link_google.py
Normal file
@ -0,0 +1,196 @@
|
||||
"""Tests for token inspection and linking in ``tool/link_google``.
|
||||
|
||||
``main()`` and ``_read_token`` are covered in
|
||||
:mod:`test_tool_link_google_main`, split to stay under the 250-line cap.
|
||||
|
||||
The failure this whole script exists to prevent is silent: linking onto a
|
||||
*new* account succeeds at the auth layer and then has every read and write
|
||||
denied by rules that pin one uid. So the two assertions that matter most here
|
||||
are that the existing account's ``idToken`` is always sent (omitting it turns
|
||||
the call into "sign in or sign up") and that a mismatched uid is a hard error.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import json
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
import requests
|
||||
|
||||
from crdt_sync import FirebaseConfig
|
||||
from tool import link_google as lg
|
||||
|
||||
_UID = "the-uid-pinned-in-the-rules"
|
||||
_CONFIG = FirebaseConfig(
|
||||
api_key="AIzaSyAthisIsTheWebApiKeyFormat",
|
||||
database_url="https://project-default-rtdb.firebasedatabase.app",
|
||||
project_id="the-project",
|
||||
uid=_UID,
|
||||
email="sync@example.com",
|
||||
)
|
||||
|
||||
|
||||
def _jwt(claims: dict[str, object]) -> str:
|
||||
"""Build an unsigned JWT carrying ``claims`` as its payload."""
|
||||
payload = base64.urlsafe_b64encode(json.dumps(claims).encode()).decode()
|
||||
return f"header.{payload.rstrip('=')}.signature"
|
||||
|
||||
|
||||
def _google_token(**overrides: object) -> str:
|
||||
"""A plausible Google ID token, with individual claims overridden."""
|
||||
claims = {
|
||||
"iss": "https://accounts.google.com",
|
||||
"email": "person@gmail.com",
|
||||
"aud": "the-web-client-id.apps.googleusercontent.com",
|
||||
}
|
||||
return _jwt({**claims, **overrides})
|
||||
|
||||
|
||||
def _response(*, ok: bool = True, status: int = 200, body: object = None) -> MagicMock:
|
||||
"""Fake a ``requests`` response from accounts:signInWithIdp."""
|
||||
response = MagicMock()
|
||||
response.ok = ok
|
||||
response.status_code = status
|
||||
response.text = "" if ok else '{"error": {"message": "INVALID_IDP_RESPONSE"}}'
|
||||
response.json.return_value = body if body is not None else {"localId": _UID}
|
||||
return response
|
||||
|
||||
|
||||
def _config_with_password() -> MagicMock:
|
||||
"""A config whose password is supplied rather than read from disk.
|
||||
|
||||
``read_password()`` falls back to the real ``~/.config/crdt-sync/
|
||||
password``, so the plain dataclass passes only on a machine that happens
|
||||
to have one -- by reading the user's own password. CI caught that.
|
||||
"""
|
||||
config = MagicMock(spec=FirebaseConfig)
|
||||
config.api_key = _CONFIG.api_key
|
||||
config.email = _CONFIG.email
|
||||
config.uid = _CONFIG.uid
|
||||
config.read_password.return_value = "the-stored-password"
|
||||
return config
|
||||
|
||||
|
||||
def _auth_provider() -> MagicMock:
|
||||
"""A token provider that signs in and yields the account's ID token."""
|
||||
auth = MagicMock()
|
||||
auth.id_token.return_value = "the-existing-account-id-token"
|
||||
return auth
|
||||
|
||||
|
||||
def test_linking_returns_the_unchanged_uid() -> None:
|
||||
"""The happy path: same uid before and after."""
|
||||
with (
|
||||
patch.object(lg, "FirebaseTokenProvider", return_value=_auth_provider()),
|
||||
patch.object(lg.requests, "post", return_value=_response()) as posted,
|
||||
):
|
||||
result = lg.link_google(_config_with_password(), _google_token())
|
||||
|
||||
assert result == _UID
|
||||
assert posted.call_count == 1
|
||||
|
||||
|
||||
def test_the_existing_id_token_is_always_sent() -> None:
|
||||
"""Omitting it makes the same endpoint create a brand-new account.
|
||||
|
||||
That is the silent failure the whole script exists to prevent, so it is
|
||||
asserted on the request body rather than inferred from the response.
|
||||
"""
|
||||
with (
|
||||
patch.object(lg, "FirebaseTokenProvider", return_value=_auth_provider()),
|
||||
patch.object(lg.requests, "post", return_value=_response()) as posted,
|
||||
):
|
||||
lg.link_google(_config_with_password(), "the-google-token")
|
||||
|
||||
sent = posted.call_args.kwargs["json"]
|
||||
assert sent["idToken"] == "the-existing-account-id-token"
|
||||
assert "id_token=the-google-token" in sent["postBody"]
|
||||
assert "providerId=google.com" in sent["postBody"]
|
||||
assert sent["returnSecureToken"] is True
|
||||
|
||||
|
||||
def test_the_account_password_is_used_to_prove_ownership() -> None:
|
||||
"""Linking requires proving ownership of the account being linked to."""
|
||||
auth = _auth_provider()
|
||||
config = _config_with_password()
|
||||
|
||||
with (
|
||||
patch.object(lg, "FirebaseTokenProvider", return_value=auth),
|
||||
patch.object(lg.requests, "post", return_value=_response()),
|
||||
):
|
||||
lg.link_google(config, _google_token())
|
||||
|
||||
auth.sign_in.assert_called_once_with(_CONFIG.email, "the-stored-password")
|
||||
|
||||
|
||||
def test_linking_onto_a_different_uid_is_a_hard_failure() -> None:
|
||||
"""The decisive check.
|
||||
|
||||
A different uid authenticates perfectly and is then denied every read and
|
||||
write, so the message has to say that outright and name the remedy.
|
||||
"""
|
||||
body = {"localId": "a-brand-new-uid"}
|
||||
|
||||
with (
|
||||
patch.object(lg, "FirebaseTokenProvider", return_value=_auth_provider()),
|
||||
patch.object(lg.requests, "post", return_value=_response(body=body)),
|
||||
pytest.raises(lg.LinkError, match="LINKED THE WRONG ACCOUNT"),
|
||||
):
|
||||
lg.link_google(_config_with_password(), _google_token())
|
||||
|
||||
|
||||
def test_the_wrong_account_message_names_the_unlink_remedy() -> None:
|
||||
"""Knowing it failed is not enough; the console step is not obvious."""
|
||||
with (
|
||||
patch.object(lg, "FirebaseTokenProvider", return_value=_auth_provider()),
|
||||
patch.object(
|
||||
lg.requests, "post", return_value=_response(body={"localId": "x"})
|
||||
),
|
||||
pytest.raises(lg.LinkError, match="Unlink this Google identity"),
|
||||
):
|
||||
lg.link_google(_config_with_password(), _google_token())
|
||||
|
||||
|
||||
def test_a_response_without_a_local_id_is_rejected() -> None:
|
||||
"""No uid at all must not read as a successful link."""
|
||||
with (
|
||||
patch.object(lg, "FirebaseTokenProvider", return_value=_auth_provider()),
|
||||
patch.object(lg.requests, "post", return_value=_response(body={})),
|
||||
pytest.raises(lg.LinkError, match="no localId"),
|
||||
):
|
||||
lg.link_google(_config_with_password(), _google_token())
|
||||
|
||||
|
||||
def test_a_rejected_link_reports_the_status_and_body() -> None:
|
||||
"""Firebase's own message is the only clue to why it refused."""
|
||||
response = _response(ok=False, status=400)
|
||||
|
||||
with (
|
||||
patch.object(lg, "FirebaseTokenProvider", return_value=_auth_provider()),
|
||||
patch.object(lg.requests, "post", return_value=response),
|
||||
pytest.raises(lg.LinkError, match="HTTP 400"),
|
||||
):
|
||||
lg.link_google(_config_with_password(), _google_token())
|
||||
|
||||
|
||||
def test_a_network_error_is_wrapped_as_a_link_error() -> None:
|
||||
"""A bare requests exception would escape main()'s handler."""
|
||||
with (
|
||||
patch.object(lg, "FirebaseTokenProvider", return_value=_auth_provider()),
|
||||
patch.object(lg.requests, "post", side_effect=requests.Timeout("timed out")),
|
||||
pytest.raises(lg.LinkError, match="network error"),
|
||||
):
|
||||
lg.link_google(_config_with_password(), _google_token())
|
||||
|
||||
|
||||
def test_the_timeout_is_passed_through() -> None:
|
||||
"""A hung link would otherwise block the run indefinitely."""
|
||||
with (
|
||||
patch.object(lg, "FirebaseTokenProvider", return_value=_auth_provider()),
|
||||
patch.object(lg.requests, "post", return_value=_response()) as posted,
|
||||
):
|
||||
lg.link_google(_config_with_password(), _google_token(), timeout_seconds=5)
|
||||
|
||||
assert posted.call_args.kwargs["timeout"] == 5
|
||||
223
crdt-sync/crdt_sync/tests/test_tool_link_google_main.py
Normal file
223
crdt-sync/crdt_sync/tests/test_tool_link_google_main.py
Normal file
@ -0,0 +1,223 @@
|
||||
"""Tests for ``_read_token`` and ``main()`` in ``tool/link_google``.
|
||||
|
||||
Split from :mod:`test_tool_link_google` to stay under the 250-line cap.
|
||||
|
||||
``main()`` catches three exception types by name rather than with a bare
|
||||
``except Exception``, deliberately, so that an unanticipated bug still
|
||||
surfaces as a traceback instead of a tidy "FAIL" line. That distinction is
|
||||
asserted here: the three named failures return 1, and anything else escapes.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import logging
|
||||
from typing import TYPE_CHECKING
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from crdt_sync._config import ConfigError
|
||||
from crdt_sync._firebase_auth import FirebaseAuthError
|
||||
from crdt_sync.tests.test_tool_link_google import _CONFIG, _UID, _google_token
|
||||
from tool import link_google as lg
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def _args(
|
||||
token: str | None = None, token_file: str | None = None
|
||||
) -> argparse.Namespace:
|
||||
"""Build the namespace ``_read_token`` reads."""
|
||||
return argparse.Namespace(
|
||||
google_id_token=token,
|
||||
google_id_token_file=token_file,
|
||||
)
|
||||
|
||||
|
||||
def test_a_token_is_read_from_the_command_line() -> None:
|
||||
"""The inline form."""
|
||||
assert lg._read_token(_args("the-token")) == "the-token"
|
||||
|
||||
|
||||
def test_a_token_is_read_from_a_file(tmp_path: Path) -> None:
|
||||
"""The file form, which is what the paired minting tool writes."""
|
||||
path = tmp_path / "token.txt"
|
||||
path.write_text("the-token", encoding="utf-8")
|
||||
|
||||
assert lg._read_token(_args(token_file=str(path))) == "the-token"
|
||||
|
||||
|
||||
def test_a_trailing_newline_is_stripped(tmp_path: Path) -> None:
|
||||
"""A token written by a file or heredoc picks one up.
|
||||
|
||||
Firebase rejects it with an unhelpful message, so stripping here is what
|
||||
keeps that from becoming a debugging session.
|
||||
"""
|
||||
path = tmp_path / "token.txt"
|
||||
path.write_text("the-token\n", encoding="utf-8")
|
||||
|
||||
assert lg._read_token(_args(token_file=str(path))) == "the-token"
|
||||
|
||||
|
||||
def test_an_unreadable_token_file_is_reported_by_path(tmp_path: Path) -> None:
|
||||
"""Naming the path is the difference between a fix and a guess."""
|
||||
missing = tmp_path / "absent.txt"
|
||||
|
||||
with pytest.raises(lg.LinkError, match="could not be read"):
|
||||
lg._read_token(_args(token_file=str(missing)))
|
||||
|
||||
|
||||
def test_an_empty_token_is_rejected(tmp_path: Path) -> None:
|
||||
"""An empty file would otherwise be sent to Firebase as a valid request."""
|
||||
path = tmp_path / "token.txt"
|
||||
path.write_text(" \n", encoding="utf-8")
|
||||
|
||||
with pytest.raises(lg.LinkError, match="is empty"):
|
||||
lg._read_token(_args(token_file=str(path)))
|
||||
|
||||
|
||||
def test_an_empty_inline_token_is_rejected() -> None:
|
||||
"""Same check, the other input route."""
|
||||
with pytest.raises(lg.LinkError, match="is empty"):
|
||||
lg._read_token(_args(""))
|
||||
|
||||
|
||||
def test_main_links_and_reports_the_unchanged_uid(
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
"""The happy path: exit 0, and the uid echoed so it can be eyeballed."""
|
||||
with (
|
||||
patch.object(lg.FirebaseConfig, "load", return_value=_CONFIG),
|
||||
patch.object(lg, "link_google", return_value=_UID) as linked,
|
||||
caplog.at_level(logging.INFO, logger="link_google"),
|
||||
):
|
||||
code = lg.main(["--google-id-token", _google_token()])
|
||||
|
||||
assert code == 0
|
||||
assert linked.call_count == 1
|
||||
assert "uid unchanged" in caplog.text
|
||||
assert _UID in caplog.text
|
||||
|
||||
|
||||
def test_main_describes_the_token_before_linking(
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
"""The operator's chance to abort on the wrong Google account."""
|
||||
with (
|
||||
patch.object(lg.FirebaseConfig, "load", return_value=_CONFIG),
|
||||
patch.object(lg, "link_google", return_value=_UID),
|
||||
caplog.at_level(logging.INFO, logger="link_google"),
|
||||
):
|
||||
lg.main(["--google-id-token", _google_token()])
|
||||
|
||||
assert "person@gmail.com" in caplog.text
|
||||
assert "linking onto sync@example.com" in caplog.text
|
||||
|
||||
|
||||
def test_main_points_at_the_verification_step(
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
"""Linking is only half the job; the preflight is what confirms it."""
|
||||
with (
|
||||
patch.object(lg.FirebaseConfig, "load", return_value=_CONFIG),
|
||||
patch.object(lg, "link_google", return_value=_UID),
|
||||
caplog.at_level(logging.INFO, logger="link_google"),
|
||||
):
|
||||
lg.main(["--google-id-token", _google_token()])
|
||||
|
||||
assert "tool/preflight_firebase.py" in caplog.text
|
||||
|
||||
|
||||
def test_main_reads_the_token_from_a_file(tmp_path: Path) -> None:
|
||||
"""The --google-id-token-file route reaches link_google intact."""
|
||||
path = tmp_path / "token.txt"
|
||||
token = _google_token()
|
||||
path.write_text(f"{token}\n", encoding="utf-8")
|
||||
|
||||
with (
|
||||
patch.object(lg.FirebaseConfig, "load", return_value=_CONFIG),
|
||||
patch.object(lg, "link_google", return_value=_UID) as linked,
|
||||
):
|
||||
code = lg.main(["--google-id-token-file", str(path)])
|
||||
|
||||
assert code == 0
|
||||
assert linked.call_args.args[1] == token
|
||||
|
||||
|
||||
def test_main_returns_1_on_a_link_error(caplog: pytest.LogCaptureFixture) -> None:
|
||||
"""The uid mismatch and every other LinkError."""
|
||||
with (
|
||||
patch.object(lg.FirebaseConfig, "load", return_value=_CONFIG),
|
||||
patch.object(lg, "link_google", side_effect=lg.LinkError("wrong account")),
|
||||
caplog.at_level(logging.INFO, logger="link_google"),
|
||||
):
|
||||
code = lg.main(["--google-id-token", _google_token()])
|
||||
|
||||
assert code == 1
|
||||
assert "FAIL" in caplog.text
|
||||
|
||||
|
||||
def test_main_returns_1_on_a_config_error(caplog: pytest.LogCaptureFixture) -> None:
|
||||
"""An unusable firebase.json is a reported failure, not a traceback."""
|
||||
with (
|
||||
patch.object(lg.FirebaseConfig, "load", side_effect=ConfigError("no config")),
|
||||
caplog.at_level(logging.INFO, logger="link_google"),
|
||||
):
|
||||
code = lg.main(["--google-id-token", _google_token()])
|
||||
|
||||
assert code == 1
|
||||
assert "FAIL" in caplog.text
|
||||
|
||||
|
||||
def test_main_returns_1_on_an_auth_error(caplog: pytest.LogCaptureFixture) -> None:
|
||||
"""A rejected password, the third named failure."""
|
||||
with (
|
||||
patch.object(lg.FirebaseConfig, "load", return_value=_CONFIG),
|
||||
patch.object(lg, "link_google", side_effect=FirebaseAuthError("bad password")),
|
||||
caplog.at_level(logging.INFO, logger="link_google"),
|
||||
):
|
||||
code = lg.main(["--google-id-token", _google_token()])
|
||||
|
||||
assert code == 1
|
||||
assert "FAIL" in caplog.text
|
||||
|
||||
|
||||
def test_main_rejects_a_malformed_token_before_touching_the_network() -> None:
|
||||
"""The local shape check exists to save a round trip; prove it does."""
|
||||
with (
|
||||
patch.object(lg.FirebaseConfig, "load") as load,
|
||||
patch.object(lg, "link_google") as linked,
|
||||
):
|
||||
code = lg.main(["--google-id-token", "not-a-jwt"])
|
||||
|
||||
assert code == 1
|
||||
load.assert_not_called()
|
||||
linked.assert_not_called()
|
||||
|
||||
|
||||
def test_an_unexpected_error_is_not_swallowed() -> None:
|
||||
"""The reason the handler names its three types instead of Exception.
|
||||
|
||||
A tidy "FAIL" line for an unanticipated bug would hide it; a traceback
|
||||
is the point.
|
||||
"""
|
||||
with (
|
||||
patch.object(lg.FirebaseConfig, "load", return_value=_CONFIG),
|
||||
patch.object(lg, "link_google", side_effect=RuntimeError("a real bug")),
|
||||
pytest.raises(RuntimeError, match="a real bug"),
|
||||
):
|
||||
lg.main(["--google-id-token", _google_token()])
|
||||
|
||||
|
||||
def test_the_two_token_sources_are_mutually_exclusive() -> None:
|
||||
"""Passing both is a user error argparse should catch, not a silent pick."""
|
||||
with pytest.raises(SystemExit):
|
||||
lg.main(["--google-id-token", "a", "--google-id-token-file", "b"])
|
||||
|
||||
|
||||
def test_one_token_source_is_required() -> None:
|
||||
"""With neither, there is nothing to link."""
|
||||
with pytest.raises(SystemExit):
|
||||
lg.main([])
|
||||
81
crdt-sync/crdt_sync/tests/test_tool_link_google_token.py
Normal file
81
crdt-sync/crdt_sync/tests/test_tool_link_google_token.py
Normal file
@ -0,0 +1,81 @@
|
||||
"""Tests for ``describe_google_token`` in ``tool/link_google``.
|
||||
|
||||
Split from :mod:`test_tool_link_google` (which covers linking) and
|
||||
:mod:`test_tool_link_google_main` (the CLI) to stay under the 250-line cap.
|
||||
|
||||
These are the local, pre-network checks. They exist so a misconfiguration
|
||||
reports itself here rather than as an opaque Firebase rejection, so what is
|
||||
asserted is the *message* -- naming what was pasted by mistake is the entire
|
||||
value of the check.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
|
||||
import pytest
|
||||
|
||||
from crdt_sync.tests.test_tool_link_google import _google_token, _jwt
|
||||
from tool import link_google as lg
|
||||
|
||||
|
||||
def test_a_token_that_is_not_three_parts_is_rejected() -> None:
|
||||
"""An access token or an auth code pasted by mistake.
|
||||
|
||||
The message names both, because that is the actual confusion -- the
|
||||
module docstring exists because the Firebase-side error does not.
|
||||
"""
|
||||
with pytest.raises(lg.LinkError, match="not an access token"):
|
||||
lg.describe_google_token("not-a-jwt")
|
||||
|
||||
|
||||
def test_a_token_with_an_unparseable_payload_is_rejected() -> None:
|
||||
"""Three parts, but the middle one is not base64url JSON."""
|
||||
with pytest.raises(lg.LinkError, match="not valid base64url JSON"):
|
||||
lg.describe_google_token("header.!!!not-base64!!!.signature")
|
||||
|
||||
|
||||
def test_a_payload_that_is_not_an_object_is_rejected() -> None:
|
||||
"""Valid base64url JSON, wrong shape."""
|
||||
payload = base64.urlsafe_b64encode(b'"just a string"').decode().rstrip("=")
|
||||
|
||||
with pytest.raises(lg.LinkError, match="not a JSON object"):
|
||||
lg.describe_google_token(f"header.{payload}.signature")
|
||||
|
||||
|
||||
def test_a_token_from_another_issuer_is_rejected() -> None:
|
||||
"""The check that makes a misconfiguration report itself locally."""
|
||||
with pytest.raises(lg.LinkError, match="not Google"):
|
||||
lg.describe_google_token(_google_token(iss="https://login.example.com"))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("issuer", [*lg._EXPECTED_ISSUERS])
|
||||
def test_both_google_issuer_spellings_are_accepted(issuer: str) -> None:
|
||||
"""Google uses both forms; rejecting either would be a false alarm."""
|
||||
assert "person@gmail.com" in lg.describe_google_token(_google_token(iss=issuer))
|
||||
|
||||
|
||||
def test_the_description_names_the_account_and_the_audience() -> None:
|
||||
"""The operator's only chance to notice they are linking the wrong one."""
|
||||
description = lg.describe_google_token(_google_token())
|
||||
|
||||
assert "person@gmail.com" in description
|
||||
assert "the-web-client-id.apps.googleusercontent.com" in description
|
||||
|
||||
|
||||
def test_missing_optional_claims_are_described_rather_than_crashing() -> None:
|
||||
"""A token without email/aud is odd but still describable."""
|
||||
token = _jwt({"iss": "accounts.google.com"})
|
||||
|
||||
description = lg.describe_google_token(token)
|
||||
|
||||
assert "<no email claim>" in description
|
||||
assert "<no aud claim>" in description
|
||||
|
||||
|
||||
def test_padding_is_restored_before_decoding() -> None:
|
||||
"""base64url in a JWT is unpadded; decoding without padding fails."""
|
||||
# A payload whose length is not a multiple of 4 once stripped.
|
||||
claims = {"iss": "accounts.google.com", "email": "a@b.co"}
|
||||
|
||||
assert "a@b.co" in lg.describe_google_token(_jwt(claims))
|
||||
216
crdt-sync/crdt_sync/tests/test_tool_migrate_github.py
Normal file
216
crdt-sync/crdt_sync/tests/test_tool_migrate_github.py
Normal file
@ -0,0 +1,216 @@
|
||||
"""Tests for the GitHub-reading half of ``tool/migrate_github_to_firebase``.
|
||||
|
||||
``main()`` is covered in :mod:`test_tool_migrate_github_main`, split to stay
|
||||
under the 250-line file cap.
|
||||
|
||||
Nothing here touches the network or the user's real config. The properties
|
||||
worth pinning are the ones chosen deliberately over an easier alternative --
|
||||
reading by sha rather than by path, refusing a truncated tree, and the skip
|
||||
list -- because each was a decision with a stated cost, and a silent
|
||||
regression in any of them produces a migration that *reports success* while
|
||||
having moved the wrong bytes.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import json
|
||||
from typing import TYPE_CHECKING
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
import requests
|
||||
|
||||
from tool import migrate_github_to_firebase as mg
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def _response(payload: object, *, status: int = 200) -> MagicMock:
|
||||
"""Fake a ``requests`` response carrying ``payload`` as JSON."""
|
||||
response = MagicMock()
|
||||
response.status_code = status
|
||||
response.json.return_value = payload
|
||||
return response
|
||||
|
||||
|
||||
def test_blob_size_is_measured_in_bytes_not_characters() -> None:
|
||||
"""A multi-byte character would under-report the payload otherwise."""
|
||||
blob = mg.Blob(path="notes/a.json", text="café")
|
||||
|
||||
assert len(blob.text) == 4
|
||||
assert blob.size == 5
|
||||
|
||||
|
||||
def test_the_session_authenticates_and_asks_for_the_v3_api() -> None:
|
||||
"""Without the Accept header GitHub may answer with a different shape."""
|
||||
session = mg._github_session("the-token")
|
||||
|
||||
assert session.headers["Authorization"] == "Bearer the-token"
|
||||
assert session.headers["Accept"] == "application/vnd.github+json"
|
||||
|
||||
|
||||
def test_the_session_retries_transient_failures() -> None:
|
||||
"""A migration that gave up half-way is worse than one that never ran.
|
||||
|
||||
403 and 429 are in the list because GitHub uses them for secondary rate
|
||||
limiting, which is the failure a bulk read actually hits.
|
||||
"""
|
||||
session = mg._github_session("the-token")
|
||||
retry = session.get_adapter("https://api.github.com").max_retries
|
||||
|
||||
assert retry.total == 5
|
||||
assert {403, 429, 500, 502, 503, 504} <= set(retry.status_forcelist)
|
||||
assert retry.raise_on_status is False
|
||||
|
||||
|
||||
def test_listing_blobs_asks_for_one_recursive_tree() -> None:
|
||||
"""One call rather than a walk; the walk would be N calls and race."""
|
||||
session = MagicMock()
|
||||
session.get.return_value = _response(
|
||||
{
|
||||
"truncated": False,
|
||||
"tree": [{"path": "a.json", "sha": "sha-a", "type": "blob"}],
|
||||
}
|
||||
)
|
||||
|
||||
entries = mg._list_blobs(session)
|
||||
|
||||
assert entries == [("a.json", "sha-a")]
|
||||
assert session.get.call_args.kwargs["params"] == {"recursive": "1"}
|
||||
|
||||
|
||||
def test_directories_are_not_listed_as_blobs() -> None:
|
||||
"""Tree entries include subtrees, which have no content to migrate."""
|
||||
session = MagicMock()
|
||||
session.get.return_value = _response(
|
||||
{
|
||||
"truncated": False,
|
||||
"tree": [
|
||||
{"path": "notes", "sha": "sha-dir", "type": "tree"},
|
||||
{"path": "notes/a.json", "sha": "sha-a", "type": "blob"},
|
||||
],
|
||||
}
|
||||
)
|
||||
|
||||
assert mg._list_blobs(session) == [("notes/a.json", "sha-a")]
|
||||
|
||||
|
||||
def test_a_truncated_tree_is_refused_rather_than_partially_migrated() -> None:
|
||||
"""The dangerous case: it would look like a successful smaller repo."""
|
||||
session = MagicMock()
|
||||
session.get.return_value = _response({"truncated": True, "tree": []})
|
||||
|
||||
with pytest.raises(RuntimeError, match="truncated"):
|
||||
mg._list_blobs(session)
|
||||
|
||||
|
||||
def test_an_http_error_listing_the_tree_is_raised() -> None:
|
||||
"""A 404 must not read as an empty repo."""
|
||||
session = MagicMock()
|
||||
response = _response({}, status=404)
|
||||
response.raise_for_status.side_effect = requests.HTTPError("404")
|
||||
session.get.return_value = response
|
||||
|
||||
with pytest.raises(requests.HTTPError):
|
||||
mg._list_blobs(session)
|
||||
|
||||
|
||||
def test_a_blob_is_fetched_by_sha_rather_than_by_path() -> None:
|
||||
"""Addressed by sha so a concurrent push cannot swap the content.
|
||||
|
||||
The contents API would return whatever is at that path *now*, which need
|
||||
not be what the tree listing described.
|
||||
"""
|
||||
session = MagicMock()
|
||||
content = base64.b64encode(b'{"v": 1}').decode()
|
||||
session.get.return_value = _response({"content": content})
|
||||
|
||||
blob = mg._fetch_blob(session, "notes/a.json", "sha-a")
|
||||
|
||||
assert blob == mg.Blob(path="notes/a.json", text='{"v": 1}')
|
||||
assert "git/blobs/sha-a" in session.get.call_args.args[0]
|
||||
|
||||
|
||||
def test_a_blob_with_multibyte_content_round_trips() -> None:
|
||||
"""The payload is decoded as UTF-8, not as latin-1 or bytes."""
|
||||
session = MagicMock()
|
||||
session.get.return_value = _response(
|
||||
{"content": base64.b64encode("café".encode()).decode()}
|
||||
)
|
||||
|
||||
assert mg._fetch_blob(session, "a.txt", "sha").text == "café"
|
||||
|
||||
|
||||
def test_an_http_error_fetching_a_blob_is_raised() -> None:
|
||||
"""A dropped blob must fail the migration, not silently vanish."""
|
||||
session = MagicMock()
|
||||
response = _response({}, status=500)
|
||||
response.raise_for_status.side_effect = requests.HTTPError("500")
|
||||
session.get.return_value = response
|
||||
|
||||
with pytest.raises(requests.HTTPError):
|
||||
mg._fetch_blob(session, "a.json", "sha")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"path",
|
||||
[
|
||||
"todo-sync/changesets/0001.json",
|
||||
"diet-guard-sync/devices/desktop/log.json",
|
||||
],
|
||||
)
|
||||
def test_the_deliberately_skipped_prefixes_are_skipped(path: str) -> None:
|
||||
"""Each costs egress or storage forever and is verified redundant."""
|
||||
assert mg._should_migrate(path) is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path", ["README.md", "notes/README.md", ".gitkeep"])
|
||||
def test_documentation_and_placeholders_are_skipped(path: str) -> None:
|
||||
"""Not sync data; matched by name at any depth."""
|
||||
assert mg._should_migrate(path) is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"path",
|
||||
[
|
||||
"todo-sync/notes/a.json",
|
||||
"diet-guard-sync/devices/pc/log.json",
|
||||
"diet-guard-sync/devices/phone/log.json",
|
||||
],
|
||||
)
|
||||
def test_real_sync_data_is_migrated(path: str) -> None:
|
||||
"""The skip rules must not over-match the paths that carry the data."""
|
||||
assert mg._should_migrate(path) is True
|
||||
|
||||
|
||||
def test_a_prefix_is_matched_at_the_start_only() -> None:
|
||||
"""A skip prefix appearing mid-path is a different file."""
|
||||
assert mg._should_migrate("archive/todo-sync/changesets/x.json") is True
|
||||
|
||||
|
||||
def test_the_firebase_client_signs_in_with_the_configured_account(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""Built from the shared config, not from per-tool credentials."""
|
||||
config = {
|
||||
"apiKey": "AIzaKey",
|
||||
"email": "sync@example.com",
|
||||
"databaseUrl": "https://project.firebasedatabase.app",
|
||||
}
|
||||
(tmp_path / "firebase.json").write_text(json.dumps(config), encoding="utf-8")
|
||||
(tmp_path / "password").write_text("the-account-phrase", encoding="utf-8")
|
||||
auth = MagicMock()
|
||||
|
||||
with (
|
||||
patch.object(mg, "_CONFIG_DIR", tmp_path),
|
||||
patch.object(mg, "FirebaseTokenProvider", return_value=auth) as provider,
|
||||
patch.object(mg, "FirebaseSyncClient") as client,
|
||||
):
|
||||
result = mg._firebase_client()
|
||||
|
||||
assert provider.call_args.args[0] == "AIzaKey"
|
||||
auth.sign_in.assert_called_once_with("sync@example.com", "the-account-phrase")
|
||||
assert client.call_args.args == ("https://project.firebasedatabase.app", auth)
|
||||
assert result is client.return_value
|
||||
248
crdt-sync/crdt_sync/tests/test_tool_migrate_github_main.py
Normal file
248
crdt-sync/crdt_sync/tests/test_tool_migrate_github_main.py
Normal file
@ -0,0 +1,248 @@
|
||||
"""Tests for ``main()`` in ``tool/migrate_github_to_firebase``.
|
||||
|
||||
Split from :mod:`test_tool_migrate_github` to stay under the 250-line cap.
|
||||
|
||||
This is a one-shot destructive-ish migration, so the properties under test are
|
||||
the safety ones: ``--dry-run`` must write nothing at all, the byte-for-byte
|
||||
read-back must actually fail the run when a file does not round-trip, and the
|
||||
report must be emitted *before* anything is written. ``main()`` reads argv
|
||||
directly, so every test patches ``sys.argv``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from tool import migrate_github_to_firebase as mg
|
||||
|
||||
_BLOBS = [
|
||||
mg.Blob(path="todo-sync/notes/a.json", text='{"a": 1}'),
|
||||
mg.Blob(path="diet-guard-sync/devices/pc/log.json", text='{"b": 2}'),
|
||||
]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def github() -> MagicMock:
|
||||
"""Patch the whole GitHub-reading half with two migratable blobs."""
|
||||
entries = [(blob.path, f"sha-{index}") for index, blob in enumerate(_BLOBS)]
|
||||
entries.append(("todo-sync/changesets/old.json", "sha-skip"))
|
||||
|
||||
with (
|
||||
patch.object(mg, "_github_session") as session,
|
||||
patch.object(mg, "_list_blobs", return_value=entries),
|
||||
patch.object(
|
||||
mg, "_fetch_blob", side_effect=lambda _s, path, _sha: _by_path(path)
|
||||
),
|
||||
patch.object(mg, "_GITHUB_TOKEN_FILE", _token_file()),
|
||||
):
|
||||
yield session
|
||||
|
||||
|
||||
def _token_file() -> MagicMock:
|
||||
"""A stand-in for the token path whose read_text yields a padded token."""
|
||||
token_file = MagicMock()
|
||||
token_file.read_text.return_value = "the-token\n"
|
||||
return token_file
|
||||
|
||||
|
||||
def _by_path(path: str) -> mg.Blob:
|
||||
"""Return the canned blob for ``path``."""
|
||||
return next(blob for blob in _BLOBS if blob.path == path)
|
||||
|
||||
|
||||
def _client_that_round_trips() -> MagicMock:
|
||||
"""A Firebase client whose read-back matches what was written."""
|
||||
written: dict[str, str] = {}
|
||||
client = MagicMock()
|
||||
client.put_file_text.side_effect = lambda path, text, **_: written.__setitem__(
|
||||
path, text
|
||||
)
|
||||
client.get_file_text.side_effect = written.get
|
||||
return client
|
||||
|
||||
|
||||
def test_dry_run_writes_nothing(github: MagicMock) -> None:
|
||||
"""The whole point of the flag: no client is even constructed."""
|
||||
with (
|
||||
patch.object(mg.sys, "argv", ["migrate", "--dry-run"]),
|
||||
patch.object(mg, "_firebase_client") as client_for,
|
||||
):
|
||||
code = mg.main()
|
||||
|
||||
assert code == 0
|
||||
client_for.assert_not_called()
|
||||
|
||||
|
||||
def test_dry_run_still_reports_what_would_move(
|
||||
github: MagicMock,
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
"""A dry run that printed nothing would be useless."""
|
||||
with (
|
||||
patch.object(mg.sys, "argv", ["migrate", "--dry-run"]),
|
||||
patch.object(mg, "_firebase_client"),
|
||||
caplog.at_level(logging.INFO, logger="migrate"),
|
||||
):
|
||||
mg.main()
|
||||
|
||||
assert "2 files to migrate" in caplog.text
|
||||
assert "DRY RUN" in caplog.text
|
||||
|
||||
|
||||
def test_the_skipped_paths_are_listed_with_their_reason(
|
||||
github: MagicMock,
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
"""Silently dropping files is the failure mode this reporting prevents."""
|
||||
with (
|
||||
patch.object(mg.sys, "argv", ["migrate", "--dry-run"]),
|
||||
patch.object(mg, "_firebase_client"),
|
||||
caplog.at_level(logging.INFO, logger="migrate"),
|
||||
):
|
||||
mg.main()
|
||||
|
||||
assert "1 skipped" in caplog.text
|
||||
assert "todo-sync/changesets/old.json" in caplog.text
|
||||
|
||||
|
||||
def test_skipped_files_are_never_fetched(github: MagicMock) -> None:
|
||||
"""Fetching then discarding would pay the egress the skip list avoids."""
|
||||
with (
|
||||
patch.object(mg.sys, "argv", ["migrate", "--dry-run"]),
|
||||
patch.object(mg, "_firebase_client"),
|
||||
patch.object(
|
||||
mg, "_fetch_blob", side_effect=lambda _s, p, _sha: _by_path(p)
|
||||
) as f,
|
||||
):
|
||||
mg.main()
|
||||
|
||||
fetched = {c.args[1] for c in f.call_args_list}
|
||||
assert fetched == {blob.path for blob in _BLOBS}
|
||||
|
||||
|
||||
def test_a_real_run_writes_every_blob_and_verifies(github: MagicMock) -> None:
|
||||
"""The happy path: written, read back, byte-for-byte equal."""
|
||||
client = _client_that_round_trips()
|
||||
|
||||
with (
|
||||
patch.object(mg.sys, "argv", ["migrate"]),
|
||||
patch.object(mg, "_firebase_client", return_value=client),
|
||||
):
|
||||
code = mg.main()
|
||||
|
||||
assert code == 0
|
||||
assert client.put_file_text.call_count == 2
|
||||
assert client.get_file_text.call_count == 2
|
||||
|
||||
|
||||
def test_the_report_is_emitted_before_anything_is_written(
|
||||
github: MagicMock,
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
"""Ordering matters: the operator sees the plan before it executes."""
|
||||
order: list[str] = []
|
||||
client = _client_that_round_trips()
|
||||
client.put_file_text.side_effect = lambda *a, **k: order.append("write")
|
||||
|
||||
with (
|
||||
patch.object(mg.sys, "argv", ["migrate"]),
|
||||
patch.object(mg, "_firebase_client", return_value=client),
|
||||
patch.object(mg, "_report", side_effect=lambda *_: order.append("report")),
|
||||
):
|
||||
mg.main()
|
||||
|
||||
assert order[0] == "report"
|
||||
assert "write" in order
|
||||
|
||||
|
||||
def test_a_file_that_does_not_round_trip_fails_the_run(github: MagicMock) -> None:
|
||||
"""The check that makes 'OK' mean something.
|
||||
|
||||
Without it a migration that silently dropped a file would report success,
|
||||
which is the one outcome worse than failing loudly.
|
||||
"""
|
||||
client = MagicMock()
|
||||
client.get_file_text.return_value = "something else entirely"
|
||||
|
||||
with (
|
||||
patch.object(mg.sys, "argv", ["migrate"]),
|
||||
patch.object(mg, "_firebase_client", return_value=client),
|
||||
):
|
||||
code = mg.main()
|
||||
|
||||
assert code == 1
|
||||
|
||||
|
||||
def test_every_mismatching_path_is_named(
|
||||
github: MagicMock,
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
"""Reporting only the first would need N runs to find N problems."""
|
||||
client = MagicMock()
|
||||
client.get_file_text.return_value = None
|
||||
|
||||
with (
|
||||
patch.object(mg.sys, "argv", ["migrate"]),
|
||||
patch.object(mg, "_firebase_client", return_value=client),
|
||||
caplog.at_level(logging.ERROR, logger="migrate"),
|
||||
):
|
||||
mg.main()
|
||||
|
||||
assert "2 file(s) did not round-trip" in caplog.text
|
||||
for blob in _BLOBS:
|
||||
assert blob.path in caplog.text
|
||||
|
||||
|
||||
def test_a_partial_mismatch_still_fails(github: MagicMock) -> None:
|
||||
"""One bad file out of two is a failed migration, not a 50% success."""
|
||||
client = MagicMock()
|
||||
client.get_file_text.side_effect = [_BLOBS[0].text, "corrupted"]
|
||||
|
||||
with (
|
||||
patch.object(mg.sys, "argv", ["migrate"]),
|
||||
patch.object(mg, "_firebase_client", return_value=client),
|
||||
):
|
||||
assert mg.main() == 1
|
||||
|
||||
|
||||
def test_the_github_token_is_read_and_stripped(github: MagicMock) -> None:
|
||||
"""A trailing newline in the token file would break the auth header."""
|
||||
client = _client_that_round_trips()
|
||||
|
||||
with (
|
||||
patch.object(mg.sys, "argv", ["migrate"]),
|
||||
patch.object(mg, "_firebase_client", return_value=client),
|
||||
):
|
||||
mg.main()
|
||||
|
||||
github.assert_called_once_with("the-token")
|
||||
|
||||
|
||||
def test_report_lists_the_largest_file_first(
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
"""Size order is what makes the report scannable for the costly ones."""
|
||||
blobs = [
|
||||
mg.Blob(path="small.json", text="x"),
|
||||
mg.Blob(path="large.json", text="x" * 100),
|
||||
]
|
||||
|
||||
with caplog.at_level(logging.INFO, logger="migrate"):
|
||||
mg._report(blobs, [])
|
||||
|
||||
listed = [r.getMessage() for r in caplog.records if ".json" in r.getMessage()]
|
||||
assert "large.json" in listed[0]
|
||||
assert "small.json" in listed[1]
|
||||
|
||||
|
||||
def test_report_omits_the_skipped_section_when_nothing_was_skipped(
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
"""An empty 'skipped' heading is noise that hides the real one."""
|
||||
with caplog.at_level(logging.INFO, logger="migrate"):
|
||||
mg._report([mg.Blob(path="a.json", text="x")], [])
|
||||
|
||||
assert "skipped" not in caplog.text
|
||||
247
crdt-sync/crdt_sync/tests/test_tool_preflight_firebase.py
Normal file
247
crdt-sync/crdt_sync/tests/test_tool_preflight_firebase.py
Normal file
@ -0,0 +1,247 @@
|
||||
"""Tests for the individual checks in ``tool/preflight_firebase``.
|
||||
|
||||
``main()`` and the loading helpers are covered in
|
||||
:mod:`test_tool_preflight_firebase_main`, split to stay under the 250-line cap.
|
||||
|
||||
The point of this tool is that each check names one specific misconfiguration,
|
||||
because the failures it catches are otherwise indistinguishable once data has
|
||||
started moving. So every check is asserted on its *message*, not just on the
|
||||
fact that it raised -- a check that fires with the wrong explanation sends the
|
||||
reader to the wrong place, which is the cost this module exists to avoid.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import json
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
import requests
|
||||
|
||||
from tool import preflight_firebase as pf
|
||||
|
||||
_UID = "the-uid-pinned-in-the-rules"
|
||||
_GOOD = {
|
||||
"apiKey": "AIzaSyAthisIsTheWebApiKeyFormat",
|
||||
"databaseUrl": "https://project-default-rtdb.europe-west1.firebasedatabase.app",
|
||||
"projectId": "the-project",
|
||||
"uid": _UID,
|
||||
"email": "sync@example.com",
|
||||
}
|
||||
_ACCOUNT_PHRASE = "the-sync-account-password"
|
||||
|
||||
|
||||
def _config(**overrides: str) -> dict[str, str]:
|
||||
"""A valid config with individual fields overridden."""
|
||||
return {**_GOOD, **overrides}
|
||||
|
||||
|
||||
def test_keys_present_accepts_a_complete_config() -> None:
|
||||
"""The happy path raises nothing."""
|
||||
pf.check_keys_present(_config())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("key", ["apiKey", "databaseUrl", "projectId", "uid", "email"])
|
||||
def test_every_required_key_is_actually_required(key: str) -> None:
|
||||
"""Each of the five keys is checked, not just the first."""
|
||||
config = _config()
|
||||
del config[key]
|
||||
|
||||
with pytest.raises(pf.PreflightError, match=key):
|
||||
pf.check_keys_present(config)
|
||||
|
||||
|
||||
def test_a_whitespace_only_value_counts_as_missing() -> None:
|
||||
"""A key present but blank is the same failure as an absent one."""
|
||||
with pytest.raises(pf.PreflightError, match="uid"):
|
||||
pf.check_keys_present(_config(uid=" "))
|
||||
|
||||
|
||||
def test_all_missing_keys_are_reported_together() -> None:
|
||||
"""Reporting one at a time would need five runs to fix five typos."""
|
||||
config = {"apiKey": _GOOD["apiKey"]}
|
||||
|
||||
with pytest.raises(pf.PreflightError) as raised:
|
||||
pf.check_keys_present(config)
|
||||
|
||||
assert "databaseUrl" in str(raised.value)
|
||||
assert "email" in str(raised.value)
|
||||
|
||||
|
||||
def test_no_placeholders_accepts_a_filled_in_config() -> None:
|
||||
"""Real values pass."""
|
||||
pf.check_no_placeholders(_config(), _ACCOUNT_PHRASE)
|
||||
|
||||
|
||||
def test_an_unreplaced_scaffold_placeholder_is_caught() -> None:
|
||||
"""The scaffold ships PASTE_ markers; one left behind is a typo."""
|
||||
with pytest.raises(pf.PreflightError, match="projectId"):
|
||||
pf.check_no_placeholders(_config(projectId="PASTE_PROJECT_ID"), _ACCOUNT_PHRASE)
|
||||
|
||||
|
||||
def test_a_placeholder_in_the_password_file_is_caught() -> None:
|
||||
"""The password lives in its own file and is easy to forget."""
|
||||
with pytest.raises(pf.PreflightError, match="password"):
|
||||
pf.check_no_placeholders(_config(), "PASTE_ACCOUNT_PHRASE_HERE")
|
||||
|
||||
|
||||
def test_shapes_accepts_well_formed_values() -> None:
|
||||
"""The happy path raises nothing."""
|
||||
pf.check_shapes(_config(), _ACCOUNT_PHRASE)
|
||||
|
||||
|
||||
def test_a_non_https_database_url_is_rejected() -> None:
|
||||
"""http:// would work locally and fail everywhere else."""
|
||||
with pytest.raises(pf.PreflightError, match="must start with https://"):
|
||||
pf.check_shapes(
|
||||
_config(databaseUrl="http://project.firebasedatabase.app"), _ACCOUNT_PHRASE
|
||||
)
|
||||
|
||||
|
||||
def test_a_trailing_slash_on_the_database_url_is_rejected() -> None:
|
||||
"""It yields a double slash in every request path built from it."""
|
||||
with pytest.raises(pf.PreflightError, match="must not end with"):
|
||||
pf.check_shapes(
|
||||
_config(databaseUrl=f"{_GOOD['databaseUrl']}/"), _ACCOUNT_PHRASE
|
||||
)
|
||||
|
||||
|
||||
def test_an_api_key_in_the_wrong_format_is_rejected() -> None:
|
||||
"""Pasting a service-account key instead of the Web API key."""
|
||||
with pytest.raises(pf.PreflightError, match="AIza"):
|
||||
pf.check_shapes(_config(apiKey="ya29.not-the-web-api-key"), _ACCOUNT_PHRASE)
|
||||
|
||||
|
||||
def test_a_password_with_a_trailing_newline_is_rejected() -> None:
|
||||
"""The single most likely hand-editing mistake, per the module docstring."""
|
||||
with pytest.raises(pf.PreflightError, match="whitespace"):
|
||||
pf.check_shapes(_config(), f"{_ACCOUNT_PHRASE}\n")
|
||||
|
||||
|
||||
def test_an_email_without_an_at_sign_is_rejected() -> None:
|
||||
"""A uid pasted into the email field, typically."""
|
||||
with pytest.raises(pf.PreflightError, match="does not look like an address"):
|
||||
pf.check_shapes(_config(email="not-an-address"), _ACCOUNT_PHRASE)
|
||||
|
||||
|
||||
def _get(status: int, payload: object = None) -> MagicMock:
|
||||
"""Fake a ``requests.get`` response with a status and JSON body."""
|
||||
response = MagicMock()
|
||||
response.status_code = status
|
||||
if isinstance(payload, ValueError):
|
||||
response.json.side_effect = payload
|
||||
else:
|
||||
response.json.return_value = payload if payload is not None else {}
|
||||
return response
|
||||
|
||||
|
||||
def test_a_denied_anonymous_read_is_the_expected_outcome() -> None:
|
||||
"""401 means the rules are published and doing their job."""
|
||||
with patch.object(pf.requests, "get", return_value=_get(401)):
|
||||
pf.check_rules_deny_anonymous(_config())
|
||||
|
||||
|
||||
def test_a_world_readable_database_is_reported_loudly() -> None:
|
||||
"""A 200 here means anyone on the internet can read the data."""
|
||||
with (
|
||||
patch.object(pf.requests, "get", return_value=_get(200)),
|
||||
pytest.raises(pf.PreflightError, match="world-readable"),
|
||||
):
|
||||
pf.check_rules_deny_anonymous(_config())
|
||||
|
||||
|
||||
def test_a_wrong_region_url_reports_the_correct_one() -> None:
|
||||
"""Firebase answers 404 with the real URL rather than an error.
|
||||
|
||||
Without this branch the wrong-region case would pass preflight, pass
|
||||
sign-in (a different host entirely) and only break mid-migration.
|
||||
"""
|
||||
body = {
|
||||
"correctUrl": "https://project-default-rtdb.asia-southeast1.firebasedatabase.app"
|
||||
}
|
||||
|
||||
with (
|
||||
patch.object(pf.requests, "get", return_value=_get(404, body)),
|
||||
pytest.raises(pf.PreflightError, match="asia-southeast1"),
|
||||
):
|
||||
pf.check_rules_deny_anonymous(_config())
|
||||
|
||||
|
||||
def test_a_404_without_a_correct_url_reports_a_missing_database() -> None:
|
||||
"""No database at that URL at all."""
|
||||
with (
|
||||
patch.object(pf.requests, "get", return_value=_get(404)),
|
||||
pytest.raises(pf.PreflightError, match="no database lives there"),
|
||||
):
|
||||
pf.check_rules_deny_anonymous(_config())
|
||||
|
||||
|
||||
def test_a_404_with_an_unparseable_body_still_reports_a_missing_database() -> None:
|
||||
"""The body is not guaranteed to be JSON; that must not mask the 404."""
|
||||
response = _get(404, ValueError("not json"))
|
||||
|
||||
with (
|
||||
patch.object(pf.requests, "get", return_value=response),
|
||||
pytest.raises(pf.PreflightError, match="no database lives there"),
|
||||
):
|
||||
pf.check_rules_deny_anonymous(_config())
|
||||
|
||||
|
||||
def _token_for(uid: str) -> str:
|
||||
"""Build a JWT whose payload carries ``uid`` as ``user_id``."""
|
||||
payload = base64.urlsafe_b64encode(json.dumps({"user_id": uid}).encode())
|
||||
return f"header.{payload.decode().rstrip('=')}.signature"
|
||||
|
||||
|
||||
def _provider(uid: str) -> MagicMock:
|
||||
"""A FirebaseTokenProvider that signs in and yields ``uid``'s token."""
|
||||
provider = MagicMock()
|
||||
provider.id_token.return_value = _token_for(uid)
|
||||
return provider
|
||||
|
||||
|
||||
def test_sign_in_with_the_pinned_uid_passes() -> None:
|
||||
"""The decisive check, in its passing form."""
|
||||
with patch.object(pf, "FirebaseTokenProvider", return_value=_provider(_UID)):
|
||||
pf.check_sign_in_uid_matches(_config(), _ACCOUNT_PHRASE)
|
||||
|
||||
|
||||
def test_signing_in_as_a_different_uid_is_rejected() -> None:
|
||||
"""Authenticates fine, then denies every read and write."""
|
||||
with (
|
||||
patch.object(
|
||||
pf, "FirebaseTokenProvider", return_value=_provider("another-uid")
|
||||
),
|
||||
pytest.raises(pf.PreflightError, match="every read and write would be denied"),
|
||||
):
|
||||
pf.check_sign_in_uid_matches(_config(), _ACCOUNT_PHRASE)
|
||||
|
||||
|
||||
def test_the_uid_is_read_from_sub_when_user_id_is_absent() -> None:
|
||||
"""Not every issuer sets user_id; sub is the standard claim."""
|
||||
payload = base64.urlsafe_b64encode(json.dumps({"sub": _UID}).encode())
|
||||
provider = MagicMock()
|
||||
provider.id_token.return_value = f"h.{payload.decode().rstrip('=')}.s"
|
||||
|
||||
with patch.object(pf, "FirebaseTokenProvider", return_value=provider):
|
||||
pf.check_sign_in_uid_matches(_config(), _ACCOUNT_PHRASE)
|
||||
|
||||
|
||||
def test_the_password_is_passed_to_sign_in_verbatim() -> None:
|
||||
"""A stripped or re-encoded password would fail for the wrong reason."""
|
||||
provider = _provider(_UID)
|
||||
|
||||
with patch.object(pf, "FirebaseTokenProvider", return_value=provider):
|
||||
pf.check_sign_in_uid_matches(_config(), _ACCOUNT_PHRASE)
|
||||
|
||||
provider.sign_in.assert_called_once_with(_GOOD["email"], _ACCOUNT_PHRASE)
|
||||
|
||||
|
||||
def test_requests_exceptions_are_not_swallowed_by_the_checks() -> None:
|
||||
"""Transport errors belong to main(), which reports them differently."""
|
||||
with (
|
||||
patch.object(pf.requests, "get", side_effect=requests.ConnectionError("down")),
|
||||
pytest.raises(requests.ConnectionError),
|
||||
):
|
||||
pf.check_rules_deny_anonymous(_config())
|
||||
225
crdt-sync/crdt_sync/tests/test_tool_preflight_firebase_main.py
Normal file
225
crdt-sync/crdt_sync/tests/test_tool_preflight_firebase_main.py
Normal file
@ -0,0 +1,225 @@
|
||||
"""Tests for ``tool/preflight_firebase``'s loaders and ``main()``.
|
||||
|
||||
Split from :mod:`test_tool_preflight_firebase` to stay under the 250-line file
|
||||
cap; that module covers the individual checks.
|
||||
|
||||
The config paths are module-level constants pointing into the real
|
||||
``~/.config/crdt-sync``, so every test here redirects them at ``tmp_path``
|
||||
first. Nothing may read or write the user's actual credentials.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
from typing import TYPE_CHECKING
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
import requests
|
||||
|
||||
from tool import preflight_firebase as pf
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Iterator
|
||||
from pathlib import Path
|
||||
|
||||
_GOOD = {
|
||||
"apiKey": "AIzaSyAthisIsTheWebApiKeyFormat",
|
||||
"databaseUrl": "https://project-default-rtdb.europe-west1.firebasedatabase.app",
|
||||
"projectId": "the-project",
|
||||
"uid": "the-uid-pinned-in-the-rules",
|
||||
"email": "sync@example.com",
|
||||
}
|
||||
_ACCOUNT_PHRASE = "the-sync-account-password"
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def config_dir(tmp_path: Path) -> Iterator[Path]:
|
||||
"""Point the module's config constants at a throwaway directory.
|
||||
|
||||
Autouse, because a test that forgot this would read -- and report on --
|
||||
the real ~/.config/crdt-sync.
|
||||
"""
|
||||
with (
|
||||
patch.object(pf, "_CONFIG_FILE", tmp_path / "firebase.json"),
|
||||
patch.object(pf, "_PASSWORD_FILE", tmp_path / "password"),
|
||||
):
|
||||
yield tmp_path
|
||||
|
||||
|
||||
def _write(directory: Path, config: object = None, password: str | None = None) -> None:
|
||||
"""Write a config and/or password file into the redirected directory."""
|
||||
if config is not None:
|
||||
text = config if isinstance(config, str) else json.dumps(config)
|
||||
(directory / "firebase.json").write_text(text, encoding="utf-8")
|
||||
if password is not None:
|
||||
(directory / "password").write_text(password, encoding="utf-8")
|
||||
|
||||
|
||||
def test_a_missing_config_file_is_reported_by_path(config_dir: Path) -> None:
|
||||
"""The message must name the file, since creating it is the fix."""
|
||||
with pytest.raises(pf.PreflightError, match="does not exist"):
|
||||
pf._load_config()
|
||||
|
||||
|
||||
def test_invalid_json_is_reported_as_such(config_dir: Path) -> None:
|
||||
"""A trailing comma is the usual cause and needs naming as a syntax error."""
|
||||
_write(config_dir, "{not json,}")
|
||||
|
||||
with pytest.raises(pf.PreflightError, match="not valid JSON"):
|
||||
pf._load_config()
|
||||
|
||||
|
||||
def test_a_json_scalar_is_rejected(config_dir: Path) -> None:
|
||||
"""Valid JSON, wrong shape: the file must hold an object."""
|
||||
_write(config_dir, "[]")
|
||||
|
||||
with pytest.raises(pf.PreflightError, match="must contain a JSON object"):
|
||||
pf._load_config()
|
||||
|
||||
|
||||
def test_scaffold_comment_keys_are_stripped(config_dir: Path) -> None:
|
||||
"""They are documentation for whoever fills the file in, not config."""
|
||||
_write(config_dir, {**_GOOD, "_comment_apiKey": "where to find this"})
|
||||
|
||||
config = pf._load_config()
|
||||
|
||||
assert config == _GOOD
|
||||
|
||||
|
||||
def test_a_missing_password_file_is_reported_by_path(config_dir: Path) -> None:
|
||||
"""Absent and empty are the same failure with the same fix."""
|
||||
with pytest.raises(pf.PreflightError, match="missing or empty"):
|
||||
pf._load_password()
|
||||
|
||||
|
||||
def test_an_empty_password_file_is_reported(config_dir: Path) -> None:
|
||||
"""A touched-but-unfilled file must not read as a valid empty password."""
|
||||
_write(config_dir, password="")
|
||||
|
||||
with pytest.raises(pf.PreflightError, match="missing or empty"):
|
||||
pf._load_password()
|
||||
|
||||
|
||||
def test_the_password_is_returned_unstripped(config_dir: Path) -> None:
|
||||
"""check_shapes is what rejects the newline, so the loader must keep it.
|
||||
|
||||
Stripping here would hide the single most likely hand-editing mistake
|
||||
rather than report it.
|
||||
"""
|
||||
_write(config_dir, password=f"{_ACCOUNT_PHRASE}\n")
|
||||
|
||||
assert pf._load_password() == f"{_ACCOUNT_PHRASE}\n"
|
||||
|
||||
|
||||
def test_main_passes_when_every_check_passes(
|
||||
config_dir: Path,
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
"""The happy path: exit 0, and every check reported by name."""
|
||||
_write(config_dir, _GOOD, _ACCOUNT_PHRASE)
|
||||
|
||||
with (
|
||||
patch.object(pf, "check_rules_deny_anonymous"),
|
||||
patch.object(pf, "check_sign_in_uid_matches"),
|
||||
caplog.at_level(logging.INFO, logger="preflight"),
|
||||
):
|
||||
code = pf.main()
|
||||
|
||||
assert code == 0
|
||||
messages = "\n".join(record.getMessage() for record in caplog.records)
|
||||
assert "PASS config keys present" in messages
|
||||
assert "PASS sign-in uid matches rules" in messages
|
||||
assert "safe to run the migration" in messages
|
||||
|
||||
|
||||
def test_main_returns_1_and_names_the_failing_check(
|
||||
config_dir: Path,
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
"""A PreflightError is an exit code plus an explanation, not a traceback."""
|
||||
_write(config_dir, {**_GOOD, "email": "not-an-address"}, _ACCOUNT_PHRASE)
|
||||
|
||||
with caplog.at_level(logging.INFO, logger="preflight"):
|
||||
code = pf.main()
|
||||
|
||||
assert code == 1
|
||||
assert "FAIL" in caplog.text
|
||||
assert "does not look like an address" in caplog.text
|
||||
|
||||
|
||||
def test_main_stops_at_the_first_failure(config_dir: Path) -> None:
|
||||
"""Cheapest-first ordering only pays off if it short-circuits.
|
||||
|
||||
A typo must be reported without a network round trip, so the later
|
||||
network checks must not run at all.
|
||||
"""
|
||||
_write(config_dir, {**_GOOD, "email": "not-an-address"}, _ACCOUNT_PHRASE)
|
||||
|
||||
with (
|
||||
patch.object(pf, "check_rules_deny_anonymous") as rules,
|
||||
patch.object(pf, "check_sign_in_uid_matches") as sign_in,
|
||||
):
|
||||
code = pf.main()
|
||||
|
||||
assert code == 1
|
||||
rules.assert_not_called()
|
||||
sign_in.assert_not_called()
|
||||
|
||||
|
||||
def test_main_reports_a_network_failure_distinctly(
|
||||
config_dir: Path,
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
"""An unreachable Firebase is not a misconfiguration; say so."""
|
||||
_write(config_dir, _GOOD, _ACCOUNT_PHRASE)
|
||||
|
||||
with (
|
||||
patch.object(
|
||||
pf,
|
||||
"check_rules_deny_anonymous",
|
||||
side_effect=requests.ConnectionError("no route to host"),
|
||||
),
|
||||
caplog.at_level(logging.INFO, logger="preflight"),
|
||||
):
|
||||
code = pf.main()
|
||||
|
||||
assert code == 1
|
||||
assert "could not reach Firebase" in caplog.text
|
||||
|
||||
|
||||
def test_main_reports_an_unreadable_config_as_a_failure(
|
||||
config_dir: Path,
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
"""An OSError reading the files is caught rather than crashing."""
|
||||
_write(config_dir, _GOOD, _ACCOUNT_PHRASE)
|
||||
|
||||
with (
|
||||
patch.object(pf, "_load_password", side_effect=OSError("permission denied")),
|
||||
caplog.at_level(logging.INFO, logger="preflight"),
|
||||
):
|
||||
code = pf.main()
|
||||
|
||||
assert code == 1
|
||||
assert "could not reach Firebase" in caplog.text
|
||||
|
||||
|
||||
def test_main_runs_the_checks_in_cheapest_first_order(config_dir: Path) -> None:
|
||||
"""The ordering is the module's stated contract, so pin it."""
|
||||
_write(config_dir, _GOOD, _ACCOUNT_PHRASE)
|
||||
called: list[str] = []
|
||||
|
||||
with (
|
||||
patch.object(pf, "check_keys_present", lambda *_: called.append("keys")),
|
||||
patch.object(pf, "check_no_placeholders", lambda *_: called.append("holders")),
|
||||
patch.object(pf, "check_shapes", lambda *_: called.append("shapes")),
|
||||
patch.object(
|
||||
pf, "check_rules_deny_anonymous", lambda *_: called.append("rules")
|
||||
),
|
||||
patch.object(pf, "check_sign_in_uid_matches", lambda *_: called.append("uid")),
|
||||
):
|
||||
assert pf.main() == 0
|
||||
|
||||
assert called == ["keys", "holders", "shapes", "rules", "uid"]
|
||||
230
crdt-sync/crdt_sync/tests/test_tool_seed_session.py
Normal file
230
crdt-sync/crdt_sync/tests/test_tool_seed_session.py
Normal file
@ -0,0 +1,230 @@
|
||||
"""Tests for ``seed_apps`` in ``tool/seed_session``.
|
||||
|
||||
``main()`` is covered in :mod:`test_tool_seed_session_main`, split to stay
|
||||
under the 250-line cap.
|
||||
|
||||
The reason this script exists is that credential files were present and the
|
||||
tokens inside them were dead, so "the file was written" proves nothing. Two
|
||||
structural decisions follow from that and are what the tests pin: every app
|
||||
gets its own exchange, and verification happens in a *second pass* after all
|
||||
sessions exist -- because minting a new session for the same uid can
|
||||
invalidate an earlier app's refresh token, which a check-as-you-go loop would
|
||||
never see.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from crdt_sync import FirebaseConfig
|
||||
from crdt_sync._firebase_auth import FirebaseAuthError
|
||||
from crdt_sync._remote import RemoteSyncError
|
||||
from tool import seed_session as ss
|
||||
|
||||
_UID = "the-uid-pinned-in-the-rules"
|
||||
_CONFIG = FirebaseConfig(
|
||||
api_key="AIzaSyAthisIsTheWebApiKeyFormat",
|
||||
database_url="https://project-default-rtdb.firebasedatabase.app",
|
||||
project_id="the-project",
|
||||
uid=_UID,
|
||||
email="sync@example.com",
|
||||
)
|
||||
_ID_VALUE = "the-google-id-token"
|
||||
_APPS = ("diet_guard", "screen_locker")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def seeding() -> tuple[MagicMock, MagicMock, MagicMock]:
|
||||
"""Patch the auth provider, credential store and sync client."""
|
||||
provider = MagicMock()
|
||||
provider.sign_in_with_google.return_value = "person@gmail.com"
|
||||
|
||||
with (
|
||||
patch.object(ss, "FirebaseTokenProvider", return_value=provider) as factory,
|
||||
patch.object(ss, "credential_store_for") as store_for,
|
||||
patch.object(ss, "FirebaseSyncClient") as client_factory,
|
||||
):
|
||||
yield factory, store_for, client_factory
|
||||
|
||||
|
||||
def test_every_named_app_is_seeded_and_returned(seeding: tuple) -> None:
|
||||
"""The happy path returns the apps that verified, in order."""
|
||||
assert ss.seed_apps(_CONFIG, _ID_VALUE, _APPS) == list(_APPS)
|
||||
|
||||
|
||||
def test_each_app_gets_its_own_credential_store(seeding: tuple) -> None:
|
||||
"""A single session copied across apps would have them all refreshing
|
||||
the same rotated token and invalidating each other."""
|
||||
_, store_for, _ = seeding
|
||||
|
||||
ss.seed_apps(_CONFIG, _ID_VALUE, _APPS)
|
||||
|
||||
seeded_names = [call.args[0] for call in store_for.call_args_list]
|
||||
assert set(seeded_names) == set(_APPS)
|
||||
|
||||
|
||||
def test_each_app_gets_its_own_exchange(seeding: tuple) -> None:
|
||||
"""One sign-in per app, not one shared session."""
|
||||
factory, _, _ = seeding
|
||||
provider = factory.return_value
|
||||
|
||||
ss.seed_apps(_CONFIG, _ID_VALUE, _APPS)
|
||||
|
||||
assert provider.sign_in_with_google.call_count == len(_APPS)
|
||||
|
||||
|
||||
def test_the_expected_uid_is_pinned_on_every_exchange(seeding: tuple) -> None:
|
||||
"""A wrong account must be refused before anything is written."""
|
||||
factory, _, _ = seeding
|
||||
provider = factory.return_value
|
||||
|
||||
ss.seed_apps(_CONFIG, _ID_VALUE, _APPS)
|
||||
|
||||
for call in provider.sign_in_with_google.call_args_list:
|
||||
assert call.args[0] == _ID_VALUE
|
||||
assert call.kwargs["expected_uid"] == _UID
|
||||
|
||||
|
||||
def test_a_rejected_token_stops_before_any_app_is_verified(seeding: tuple) -> None:
|
||||
"""Raised on the first failure, so a wrong account reaches no app."""
|
||||
factory, _, client_factory = seeding
|
||||
factory.return_value.sign_in_with_google.side_effect = FirebaseAuthError("nope")
|
||||
|
||||
with pytest.raises(FirebaseAuthError):
|
||||
ss.seed_apps(_CONFIG, _ID_VALUE, _APPS)
|
||||
|
||||
client_factory.assert_not_called()
|
||||
|
||||
|
||||
def test_verification_happens_after_every_session_exists(seeding: tuple) -> None:
|
||||
"""The structural point of the two-pass design.
|
||||
|
||||
Checking each app as it is written would pass an app that a later
|
||||
exchange then invalidates -- precisely the failure being guarded against.
|
||||
"""
|
||||
factory, _, client_factory = seeding
|
||||
order: list[str] = []
|
||||
|
||||
def _record_seed(*_args: object, **_kwargs: object) -> str:
|
||||
order.append("seed")
|
||||
return "person@gmail.com"
|
||||
|
||||
def _record_verify(_path: str) -> None:
|
||||
order.append("verify")
|
||||
|
||||
factory.return_value.sign_in_with_google.side_effect = _record_seed
|
||||
client_factory.return_value.list_directory.side_effect = _record_verify
|
||||
|
||||
ss.seed_apps(_CONFIG, _ID_VALUE, _APPS)
|
||||
|
||||
assert order == ["seed", "seed", "verify", "verify"]
|
||||
|
||||
|
||||
def test_each_app_is_verified_with_a_real_authenticated_read(
|
||||
seeding: tuple,
|
||||
) -> None:
|
||||
"""A written credential file is not evidence of working sync."""
|
||||
_, _, client_factory = seeding
|
||||
|
||||
ss.seed_apps(_CONFIG, _ID_VALUE, _APPS)
|
||||
|
||||
client = client_factory.return_value
|
||||
assert client.list_directory.call_count == len(_APPS)
|
||||
for call in client.list_directory.call_args_list:
|
||||
# The database root, which is where the rules grant .read.
|
||||
assert call.args == ("",)
|
||||
|
||||
|
||||
def test_the_client_is_built_against_the_configured_database(
|
||||
seeding: tuple,
|
||||
) -> None:
|
||||
"""Verifying against the wrong database would prove nothing."""
|
||||
_, _, client_factory = seeding
|
||||
|
||||
ss.seed_apps(_CONFIG, _ID_VALUE, _APPS)
|
||||
|
||||
assert client_factory.call_args.args[0] == _CONFIG.database_url
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"failure",
|
||||
[RemoteSyncError("rules denied"), FirebaseAuthError("token dead")],
|
||||
)
|
||||
def test_a_session_that_cannot_read_is_a_seed_error(
|
||||
seeding: tuple,
|
||||
failure: Exception,
|
||||
) -> None:
|
||||
"""Both failure shapes are caught, and neither reads as success.
|
||||
|
||||
list_directory is used rather than can_access_remote() precisely so these
|
||||
stay distinguishable in the message.
|
||||
"""
|
||||
_, _, client_factory = seeding
|
||||
client_factory.return_value.list_directory.side_effect = failure
|
||||
|
||||
with pytest.raises(ss.SeedError, match="cannot read the database"):
|
||||
ss.seed_apps(_CONFIG, _ID_VALUE, _APPS)
|
||||
|
||||
|
||||
def test_a_seed_error_names_the_failing_app(seeding: tuple) -> None:
|
||||
"""Which app broke is the first thing needed to fix it."""
|
||||
_, _, client_factory = seeding
|
||||
client_factory.return_value.list_directory.side_effect = RemoteSyncError("denied")
|
||||
|
||||
with pytest.raises(ss.SeedError, match="diet_guard was seeded but cannot read"):
|
||||
ss.seed_apps(_CONFIG, _ID_VALUE, _APPS)
|
||||
|
||||
|
||||
def test_a_seed_error_carries_the_apps_already_verified(seeding: tuple) -> None:
|
||||
"""So a partial run reports what is left instead of being reconstructed."""
|
||||
_, _, client_factory = seeding
|
||||
client_factory.return_value.list_directory.side_effect = [
|
||||
None,
|
||||
RemoteSyncError("denied"),
|
||||
]
|
||||
|
||||
with pytest.raises(ss.SeedError) as raised:
|
||||
ss.seed_apps(_CONFIG, _ID_VALUE, _APPS)
|
||||
|
||||
assert raised.value.done == ("diet_guard",)
|
||||
|
||||
|
||||
def test_a_seed_error_defaults_to_no_completed_apps() -> None:
|
||||
"""Constructed without a done tuple, nothing is claimed as working."""
|
||||
assert ss.SeedError("something broke").done == ()
|
||||
|
||||
|
||||
def test_seeding_no_apps_is_a_no_op(seeding: tuple) -> None:
|
||||
"""An empty selection must not report a spurious success."""
|
||||
_, _, client_factory = seeding
|
||||
|
||||
assert ss.seed_apps(_CONFIG, _ID_VALUE, ()) == []
|
||||
client_factory.assert_not_called()
|
||||
|
||||
|
||||
def test_the_account_email_is_reported_per_app(
|
||||
seeding: tuple,
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
"""The operator's check that the right Google account was used."""
|
||||
with caplog.at_level(logging.INFO, logger="seed_session"):
|
||||
ss.seed_apps(_CONFIG, _ID_VALUE, ("diet_guard",))
|
||||
|
||||
assert "diet_guard seeded as person@gmail.com" in caplog.text
|
||||
|
||||
|
||||
def test_the_config_email_is_used_when_google_returns_none(
|
||||
seeding: tuple,
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
"""Not every exchange echoes an email; the line must still be useful."""
|
||||
factory, _, _ = seeding
|
||||
factory.return_value.sign_in_with_google.return_value = None
|
||||
|
||||
with caplog.at_level(logging.INFO, logger="seed_session"):
|
||||
ss.seed_apps(_CONFIG, _ID_VALUE, ("diet_guard",))
|
||||
|
||||
assert f"diet_guard seeded as {_CONFIG.email}" in caplog.text
|
||||
220
crdt-sync/crdt_sync/tests/test_tool_seed_session_main.py
Normal file
220
crdt-sync/crdt_sync/tests/test_tool_seed_session_main.py
Normal file
@ -0,0 +1,220 @@
|
||||
"""Tests for ``main()`` in ``tool/seed_session``.
|
||||
|
||||
Split from :mod:`test_tool_seed_session` to stay under the 250-line cap.
|
||||
|
||||
The behaviour worth pinning here is what happens when a run dies partway. It
|
||||
leaves some apps working and some not, and saying exactly which is the
|
||||
difference between rerunning the ones that need it and a hunt through
|
||||
``~/.config`` for what actually happened -- so the rerun line is asserted to
|
||||
list the remaining apps and only those.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from crdt_sync._config import ConfigError
|
||||
from crdt_sync._firebase_auth import FirebaseAuthError
|
||||
from crdt_sync.tests.test_tool_seed_session import _CONFIG, _ID_VALUE
|
||||
from tool import seed_session as ss
|
||||
from tool.google_id_token import TokenError
|
||||
|
||||
_CLIENT_ID = "the-web-client-id"
|
||||
_CLIENT_CREDENTIAL = "the-web-client-secret"
|
||||
_ARGV = ["--client-id", _CLIENT_ID, "--client-secret", _CLIENT_CREDENTIAL]
|
||||
|
||||
|
||||
def test_main_seeds_every_default_app(caplog: pytest.LogCaptureFixture) -> None:
|
||||
"""With no --app, all of DEFAULT_APPS are seeded."""
|
||||
with (
|
||||
patch.object(ss.FirebaseConfig, "load", return_value=_CONFIG),
|
||||
patch.object(ss, "fetch_id_token", return_value=_ID_VALUE),
|
||||
patch.object(ss, "seed_apps", return_value=list(ss.DEFAULT_APPS)) as seeded,
|
||||
caplog.at_level(logging.INFO, logger="seed_session"),
|
||||
):
|
||||
code = ss.main(_ARGV)
|
||||
|
||||
assert code == 0
|
||||
assert seeded.call_args.args[2] == ss.DEFAULT_APPS
|
||||
assert f"{len(ss.DEFAULT_APPS)} desktop session(s)" in caplog.text
|
||||
|
||||
|
||||
def test_todo_is_among_the_default_apps() -> None:
|
||||
"""It grew a desktop wrapper with its own Firebase REST client.
|
||||
|
||||
Its credential cache needs seeding exactly like the Python daemons, which
|
||||
is why it is no longer grouped with the phone-only Flutter apps.
|
||||
"""
|
||||
assert "todo" in ss.DEFAULT_APPS
|
||||
|
||||
|
||||
def test_a_single_app_can_be_selected() -> None:
|
||||
"""--app narrows the run, which is what a rerun after a failure uses."""
|
||||
with (
|
||||
patch.object(ss.FirebaseConfig, "load", return_value=_CONFIG),
|
||||
patch.object(ss, "fetch_id_token", return_value=_ID_VALUE),
|
||||
patch.object(ss, "seed_apps", return_value=["diet_guard"]) as seeded,
|
||||
):
|
||||
code = ss.main([*_ARGV, "--app", "diet_guard"])
|
||||
|
||||
assert code == 0
|
||||
assert seeded.call_args.args[2] == ("diet_guard",)
|
||||
|
||||
|
||||
def test_the_app_flag_is_repeatable() -> None:
|
||||
"""Rerunning two failed apps should not need two invocations."""
|
||||
with (
|
||||
patch.object(ss.FirebaseConfig, "load", return_value=_CONFIG),
|
||||
patch.object(ss, "fetch_id_token", return_value=_ID_VALUE),
|
||||
patch.object(ss, "seed_apps", return_value=["diet_guard", "todo"]) as seeded,
|
||||
):
|
||||
ss.main([*_ARGV, "--app", "diet_guard", "--app", "todo"])
|
||||
|
||||
assert seeded.call_args.args[2] == ("diet_guard", "todo")
|
||||
|
||||
|
||||
def test_an_unknown_app_is_refused_by_argparse() -> None:
|
||||
"""The constrained choices exist because of a real failure.
|
||||
|
||||
A typo like "diet-guard" would otherwise create ~/.config/diet-guard/,
|
||||
verify against it happily, and report PASS while the real diet_guard
|
||||
stayed dead.
|
||||
"""
|
||||
with pytest.raises(SystemExit):
|
||||
ss.main([*_ARGV, "--app", "diet-guard"])
|
||||
|
||||
|
||||
def test_the_consent_flow_receives_the_client_and_port() -> None:
|
||||
"""A Web client needs the registered port verbatim, not a free one."""
|
||||
with (
|
||||
patch.object(ss.FirebaseConfig, "load", return_value=_CONFIG),
|
||||
patch.object(ss, "fetch_id_token", return_value=_ID_VALUE) as fetch,
|
||||
patch.object(ss, "seed_apps", return_value=[]),
|
||||
):
|
||||
ss.main([*_ARGV, "--port", "9999", "--no-browser"])
|
||||
|
||||
assert fetch.call_args.args == (_CLIENT_ID, _CLIENT_CREDENTIAL)
|
||||
assert fetch.call_args.kwargs == {"open_browser": False, "port": 9999}
|
||||
|
||||
|
||||
def test_the_default_port_is_the_registered_one() -> None:
|
||||
"""8765 is what is registered on the Web client as http://localhost:8765."""
|
||||
with (
|
||||
patch.object(ss.FirebaseConfig, "load", return_value=_CONFIG),
|
||||
patch.object(ss, "fetch_id_token", return_value=_ID_VALUE) as fetch,
|
||||
patch.object(ss, "seed_apps", return_value=[]),
|
||||
):
|
||||
ss.main(_ARGV)
|
||||
|
||||
assert fetch.call_args.kwargs["port"] == 8765
|
||||
|
||||
|
||||
def test_the_expected_uid_is_announced_before_the_flow(
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
"""So the wrong Google account can be spotted at the picker, not after."""
|
||||
with (
|
||||
patch.object(ss.FirebaseConfig, "load", return_value=_CONFIG),
|
||||
patch.object(ss, "fetch_id_token", return_value=_ID_VALUE),
|
||||
patch.object(ss, "seed_apps", return_value=[]),
|
||||
caplog.at_level(logging.INFO, logger="seed_session"),
|
||||
):
|
||||
ss.main(_ARGV)
|
||||
|
||||
assert _CONFIG.uid in caplog.text
|
||||
assert _CONFIG.email in caplog.text
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"failure",
|
||||
[
|
||||
ConfigError("no config"),
|
||||
FirebaseAuthError("wrong uid"),
|
||||
TokenError("consent refused"),
|
||||
],
|
||||
)
|
||||
def test_the_named_failures_return_1(
|
||||
failure: Exception,
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
"""Each is reported, not raised as a traceback."""
|
||||
with (
|
||||
patch.object(ss.FirebaseConfig, "load", return_value=_CONFIG),
|
||||
patch.object(ss, "fetch_id_token", side_effect=failure),
|
||||
caplog.at_level(logging.INFO, logger="seed_session"),
|
||||
):
|
||||
code = ss.main(_ARGV)
|
||||
|
||||
assert code == 1
|
||||
assert "FAIL" in caplog.text
|
||||
|
||||
|
||||
def test_an_unexpected_error_is_not_swallowed() -> None:
|
||||
"""The reason the handler names its four types instead of Exception."""
|
||||
with (
|
||||
patch.object(ss.FirebaseConfig, "load", return_value=_CONFIG),
|
||||
patch.object(ss, "fetch_id_token", side_effect=RuntimeError("a real bug")),
|
||||
pytest.raises(RuntimeError, match="a real bug"),
|
||||
):
|
||||
ss.main(_ARGV)
|
||||
|
||||
|
||||
def test_a_total_failure_suggests_rerunning_every_app(
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
"""Nothing verified, so nothing may be reported as already working."""
|
||||
with (
|
||||
patch.object(ss.FirebaseConfig, "load", return_value=_CONFIG),
|
||||
patch.object(ss, "fetch_id_token", return_value=_ID_VALUE),
|
||||
patch.object(ss, "seed_apps", side_effect=ss.SeedError("all dead")),
|
||||
caplog.at_level(logging.INFO, logger="seed_session"),
|
||||
):
|
||||
code = ss.main([*_ARGV, "--app", "diet_guard", "--app", "todo"])
|
||||
|
||||
assert code == 1
|
||||
assert "already working" not in caplog.text
|
||||
assert "--app diet_guard --app todo" in caplog.text
|
||||
|
||||
|
||||
def test_a_partial_failure_reports_what_already_works(
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
"""The apps that verified must not be reseeded needlessly."""
|
||||
partial = ss.SeedError("todo is dead", done=("diet_guard",))
|
||||
|
||||
with (
|
||||
patch.object(ss.FirebaseConfig, "load", return_value=_CONFIG),
|
||||
patch.object(ss, "fetch_id_token", return_value=_ID_VALUE),
|
||||
patch.object(ss, "seed_apps", side_effect=partial),
|
||||
caplog.at_level(logging.INFO, logger="seed_session"),
|
||||
):
|
||||
code = ss.main([*_ARGV, "--app", "diet_guard", "--app", "todo"])
|
||||
|
||||
assert code == 1
|
||||
assert "already working: diet_guard" in caplog.text
|
||||
|
||||
|
||||
def test_the_rerun_line_excludes_the_apps_that_already_work(
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
"""The whole value of the partial report is a copy-pasteable rerun."""
|
||||
partial = ss.SeedError("todo is dead", done=("diet_guard",))
|
||||
|
||||
with (
|
||||
patch.object(ss.FirebaseConfig, "load", return_value=_CONFIG),
|
||||
patch.object(ss, "fetch_id_token", return_value=_ID_VALUE),
|
||||
patch.object(ss, "seed_apps", side_effect=partial),
|
||||
caplog.at_level(logging.INFO, logger="seed_session"),
|
||||
):
|
||||
ss.main([*_ARGV, "--app", "diet_guard", "--app", "todo"])
|
||||
|
||||
assert "rerun with: --app todo" in caplog.text
|
||||
|
||||
|
||||
def test_both_credentials_are_required() -> None:
|
||||
"""Neither half of the OAuth client is optional."""
|
||||
with pytest.raises(SystemExit):
|
||||
ss.main(["--client-id", _CLIENT_ID])
|
||||
@ -125,6 +125,7 @@ addopts = [
|
||||
"--strict-config",
|
||||
"-ra",
|
||||
"--cov=crdt_sync",
|
||||
"--cov=tool",
|
||||
"--cov-branch",
|
||||
"--cov-report=term-missing",
|
||||
"--cov-report=lcov",
|
||||
@ -136,7 +137,10 @@ filterwarnings = [
|
||||
]
|
||||
|
||||
[tool.coverage.run]
|
||||
source = ["crdt_sync"]
|
||||
# `tool` is measured but deliberately not installed: [tool.setuptools] ships
|
||||
# only crdt_sync, so these one-shot scripts stay out of every consumer's
|
||||
# site-packages. They still run and import as a package from this directory.
|
||||
source = ["crdt_sync", "tool"]
|
||||
branch = true
|
||||
omit = [
|
||||
"*/__pycache__/*",
|
||||
|
||||
@ -1,197 +0,0 @@
|
||||
> **This file is a ready-to-use prompt.** Open this repo (`~/utils`) and say
|
||||
> "do post-250-cap-cleanup". It is self-contained -- it needs no context from
|
||||
> any other session.
|
||||
>
|
||||
> Generated 2026-08-22 at the end of the session that finished
|
||||
> `refactor_claude_todo.md` (the 250-line cap). Everything below was measured
|
||||
> in that session; **re-verify each figure before trusting it**, since the
|
||||
> numbers are a snapshot.
|
||||
|
||||
## ⛔ WHEN YOU FINISH THIS PROMPT
|
||||
|
||||
Delete this file and commit that deletion together with the work:
|
||||
|
||||
```bash
|
||||
git rm prompts/post-250-cap-cleanup.md
|
||||
```
|
||||
|
||||
A finished prompt left in the repo is indistinguishable from a pending one,
|
||||
and the next session will re-run it. If you complete only some of the four
|
||||
tasks, do **not** delete it -- strike through the finished ones instead and
|
||||
leave the rest.
|
||||
|
||||
**Current state: only Task 2 is left.** Delete this file once `tool/` is
|
||||
covered and the config flip has landed -- not before.
|
||||
|
||||
## Context
|
||||
|
||||
The 250-line file cap is done and enforced: `bash
|
||||
scripts/check_file_length.sh --all` exits 0, a pre-commit hook blocks an
|
||||
over-cap commit, and `.github/workflows/file-length.yml` runs the same check
|
||||
on push. **Do not undo any of that.** Every new file this prompt creates must
|
||||
also stay at or under 250 lines -- the hook will block your commit otherwise,
|
||||
which is the point.
|
||||
|
||||
Four loose ends were deliberately left. **Three are now done** (1, 3 and 4 --
|
||||
see the struck-through sections, which record what was actually found; the
|
||||
prompt's original diagnosis was wrong for both 1 and 4). **Only Task 2
|
||||
remains.**
|
||||
|
||||
---
|
||||
|
||||
## ~~Task 1 -- make `web-ui-tests` green~~ -- DONE (53f2816)
|
||||
|
||||
The diagnosis above was wrong, so it is replaced rather than struck through.
|
||||
`dist/` had not drifted: all 16 files were byte-identical to a fresh build
|
||||
except for a **trailing newline** that `tsc` does not emit.
|
||||
|
||||
At `03bf1ed` the subproject config had no `exclude`, so pre-commit's
|
||||
`end-of-file-fixer` appended a newline to each generated file. `eaa5683` added
|
||||
`exclude: ^web_ui/dist/` so it would not recur, but never reverted the
|
||||
newlines already committed -- leaving a `dist/` that no `pnpm build` could
|
||||
reproduce, and a job that could never pass.
|
||||
|
||||
It looked fine locally because `tsc -b` is incremental: with a warm
|
||||
`tsconfig.tsbuildinfo` it skips emit entirely, so `pnpm build` was a no-op and
|
||||
showed no diff. CI has no cache, always emits, always failed. To reproduce
|
||||
locally, delete `web_ui/tsconfig.tsbuildinfo` first -- otherwise you are
|
||||
testing nothing.
|
||||
|
||||
Fixed by committing the real `tsc` output. Verified green on CI (run
|
||||
32578353684), `pnpm lint` clean, `pnpm coverage` 84 tests / 100%.
|
||||
|
||||
---
|
||||
|
||||
## Task 2 -- put `crdt-sync/tool/` under test at 100% coverage
|
||||
|
||||
**Read this scope note before starting; it is bigger than it first looks.**
|
||||
|
||||
`crdt-sync/pyproject.toml` measures `--cov=crdt_sync` with
|
||||
`source = ["crdt_sync"]`, so the whole `tool/` package is currently
|
||||
unmeasured. The trigger for this task was `tool/_oauth_callback.py` (105
|
||||
lines, extracted during the cap work, whose `_start_callback_server` runtime
|
||||
path is unexercised) -- but adding `tool` to the coverage source pulls in
|
||||
**seven modules, ~1350 lines**, none of which have tests today:
|
||||
|
||||
| lines | file |
|
||||
| ----: | :--- |
|
||||
| 250 | `tool/seed_session.py` |
|
||||
| 243 | `tool/link_google.py` |
|
||||
| 233 | `tool/google_id_token.py` |
|
||||
| 216 | `tool/migrate_github_to_firebase.py` |
|
||||
| 212 | `tool/preflight_firebase.py` |
|
||||
| 105 | `tool/_oauth_callback.py` |
|
||||
| 89 | `tool/interop_seed.py` |
|
||||
| 6 | `tool/__init__.py` |
|
||||
|
||||
The bar in this repo is **100% branch coverage, and omitting packages from
|
||||
coverage is forbidden** (`~/.claude/memories/code-quality.md`: "NEVER omit
|
||||
packages from coverage. Write tests for everything." and "even if it takes
|
||||
hours"). So the honest shape of this task is: test all of `tool/`, not just
|
||||
the one file.
|
||||
|
||||
**Suggested order** -- land each as its own commit so partial progress is
|
||||
useful:
|
||||
|
||||
1. `_oauth_callback.py` first. It is the reason this task exists and the only
|
||||
one with no network dependency: `_free_port` binds a real socket,
|
||||
`_CallbackHandler` can be driven with a fake request, and
|
||||
`_start_callback_server` can be exercised against `http.client` on the port
|
||||
it picks. Do this one even if you do nothing else.
|
||||
2. `google_id_token.py` -- `fetch_id_token` is a `requests` call; mock at the
|
||||
session boundary the way `crdt_sync/tests/test_firebase_auth.py` already
|
||||
does. `main()` is argparse; test it via `main(["--client-id", ...])`.
|
||||
3. The rest, largest-payoff first.
|
||||
|
||||
Only after every module is covered, flip the config:
|
||||
|
||||
```toml
|
||||
addopts = [..., "--cov=crdt_sync", "--cov=tool", ...]
|
||||
[tool.coverage.run]
|
||||
source = ["crdt_sync", "tool"]
|
||||
```
|
||||
|
||||
Flipping it earlier makes the suite fail on the 100% gate for every module you
|
||||
have not reached yet, which blocks unrelated commits -- so it is the **last**
|
||||
step, not the first.
|
||||
|
||||
**Traps, all hit during the cap work:**
|
||||
|
||||
- Tests live in `crdt-sync/crdt_sync/tests/`, and `testpaths` points there. A
|
||||
`tool/` test still belongs under that directory (e.g.
|
||||
`crdt_sync/tests/test_tool_oauth_callback.py`) unless you also extend
|
||||
`testpaths` -- decide once and be consistent.
|
||||
- `tool` is imported as a package from the `crdt-sync` root
|
||||
(`python3 -m tool.google_id_token`, and `seed_session.py` does
|
||||
`from tool.google_id_token import ...`). Do not "fix" those to relative
|
||||
imports.
|
||||
- Do **not** add `# noqa` or `# type: ignore` anywhere; the repo bans them and
|
||||
a pre-commit hook blocks them. If lint fights you, fix the code.
|
||||
- Run the CI-pinned ruff, not whatever `ls | head -1` finds. The cache holds
|
||||
three versions and CI pins **0.15.2**:
|
||||
`/home/kuhy/.cache/pre-commit/repodhz30fnk/py_env-python3/bin/ruff`.
|
||||
Confirm with `--version`; 0.14.5 misses findings that fail CI.
|
||||
- Verify with `bash scripts/check_file_length.sh --all` and
|
||||
`pre-commit run --config crdt-sync/.pre-commit-config.yaml --all-files`
|
||||
(the `--all-files` run catches ruff pruning re-export imports, which broke
|
||||
`import crdt_sync` three times during the cap work).
|
||||
|
||||
**Done when:** `source = ["crdt_sync", "tool"]` is in effect and
|
||||
`bash scripts/run_subproject_tests.sh crdt-sync` still reports 100% with the
|
||||
suite green. Baseline before you start: **259 passed, 100%**.
|
||||
|
||||
---
|
||||
|
||||
## ~~Task 3 -- resolve the three dirty working-tree items~~ -- DONE
|
||||
|
||||
- **`seed_session.py`** -- both files its comment cites were re-confirmed
|
||||
present, so the change was committed as-is (9d638fb).
|
||||
- **`firebase-debug.log`** -- deleted, and the root `.gitignore` now covers it
|
||||
plus the sibling logs the Firebase CLI writes (e0eef3d).
|
||||
- **`staged/`** -- the user chose *apply*. `APPLY.sh` installed the split into
|
||||
`~/.claude` (committed there as e0cf24a): `phone_deploy.sh` 311 -> 140 lines
|
||||
with three sourced libs, 12/12 function parity, and the unreachable-device
|
||||
path still exiting 30. `staged/` was then removed; the pre-split original
|
||||
remains recoverable from `~/.claude` at `80cd45e`.
|
||||
**Still unverified:** the build/install/launch tail, which needs a real APK
|
||||
install on the phone (`bash ~/.claude/scripts/phone_deploy.sh ~/todo
|
||||
--release`).
|
||||
|
||||
---
|
||||
|
||||
## ~~Task 4 -- fix the stale skill pointer~~ -- DONE (~/.claude e0cf24a)
|
||||
|
||||
The description above was partly wrong: `README.md` **does** still hold the
|
||||
per-stack patterns and the "Do NOT" list. What actually split out during the
|
||||
cap work was the pointer-free-operability and screen-size material, into
|
||||
`operability.md` (rules) and `operability-patterns.md` (per-stack code);
|
||||
README's "Pointer-free + small-screen" section is now a stub pointing at them.
|
||||
|
||||
`~/.claude/skills/unified-design-system/SKILL.md` now lists both new files and
|
||||
tells the reader to read `operability.md` before building any interactive
|
||||
widget, since its rules are marked required. All six relative links were
|
||||
checked to resolve. This edit lives outside `~/utils`, so `git status` here
|
||||
will never show it.
|
||||
|
||||
---
|
||||
|
||||
## Verify (all four)
|
||||
|
||||
```bash
|
||||
cd ~/utils
|
||||
bash scripts/check_file_length.sh --all # must exit 0
|
||||
bash scripts/run_subproject_tests.sh crdt-sync # 100% coverage
|
||||
pre-commit run --config crdt-sync/.pre-commit-config.yaml --all-files
|
||||
git status --short # should be empty
|
||||
gh run list --limit 10 # all workflows green
|
||||
```
|
||||
|
||||
`web-ui-tests` was the one red workflow; it went green at 53f2816. Note that
|
||||
`git status` here cannot see the Task 3/4 edits under `~/.claude` -- those are
|
||||
committed in that repo (e0cf24a), not this one.
|
||||
|
||||
One finding outside the four tasks, left for the user to decide:
|
||||
`~/.claude/scripts/finish.sh` is **309 lines**, over the cap. It does not
|
||||
block anything today -- the hook checks staged files only, so it fires only if
|
||||
a commit stages that file -- but it is the last known over-cap file in that
|
||||
repo.
|
||||
Loading…
Reference in New Issue
Block a user