pubtestrules 0.4.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.
- pubtest/__init__.py +8 -0
- pubtest/_child/report.mjs +40 -0
- pubtest/_child/sitecustomize.py +47 -0
- pubtest/cassettes.py +587 -0
- pubtest/cli.py +253 -0
- pubtest/core.py +274 -0
- pubtest/http.py +156 -0
- pubtest/plugin.py +286 -0
- pubtest/steps/__init__.py +72 -0
- pubtest/steps/environment.py +17 -0
- pubtest/steps/fakes.py +176 -0
- pubtest/steps/files.py +179 -0
- pubtest/steps/git.py +80 -0
- pubtest/steps/http.py +161 -0
- pubtest/steps/integrations.py +65 -0
- pubtest/steps/programs.py +186 -0
- pubtest/steps/result.py +178 -0
- pubtest/steps/secrets.py +49 -0
- pubtest/steps/standins.py +243 -0
- pubtestrules-0.4.0.dist-info/METADATA +136 -0
- pubtestrules-0.4.0.dist-info/RECORD +25 -0
- pubtestrules-0.4.0.dist-info/WHEEL +5 -0
- pubtestrules-0.4.0.dist-info/entry_points.txt +5 -0
- pubtestrules-0.4.0.dist-info/licenses/LICENSE +202 -0
- pubtestrules-0.4.0.dist-info/top_level.txt +1 -0
pubtest/plugin.py
ADDED
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
"""The pytest plugin every Sustenaut suite loads (the `pytest11` entry point).
|
|
2
|
+
|
|
3
|
+
It gives a suite pubtest's steps (GRAMMAR.md), and:
|
|
4
|
+
|
|
5
|
+
- `ctx`: the scenario's context, its result and refusal, and the cleanups
|
|
6
|
+
that run when it ends, in reverse, passed or failed;
|
|
7
|
+
- `binary(name)`: a program under test, from `<NAME>_BIN_DIR`, never from
|
|
8
|
+
PATH, so another implementation runs the suite by setting one variable;
|
|
9
|
+
- `run(...)`: run a program and capture what it did as a `Completed`;
|
|
10
|
+
- markers for every `@tag` the feature files carry, so `--strict-markers`
|
|
11
|
+
catches a typo without each tag registered by hand;
|
|
12
|
+
- Hypothesis's examples per property from `PUBRULES_FUZZ_RUNS`, which CI sets;
|
|
13
|
+
- record and replay (`pubtest.cassettes`): a cassette per scenario for the
|
|
14
|
+
calls it makes through integrations, when integrations is installed and the
|
|
15
|
+
repository turns cassettes on, and the test customers packages register in
|
|
16
|
+
the `pubtest.customers` entry point group.
|
|
17
|
+
|
|
18
|
+
A suite's own step with the same text takes precedence over these.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import contextlib
|
|
24
|
+
import os
|
|
25
|
+
import subprocess
|
|
26
|
+
import sys
|
|
27
|
+
from collections.abc import Callable, Mapping
|
|
28
|
+
from pathlib import Path
|
|
29
|
+
from typing import Any
|
|
30
|
+
|
|
31
|
+
import pytest
|
|
32
|
+
|
|
33
|
+
from . import cassettes
|
|
34
|
+
from .core import Completed, Context, Result, bin_var, program, repository
|
|
35
|
+
|
|
36
|
+
__all__ = ["Completed", "Context", "Result", "bin_var"]
|
|
37
|
+
|
|
38
|
+
pytest_plugins = [
|
|
39
|
+
"pubtest.steps.result",
|
|
40
|
+
"pubtest.steps.files",
|
|
41
|
+
"pubtest.steps.environment",
|
|
42
|
+
"pubtest.steps.programs",
|
|
43
|
+
"pubtest.steps.standins",
|
|
44
|
+
"pubtest.steps.http",
|
|
45
|
+
"pubtest.steps.fakes",
|
|
46
|
+
"pubtest.steps.secrets",
|
|
47
|
+
"pubtest.steps.git",
|
|
48
|
+
"pubtest.steps.integrations",
|
|
49
|
+
]
|
|
50
|
+
|
|
51
|
+
# The test customers packages register (`pubtest.customers`), by name.
|
|
52
|
+
CUSTOMERS: dict[str, Any] = {}
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _finish(context: Context) -> None:
|
|
56
|
+
try:
|
|
57
|
+
unread = context.unread_refusal()
|
|
58
|
+
if unread is not None:
|
|
59
|
+
raise AssertionError(f"the action was refused, and no step read it: {unread!r}") from unread
|
|
60
|
+
finally:
|
|
61
|
+
context.close()
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@pytest.fixture
|
|
65
|
+
def ctx() -> Any:
|
|
66
|
+
"""The scenario's context, which a suite's own steps reach as `ctx`. A
|
|
67
|
+
suite may replace it with a fixture of its own; pubtest's steps then keep
|
|
68
|
+
theirs apart (`pubtest_ctx`)."""
|
|
69
|
+
context = Context()
|
|
70
|
+
yield context
|
|
71
|
+
_finish(context)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@pytest.fixture
|
|
75
|
+
def pubtest_ctx(request) -> Any:
|
|
76
|
+
"""The context pubtest's own steps use: the suite's `ctx` when it is
|
|
77
|
+
pubtest's, and otherwise one of their own, so a suite whose `ctx` is
|
|
78
|
+
something else (a dict, say) loses none of the steps."""
|
|
79
|
+
suite = request.getfixturevalue("ctx")
|
|
80
|
+
if isinstance(suite, Context):
|
|
81
|
+
yield suite
|
|
82
|
+
return
|
|
83
|
+
context = Context()
|
|
84
|
+
yield context
|
|
85
|
+
_finish(context)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
@pytest.fixture(scope="session")
|
|
89
|
+
def binary() -> Callable[..., Path]:
|
|
90
|
+
"""`binary(name, var=None)`: the path of a program under test."""
|
|
91
|
+
|
|
92
|
+
def resolve(name: str, var: str | None = None) -> Path:
|
|
93
|
+
try:
|
|
94
|
+
return program(name, var)
|
|
95
|
+
except LookupError as e:
|
|
96
|
+
pytest.fail(str(e))
|
|
97
|
+
|
|
98
|
+
return resolve
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def run_program(argv: list[str], stdin: bytes | str | None, cwd: str | os.PathLike[str],
|
|
102
|
+
env: Mapping[str, str | None] | None, timeout: float | None) -> Completed:
|
|
103
|
+
merged = dict(os.environ)
|
|
104
|
+
for key, val in (env or {}).items():
|
|
105
|
+
if val is None:
|
|
106
|
+
merged.pop(key, None)
|
|
107
|
+
else:
|
|
108
|
+
merged[key] = val
|
|
109
|
+
if isinstance(stdin, str):
|
|
110
|
+
stdin = stdin.encode()
|
|
111
|
+
proc = subprocess.run(argv, input=stdin, capture_output=True, cwd=cwd, env=merged, timeout=timeout,
|
|
112
|
+
check=False)
|
|
113
|
+
return Completed(argv, proc.returncode, proc.stdout, proc.stderr)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
@pytest.fixture
|
|
117
|
+
def run(tmp_path: Path) -> Callable[..., Completed]:
|
|
118
|
+
"""`run(program, *args, stdin=None, cwd=tmp_path, env=None)` -> Completed.
|
|
119
|
+
|
|
120
|
+
`env` is merged over the current environment; a value of None removes
|
|
121
|
+
that variable.
|
|
122
|
+
"""
|
|
123
|
+
|
|
124
|
+
def runner(prog: str | os.PathLike[str], *args: str | os.PathLike[str], stdin: bytes | str | None = None,
|
|
125
|
+
cwd: str | os.PathLike[str] | None = None, env: Mapping[str, str | None] | None = None,
|
|
126
|
+
timeout: float | None = 120) -> Completed:
|
|
127
|
+
return run_program([str(prog), *(str(a) for a in args)], stdin, cwd or tmp_path, env, timeout)
|
|
128
|
+
|
|
129
|
+
return runner
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _features(config: pytest.Config) -> Path:
|
|
133
|
+
base = config.inipath.parent if config.inipath else config.rootpath
|
|
134
|
+
try:
|
|
135
|
+
configured = config.getini("bdd_features_base_dir")
|
|
136
|
+
except ValueError:
|
|
137
|
+
configured = ""
|
|
138
|
+
return base / configured if configured else base
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _hypothesis_runs() -> None:
|
|
142
|
+
"""Load a Hypothesis profile running PUBRULES_FUZZ_RUNS examples per
|
|
143
|
+
property, with no deadline: on a shared CI runner timing is noise."""
|
|
144
|
+
raw = os.environ.get("PUBRULES_FUZZ_RUNS", "")
|
|
145
|
+
if not raw:
|
|
146
|
+
return
|
|
147
|
+
if not raw.isdigit() or int(raw) < 1:
|
|
148
|
+
raise pytest.UsageError(f"PUBRULES_FUZZ_RUNS must be a positive whole number, not {raw!r}")
|
|
149
|
+
try:
|
|
150
|
+
from hypothesis import settings # noqa: PLC0415
|
|
151
|
+
except ImportError:
|
|
152
|
+
return
|
|
153
|
+
settings.register_profile("pubrules", max_examples=int(raw), deadline=None, print_blob=True)
|
|
154
|
+
settings.load_profile("pubrules")
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _customers(config: pytest.Config) -> None:
|
|
158
|
+
"""Each `pubtest.customers` entry point: a module (or object) with a `name`,
|
|
159
|
+
`setup(tape) -> {name: real name}` and `cleanup(tape, names)`, both for record
|
|
160
|
+
mode only, and the steps of its own, which load as a pytest plugin does."""
|
|
161
|
+
from importlib.metadata import entry_points # noqa: PLC0415
|
|
162
|
+
for point in entry_points(group="pubtest.customers"):
|
|
163
|
+
customer = point.load()
|
|
164
|
+
CUSTOMERS[getattr(customer, "name", point.name)] = customer
|
|
165
|
+
if not config.pluginmanager.is_registered(customer):
|
|
166
|
+
config.pluginmanager.register(customer, f"pubtest-customer-{point.name}")
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def pytest_configure(config: pytest.Config) -> None:
|
|
170
|
+
_hypothesis_runs()
|
|
171
|
+
_customers(config)
|
|
172
|
+
found = cassettes.settings(repository(Path(str(config.rootpath))))
|
|
173
|
+
try:
|
|
174
|
+
cassettes.start_session(found)
|
|
175
|
+
except LookupError as e:
|
|
176
|
+
raise pytest.UsageError(str(e)) from None
|
|
177
|
+
config.stash[_SETTINGS] = found
|
|
178
|
+
root = _features(config)
|
|
179
|
+
tags: set[str] = set()
|
|
180
|
+
if root.is_dir():
|
|
181
|
+
for path in root.rglob("*.feature"):
|
|
182
|
+
for line in path.read_text(encoding="utf-8").splitlines():
|
|
183
|
+
stripped = line.strip()
|
|
184
|
+
if stripped.startswith("@"):
|
|
185
|
+
tags.update(t[1:] for t in stripped.split() if t.startswith("@") and not
|
|
186
|
+
t.startswith("@cassette:"))
|
|
187
|
+
for tag in sorted(tags):
|
|
188
|
+
config.addinivalue_line("markers", f"{tag}: a feature-file tag")
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
# --- record and replay -----------------------------------------------------------
|
|
192
|
+
|
|
193
|
+
_SETTINGS = pytest.StashKey[cassettes.Settings]()
|
|
194
|
+
_TAPE = pytest.StashKey[cassettes.Tape]()
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _scenario(item: Any) -> cassettes.Scenario | None:
|
|
198
|
+
"""The scenario a test item runs, as a cassette names it."""
|
|
199
|
+
template = getattr(getattr(item, "function", None), "__scenario__", None)
|
|
200
|
+
if template is None:
|
|
201
|
+
return None
|
|
202
|
+
callspec = getattr(item, "callspec", None)
|
|
203
|
+
index = callspec.indices.get("_pytest_bdd_example") if callspec is not None else None
|
|
204
|
+
row = index + 1 if index is not None and template.examples else None
|
|
205
|
+
return cassettes.Scenario(Path(template.feature.filename).name, template.name, row)
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def pytest_collection_modifyitems(config: pytest.Config, items: list[pytest.Item]) -> None:
|
|
209
|
+
"""With PUBTEST_ONLY (`pubtest record`), only the scenarios it names run."""
|
|
210
|
+
if cassettes.only() is None:
|
|
211
|
+
return
|
|
212
|
+
keep, drop = [], []
|
|
213
|
+
for item in items:
|
|
214
|
+
scenario = _scenario(item)
|
|
215
|
+
(keep if scenario is not None and cassettes.selected(scenario) else drop).append(item)
|
|
216
|
+
if drop:
|
|
217
|
+
config.hook.pytest_deselected(items=drop)
|
|
218
|
+
items[:] = keep
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
@pytest.hookimpl(tryfirst=True)
|
|
222
|
+
def pytest_bdd_apply_tag(tag: str, function: Any) -> Any:
|
|
223
|
+
"""@cassette:PATH says which cassette a scenario replays: not a marker."""
|
|
224
|
+
return function if tag.startswith("cassette:") else None
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def pytest_collection_finish(session: pytest.Session) -> None:
|
|
228
|
+
"""Once the suite's modules are imported, and with them its record transport,
|
|
229
|
+
if it has its own: a recording through the real network into pubrules.json's
|
|
230
|
+
"DIR" says that the form is not for it."""
|
|
231
|
+
found = session.config.stash.get(_SETTINGS, None)
|
|
232
|
+
warning = found and cassettes.stand_in_only(found, real_network=cassettes.network is None)
|
|
233
|
+
if warning:
|
|
234
|
+
capture = session.config.pluginmanager.get_plugin("capturemanager")
|
|
235
|
+
with capture.global_and_fixture_disabled() if capture else contextlib.nullcontext():
|
|
236
|
+
print(warning, file=sys.stderr, flush=True)
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def pytest_bdd_before_scenario(request: pytest.FixtureRequest, feature: Any, scenario: Any) -> None:
|
|
240
|
+
found = request.config.stash.get(_SETTINGS, None)
|
|
241
|
+
if found is None or not found.active:
|
|
242
|
+
return
|
|
243
|
+
named = _scenario(request.node)
|
|
244
|
+
if named is None:
|
|
245
|
+
return
|
|
246
|
+
text = cassettes.text_hash([(s.name, s.docstring, [list(map(str, r)) for r in s.datatable.raw()]
|
|
247
|
+
if s.datatable else None) for s in scenario.steps])
|
|
248
|
+
tape = cassettes.Tape(found, named, set(scenario.tags) | set(feature.tags), text)
|
|
249
|
+
tape.customers = CUSTOMERS
|
|
250
|
+
tape.begin()
|
|
251
|
+
request.node.stash[_TAPE] = tape
|
|
252
|
+
request.getfixturevalue("pubtest_ctx").tape = tape
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def pytest_bdd_before_step(request: Any, feature: Any, scenario: Any, step: Any, step_func: Any) -> None:
|
|
256
|
+
held = request.node.stash.get(_TAPE, None)
|
|
257
|
+
if held is not None:
|
|
258
|
+
held.step(step_func)
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def pytest_bdd_step_error(request: Any, feature: Any, scenario: Any, step: Any, step_func: Any,
|
|
262
|
+
step_func_args: Any, exception: Any) -> None:
|
|
263
|
+
held = request.node.stash.get(_TAPE, None)
|
|
264
|
+
if held is not None:
|
|
265
|
+
held.failed = True
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def pytest_bdd_step_func_lookup_error(request: Any, feature: Any, scenario: Any, step: Any, exception: Any) -> None:
|
|
269
|
+
held = request.node.stash.get(_TAPE, None)
|
|
270
|
+
if held is not None:
|
|
271
|
+
held.failed = True
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def pytest_bdd_after_scenario(request: pytest.FixtureRequest, feature: Any, scenario: Any) -> None:
|
|
275
|
+
__tracebackhide__ = True
|
|
276
|
+
held = request.node.stash.get(_TAPE, None)
|
|
277
|
+
if held is None:
|
|
278
|
+
return
|
|
279
|
+
tape = held
|
|
280
|
+
del request.node.stash[_TAPE]
|
|
281
|
+
problems = tape.end()
|
|
282
|
+
if problems and tape.failed: # the step's own failure says more; these only add to it
|
|
283
|
+
import warnings # noqa: PLC0415
|
|
284
|
+
warnings.warn("\n".join(problems), stacklevel=1)
|
|
285
|
+
elif problems:
|
|
286
|
+
raise AssertionError("\n".join(problems))
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"""pubtest's steps, one module per family of GRAMMAR.md."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from pytest_bdd import parsers
|
|
9
|
+
|
|
10
|
+
__all__ = ["phrase"]
|
|
11
|
+
|
|
12
|
+
# A value in quotes is any text, empty too, read as cucumber's {string} reads
|
|
13
|
+
# one: \" is a quote and \\ a backslash. It is read strictly first, with no
|
|
14
|
+
# bare quote inside, so a shorter step never swallows a longer one's text
|
|
15
|
+
# (`… asked "GET /a" with the header "H" set to "V"`). When no step of
|
|
16
|
+
# pubtest's reads the text strictly, a value may hold bare quotes
|
|
17
|
+
# (`holding "{"kind": "utility"}"`, `mentions ""tags" must be true"`), read
|
|
18
|
+
# to the step's last quote. {name:d} is a whole number; a bare {name} is words.
|
|
19
|
+
_FIELD = re.compile(r'"\{(?P<quoted>\w+)\}"|\{(?P<whole>\w+):d\}|\{(?P<bare>\w+)\}')
|
|
20
|
+
_STRICT = r'(?:[^"\\]|\\.)*'
|
|
21
|
+
_LOOSE = r'(?:\\.|[^\\])*?'
|
|
22
|
+
_ESCAPE = re.compile(r'\\(["\\])')
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _pattern(template: str, quoted: str) -> str:
|
|
26
|
+
out, pos = [], 0
|
|
27
|
+
for field in _FIELD.finditer(template):
|
|
28
|
+
out.append(re.escape(template[pos:field.start()]))
|
|
29
|
+
if field["quoted"]:
|
|
30
|
+
out.append(f'"(?P<{field["quoted"]}>{quoted})"')
|
|
31
|
+
elif field["whole"]:
|
|
32
|
+
out.append(rf"(?P<{field['whole']}>-?\d+)")
|
|
33
|
+
else:
|
|
34
|
+
out.append(f"(?P<{field['bare']}>.+)")
|
|
35
|
+
pos = field.end()
|
|
36
|
+
out.append(re.escape(template[pos:]))
|
|
37
|
+
return "".join(out)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class phrase(parsers.re): # noqa: N801 - read as a parser, like parsers.parse
|
|
41
|
+
"""A step's words, its values in braces as parsers.parse writes them
|
|
42
|
+
(`'the file "{path}" holds "{text}"'`), matched so that a quoted value
|
|
43
|
+
may be empty (`""`), its escapes read as cucumber reads them, and a
|
|
44
|
+
shorter step's pattern never swallows a longer one's text. `{n:d}` is a
|
|
45
|
+
whole number. Its name stays the words, so a suite's own step of the
|
|
46
|
+
same words takes its place, as with parsers.parse."""
|
|
47
|
+
|
|
48
|
+
every: list["phrase"] = []
|
|
49
|
+
|
|
50
|
+
def __init__(self, template: str) -> None:
|
|
51
|
+
super().__init__(_pattern(template, _STRICT), re.S)
|
|
52
|
+
self.loose = re.compile(_pattern(template, _LOOSE), re.S)
|
|
53
|
+
self.name = template
|
|
54
|
+
self.whole = [f["whole"] for f in _FIELD.finditer(template) if f["whole"]]
|
|
55
|
+
self.quoted = [f["quoted"] for f in _FIELD.finditer(template) if f["quoted"]]
|
|
56
|
+
phrase.every.append(self)
|
|
57
|
+
|
|
58
|
+
def is_matching(self, name: str) -> bool:
|
|
59
|
+
if self.regex.fullmatch(name):
|
|
60
|
+
return True
|
|
61
|
+
return bool(self.loose.fullmatch(name)) and not any(p.regex.fullmatch(name) for p in phrase.every)
|
|
62
|
+
|
|
63
|
+
def parse_arguments(self, name: str) -> dict[str, Any] | None:
|
|
64
|
+
found = self.regex.fullmatch(name) or self.loose.fullmatch(name)
|
|
65
|
+
if found is None:
|
|
66
|
+
return None
|
|
67
|
+
values: dict[str, Any] = found.groupdict()
|
|
68
|
+
for key in self.whole:
|
|
69
|
+
values[key] = int(values[key])
|
|
70
|
+
for key in self.quoted:
|
|
71
|
+
values[key] = _ESCAPE.sub(r"\1", values[key])
|
|
72
|
+
return values
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""The environment, for the scenario only."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pytest_bdd import given
|
|
6
|
+
|
|
7
|
+
from . import phrase
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@given(phrase('the environment sets "{name}" to "{text}"'))
|
|
11
|
+
def sets(monkeypatch, name, text):
|
|
12
|
+
monkeypatch.setenv(name, text)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@given(phrase('the environment does not set "{name}"'))
|
|
16
|
+
def unsets(monkeypatch, name):
|
|
17
|
+
monkeypatch.delenv(name, raising=False)
|
pubtest/steps/fakes.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
"""HTTP: fake services the code under test calls."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import threading
|
|
7
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
8
|
+
|
|
9
|
+
from pytest_bdd import given, then
|
|
10
|
+
|
|
11
|
+
from . import phrase
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class Fake:
|
|
15
|
+
"""One fake service: its answers by "METHOD PATH", and the requests it was sent."""
|
|
16
|
+
|
|
17
|
+
def __init__(self, name: str) -> None:
|
|
18
|
+
self.name = name
|
|
19
|
+
self.answers: dict[str, list[tuple[int, str, dict]]] = {}
|
|
20
|
+
self.requests: list[dict] = []
|
|
21
|
+
fake = self
|
|
22
|
+
|
|
23
|
+
class Handler(BaseHTTPRequestHandler):
|
|
24
|
+
def _answer(self):
|
|
25
|
+
length = int(self.headers.get("Content-Length") or 0)
|
|
26
|
+
body = self.rfile.read(length).decode("utf-8", "replace") if length else ""
|
|
27
|
+
key = f"{self.command} {self.path}"
|
|
28
|
+
fake.requests.append({"method": self.command, "path": self.path, "body": body,
|
|
29
|
+
"headers": dict(self.headers)})
|
|
30
|
+
queue = fake.answers.get(key) or fake.answers.get(f"{self.command} {self.path.split('?')[0]}")
|
|
31
|
+
status, text, headers = (queue.pop(0) if len(queue) > 1 else queue[0]) if queue else (404, "", {})
|
|
32
|
+
data = text.encode()
|
|
33
|
+
self.send_response(status)
|
|
34
|
+
self.send_header("Content-Length", str(len(data)))
|
|
35
|
+
if text.lstrip().startswith(("{", "[")) and "content-type" not in {k.lower() for k in headers}:
|
|
36
|
+
self.send_header("Content-Type", "application/json")
|
|
37
|
+
for name, value in headers.items():
|
|
38
|
+
self.send_header(name, value)
|
|
39
|
+
self.end_headers()
|
|
40
|
+
self.wfile.write(data)
|
|
41
|
+
|
|
42
|
+
do_GET = do_POST = do_PUT = do_PATCH = do_DELETE = do_HEAD = _answer
|
|
43
|
+
|
|
44
|
+
def log_message(self, *args):
|
|
45
|
+
pass
|
|
46
|
+
|
|
47
|
+
self.server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
|
|
48
|
+
# A short poll, so the scenario's end does not wait half a second on it.
|
|
49
|
+
threading.Thread(target=self.server.serve_forever, kwargs={"poll_interval": 0.02}, daemon=True).start()
|
|
50
|
+
|
|
51
|
+
@property
|
|
52
|
+
def url(self) -> str:
|
|
53
|
+
return f"http://127.0.0.1:{self.server.server_address[1]}"
|
|
54
|
+
|
|
55
|
+
def answer(self, request: str, status: int, body: str = "", headers: dict | None = None) -> None:
|
|
56
|
+
self.answers.setdefault(request, []).append((status, body, headers or {}))
|
|
57
|
+
|
|
58
|
+
def stop(self) -> None:
|
|
59
|
+
self.server.shutdown()
|
|
60
|
+
self.server.server_close()
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _env_name(name: str) -> str:
|
|
64
|
+
return "".join(c if c.isalnum() else "_" for c in name).upper() + "_URL"
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def fake(pubtest_ctx, monkeypatch, name: str) -> Fake:
|
|
68
|
+
if not hasattr(pubtest_ctx, "fakes"):
|
|
69
|
+
pubtest_ctx.fakes = {}
|
|
70
|
+
if name not in pubtest_ctx.fakes:
|
|
71
|
+
pubtest_ctx.fakes[name] = Fake(name)
|
|
72
|
+
monkeypatch.setenv(_env_name(name), pubtest_ctx.fakes[name].url)
|
|
73
|
+
pubtest_ctx.cleanup(pubtest_ctx.fakes[name].stop)
|
|
74
|
+
return pubtest_ctx.fakes[name]
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
@given(phrase('a fake "{name}" service'))
|
|
78
|
+
def fake_service(pubtest_ctx, monkeypatch, name):
|
|
79
|
+
fake(pubtest_ctx, monkeypatch, name)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
@given(phrase('the "{name}" service answers "{request}" with {status:d}'))
|
|
83
|
+
def answers(pubtest_ctx, monkeypatch, name, request, status):
|
|
84
|
+
fake(pubtest_ctx, monkeypatch, name).answer(request, status)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
@given(phrase('the "{name}" service answers "{request}" with {status:d} and:'))
|
|
88
|
+
def answers_with(pubtest_ctx, monkeypatch, name, request, status, docstring):
|
|
89
|
+
fake(pubtest_ctx, monkeypatch, name).answer(request, status, docstring)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
@given(phrase('the "{name}" service answers "{request}" with {status:d} and the header "{header}" set to "{value}"'))
|
|
93
|
+
def answers_with_header(pubtest_ctx, monkeypatch, name, request, status, header, value):
|
|
94
|
+
fake(pubtest_ctx, monkeypatch, name).answer(request, status, "", {header: value})
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
@given(phrase('the "{name}" service answers "{request}" with {status:d}, the header "{header}" set to "{value}", and:'))
|
|
98
|
+
def answers_with_header_and(pubtest_ctx, monkeypatch, name, request, status, header, value, docstring):
|
|
99
|
+
fake(pubtest_ctx, monkeypatch, name).answer(request, status, docstring, {header: value})
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _asked(pubtest_ctx, name: str) -> list[dict]:
|
|
103
|
+
fakes = getattr(pubtest_ctx, "fakes", {})
|
|
104
|
+
assert name in fakes, f"there is no fake {name} service"
|
|
105
|
+
return fakes[name].requests
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
@then(phrase('the "{name}" service was asked "{request}"'))
|
|
109
|
+
def was_asked(pubtest_ctx, name, request):
|
|
110
|
+
asked = [f"{r['method']} {r['path']}" for r in _asked(pubtest_ctx, name)]
|
|
111
|
+
assert request in asked or request in [a.split("?")[0] for a in asked], f"{name} was asked {asked}"
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _requests(pubtest_ctx, name: str, request: str) -> list[dict]:
|
|
115
|
+
"""The requests `name` was asked that are `request`, "METHOD PATH", its
|
|
116
|
+
query left out unless `request` names one."""
|
|
117
|
+
return [r for r in _asked(pubtest_ctx, name)
|
|
118
|
+
if request in (f"{r['method']} {r['path']}", f"{r['method']} {r['path'].split('?')[0]}")]
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _header(request: dict, header: str) -> str | None:
|
|
122
|
+
return {k.lower(): v for k, v in request["headers"].items()}.get(header.lower())
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
@then(phrase('the "{name}" service was asked "{request}" {count:d} times'))
|
|
126
|
+
def asked_times(pubtest_ctx, name, request, count):
|
|
127
|
+
found = _requests(pubtest_ctx, name, request)
|
|
128
|
+
assert len(found) == count, f"{name} was asked {request} {len(found)} times"
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
@then(phrase('the "{name}" service was asked "{request}" with the header "{header}" set to "{value}"'))
|
|
132
|
+
def asked_with_header(pubtest_ctx, name, request, header, value):
|
|
133
|
+
found = _requests(pubtest_ctx, name, request)
|
|
134
|
+
seen = [_header(r, header) for r in found]
|
|
135
|
+
assert value in seen, f"{name} was asked {request} with {header} {seen}"
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
@then(phrase('the "{name}" service was asked "{request}" without the header "{header}"'))
|
|
139
|
+
def asked_without_header(pubtest_ctx, name, request, header):
|
|
140
|
+
"""It was asked METHOD PATH, and no such request carried the header."""
|
|
141
|
+
found = _requests(pubtest_ctx, name, request)
|
|
142
|
+
assert found, f"{name} was not asked {request}"
|
|
143
|
+
seen = [_header(r, header) for r in found if _header(r, header) is not None]
|
|
144
|
+
assert not seen, f"{name} was asked {request} with {header} {seen}"
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
@then(phrase('every request to the "{name}" service carried the header "{header}" set to "{value}"'))
|
|
148
|
+
def every_request_carried(pubtest_ctx, name, header, value):
|
|
149
|
+
"""It was asked something, and each request carried the header with this value."""
|
|
150
|
+
asked = _asked(pubtest_ctx, name)
|
|
151
|
+
assert asked, f"{name} was asked nothing"
|
|
152
|
+
wrong = [f"{r['method']} {r['path']}: {_header(r, header)!r}" for r in asked if _header(r, header) != value]
|
|
153
|
+
assert not wrong, f"not every request to {name} carried {header} {value!r}: {wrong}"
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
@then(phrase('the "{name}" service was sent:'))
|
|
157
|
+
def was_sent(pubtest_ctx, name, docstring):
|
|
158
|
+
want = json.loads(docstring)
|
|
159
|
+
bodies = []
|
|
160
|
+
for request in _asked(pubtest_ctx, name):
|
|
161
|
+
try:
|
|
162
|
+
bodies.append(json.loads(request["body"]))
|
|
163
|
+
except ValueError:
|
|
164
|
+
bodies.append(request["body"])
|
|
165
|
+
assert want in bodies, f"{name} was sent {bodies}"
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
@then(phrase('the "{name}" service was asked nothing'))
|
|
169
|
+
def asked_nothing(pubtest_ctx, name):
|
|
170
|
+
assert not _asked(pubtest_ctx, name), f"{name} was asked {_asked(pubtest_ctx, name)}"
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
@then("nothing was sent")
|
|
174
|
+
def nothing_sent(pubtest_ctx):
|
|
175
|
+
sent = {name: f.requests for name, f in getattr(pubtest_ctx, "fakes", {}).items() if f.requests}
|
|
176
|
+
assert not sent, f"sent: {sent}"
|