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/__init__.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"""pubtest: the Gherkin steps every Sustenaut suite shares (GRAMMAR.md).
|
|
2
|
+
|
|
3
|
+
Installed, its pytest plugin loads into every pytest session and gives a
|
|
4
|
+
suite the steps, the `ctx` a scenario keeps its state in, and `run` and
|
|
5
|
+
`binary` for the programs it drives.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
// Loaded by every Node program a pubtest scenario runs (NODE_OPTIONS=--import):
|
|
2
|
+
// a program in replay answers its calls from INTEGRATIONS_CASSETTE through a
|
|
3
|
+
// Cassette of its own, installed with integrations' use(), and at exit writes
|
|
4
|
+
// which recorded calls it used to INTEGRATIONS_CASSETTE_REPORT, so the scenario
|
|
5
|
+
// fails on a recorded call no process made. integrations has no hook for this
|
|
6
|
+
// yet. @sustenaut/integrations is found from the program's working directory,
|
|
7
|
+
// else from here; a program that loads another copy of it is not reported.
|
|
8
|
+
import fs from "node:fs";
|
|
9
|
+
import { createRequire } from "node:module";
|
|
10
|
+
import path from "node:path";
|
|
11
|
+
import { pathToFileURL } from "node:url";
|
|
12
|
+
|
|
13
|
+
const report = process.env.INTEGRATIONS_CASSETTE_REPORT;
|
|
14
|
+
const file = process.env.INTEGRATIONS_CASSETTE;
|
|
15
|
+
if (report && file && process.env.INTEGRATIONS_MODE === "replay" && process.env.PUBTEST_RUN) {
|
|
16
|
+
let transports = null;
|
|
17
|
+
for (const from of [path.join(process.cwd(), "noop.js"), import.meta.url]) {
|
|
18
|
+
try {
|
|
19
|
+
transports = await import(pathToFileURL(createRequire(from).resolve("@sustenaut/integrations/transports.js")).href);
|
|
20
|
+
break;
|
|
21
|
+
} catch {
|
|
22
|
+
// not there: the program makes no integration calls through this copy
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
if (transports) {
|
|
26
|
+
let cassette = null;
|
|
27
|
+
transports.use({
|
|
28
|
+
fetch: async (url, init) => {
|
|
29
|
+
cassette ??= new transports.Cassette(transports.cassettePath(file), { mode: "replay" });
|
|
30
|
+
return cassette.fetch(url, init);
|
|
31
|
+
},
|
|
32
|
+
});
|
|
33
|
+
process.on("exit", () => {
|
|
34
|
+
if (!cassette) return;
|
|
35
|
+
const used = cassette.calls.flatMap((c, i) => (c.used ? [i] : []));
|
|
36
|
+
const answered = cassette.calls.reduce((n, c) => n + c.used, 0);
|
|
37
|
+
fs.appendFileSync(report, JSON.stringify({ pid: process.pid, language: "node", cassette: file, calls: cassette.calls.length, used, sent: cassette.sent.length, answered }) + "\n");
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""Loaded by every Python program a pubtest scenario runs (its directory is
|
|
2
|
+
first on PYTHONPATH then): at exit, a program that replayed calls from a
|
|
3
|
+
cassette writes which recorded calls it used to INTEGRATIONS_CASSETTE_REPORT,
|
|
4
|
+
so the scenario fails on a recorded call no process made.
|
|
5
|
+
|
|
6
|
+
integrations has no hook for this yet, so it reads the Cassette that
|
|
7
|
+
`integrations.transports.current_transport()` made from INTEGRATIONS_MODE
|
|
8
|
+
(`_by_mode`, private). A sitecustomize of the program's own, further along
|
|
9
|
+
sys.path, still runs after this one.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import atexit
|
|
13
|
+
import json
|
|
14
|
+
import os
|
|
15
|
+
import sys
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _report() -> None:
|
|
19
|
+
path = os.environ.get("INTEGRATIONS_CASSETTE_REPORT")
|
|
20
|
+
transports = sys.modules.get("integrations.transports")
|
|
21
|
+
if not path or transports is None:
|
|
22
|
+
return
|
|
23
|
+
for transport in list(getattr(transports, "_by_mode", {}).values()):
|
|
24
|
+
if not isinstance(transport, transports.Cassette):
|
|
25
|
+
continue
|
|
26
|
+
calls = transport.calls
|
|
27
|
+
entry = {"pid": os.getpid(), "language": "python", "cassette": os.environ.get("INTEGRATIONS_CASSETTE"),
|
|
28
|
+
"calls": len(calls), "used": [i for i, c in enumerate(calls) if c.used],
|
|
29
|
+
"sent": len(transport.sent), "answered": sum(c.used for c in calls)}
|
|
30
|
+
with open(path, "a", encoding="utf-8") as out:
|
|
31
|
+
out.write(json.dumps(entry) + "\n")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _chain() -> None:
|
|
35
|
+
"""The next sitecustomize on sys.path, which this one would otherwise hide."""
|
|
36
|
+
import importlib.machinery # noqa: PLC0415
|
|
37
|
+
import importlib.util # noqa: PLC0415
|
|
38
|
+
here = os.path.dirname(os.path.abspath(__file__))
|
|
39
|
+
rest = [p for p in sys.path if os.path.abspath(p or os.curdir) != here]
|
|
40
|
+
spec = importlib.machinery.PathFinder.find_spec("sitecustomize", rest)
|
|
41
|
+
if spec is not None and spec.loader is not None:
|
|
42
|
+
module = importlib.util.module_from_spec(spec)
|
|
43
|
+
spec.loader.exec_module(module)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
atexit.register(_report)
|
|
47
|
+
_chain()
|
pubtest/cassettes.py
ADDED
|
@@ -0,0 +1,587 @@
|
|
|
1
|
+
"""Record and replay for a suite's calls to outside services (GRAMMAR.md,
|
|
2
|
+
"Record and replay").
|
|
3
|
+
|
|
4
|
+
One cassette per scenario, in integrations' format (`integrations.cassette/1`):
|
|
5
|
+
each scenario runs on `use(Cassette(...))` in replay, or on
|
|
6
|
+
`use(Recorder(Network(), ...))` in record mode, saved when it passes. Programs a
|
|
7
|
+
scenario runs learn their cassette from `INTEGRATIONS_MODE` and
|
|
8
|
+
`INTEGRATIONS_CASSETTE`, and say at exit which recorded calls they used, so an
|
|
9
|
+
unused call fails the scenario wherever it was recorded.
|
|
10
|
+
|
|
11
|
+
integrations is optional: everything here is inert unless
|
|
12
|
+
`integrations.transports` imports and the repository turns cassettes on
|
|
13
|
+
(`"pubtest": {"cassettes": ...}` in pubrules.json, or `PUBTEST_CASSETTES=1`).
|
|
14
|
+
pubtest never depends on integrations, whose own suite runs on pubtest.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import hashlib
|
|
20
|
+
import importlib
|
|
21
|
+
import inspect
|
|
22
|
+
import json
|
|
23
|
+
import os
|
|
24
|
+
import random
|
|
25
|
+
import re
|
|
26
|
+
import subprocess
|
|
27
|
+
import sys
|
|
28
|
+
import tempfile
|
|
29
|
+
import time
|
|
30
|
+
import uuid
|
|
31
|
+
from dataclasses import dataclass
|
|
32
|
+
from pathlib import Path
|
|
33
|
+
from typing import Any, Callable
|
|
34
|
+
|
|
35
|
+
from .core import repository
|
|
36
|
+
|
|
37
|
+
__all__ = ["Scenario", "Settings", "Tape", "path_for", "settings", "slug"]
|
|
38
|
+
|
|
39
|
+
RECORD = "PUBTEST_RECORD" # 1: record; anything else: replay
|
|
40
|
+
SWITCH = "PUBTEST_CASSETTES" # 1 turns the harness on, 0 off, whatever pubrules.json says
|
|
41
|
+
ONLY = "PUBTEST_ONLY" # a JSON list of scenarios: the others are not run
|
|
42
|
+
PLAN = "PUBTEST_PLAN" # a file: each scenario writes whether its cassette is stale
|
|
43
|
+
REPORT = "INTEGRATIONS_CASSETTE_REPORT" # a file: each program writes the calls it used
|
|
44
|
+
RUN = "PUBTEST_RUN"
|
|
45
|
+
MODE = "INTEGRATIONS_MODE"
|
|
46
|
+
CASSETTE = "INTEGRATIONS_CASSETTE"
|
|
47
|
+
CASSETTES = "INTEGRATIONS_CASSETTES"
|
|
48
|
+
CHILD = Path(__file__).parent / "_child"
|
|
49
|
+
NO_DATA_REPO = "no data repo: `pubtest record --all` creates it"
|
|
50
|
+
OFF = ('the integration steps need the record/replay harness: install integrations and set '
|
|
51
|
+
'"pubtest": {"cassettes": ...} in pubrules.json (GRAMMAR.md, "Record and replay")')
|
|
52
|
+
|
|
53
|
+
# The transport record mode records through: the network. A suite's own tests
|
|
54
|
+
# of recording put a stand-in here; nothing else should.
|
|
55
|
+
network: Callable[[], Any] | None = None
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def transports() -> Any:
|
|
59
|
+
"""integrations.transports, or None when integrations is not installed."""
|
|
60
|
+
try:
|
|
61
|
+
return importlib.import_module("integrations.transports")
|
|
62
|
+
except ImportError:
|
|
63
|
+
return None
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def slug(title: str) -> str:
|
|
67
|
+
"""A scenario's title as a file name: lower-cased, each run of anything but
|
|
68
|
+
a-z and 0-9 one "-", none at either end."""
|
|
69
|
+
return re.sub(r"[^a-z0-9]+", "-", title.lower()).strip("-") or "scenario"
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@dataclass(frozen=True)
|
|
73
|
+
class Scenario:
|
|
74
|
+
"""A scenario as a cassette names it: its feature file's name, its title (an
|
|
75
|
+
outline's, its <placeholders> as written) and, for an outline, its Examples
|
|
76
|
+
row, from 1."""
|
|
77
|
+
|
|
78
|
+
feature: str
|
|
79
|
+
title: str
|
|
80
|
+
row: int | None = None
|
|
81
|
+
|
|
82
|
+
@property
|
|
83
|
+
def stem(self) -> str:
|
|
84
|
+
return self.feature.removesuffix(".feature")
|
|
85
|
+
|
|
86
|
+
@property
|
|
87
|
+
def id(self) -> str:
|
|
88
|
+
return f"{self.feature}: {self.title}" + (f" #{self.row}" if self.row else "")
|
|
89
|
+
|
|
90
|
+
@property
|
|
91
|
+
def relative(self) -> str:
|
|
92
|
+
if self.row:
|
|
93
|
+
return f"{self.stem}/{slug(self.title)}/{self.row}.json"
|
|
94
|
+
return f"{self.stem}/{slug(self.title)}.json"
|
|
95
|
+
|
|
96
|
+
def named_by(self, selector: str) -> bool:
|
|
97
|
+
"""Whether `selector` names this scenario: its id, its id without the row,
|
|
98
|
+
"stem: title", the title alone, or its cassette's path without .json."""
|
|
99
|
+
selector = selector.strip()
|
|
100
|
+
names = {self.id, f"{self.feature}: {self.title}", f"{self.stem}: {self.title}", self.title,
|
|
101
|
+
self.relative.removesuffix(".json")}
|
|
102
|
+
if self.row:
|
|
103
|
+
names.add(f"{self.stem}: {self.title} #{self.row}")
|
|
104
|
+
return selector in names
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def parse(selector: str, feature: str | None = None) -> Scenario:
|
|
108
|
+
"""A scenario from what a person writes: "FILE: TITLE[ #ROW]", or a TITLE of
|
|
109
|
+
`feature`'s."""
|
|
110
|
+
text = selector.strip()
|
|
111
|
+
row = None
|
|
112
|
+
m = re.fullmatch(r"(.*) #(\d+)", text)
|
|
113
|
+
if m:
|
|
114
|
+
text, row = m.group(1), int(m.group(2))
|
|
115
|
+
head, sep, title = text.partition(": ")
|
|
116
|
+
if sep and head.endswith(".feature"):
|
|
117
|
+
return Scenario(head, title, row)
|
|
118
|
+
if feature is None:
|
|
119
|
+
raise ValueError(f'"{selector}" names no feature: write it "FILE.feature: TITLE"')
|
|
120
|
+
return Scenario(feature, text, row)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _truthy(value: str | None) -> bool | None:
|
|
124
|
+
if value is None or value == "":
|
|
125
|
+
return None
|
|
126
|
+
return value.lower() not in ("0", "false", "no", "off")
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _declared(root: Path) -> Any:
|
|
130
|
+
try:
|
|
131
|
+
data = json.loads((root / "pubrules.json").read_text(encoding="utf-8"))
|
|
132
|
+
except (OSError, ValueError):
|
|
133
|
+
return None
|
|
134
|
+
block = data.get("pubtest") if isinstance(data, dict) else None
|
|
135
|
+
return block.get("cassettes") if isinstance(block, dict) else None
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
@dataclass
|
|
139
|
+
class Settings:
|
|
140
|
+
"""The session's: whether the harness is on, its mode, and where cassettes are."""
|
|
141
|
+
|
|
142
|
+
active: bool
|
|
143
|
+
mode: str
|
|
144
|
+
root: Path
|
|
145
|
+
cassettes: Path | None
|
|
146
|
+
data_repo: Path | None
|
|
147
|
+
# The cassettes directory is pubrules.json's "DIR", in the repository itself.
|
|
148
|
+
named: bool = False
|
|
149
|
+
|
|
150
|
+
@property
|
|
151
|
+
def recording(self) -> bool:
|
|
152
|
+
return self.mode == "record"
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def settings(root: Path | None = None, env: dict[str, str] | None = None) -> Settings:
|
|
156
|
+
"""The harness's settings for the repository at `root`.
|
|
157
|
+
|
|
158
|
+
On when integrations.transports imports and either PUBTEST_CASSETTES is 1 or
|
|
159
|
+
pubrules.json has `"pubtest": {"cassettes": true}` (the data repository's
|
|
160
|
+
directory) or `{"cassettes": "DIR"}` (a directory of the repository's own);
|
|
161
|
+
PUBTEST_CASSETTES=0 turns it off. The cassettes directory is
|
|
162
|
+
INTEGRATIONS_CASSETTES, else DIR, else ../<repo>-data/integrations/cassettes."""
|
|
163
|
+
env = os.environ if env is None else env
|
|
164
|
+
root = (root or repository()).resolve()
|
|
165
|
+
declared = _declared(root)
|
|
166
|
+
switch = _truthy(env.get(SWITCH))
|
|
167
|
+
wanted = switch if switch is not None else bool(declared)
|
|
168
|
+
active = bool(wanted) and transports() is not None
|
|
169
|
+
data_repo = None
|
|
170
|
+
named = False
|
|
171
|
+
if env.get(CASSETTES):
|
|
172
|
+
cassettes = Path(env[CASSETTES]).absolute()
|
|
173
|
+
elif isinstance(declared, str):
|
|
174
|
+
cassettes = (root / declared).absolute()
|
|
175
|
+
named = True
|
|
176
|
+
else:
|
|
177
|
+
data_repo = root.parent / f"{root.name}-data"
|
|
178
|
+
cassettes = data_repo / "integrations" / "cassettes"
|
|
179
|
+
return Settings(active, "record" if _truthy(env.get(RECORD)) else "replay", root, cassettes, data_repo,
|
|
180
|
+
named)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def stand_in_only(found: Settings, real_network: bool) -> str | None:
|
|
184
|
+
"""The warning a recording gives when it records the real network into
|
|
185
|
+
pubrules.json's "DIR": that form is for a suite whose record transport is a
|
|
186
|
+
stand-in (pubtest's own), since the repository is no place for what real
|
|
187
|
+
services answered."""
|
|
188
|
+
if not (found.active and found.recording and found.named and real_network):
|
|
189
|
+
return None
|
|
190
|
+
return (f'pubtest record: warning: {found.cassettes} is pubrules.json\'s "cassettes": "DIR", which is only '
|
|
191
|
+
"for a suite whose record transport is a stand-in; this one records the real network, whose answers "
|
|
192
|
+
'belong in the private data repository ("pubtest": {"cassettes": true})')
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def start_session(found: Settings) -> None:
|
|
196
|
+
"""At the session's start: refuse a replay with no cassettes at all, make the
|
|
197
|
+
directory a recording needs, and set the variables every program inherits.
|
|
198
|
+
Raises `LookupError` saying what is missing."""
|
|
199
|
+
if not found.active:
|
|
200
|
+
return
|
|
201
|
+
if not found.cassettes.is_dir():
|
|
202
|
+
if found.recording and (found.data_repo is None or found.data_repo.is_dir()):
|
|
203
|
+
found.cassettes.mkdir(parents=True, exist_ok=True)
|
|
204
|
+
else:
|
|
205
|
+
raise LookupError(f"{NO_DATA_REPO} (there is no {found.cassettes})")
|
|
206
|
+
os.environ.setdefault(RUN, uuid.uuid4().hex)
|
|
207
|
+
os.environ[MODE] = found.mode
|
|
208
|
+
os.environ[CASSETTES] = str(found.cassettes.resolve())
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def only() -> list[str] | None:
|
|
212
|
+
raw = os.environ.get(ONLY)
|
|
213
|
+
return json.loads(raw) if raw else None
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def selected(scenario: Scenario) -> bool:
|
|
217
|
+
chosen = only()
|
|
218
|
+
return chosen is None or any(scenario.named_by(s) for s in chosen)
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def path_for(scenario: Scenario, found: Settings | None = None) -> Path:
|
|
222
|
+
"""The cassette of `scenario`: <feature stem>/<title slug>.json, or
|
|
223
|
+
<feature stem>/<title slug>/<row>.json for an Examples row, in the cassettes
|
|
224
|
+
directory."""
|
|
225
|
+
found = found or settings()
|
|
226
|
+
if found.cassettes is None:
|
|
227
|
+
raise LookupError(NO_DATA_REPO)
|
|
228
|
+
return found.cassettes / scenario.relative
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def matches_name(name: str, plugin: str | None) -> bool:
|
|
232
|
+
"""NAME is a plugin's id (`github.edit-pr`) or what every id it stands for
|
|
233
|
+
starts with, before a dot (`github` is every github.* plugin)."""
|
|
234
|
+
plugin = plugin or ""
|
|
235
|
+
return plugin == name or plugin.startswith(name + ".")
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def text_hash(steps: list[tuple[str, str | None, list[list[str]] | None]]) -> str:
|
|
239
|
+
"""The scenario's steps as it runs them: each one's text, docstring and table."""
|
|
240
|
+
lines = []
|
|
241
|
+
for text, docstring, table in steps:
|
|
242
|
+
lines.append(text)
|
|
243
|
+
if docstring is not None:
|
|
244
|
+
lines.append('"""\n' + docstring + '\n"""')
|
|
245
|
+
for row in table or []:
|
|
246
|
+
lines.append("| " + " | ".join(row) + " |")
|
|
247
|
+
return hashlib.sha256("\n".join(lines).encode()).hexdigest()
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def _git(root: Path, *args: str) -> str:
|
|
251
|
+
try:
|
|
252
|
+
done = subprocess.run(["git", *args], cwd=root, capture_output=True, text=True, check=False, timeout=30)
|
|
253
|
+
except OSError:
|
|
254
|
+
return ""
|
|
255
|
+
return done.stdout.strip() if done.returncode == 0 else ""
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def consumer(root: Path) -> str:
|
|
259
|
+
"""<repo>@<commit>: the repository the recording was made from."""
|
|
260
|
+
origin = _git(root, "remote", "get-url", "origin")
|
|
261
|
+
name = re.sub(r"\.git$", "", origin.rstrip("/").rsplit("/", 1)[-1].rsplit(":", 1)[-1]) if origin else root.name
|
|
262
|
+
return f"{name}@{_git(root, 'rev-parse', 'HEAD') or 'uncommitted'}"
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def integrations_version() -> str:
|
|
266
|
+
try:
|
|
267
|
+
return importlib.import_module("integrations").__version__
|
|
268
|
+
except (ImportError, AttributeError):
|
|
269
|
+
return "unknown"
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
class Clock:
|
|
273
|
+
"""The scenario's clock, sleep and jitter for a Caller. In replay nothing waits:
|
|
274
|
+
a sleep moves the clock on, as `Faulty`'s slow answers do, and the jitter is
|
|
275
|
+
half its range. In record mode a sleep waits."""
|
|
276
|
+
|
|
277
|
+
def __init__(self, fake: bool) -> None:
|
|
278
|
+
self.fake, self.offset, self.slept, self.base = fake, 0.0, 0.0, time.monotonic()
|
|
279
|
+
|
|
280
|
+
def now(self) -> float:
|
|
281
|
+
return (self.base if self.fake else time.monotonic()) + self.offset
|
|
282
|
+
|
|
283
|
+
def sleep(self, seconds: float) -> None:
|
|
284
|
+
self.slept += seconds
|
|
285
|
+
if self.fake:
|
|
286
|
+
self.offset += seconds
|
|
287
|
+
else:
|
|
288
|
+
time.sleep(seconds)
|
|
289
|
+
|
|
290
|
+
def advance(self, seconds: float) -> None:
|
|
291
|
+
self.offset += seconds
|
|
292
|
+
|
|
293
|
+
def random(self) -> float:
|
|
294
|
+
return 0.5 if self.fake else random.random()
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
class _Hold:
|
|
298
|
+
"""A transport that hands each call to `fn`."""
|
|
299
|
+
|
|
300
|
+
def __init__(self, fn: Callable[[Any, float], Any]) -> None:
|
|
301
|
+
self.send = fn
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
class Tape:
|
|
305
|
+
"""One scenario's calls: its cassette, the faults put on it, the clock, the
|
|
306
|
+
requests made, and the names its test customers gave."""
|
|
307
|
+
|
|
308
|
+
def __init__(self, found: Settings, scenario: Scenario, tags: set[str], steps_text: str) -> None:
|
|
309
|
+
self.t = transports()
|
|
310
|
+
self.settings, self.scenario, self.text = found, scenario, steps_text
|
|
311
|
+
self.path = path_for(scenario, found)
|
|
312
|
+
self.borrowed: Path | None = None
|
|
313
|
+
for tag in tags:
|
|
314
|
+
if tag.startswith("cassette:"):
|
|
315
|
+
self.borrow(tag.removeprefix("cassette:").strip('"'))
|
|
316
|
+
self.clock = Clock(fake=not found.recording or self.borrowed is not None)
|
|
317
|
+
self.requests: list[tuple[str | None, str | None]] = []
|
|
318
|
+
self.errors: list[str] = []
|
|
319
|
+
self.sources: list[str] = []
|
|
320
|
+
self.names: dict[str, dict[str, str]] = {}
|
|
321
|
+
self.customers: dict[str, Any] = {}
|
|
322
|
+
self.cassette = None
|
|
323
|
+
self.recorder = None
|
|
324
|
+
self.failed = False
|
|
325
|
+
work = Path(tempfile.mkdtemp(prefix="pubtest-cassette-"))
|
|
326
|
+
self.work, self.report = work, work / "report.jsonl"
|
|
327
|
+
self.faulty = self.t.Faulty(_Hold(self._inner), [], advance=self.clock.advance)
|
|
328
|
+
self._saved_env: dict[str, str | None] = {}
|
|
329
|
+
self._defaults: dict[str, Any] | None = None
|
|
330
|
+
self._use = None
|
|
331
|
+
if not found.recording or self.borrowed is not None:
|
|
332
|
+
self._replayed_names()
|
|
333
|
+
|
|
334
|
+
# --- what the steps change -------------------------------------------------
|
|
335
|
+
|
|
336
|
+
def borrow(self, selector: str) -> None:
|
|
337
|
+
"""Replay another scenario's cassette: a fault scenario's, over a recording
|
|
338
|
+
of the scenario it breaks. `selector` names the scenario ("FILE: TITLE", or
|
|
339
|
+
a TITLE of this feature's), or, as a tag must for want of spaces, its
|
|
340
|
+
cassette's path without .json."""
|
|
341
|
+
if "/" in selector and ": " not in selector:
|
|
342
|
+
self.borrowed = self.settings.cassettes / (selector.removesuffix(".json") + ".json")
|
|
343
|
+
else:
|
|
344
|
+
self.borrowed = path_for(parse(selector, self.scenario.feature), self.settings)
|
|
345
|
+
self.cassette = None
|
|
346
|
+
if hasattr(self, "clock"):
|
|
347
|
+
self.clock.fake = True
|
|
348
|
+
self._replayed_names()
|
|
349
|
+
|
|
350
|
+
def fault(self, name: str, effect: str, nth: str = "*", where: str = "", body: str | None = None) -> None:
|
|
351
|
+
"""A fault on the calls to NAME (a plugin, or a prefix of plugins), matching
|
|
352
|
+
"METHOD PATH" when `where` gives one."""
|
|
353
|
+
fault = _prefixed(self.t)({"match": f"* {where}".strip(), "nth": nth, "effect": effect,
|
|
354
|
+
**({"body": body} if body is not None else {})}, name)
|
|
355
|
+
self.faulty.rules.append(fault)
|
|
356
|
+
|
|
357
|
+
def names_of(self, customer: str) -> dict[str, str]:
|
|
358
|
+
"""The names a test customer gave: made by its setup when recording, read
|
|
359
|
+
back from the cassette in replay."""
|
|
360
|
+
if customer not in self.names and self.settings.recording and self.borrowed is None:
|
|
361
|
+
found = self.customers.get(customer)
|
|
362
|
+
if found is None:
|
|
363
|
+
raise LookupError(f"no test customer {customer}: a package registers it in pubtest.customers")
|
|
364
|
+
self.names[customer] = dict(getattr(found, "setup", lambda ctx: {})(self) or {})
|
|
365
|
+
return self.names.setdefault(customer, {})
|
|
366
|
+
|
|
367
|
+
# --- the transport ------------------------------------------------------------
|
|
368
|
+
|
|
369
|
+
def send(self, request: Any, timeout: float) -> Any:
|
|
370
|
+
self.requests.append((request.plugin or None, request.operation or None))
|
|
371
|
+
return self.faulty.send(request, timeout)
|
|
372
|
+
|
|
373
|
+
def _inner(self, request: Any, timeout: float) -> Any:
|
|
374
|
+
if self.settings.recording and self.borrowed is None:
|
|
375
|
+
if self.recorder is None:
|
|
376
|
+
inner = network() if network is not None else self.t.Network()
|
|
377
|
+
self.recorder = self.t.Recorder(inner, None, scenario=self.scenario.id,
|
|
378
|
+
consumer=consumer(self.settings.root), clock=self.clock.now)
|
|
379
|
+
return self.recorder.send(request, timeout)
|
|
380
|
+
return self._loaded().send(request, timeout)
|
|
381
|
+
|
|
382
|
+
def _loaded(self) -> Any:
|
|
383
|
+
if self.cassette is None:
|
|
384
|
+
source = self.borrowed or self.path
|
|
385
|
+
if not source.is_file():
|
|
386
|
+
whose = self.scenario.id if self.borrowed is None else source.relative_to(self.settings.cassettes)
|
|
387
|
+
message = f'no cassette for {whose}: record it (`pubtest record "{self.scenario.id}"`)'
|
|
388
|
+
self.errors.append(message)
|
|
389
|
+
raise self.t.NoSnapshot(message)
|
|
390
|
+
cassette = self.t.Cassette(source, mode="replay")
|
|
391
|
+
answer = cassette.send
|
|
392
|
+
|
|
393
|
+
def send(request: Any, timeout: float) -> Any:
|
|
394
|
+
try:
|
|
395
|
+
return answer(request, timeout)
|
|
396
|
+
except self.t.NoSnapshot as e: # kept, so code that swallows it still fails the scenario
|
|
397
|
+
self.errors.append(str(e))
|
|
398
|
+
raise
|
|
399
|
+
cassette.send = send
|
|
400
|
+
self.cassette = cassette
|
|
401
|
+
return self.cassette
|
|
402
|
+
|
|
403
|
+
def _replayed_names(self) -> None:
|
|
404
|
+
source = self.borrowed or self.path
|
|
405
|
+
try:
|
|
406
|
+
data = json.loads(source.read_text(encoding="utf-8"))
|
|
407
|
+
except (OSError, ValueError):
|
|
408
|
+
return
|
|
409
|
+
names = ((data.get("current") or {}).get("recorded") or {}).get("pubtest", {}).get("names") or {}
|
|
410
|
+
self.names = {k: dict(v) for k, v in names.items()}
|
|
411
|
+
|
|
412
|
+
# --- the scenario's start and end ----------------------------------------------
|
|
413
|
+
|
|
414
|
+
def begin(self) -> None:
|
|
415
|
+
self._use = self.t.use(_Hold(self.send))
|
|
416
|
+
self._use.__enter__()
|
|
417
|
+
self._patch_caller()
|
|
418
|
+
child_cassette = self.borrowed or self.path
|
|
419
|
+
env = {CASSETTE: str(child_cassette), REPORT: str(self.report)}
|
|
420
|
+
if self.settings.recording and self.borrowed is None:
|
|
421
|
+
# A program records into a file of its own, which the scenario takes
|
|
422
|
+
# as its recording when it makes no calls itself.
|
|
423
|
+
env = {CASSETTE: str(self.work / "child.json"), CASSETTES: str(self.work.resolve()),
|
|
424
|
+
REPORT: str(self.report)}
|
|
425
|
+
env["PYTHONPATH"] = os.pathsep.join(p for p in (str(CHILD), os.environ.get("PYTHONPATH")) if p)
|
|
426
|
+
hook = f"--import={(CHILD / 'report.mjs').as_uri()}"
|
|
427
|
+
env["NODE_OPTIONS"] = " ".join(p for p in (os.environ.get("NODE_OPTIONS"), hook) if p)
|
|
428
|
+
for key, value in env.items():
|
|
429
|
+
self._saved_env[key] = os.environ.get(key)
|
|
430
|
+
os.environ[key] = value
|
|
431
|
+
|
|
432
|
+
def _patch_caller(self) -> None:
|
|
433
|
+
calls = sys.modules.get("integrations.calls") or importlib.import_module("integrations.calls")
|
|
434
|
+
defaults = calls.Caller.__init__.__kwdefaults__
|
|
435
|
+
self._defaults = dict(defaults)
|
|
436
|
+
defaults.update(clock=self.clock.now, sleep=self.clock.sleep, random=self.clock.random)
|
|
437
|
+
|
|
438
|
+
def step(self, fn: Callable) -> None:
|
|
439
|
+
try:
|
|
440
|
+
self.sources.append(inspect.getsource(fn))
|
|
441
|
+
except (OSError, TypeError):
|
|
442
|
+
self.sources.append(getattr(fn, "__qualname__", repr(fn)))
|
|
443
|
+
|
|
444
|
+
@property
|
|
445
|
+
def steps_hash(self) -> str:
|
|
446
|
+
return hashlib.sha256("\n".join(self.sources).encode()).hexdigest()
|
|
447
|
+
|
|
448
|
+
def children(self) -> list[dict]:
|
|
449
|
+
if not self.report.is_file():
|
|
450
|
+
return []
|
|
451
|
+
return [json.loads(line) for line in self.report.read_text(encoding="utf-8").splitlines() if line.strip()]
|
|
452
|
+
|
|
453
|
+
def end(self) -> list[str]:
|
|
454
|
+
"""Close the scenario: undo what begin() did, check or save its cassette,
|
|
455
|
+
run its customers' cleanups. Returns what fails it."""
|
|
456
|
+
problems: list[str] = []
|
|
457
|
+
try:
|
|
458
|
+
if self._use is not None:
|
|
459
|
+
self._use.__exit__(None, None, None)
|
|
460
|
+
if self._defaults is not None:
|
|
461
|
+
calls = sys.modules["integrations.calls"]
|
|
462
|
+
calls.Caller.__init__.__kwdefaults__.clear()
|
|
463
|
+
calls.Caller.__init__.__kwdefaults__.update(self._defaults)
|
|
464
|
+
for key, value in self._saved_env.items():
|
|
465
|
+
if value is None:
|
|
466
|
+
os.environ.pop(key, None)
|
|
467
|
+
else:
|
|
468
|
+
os.environ[key] = value
|
|
469
|
+
if self.settings.recording and self.borrowed is None:
|
|
470
|
+
if not self.failed:
|
|
471
|
+
problems += self._save()
|
|
472
|
+
else:
|
|
473
|
+
problems += self._check()
|
|
474
|
+
if os.environ.get(PLAN):
|
|
475
|
+
self._plan(problems)
|
|
476
|
+
finally:
|
|
477
|
+
if self.settings.recording and self.borrowed is None:
|
|
478
|
+
for name, customer in self.customers.items():
|
|
479
|
+
if name in self.names and hasattr(customer, "cleanup"):
|
|
480
|
+
try:
|
|
481
|
+
customer.cleanup(self, self.names[name])
|
|
482
|
+
except Exception as e: # noqa: BLE001 - every cleanup runs, and says so
|
|
483
|
+
problems.append(f"the test customer {name}'s cleanup failed: {e}")
|
|
484
|
+
_rmtree(self.work)
|
|
485
|
+
return problems
|
|
486
|
+
|
|
487
|
+
def _check(self) -> list[str]:
|
|
488
|
+
problems = list(dict.fromkeys(self.errors)) if not self.failed else []
|
|
489
|
+
children = self.children()
|
|
490
|
+
missed = sum(max(0, c.get("sent", 0) - c.get("answered", 0)) for c in children)
|
|
491
|
+
if missed and not self.failed:
|
|
492
|
+
problems.append(f"{missed} call{'s' * (missed != 1)} a program made had no recording in "
|
|
493
|
+
f"{self.scenario.id}: record it (`pubtest record \"{self.scenario.id}\"`)")
|
|
494
|
+
if self.borrowed is not None or self.failed or not self.path.is_file():
|
|
495
|
+
return problems
|
|
496
|
+
cassette = self.cassette or self.t.Cassette(self.path, mode="replay")
|
|
497
|
+
used = {i for i, call in enumerate(cassette.calls) if call.used}
|
|
498
|
+
# A program names the cassette it replayed as begin() gave it, in
|
|
499
|
+
# INTEGRATIONS_CASSETTE: compared as text, a path read from its report
|
|
500
|
+
# is never looked up on disk.
|
|
501
|
+
mine = str(self.path)
|
|
502
|
+
for child in children:
|
|
503
|
+
if child.get("cassette") == mine:
|
|
504
|
+
used.update(child.get("used", []))
|
|
505
|
+
left = [i for i in range(len(cassette.calls)) if i not in used]
|
|
506
|
+
if left:
|
|
507
|
+
lines = [f"{len(left)} recorded call{'s' * (len(left) != 1)} in {self.scenario.id} never made:"]
|
|
508
|
+
for i in left:
|
|
509
|
+
call = cassette.calls[i]
|
|
510
|
+
lines.append(f" {call.plugin or '*'} {call.operation or '*'} {call.request['method'].upper()} "
|
|
511
|
+
f"{call.request['url']}")
|
|
512
|
+
lines.append(f'record it: pubtest record "{self.scenario.id}"')
|
|
513
|
+
problems.append("\n".join(lines))
|
|
514
|
+
return problems
|
|
515
|
+
|
|
516
|
+
def _stamp(self, current: dict) -> dict:
|
|
517
|
+
recorded = current.setdefault("recorded", {})
|
|
518
|
+
recorded["integrations"] = integrations_version()
|
|
519
|
+
recorded["consumer"] = recorded.get("consumer") or consumer(self.settings.root)
|
|
520
|
+
recorded["pubtest"] = {"scenario": self.text, "steps": self.steps_hash, "names": self.names}
|
|
521
|
+
return current
|
|
522
|
+
|
|
523
|
+
def _save(self) -> list[str]:
|
|
524
|
+
own = self.recorder.calls if self.recorder is not None else []
|
|
525
|
+
child_file = self.work / "child.json"
|
|
526
|
+
child = json.loads(child_file.read_text(encoding="utf-8")) if child_file.is_file() else None
|
|
527
|
+
if own and child:
|
|
528
|
+
return [f"{self.scenario.id} made calls itself and through a program it ran: a cassette holds one "
|
|
529
|
+
"process's calls, so record them in separate scenarios"]
|
|
530
|
+
try:
|
|
531
|
+
current = self.recorder.recording() if own else (child or {}).get("current")
|
|
532
|
+
except self.t.SecretInRecording as e:
|
|
533
|
+
return [str(e)]
|
|
534
|
+
if not current or not current.get("calls"):
|
|
535
|
+
if self.path.is_file():
|
|
536
|
+
self.path.unlink() # it makes no calls now: its old cassette goes
|
|
537
|
+
return []
|
|
538
|
+
old: dict = {}
|
|
539
|
+
if self.path.is_file():
|
|
540
|
+
old = json.loads(self.path.read_text(encoding="utf-8"))
|
|
541
|
+
baseline = None
|
|
542
|
+
if old.get("format") == self.t.FORMAT:
|
|
543
|
+
baseline = old.get("baseline") if old.get("baseline") is not None else old.get("current")
|
|
544
|
+
self.t.write_cassette(self.path, {"format": self.t.FORMAT, "scenario": self.scenario.id,
|
|
545
|
+
"current": self._stamp(current), "baseline": baseline},
|
|
546
|
+
self.settings.cassettes)
|
|
547
|
+
return []
|
|
548
|
+
|
|
549
|
+
def _plan(self, problems: list[str]) -> None:
|
|
550
|
+
"""Whether this scenario's cassette needs recording again, for
|
|
551
|
+
`pubtest record --changed`."""
|
|
552
|
+
reason = None
|
|
553
|
+
if self.borrowed is None:
|
|
554
|
+
if any(e.startswith("no cassette for") for e in self.errors):
|
|
555
|
+
reason = "it has no cassette"
|
|
556
|
+
elif problems:
|
|
557
|
+
reason = "it no longer fits its cassette"
|
|
558
|
+
elif self.path.is_file():
|
|
559
|
+
data = json.loads(self.path.read_text(encoding="utf-8"))
|
|
560
|
+
recorded = (data.get("current") or {}).get("recorded") or {}
|
|
561
|
+
stamp = recorded.get("pubtest") or {}
|
|
562
|
+
if stamp.get("scenario") != self.text:
|
|
563
|
+
reason = "its text changed"
|
|
564
|
+
elif stamp.get("steps") != self.steps_hash:
|
|
565
|
+
reason = "its steps' code changed"
|
|
566
|
+
elif recorded.get("integrations") != integrations_version():
|
|
567
|
+
reason = f"integrations is {integrations_version()}, not {recorded.get('integrations')}"
|
|
568
|
+
with open(os.environ[PLAN], "a", encoding="utf-8") as out:
|
|
569
|
+
out.write(json.dumps({"scenario": self.scenario.id, "changed": reason}) + "\n")
|
|
570
|
+
|
|
571
|
+
|
|
572
|
+
def _prefixed(t: Any) -> type:
|
|
573
|
+
class Prefixed(t.Fault):
|
|
574
|
+
"""A Fault on NAME's calls: a plugin, or every plugin under a prefix."""
|
|
575
|
+
|
|
576
|
+
def __init__(self, rule: dict, name: str) -> None:
|
|
577
|
+
super().__init__(rule)
|
|
578
|
+
self.name = name
|
|
579
|
+
|
|
580
|
+
def matches(self, request: Any) -> bool:
|
|
581
|
+
return matches_name(self.name, request.plugin) and super().matches(request)
|
|
582
|
+
return Prefixed
|
|
583
|
+
|
|
584
|
+
|
|
585
|
+
def _rmtree(path: Path) -> None:
|
|
586
|
+
import shutil # noqa: PLC0415
|
|
587
|
+
shutil.rmtree(path, ignore_errors=True)
|