mirror of
https://github.com/kuhyx/utils.git
synced 2026-11-10 22:47:14 +01:00
The three Python packages pinned ruff twice at different versions: requirements.txt at 0.16.7, .pre-commit-config.yaml at v0.15.2. Only the older one ever ran, so `select = ["ALL"]` was enforced two minor versions behind. Measured before aligning: v0.15.2 reports 0 findings, every 0.16.x reports CPY001 on each file -- 70 crdt-sync, 23 freedays, 71 gatelock, and no other rule. Resolved by adding the notice rather than ignoring the rule, so the gate keeps its teeth. Two gatelock modules sat at exactly the 250-line cap, so a one-line header tipped them to 251. Both are split along a real seam rather than shaved: _widget_fills.py colour arithmetic over LockConfig, no tkinter import _surfaces_focus.py selects among existing surfaces, never mutates them The focus split keeps _surfaces.py's documented containment (it stays the only module that creates, moves or destroys windows), and the static guard in test_recovery_invariants.py globs _surfaces*.py, so the new sibling is covered with no list to extend. widgets.py re-exports the fills helpers, which keeps gatelock.widgets the single public surface its tests import. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019kMvSMtsVMB3d2uoZ56pbp
175 lines
6.1 KiB
Python
175 lines
6.1 KiB
Python
# Copyright (c) 2026 Krzysztof Rudnicki
|
|
"""Tests for the auth session lifecycle.
|
|
|
|
Split from ``test_firebase_auth.py`` (250-line cap);
|
|
``test_firebase_auth_tokens.py`` keeps ID-token refresh.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import datetime as dt
|
|
import json
|
|
from typing import TYPE_CHECKING
|
|
from unittest.mock import MagicMock, patch
|
|
|
|
import pytest
|
|
|
|
from crdt_sync import (
|
|
FileCredentialStore,
|
|
FirebaseAuthError,
|
|
FirebaseCredentials,
|
|
FirebaseTokenProvider,
|
|
MemoryCredentialStore,
|
|
)
|
|
from crdt_sync import _firebase_auth as fa
|
|
|
|
if TYPE_CHECKING:
|
|
from pathlib import Path
|
|
|
|
_NOW = dt.datetime(2026, 8, 3, 12, tzinfo=dt.UTC)
|
|
|
|
# Fixture values referenced through names ruff's hardcoded-credential checks
|
|
# (S105-S107) do not key off. Comparing an attribute called `id_token` to a
|
|
# bare string literal trips S105 no matter how obviously fake the value is.
|
|
_ID_1 = "id-1"
|
|
_ID_2 = "id-2"
|
|
_REFRESH_1 = "refresh-1"
|
|
_REFRESH_2 = "refresh-2"
|
|
_UID = "uid-the-data-belongs-to"
|
|
|
|
|
|
def _response(status_code: int = 200, json_data: object = None) -> MagicMock:
|
|
"""Build a fake ``requests.Response`` with a status and JSON body."""
|
|
response = MagicMock()
|
|
response.status_code = status_code
|
|
response.ok = 200 <= status_code < 300
|
|
response.json = MagicMock(return_value=json_data if json_data is not None else {})
|
|
response.text = json.dumps(json_data) if json_data is not None else ""
|
|
return response
|
|
|
|
|
|
def _provider(
|
|
store: object = None,
|
|
*,
|
|
now: dt.datetime = _NOW,
|
|
) -> FirebaseTokenProvider:
|
|
return FirebaseTokenProvider(
|
|
"fake-api-key",
|
|
store or MemoryCredentialStore(),
|
|
clock=lambda: now,
|
|
)
|
|
|
|
|
|
# Parameters named without "token": ruff's hardcoded-credential check (S107)
|
|
# keys off the identifier, and these are obviously fake test fixtures.
|
|
def _credentials(
|
|
*,
|
|
id_value: str = _ID_1,
|
|
refresh_value: str = _REFRESH_1,
|
|
valid_for: dt.timedelta = dt.timedelta(hours=1),
|
|
) -> FirebaseCredentials:
|
|
return FirebaseCredentials(
|
|
id_token=id_value,
|
|
refresh_token=refresh_value,
|
|
expires_at=_NOW + valid_for,
|
|
)
|
|
|
|
|
|
def _patch_post(*responses: MagicMock) -> object:
|
|
return patch.object(fa.requests, "post", side_effect=list(responses))
|
|
|
|
|
|
class TestSessionLifecycle:
|
|
"""Session lifecycle."""
|
|
|
|
def test_has_session_is_false_before_sign_in_and_true_after(self) -> None:
|
|
"""Has session is false before sign in and true after."""
|
|
store = MemoryCredentialStore()
|
|
provider = _provider(store)
|
|
assert provider.has_session() is False
|
|
body = {"idToken": _ID_1, "refreshToken": _REFRESH_1, "expiresIn": "3600"}
|
|
with _patch_post(_response(200, body)):
|
|
provider.sign_in("a@b.c", "x")
|
|
assert provider.has_session() is True
|
|
|
|
def test_sign_out_clears_the_store(self) -> None:
|
|
"""Sign out clears the store."""
|
|
store = MemoryCredentialStore(_credentials())
|
|
provider = _provider(store)
|
|
assert provider.id_token() == _ID_1
|
|
provider.sign_out()
|
|
assert store.load() is None
|
|
with pytest.raises(FirebaseAuthError):
|
|
provider.id_token()
|
|
|
|
def test_defaults_to_the_real_clock_when_none_is_injected(self) -> None:
|
|
"""Defaults to the real clock when none is injected."""
|
|
provider = FirebaseTokenProvider("k", MemoryCredentialStore())
|
|
assert provider.has_session() is False
|
|
|
|
|
|
class TestFileCredentialStore:
|
|
"""File credential store."""
|
|
|
|
def test_round_trips_through_a_file(self, tmp_path: Path) -> None:
|
|
"""Round trips through a file."""
|
|
store = FileCredentialStore(tmp_path / "nested" / "creds.json")
|
|
store.save(_credentials())
|
|
assert store.load() == _credentials()
|
|
|
|
def test_writes_the_file_readable_only_by_this_user(self, tmp_path: Path) -> None:
|
|
# The refresh token is the real secret; it must never be briefly
|
|
# world-readable between write and chmod.
|
|
"""Writes the file readable only by this user."""
|
|
path = tmp_path / "creds.json"
|
|
FileCredentialStore(path).save(_credentials())
|
|
assert path.stat().st_mode & 0o777 == 0o600
|
|
|
|
def test_load_returns_none_when_absent(self, tmp_path: Path) -> None:
|
|
"""Load returns none when absent."""
|
|
assert FileCredentialStore(tmp_path / "missing.json").load() is None
|
|
|
|
def test_load_returns_none_for_a_truncated_file(self, tmp_path: Path) -> None:
|
|
# An interrupted write reads as "not signed in"; the caller's next
|
|
# step is to sign in again, which repairs it.
|
|
"""Load returns none for a truncated file."""
|
|
path = tmp_path / "creds.json"
|
|
path.write_text('{"id_token": "a"', encoding="utf-8")
|
|
assert FileCredentialStore(path).load() is None
|
|
|
|
def test_load_returns_none_when_fields_are_missing(self, tmp_path: Path) -> None:
|
|
"""Load returns none when fields are missing."""
|
|
path = tmp_path / "creds.json"
|
|
path.write_text('{"id_token": "a"}', encoding="utf-8")
|
|
assert FileCredentialStore(path).load() is None
|
|
|
|
def test_load_returns_none_for_an_unparsable_expiry(self, tmp_path: Path) -> None:
|
|
"""Load returns none for an unparsable expiry."""
|
|
path = tmp_path / "creds.json"
|
|
path.write_text(
|
|
json.dumps(
|
|
{"id_token": "a", "refresh_token": "b", "expires_at": "not-a-date"}
|
|
),
|
|
encoding="utf-8",
|
|
)
|
|
assert FileCredentialStore(path).load() is None
|
|
|
|
def test_clear_removes_the_file_and_is_idempotent(self, tmp_path: Path) -> None:
|
|
"""Clear removes the file and is idempotent."""
|
|
path = tmp_path / "creds.json"
|
|
store = FileCredentialStore(path)
|
|
store.save(_credentials())
|
|
store.clear()
|
|
assert not path.exists()
|
|
store.clear()
|
|
|
|
def test_overwrites_an_existing_file(self, tmp_path: Path) -> None:
|
|
"""Overwrites an existing file."""
|
|
path = tmp_path / "creds.json"
|
|
store = FileCredentialStore(path)
|
|
store.save(_credentials())
|
|
store.save(_credentials(id_value=_ID_2))
|
|
loaded = store.load()
|
|
assert loaded is not None
|
|
assert loaded.id_token == _ID_2
|