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/cli.py ADDED
@@ -0,0 +1,253 @@
1
+ """`pubtest record`: record the cassettes of a suite's scenarios (GRAMMAR.md,
2
+ "Record and replay").
3
+
4
+ pubtest record --all every scenario
5
+ pubtest record --changed the scenarios whose cassette is out of date
6
+ pubtest record "FILE: TITLE" ... these scenarios
7
+ pubtest record --rename OLD NEW move a scenario's cassette to its new name
8
+
9
+ It runs the repository's suite with PUBTEST_RECORD=1: pytest-bdd for a Python
10
+ repository, cucumber-js for a Node one (pubrules.json's ci.language, else this
11
+ program's own). The same command is in the npm package.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import argparse
17
+ import json
18
+ import os
19
+ import subprocess
20
+ import sys
21
+ import tempfile
22
+ from pathlib import Path
23
+
24
+ from . import cassettes
25
+ from .core import repository
26
+
27
+ # What a harness sets for the programs it runs, which a suite run from inside
28
+ # one (pubtest's own) must not inherit.
29
+ HARNESS = (cassettes.RUN, cassettes.MODE, cassettes.CASSETTE, cassettes.CASSETTES, cassettes.REPORT,
30
+ cassettes.ONLY, cassettes.PLAN, cassettes.RECORD)
31
+
32
+ README = """# {name}
33
+
34
+ The recorded answers {repo}'s tests replay: one cassette per scenario under
35
+ `integrations/cassettes/`, in integrations' `integrations.cassette/1` format,
36
+ written by `pubtest record` in {repo}. Private: a recording holds no secret,
37
+ but it does hold what the services answered.
38
+ """
39
+
40
+
41
+ def _fail(message: str, code: int = 2) -> int:
42
+ print(f"pubtest record: {message}", file=sys.stderr)
43
+ return code
44
+
45
+
46
+ def _env() -> dict[str, str]:
47
+ env = dict(os.environ)
48
+ if env.get(cassettes.RUN):
49
+ for key in HARNESS:
50
+ env.pop(key, None)
51
+ env[cassettes.SWITCH] = "1"
52
+ return env
53
+
54
+
55
+ def _language(root: Path, own: str) -> str:
56
+ try:
57
+ language = json.loads((root / "pubrules.json").read_text(encoding="utf-8")).get("ci", {}).get("language")
58
+ except (OSError, ValueError, AttributeError):
59
+ language = None
60
+ if language in ("node", "javascript", "typescript", "js"):
61
+ return "node"
62
+ if language == "python":
63
+ return "python"
64
+ return own
65
+
66
+
67
+ def runner(root: Path, language: str) -> tuple[list[str], Path]:
68
+ """The suite's command, and where it runs."""
69
+ if language == "python":
70
+ here = root / "tests" if (root / "tests" / "pytest.ini").is_file() else root
71
+ python = sys.executable if Path(sys.executable).exists() else "python3"
72
+ return [python, "-m", "pytest", "-q", "-p", "no:cacheprovider"], here
73
+ cucumber = root / "node_modules" / "@cucumber" / "cucumber" / "bin" / "cucumber.js"
74
+ return (["node", str(cucumber)] if cucumber.is_file() else ["npx", "cucumber-js"]), root
75
+
76
+
77
+ def _owner(root: Path) -> str | None:
78
+ origin = cassettes._git(root, "remote", "get-url", "origin")
79
+ if not origin:
80
+ return None
81
+ path = origin.removesuffix(".git").replace(":", "/").split("/")
82
+ return path[-2] if len(path) >= 2 else None
83
+
84
+
85
+ def data_repo(found: cassettes.Settings, create: bool) -> int:
86
+ """Make sure the cassettes directory is there: a directory of the repository's
87
+ own is made; a missing data repository is created with gh only when asked."""
88
+ if found.cassettes.is_dir():
89
+ return 0
90
+ if found.data_repo is None or found.data_repo.is_dir():
91
+ found.cassettes.mkdir(parents=True, exist_ok=True)
92
+ return 0
93
+ owner = _owner(found.root) or "OWNER"
94
+ name = found.data_repo.name
95
+ command = ["gh", "repo", "create", f"{owner}/{name}", "--private", "--clone",
96
+ "--description", f"The recorded answers {found.root.name}'s tests replay"]
97
+ if not create:
98
+ print(f"{cassettes.NO_DATA_REPO.split(':')[0]} at {found.data_repo}. Create it, private and beside "
99
+ f"this repository, with:\n\n (cd {found.root.parent} && {' '.join(_quoted(command))})\n\n"
100
+ "or run pubtest record again with --create-data-repo, which runs that and commits its README, "
101
+ "pubrules.json and integrations.json.", file=sys.stderr)
102
+ return 1
103
+ done = subprocess.run(command, cwd=found.root.parent, check=False)
104
+ if done.returncode != 0 or not found.data_repo.is_dir():
105
+ return _fail("gh repo create failed", done.returncode or 1)
106
+ repo = found.data_repo
107
+ (repo / "README.md").write_text(README.format(name=name, repo=found.root.name), encoding="utf-8")
108
+ (repo / "pubrules.json").write_text(json.dumps({"kind": "content"}, indent=2) + "\n", encoding="utf-8")
109
+ (repo / "integrations.json").write_text(json.dumps(
110
+ {"uses": [], "exclude": [{"path": "**", "reason": "Recorded answers, not code"}]}, indent=2) + "\n",
111
+ encoding="utf-8")
112
+ found.cassettes.mkdir(parents=True, exist_ok=True)
113
+ (found.cassettes / ".gitkeep").write_text("", encoding="utf-8")
114
+ for args in (["add", "-A"], ["commit", "-q", "-m", "Start the data repository"], ["push", "-q", "-u", "origin",
115
+ "HEAD"]):
116
+ if subprocess.run(["git", *args], cwd=repo, check=False).returncode != 0:
117
+ return _fail(f"git {' '.join(args)} failed in {repo}", 1)
118
+ return 0
119
+
120
+
121
+ def _quoted(words: list[str]) -> list[str]:
122
+ import shlex # noqa: PLC0415
123
+ return [shlex.quote(w) for w in words]
124
+
125
+
126
+ def _find(found: cassettes.Settings, selector: str) -> cassettes.Scenario:
127
+ """The scenario `selector` names among the recorded ones, when it names no
128
+ feature file itself."""
129
+ try:
130
+ return cassettes.parse(selector)
131
+ except ValueError:
132
+ pass
133
+ hits = []
134
+ for path in sorted(found.cassettes.rglob("*.json")):
135
+ try:
136
+ recorded = json.loads(path.read_text(encoding="utf-8")).get("scenario", "")
137
+ scenario = cassettes.parse(recorded)
138
+ except (OSError, ValueError, AttributeError):
139
+ continue
140
+ if scenario.named_by(selector):
141
+ hits.append(scenario)
142
+ if len(hits) != 1:
143
+ raise LookupError(f'"{selector}" names {len(hits)} recorded scenarios: write it "FILE.feature: TITLE"')
144
+ return hits[0]
145
+
146
+
147
+ def rename(found: cassettes.Settings, old: str, new: str) -> int:
148
+ try:
149
+ before = _find(found, old)
150
+ after = cassettes.parse(new, before.feature)
151
+ except (LookupError, ValueError) as e:
152
+ return _fail(str(e))
153
+ source, target = cassettes.path_for(before, found), cassettes.path_for(after, found)
154
+ if not source.is_file():
155
+ return _fail(f"{before.id} has no cassette: there is no {source}")
156
+ if target.exists():
157
+ return _fail(f"{after.id} has a cassette already: {target}")
158
+ root = found.cassettes.resolve()
159
+ if not target.resolve().is_relative_to(root):
160
+ return _fail(f"{target} is outside the cassettes directory {root}")
161
+ data = json.loads(source.read_text(encoding="utf-8"))
162
+ data["scenario"] = after.id
163
+ target.parent.mkdir(parents=True, exist_ok=True)
164
+ target.write_text(json.dumps(data, indent=1, ensure_ascii=False) + "\n", encoding="utf-8")
165
+ source.unlink()
166
+ for directory in (source.parent, source.parent.parent):
167
+ if directory != root and directory.is_dir() and not any(directory.iterdir()):
168
+ directory.rmdir()
169
+ print(f"{source.relative_to(root)} -> {target.relative_to(root)}")
170
+ return 0
171
+
172
+
173
+ def changed(command: list[str], where: Path) -> list[str] | None:
174
+ """The scenarios whose cassette is out of date: the suite runs in replay and
175
+ each scenario says whether it no longer fits its cassette, has none though it
176
+ makes calls, or its text, step code or integrations differ from its recording."""
177
+ with tempfile.TemporaryDirectory(prefix="pubtest-plan-") as work:
178
+ plan = Path(work) / "plan.jsonl"
179
+ env = _env()
180
+ env[cassettes.PLAN] = str(plan)
181
+ subprocess.run(command, cwd=where, env=env, check=False, stdout=subprocess.DEVNULL)
182
+ if not plan.is_file():
183
+ return None
184
+ entries = [json.loads(line) for line in plan.read_text(encoding="utf-8").splitlines() if line.strip()]
185
+ found = {}
186
+ for entry in entries:
187
+ if entry.get("changed"):
188
+ found[entry["scenario"]] = entry["changed"]
189
+ for scenario, reason in found.items():
190
+ print(f"{scenario}: {reason}", flush=True)
191
+ return list(found)
192
+
193
+
194
+ def record(argv: list[str] | None = None, own: str = "python") -> int:
195
+ parser = argparse.ArgumentParser(prog="pubtest record", description="Record the cassettes of a suite's scenarios.")
196
+ which = parser.add_mutually_exclusive_group()
197
+ which.add_argument("--all", action="store_true", help="every scenario")
198
+ which.add_argument("--changed", action="store_true", help="the scenarios whose cassette is out of date")
199
+ parser.add_argument("--rename", nargs=2, metavar=("OLD", "NEW"), help="move OLD's cassette to NEW")
200
+ parser.add_argument("--create-data-repo", action="store_true", help="create the data repository with gh")
201
+ parser.add_argument("scenarios", nargs="*", metavar="SCENARIO", help='"FILE.feature: TITLE[ #ROW]"')
202
+ args = parser.parse_args(argv)
203
+ root = repository()
204
+ found = cassettes.settings(root, _env())
205
+ if args.rename:
206
+ if args.all or args.changed or args.scenarios:
207
+ return _fail("--rename moves one cassette, and records nothing")
208
+ return rename(found, *args.rename)
209
+ if not (args.all or args.changed or args.scenarios):
210
+ return _fail("say which: --all, --changed, or the scenarios")
211
+ if args.all and args.scenarios or args.changed and args.scenarios:
212
+ return _fail("--all and --changed take no scenarios")
213
+ made = data_repo(found, args.create_data_repo)
214
+ if made:
215
+ return made
216
+ command, where = runner(root, _language(root, own))
217
+ chosen: list[str] | None = None if args.all else list(args.scenarios)
218
+ if args.changed:
219
+ chosen = changed(command, where)
220
+ if chosen is None:
221
+ return _fail("the suite said nothing about its scenarios: is pubtest's harness on in it?", 1)
222
+ if not chosen:
223
+ print("no scenario's cassette is out of date", flush=True)
224
+ return 0
225
+ env = _env()
226
+ env[cassettes.RECORD] = "1"
227
+ if chosen is not None:
228
+ env[cassettes.ONLY] = json.dumps(chosen)
229
+ before = _stamps(found.cassettes)
230
+ done = subprocess.run(command, cwd=where, env=env, check=False)
231
+ after = _stamps(found.cassettes)
232
+ for path in sorted(p for p, stamp in after.items() if before.get(p) != stamp):
233
+ print(f"recorded {path.relative_to(found.cassettes)}")
234
+ return done.returncode
235
+
236
+
237
+ def _stamps(directory: Path) -> dict[Path, tuple[int, int]]:
238
+ """Each cassette's modification time and size: what a recording changed."""
239
+ return {p: (p.stat().st_mtime_ns, p.stat().st_size) for p in directory.rglob("*.json")}
240
+
241
+
242
+ def main(argv: list[str] | None = None) -> int:
243
+ argv = sys.argv[1:] if argv is None else argv
244
+ if not argv or argv[0] in ("-h", "--help"):
245
+ print(__doc__.strip())
246
+ return 0 if argv else 2
247
+ if argv[0] != "record":
248
+ return _fail(f"no command {argv[0]!r}: pubtest record", 2)
249
+ return record(argv[1:])
250
+
251
+
252
+ if __name__ == "__main__":
253
+ raise SystemExit(main())
pubtest/core.py ADDED
@@ -0,0 +1,274 @@
1
+ """What every step shares: a scenario's context, a program's run, and how a
2
+ step's quoted value is compared."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import json
7
+ import os
8
+ import re
9
+ import sys
10
+ from collections.abc import Callable
11
+ from dataclasses import dataclass, field
12
+ from pathlib import Path
13
+ from types import SimpleNamespace
14
+ from typing import Any
15
+
16
+ __all__ = ["Completed", "Context", "Refused", "Result", "bin_var", "dig", "matches", "repository", "same", "value"]
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class Completed:
21
+ """The observable result of running a program."""
22
+
23
+ argv: list[str]
24
+ code: int
25
+ out: bytes
26
+ err: bytes
27
+
28
+ @property
29
+ def stdout(self) -> str:
30
+ return self.out.decode("utf-8", "replace")
31
+
32
+ @property
33
+ def stderr(self) -> str:
34
+ return self.err.decode("utf-8", "replace")
35
+
36
+ @property
37
+ def lines(self) -> list[str]:
38
+ return self.stdout.splitlines()
39
+
40
+ def describe(self) -> str:
41
+ return (f"$ {' '.join(self.argv)}\nexit {self.code}\n"
42
+ f"stdout: {self.stdout!r}\nstderr: {self.stderr!r}")
43
+
44
+
45
+ @dataclass
46
+ class Refused:
47
+ """What an attempted action raised."""
48
+
49
+ error: BaseException
50
+
51
+ @property
52
+ def message(self) -> str:
53
+ if isinstance(self.error, SystemExit):
54
+ code = self.error.code
55
+ return "" if code is None or isinstance(code, int) else str(code)
56
+ return str(self.error)
57
+
58
+
59
+ @dataclass
60
+ class Result:
61
+ """What a scenario's action came to, whichever kind of When it was: the
62
+ value it returned or the refusal it raised, and its exit code and what it
63
+ printed. `I run` fills the code and output; `attempt` fills the value or
64
+ the refusal, and the output too, with code 0 for a return, 1 for a raise
65
+ and the SystemExit code for an exit."""
66
+
67
+ value: Any = None
68
+ refused: Refused | None = None
69
+ code: int = 0
70
+ stdout: str = ""
71
+ stderr: str = ""
72
+ argv: list[str] = field(default_factory=list)
73
+
74
+ @property
75
+ def returncode(self) -> int:
76
+ return self.code
77
+
78
+ def describe(self) -> str:
79
+ head = f"$ {' '.join(self.argv)}\n" if self.argv else ""
80
+ refused = f"refused: {self.refused.message!r}\n" if self.refused else ""
81
+ return f"{head}exit {self.code}\n{refused}stdout: {self.stdout!r}\nstderr: {self.stderr!r}"
82
+
83
+
84
+ @dataclass
85
+ class Context(SimpleNamespace):
86
+ """A scenario's state: what its action came to, the scratch directory,
87
+ the secrets, and the cleanups that run when it ends, in reverse, passed
88
+ or failed."""
89
+
90
+ outcome: Result | None = None
91
+ refusal_read: bool = False
92
+ directory: Path | None = None
93
+ secrets: list[str] = field(default_factory=list)
94
+ written: dict[str, bytes] | None = None
95
+ # The record/replay harness's tape for the scenario (pubtest.cassettes), when it is on.
96
+ tape: Any = None
97
+ _cleanups: list[Callable[[], Any]] = field(default_factory=list)
98
+
99
+ @property
100
+ def result(self) -> Any:
101
+ return self.outcome.value if self.outcome else None
102
+
103
+ @property
104
+ def refused(self) -> Refused | None:
105
+ return self.outcome.refused if self.outcome else None
106
+
107
+ def cleanup(self, fn: Callable[[], Any]) -> Callable[[], Any]:
108
+ """Run `fn` when the scenario ends; usable as a decorator."""
109
+ self._cleanups.append(fn)
110
+ return fn
111
+
112
+ def acting(self) -> None:
113
+ """Before an action: the scratch directory as it was before the first one."""
114
+ if self.directory is not None and self.written is None:
115
+ self.written = files_in(self.directory)
116
+
117
+ def attempt(self, action: Callable[[], Any]) -> Any:
118
+ """Do the scenario's action: keep what it returns, or what it raises,
119
+ and what it printed. An awaitable it returns is awaited."""
120
+ import asyncio # noqa: PLC0415
121
+ import contextlib # noqa: PLC0415
122
+ import inspect # noqa: PLC0415
123
+ import io # noqa: PLC0415
124
+ self.acting()
125
+ out, err = io.StringIO(), io.StringIO()
126
+ outcome = Result()
127
+ try:
128
+ with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
129
+ returned = action()
130
+ if inspect.isawaitable(returned):
131
+ returned = asyncio.run(_awaited(returned))
132
+ outcome.value = returned
133
+ except SystemExit as exit_:
134
+ outcome.refused = Refused(exit_)
135
+ outcome.code = exit_.code if isinstance(exit_.code, int) else (0 if exit_.code is None else 1)
136
+ if outcome.code == 0:
137
+ outcome.refused = None
138
+ except Exception as error: # noqa: BLE001 - the refusal is the point
139
+ outcome.refused, outcome.code = Refused(error), 1
140
+ outcome.stdout, outcome.stderr = out.getvalue(), err.getvalue()
141
+ self.outcome, self.refusal_read = outcome, False
142
+ return outcome.value
143
+
144
+ def ran(self, outcome: "Result") -> "Result":
145
+ """Keep a program's run as what the action came to."""
146
+ self.outcome, self.refusal_read = outcome, False
147
+ return outcome
148
+
149
+ def unread_refusal(self) -> BaseException | None:
150
+ """A refusal no Then read: the scenario fails with it."""
151
+ if self.refused is not None and not self.refusal_read:
152
+ return self.refused.error
153
+ return None
154
+
155
+ def close(self) -> None:
156
+ errors: list[BaseException] = []
157
+ while self._cleanups:
158
+ fn = self._cleanups.pop()
159
+ try:
160
+ fn()
161
+ except Exception as e: # noqa: BLE001 - every cleanup must run
162
+ errors.append(e)
163
+ if errors:
164
+ raise errors[0]
165
+
166
+
167
+ async def _awaited(awaitable):
168
+ return await awaitable
169
+
170
+
171
+ def files_in(root: Path) -> dict[str, bytes]:
172
+ return {p.relative_to(root).as_posix(): p.read_bytes() for p in sorted(root.rglob("*")) if p.is_file()}
173
+
174
+
175
+ def bin_var(name: str) -> str:
176
+ """The variable naming the directory that holds `name`: pub -> PUB_BIN_DIR."""
177
+ return re.sub(r"[^A-Za-z0-9]", "_", name).upper() + "_BIN_DIR"
178
+
179
+
180
+ def program(name: str, var: str | None = None) -> Path:
181
+ """The program under test `name`, from `<NAME>_BIN_DIR`, never from PATH."""
182
+ var = var or bin_var(name)
183
+ raw = os.environ.get(var)
184
+ if not raw:
185
+ raise LookupError(f"{var} is not set: it must name the directory holding {name}")
186
+ path = Path(raw) / (name + (".exe" if sys.platform == "win32" else ""))
187
+ if not path.exists():
188
+ raise LookupError(f"{var}={raw} has no {name}")
189
+ return path
190
+
191
+
192
+ def value(text: str) -> Any:
193
+ """A step's quoted value: JSON when it reads as JSON, text otherwise."""
194
+ try:
195
+ return json.loads(text)
196
+ except ValueError:
197
+ return text
198
+
199
+
200
+ def same(actual: Any, wanted: str) -> bool:
201
+ """Whether `actual` is the step's value V. When the result is text, V is
202
+ compared as text. Otherwise V is read as JSON and compared as a value; a
203
+ V that does not read as JSON is compared with the result's text."""
204
+ if isinstance(actual, (bytes, bytearray)):
205
+ actual = actual.decode("utf-8", "replace")
206
+ if isinstance(actual, str):
207
+ return actual == wanted
208
+ try:
209
+ want = json.loads(wanted)
210
+ except ValueError:
211
+ return str(actual) == wanted
212
+ if isinstance(actual, bool) != isinstance(want, bool):
213
+ return False # true is not 1, and 0 is not false
214
+ return actual == want
215
+
216
+
217
+ def dig(data: Any, key: str) -> Any:
218
+ """The value at a dotted key: `a.b.0` is data["a"]["b"][0]."""
219
+ for part in key.split("."):
220
+ if isinstance(data, list):
221
+ data = data[int(part)]
222
+ elif isinstance(data, dict):
223
+ data = data[part]
224
+ else:
225
+ data = getattr(data, part)
226
+ return data
227
+
228
+
229
+ def includes(container: Any, item: str) -> bool:
230
+ """Text contains it, a list holds it, a map has it as a key; the item is
231
+ compared as text with text, and read as JSON otherwise."""
232
+ if isinstance(container, (bytes, bytearray)):
233
+ container = container.decode("utf-8", "replace")
234
+ if isinstance(container, str):
235
+ return item in container
236
+ want = value(item)
237
+ if isinstance(container, dict):
238
+ return want in container or item in container
239
+ return want in container or item in [str(x) for x in container]
240
+
241
+
242
+ def matches(pattern: str, text: str) -> bool:
243
+ """Whether all of `text` is `pattern`, in which only `*` is special: it
244
+ stands for anything, newlines too. The same in Python and in Node."""
245
+ return re.fullmatch(".*".join(map(re.escape, pattern.split("*"))), text, re.S) is not None
246
+
247
+
248
+ def repository(start: Path | None = None) -> Path:
249
+ """The repository the suite runs in: the nearest directory, from `start`
250
+ (the working directory) up, that holds pubrules.json, or else `start`."""
251
+ here = (start or Path.cwd()).resolve()
252
+ for directory in [here, *here.parents]:
253
+ if (directory / "pubrules.json").is_file():
254
+ return directory
255
+ return here
256
+
257
+
258
+ def yaml_documents(text: str) -> Any:
259
+ """A YAML text's document, or the list of its documents when it holds
260
+ more than one. PyYAML is the suite's to install: pubtest needs it only
261
+ for the YAML steps."""
262
+ try:
263
+ import yaml # noqa: PLC0415
264
+ except ImportError as e:
265
+ raise AssertionError("the YAML steps need PyYAML: add pyyaml to the suite's requirements") from e
266
+ documents = [d for d in yaml.safe_load_all(text) if d is not None]
267
+ return documents[0] if len(documents) == 1 else documents
268
+
269
+
270
+ def show(data: Any) -> str:
271
+ try:
272
+ return json.dumps(data, indent=2, default=str)
273
+ except TypeError:
274
+ return repr(data)
pubtest/http.py ADDED
@@ -0,0 +1,156 @@
1
+ """Adapters that let pubtest's HTTP steps send a suite's service a request.
2
+
3
+ A suite gives pubtest an `http_client` fixture: a callable taking a method,
4
+ a path, headers and a body, and answering an `Answer`. These make one from
5
+ the usual kinds of app:
6
+
7
+ @pytest.fixture
8
+ def http_client():
9
+ return pubtest.http.asgi(create_app())
10
+
11
+ or `pubtest.http.wsgi(app)`, or `pubtest.http.url(base)` for a server
12
+ already listening.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import asyncio
18
+ import io
19
+ from collections.abc import Callable, Mapping
20
+ from dataclasses import dataclass
21
+ from typing import Any
22
+ from urllib.parse import unquote, urlsplit
23
+
24
+ __all__ = ["Answer", "asgi", "url", "wsgi"]
25
+
26
+ Client = Callable[[str, str, Mapping[str, str], bytes | None], "Answer"]
27
+
28
+
29
+ @dataclass
30
+ class Answer:
31
+ """What a service answered."""
32
+
33
+ status: int
34
+ headers: dict[str, str]
35
+ body: bytes
36
+
37
+ @property
38
+ def text(self) -> str:
39
+ return self.body.decode("utf-8", "replace")
40
+
41
+ def json(self) -> Any:
42
+ """The body read as JSON, when a step asks for it."""
43
+ import json # noqa: PLC0415
44
+ return json.loads(self.body)
45
+
46
+ def header(self, name: str) -> str | None:
47
+ """A header, its name compared without case."""
48
+
49
+ return next((v for k, v in self.headers.items() if k.lower() == name.lower()), None)
50
+
51
+
52
+ def wsgi(app: Callable[..., Any]) -> Client:
53
+ """A WSGI app (Flask, Django, a plain callable)."""
54
+
55
+ def send(method: str, path: str, headers: Mapping[str, str], body: bytes | None) -> Answer:
56
+ url = urlsplit(path)
57
+ environ = {
58
+ "REQUEST_METHOD": method, "PATH_INFO": url.path, "QUERY_STRING": url.query,
59
+ "SERVER_NAME": "localhost", "SERVER_PORT": "80", "SERVER_PROTOCOL": "HTTP/1.1",
60
+ "wsgi.version": (1, 0), "wsgi.url_scheme": "http", "wsgi.input": io.BytesIO(body or b""),
61
+ "wsgi.errors": io.StringIO(), "wsgi.multithread": False, "wsgi.multiprocess": False,
62
+ "wsgi.run_once": True, "CONTENT_LENGTH": str(len(body or b"")),
63
+ }
64
+ for name, value in headers.items():
65
+ key = name.upper().replace("-", "_")
66
+ environ[key if key in ("CONTENT_TYPE", "CONTENT_LENGTH") else f"HTTP_{key}"] = value
67
+ started: dict[str, Any] = {}
68
+
69
+ def start_response(status, response_headers, exc_info=None):
70
+ started["status"], started["headers"] = status, response_headers
71
+
72
+ chunks = app(environ, start_response)
73
+ try:
74
+ data = b"".join(chunks)
75
+ finally:
76
+ getattr(chunks, "close", lambda: None)()
77
+ return Answer(int(started["status"].split()[0]), dict(started["headers"]), data)
78
+
79
+ return send
80
+
81
+
82
+ def asgi(app: Callable[..., Any]) -> Client:
83
+ """An ASGI app (Starlette, FastAPI), called directly, with no server.
84
+
85
+ As a server does, it gives the app the path percent-decoded (`raw_path`
86
+ the bytes as sent), a Content-Length for a body, and the body; then it
87
+ keeps the connection until the answer is complete, so an app listening
88
+ for the client to leave (a streamed answer) is not cut short. The client
89
+ leaves only once the answer is complete: an app that waits for
90
+ `http.disconnect` before it answers at all waits forever here."""
91
+
92
+ def send(method: str, path: str, headers: Mapping[str, str], body: bytes | None) -> Answer:
93
+ url = urlsplit(path)
94
+ sent = [(k.lower().encode(), v.encode()) for k, v in headers.items()]
95
+ if body is not None and not any(k == b"content-length" for k, _ in sent):
96
+ sent.append((b"content-length", str(len(body)).encode()))
97
+ scope = {
98
+ "type": "http", "asgi": {"version": "3.0"}, "http_version": "1.1", "method": method,
99
+ "scheme": "http", "path": unquote(url.path), "raw_path": url.path.encode(),
100
+ "query_string": url.query.encode(), "root_path": "", "server": ("localhost", 80),
101
+ "client": ("127.0.0.1", 50000), "headers": sent,
102
+ }
103
+ answer: dict[str, Any] = {"body": b""}
104
+
105
+ async def run() -> None:
106
+ messages = [{"type": "http.request", "body": body or b"", "more_body": False}]
107
+ complete = asyncio.Event()
108
+
109
+ async def receive():
110
+ if messages:
111
+ return messages.pop(0)
112
+ await complete.wait()
113
+ return {"type": "http.disconnect"}
114
+
115
+ async def respond(message):
116
+ if message["type"] == "http.response.start":
117
+ answer["status"] = message["status"]
118
+ answer["headers"] = {k.decode(): v.decode()
119
+ for k, v in message.get("headers", [])}
120
+ elif message["type"] == "http.response.body":
121
+ answer["body"] += message.get("body", b"")
122
+ if not message.get("more_body", False):
123
+ complete.set()
124
+
125
+ try:
126
+ await app(scope, receive, respond)
127
+ finally:
128
+ complete.set()
129
+
130
+ asyncio.run(run())
131
+ return Answer(answer["status"], answer.get("headers", {}), answer["body"])
132
+
133
+ return send
134
+
135
+
136
+ def url(base: str) -> Client:
137
+ """A server already listening at `base` (`http://127.0.0.1:8000`), its
138
+ path prefix kept. It does not follow redirects."""
139
+ import http.client # noqa: PLC0415
140
+
141
+ root = urlsplit(base)
142
+ if root.scheme not in ("http", "https") or not root.netloc:
143
+ raise ValueError(f"{base!r} is not an http or https address")
144
+ connection = http.client.HTTPSConnection if root.scheme == "https" else http.client.HTTPConnection
145
+
146
+ def send(method: str, path: str, headers: Mapping[str, str], body: bytes | None) -> Answer:
147
+ target = root.path.rstrip("/") + (path if path.startswith("/") else "/" + path)
148
+ conn = connection(root.netloc, timeout=120)
149
+ try:
150
+ conn.request(method, target, body=body, headers=dict(headers))
151
+ response = conn.getresponse()
152
+ return Answer(response.status, dict(response.getheaders()), response.read())
153
+ finally:
154
+ conn.close()
155
+
156
+ return send