steam-backlog-enforcer/steam_backlog_enforcer/tests/test_serve_guard.py
Krzysztof kuhy Rudnicki 47f77f5f1e
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (push) Waiting to run
Tests / test (push) Waiting to run
Make serve re-runnable, and cover it to 100%
The serve rework was sitting untracked: a /proc-based port guard, the
start-or-defer decision, and a stale-bundle rebuild. It had no tests, and it
changed cmd_serve(_config, state) to cmd_serve(argv) without updating the one
test that called it, so the suite was red and coverage was 251 lines short.

Tests, all against fakes:
- _fake_proc builds a synthetic /proc. _NET_TCP is derived from _PROC at
  import time, so patch_proc redirects both; patching _PROC alone would have
  had these tests parse the host's real process table.
- _serve_guard is split across two test files to stay under the 250-line cap.
  os is replaced wholesale in every termination test, so no signal can reach a
  real process even if the guard's self-protection were removed.
- _web_build mocks subprocess entirely and redirects every path constant into
  tmp_path. _no_subprocess now blocks _web_build.subprocess.run too: an
  unguarded test would fire a real `npm run build`, rewriting web/dist and
  perturbing frontend_is_stale() for every later test in the run.

Source changes, both required rather than incidental:
- _serve_guard's wildcard match was a `# noqa: S104` on a "0.0.0.0" literal,
  which the no-noqa hook rejects outright. It is now the all-zero hex column
  /proc actually prints, so the dotted-quad literal never appears.
- main/__init__.py's serve dispatch arm was itself uncovered; it now has a
  test asserting the raw argv passes through unparsed.

Also drops the document.hidden guard from useBudgetPoll: it skipped the very
first load, so the budget panel sat on "Reading budget state…" forever in a
background tab, which is every tab under browser automation.

Verified: 1712 python tests, 100% branch coverage; 128 vitest, 100%. The
guard's /proc parser was checked read-only against a real listener on :8000
and resolved the same pid as `ss`.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MKFzwzwRU1JD7SFLHtQBsz
2026-08-29 18:52:11 +02:00

223 lines
8.7 KiB
Python

"""Tests for _serve_guard's /proc parsing and port-ownership resolution.
Split from test_serve_guard_lifecycle.py to stay inside the 250-line file cap;
this half covers "who holds the port", that half covers "what to do about it".
Every test runs against a fake /proc built in tmp_path — none reads the host's
real process table, and none signals a real pid.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
from steam_backlog_enforcer import _serve_guard
from steam_backlog_enforcer.tests._fake_proc import (
add_opaque_pid,
add_pid,
make_proc,
patch_proc,
tcp_row,
write_net_tcp,
)
if TYPE_CHECKING:
from pathlib import Path
_HOST = "127.0.0.1"
_PORT = 8000
_LOCAL_V4 = f"{_serve_guard._hex_v4(_HOST)}:{_serve_guard._hex_port(_PORT)}"
class TestHexRendering:
"""Tests for the /proc address column encoders."""
def test_port_is_upper_hex(self) -> None:
assert _serve_guard._hex_port(8000) == "1F40"
def test_ipv4_is_little_endian(self) -> None:
assert _serve_guard._hex_v4("127.0.0.1") == "0100007F"
def test_ipv6_swaps_each_word(self) -> None:
assert _serve_guard._hex_v6("::1") == "0" * 24 + "01000000"
def test_v4_mapped_v6_is_rendered(self) -> None:
mapped = _serve_guard._hex_v6("::ffff:127.0.0.1")
assert mapped.endswith("0100007F")
class TestConflictingAddresses:
"""Tests for which listeners actually block a bind."""
def test_includes_self_wildcard_and_mapped(self) -> None:
addrs = _serve_guard._conflicting_addresses(_HOST)
assert _serve_guard._hex_v4(_HOST) in addrs
assert _serve_guard._WILDCARD_V4 in addrs
assert _serve_guard._hex_v6("::") in addrs
def test_excludes_an_unrelated_interface(self) -> None:
# A listener on a LAN address must never be reported as the owner of a
# loopback bind; naming it would blame an innocent process.
assert _serve_guard._hex_v4(
"192.168.1.5"
) not in _serve_guard._conflicting_addresses(_HOST)
class TestListeningInodes:
"""Tests for parsing /proc/net/tcp."""
def test_finds_matching_listener(self, tmp_path: Path) -> None:
proc = make_proc(tmp_path)
write_net_tcp(proc, [tcp_row(_LOCAL_V4, 4242)])
with patch_proc(proc):
assert _serve_guard._listening_inodes(_HOST, _PORT) == {4242}
def test_finds_wildcard_listener(self, tmp_path: Path) -> None:
proc = make_proc(tmp_path)
wildcard = f"{_serve_guard._WILDCARD_V4}:{_serve_guard._hex_port(_PORT)}"
write_net_tcp(proc, [tcp_row(wildcard, 7)])
with patch_proc(proc):
assert _serve_guard._listening_inodes(_HOST, _PORT) == {7}
def test_finds_v6_wildcard_listener(self, tmp_path: Path) -> None:
# A dual-stack bind lives in tcp6 even when our bind is IPv4, which is
# why both files are scanned.
proc = make_proc(tmp_path)
local = f"{_serve_guard._hex_v6('::')}:{_serve_guard._hex_port(_PORT)}"
write_net_tcp(proc, [tcp_row(local, 9)], v6=True)
with patch_proc(proc):
assert _serve_guard._listening_inodes(_HOST, _PORT) == {9}
def test_ignores_non_listening_state(self, tmp_path: Path) -> None:
# 01 is ESTABLISHED: an outbound connection, not a bind.
proc = make_proc(tmp_path)
write_net_tcp(proc, [tcp_row(_LOCAL_V4, 4242, state="01")])
with patch_proc(proc):
assert _serve_guard._listening_inodes(_HOST, _PORT) == set()
def test_ignores_other_port(self, tmp_path: Path) -> None:
proc = make_proc(tmp_path)
other = f"{_serve_guard._hex_v4(_HOST)}:{_serve_guard._hex_port(9999)}"
write_net_tcp(proc, [tcp_row(other, 4242)])
with patch_proc(proc):
assert _serve_guard._listening_inodes(_HOST, _PORT) == set()
def test_ignores_other_interface(self, tmp_path: Path) -> None:
proc = make_proc(tmp_path)
lan = f"{_serve_guard._hex_v4('192.168.1.5')}:{_serve_guard._hex_port(_PORT)}"
write_net_tcp(proc, [tcp_row(lan, 4242)])
with patch_proc(proc):
assert _serve_guard._listening_inodes(_HOST, _PORT) == set()
def test_ignores_truncated_row(self, tmp_path: Path) -> None:
proc = make_proc(tmp_path)
write_net_tcp(proc, [f" 0: {_LOCAL_V4} 0A 4242"])
with patch_proc(proc):
assert _serve_guard._listening_inodes(_HOST, _PORT) == set()
def test_ignores_non_numeric_inode(self, tmp_path: Path) -> None:
proc = make_proc(tmp_path)
write_net_tcp(proc, [tcp_row(_LOCAL_V4, inode="notanumber")])
with patch_proc(proc):
assert _serve_guard._listening_inodes(_HOST, _PORT) == set()
def test_unreadable_file_is_skipped(self, tmp_path: Path) -> None:
proc = make_proc(tmp_path)
write_net_tcp(proc, [tcp_row(_LOCAL_V4, 4242)])
(proc / "net" / "tcp6").unlink()
with patch_proc(proc):
assert _serve_guard._listening_inodes(_HOST, _PORT) == {4242}
class TestPidOwnsInode:
"""Tests for matching a socket inode to a process."""
def test_matching_fd_is_found(self, tmp_path: Path) -> None:
proc = make_proc(tmp_path)
pid_dir = add_pid(proc, 100, inodes=[1, 4242])
assert _serve_guard._pid_owns_inode(pid_dir, {4242}) is True
def test_unrelated_fds_do_not_match(self, tmp_path: Path) -> None:
proc = make_proc(tmp_path)
pid_dir = add_pid(proc, 100, inodes=[1, 2])
assert _serve_guard._pid_owns_inode(pid_dir, {4242}) is False
def test_unreadable_fd_dir_is_not_an_owner(self, tmp_path: Path) -> None:
proc = make_proc(tmp_path)
pid_dir = add_opaque_pid(proc, 100)
assert _serve_guard._pid_owns_inode(pid_dir, {4242}) is False
def test_unreadable_single_fd_is_skipped(self, tmp_path: Path) -> None:
# A plain file in fd/ cannot be readlink()ed; the scan must continue
# to the sibling entry rather than abandoning the process.
proc = make_proc(tmp_path)
pid_dir = add_pid(proc, 100, inodes=[4242])
(pid_dir / "fd" / "broken").write_text("", encoding="utf-8")
assert _serve_guard._pid_owns_inode(pid_dir, {4242}) is True
class TestFindPortOwner:
"""Tests for end-to-end owner resolution."""
def test_no_listener_returns_none(self, tmp_path: Path) -> None:
proc = make_proc(tmp_path)
with patch_proc(proc):
assert _serve_guard.find_port_owner(_HOST, _PORT) is None
def test_resolves_the_listening_pid(self, tmp_path: Path) -> None:
proc = make_proc(tmp_path)
write_net_tcp(proc, [tcp_row(_LOCAL_V4, 4242)])
add_pid(proc, 100, inodes=[9])
add_pid(proc, 200, inodes=[4242])
with patch_proc(proc):
assert _serve_guard.find_port_owner(_HOST, _PORT) == 200
def test_uninspectable_owner_resolves_to_none(self, tmp_path: Path) -> None:
# Another user's listener: occupied, but not attributable. Callers must
# read this as "cannot identify", never as "free".
proc = make_proc(tmp_path)
write_net_tcp(proc, [tcp_row(_LOCAL_V4, 4242)])
add_opaque_pid(proc, 100)
with patch_proc(proc):
assert _serve_guard.find_port_owner(_HOST, _PORT) is None
class TestReadCmdline:
"""Tests for argv reading."""
def test_returns_argv(self, tmp_path: Path) -> None:
proc = make_proc(tmp_path)
add_pid(proc, 100, cmdline=["python", "-m", "steam_backlog_enforcer.main"])
with patch_proc(proc):
assert _serve_guard.read_cmdline(100)[0] == "python"
def test_missing_process_is_empty(self, tmp_path: Path) -> None:
proc = make_proc(tmp_path)
with patch_proc(proc):
assert _serve_guard.read_cmdline(4321) == []
class TestIsOurServer:
"""Tests for recognising one of our own serve processes."""
def test_our_serve_process_matches(self, tmp_path: Path) -> None:
proc = make_proc(tmp_path)
add_pid(
proc, 100, cmdline=["python", "-m", "steam_backlog_enforcer.main", "serve"]
)
with patch_proc(proc):
assert _serve_guard.is_our_server(100) is True
def test_other_subcommand_does_not_match(self, tmp_path: Path) -> None:
proc = make_proc(tmp_path)
add_pid(
proc, 100, cmdline=["python", "-m", "steam_backlog_enforcer.main", "status"]
)
with patch_proc(proc):
assert _serve_guard.is_our_server(100) is False
def test_unrelated_process_does_not_match(self, tmp_path: Path) -> None:
proc = make_proc(tmp_path)
add_pid(proc, 100, cmdline=["nginx", "serve"])
with patch_proc(proc):
assert _serve_guard.is_our_server(100) is False