pytest-racekit 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pytest_racekit-0.1.0.dist-info/METADATA +169 -0
- pytest_racekit-0.1.0.dist-info/RECORD +25 -0
- pytest_racekit-0.1.0.dist-info/WHEEL +4 -0
- pytest_racekit-0.1.0.dist-info/entry_points.txt +6 -0
- pytest_racekit-0.1.0.dist-info/licenses/LICENSE +201 -0
- racekit/__init__.py +31 -0
- racekit/cli.py +104 -0
- racekit/invariants/__init__.py +1 -0
- racekit/invariants/checks.py +43 -0
- racekit/invariants/result.py +144 -0
- racekit/pg/__init__.py +29 -0
- racekit/pg/force.py +78 -0
- racekit/pg/pause.py +108 -0
- racekit/pg/snapshot.py +79 -0
- racekit/py.typed +0 -0
- racekit/pytest_plugin.py +79 -0
- racekit/race.py +74 -0
- racekit/runner/__init__.py +1 -0
- racekit/runner/aio.py +135 -0
- racekit/runner/capture.py +39 -0
- racekit/runner/gate.py +41 -0
- racekit/runner/rng.py +49 -0
- racekit/runner/rounds.py +82 -0
- racekit/runner/threads.py +142 -0
- racekit/scenarios/__init__.py +155 -0
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
"""What a run returns: one ``RoundResult`` per round, gathered in a ``RunResult``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import statistics
|
|
6
|
+
from collections import Counter
|
|
7
|
+
from collections.abc import Iterable
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
|
|
10
|
+
from racekit.runner.capture import CallRecord
|
|
11
|
+
from racekit.runner.gate import spread_ms
|
|
12
|
+
|
|
13
|
+
#: How many violating rounds ``report()`` shows in full.
|
|
14
|
+
REPORT_ROUNDS = 3
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass
|
|
18
|
+
class RoundResult:
|
|
19
|
+
number: int
|
|
20
|
+
calls: list[CallRecord]
|
|
21
|
+
violated: bool = False
|
|
22
|
+
#: Why the check failed: the AssertionError's message, or "check returned False".
|
|
23
|
+
check_message: str | None = None
|
|
24
|
+
|
|
25
|
+
@property
|
|
26
|
+
def spread_ms(self) -> float:
|
|
27
|
+
"""How far apart the workers left the gate in this round."""
|
|
28
|
+
return spread_ms(call.released for call in self.calls)
|
|
29
|
+
|
|
30
|
+
@property
|
|
31
|
+
def statuses(self) -> Counter[int | None]:
|
|
32
|
+
"""How many calls returned each status (``None`` when there was no status)."""
|
|
33
|
+
return _statuses(self.calls)
|
|
34
|
+
|
|
35
|
+
@property
|
|
36
|
+
def errors(self) -> Counter[str]:
|
|
37
|
+
"""How many calls raised each exception type."""
|
|
38
|
+
return Counter(type(call.error).__name__ for call in self.calls if call.error)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass
|
|
42
|
+
class RunResult:
|
|
43
|
+
seed: int
|
|
44
|
+
clients: int
|
|
45
|
+
rounds: list[RoundResult] = field(default_factory=list)
|
|
46
|
+
#: For ``interleave``: the step each client ran, by client index.
|
|
47
|
+
steps: list[str] | None = None
|
|
48
|
+
|
|
49
|
+
@property
|
|
50
|
+
def rounds_run(self) -> int:
|
|
51
|
+
return len(self.rounds)
|
|
52
|
+
|
|
53
|
+
@property
|
|
54
|
+
def violations(self) -> int:
|
|
55
|
+
"""Rounds in which the invariant check failed."""
|
|
56
|
+
return sum(r.violated for r in self.rounds)
|
|
57
|
+
|
|
58
|
+
@property
|
|
59
|
+
def violation_rate(self) -> float:
|
|
60
|
+
return self.violations / self.rounds_run if self.rounds else 0.0
|
|
61
|
+
|
|
62
|
+
def summary(self) -> str:
|
|
63
|
+
"""A few lines: rounds, violations, spread, the first violating round, the seed."""
|
|
64
|
+
lines = [self._headline()]
|
|
65
|
+
if self.rounds:
|
|
66
|
+
lines.append(self._spread_line())
|
|
67
|
+
failing = next((r for r in self.rounds if r.violated), None)
|
|
68
|
+
if failing is not None:
|
|
69
|
+
lines.append(
|
|
70
|
+
f"first violating round ({failing.number}): statuses"
|
|
71
|
+
f" {_mix(failing.statuses)}; errors {_mix(failing.errors)};"
|
|
72
|
+
f" check: {failing.check_message}"
|
|
73
|
+
)
|
|
74
|
+
lines.append(self._seed_line())
|
|
75
|
+
return "\n".join(lines)
|
|
76
|
+
|
|
77
|
+
def report(self) -> str:
|
|
78
|
+
"""The full failure report, for an assertion message."""
|
|
79
|
+
lines = [self._headline()]
|
|
80
|
+
if not self.rounds:
|
|
81
|
+
return "\n".join([*lines, self._seed_line()])
|
|
82
|
+
calls = [c for r in self.rounds for c in r.calls]
|
|
83
|
+
bad = [r for r in self.rounds if r.violated]
|
|
84
|
+
lines.append(self._spread_line())
|
|
85
|
+
latencies = sorted(c.latency_ms for c in calls)
|
|
86
|
+
lines.append(
|
|
87
|
+
f"latency: p50 {_percentile(latencies, 50):.1f} ms,"
|
|
88
|
+
f" p95 {_percentile(latencies, 95):.1f} ms, max {latencies[-1]:.1f} ms"
|
|
89
|
+
)
|
|
90
|
+
lines.append(f"statuses, all rounds: {_mix(_statuses(calls))}")
|
|
91
|
+
if bad:
|
|
92
|
+
bad_calls = [c for r in bad for c in r.calls]
|
|
93
|
+
lines.append(f"statuses, violating rounds: {_mix(_statuses(bad_calls))}")
|
|
94
|
+
if self.steps is not None:
|
|
95
|
+
for name in dict.fromkeys(self.steps):
|
|
96
|
+
mine = [c for c in calls if self.steps[c.index] == name]
|
|
97
|
+
lines.append(f" step {name}: {_mix(_statuses(mine))}")
|
|
98
|
+
errors = Counter(type(c.error).__name__ for c in calls if c.error)
|
|
99
|
+
if errors:
|
|
100
|
+
lines.append(f"errors, all rounds: {_mix(errors)}")
|
|
101
|
+
if bad:
|
|
102
|
+
lines.append(f"violating rounds (first {min(len(bad), REPORT_ROUNDS)} of {len(bad)}):")
|
|
103
|
+
for r in bad[:REPORT_ROUNDS]:
|
|
104
|
+
lines.append(
|
|
105
|
+
f" round {r.number}: {r.check_message}; statuses {_mix(r.statuses)};"
|
|
106
|
+
f" spread {r.spread_ms:.1f} ms"
|
|
107
|
+
)
|
|
108
|
+
first = next((c for c in r.calls if c.error), None)
|
|
109
|
+
if first is not None:
|
|
110
|
+
lines.append(f" first error, client {first.index}: {first.error!r}")
|
|
111
|
+
else:
|
|
112
|
+
lines.append("no round violated the invariant")
|
|
113
|
+
lines.append(self._seed_line())
|
|
114
|
+
return "\n".join(lines)
|
|
115
|
+
|
|
116
|
+
def _headline(self) -> str:
|
|
117
|
+
return (
|
|
118
|
+
f"racekit: {self.violations} of {self.rounds_run} rounds violated the invariant"
|
|
119
|
+
f" ({self.violation_rate:.0%}), {self.clients} clients, seed {self.seed}"
|
|
120
|
+
)
|
|
121
|
+
|
|
122
|
+
def _spread_line(self) -> str:
|
|
123
|
+
spreads = [r.spread_ms for r in self.rounds]
|
|
124
|
+
return (
|
|
125
|
+
f"start spread: median {statistics.median(spreads):.1f} ms, worst {max(spreads):.1f} ms"
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
def _seed_line(self) -> str:
|
|
129
|
+
return f"rerun with seed={self.seed} to repeat the same inputs"
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _statuses(calls: Iterable[CallRecord]) -> Counter[int | None]:
|
|
133
|
+
return Counter(call.status for call in calls if call.ok)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _mix(counts: Counter[int | None] | Counter[str]) -> str:
|
|
137
|
+
if not counts:
|
|
138
|
+
return "none"
|
|
139
|
+
return ", ".join(f"{k} x{n}" for k, n in sorted(counts.items(), key=lambda kv: str(kv[0])))
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _percentile(ordered: list[float], pct: int) -> float:
|
|
143
|
+
"""Nearest-rank percentile of an already sorted list."""
|
|
144
|
+
return ordered[max(0, -(-pct * len(ordered) // 100) - 1)]
|
racekit/pg/__init__.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""PostgreSQL helpers: table snapshots for resets, and pause points to force an interleaving.
|
|
2
|
+
|
|
3
|
+
Needs psycopg 3 (``pip install pytest-racekit[pg]``), imported only when a helper that talks
|
|
4
|
+
to the database is used; ``pause_point`` itself uses the app's own connection.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from racekit.pg.force import force
|
|
8
|
+
from racekit.pg.pause import (
|
|
9
|
+
ENV,
|
|
10
|
+
NAMESPACE,
|
|
11
|
+
Held,
|
|
12
|
+
PausePointNotReached,
|
|
13
|
+
PausePoints,
|
|
14
|
+
enabled,
|
|
15
|
+
pause_point,
|
|
16
|
+
)
|
|
17
|
+
from racekit.pg.snapshot import Snapshot
|
|
18
|
+
|
|
19
|
+
__all__ = [
|
|
20
|
+
"ENV",
|
|
21
|
+
"NAMESPACE",
|
|
22
|
+
"Held",
|
|
23
|
+
"PausePointNotReached",
|
|
24
|
+
"PausePoints",
|
|
25
|
+
"Snapshot",
|
|
26
|
+
"enabled",
|
|
27
|
+
"force",
|
|
28
|
+
"pause_point",
|
|
29
|
+
]
|
racekit/pg/force.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"""``racekit.pg.force``: run two steps in one exact order, every round, with a pause point.
|
|
2
|
+
|
|
3
|
+
Each round: ``reset()``; start ``first`` in a thread while the test holds the pause point
|
|
4
|
+
``at``; wait until ``first`` is blocked there; run ``then`` to completion; release; wait for
|
|
5
|
+
``first`` to finish; ``check``. The result is an ordinary ``RunResult`` (client 0 is ``first``,
|
|
6
|
+
client 1 is ``then``), so ``report()``, ``violations`` and the pytest plugin work as usual.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import threading
|
|
12
|
+
import time
|
|
13
|
+
from collections.abc import Callable
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
from racekit.invariants.result import RoundResult, RunResult
|
|
17
|
+
from racekit.pg.pause import PausePointNotReached, PausePoints
|
|
18
|
+
from racekit.runner.capture import CallRecord
|
|
19
|
+
from racekit.runner.rounds import judge
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _call(fn: Callable[[], Any], record: CallRecord) -> None:
|
|
23
|
+
record.released = time.perf_counter()
|
|
24
|
+
try:
|
|
25
|
+
record.value = fn()
|
|
26
|
+
except Exception as exc:
|
|
27
|
+
record.error = exc
|
|
28
|
+
finally:
|
|
29
|
+
record.ended = time.perf_counter()
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def force(
|
|
33
|
+
first: Callable[[], Any],
|
|
34
|
+
then: Callable[[], Any],
|
|
35
|
+
*,
|
|
36
|
+
at: str,
|
|
37
|
+
dsn: str,
|
|
38
|
+
rounds: int = 1,
|
|
39
|
+
reset: Callable[[], object] | None = None,
|
|
40
|
+
check: Callable[..., object] | None = None,
|
|
41
|
+
timeout: float = 10.0,
|
|
42
|
+
names: tuple[str, str] = ("first", "then"),
|
|
43
|
+
) -> RunResult:
|
|
44
|
+
"""``first`` pauses at ``at``; ``then`` runs meanwhile; ``first`` finishes; check.
|
|
45
|
+
|
|
46
|
+
The app under test must have ``RACEKIT_PAUSE_POINTS=1`` and call
|
|
47
|
+
``racekit.pg.pause_point(conn, at)`` on ``first``'s code path.
|
|
48
|
+
"""
|
|
49
|
+
if rounds < 1:
|
|
50
|
+
raise ValueError("rounds must be at least 1")
|
|
51
|
+
pauses = PausePoints(dsn)
|
|
52
|
+
result = RunResult(seed=0, clients=2, steps=list(names))
|
|
53
|
+
for number in range(1, rounds + 1):
|
|
54
|
+
if reset is not None:
|
|
55
|
+
reset()
|
|
56
|
+
held_first, ran_then = CallRecord(0), CallRecord(1)
|
|
57
|
+
worker = threading.Thread(target=_call, args=(first, held_first), daemon=True)
|
|
58
|
+
reached = True
|
|
59
|
+
with pauses.hold(at) as held:
|
|
60
|
+
worker.start()
|
|
61
|
+
try:
|
|
62
|
+
held.wait_until_paused(timeout)
|
|
63
|
+
except PausePointNotReached:
|
|
64
|
+
reached = False
|
|
65
|
+
else:
|
|
66
|
+
_call(then, ran_then)
|
|
67
|
+
worker.join(timeout)
|
|
68
|
+
if not reached:
|
|
69
|
+
raise PausePointNotReached(
|
|
70
|
+
f"round {number}: {names[0]} never reached pause point {at!r};"
|
|
71
|
+
" is RACEKIT_PAUSE_POINTS=1 set for the app?"
|
|
72
|
+
)
|
|
73
|
+
if worker.is_alive():
|
|
74
|
+
raise RuntimeError(f"round {number}: {names[0]} did not finish after the release")
|
|
75
|
+
this = RoundResult(number, [held_first, ran_then])
|
|
76
|
+
this.violated, this.check_message = judge(check, this)
|
|
77
|
+
result.rounds.append(this)
|
|
78
|
+
return result
|
racekit/pg/pause.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
"""Pause points: hold a request at a named line of the app's code, using PostgreSQL itself.
|
|
2
|
+
|
|
3
|
+
A race that load hits only sometimes needs one exact order of events, for example "the top-up
|
|
4
|
+
commits while the cashback job is between its read and its write". Pause points make that
|
|
5
|
+
order happen every time:
|
|
6
|
+
|
|
7
|
+
1. **In the app**, one line where the window is: ``pause_point(conn, "cashback:before_write")``.
|
|
8
|
+
It does nothing unless ``RACEKIT_PAUSE_POINTS=1`` is set in the app's environment, so
|
|
9
|
+
production pays nothing. When enabled, it takes and at once releases a PostgreSQL advisory
|
|
10
|
+
lock named after the point.
|
|
11
|
+
2. **In the test**, ``PausePoints(dsn).hold(name)`` takes that lock first, on the test's own
|
|
12
|
+
connection. The app's request now blocks at the pause point. ``wait_until_paused`` watches
|
|
13
|
+
``pg_locks`` until it sees the request waiting; the test then sends the other request, and
|
|
14
|
+
releasing the lock lets the first one finish.
|
|
15
|
+
|
|
16
|
+
Locks use the two-number form ``pg_advisory_lock(NAMESPACE, hashtext(name))``. The fixed first
|
|
17
|
+
number keeps them apart from any advisory locks the app takes itself.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import os
|
|
23
|
+
import time
|
|
24
|
+
from collections.abc import Iterator
|
|
25
|
+
from contextlib import contextmanager
|
|
26
|
+
from typing import Any
|
|
27
|
+
|
|
28
|
+
#: First key of every pause-point lock: the bytes "RACE".
|
|
29
|
+
NAMESPACE = 0x52414345
|
|
30
|
+
#: Pause points only act when this is "1" in the app's environment.
|
|
31
|
+
ENV = "RACEKIT_PAUSE_POINTS"
|
|
32
|
+
|
|
33
|
+
_LOCK = "SELECT pg_advisory_lock(%s, hashtext(%s))"
|
|
34
|
+
_UNLOCK = "SELECT pg_advisory_unlock(%s, hashtext(%s))"
|
|
35
|
+
# A two-key advisory lock shows in pg_locks as classid = key 1, objid = key 2 (as an unsigned
|
|
36
|
+
# oid) and objsubid = 2. hashtext() is signed, hence the mask.
|
|
37
|
+
_WAITING = (
|
|
38
|
+
"SELECT count(*) FROM pg_locks"
|
|
39
|
+
" WHERE locktype = 'advisory' AND NOT granted AND objsubid = 2"
|
|
40
|
+
" AND database = (SELECT oid FROM pg_database WHERE datname = current_database())"
|
|
41
|
+
" AND classid = %s::bigint::oid"
|
|
42
|
+
" AND objid = (hashtext(%s)::bigint & 4294967295)::oid"
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class PausePointNotReached(RuntimeError):
|
|
47
|
+
"""No request reached the pause point in time."""
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def enabled() -> bool:
|
|
51
|
+
return os.environ.get(ENV) == "1"
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def pause_point(conn: Any, name: str) -> None:
|
|
55
|
+
"""Wait here while a test holds the pause point ``name``. A no-op unless enabled.
|
|
56
|
+
|
|
57
|
+
``conn`` is the app's psycopg connection (any object with ``execute`` works). The lock is
|
|
58
|
+
taken and released at once, so with nobody holding it, it only costs two round trips.
|
|
59
|
+
"""
|
|
60
|
+
if not enabled():
|
|
61
|
+
return
|
|
62
|
+
conn.execute(_LOCK, (NAMESPACE, name))
|
|
63
|
+
conn.execute(_UNLOCK, (NAMESPACE, name))
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class Held:
|
|
67
|
+
"""A pause point the test is holding. Requests reaching it wait until it is released."""
|
|
68
|
+
|
|
69
|
+
def __init__(self, conn: Any, name: str) -> None:
|
|
70
|
+
self._conn = conn
|
|
71
|
+
self.name = name
|
|
72
|
+
|
|
73
|
+
def waiting(self) -> int:
|
|
74
|
+
"""How many sessions are blocked at this pause point right now."""
|
|
75
|
+
row = self._conn.execute(_WAITING, (NAMESPACE, self.name)).fetchone()
|
|
76
|
+
return int(row[0])
|
|
77
|
+
|
|
78
|
+
def wait_until_paused(self, timeout: float = 10.0, count: int = 1) -> None:
|
|
79
|
+
"""Block until ``count`` requests are waiting here; raise if that takes too long."""
|
|
80
|
+
deadline = time.monotonic() + timeout
|
|
81
|
+
while self.waiting() < count:
|
|
82
|
+
if time.monotonic() > deadline:
|
|
83
|
+
raise PausePointNotReached(
|
|
84
|
+
f"no request reached pause point {self.name!r} within {timeout:g} s;"
|
|
85
|
+
f" is {ENV}=1 set for the app, and does the code path call it?"
|
|
86
|
+
)
|
|
87
|
+
time.sleep(0.002)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class PausePoints:
|
|
91
|
+
"""The test side: hold pause points on a connection of its own."""
|
|
92
|
+
|
|
93
|
+
def __init__(self, dsn: str) -> None:
|
|
94
|
+
self.dsn = dsn
|
|
95
|
+
|
|
96
|
+
@contextmanager
|
|
97
|
+
def hold(self, name: str) -> Iterator[Held]:
|
|
98
|
+
import psycopg # optional dependency: pip install pytest-racekit[pg]
|
|
99
|
+
|
|
100
|
+
conn = psycopg.connect(self.dsn, autocommit=True)
|
|
101
|
+
try:
|
|
102
|
+
conn.execute(_LOCK, (NAMESPACE, name))
|
|
103
|
+
try:
|
|
104
|
+
yield Held(conn, name)
|
|
105
|
+
finally:
|
|
106
|
+
conn.execute(_UNLOCK, (NAMESPACE, name))
|
|
107
|
+
finally:
|
|
108
|
+
conn.close()
|
racekit/pg/snapshot.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""Table snapshot and restore, for resetting a database between rounds.
|
|
2
|
+
|
|
3
|
+
snap = Snapshot(conn, ["shop_wallets", "shop_wallet_history"])
|
|
4
|
+
snap.take() # copy the tables as they are now
|
|
5
|
+
racekit.run(..., reset=snap.restore)
|
|
6
|
+
snap.drop()
|
|
7
|
+
|
|
8
|
+
``take()`` copies each table into an unlogged ``racekit_snap_<table>``. ``restore()`` empties
|
|
9
|
+
all the listed tables in one ``TRUNCATE`` (so foreign keys *between* them are no obstacle) and
|
|
10
|
+
reinserts the rows in the order listed: list parent tables before the tables that refer to
|
|
11
|
+
them. Everything happens in one transaction.
|
|
12
|
+
|
|
13
|
+
Not restored: sequences keep counting, so ids made after a restore differ from the first run's.
|
|
14
|
+
Tables are named without a schema and found through ``search_path``.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
from collections.abc import Sequence
|
|
20
|
+
from types import TracebackType
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class Snapshot:
|
|
25
|
+
def __init__(self, conn: Any, tables: Sequence[str]) -> None:
|
|
26
|
+
if not tables:
|
|
27
|
+
raise ValueError("Snapshot needs at least one table")
|
|
28
|
+
self.conn = conn
|
|
29
|
+
self.tables = list(tables)
|
|
30
|
+
|
|
31
|
+
def _ids(self, table: str) -> tuple[Any, Any]:
|
|
32
|
+
from psycopg import sql
|
|
33
|
+
|
|
34
|
+
return sql.Identifier(table), sql.Identifier(f"racekit_snap_{table}")
|
|
35
|
+
|
|
36
|
+
def take(self) -> None:
|
|
37
|
+
from psycopg import sql
|
|
38
|
+
|
|
39
|
+
with self.conn.transaction():
|
|
40
|
+
for table in self.tables:
|
|
41
|
+
live, copy = self._ids(table)
|
|
42
|
+
self.conn.execute(sql.SQL("DROP TABLE IF EXISTS {}").format(copy))
|
|
43
|
+
self.conn.execute(
|
|
44
|
+
sql.SQL("CREATE UNLOGGED TABLE {} AS SELECT * FROM {}").format(copy, live)
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
def restore(self) -> None:
|
|
48
|
+
from psycopg import sql
|
|
49
|
+
|
|
50
|
+
with self.conn.transaction():
|
|
51
|
+
everything = sql.SQL(", ").join(self._ids(t)[0] for t in self.tables)
|
|
52
|
+
self.conn.execute(sql.SQL("TRUNCATE {}").format(everything))
|
|
53
|
+
for table in self.tables:
|
|
54
|
+
live, copy = self._ids(table)
|
|
55
|
+
# OVERRIDING SYSTEM VALUE: put back the saved ids even in GENERATED ALWAYS columns.
|
|
56
|
+
self.conn.execute(
|
|
57
|
+
sql.SQL("INSERT INTO {} OVERRIDING SYSTEM VALUE SELECT * FROM {}").format(
|
|
58
|
+
live, copy
|
|
59
|
+
)
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
def drop(self) -> None:
|
|
63
|
+
from psycopg import sql
|
|
64
|
+
|
|
65
|
+
with self.conn.transaction():
|
|
66
|
+
for table in self.tables:
|
|
67
|
+
self.conn.execute(sql.SQL("DROP TABLE IF EXISTS {}").format(self._ids(table)[1]))
|
|
68
|
+
|
|
69
|
+
def __enter__(self) -> Snapshot:
|
|
70
|
+
self.take()
|
|
71
|
+
return self
|
|
72
|
+
|
|
73
|
+
def __exit__(
|
|
74
|
+
self,
|
|
75
|
+
exc_type: type[BaseException] | None,
|
|
76
|
+
exc: BaseException | None,
|
|
77
|
+
tb: TracebackType | None,
|
|
78
|
+
) -> None:
|
|
79
|
+
self.drop()
|
racekit/py.typed
ADDED
|
File without changes
|
racekit/pytest_plugin.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""The pytest plugin, loaded through the ``pytest11`` entry point when the package is installed.
|
|
2
|
+
|
|
3
|
+
- ``race`` fixture: a ``racekit.Race`` for the test.
|
|
4
|
+
- ``--race-rounds N`` / ``--race-seed S``: defaults for every ``race`` in the session, so CI
|
|
5
|
+
can run more rounds than a quick local run without touching the tests.
|
|
6
|
+
- ``@pytest.mark.race(rounds=..., seed=...)``: defaults for one test; beats the options.
|
|
7
|
+
- When a test that used ``race`` fails, its output gets a "racekit" section with every run's
|
|
8
|
+
report, including the seed to rerun with.
|
|
9
|
+
|
|
10
|
+
Kept cheap to import: pytest imports it in every session once the package is installed.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
from collections.abc import Generator
|
|
16
|
+
|
|
17
|
+
import pytest
|
|
18
|
+
|
|
19
|
+
from racekit.race import Race
|
|
20
|
+
|
|
21
|
+
_RACE = pytest.StashKey[Race]()
|
|
22
|
+
_MARKER_ARGS = {"rounds", "seed"}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def pytest_addoption(parser: pytest.Parser) -> None:
|
|
26
|
+
group = parser.getgroup("racekit", "race testing (pytest-racekit)")
|
|
27
|
+
group.addoption(
|
|
28
|
+
"--race-rounds",
|
|
29
|
+
type=int,
|
|
30
|
+
default=None,
|
|
31
|
+
help="rounds for every race that does not set its own (marker or argument)",
|
|
32
|
+
)
|
|
33
|
+
group.addoption(
|
|
34
|
+
"--race-seed",
|
|
35
|
+
type=int,
|
|
36
|
+
default=None,
|
|
37
|
+
help="seed for every race that does not set its own, to repeat a run's inputs",
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def pytest_configure(config: pytest.Config) -> None:
|
|
42
|
+
config.addinivalue_line(
|
|
43
|
+
"markers", "race(rounds=None, seed=None): defaults for the race fixture in this test"
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@pytest.fixture
|
|
48
|
+
def race(request: pytest.FixtureRequest) -> Race:
|
|
49
|
+
"""A ``racekit.Race``: ``race.run``, ``race.duplicate``, ``race.lost_update``,
|
|
50
|
+
``race.interleave`` and ``race.arun``, with the marker's and options' defaults."""
|
|
51
|
+
marker = request.node.get_closest_marker("race")
|
|
52
|
+
settings: dict[str, int | None] = {
|
|
53
|
+
"rounds": request.config.getoption("race_rounds"),
|
|
54
|
+
"seed": request.config.getoption("race_seed"),
|
|
55
|
+
}
|
|
56
|
+
if marker is not None:
|
|
57
|
+
unknown = set(marker.kwargs) - _MARKER_ARGS
|
|
58
|
+
if marker.args or unknown:
|
|
59
|
+
pytest.fail(
|
|
60
|
+
f"@pytest.mark.race takes only rounds= and seed=; got {marker.args or ''}"
|
|
61
|
+
f" {sorted(unknown) or ''}".strip(),
|
|
62
|
+
pytrace=False,
|
|
63
|
+
)
|
|
64
|
+
settings.update(marker.kwargs)
|
|
65
|
+
found = Race(rounds=settings["rounds"], seed=settings["seed"])
|
|
66
|
+
request.node.stash[_RACE] = found
|
|
67
|
+
return found
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@pytest.hookimpl(wrapper=True)
|
|
71
|
+
def pytest_runtest_makereport(
|
|
72
|
+
item: pytest.Item, call: pytest.CallInfo[None]
|
|
73
|
+
) -> Generator[None, pytest.TestReport, pytest.TestReport]:
|
|
74
|
+
report = yield
|
|
75
|
+
if report.when == "call" and report.failed:
|
|
76
|
+
found = item.stash.get(_RACE, None)
|
|
77
|
+
if found is not None and found.results:
|
|
78
|
+
report.sections.append(("racekit", found.report()))
|
|
79
|
+
return report
|
racekit/race.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""``Race``: what the pytest fixture and ``racekit run`` hand to a scenario.
|
|
2
|
+
|
|
3
|
+
It has the same methods as the library (``run``, ``duplicate``, ``lost_update``,
|
|
4
|
+
``interleave``, ``arun``) with two additions:
|
|
5
|
+
|
|
6
|
+
- **defaults**: ``rounds`` and ``seed`` are filled in when a call does not pass them. The
|
|
7
|
+
fixture takes them from the ``@pytest.mark.race`` marker, then from ``--race-rounds`` and
|
|
8
|
+
``--race-seed``; the CLI from its ``--rounds`` and ``--seed``. An argument written in the
|
|
9
|
+
call always wins.
|
|
10
|
+
- **memory**: every result is kept, so a failing test or a CLI run can show all the reports.
|
|
11
|
+
|
|
12
|
+
A scenario written as ``def race_x(race): ...`` runs unchanged under pytest (as a test taking
|
|
13
|
+
the ``race`` fixture) and under ``racekit run``.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
from collections.abc import Awaitable, Callable
|
|
19
|
+
from typing import Any
|
|
20
|
+
|
|
21
|
+
from racekit.invariants.result import RunResult
|
|
22
|
+
from racekit.runner.aio import arun as _arun
|
|
23
|
+
from racekit.runner.rounds import run as _run
|
|
24
|
+
from racekit.scenarios import duplicate as _duplicate
|
|
25
|
+
from racekit.scenarios import interleave as _interleave
|
|
26
|
+
from racekit.scenarios import lost_update as _lost_update
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class Race:
|
|
30
|
+
def __init__(self, rounds: int | None = None, seed: int | None = None) -> None:
|
|
31
|
+
self.rounds = rounds
|
|
32
|
+
self.seed = seed
|
|
33
|
+
#: Every run so far, as (what ran, its result), in order.
|
|
34
|
+
self.results: list[tuple[str, RunResult]] = []
|
|
35
|
+
|
|
36
|
+
def _defaults(self, kwargs: dict[str, Any]) -> dict[str, Any]:
|
|
37
|
+
if kwargs.get("rounds") is None and self.rounds is not None:
|
|
38
|
+
kwargs["rounds"] = self.rounds
|
|
39
|
+
if kwargs.get("seed") is None and self.seed is not None:
|
|
40
|
+
kwargs["seed"] = self.seed
|
|
41
|
+
return kwargs
|
|
42
|
+
|
|
43
|
+
def _keep(self, name: str, result: RunResult) -> RunResult:
|
|
44
|
+
self.results.append((name, result))
|
|
45
|
+
return result
|
|
46
|
+
|
|
47
|
+
def run(self, call: Callable[..., Any], **kwargs: Any) -> RunResult:
|
|
48
|
+
"""``racekit.run`` with this race's defaults. Same arguments."""
|
|
49
|
+
return self._keep("run", _run(call, **self._defaults(kwargs)))
|
|
50
|
+
|
|
51
|
+
def duplicate(self, call: Callable[..., Any], **kwargs: Any) -> RunResult:
|
|
52
|
+
"""``racekit.duplicate`` with this race's defaults. Same arguments."""
|
|
53
|
+
return self._keep("duplicate", _duplicate(call, **self._defaults(kwargs)))
|
|
54
|
+
|
|
55
|
+
def lost_update(self, apply: Callable[..., Any], **kwargs: Any) -> RunResult:
|
|
56
|
+
"""``racekit.lost_update`` with this race's defaults. Same arguments."""
|
|
57
|
+
return self._keep("lost_update", _lost_update(apply, **self._defaults(kwargs)))
|
|
58
|
+
|
|
59
|
+
def interleave(self, steps: dict[str, Callable[..., Any]], **kwargs: Any) -> RunResult:
|
|
60
|
+
"""``racekit.interleave`` with this race's defaults. Same arguments."""
|
|
61
|
+
return self._keep("interleave", _interleave(steps, **self._defaults(kwargs)))
|
|
62
|
+
|
|
63
|
+
async def arun(self, call: Callable[..., Awaitable[Any]], **kwargs: Any) -> RunResult:
|
|
64
|
+
"""``racekit.arun`` with this race's defaults. Same arguments."""
|
|
65
|
+
return self._keep("arun", await _arun(call, **self._defaults(kwargs)))
|
|
66
|
+
|
|
67
|
+
def report(self) -> str:
|
|
68
|
+
"""Every run's report, numbered, in the order they ran."""
|
|
69
|
+
if not self.results:
|
|
70
|
+
return "racekit: no runs"
|
|
71
|
+
return "\n\n".join(
|
|
72
|
+
f"[{n}] {name}\n{result.report()}"
|
|
73
|
+
for n, (name, result) in enumerate(self.results, start=1)
|
|
74
|
+
)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Barrier start, thread backend, round loop and call capture."""
|