Cover the store check error paths
Some checks are pending
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint,dependency-freshness) (push) Waiting to run
Tests / test (push) Waiting to run
Tests / web-coverage (push) Waiting to run
repo-contract / repo contract (push) Waiting to run

Todo: 85af719b

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Krzysztof Rudnicki 2026-11-22 17:18:12 +01:00
parent b29b708fb8
commit 0c949d399f
6 changed files with 196 additions and 84 deletions

View File

@ -0,0 +1,68 @@
"""A fake machine for the store checks: answers curl, getent, iptables, journalctl."""
from __future__ import annotations
from typing import TYPE_CHECKING, Any
from unittest.mock import MagicMock, patch
from steam_backlog_enforcer import _store_verify as sv
from steam_backlog_enforcer.config import BLOCKED_DOMAINS
if TYPE_CHECKING:
from collections.abc import Iterator
from pathlib import Path
V4 = ".".join(["0"] * 4) # The IPv4 sinkhole.
class FakeHost:
"""Answers the commands the checks run, from settable machine state."""
def __init__(self, hosts: Path) -> None:
"""Start as a correctly unblocked, online machine."""
self.hosts = hosts
self.sleep = MagicMock()
self.chain = False
self.reachable = {sv.STORE_URL: True, sv.CONTROL_URL: True}
self.resolves: dict[str, str] = dict.fromkeys(BLOCKED_DOMAINS, "1.2.3.4")
self.calls: list[list[str]] = []
def run(self, cmd: list[str], **_kw: object) -> MagicMock:
"""Fake ``subprocess.run``."""
self.calls.append(cmd)
out, rc = "", 0
if cmd[0] == sv.CURL:
rc = 0 if _next(self.reachable, cmd[-1]) else 7
out = "200" if rc == 0 else "curl: (7) Failed to connect"
elif cmd[0] == sv.GETENT:
addr = _next(self.resolves, cmd[-1])
out = f"{addr} STREAM {cmd[-1]}\n" if addr else ""
rc = 0 if addr else 2
elif "-S" in cmd:
rc = 0 if self.chain else 1
out = "-N STEAM_ENFORCER\n-A STEAM_ENFORCER -d 1.2.3.4 -j DROP"
out = out if self.chain else "iptables: No chain/target/match."
elif cmd[0] == sv.JOURNALCTL:
out = "\n".join(f"journal line {i}" for i in range(50))
return MagicMock(returncode=rc, stdout=out, stderr="")
def _next(table: dict[str, Any], key: str) -> object:
"""The value for *key*; a list is a sequence of answers, one per call."""
value = table[key]
if isinstance(value, list):
return value.pop(0) if len(value) > 1 else value[0]
return value
def fake_host(tmp_path: Path) -> Iterator[FakeHost]:
"""Patch the checks onto a fresh :class:`FakeHost`; yield it."""
hosts = tmp_path / "hosts"
fake = FakeHost(hosts)
hosts.write_text("127.0.0.1 localhost\n", encoding="utf-8")
with (
patch(f"{sv.__name__}.time.sleep") as fake.sleep,
patch(f"{sv.__name__}.subprocess.run", side_effect=fake.run),
patch(f"{sv.__name__}.HOSTS_FILE", hosts),
):
yield fake

View File

@ -7,7 +7,7 @@ from unittest.mock import MagicMock, patch
import pytest
from steam_backlog_enforcer import _ctl_ops
from steam_backlog_enforcer import _ctl_client, _ctl_ops
from steam_backlog_enforcer._ctl_protocol import CtlError
from steam_backlog_enforcer._store_check_report import (
Check,
@ -50,3 +50,11 @@ def test_store_reports_hands_back_queued_reports() -> None:
queued = [{"title": "Store re-block verification failed: dns"}]
with patch.object(_ctl_ops, "take_store_reports", return_value=queued):
assert _ctl_ops.op_store_reports(make_ctx(), {}) == {"reports": queued}
def test_client_store_reports_keeps_only_objects() -> None:
"""The client returns the report objects and drops anything malformed."""
reply = {"reports": [{"title": "t"}, "junk"]}
with patch.object(_ctl_client, "call", return_value=reply) as call:
assert _ctl_client.store_reports() == [{"title": "t"}]
call.assert_called_once_with("store_reports")

View File

@ -95,3 +95,9 @@ def test_failed_write_reports_failure_and_relocks(tmp_path: Path) -> None:
ok = rewrite_hosts_lines(lambda line: f"# {line}", "done")
assert ok is False
relock.assert_called_once()
def test_fully_blocked_is_false_without_hosts_file(tmp_path: Path) -> None:
"""An unreadable /etc/hosts never counts as fully blocked."""
with patch(f"{PKG}.HOSTS_FILE", tmp_path / "missing"):
assert store_blocker.hosts_fully_block_store() is False

View File

@ -2,7 +2,7 @@
from __future__ import annotations
from typing import TYPE_CHECKING, Any
from typing import TYPE_CHECKING
from unittest.mock import MagicMock, patch
import pytest
@ -11,67 +11,20 @@ from steam_backlog_enforcer import _store_verify as sv
from steam_backlog_enforcer._store_check_report import NETWORK_DOWN, StoreVerifyError
from steam_backlog_enforcer._store_verify import _run as run_command
from steam_backlog_enforcer.config import BLOCKED_DOMAINS
from steam_backlog_enforcer.tests._fake_store_host import V4 as _V4
from steam_backlog_enforcer.tests._fake_store_host import FakeHost, fake_host
if TYPE_CHECKING:
from collections.abc import Iterator
from pathlib import Path
_STORE = "store.steampowered.com"
_V4 = ".".join(["0"] * 4) # The IPv4 sinkhole.
class FakeHost:
"""Answers the commands the checks run, from settable machine state."""
def __init__(self, hosts: Path) -> None:
"""Start as a correctly unblocked, online machine."""
self.hosts = hosts
self.sleep = MagicMock()
self.chain = False
self.reachable = {sv.STORE_URL: True, sv.CONTROL_URL: True}
self.resolves: dict[str, str] = dict.fromkeys(BLOCKED_DOMAINS, "1.2.3.4")
self.calls: list[list[str]] = []
def run(self, cmd: list[str], **_kw: object) -> MagicMock:
"""Fake ``subprocess.run``."""
self.calls.append(cmd)
out, rc = "", 0
if cmd[0] == sv.CURL:
rc = 0 if _next(self.reachable, cmd[-1]) else 7
out = "200" if rc == 0 else "curl: (7) Failed to connect"
elif cmd[0] == sv.GETENT:
addr = _next(self.resolves, cmd[-1])
out = f"{addr} STREAM {cmd[-1]}\n" if addr else ""
rc = 0 if addr else 2
elif "-S" in cmd:
rc = 0 if self.chain else 1
out = "-N STEAM_ENFORCER\n-A STEAM_ENFORCER -d 1.2.3.4 -j DROP"
out = out if self.chain else "iptables: No chain/target/match."
elif cmd[0] == sv.JOURNALCTL:
out = "\n".join(f"journal line {i}" for i in range(50))
return MagicMock(returncode=rc, stdout=out, stderr="")
def _next(table: dict[str, Any], key: str) -> object:
"""The value for *key*; a list is a sequence of answers, one per call."""
value = table[key]
if isinstance(value, list):
return value.pop(0) if len(value) > 1 else value[0]
return value
@pytest.fixture(name="host")
def fixture_host(tmp_path: Path) -> Iterator[FakeHost]:
"""A fake machine with an empty /etc/hosts."""
hosts = tmp_path / "hosts"
fake = FakeHost(hosts)
hosts.write_text("127.0.0.1 localhost\n", encoding="utf-8")
with (
patch(f"{sv.__name__}.time.sleep") as fake.sleep,
patch(f"{sv.__name__}.subprocess.run", side_effect=fake.run),
patch(f"{sv.__name__}.HOSTS_FILE", hosts),
):
yield fake
yield from fake_host(tmp_path)
def _hosts(host: FakeHost, text: str) -> None:
@ -205,35 +158,3 @@ def test_error_carries_report(host: FakeHost) -> None:
err = StoreVerifyError(sv.check_unblock())
assert str(err) == "Store unblock failed: iptables"
assert err.report.failed_check == "iptables"
def test_unblock_https_settles_after_dns_reload(host: FakeHost) -> None:
"""Resolution fails for a moment after a hosts edit: retried, then ok."""
host.reachable[sv.STORE_URL] = [False, False, True]
report = sv.check_unblock()
assert report.ok
assert host.sleep.call_count == 2
def test_unblock_https_gives_up_after_attempts(host: FakeHost) -> None:
"""A store that stays unreachable fails after the last attempt."""
host.reachable[sv.STORE_URL] = False
assert sv.check_unblock().failed_check == "https"
store_probes = [c for c in host.calls if c[-1] == sv.STORE_URL]
assert len(store_probes) == sv.SETTLE_ATTEMPTS
def test_reblock_no_answer_counts_as_blocked(host: FakeHost) -> None:
"""systemd-resolved answers no address for a sinkholed name: blocked."""
host.resolves = dict.fromkeys(BLOCKED_DOMAINS, "")
host.reachable[sv.STORE_URL] = False
report = sv.check_reblock()
assert report.ok
def test_reblock_settles_stale_cache(host: FakeHost) -> None:
"""A cached real address and an answering store settle to blocked."""
host.resolves = dict.fromkeys(BLOCKED_DOMAINS, _V4)
host.resolves[_STORE] = ["2.18.70.115", _V4]
host.reachable[sv.STORE_URL] = [True, False]
assert sv.check_reblock().ok

View File

@ -0,0 +1,76 @@
"""Store checks repeat until name resolution catches up with a hosts edit."""
from __future__ import annotations
from typing import TYPE_CHECKING
from unittest.mock import MagicMock
import pytest
from steam_backlog_enforcer import _store_verify as sv
from steam_backlog_enforcer.config import BLOCKED_DOMAINS
from steam_backlog_enforcer.tests._fake_store_host import V4 as _V4
from steam_backlog_enforcer.tests._fake_store_host import FakeHost, fake_host
if TYPE_CHECKING:
from collections.abc import Iterator
from pathlib import Path
_STORE = "store.steampowered.com"
@pytest.fixture(name="host")
def fixture_host(tmp_path: Path) -> Iterator[FakeHost]:
"""A fake machine with an empty /etc/hosts."""
yield from fake_host(tmp_path)
def test_unblock_https_settles_after_dns_reload(host: FakeHost) -> None:
"""Resolution fails for a moment after a hosts edit: retried, then ok."""
host.reachable[sv.STORE_URL] = [False, False, True]
report = sv.check_unblock()
assert report.ok
assert host.sleep.call_count == 2
def test_unblock_https_gives_up_after_attempts(host: FakeHost) -> None:
"""A store that stays unreachable fails after the last attempt."""
host.reachable[sv.STORE_URL] = False
assert sv.check_unblock().failed_check == "https"
store_probes = [c for c in host.calls if c[-1] == sv.STORE_URL]
assert len(store_probes) == sv.SETTLE_ATTEMPTS
def test_reblock_no_answer_counts_as_blocked(host: FakeHost) -> None:
"""systemd-resolved answers no address for a sinkholed name: blocked."""
host.resolves = dict.fromkeys(BLOCKED_DOMAINS, "")
host.reachable[sv.STORE_URL] = False
report = sv.check_reblock()
assert report.ok
def test_reblock_settles_stale_cache(host: FakeHost) -> None:
"""A cached real address and an answering store settle to blocked."""
host.resolves = dict.fromkeys(BLOCKED_DOMAINS, _V4)
host.resolves[_STORE] = ["2.18.70.115", _V4]
host.reachable[sv.STORE_URL] = [True, False]
assert sv.check_reblock().ok
@pytest.mark.usefixtures("host")
def test_verify_passing_first_time_runs_no_repair() -> None:
"""Checks that hold at once skip the repair and the evidence."""
repair = MagicMock()
report = sv.verify(sv.check_unblock, repair)
assert report.ok
repair.assert_not_called()
assert not report.evidence
def test_unreadable_hosts_is_reported_not_raised(host: FakeHost) -> None:
"""A missing /etc/hosts does not crash the checks or the evidence."""
host.hosts.unlink()
host.chain = True
report = sv.verify(sv.check_unblock)
assert report.evidence["/etc/hosts store lines"] == ""
assert report.failed_check == "iptables"

View File

@ -2,7 +2,9 @@
from __future__ import annotations
import json
from typing import TYPE_CHECKING
from unittest.mock import patch
import pytest
@ -122,3 +124,34 @@ def test_unparsable_reply_raises(ctype: str, body: str) -> None:
"""A reply with no JSON-RPC object in it is a FilingError."""
with pytest.raises(FilingError, match="unparsable"):
_parse(ctype, body)
def _reply(message: dict[str, object]) -> tuple[str, str, None]:
return "application/json", json.dumps(message), None
def test_rpc_error_raises() -> None:
"""A JSON-RPC error answer is a FilingError naming the method."""
error = _reply({"jsonrpc": "2.0", "id": 1, "error": {"message": "boom"}})
with (
patch.object(_Mcp, "_post", return_value=error),
pytest.raises(FilingError, match="initialize"),
):
_Mcp("http://127.0.0.1:9/mcp", "t").call("list_tasks", {})
def test_tool_error_raises() -> None:
"""A tool that reports isError is a FilingError with its text."""
ok = _reply({"jsonrpc": "2.0", "id": 1, "result": {}})
bad = _reply(
{
"jsonrpc": "2.0",
"id": 2,
"result": {"isError": True, "content": [{"type": "text", "text": "no"}]},
}
)
with (
patch.object(_Mcp, "_post", side_effect=[ok, ok, bad]),
pytest.raises(FilingError, match="add_task: no"),
):
_Mcp("http://127.0.0.1:9/mcp", "t").call("add_task", {})