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/steps/files.py ADDED
@@ -0,0 +1,179 @@
1
+ """Files in the scenario's scratch directory."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import shutil
8
+ import stat
9
+ from pathlib import Path
10
+
11
+ import pytest
12
+ from pytest_bdd import given, then, when
13
+
14
+ from ..core import dig, files_in, repository, same, show, yaml_documents
15
+ from . import phrase
16
+
17
+
18
+ def at(pubtest_ctx, path: str) -> Path:
19
+ """`path`, in the scratch directory when there is one."""
20
+ return (pubtest_ctx.directory or Path.cwd()) / path
21
+
22
+
23
+ @given("a scratch directory")
24
+ def scratch_directory(pubtest_ctx, tmp_path, monkeypatch):
25
+ pubtest_ctx.directory = tmp_path / "scratch"
26
+ pubtest_ctx.directory.mkdir()
27
+ monkeypatch.chdir(pubtest_ctx.directory)
28
+
29
+
30
+ def _write(pubtest_ctx, path: str, text: str) -> None:
31
+ target = at(pubtest_ctx, path)
32
+ target.parent.mkdir(parents=True, exist_ok=True)
33
+ target.write_text(text, encoding="utf-8")
34
+
35
+
36
+ @given(phrase('a file "{path}" holding "{text}"'))
37
+ def holds_line(pubtest_ctx, path, text):
38
+ _write(pubtest_ctx, path, text + "\n")
39
+
40
+
41
+ @given(phrase('a file "{path}" holding:'))
42
+ def holds_text(pubtest_ctx, path, docstring):
43
+ _write(pubtest_ctx, path, docstring + "\n")
44
+
45
+
46
+ @pytest.fixture(scope="session")
47
+ def pubtest_repository(request) -> Path:
48
+ """The repository the suite runs in, which `copied from` paths are in."""
49
+ return repository(Path(request.config.invocation_params.dir))
50
+
51
+
52
+ @given(phrase('a file "{path}" copied from "{source}"'))
53
+ def copied(pubtest_ctx, pubtest_repository, path, source):
54
+ origin = (pubtest_repository / source).resolve()
55
+ if Path(source).is_absolute() or not origin.is_relative_to(pubtest_repository.resolve()):
56
+ raise AssertionError(f"{source} is not in the repository: copy only the repository's own files")
57
+ assert origin.exists(), f"the repository has no {source}"
58
+ target = at(pubtest_ctx, path)
59
+ target.parent.mkdir(parents=True, exist_ok=True)
60
+ if origin.is_dir():
61
+ shutil.copytree(origin, target, dirs_exist_ok=True)
62
+ else:
63
+ shutil.copyfile(origin, target)
64
+
65
+
66
+ @given(phrase('the file "{path}" is executable'))
67
+ def executable(pubtest_ctx, path):
68
+ target = at(pubtest_ctx, path)
69
+ target.chmod(target.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
70
+
71
+
72
+ @given(phrase('the file "{path}" is removed'))
73
+ def removed(pubtest_ctx, path):
74
+ """Deletes it, or a directory and what it holds; one already gone is fine."""
75
+ target = at(pubtest_ctx, path)
76
+ if target.is_dir() and not target.is_symlink():
77
+ shutil.rmtree(target)
78
+ else:
79
+ target.unlink(missing_ok=True)
80
+
81
+
82
+ @when(phrase('the file "{path}" changes to:'))
83
+ def changes(pubtest_ctx, path, docstring):
84
+ _write(pubtest_ctx, path, docstring + "\n")
85
+
86
+
87
+ @then(phrase('the file "{path}" exists'))
88
+ def exists(pubtest_ctx, path):
89
+ assert at(pubtest_ctx, path).exists(), f"there is no {path}"
90
+
91
+
92
+ @then(phrase('the file "{path}" does not exist'))
93
+ def not_exists(pubtest_ctx, path):
94
+ assert not at(pubtest_ctx, path).exists(), f"{path} exists"
95
+
96
+
97
+ def _text(pubtest_ctx, path: str) -> str:
98
+ target = at(pubtest_ctx, path)
99
+ assert target.is_file(), f"there is no {path}"
100
+ return target.read_text(encoding="utf-8")
101
+
102
+
103
+ @then(phrase('the file "{path}" holds "{text}"'))
104
+ def file_holds_line(pubtest_ctx, path, text):
105
+ got = _text(pubtest_ctx, path)
106
+ assert got.removesuffix("\n") == text, f"{path} holds {got!r}"
107
+
108
+
109
+ @then(phrase('the file "{path}" holds:'))
110
+ def file_holds_text(pubtest_ctx, path, docstring):
111
+ got = _text(pubtest_ctx, path)
112
+ assert got.removesuffix("\n") == docstring.removesuffix("\n"), f"{path} holds:\n{got}"
113
+
114
+
115
+ @then(phrase('the file "{path}" includes "{text}" once'))
116
+ def file_includes_once(pubtest_ctx, path, text):
117
+ lines = [line for line in _text(pubtest_ctx, path).splitlines() if text in line]
118
+ assert len(lines) == 1, f"{path} has {len(lines)} lines with {text!r}"
119
+
120
+
121
+ @then(phrase('the file "{path}" includes "{text}"'))
122
+ def file_includes(pubtest_ctx, path, text):
123
+ assert text in _text(pubtest_ctx, path), f"{path} does not include {text!r}"
124
+
125
+
126
+ @then(phrase('the file "{path}" does not include "{text}"'))
127
+ def file_excludes(pubtest_ctx, path, text):
128
+ assert text not in _text(pubtest_ctx, path), f"{path} includes {text!r}"
129
+
130
+
131
+ @then(phrase('the JSON in "{path}" is:'))
132
+ def json_is(pubtest_ctx, path, docstring):
133
+ got = json.loads(_text(pubtest_ctx, path))
134
+ assert got == json.loads(docstring), f"{path} holds {show(got)}"
135
+
136
+
137
+ @then(phrase('the JSON in "{path}" has "{key}" equal to "{wanted}"'))
138
+ def json_key(pubtest_ctx, path, key, wanted):
139
+ got = dig(json.loads(_text(pubtest_ctx, path)), key)
140
+ assert same(got, wanted), f"{path}'s {key} is {show(got)}, not {wanted}"
141
+
142
+
143
+ @then("nothing was written")
144
+ def nothing_written(pubtest_ctx):
145
+ assert pubtest_ctx.directory is not None, "nothing was written needs a scratch directory"
146
+ assert pubtest_ctx.written is not None, "nothing was written needs a When: it compares with the directory before it"
147
+ before, after = pubtest_ctx.written, files_in(pubtest_ctx.directory)
148
+ changed = sorted(p for p in set(before) | set(after) if before.get(p) != after.get(p))
149
+ assert not changed, f"written: {', '.join(changed)}"
150
+
151
+
152
+ @then(phrase('the file "{path}" can be run'))
153
+ def can_be_run(pubtest_ctx, path):
154
+ target = at(pubtest_ctx, path)
155
+ assert target.is_file(), f"there is no {path}"
156
+ assert os.access(target, os.X_OK), f"{path} is not executable"
157
+
158
+
159
+ @then(phrase('the directory "{path}" holds:'))
160
+ def directory_holds(pubtest_ctx, path, docstring):
161
+ """The names in the directory, one a line, in name order; a directory's
162
+ ends with a slash."""
163
+ target = at(pubtest_ctx, path)
164
+ assert target.is_dir(), f"there is no directory {path}"
165
+ names = sorted(p.name + ("/" if p.is_dir() else "") for p in target.iterdir())
166
+ want = [line.strip() for line in docstring.splitlines() if line.strip()]
167
+ assert names == want, f"{path} holds:\n" + "\n".join(names)
168
+
169
+
170
+ @then(phrase('the YAML in "{path}" is:'))
171
+ def yaml_is(pubtest_ctx, path, docstring):
172
+ got, want = yaml_documents(_text(pubtest_ctx, path)), yaml_documents(docstring)
173
+ assert got == want, f"{path} holds {show(got)}"
174
+
175
+
176
+ @then(phrase('the YAML in "{path}" has "{key}" equal to "{wanted}"'))
177
+ def yaml_key(pubtest_ctx, path, key, wanted):
178
+ got = dig(yaml_documents(_text(pubtest_ctx, path)), key)
179
+ assert same(got, wanted), f"{path}'s {key} is {show(got)}, not {wanted}"
pubtest/steps/git.py ADDED
@@ -0,0 +1,80 @@
1
+ """Git: a repository in the scratch directory, its remotes, and what was
2
+ committed."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import os
7
+ import subprocess
8
+
9
+ from pytest_bdd import given, then
10
+
11
+ from . import phrase
12
+
13
+ GIT_ENV = {"GIT_AUTHOR_NAME": "pubtest", "GIT_AUTHOR_EMAIL": "pubtest@example.org",
14
+ "GIT_COMMITTER_NAME": "pubtest", "GIT_COMMITTER_EMAIL": "pubtest@example.org"}
15
+
16
+
17
+ def git(pubtest_ctx, *args: str, cwd: str | os.PathLike[str] | None = None) -> str:
18
+ done = subprocess.run(["git", *args], cwd=cwd or pubtest_ctx.directory or os.getcwd(), capture_output=True,
19
+ text=True, env={**os.environ, **GIT_ENV}, check=False)
20
+ assert done.returncode == 0, f"git {' '.join(args)}: {done.stderr}"
21
+ return done.stdout.strip()
22
+
23
+
24
+ @given("a git repository")
25
+ def repository(pubtest_ctx):
26
+ git(pubtest_ctx, "init", "-q", "-b", "main")
27
+ git(pubtest_ctx, "commit", "-q", "--allow-empty", "-m", "start")
28
+
29
+
30
+ @given(phrase('a commit tagged "{tag}"'))
31
+ def commit_tagged(pubtest_ctx, tag):
32
+ git(pubtest_ctx, "add", "-A")
33
+ git(pubtest_ctx, "commit", "-q", "--allow-empty", "-m", tag)
34
+ git(pubtest_ctx, "tag", tag)
35
+
36
+
37
+ @given(phrase('the branch "{branch}"'))
38
+ def branch(pubtest_ctx, branch):
39
+ git(pubtest_ctx, "switch", "-q", "-c", branch)
40
+
41
+
42
+ @given(phrase('everything is committed with the message "{message}"'))
43
+ def committed(pubtest_ctx, message):
44
+ git(pubtest_ctx, "add", "-A")
45
+ git(pubtest_ctx, "commit", "-q", "--allow-empty", "-m", message)
46
+
47
+
48
+ @given(phrase('a bare remote "{name}"'))
49
+ def bare_remote(pubtest_ctx, tmp_path, name):
50
+ """A bare repository outside the scratch directory, added as the remote
51
+ `name`, with the current branch pushed to it."""
52
+ remote = tmp_path / "pubtest-remotes" / f"{name}.git"
53
+ remote.mkdir(parents=True)
54
+ git(pubtest_ctx, "init", "-q", "--bare", "-b", "main", str(remote), cwd=remote.parent)
55
+ git(pubtest_ctx, "remote", "add", name, str(remote))
56
+ git(pubtest_ctx, "push", "-q", name, "HEAD")
57
+
58
+
59
+ @then(phrase('the last commit\'s message includes "{text}"'))
60
+ def last_message(pubtest_ctx, text):
61
+ message = git(pubtest_ctx, "log", "-1", "--format=%B")
62
+ assert text in message, f"the last commit's message is {message!r}"
63
+
64
+
65
+ @then("the working tree is clean")
66
+ def clean(pubtest_ctx):
67
+ status = git(pubtest_ctx, "status", "--porcelain")
68
+ assert not status, f"the working tree has changes:\n{status}"
69
+
70
+
71
+ @then(phrase('the tag "{tag}" exists'))
72
+ def tag_exists(pubtest_ctx, tag):
73
+ tags = git(pubtest_ctx, "tag", "--list").splitlines()
74
+ assert tag in tags, f"the tags are {tags}"
75
+
76
+
77
+ @then(phrase('the remote "{name}" has the branch "{branch}"'))
78
+ def remote_has(pubtest_ctx, name, branch):
79
+ heads = git(pubtest_ctx, "ls-remote", "--heads", name, branch)
80
+ assert heads, f"the remote {name} has no branch {branch}"
pubtest/steps/http.py ADDED
@@ -0,0 +1,161 @@
1
+ """HTTP: a request to the service under test, and its answer."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from urllib.parse import urlencode
7
+
8
+ import pytest
9
+ from pytest_bdd import given, then, when
10
+
11
+ from ..core import Result, same
12
+ from . import phrase
13
+
14
+
15
+ @pytest.fixture
16
+ def http_client():
17
+ pytest.fail("the HTTP steps need the suite's http_client fixture: pubtest.http.asgi(app), "
18
+ "pubtest.http.wsgi(app), pubtest.http.url(base), or a callable of its own")
19
+
20
+
21
+ @pytest.fixture
22
+ def identity_header() -> str:
23
+ """The header a signed-in person's email comes in, behind the sign-in proxy."""
24
+ return "X-Forwarded-Email"
25
+
26
+
27
+ def _headers(pubtest_ctx) -> dict:
28
+ if not hasattr(pubtest_ctx, "headers"):
29
+ pubtest_ctx.headers = {}
30
+ return pubtest_ctx.headers
31
+
32
+
33
+ @given(phrase('I am signed in as "{email}"'))
34
+ def signed_in(pubtest_ctx, identity_header, email):
35
+ _headers(pubtest_ctx)[identity_header] = email
36
+
37
+
38
+ @given("I am not signed in")
39
+ def not_signed_in(pubtest_ctx, identity_header):
40
+ _headers(pubtest_ctx).pop(identity_header, None)
41
+
42
+
43
+ @given(phrase('requests carry the header "{name}" set to "{value}"'))
44
+ def carry_header(pubtest_ctx, name, value):
45
+ _headers(pubtest_ctx)[name] = value
46
+
47
+
48
+ @given(phrase('requests come from "{origin}"'))
49
+ def origin(pubtest_ctx, origin):
50
+ _headers(pubtest_ctx)["Origin"] = origin
51
+
52
+
53
+ def send(pubtest_ctx, http_client, method: str, path: str, body: bytes | None = None, content_type: str | None = None):
54
+ headers = dict(_headers(pubtest_ctx))
55
+ if content_type:
56
+ headers["Content-Type"] = content_type
57
+ pubtest_ctx.acting()
58
+ pubtest_ctx.answer = http_client(method, path, headers, body)
59
+ pubtest_ctx.ran(Result(value=pubtest_ctx.answer))
60
+ return pubtest_ctx.answer
61
+
62
+
63
+ @when(phrase('I GET "{path}"'))
64
+ def get(pubtest_ctx, http_client, path):
65
+ send(pubtest_ctx, http_client, "GET", path)
66
+
67
+
68
+ @when(phrase('I POST to "{path}" with:'))
69
+ def post_json(pubtest_ctx, http_client, path, docstring):
70
+ send(pubtest_ctx, http_client, "POST", path, docstring.encode(), "application/json")
71
+
72
+
73
+ @when(phrase('I POST to "{path}" with the form:'))
74
+ def post_form(pubtest_ctx, http_client, path, datatable):
75
+ fields = {row[0]: row[1] for row in datatable[1:]} if datatable and datatable[0][:2] == ["field", "value"] \
76
+ else {row[0]: row[1] for row in datatable}
77
+ send(pubtest_ctx, http_client, "POST", path, urlencode(fields).encode(), "application/x-www-form-urlencoded")
78
+
79
+
80
+ @when(phrase('I send "{method}" to "{path}"'))
81
+ def send_method(pubtest_ctx, http_client, method, path):
82
+ send(pubtest_ctx, http_client, method, path)
83
+
84
+
85
+ @when(phrase('I send "{method}" to "{path}" with:'))
86
+ def send_json(pubtest_ctx, http_client, method, path, docstring):
87
+ send(pubtest_ctx, http_client, method, path, docstring.encode(), "application/json")
88
+
89
+
90
+ @when(phrase('I send "{method}" to "{path}" with the file "{file}"'))
91
+ def send_file(pubtest_ctx, http_client, method, path, file):
92
+ """The file's bytes, as they are, with the Content-Type a Given set, or
93
+ application/octet-stream."""
94
+ from .files import at # noqa: PLC0415
95
+ body = at(pubtest_ctx, file).read_bytes()
96
+ typed = any(k.lower() == "content-type" for k in _headers(pubtest_ctx))
97
+ send(pubtest_ctx, http_client, method, path, body, None if typed else "application/octet-stream")
98
+
99
+
100
+ def _answer(pubtest_ctx):
101
+ assert getattr(pubtest_ctx, "answer", None) is not None, "no request was sent"
102
+ return pubtest_ctx.answer
103
+
104
+
105
+ def _show(answer) -> str:
106
+ return f"{answer.status} {answer.headers}\n{answer.text[:2000]}"
107
+
108
+
109
+ @then(phrase("the answer is {status:d}"))
110
+ def answer_is(pubtest_ctx, status):
111
+ answer = _answer(pubtest_ctx)
112
+ assert answer.status == status, _show(answer)
113
+
114
+
115
+ @then(phrase('the answer\'s "{name}" is "{wanted}"'))
116
+ def answer_header(pubtest_ctx, name, wanted):
117
+ answer = _answer(pubtest_ctx)
118
+ assert answer.header(name) == wanted, _show(answer)
119
+
120
+
121
+ @then(phrase('the answer\'s "{name}" includes "{text}"'))
122
+ def answer_header_includes(pubtest_ctx, name, text):
123
+ answer = _answer(pubtest_ctx)
124
+ got = answer.header(name)
125
+ assert got is not None and text in got, _show(answer)
126
+
127
+
128
+ @then(phrase('the answer has no "{name}"'))
129
+ def answer_no_header(pubtest_ctx, name):
130
+ answer = _answer(pubtest_ctx)
131
+ assert answer.header(name) is None, _show(answer)
132
+
133
+
134
+ @then(phrase('the answer includes "{text}" once'))
135
+ def answer_includes_once(pubtest_ctx, text):
136
+ answer = _answer(pubtest_ctx)
137
+ assert sum(1 for line in answer.text.splitlines() if text in line) == 1, _show(answer)
138
+
139
+
140
+ @then(phrase('the answer includes "{text}"'))
141
+ def answer_includes(pubtest_ctx, text):
142
+ answer = _answer(pubtest_ctx)
143
+ assert text in answer.text, _show(answer)
144
+
145
+
146
+ @then(phrase('the answer does not include "{text}"'))
147
+ def answer_excludes(pubtest_ctx, text):
148
+ answer = _answer(pubtest_ctx)
149
+ assert text not in answer.text, _show(answer)
150
+
151
+
152
+ @then("the answer is the JSON:")
153
+ def answer_json(pubtest_ctx, docstring):
154
+ answer = _answer(pubtest_ctx)
155
+ assert json.loads(answer.body) == json.loads(docstring), _show(answer)
156
+
157
+
158
+ @then(phrase('the answer redirects to "{path}"'))
159
+ def answer_redirects(pubtest_ctx, path):
160
+ answer = _answer(pubtest_ctx)
161
+ assert 300 <= answer.status < 400 and same(answer.header("Location"), path), _show(answer)
@@ -0,0 +1,65 @@
1
+ """Calls to outside services: faults on a scenario's cassette, another
2
+ scenario's cassette, and what the calls came to (the record/replay harness,
3
+ pubtest.cassettes)."""
4
+
5
+ from __future__ import annotations
6
+
7
+ from pytest_bdd import given, then
8
+
9
+ from .. import cassettes
10
+ from . import phrase
11
+
12
+ # Longer than any operation's timeout: slower than this is no answer.
13
+ NEVER = 86400
14
+
15
+
16
+ def tape(pubtest_ctx) -> cassettes.Tape:
17
+ """The scenario's tape; a failure saying how to turn the harness on when it is off."""
18
+ found = getattr(pubtest_ctx, "tape", None)
19
+ assert found is not None, cassettes.OFF
20
+ return found
21
+
22
+
23
+ @given(phrase('the "{name}" integration can\'t be reached'))
24
+ def cant_be_reached(pubtest_ctx, name):
25
+ """NAME is a plugin's id, or a prefix: "github" is every github.* plugin."""
26
+ tape(pubtest_ctx).fault(name, "no-answer")
27
+
28
+
29
+ @given(phrase('the "{name}" integration does not answer in time'))
30
+ def not_in_time(pubtest_ctx, name):
31
+ tape(pubtest_ctx).fault(name, f"slow {NEVER}")
32
+
33
+
34
+ @given(phrase('the "{name}" integration answers "{request}" with {status:d} and:'))
35
+ def answers_with_body(pubtest_ctx, name, request, status, docstring):
36
+ """REQUEST is "METHOD PATH", PATH a pattern in which * is anything."""
37
+ tape(pubtest_ctx).fault(name, f"status {status}", where=request, body=docstring)
38
+
39
+
40
+ @given(phrase('the "{name}" integration answers with {status:d}, then as recorded'))
41
+ def answers_then_recorded(pubtest_ctx, name, status):
42
+ tape(pubtest_ctx).fault(name, f"status {status}", nth="first")
43
+
44
+
45
+ @given(phrase('the "{name}" integration answers with what is not JSON'))
46
+ def not_json(pubtest_ctx, name):
47
+ tape(pubtest_ctx).fault(name, "malformed")
48
+
49
+
50
+ @given(phrase('the cassette of "{scenario}"'))
51
+ def cassette_of(pubtest_ctx, scenario):
52
+ tape(pubtest_ctx).borrow(scenario)
53
+
54
+
55
+ @then(phrase("the Caller slept {seconds} seconds"))
56
+ def slept(pubtest_ctx, seconds):
57
+ got = tape(pubtest_ctx).clock.slept
58
+ assert abs(got - float(seconds)) < 1e-9, f"the Caller slept {got:g} seconds"
59
+
60
+
61
+ @then(phrase('"{name}" was called {count:d} times'))
62
+ def called(pubtest_ctx, name, count):
63
+ """Each try counts: a call tried three times was called three times."""
64
+ made = [p for p, _ in tape(pubtest_ctx).requests if cassettes.matches_name(name, p)]
65
+ assert len(made) == count, f"{name} was called {len(made)} times: {tape(pubtest_ctx).requests}"
@@ -0,0 +1,186 @@
1
+ """Programs: the one under test, run as a person runs it."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import shlex
8
+ from typing import Any
9
+
10
+ import pytest
11
+ from pytest_bdd import given, then, when
12
+
13
+ from ..core import Completed, Result, dig, matches, program, same, show
14
+ from . import phrase
15
+ from .result import Current, outcome
16
+
17
+
18
+ def _text(result: Any, stream: str) -> str:
19
+ raw = getattr(result, stream)
20
+ return raw.decode("utf-8", "replace") if isinstance(raw, bytes) else raw
21
+
22
+
23
+ def _code(result: Any) -> int:
24
+ code = getattr(result, "code", None)
25
+ return result.returncode if code is None else code
26
+
27
+
28
+ def _show(result: Any) -> str:
29
+ if isinstance(result, (Completed, Result)):
30
+ return result.describe()
31
+ return f"exit {_code(result)}\nstdout: {_text(result, 'stdout')!r}\nstderr: {_text(result, 'stderr')!r}"
32
+
33
+
34
+ @given(phrase('the program under test is "{name}"'))
35
+ def under_test(pubtest_ctx, name):
36
+ try:
37
+ pubtest_ctx.programs = {**getattr(pubtest_ctx, "programs", {}), name: str(program(name))}
38
+ except LookupError as e:
39
+ pytest.fail(str(e))
40
+
41
+
42
+ def run_command(pubtest_ctx, command: str, stdin: str | None) -> Result:
43
+ """CMD's first word is the program under test of that name, from its
44
+ _BIN_DIR, when a Given named it; otherwise it is found on PATH, stand-ins
45
+ first. It runs for at most 120 seconds."""
46
+ from ..plugin import run_program # noqa: PLC0415
47
+ argv = shlex.split(command)
48
+ argv[0] = getattr(pubtest_ctx, "programs", {}).get(argv[0], argv[0])
49
+ env = {}
50
+ if getattr(pubtest_ctx, "standins", None) is not None:
51
+ env["PATH"] = pubtest_ctx.standins.path()
52
+ pubtest_ctx.acting()
53
+ done = run_program(argv, stdin, pubtest_ctx.directory or os.getcwd(), env, 120)
54
+ return pubtest_ctx.ran(Result(code=done.code, stdout=done.stdout, stderr=done.stderr, argv=done.argv))
55
+
56
+
57
+ # The result fixture is the context's own again, after a suite's step that
58
+ # set it: later steps read this run.
59
+ @when(phrase('I run "{command}"'), target_fixture="result")
60
+ def i_run(pubtest_ctx, command):
61
+ run_command(pubtest_ctx, command, None)
62
+ return Current(pubtest_ctx)
63
+
64
+
65
+ @when(phrase('I run "{command}" with the input:'), target_fixture="result")
66
+ def i_run_with_input(pubtest_ctx, command, docstring):
67
+ run_command(pubtest_ctx, command, docstring + "\n")
68
+ return Current(pubtest_ctx)
69
+
70
+
71
+ def _read(pubtest_ctx) -> None:
72
+ """A step that reads the exit code reads a refusal too."""
73
+ pubtest_ctx.refusal_read = True
74
+
75
+
76
+ def _lines(run: Any, stream: str) -> list[str]:
77
+ return _text(run, stream).splitlines()
78
+
79
+
80
+ @then("it succeeds")
81
+ def it_succeeds(pubtest_ctx, result):
82
+ _read(pubtest_ctx)
83
+ run = outcome(pubtest_ctx, result)
84
+ assert _code(run) == 0, _show(run)
85
+
86
+
87
+ @then("it fails")
88
+ def it_fails(pubtest_ctx, result):
89
+ _read(pubtest_ctx)
90
+ run = outcome(pubtest_ctx, result)
91
+ assert _code(run) != 0, _show(run)
92
+
93
+
94
+ @then(phrase("the exit code is {code:d}"))
95
+ def exit_code_is(pubtest_ctx, result, code):
96
+ _read(pubtest_ctx)
97
+ run = outcome(pubtest_ctx, result)
98
+ assert _code(run) == code, _show(run)
99
+
100
+
101
+ @then(phrase('it prints "{text}"'))
102
+ def it_prints(pubtest_ctx, result, text):
103
+ run = outcome(pubtest_ctx, result)
104
+ assert text in _text(run, "stdout"), _show(run)
105
+
106
+
107
+ @then(phrase('it does not print "{text}"'))
108
+ def it_does_not_print(pubtest_ctx, result, text):
109
+ run = outcome(pubtest_ctx, result)
110
+ assert text not in _text(run, "stdout"), _show(run)
111
+
112
+
113
+ @then("it prints:")
114
+ def it_prints_exactly(pubtest_ctx, result, docstring):
115
+ run = outcome(pubtest_ctx, result)
116
+ assert _text(run, "stdout").removesuffix("\n") == docstring.removesuffix("\n"), _show(run)
117
+
118
+
119
+ @then("stdout is empty")
120
+ def stdout_is_empty(pubtest_ctx, result):
121
+ run = outcome(pubtest_ctx, result)
122
+ assert _text(run, "stdout") == "", _show(run)
123
+
124
+
125
+ @then("stderr is empty")
126
+ def stderr_is_empty(pubtest_ctx, result):
127
+ run = outcome(pubtest_ctx, result)
128
+ assert _text(run, "stderr") == "", _show(run)
129
+
130
+
131
+ @then(phrase('stderr mentions "{text}"'))
132
+ def stderr_mentions(pubtest_ctx, result, text):
133
+ run = outcome(pubtest_ctx, result)
134
+ assert text in _text(run, "stderr"), _show(run)
135
+
136
+
137
+ @then(phrase('stderr does not mention "{text}"'))
138
+ def stderr_does_not_mention(pubtest_ctx, result, text):
139
+ run = outcome(pubtest_ctx, result)
140
+ assert text not in _text(run, "stderr"), _show(run)
141
+
142
+
143
+ def _printed_json(run: Any) -> Any:
144
+ try:
145
+ return json.loads(_text(run, "stdout"))
146
+ except ValueError as e:
147
+ raise AssertionError(f"it printed no JSON\n{_show(run)}") from e
148
+
149
+
150
+ @then("it prints the JSON:")
151
+ def it_prints_json(pubtest_ctx, result, docstring):
152
+ got = _printed_json(outcome(pubtest_ctx, result))
153
+ assert same(got, docstring), f"it printed {show(got)}, not:\n{docstring}"
154
+
155
+
156
+ @then(phrase('the JSON it prints has "{key}" equal to "{wanted}"'))
157
+ def printed_json_key(pubtest_ctx, result, key, wanted):
158
+ got = dig(_printed_json(outcome(pubtest_ctx, result)), key)
159
+ assert same(got, wanted), f"the {key} it printed is {show(got)}, not {wanted}"
160
+
161
+
162
+ @then(phrase('it prints a line matching "{pattern}"'))
163
+ def prints_line_matching(pubtest_ctx, result, pattern):
164
+ run = outcome(pubtest_ctx, result)
165
+ assert any(matches(pattern, line) for line in _lines(run, "stdout")), f"no line matches {pattern!r}\n{_show(run)}"
166
+
167
+
168
+ @then(phrase('it prints no line matching "{pattern}"'))
169
+ def prints_no_line_matching(pubtest_ctx, result, pattern):
170
+ run = outcome(pubtest_ctx, result)
171
+ found = [line for line in _lines(run, "stdout") if matches(pattern, line)]
172
+ assert not found, f"lines match {pattern!r}: {found}\n{_show(run)}"
173
+
174
+
175
+ @then(phrase('stderr has a line matching "{pattern}"'))
176
+ def stderr_line_matching(pubtest_ctx, result, pattern):
177
+ run = outcome(pubtest_ctx, result)
178
+ assert any(matches(pattern, line) for line in _lines(run, "stderr")), \
179
+ f"no line of stderr matches {pattern!r}\n{_show(run)}"
180
+
181
+
182
+ @then(phrase('stderr has no line matching "{pattern}"'))
183
+ def stderr_no_line_matching(pubtest_ctx, result, pattern):
184
+ run = outcome(pubtest_ctx, result)
185
+ found = [line for line in _lines(run, "stderr") if matches(pattern, line)]
186
+ assert not found, f"lines of stderr match {pattern!r}: {found}\n{_show(run)}"