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.
@@ -0,0 +1,169 @@
1
+ Metadata-Version: 2.4
2
+ Name: pytest-racekit
3
+ Version: 0.1.0
4
+ Summary: Race testing for live services: release many requests from one starting gate, repeat for many rounds, and count the rounds that broke a database invariant.
5
+ Keywords: pytest,race-condition,concurrency,testing,postgresql,idempotency,httpx
6
+ Author: ManvGit17
7
+ License-Expression: Apache-2.0
8
+ License-File: LICENSE
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Framework :: Pytest
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3 :: Only
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Programming Language :: Python :: 3.14
19
+ Classifier: Programming Language :: Python :: 3.15
20
+ Classifier: Topic :: Database
21
+ Classifier: Topic :: Software Development :: Testing
22
+ Classifier: Typing :: Typed
23
+ Requires-Dist: psycopg>=3.2,<4 ; extra == 'pg'
24
+ Requires-Python: >=3.11
25
+ Project-URL: Homepage, https://github.com/ManvGit17/race-test-kit
26
+ Project-URL: Source, https://github.com/ManvGit17/race-test-kit
27
+ Project-URL: Issues, https://github.com/ManvGit17/race-test-kit/issues
28
+ Project-URL: Documentation, https://github.com/ManvGit17/race-test-kit/tree/main/docs
29
+ Project-URL: Changelog, https://github.com/ManvGit17/race-test-kit/blob/main/CHANGELOG.md
30
+ Provides-Extra: pg
31
+ Description-Content-Type: text/markdown
32
+
33
+ # pytest-racekit
34
+
35
+ Race testing for live services. Your tests pass because they send one request at a time.
36
+ pytest-racekit releases many requests from one starting gate, repeats that for many rounds,
37
+ and reports in how many rounds an invariant broke: a seat sold twice, a payment charged twice,
38
+ an update lost.
39
+
40
+ > **Status: alpha.** The API may still change before 1.0.
41
+
42
+ ## What it is and is not
43
+
44
+ - It finds races in a running service by black-box load with a synchronised start, and checks
45
+ invariants after every round, usually in the database.
46
+ - It is **not** a model checker and does not prove that a race is absent. A clean run is a
47
+ sample, which is why it reports rounds, not a single pass or fail.
48
+
49
+ ## Install
50
+
51
+ ```bash
52
+ pip install "pytest-racekit[pg]"
53
+ ```
54
+
55
+ The `pg` extra adds psycopg 3 for the PostgreSQL helpers. Installing is enough for pytest to
56
+ load the plugin: no conftest changes.
57
+
58
+ ## Quick start
59
+
60
+ ```python
61
+ import httpx
62
+
63
+
64
+ def test_never_oversells(race, db):
65
+ def reserve(i, client):
66
+ return client.post("/events/1/reserve", json={"student": i})
67
+
68
+ result = race.run(
69
+ reserve,
70
+ clients=50, # released together, every round
71
+ rounds=20,
72
+ prepare=lambda i: httpx.Client(base_url=URL), # connect before the race starts
73
+ reset=lambda: db.reset_event(1, seats=10), # before every round
74
+ check=lambda: db.count_sold(1) <= 10, # after every round
75
+ )
76
+ assert result.violations == 0
77
+ ```
78
+
79
+ When the test fails, pytest prints a `racekit` section: rounds violated, start spread, latency,
80
+ status mix overall and in the violating rounds, the first violating rounds in full, and the seed.
81
+
82
+ Options: `--race-rounds N` and `--race-seed S` set defaults for every test;
83
+ `@pytest.mark.race(rounds=..., seed=...)` sets them for one test. An argument in the call wins
84
+ over the marker, which wins over the option.
85
+
86
+ ## Scenarios
87
+
88
+ | | races | checks |
89
+ |---|---|---|
90
+ | `race.run(call, clients=N)` | N different callers at once | your `check` |
91
+ | `race.duplicate(call, copies=5)` | the same request N times (retries, double clicks) | your `check`, e.g. `racekit.same_response(...)` |
92
+ | `race.lost_update(apply, read=..., clients=N, delta=d)` | N read-modify-write updates | built in: every acknowledged update counted |
93
+ | `race.interleave({"pay": pay, "cancel": cancel}, copies=k)` | different steps at once | your `check`; statuses shown per step |
94
+ | `await race.arun(async_call, clients=N)` | like `run`, on asyncio | your `check` |
95
+
96
+ A `check()` passes unless it returns `False` or raises `AssertionError`; a `check(round)` also
97
+ gets the round's responses.
98
+
99
+ ## Forcing a rare interleaving
100
+
101
+ Some races need one exact order of events, and load hits it only sometimes. Put a pause point
102
+ in the app where the window is, and make the order happen every round:
103
+
104
+ ```python
105
+ from racekit import pg
106
+
107
+ # in the app, a no-op unless RACEKIT_PAUSE_POINTS=1:
108
+ pg.pause_point(conn, "cashback:before_write")
109
+
110
+ # in the test:
111
+ result = pg.force(
112
+ pay_cashback,
113
+ top_up,
114
+ at="cashback:before_write",
115
+ dsn=DSN,
116
+ rounds=10,
117
+ reset=reset_wallet,
118
+ check=balance_includes_both,
119
+ )
120
+ ```
121
+
122
+ `pg.Snapshot(conn, tables)` copies tables once and restores them before each round
123
+ (`reset=snapshot.restore`).
124
+
125
+ ## Outside pytest
126
+
127
+ ```bash
128
+ racekit run scenarios.py --rounds 50 --seed 7
129
+ ```
130
+
131
+ Runs every `race_*(race)` function in the file, the same function a test would be. Exit 0 if
132
+ all pass, 1 if any fail, 2 if the file cannot be loaded.
133
+
134
+ ## Measured on the demo shop
135
+
136
+ `examples/shop` is a FastAPI + PostgreSQL shop where every feature has a version broken on
137
+ purpose and a fixed one. Each number below comes from a committed script; the full results,
138
+ machine and versions are in `bench/results/`.
139
+
140
+ | what | broken | fixed | script |
141
+ |---|---|---|---|
142
+ | 50 students, 10 seats (`naive` vs `row_lock`, `atomic_update`, `skip_locked`) | oversold in 90 of 100 rounds | 0 of 100 each | `bench/shop_strategies.py` |
143
+ | one payment sent 5 times | caught in 100 of 100 rounds | 0 of 100 | `bench/shop_scenarios.py` |
144
+ | 20 top-ups at once | caught in 100 of 100 rounds | 0 of 100 | `bench/shop_scenarios.py` |
145
+ | pay against cancel on 5 orders | caught in 100 of 100 rounds | 0 of 100 | `bench/shop_scenarios.py` |
146
+ | cashback against a top-up, load alone | the 2-round test failed in 36 of 100 runs | 0 of 100 | `bench/pause_points.py` |
147
+ | the same, with the pause point | failed in 100 of 100 runs | 0 of 100 | `bench/pause_points.py` |
148
+
149
+ ## Choosing clients and rounds
150
+
151
+ - Races are probabilistic: run enough rounds that a bug caught in a fraction of them is still
152
+ caught at least once. Raise `--race-rounds` on CI rather than editing tests.
153
+ - Connect in `prepare`, not in the call: first-call costs spread the start out.
154
+ - Watch the start spread in the report. Threads are the default; `arun` suits async clients and
155
+ hundreds of clients, but with `httpx` it started 50 clients less tightly than threads on our
156
+ machine (ADR 0007).
157
+ - Each round starts the clients in a different shuffled order (fixed by the seed), so a race
158
+ that depends on who goes first is not hidden by the barrier's own wake-up order.
159
+ - Keep one test that the broken version is still caught; it tells you the settings still work on
160
+ your hardware.
161
+
162
+ ## Docs
163
+
164
+ [Prior art](https://github.com/ManvGit17/race-test-kit/blob/main/docs/prior-art.md) · [ADRs](https://github.com/ManvGit17/race-test-kit/tree/main/docs/adr) ·
165
+ [Changelog](https://github.com/ManvGit17/race-test-kit/blob/main/CHANGELOG.md) · [Contributing](https://github.com/ManvGit17/race-test-kit/blob/main/CONTRIBUTING.md)
166
+
167
+ ## Licence
168
+
169
+ Apache-2.0
@@ -0,0 +1,25 @@
1
+ racekit/__init__.py,sha256=SdWigzGRDK55sVna5bd1sa45nfT38ZF1NHOHWiCmqKo,810
2
+ racekit/cli.py,sha256=2-6KuelX6fC89Dp5dVWEnLK-jOh15EXv_mThdd22PYQ,3757
3
+ racekit/invariants/__init__.py,sha256=Fv2VlIMaV2hU7RK7t_RwiJkf2gK_xaJUuDLvNrLuGoQ,75
4
+ racekit/invariants/checks.py,sha256=6Zxyy0-xI1T6D5dhSWElBfVjuVl8ZN0dYtu7Pc0eKgQ,1563
5
+ racekit/invariants/result.py,sha256=ZditudCu53I0-RSaXrc_fTZls58mafktueal63YcseA,5431
6
+ racekit/pg/__init__.py,sha256=4iqUFen0TUEC4Y7pi30K19ByC7S3nmT_tWpe_bywBeM,653
7
+ racekit/pg/force.py,sha256=6AkIi2GQTHZfSiRpXkpuP5rh5S25SORNguCypCCI-0Q,2837
8
+ racekit/pg/pause.py,sha256=0jF28LeQqVVZ6L5TTIDLq4yLbI_r8UjRjwlcdL_cib0,4230
9
+ racekit/pg/snapshot.py,sha256=8t3j_5dOh72iW4v9oMbE_pwGzdhmxjUeobFhqQYcYXg,2849
10
+ racekit/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
11
+ racekit/pytest_plugin.py,sha256=SLYpbHCiscVgia4BbQPPptrNspBFaU3N3-Xla7pHUSY,2846
12
+ racekit/race.py,sha256=7oas3p_dTklR1lUuCPOExcoT674NoADEThxKCD4wwIE,3402
13
+ racekit/runner/__init__.py,sha256=GoExlhXAWVlFGydACcTdMeS5GgScWE5Tn2V61K0sqis,66
14
+ racekit/runner/aio.py,sha256=eBPXydWTgGBaPCQI09QE7_eJd36AIfG69n3_zW1TR38,4993
15
+ racekit/runner/capture.py,sha256=Ak5Y7mMB4htB5bRV2YCLFDTdT1gvwCGCD8AtxlNlRX4,1098
16
+ racekit/runner/gate.py,sha256=Hi0t5wMp2K_ONu2hx5Benh5-wqBZh___GAgDrau4FHw,1480
17
+ racekit/runner/rng.py,sha256=M5ugBHV-gW_uIaui-z0CT_uWxqiWM4fomchyVlH5YkE,1970
18
+ racekit/runner/rounds.py,sha256=fLNuK5mStbz96HQ1MnbGpqisNERyhfBMaiAGoF2NBAY,3320
19
+ racekit/runner/threads.py,sha256=IRW0W_XZ9uojN8xOpEKzthU4wsi99I3jjNCEzePbx3I,5493
20
+ racekit/scenarios/__init__.py,sha256=pnpdPRk40eCUXxRRrnNOiJkdXpEq3nI_0rxlo-6dxAI,5076
21
+ pytest_racekit-0.1.0.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
22
+ pytest_racekit-0.1.0.dist-info/WHEEL,sha256=-gI5GRFdiNNn2CFz-ptlExISMINC-k8bFxeojAlHbrM,81
23
+ pytest_racekit-0.1.0.dist-info/entry_points.txt,sha256=RF0oVQ8z3EOmyA8eiMciaabPdExoDuKm1u_bmxg8Luw,90
24
+ pytest_racekit-0.1.0.dist-info/METADATA,sha256=F0ycdhJBLiwMbUwIRlY4kRueFfmIDVJA2srndgPIgjg,7131
25
+ pytest_racekit-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.13.10
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,6 @@
1
+ [console_scripts]
2
+ racekit = racekit.cli:main
3
+
4
+ [pytest11]
5
+ racekit = racekit.pytest_plugin
6
+
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
racekit/__init__.py ADDED
@@ -0,0 +1,31 @@
1
+ """Race Test Kit: release many requests from one starting gate and check invariants."""
2
+
3
+ from racekit.invariants.checks import at_most, same_response
4
+ from racekit.invariants.result import RoundResult, RunResult
5
+ from racekit.race import Race
6
+ from racekit.runner.aio import arun
7
+ from racekit.runner.capture import CallRecord
8
+ from racekit.runner.rng import rng
9
+ from racekit.runner.rounds import run
10
+ from racekit.runner.threads import PrepareError, RoundTimeout
11
+ from racekit.scenarios import duplicate, interleave, lost_update
12
+
13
+ __version__ = "0.1.0"
14
+
15
+ __all__ = [
16
+ "CallRecord",
17
+ "PrepareError",
18
+ "Race",
19
+ "RoundResult",
20
+ "RoundTimeout",
21
+ "RunResult",
22
+ "__version__",
23
+ "arun",
24
+ "at_most",
25
+ "duplicate",
26
+ "interleave",
27
+ "lost_update",
28
+ "rng",
29
+ "run",
30
+ "same_response",
31
+ ]
racekit/cli.py ADDED
@@ -0,0 +1,104 @@
1
+ """``racekit run FILE``: run race scenarios outside pytest.
2
+
3
+ racekit run examples/shop/race_shop.py --rounds 50 --seed 7 -k oversell
4
+
5
+ Runs every function in FILE whose name starts with ``race_`` and that takes one argument, the
6
+ same ``race`` a pytest test gets as a fixture (``async def`` functions too). Prints each run's
7
+ report. Exit status: 0 if every function returned, 1 if any raised (a failed ``assert`` is the
8
+ usual way to say an invariant broke), 2 if FILE could not be loaded or has no scenarios.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import argparse
14
+ import asyncio
15
+ import importlib.util
16
+ import inspect
17
+ import sys
18
+ import traceback
19
+ from collections.abc import Callable, Sequence
20
+ from pathlib import Path
21
+ from types import ModuleType
22
+ from typing import Any
23
+
24
+ from racekit.race import Race
25
+
26
+
27
+ def _load(path: Path) -> ModuleType:
28
+ spec = importlib.util.spec_from_file_location(f"racekit_scenarios_{path.stem}", path)
29
+ if spec is None or spec.loader is None:
30
+ raise ImportError(f"cannot load {path}")
31
+ module = importlib.util.module_from_spec(spec)
32
+ sys.path.insert(0, str(path.parent)) # let the file import its neighbours, like pytest does
33
+ spec.loader.exec_module(module)
34
+ return module
35
+
36
+
37
+ def _scenarios(module: ModuleType, keyword: str | None) -> list[Callable[..., Any]]:
38
+ return [
39
+ value
40
+ for name, value in vars(module).items()
41
+ if name.startswith("race_")
42
+ and inspect.isfunction(value)
43
+ and (keyword is None or keyword in name)
44
+ ]
45
+
46
+
47
+ def _where(exc: AssertionError) -> str:
48
+ """Where the failed assert is, and its message's first line (the report follows anyway)."""
49
+ frame = traceback.extract_tb(exc.__traceback__)[-1]
50
+ place = f"{Path(frame.filename).name}:{frame.lineno}: {frame.line or 'assert'}"
51
+ first = str(exc).splitlines()[0] if str(exc) else ""
52
+ return f"{place} ({first})" if first else place
53
+
54
+
55
+ def _run_one(scenario: Callable[..., Any], race: Race) -> bool:
56
+ try:
57
+ if inspect.iscoroutinefunction(scenario):
58
+ asyncio.run(scenario(race))
59
+ else:
60
+ scenario(race)
61
+ except AssertionError as exc:
62
+ print(f"FAIL {scenario.__name__}: {_where(exc)}")
63
+ return False
64
+ except Exception:
65
+ print(f"ERROR {scenario.__name__}:")
66
+ traceback.print_exc(file=sys.stdout)
67
+ return False
68
+ print(f"PASS {scenario.__name__}")
69
+ return True
70
+
71
+
72
+ def main(argv: Sequence[str] | None = None) -> int:
73
+ parser = argparse.ArgumentParser(prog="racekit", description="Race testing for live services.")
74
+ commands = parser.add_subparsers(dest="command", required=True)
75
+ run = commands.add_parser("run", help="run the race_* functions in a file")
76
+ run.add_argument("file", type=Path)
77
+ run.add_argument("-k", dest="keyword", help="only functions whose name contains this")
78
+ run.add_argument("--rounds", type=int, help="rounds for runs that do not set their own")
79
+ run.add_argument("--seed", type=int, help="seed for runs that do not set their own")
80
+ args = parser.parse_args(argv)
81
+
82
+ try:
83
+ module = _load(args.file)
84
+ except Exception:
85
+ print(f"racekit: could not load {args.file}:")
86
+ traceback.print_exc(file=sys.stdout)
87
+ return 2
88
+ scenarios = _scenarios(module, args.keyword)
89
+ if not scenarios:
90
+ print(f"racekit: no race_* functions in {args.file}")
91
+ return 2
92
+
93
+ failed = 0
94
+ for scenario in scenarios:
95
+ race = Race(rounds=args.rounds, seed=args.seed)
96
+ if not _run_one(scenario, race):
97
+ failed += 1
98
+ print(race.report(), end="\n\n")
99
+ print(f"racekit: {len(scenarios) - failed} passed, {failed} failed")
100
+ return 1 if failed else 0
101
+
102
+
103
+ if __name__ == "__main__":
104
+ sys.exit(main())
@@ -0,0 +1 @@
1
+ """Results of a run and, later, built-in checks and the failure report."""
@@ -0,0 +1,43 @@
1
+ """Ready-made checks that look at a round's responses. No database needed.
2
+
3
+ Each returns a ``check(round)`` for ``racekit.run`` and the scenarios.
4
+
5
+ They raise ``AssertionError`` explicitly instead of using ``assert``: pytest rewrites asserts in
6
+ installed plugins' packages and would append its own explanation to these messages.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from collections.abc import Callable
12
+ from typing import Any
13
+
14
+ from racekit.invariants.result import RoundResult
15
+
16
+
17
+ def at_most(status: int, n: int) -> Callable[[RoundResult], None]:
18
+ """At most ``n`` calls in the round got ``status`` (for example one 201 per seat)."""
19
+
20
+ def check(round: RoundResult) -> None:
21
+ got = round.statuses[status]
22
+ if got > n:
23
+ raise AssertionError(f"{got} responses with status {status}, at most {n} allowed")
24
+
25
+ return check
26
+
27
+
28
+ def same_response(key: Callable[[Any], object]) -> Callable[[RoundResult], None]:
29
+ """Every successful call got the same answer, as extracted by ``key(value)``.
30
+
31
+ For idempotency: ``same_response(lambda r: r.json()["charge"])`` fails when two copies
32
+ of one request were given different charges. Calls that raised are left out, so are
33
+ responses with a 4xx or 5xx status.
34
+ """
35
+
36
+ def check(round: RoundResult) -> None:
37
+ answers = {
38
+ repr(key(c.value)) for c in round.calls if c.ok and (c.status is None or c.status < 400)
39
+ }
40
+ if len(answers) > 1:
41
+ raise AssertionError(f"{len(answers)} different answers: {sorted(answers)[:5]}")
42
+
43
+ return check