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/steps/result.py
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
"""The result: what a scenario's action returned, or the refusal it raised."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
import pytest
|
|
8
|
+
from pytest_bdd import then
|
|
9
|
+
|
|
10
|
+
from ..core import dig, includes, matches, same, show
|
|
11
|
+
from . import phrase
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class Current:
|
|
15
|
+
"""The `result` fixture: whatever the context's action came to at the
|
|
16
|
+
moment it is read, so a second When is what later steps see. Its
|
|
17
|
+
attributes are the current Result's."""
|
|
18
|
+
|
|
19
|
+
def __init__(self, pubtest_ctx) -> None:
|
|
20
|
+
self._ctx = pubtest_ctx
|
|
21
|
+
|
|
22
|
+
def __getattr__(self, name: str) -> Any:
|
|
23
|
+
return getattr(self._ctx.outcome, name)
|
|
24
|
+
|
|
25
|
+
def __repr__(self) -> str:
|
|
26
|
+
return f"Current({self._ctx.outcome!r})"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@pytest.fixture
|
|
30
|
+
def result(pubtest_ctx) -> Any:
|
|
31
|
+
"""What the action came to: the context's current Result, read when a
|
|
32
|
+
step reads it. A suite's step that sets target_fixture="result" takes
|
|
33
|
+
its place with a value of its own."""
|
|
34
|
+
return Current(pubtest_ctx)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def outcome(pubtest_ctx, result: Any) -> Any:
|
|
38
|
+
"""What a step that reads the run checks: the context's outcome now,
|
|
39
|
+
unless a suite's own step put something else in the `result` fixture."""
|
|
40
|
+
if isinstance(result, Current):
|
|
41
|
+
assert pubtest_ctx.outcome is not None, "no action was taken: a When leaves the result"
|
|
42
|
+
return pubtest_ctx.outcome
|
|
43
|
+
return result
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _returned(pubtest_ctx) -> Any:
|
|
47
|
+
assert pubtest_ctx.outcome is not None, "no action was taken: a When leaves the result"
|
|
48
|
+
if pubtest_ctx.refused is not None:
|
|
49
|
+
pubtest_ctx.refusal_read = True
|
|
50
|
+
raise AssertionError(f"it was refused: {pubtest_ctx.refused.message!r}") from pubtest_ctx.refused.error
|
|
51
|
+
return pubtest_ctx.result
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@then(phrase('the result is "{wanted}"'))
|
|
55
|
+
def result_is(pubtest_ctx, wanted):
|
|
56
|
+
got = _returned(pubtest_ctx)
|
|
57
|
+
assert same(got, wanted), f"the result is {show(got)}, not {wanted}"
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@then(phrase('the result is not "{wanted}"'))
|
|
61
|
+
def result_is_not(pubtest_ctx, wanted):
|
|
62
|
+
got = _returned(pubtest_ctx)
|
|
63
|
+
assert not same(got, wanted), f"the result is {wanted}"
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@then("the result is:")
|
|
67
|
+
def result_is_docstring(pubtest_ctx, docstring=None, datatable=None):
|
|
68
|
+
"""A docstring is the JSON (or text) the result is; a table is a list of
|
|
69
|
+
maps, its header row the keys, each cell compared as a step's value."""
|
|
70
|
+
got = _returned(pubtest_ctx)
|
|
71
|
+
if datatable is not None:
|
|
72
|
+
keys, rows = datatable[0], datatable[1:]
|
|
73
|
+
assert isinstance(got, list) and len(got) == len(rows), f"the result is {show(got)}"
|
|
74
|
+
for item, row in zip(got, rows, strict=True):
|
|
75
|
+
for key, cell in zip(keys, row, strict=True):
|
|
76
|
+
assert same(dig(item, key), cell), f"the result is {show(got)}; {key} is not {cell}"
|
|
77
|
+
return
|
|
78
|
+
assert same(got, docstring), f"the result is {show(got)}, not:\n{docstring}"
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
@then(phrase('the result includes "{item}"'))
|
|
82
|
+
def result_includes(pubtest_ctx, item):
|
|
83
|
+
got = _returned(pubtest_ctx)
|
|
84
|
+
assert includes(got, item), f"the result {show(got)} does not include {item}"
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
@then(phrase('the result does not include "{item}"'))
|
|
88
|
+
def result_excludes(pubtest_ctx, item):
|
|
89
|
+
got = _returned(pubtest_ctx)
|
|
90
|
+
assert not includes(got, item), f"the result {show(got)} includes {item}"
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _at(data: Any, key: str, what: str) -> Any:
|
|
94
|
+
try:
|
|
95
|
+
return dig(data, key)
|
|
96
|
+
except (LookupError, AttributeError, TypeError, ValueError) as e:
|
|
97
|
+
raise AssertionError(f"{what} has no {key}: {show(data)}") from e
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
@then(phrase('the result\'s "{key}" is "{wanted}"'))
|
|
101
|
+
def result_key_is(pubtest_ctx, key, wanted):
|
|
102
|
+
got = _at(_returned(pubtest_ctx), key, "the result")
|
|
103
|
+
assert same(got, wanted), f"the result's {key} is {show(got)}, not {wanted}"
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
@then(phrase('the result\'s "{key}" includes "{item}"'))
|
|
107
|
+
def result_key_includes(pubtest_ctx, key, item):
|
|
108
|
+
got = _at(_returned(pubtest_ctx), key, "the result")
|
|
109
|
+
assert includes(got, item), f"the result's {key} {show(got)} does not include {item}"
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
@then(phrase('the result\'s "{key}" matches "{pattern}"'))
|
|
113
|
+
def result_key_matches(pubtest_ctx, key, pattern):
|
|
114
|
+
got = _at(_returned(pubtest_ctx), key, "the result")
|
|
115
|
+
assert isinstance(got, str), f"the result's {key} is {show(got)}, not text"
|
|
116
|
+
assert matches(pattern, got), f"the result's {key} {got!r} does not match {pattern!r}"
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
@then(phrase("the result has {count:d} {noun}"))
|
|
120
|
+
def result_has(pubtest_ctx, count, noun):
|
|
121
|
+
got = _returned(pubtest_ctx)
|
|
122
|
+
assert len(got) == count, f"the result has {len(got)} {noun}, not {count}: {show(got)}"
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
@then("the result is empty")
|
|
126
|
+
def result_empty(pubtest_ctx):
|
|
127
|
+
got = _returned(pubtest_ctx)
|
|
128
|
+
assert got is None or got in ("", [], {}, ()), f"the result is {show(got)}"
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
@then(phrase('it is refused, saying "{text}"'))
|
|
132
|
+
def refused_saying(pubtest_ctx, text):
|
|
133
|
+
said = _refusal(pubtest_ctx).message or pubtest_ctx.outcome.stderr
|
|
134
|
+
assert text in said, f"it was refused, saying {said!r}"
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
@then("it is refused")
|
|
138
|
+
def refused(pubtest_ctx):
|
|
139
|
+
_refusal(pubtest_ctx)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
@then("it is not refused")
|
|
143
|
+
def not_refused(pubtest_ctx):
|
|
144
|
+
pubtest_ctx.refusal_read = True
|
|
145
|
+
assert pubtest_ctx.refused is None, f"it was refused, saying {pubtest_ctx.refused.message!r}"
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
@then(phrase('the result matches "{pattern}"'))
|
|
149
|
+
def result_matches(pubtest_ctx, pattern):
|
|
150
|
+
"""The result is text, and all of it is the pattern (`*` for anything)."""
|
|
151
|
+
got = _returned(pubtest_ctx)
|
|
152
|
+
assert isinstance(got, str), f"the result is {show(got)}, not text"
|
|
153
|
+
assert matches(pattern, got), f"the result {got!r} does not match {pattern!r}"
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _refusal(pubtest_ctx):
|
|
157
|
+
pubtest_ctx.refusal_read = True
|
|
158
|
+
assert pubtest_ctx.refused is not None, f"it was not refused: the result is {show(pubtest_ctx.result)}"
|
|
159
|
+
return pubtest_ctx.refused
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
@then(phrase('the refusal is a "{name}"'))
|
|
163
|
+
def refusal_is_a(pubtest_ctx, name):
|
|
164
|
+
"""The refusal's class, or a class it derives from, is NAME: its own
|
|
165
|
+
name, or its module's and its own (`builtins.KeyError`)."""
|
|
166
|
+
error = _refusal(pubtest_ctx).error
|
|
167
|
+
classes = type(error).__mro__
|
|
168
|
+
names = {c.__name__ for c in classes} | {f"{c.__module__}.{c.__qualname__}" for c in classes}
|
|
169
|
+
assert name in names, f"the refusal is a {' < '.join(c.__qualname__ for c in classes)}, not a {name}"
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
@then(phrase('the refusal\'s "{key}" is "{wanted}"'))
|
|
173
|
+
def refusal_key_is(pubtest_ctx, key, wanted):
|
|
174
|
+
"""The value at the dotted key K of the refusal's attributes; `message`
|
|
175
|
+
is its message."""
|
|
176
|
+
refused = _refusal(pubtest_ctx)
|
|
177
|
+
got = refused.message if key == "message" else _at(refused.error, key, "the refusal")
|
|
178
|
+
assert same(got, wanted), f"the refusal's {key} is {show(got)}, not {wanted}"
|
pubtest/steps/secrets.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""Secrets: values that must never show in anything the action produced."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
|
|
7
|
+
from pytest_bdd import given, then
|
|
8
|
+
|
|
9
|
+
from ..core import files_in
|
|
10
|
+
from . import phrase
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@given(phrase('the secret "{text}"'))
|
|
14
|
+
def secret(pubtest_ctx, text):
|
|
15
|
+
pubtest_ctx.secrets.append(text)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def produced(pubtest_ctx) -> dict[str, str]:
|
|
19
|
+
"""Everything the action produced, by where it went."""
|
|
20
|
+
out: dict[str, str] = {}
|
|
21
|
+
outcome = pubtest_ctx.outcome
|
|
22
|
+
if outcome is not None:
|
|
23
|
+
out["stdout"], out["stderr"] = outcome.stdout, outcome.stderr
|
|
24
|
+
out["the result"] = json.dumps(outcome.value, default=str) if outcome.value is not None else ""
|
|
25
|
+
if outcome.refused is not None:
|
|
26
|
+
out["the refusal"] = outcome.refused.message + repr(outcome.refused.error)
|
|
27
|
+
answer = getattr(pubtest_ctx, "answer", None)
|
|
28
|
+
if answer is not None:
|
|
29
|
+
out["the answer"] = json.dumps(answer.headers) + answer.text
|
|
30
|
+
if pubtest_ctx.directory is not None:
|
|
31
|
+
before = pubtest_ctx.written or {}
|
|
32
|
+
for path, data in files_in(pubtest_ctx.directory).items():
|
|
33
|
+
if before.get(path) != data:
|
|
34
|
+
out[f"the file {path}"] = data.decode("utf-8", "replace")
|
|
35
|
+
standins = getattr(pubtest_ctx, "standins", None)
|
|
36
|
+
if standins is not None:
|
|
37
|
+
# The arguments it gave a program; what it gave one through its
|
|
38
|
+
# environment is deliberately not a leak.
|
|
39
|
+
out["the programs it ran"] = json.dumps(standins.runs())
|
|
40
|
+
for name, fake in getattr(pubtest_ctx, "fakes", {}).items():
|
|
41
|
+
out[f"what it sent {name}"] = json.dumps(fake.requests)
|
|
42
|
+
return out
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@then("no secret appears in what it produced")
|
|
46
|
+
def no_secret(pubtest_ctx):
|
|
47
|
+
assert pubtest_ctx.secrets, "no secret was given: the step checks the values a Given named"
|
|
48
|
+
leaks = [f"{s!r} in {where}" for where, text in produced(pubtest_ctx).items() for s in pubtest_ctx.secrets if s in text]
|
|
49
|
+
assert not leaks, "a secret appears: " + "; ".join(leaks)
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
"""Stand-in programs: scripts first on PATH in place of real ones, each run
|
|
2
|
+
recorded, so a suite tests what drives kubectl, ssh or git without them."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import shutil
|
|
9
|
+
import sys
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
from pytest_bdd import given, then
|
|
13
|
+
|
|
14
|
+
from ..core import matches
|
|
15
|
+
from . import phrase
|
|
16
|
+
|
|
17
|
+
# What a stand-in-only PATH still holds: the shell's basic tools.
|
|
18
|
+
BASIC = ("sh", "bash", "env", "cat", "echo", "printf", "mkdir", "rm", "cp", "mv", "chmod", "ls", "sed",
|
|
19
|
+
"grep", "head", "tail", "tr", "cut", "sort", "uniq", "wc", "dirname", "basename", "mktemp", "date",
|
|
20
|
+
"sleep", "true", "false", "test", "touch", "readlink", "realpath", "id", "uname")
|
|
21
|
+
|
|
22
|
+
# A stand-in that answers in turn: the first answer whose args match, of
|
|
23
|
+
# those not yet given, else the last that matches.
|
|
24
|
+
TURNS = '''#!{python}
|
|
25
|
+
import json, re, sys
|
|
26
|
+
with open({log!r}, "a", encoding="utf-8") as log:
|
|
27
|
+
log.write(json.dumps({{"name": {name!r}, "args": sys.argv[1:]}}) + "\\n")
|
|
28
|
+
with open({answers!r}, encoding="utf-8") as f:
|
|
29
|
+
answers = json.load(f)
|
|
30
|
+
args = " ".join(sys.argv[1:])
|
|
31
|
+
matching = [a for a in answers if re.fullmatch(".*".join(map(re.escape, a["args"].split("*"))), args, re.S)]
|
|
32
|
+
fresh = [a for a in matching if not a.get("given")]
|
|
33
|
+
none = {{"exit": 127, "stdout": "", "stderr": {name!r} + ": no answer for " + args + "\\n"}}
|
|
34
|
+
answer = fresh[0] if fresh else (matching[-1] if matching else none)
|
|
35
|
+
answer["given"] = True
|
|
36
|
+
with open({answers!r}, "w", encoding="utf-8") as f:
|
|
37
|
+
json.dump(answers, f)
|
|
38
|
+
sys.stdout.write(answer.get("stdout", ""))
|
|
39
|
+
sys.stderr.write(answer.get("stderr", ""))
|
|
40
|
+
sys.exit(int(answer.get("exit", 0)))
|
|
41
|
+
'''
|
|
42
|
+
|
|
43
|
+
STANDIN = '''#!{python}
|
|
44
|
+
import json, sys
|
|
45
|
+
read = sys.stdin.read() if {reads!r} else None
|
|
46
|
+
with open({log!r}, "a", encoding="utf-8") as log:
|
|
47
|
+
log.write(json.dumps({{"name": {name!r}, "args": sys.argv[1:], "input": read}}) + "\\n")
|
|
48
|
+
sys.stdout.write({out!r})
|
|
49
|
+
sys.stderr.write({err!r})
|
|
50
|
+
sys.exit({code})
|
|
51
|
+
'''
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class Standins:
|
|
55
|
+
"""A directory of stand-ins, its log of runs, and the PATH it makes."""
|
|
56
|
+
|
|
57
|
+
def __init__(self, root: Path) -> None:
|
|
58
|
+
self.bin = root / "standins"
|
|
59
|
+
self.bin.mkdir(parents=True)
|
|
60
|
+
self.log = root / "standins.log"
|
|
61
|
+
self.log.touch()
|
|
62
|
+
self.only = False
|
|
63
|
+
self.basic = root / "basic"
|
|
64
|
+
|
|
65
|
+
def add(self, name: str, out: str = "", err: str = "", code: int = 0, reads: bool = False) -> None:
|
|
66
|
+
path = self.bin / name
|
|
67
|
+
path.write_text(STANDIN.format(python=sys.executable, log=str(self.log), name=name, out=out, err=err,
|
|
68
|
+
code=code, reads=reads), encoding="utf-8")
|
|
69
|
+
path.chmod(0o755)
|
|
70
|
+
|
|
71
|
+
def add_turns(self, name: str, answers: list[dict]) -> None:
|
|
72
|
+
store = self.bin.parent / f"{name}.answers.json"
|
|
73
|
+
store.write_text(json.dumps(answers), encoding="utf-8")
|
|
74
|
+
path = self.bin / name
|
|
75
|
+
path.write_text(TURNS.format(python=sys.executable, log=str(self.log), name=name, answers=str(store)),
|
|
76
|
+
encoding="utf-8")
|
|
77
|
+
path.chmod(0o755)
|
|
78
|
+
|
|
79
|
+
def remove(self, name: str) -> None:
|
|
80
|
+
(self.bin / name).unlink(missing_ok=True)
|
|
81
|
+
|
|
82
|
+
def path(self) -> str:
|
|
83
|
+
if not self.only:
|
|
84
|
+
return f"{self.bin}{os.pathsep}{os.environ.get('PATH', '')}"
|
|
85
|
+
self.basic.mkdir(exist_ok=True)
|
|
86
|
+
for tool in BASIC:
|
|
87
|
+
found = shutil.which(tool)
|
|
88
|
+
if found and not (self.basic / tool).exists() and not (self.bin / tool).exists():
|
|
89
|
+
(self.basic / tool).symlink_to(found)
|
|
90
|
+
return f"{self.bin}{os.pathsep}{self.basic}"
|
|
91
|
+
|
|
92
|
+
def entries(self, name: str | None = None) -> list[dict]:
|
|
93
|
+
entries = [json.loads(line) for line in self.log.read_text(encoding="utf-8").splitlines() if line]
|
|
94
|
+
return [e for e in entries if name is None or e["name"] == name]
|
|
95
|
+
|
|
96
|
+
def runs(self, name: str | None = None) -> list[list[str]]:
|
|
97
|
+
return [e["args"] for e in self.entries(name)]
|
|
98
|
+
|
|
99
|
+
def inputs(self, name: str) -> list[str]:
|
|
100
|
+
return [e["input"] for e in self.entries(name) if e.get("input") is not None]
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def standins(pubtest_ctx, tmp_path) -> Standins:
|
|
104
|
+
if getattr(pubtest_ctx, "standins", None) is None:
|
|
105
|
+
pubtest_ctx.standins = Standins(tmp_path / "pubtest")
|
|
106
|
+
previous = os.environ.get("PATH", "")
|
|
107
|
+
os.environ["PATH"] = pubtest_ctx.standins.path()
|
|
108
|
+
|
|
109
|
+
@pubtest_ctx.cleanup
|
|
110
|
+
def restore():
|
|
111
|
+
os.environ["PATH"] = previous
|
|
112
|
+
return pubtest_ctx.standins
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _refresh(pubtest_ctx) -> None:
|
|
116
|
+
os.environ["PATH"] = pubtest_ctx.standins.path()
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
@given(phrase('a stand-in "{name}"'))
|
|
120
|
+
def standin(pubtest_ctx, tmp_path, name):
|
|
121
|
+
standins(pubtest_ctx, tmp_path).add(name)
|
|
122
|
+
_refresh(pubtest_ctx)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
@given(phrase('a stand-in "{name}" that prints "{text}"'))
|
|
126
|
+
def standin_prints(pubtest_ctx, tmp_path, name, text):
|
|
127
|
+
standins(pubtest_ctx, tmp_path).add(name, out=text + "\n")
|
|
128
|
+
_refresh(pubtest_ctx)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
@given(phrase('a stand-in "{name}" that prints:'))
|
|
132
|
+
def standin_prints_text(pubtest_ctx, tmp_path, name, docstring):
|
|
133
|
+
standins(pubtest_ctx, tmp_path).add(name, out=docstring + "\n")
|
|
134
|
+
_refresh(pubtest_ctx)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
@given(phrase('a stand-in "{name}" that fails, saying "{text}"'))
|
|
138
|
+
def standin_fails(pubtest_ctx, tmp_path, name, text):
|
|
139
|
+
standins(pubtest_ctx, tmp_path).add(name, err=text + "\n", code=1)
|
|
140
|
+
_refresh(pubtest_ctx)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
@given(phrase('a stand-in "{name}" that answers in turn:'))
|
|
144
|
+
def standin_turns(pubtest_ctx, tmp_path, name, datatable):
|
|
145
|
+
"""A row per answer: args (a pattern, * for any), and optionally exit,
|
|
146
|
+
stdout and stderr. A run takes the first matching answer not yet given,
|
|
147
|
+
or the last that matches once all are given."""
|
|
148
|
+
keys, rows = datatable[0], datatable[1:]
|
|
149
|
+
answers = []
|
|
150
|
+
for row in rows:
|
|
151
|
+
answer = dict(zip(keys, row, strict=True))
|
|
152
|
+
for stream in ("stdout", "stderr"):
|
|
153
|
+
if answer.get(stream):
|
|
154
|
+
answer[stream] = answer[stream].replace("\\n", "\n") + "\n"
|
|
155
|
+
answers.append(answer)
|
|
156
|
+
standins(pubtest_ctx, tmp_path).add_turns(name, answers)
|
|
157
|
+
_refresh(pubtest_ctx)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
@given(phrase('a stand-in "{name}" that reads its input'))
|
|
161
|
+
def standin_reads(pubtest_ctx, tmp_path, name):
|
|
162
|
+
"""Reads its standard input to the end, as `kubectl apply -f -` does, and
|
|
163
|
+
keeps it for `read the input`. Only a stand-in that reads waits for it."""
|
|
164
|
+
standins(pubtest_ctx, tmp_path).add(name, reads=True)
|
|
165
|
+
_refresh(pubtest_ctx)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
@given("only stand-ins are installed")
|
|
169
|
+
def only_standins(pubtest_ctx, tmp_path):
|
|
170
|
+
standins(pubtest_ctx, tmp_path).only = True
|
|
171
|
+
_refresh(pubtest_ctx)
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
@given(phrase('"{name}" is not installed'))
|
|
175
|
+
def not_installed(pubtest_ctx, tmp_path, name):
|
|
176
|
+
found = standins(pubtest_ctx, tmp_path)
|
|
177
|
+
found.remove(name)
|
|
178
|
+
found.only = True
|
|
179
|
+
_refresh(pubtest_ctx)
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
@then(phrase('"{name}" was run with "{args}"'))
|
|
183
|
+
def run_with(pubtest_ctx, name, args):
|
|
184
|
+
import shlex # noqa: PLC0415
|
|
185
|
+
runs = pubtest_ctx.standins.runs(name)
|
|
186
|
+
assert shlex.split(args) in runs, f"{name} ran with {runs}"
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
@then(phrase('"{name}" was run {count:d} times'))
|
|
190
|
+
def run_times(pubtest_ctx, name, count):
|
|
191
|
+
assert len(pubtest_ctx.standins.runs(name)) == count, f"{name} ran {len(pubtest_ctx.standins.runs(name))} times"
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
@then(phrase('"{name}" was not run'))
|
|
195
|
+
def not_run(pubtest_ctx, name):
|
|
196
|
+
runs = pubtest_ctx.standins.runs(name) if getattr(pubtest_ctx, "standins", None) else []
|
|
197
|
+
assert not runs, f"{name} ran with {runs}"
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
@then("nothing was run")
|
|
201
|
+
def nothing_run(pubtest_ctx):
|
|
202
|
+
runs = pubtest_ctx.standins.runs() if getattr(pubtest_ctx, "standins", None) else []
|
|
203
|
+
assert not runs, f"ran: {runs}"
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _runs(pubtest_ctx, name: str) -> list[list[str]]:
|
|
207
|
+
return pubtest_ctx.standins.runs(name) if getattr(pubtest_ctx, "standins", None) else []
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
@then(phrase('"{name}" was run with arguments matching "{pattern}"'))
|
|
211
|
+
def run_matching(pubtest_ctx, name, pattern):
|
|
212
|
+
runs = _runs(pubtest_ctx, name)
|
|
213
|
+
assert any(matches(pattern, " ".join(args)) for args in runs), f"{name} ran with {runs}"
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
@then(phrase('"{name}" was not run with arguments matching "{pattern}"'))
|
|
217
|
+
def not_run_matching(pubtest_ctx, name, pattern):
|
|
218
|
+
runs = _runs(pubtest_ctx, name)
|
|
219
|
+
found = [args for args in runs if matches(pattern, " ".join(args))]
|
|
220
|
+
assert not found, f"{name} ran with {found}"
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
@then(phrase('"{name}" was run, in order, with arguments matching:'))
|
|
224
|
+
def run_in_order(pubtest_ctx, name, docstring):
|
|
225
|
+
"""Each line of the docstring is a pattern; some runs, in this order,
|
|
226
|
+
though others may come between them, match them one by one."""
|
|
227
|
+
patterns = [line.strip() for line in docstring.splitlines() if line.strip()]
|
|
228
|
+
runs = [" ".join(args) for args in _runs(pubtest_ctx, name)]
|
|
229
|
+
left = iter(runs)
|
|
230
|
+
missing = next((p for p in patterns if not any(matches(p, run) for run in left)), None)
|
|
231
|
+
assert missing is None, f"{name} ran with nothing matching {missing!r} in order; it ran: {runs}"
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
@then(phrase('"{name}" read the input:'))
|
|
235
|
+
def read_input(pubtest_ctx, name, docstring):
|
|
236
|
+
inputs = pubtest_ctx.standins.inputs(name)
|
|
237
|
+
assert docstring.removesuffix("\n") in [i.removesuffix("\n") for i in inputs], f"{name} read {inputs}"
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
@then(phrase('"{name}" read input including "{text}"'))
|
|
241
|
+
def read_input_including(pubtest_ctx, name, text):
|
|
242
|
+
inputs = pubtest_ctx.standins.inputs(name)
|
|
243
|
+
assert any(text in i for i in inputs), f"{name} read {inputs}"
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pubtestrules
|
|
3
|
+
Version: 0.4.0
|
|
4
|
+
Summary: The Gherkin steps every Sustenaut suite shares, as a pytest-bdd plugin (and, from the same grammar, an npm package).
|
|
5
|
+
Author-email: David Schryer <schryer@gmail.com>
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Repository, https://github.com/Sustenaut/pubtest
|
|
8
|
+
Requires-Python: >=3.11
|
|
9
|
+
Description-Content-Type: text/markdown
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Requires-Dist: pytest>=8
|
|
12
|
+
Requires-Dist: pytest-bdd>=8.1
|
|
13
|
+
Dynamic: license-file
|
|
14
|
+
|
|
15
|
+
# pubtest
|
|
16
|
+
|
|
17
|
+
The Gherkin steps every Sustenaut suite shares. One grammar,
|
|
18
|
+
[GRAMMAR.md](GRAMMAR.md), shipped two ways:
|
|
19
|
+
|
|
20
|
+
- **`pubtest`**, a Python package: a pytest-bdd plugin that loads into every
|
|
21
|
+
pytest session.
|
|
22
|
+
- **`@sustenaut/pubtest`**, an npm package: the same steps for cucumber-js and
|
|
23
|
+
quickpickle.
|
|
24
|
+
|
|
25
|
+
A suite writes the Givens of its own domain and its own When. Everything a
|
|
26
|
+
scenario checks, and the setups that repeat across repositories (files, the
|
|
27
|
+
environment, programs and stand-ins for them, HTTP, fake services, recorded
|
|
28
|
+
answers, secrets, git), are pubtest's, in the same words everywhere. The same
|
|
29
|
+
features run against both packages, under pytest-bdd, cucumber-js and
|
|
30
|
+
quickpickle, so a step means the same in Python and in Node.
|
|
31
|
+
|
|
32
|
+
## Python
|
|
33
|
+
|
|
34
|
+
pubrules's managed `tests/requirements-pubrules.txt` pins pubtest for every
|
|
35
|
+
repository, so a suite only writes steps:
|
|
36
|
+
|
|
37
|
+
```python
|
|
38
|
+
from pytest_bdd import parsers, scenarios, when
|
|
39
|
+
|
|
40
|
+
scenarios("planner.feature")
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@when(parsers.parse('the planner plans "{week}"'))
|
|
44
|
+
def plans(ctx, week):
|
|
45
|
+
ctx.attempt(lambda: planner.plan(week))
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
```gherkin
|
|
49
|
+
Scenario: A week with no work is refused
|
|
50
|
+
Given a scratch directory
|
|
51
|
+
When the planner plans "2026-W53"
|
|
52
|
+
Then it is refused, saying "no such week"
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Besides the steps, the plugin gives a suite `ctx` (the scenario's context:
|
|
56
|
+
`attempt`, `cleanup`, the result), `binary(name)` (a program under test from
|
|
57
|
+
`<NAME>_BIN_DIR`, never PATH), `run(...)`, a marker for every `@tag` in the
|
|
58
|
+
feature files, and Hypothesis's examples per property from `PUBRULES_FUZZ_RUNS`.
|
|
59
|
+
A suite that tests a service gives pubtest its client:
|
|
60
|
+
|
|
61
|
+
```python
|
|
62
|
+
import pubtest.http
|
|
63
|
+
|
|
64
|
+
@pytest.fixture
|
|
65
|
+
def http_client():
|
|
66
|
+
return pubtest.http.asgi(create_app()) # or .wsgi(app), or .url("http://127.0.0.1:8000")
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
## Node
|
|
70
|
+
|
|
71
|
+
```sh
|
|
72
|
+
npm install --save-dev --save-exact github:Sustenaut/pubtest#v0.1.0
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
```js
|
|
76
|
+
// features/support/steps.js, for cucumber-js
|
|
77
|
+
import * as cucumber from "@cucumber/cucumber";
|
|
78
|
+
import { register } from "@sustenaut/pubtest";
|
|
79
|
+
import { fromFetch } from "@sustenaut/pubtest/http";
|
|
80
|
+
import worker from "../../src/worker.js";
|
|
81
|
+
|
|
82
|
+
register(cucumber, { client: () => fromFetch((request) => worker.fetch(request, env)) });
|
|
83
|
+
|
|
84
|
+
cucumber.When("the planner plans {string}", function (week) {
|
|
85
|
+
return this.attempt(() => planner.plan(week));
|
|
86
|
+
});
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
For quickpickle, pass its module and `{ runner: "quickpickle" }`, and load the
|
|
90
|
+
file through vitest's `setupFiles`.
|
|
91
|
+
|
|
92
|
+
## Record and replay
|
|
93
|
+
|
|
94
|
+
A suite that calls outside services through integrations' `Caller` replays
|
|
95
|
+
what they answered: one cassette per scenario, recorded with
|
|
96
|
+
`pubtest record`, in the data repository beside the repository
|
|
97
|
+
(`../<repo>-data/integrations/cassettes/`). Turn it on in pubrules.json:
|
|
98
|
+
|
|
99
|
+
```json
|
|
100
|
+
"pubtest": {"cassettes": true}
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
and install integrations beside pubtest: the suite's own pin of it in Python,
|
|
104
|
+
`@sustenaut/integrations` (an optional peer) in Node. pubtest itself never
|
|
105
|
+
depends on integrations, whose own suite runs on pubtest. Then:
|
|
106
|
+
|
|
107
|
+
```sh
|
|
108
|
+
pubtest record --all # record every scenario's calls
|
|
109
|
+
pubtest record --changed # only those whose cassette is out of date
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
and the failure steps (`Given the "github" integration can't be reached`)
|
|
113
|
+
break a scenario's calls on purpose, over its cassette. GRAMMAR.md, "Record
|
|
114
|
+
and replay", has the modes, variables, paths, errors and test customers.
|
|
115
|
+
|
|
116
|
+
## Developing
|
|
117
|
+
|
|
118
|
+
```sh
|
|
119
|
+
make venv && npm ci --ignore-scripts
|
|
120
|
+
make functional # the features under pytest-bdd, with coverage
|
|
121
|
+
npm test # the same features under cucumber-js, then quickpickle
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
`features/` is the library's own suite, the steps a suite would write are in
|
|
125
|
+
`tests/conftest.py` and `test/suite.js` (the same texts in both), and
|
|
126
|
+
`tests/python-features/` holds the Python-only adapter scenarios. The suite
|
|
127
|
+
turns cassettes on, kept in `tests/cassettes/`, and its example test customer
|
|
128
|
+
is in `tests/customers/` and `test/customer.js`; `pubtest record --all`
|
|
129
|
+
records them again, through a stand-in for the network. A change to
|
|
130
|
+
a step changes GRAMMAR.md, both packages and a feature, in one pull request,
|
|
131
|
+
and records itself with `pubrel add`. Releases are cut with `pubrel prepare`
|
|
132
|
+
from a checkout whose `corpus/.publet` holds the release key.
|
|
133
|
+
|
|
134
|
+
## Licence
|
|
135
|
+
|
|
136
|
+
Apache-2.0.
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
pubtest/__init__.py,sha256=NBN2suthhBv5DEknve9yzZK9k3baRGbWCQJe-fhnnXs,283
|
|
2
|
+
pubtest/cassettes.py,sha256=jMBqYgPOS6nybZVMkIid-x6bjqCAMpNc27qH7n9-Lvw,25638
|
|
3
|
+
pubtest/cli.py,sha256=mN5iYAtpDDu2xLSdwB-G2v5WEgXbq4cTluDQGCWxUjk,11166
|
|
4
|
+
pubtest/core.py,sha256=JQ2nahb2qonna_okHPVga6qpRnRDE1wa3VqDV0OAUc0,9611
|
|
5
|
+
pubtest/http.py,sha256=KnV61g-WlYouv0DV_TEqB5xI2OFiaH0bznV5Ce2o9v4,6153
|
|
6
|
+
pubtest/plugin.py,sha256=LeCEArdq3Iq28T2xNtcVZWJ-1suNKKlGKh3EKVTasYA,10926
|
|
7
|
+
pubtest/_child/report.mjs,sha256=6q-53_F3z4f-7uxKYXRAQQ74h_0Yc_Z7UgTiKsTBNis,1911
|
|
8
|
+
pubtest/_child/sitecustomize.py,sha256=Uz-8uu18niqf8Dv7-OQWtJoCofe-TmSuJ3lrmFbVQ90,1953
|
|
9
|
+
pubtest/steps/__init__.py,sha256=sSndPzKUC0OcJkvuxJaa5To2_PrAJXbw6T9uVeHROF8,2982
|
|
10
|
+
pubtest/steps/environment.py,sha256=rw4VbsAQtdlXX4oS-Iz7vcStQ3Y4KCpf3qbHsPC8yWQ,399
|
|
11
|
+
pubtest/steps/fakes.py,sha256=bgLVLJ5ZapuR5MRF5hno_oBcHknnGz8VWTWHjZbgdyo,7573
|
|
12
|
+
pubtest/steps/files.py,sha256=ybi53lgLt6MbxEkh2Gh09CFj6kv3Ly5C2IhsnwfVVWM,6419
|
|
13
|
+
pubtest/steps/git.py,sha256=-tqjzGQ-FQx7Yr9qKAV6WIO3QTf0m5H1I1IfOxpuUbw,2831
|
|
14
|
+
pubtest/steps/http.py,sha256=BPiJiM-2xEBRktYVDsZ1pDqxH66IEABEtTn71A97pjY,5326
|
|
15
|
+
pubtest/steps/integrations.py,sha256=0uNZVRw1DYvfrkPk-b7tS3FORWc93KnSZ-CYmlwPHcU,2376
|
|
16
|
+
pubtest/steps/programs.py,sha256=xjZvg3itdM7vlrQvQV8_WyP-dED1PuTX24UR1fnBdWM,6265
|
|
17
|
+
pubtest/steps/result.py,sha256=oriedwrBOLqdtCQbiOvDLHFvTFlgENJ9YYJ19bXotaE,6679
|
|
18
|
+
pubtest/steps/secrets.py,sha256=ntkpOKquCHdAP7Rs5_ArDKjOJIycFFi6lKY9dhwP3oM,2005
|
|
19
|
+
pubtest/steps/standins.py,sha256=e8dIu1N7sSu4KmYvO87_P4MQ2uwDMyZYZHYHokghsDQ,9414
|
|
20
|
+
pubtestrules-0.4.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
|
|
21
|
+
pubtestrules-0.4.0.dist-info/METADATA,sha256=uJBbkq3swU0hWeqdnGC5xbzeD0XLTToUHxX5B9r4cjo,4745
|
|
22
|
+
pubtestrules-0.4.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
23
|
+
pubtestrules-0.4.0.dist-info/entry_points.txt,sha256=V-WlBHWPugMcvgxtCKcjEhX4sObDcqOtcWp1nDZKPbE,82
|
|
24
|
+
pubtestrules-0.4.0.dist-info/top_level.txt,sha256=J0a973jEKhO0od9f5FDgwUYH_9fk_87MqeUAvhdZ5o0,8
|
|
25
|
+
pubtestrules-0.4.0.dist-info/RECORD,,
|