149 lines
6.1 KiB
Python
149 lines
6.1 KiB
Python
# #region Test.PytestWorkerIsolation [C:2] [TYPE Module] [SEMANTICS pytest,xdist,postgres,ownership]
|
|
# @BRIEF Verify xdist worker identity is explicit, scheduler-independent, and run-owned.
|
|
# @RELATION BINDS_TO -> [Test.PytestEarly.IntegrationDatabase]
|
|
# @TEST_EDGE: serial_without_identity -> Typed refusal rather than an unverified pass
|
|
# @TEST_EDGE: foreign_or_mismatched_worker -> Reject before database use
|
|
# @TEST_EDGE: invalid_descriptor_or_lease -> Reject before accepting worker ownership
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import stat
|
|
from types import SimpleNamespace
|
|
|
|
import pytest
|
|
from sqlalchemy import text
|
|
|
|
import pytest_early
|
|
from src.core.database import engine
|
|
|
|
|
|
def test_worker_count_accepts_explicit_auto_and_single_worker():
|
|
config = SimpleNamespace(option=SimpleNamespace(numprocesses=None), hook=SimpleNamespace(
|
|
pytest_xdist_auto_num_workers=lambda **_: 5,
|
|
))
|
|
assert pytest_early._parse_parallel_worker_count(
|
|
config, ["-n", "auto", "--max-worker-restart=0"],
|
|
) == 5
|
|
assert config.option.numprocesses == 5
|
|
assert pytest_early._parse_parallel_worker_count(
|
|
config, ["-n", "1", "--max-worker-restart=0"],
|
|
) == 1
|
|
|
|
for args in (
|
|
["--max-worker-restart=0"],
|
|
["-n", "auto"],
|
|
["-n", "2", "--max-worker-restart=1"],
|
|
["-n", "2", "--max-worker-restart=0", "--dist=each"],
|
|
):
|
|
with pytest.raises(RuntimeError, match="PYTEST_WORKER_PG_"):
|
|
pytest_early._parse_parallel_worker_count(config, args)
|
|
|
|
|
|
def test_worker_bootstrap_returns_before_controller_path(monkeypatch):
|
|
calls = []
|
|
monkeypatch.setenv("PYTEST_WORKER_PG_RUN_ID", "run-id-from-controller")
|
|
monkeypatch.setattr(
|
|
pytest_early, "_bootstrap_parallel_pg_worker", lambda args: calls.append("worker"),
|
|
)
|
|
monkeypatch.setattr(
|
|
pytest_early, "_bootstrap_parallel_pg_controller", lambda *args: calls.append("controller"),
|
|
)
|
|
|
|
pytest_early.pytest_load_initial_conftests(
|
|
early_config=None, parser=None, args=["--run-isolated-pg-workers"],
|
|
)
|
|
|
|
assert calls == ["worker"]
|
|
|
|
|
|
def test_controller_cleans_prepared_databases_if_no_worker_started(monkeypatch):
|
|
context = {
|
|
"role": "controller",
|
|
"expected_workers": {"gw0", "gw1"},
|
|
"started_workers": set(),
|
|
"stopped_workers": set(),
|
|
}
|
|
calls = []
|
|
monkeypatch.setattr(pytest_early, "_parallel_pg_context", context)
|
|
monkeypatch.setattr(
|
|
pytest_early,
|
|
"_cleanup_parallel_pg",
|
|
lambda received, *, allow_unstarted: calls.append((received, allow_unstarted)),
|
|
)
|
|
|
|
pytest_early._pytest_unconfigure_parallel(SimpleNamespace(_session=None))
|
|
|
|
assert calls == [(context, True)]
|
|
|
|
|
|
def test_worker_context_accepts_any_declared_gw_and_refuses_foreign_or_serial(monkeypatch):
|
|
run_id = "0123456789abcdef0123456789abcdef"
|
|
workers = {f"gw{index}": {} for index in range(5)}
|
|
manifest = {"run_id": run_id, "worker_count": 5, "workers": workers}
|
|
monkeypatch.setenv("PYTEST_XDIST_TESTRUNUID", run_id)
|
|
pytest_early._validate_worker_context(manifest, run_id, "gw4", "5")
|
|
|
|
with pytest.raises(RuntimeError, match="PYTEST_WORKER_PG_WORKER_MAP_INVALID"):
|
|
pytest_early._validate_worker_context(manifest, run_id, "gw5", "5")
|
|
with pytest.raises(RuntimeError, match="PYTEST_WORKER_PG_WORKER_MAP_INVALID"):
|
|
pytest_early._validate_worker_context(manifest, run_id, "gw4", "4")
|
|
|
|
monkeypatch.delenv("PYTEST_XDIST_TESTRUNUID")
|
|
with pytest.raises(RuntimeError, match="PYTEST_WORKER_PG_WORKER_MAP_INVALID"):
|
|
pytest_early._validate_worker_context(manifest, run_id, "", None)
|
|
|
|
|
|
def test_worker_descriptor_and_lease_bind_run_identity():
|
|
run_id = "0123456789abcdef0123456789abcdef"
|
|
worker_id = "gw3"
|
|
database = f"ss_test_{run_id}_{worker_id}"
|
|
worker = {"database": database}
|
|
pytest_early._validate_worker_descriptor_binding(worker, {"database": database})
|
|
with pytest.raises(RuntimeError, match="PYTEST_WORKER_PG_DESCRIPTOR_BINDING_INVALID"):
|
|
pytest_early._validate_worker_descriptor_binding(
|
|
worker, {"database": database + "_foreign"},
|
|
)
|
|
|
|
lease = {
|
|
"run_id": run_id, "worker_id": worker_id, "database": database,
|
|
"pid": 12345, "process_start_ticks": 67890,
|
|
}
|
|
pytest_early._validate_worker_lease(lease, run_id, worker_id, database)
|
|
with pytest.raises(RuntimeError, match="PYTEST_WORKER_PG_WORKER_LEASE_INVALID"):
|
|
pytest_early._validate_worker_lease(lease, run_id, "gw2", database)
|
|
|
|
|
|
def test_serial_execution_is_explicitly_unavailable_and_worker_proof_is_live(monkeypatch):
|
|
run_id = os.environ.get("PYTEST_WORKER_PG_RUN_ID")
|
|
worker_id = os.environ.get("PYTEST_XDIST_WORKER")
|
|
if not run_id or not worker_id:
|
|
with pytest.raises(RuntimeError, match="PYTEST_WORKER_PG_WORKER_MAP_INVALID"):
|
|
pytest_early._validate_worker_context({}, "", "", None)
|
|
else:
|
|
manifest = json.loads(Path(os.environ["PYTEST_WORKER_PG_RUN_MANIFEST"]).read_text())
|
|
pytest_early._validate_worker_context(
|
|
manifest, run_id, worker_id, os.environ.get("PYTEST_XDIST_WORKER_COUNT"),
|
|
)
|
|
descriptor_path = Path(os.environ["PG_CONSUMER_CONNECTION_FILE"])
|
|
descriptor = json.loads(descriptor_path.read_text(encoding="utf-8"))
|
|
with engine.connect() as connection:
|
|
current_database = connection.execute(text("SELECT current_database()")).scalar_one()
|
|
assert current_database == descriptor["database"]
|
|
assert current_database.endswith(f"_{worker_id}")
|
|
|
|
storage_root = Path(os.environ["PYTEST_WORKER_PG_STORAGE_ROOT"])
|
|
assert storage_root == Path(manifest["workers"][worker_id]["storage"])
|
|
info = storage_root.lstat()
|
|
assert stat.S_ISDIR(info.st_mode)
|
|
assert info.st_uid == os.getuid()
|
|
assert stat.S_IMODE(info.st_mode) == 0o700
|
|
lease = json.loads((storage_root / ".pytest-worker-owner.json").read_text())
|
|
assert lease["run_id"] == run_id
|
|
assert lease["worker_id"] == worker_id
|
|
assert lease["pid"] == os.getpid()
|
|
|
|
|
|
# #endregion Test.PytestWorkerIsolation
|