pytest-big-dill 0.1.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.
- pytest_big_dill/__init__.py +4 -0
- pytest_big_dill/__main__.py +43 -0
- pytest_big_dill/bridge.py +254 -0
- pytest_big_dill/docstring_utils.py +57 -0
- pytest_big_dill/hooks.py +340 -0
- pytest_big_dill/hookspec.py +110 -0
- pytest_big_dill/lint_runner.py +87 -0
- pytest_big_dill/lint_types.py +45 -0
- pytest_big_dill/metadata_gen.py +67 -0
- pytest_big_dill/step_registry.py +182 -0
- pytest_big_dill/step_types.py +50 -0
- pytest_big_dill-0.1.0.dist-info/METADATA +119 -0
- pytest_big_dill-0.1.0.dist-info/RECORD +16 -0
- pytest_big_dill-0.1.0.dist-info/WHEEL +4 -0
- pytest_big_dill-0.1.0.dist-info/entry_points.txt +5 -0
- pytest_big_dill-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""Run pytest for a specific set of tests, read from a file.
|
|
2
|
+
|
|
3
|
+
python -m pytest_big_dill [pytest args...]
|
|
4
|
+
|
|
5
|
+
Test node ids come from the file named by ``BIG_DILL_TEST_IDS`` rather than the
|
|
6
|
+
command line, because Windows caps a command line at roughly 32,000 characters —
|
|
7
|
+
a few hundred BDD scenarios is enough to exceed it, and the failure mode is an
|
|
8
|
+
opaque OS error rather than anything actionable.
|
|
9
|
+
|
|
10
|
+
Without that variable this is simply ``pytest``, so the module is usable by hand.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import os
|
|
16
|
+
import sys
|
|
17
|
+
|
|
18
|
+
import pytest
|
|
19
|
+
|
|
20
|
+
TEST_IDS_ENV = "BIG_DILL_TEST_IDS"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def read_test_ids(path: str) -> list[str]:
|
|
24
|
+
with open(path, encoding="utf-8") as handle:
|
|
25
|
+
return [line.strip() for line in handle if line.strip()]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def main(argv: list[str] | None = None) -> int:
|
|
29
|
+
args = list(argv if argv is not None else sys.argv[1:])
|
|
30
|
+
|
|
31
|
+
ids_file = os.environ.get(TEST_IDS_ENV)
|
|
32
|
+
if ids_file:
|
|
33
|
+
try:
|
|
34
|
+
args.extend(read_test_ids(ids_file))
|
|
35
|
+
except OSError as error:
|
|
36
|
+
print(f"big-dill: cannot read test ids from {ids_file}: {error}", file=sys.stderr)
|
|
37
|
+
return 2
|
|
38
|
+
|
|
39
|
+
return pytest.main(args)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
if __name__ == "__main__":
|
|
43
|
+
sys.exit(main())
|
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
"""IPC bridge between pytest and a host such as the Big Dill VS Code extension.
|
|
2
|
+
|
|
3
|
+
The host creates a named pipe (Windows) or Unix domain socket, passes its path in
|
|
4
|
+
``TEST_RUN_PIPE``, and reads content-length framed JSON-RPC from it. This module
|
|
5
|
+
is the writing half, plus the discovery and execution payloads themselves.
|
|
6
|
+
|
|
7
|
+
Wire format, one frame per message::
|
|
8
|
+
|
|
9
|
+
content-length: <N>\\r\\n
|
|
10
|
+
content-type: application/json\\r\\n
|
|
11
|
+
\\r\\n
|
|
12
|
+
{"jsonrpc": "2.0", "params": <payload>}
|
|
13
|
+
|
|
14
|
+
``N`` counts characters rather than bytes. That is only safe because
|
|
15
|
+
``json.dumps`` escapes non-ASCII by default, making the two equal — do not pass
|
|
16
|
+
``ensure_ascii=False`` without changing the reader to match, or a single accented
|
|
17
|
+
character in a scenario name will desynchronise the stream.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import atexit
|
|
23
|
+
import json
|
|
24
|
+
import os
|
|
25
|
+
import sys
|
|
26
|
+
from typing import Any
|
|
27
|
+
|
|
28
|
+
TEST_RUN_PIPE_ENV = "TEST_RUN_PIPE"
|
|
29
|
+
|
|
30
|
+
_writer: Any = None
|
|
31
|
+
_errors: list[str] = []
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def pipe_path() -> str | None:
|
|
35
|
+
"""Path of the host's pipe, or None when running outside a host."""
|
|
36
|
+
return os.environ.get(TEST_RUN_PIPE_ENV) or None
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def record_error(message: str) -> None:
|
|
40
|
+
"""Note an error to be reported with the next payload."""
|
|
41
|
+
_errors.append(message)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def collected_errors() -> list[str]:
|
|
45
|
+
return list(_errors)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _open_pipe(path: str):
|
|
49
|
+
"""Connect to the host's pipe.
|
|
50
|
+
|
|
51
|
+
Windows named pipes behave as files; everywhere else the host creates a Unix
|
|
52
|
+
domain socket, which has to be connected rather than opened.
|
|
53
|
+
"""
|
|
54
|
+
if sys.platform == "win32":
|
|
55
|
+
return open(path, "wb") # noqa: SIM115, PTH123
|
|
56
|
+
|
|
57
|
+
import socket
|
|
58
|
+
|
|
59
|
+
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
|
60
|
+
sock.connect(path)
|
|
61
|
+
return sock.makefile("wb")
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _close_writer() -> None:
|
|
65
|
+
global _writer
|
|
66
|
+
if _writer is not None:
|
|
67
|
+
try:
|
|
68
|
+
_writer.close()
|
|
69
|
+
except Exception: # noqa: BLE001 - closing must never raise at exit
|
|
70
|
+
pass
|
|
71
|
+
_writer = None
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
atexit.register(_close_writer)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def send_message(payload: dict) -> None:
|
|
78
|
+
"""Send one payload to the host. A no-op when no pipe is configured.
|
|
79
|
+
|
|
80
|
+
Failures are reported on stderr and swallowed: a broken pipe should not fail
|
|
81
|
+
the user's test run, and the host treats a missing payload as an error
|
|
82
|
+
already.
|
|
83
|
+
"""
|
|
84
|
+
path = pipe_path()
|
|
85
|
+
if not path:
|
|
86
|
+
return
|
|
87
|
+
|
|
88
|
+
global _writer
|
|
89
|
+
if _writer is None:
|
|
90
|
+
try:
|
|
91
|
+
_writer = _open_pipe(path)
|
|
92
|
+
except Exception as error: # noqa: BLE001 - reported, not raised
|
|
93
|
+
print(f"big-dill: cannot connect to {path}: {error}", file=sys.stderr)
|
|
94
|
+
return
|
|
95
|
+
|
|
96
|
+
# ensure_ascii keeps character count equal to byte count — see module docstring.
|
|
97
|
+
data = json.dumps({"jsonrpc": "2.0", "params": payload}, ensure_ascii=True)
|
|
98
|
+
frame = (
|
|
99
|
+
f"content-length: {len(data)}\r\n"
|
|
100
|
+
f"content-type: application/json\r\n"
|
|
101
|
+
f"\r\n"
|
|
102
|
+
f"{data}"
|
|
103
|
+
).encode()
|
|
104
|
+
|
|
105
|
+
try:
|
|
106
|
+
written = 0
|
|
107
|
+
while written < len(frame):
|
|
108
|
+
written += _writer.write(frame[written : written + 4096])
|
|
109
|
+
_writer.flush()
|
|
110
|
+
except Exception as error: # noqa: BLE001 - reported, not raised
|
|
111
|
+
print(f"big-dill: failed sending payload: {error}", file=sys.stderr)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
# ── Payload construction ────────────────────────────────────────────────────
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _line_of(item) -> int:
|
|
118
|
+
"""1-based line of a test item, or 0 when pytest does not report one."""
|
|
119
|
+
location = getattr(item, "location", None)
|
|
120
|
+
if location and len(location) > 1 and isinstance(location[1], int):
|
|
121
|
+
# pytest reports a 0-based line here; the wire contract is 1-based.
|
|
122
|
+
return location[1] + 1
|
|
123
|
+
return 0
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def discovery_item(item, rootdir: str) -> dict:
|
|
127
|
+
"""One collected test as a wire item.
|
|
128
|
+
|
|
129
|
+
BDD metadata is attached during collection by the plugin's
|
|
130
|
+
``pytest_collection_modifyitems``; plain pytest items simply lack it and the
|
|
131
|
+
host renders them under a file hierarchy instead.
|
|
132
|
+
"""
|
|
133
|
+
node: dict[str, Any] = {
|
|
134
|
+
"path": str(getattr(item, "fspath", "") or ""),
|
|
135
|
+
"name": item.name,
|
|
136
|
+
"type_": "test",
|
|
137
|
+
"id_": item.nodeid,
|
|
138
|
+
"lineno": _line_of(item),
|
|
139
|
+
"runID": item.nodeid,
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
feature_path = getattr(item, "_bdd_feature_path", None)
|
|
143
|
+
if feature_path is not None:
|
|
144
|
+
node["feature_path"] = feature_path
|
|
145
|
+
# A BDD item is displayed against its .feature file, so its line must come
|
|
146
|
+
# from there rather than from the Python test function.
|
|
147
|
+
bdd_line = getattr(item, "_bdd_line_number", None)
|
|
148
|
+
if isinstance(bdd_line, int):
|
|
149
|
+
node["lineno"] = bdd_line
|
|
150
|
+
node["scenario_name"] = getattr(item, "_bdd_scenario_name", item.name)
|
|
151
|
+
scenario_tags = getattr(item, "_bdd_scenario_tags", None)
|
|
152
|
+
if scenario_tags:
|
|
153
|
+
node["scenario_tags"] = list(scenario_tags)
|
|
154
|
+
feature_tags = getattr(item, "_bdd_feature_tags", None)
|
|
155
|
+
if feature_tags:
|
|
156
|
+
node["feature_tags"] = list(feature_tags)
|
|
157
|
+
feature_name = getattr(item, "_bdd_feature_name", None)
|
|
158
|
+
if feature_name:
|
|
159
|
+
node["feature_name"] = feature_name
|
|
160
|
+
|
|
161
|
+
return node
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def discovery_payload(items, rootdir: str) -> dict:
|
|
165
|
+
"""The full discovery payload.
|
|
166
|
+
|
|
167
|
+
Items are emitted flat beneath a single root. The host derives the folder
|
|
168
|
+
hierarchy from each item's ``feature_path``, so nesting them here would be
|
|
169
|
+
redundant — and would have to agree with that derivation.
|
|
170
|
+
"""
|
|
171
|
+
return {
|
|
172
|
+
"cwd": rootdir,
|
|
173
|
+
"status": "error" if _errors else "success",
|
|
174
|
+
"tests": {
|
|
175
|
+
"path": rootdir,
|
|
176
|
+
"name": os.path.basename(rootdir.rstrip(os.sep)) or rootdir,
|
|
177
|
+
"type_": "folder",
|
|
178
|
+
"id_": rootdir,
|
|
179
|
+
"children": [discovery_item(item, rootdir) for item in items],
|
|
180
|
+
},
|
|
181
|
+
"error": list(_errors),
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def execution_payload(results: dict[str, dict], rootdir: str, not_found: list[str] | None = None) -> dict:
|
|
186
|
+
"""The full execution payload."""
|
|
187
|
+
payload: dict[str, Any] = {
|
|
188
|
+
"cwd": rootdir,
|
|
189
|
+
"status": "error" if _errors else "success",
|
|
190
|
+
"result": results,
|
|
191
|
+
"error": "\n".join(_errors),
|
|
192
|
+
}
|
|
193
|
+
if not_found:
|
|
194
|
+
payload["notFound"] = not_found
|
|
195
|
+
return payload
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def outcome_of(report) -> str:
|
|
199
|
+
"""Map a pytest report onto the wire's outcome vocabulary.
|
|
200
|
+
|
|
201
|
+
xfail and xpass are deliberately not special-cased: an expected failure is
|
|
202
|
+
reported by pytest as skipped, and an unexpected pass as failed, which is
|
|
203
|
+
what a reader should see.
|
|
204
|
+
"""
|
|
205
|
+
if report.outcome == "passed":
|
|
206
|
+
return "success"
|
|
207
|
+
if report.outcome == "skipped":
|
|
208
|
+
return "skipped"
|
|
209
|
+
return "failure" if report.when == "call" else "error"
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def result_entry(report) -> dict:
|
|
213
|
+
"""One test's result. ``custom_status`` is attached by the plugin's hooks."""
|
|
214
|
+
entry: dict[str, Any] = {
|
|
215
|
+
"test": report.nodeid,
|
|
216
|
+
"outcome": outcome_of(report),
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
if report.longrepr is not None:
|
|
220
|
+
text = str(report.longrepr)
|
|
221
|
+
entry["message"] = text
|
|
222
|
+
entry["traceback"] = text
|
|
223
|
+
|
|
224
|
+
custom = getattr(report, "vscode_custom_status", None)
|
|
225
|
+
if custom is not None:
|
|
226
|
+
entry["custom_status"] = custom
|
|
227
|
+
|
|
228
|
+
return entry
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def record_report(results: dict[str, dict], report) -> None:
|
|
232
|
+
"""Fold one phase report into the accumulated results.
|
|
233
|
+
|
|
234
|
+
pytest emits setup, call and teardown reports per test. The call phase is
|
|
235
|
+
what a reader wants when it happened; a setup failure means the test never
|
|
236
|
+
ran and is an error; a setup skip is how skipif and fixtures signal skipped.
|
|
237
|
+
Teardown only overwrites when it failed and nothing worse was recorded, so a
|
|
238
|
+
passing test with a broken fixture teardown still surfaces.
|
|
239
|
+
"""
|
|
240
|
+
nodeid = report.nodeid
|
|
241
|
+
existing = results.get(nodeid)
|
|
242
|
+
|
|
243
|
+
if report.when == "call":
|
|
244
|
+
results[nodeid] = result_entry(report)
|
|
245
|
+
return
|
|
246
|
+
|
|
247
|
+
if report.failed:
|
|
248
|
+
# A call result already describes the test better than a teardown error.
|
|
249
|
+
if existing is None or existing.get("outcome") == "success":
|
|
250
|
+
results[nodeid] = result_entry(report)
|
|
251
|
+
return
|
|
252
|
+
|
|
253
|
+
if report.when == "setup" and report.skipped and existing is None:
|
|
254
|
+
results[nodeid] = result_entry(report)
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""Utility functions for extracting structured information from docstrings."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import re
|
|
5
|
+
|
|
6
|
+
_SECTION_RE = re.compile(r'^[ \t]*([A-Z][A-Za-z]*):\s*$', re.MULTILINE)
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def get_summary(docstring: str | None) -> str | None:
|
|
10
|
+
"""Return the first non-empty line before any section header, stripped of whitespace.
|
|
11
|
+
|
|
12
|
+
Returns None if no such line exists (empty docstring, or docstring starts
|
|
13
|
+
with a section header like ``Tags:``).
|
|
14
|
+
"""
|
|
15
|
+
if not docstring:
|
|
16
|
+
return None
|
|
17
|
+
for line in docstring.splitlines():
|
|
18
|
+
# Stop at the first section header — summary must precede sections
|
|
19
|
+
if _SECTION_RE.match(line):
|
|
20
|
+
return None
|
|
21
|
+
stripped = line.strip()
|
|
22
|
+
if stripped:
|
|
23
|
+
return stripped
|
|
24
|
+
return None
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def parse_tags(docstring: str | None) -> list[str]:
|
|
28
|
+
"""Extract the Tags: section from a Google-style docstring.
|
|
29
|
+
|
|
30
|
+
Returns a list of lowercased, whitespace-stripped tag strings.
|
|
31
|
+
"""
|
|
32
|
+
if not docstring:
|
|
33
|
+
return []
|
|
34
|
+
|
|
35
|
+
lines = docstring.splitlines()
|
|
36
|
+
tags_start: int | None = None
|
|
37
|
+
for i, line in enumerate(lines):
|
|
38
|
+
if re.match(r'^[ \t]*Tags:\s*$', line):
|
|
39
|
+
tags_start = i
|
|
40
|
+
break
|
|
41
|
+
|
|
42
|
+
if tags_start is None:
|
|
43
|
+
return []
|
|
44
|
+
|
|
45
|
+
body_lines: list[str] = []
|
|
46
|
+
for line in lines[tags_start + 1:]:
|
|
47
|
+
if _SECTION_RE.match(line):
|
|
48
|
+
break
|
|
49
|
+
body_lines.append(line)
|
|
50
|
+
|
|
51
|
+
tags: list[str] = []
|
|
52
|
+
for line in body_lines:
|
|
53
|
+
for part in line.split(','):
|
|
54
|
+
tag = part.strip().lower()
|
|
55
|
+
if tag:
|
|
56
|
+
tags.append(tag)
|
|
57
|
+
return tags
|
pytest_big_dill/hooks.py
ADDED
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
"""pytest hooks for the Big Dill test runner plugin."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
import pytest
|
|
7
|
+
|
|
8
|
+
from . import bridge
|
|
9
|
+
from .hookspec import BigDillHookSpec
|
|
10
|
+
from .lint_runner import interpolate_scenario, validate_step_params
|
|
11
|
+
from .lint_types import LintDiagnostic
|
|
12
|
+
from .step_registry import collect_step_definitions, collect_step_type_classes
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def pytest_configure(config):
|
|
16
|
+
config.pluginmanager.add_hookspecs(BigDillHookSpec)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def pytest_addoption(parser):
|
|
20
|
+
parser.addoption(
|
|
21
|
+
"--bdd-lint",
|
|
22
|
+
nargs="?",
|
|
23
|
+
const="__all__",
|
|
24
|
+
default=None,
|
|
25
|
+
metavar="FILE",
|
|
26
|
+
help="Lint .feature files for parameter errors and scenario rule violations.",
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def pytest_collection_modifyitems(session, config, items):
|
|
31
|
+
"""Attach BDD metadata to pytest-bdd items and resolve custom display names."""
|
|
32
|
+
for item in items:
|
|
33
|
+
# pytest-bdd 8.x stores the ScenarioTemplate on the test function as __scenario__
|
|
34
|
+
obj = getattr(item, "_obj", None)
|
|
35
|
+
scenario = getattr(obj, "__scenario__", None)
|
|
36
|
+
|
|
37
|
+
if scenario is None:
|
|
38
|
+
continue # not a pytest-bdd item
|
|
39
|
+
|
|
40
|
+
# Resolve both sides before comparing. If one is reached through a symlink
|
|
41
|
+
# and the other is not — a workspace opened via a link, or macOS's
|
|
42
|
+
# /tmp -> /private/tmp — relpath yields "../real/features/x.feature", and
|
|
43
|
+
# the host then builds folder nodes called ".." and resolves URIs outside
|
|
44
|
+
# the workspace.
|
|
45
|
+
feature_path = os.path.relpath(
|
|
46
|
+
os.path.realpath(scenario.feature.filename),
|
|
47
|
+
os.path.realpath(str(config.rootdir)),
|
|
48
|
+
)
|
|
49
|
+
item._bdd_feature_path = feature_path
|
|
50
|
+
item._bdd_scenario_name = scenario.name # default: plain scenario name
|
|
51
|
+
|
|
52
|
+
# pytest-bdd 8.x stores example row values under the '_pytest_bdd_example'
|
|
53
|
+
# key inside callspec.params, not at the top level.
|
|
54
|
+
raw_params = item.callspec.params if hasattr(item, "callspec") else {}
|
|
55
|
+
example_params = raw_params.get('_pytest_bdd_example', {})
|
|
56
|
+
|
|
57
|
+
# Call the user-defined hook — first non-None result wins (firstresult=True)
|
|
58
|
+
custom_name = config.hook.pytest_big_dill_test_name(
|
|
59
|
+
scenario_name=scenario.name,
|
|
60
|
+
example_params=example_params,
|
|
61
|
+
feature_name=scenario.feature.name,
|
|
62
|
+
feature_path=feature_path,
|
|
63
|
+
)
|
|
64
|
+
if custom_name is not None:
|
|
65
|
+
item.name = custom_name
|
|
66
|
+
item._bdd_scenario_name = custom_name
|
|
67
|
+
# item.nodeid is intentionally left unchanged — used for execution tracking
|
|
68
|
+
|
|
69
|
+
# The host anchors this item at the .feature file, so the line must be the
|
|
70
|
+
# Scenario keyword's line there — not location[1], which is the line of the
|
|
71
|
+
# scenarios() call in the Python file. Getting this wrong puts gutter icons
|
|
72
|
+
# on an unrelated line, or past the end of the file.
|
|
73
|
+
line_number = getattr(scenario, "line_number", None)
|
|
74
|
+
if isinstance(line_number, int):
|
|
75
|
+
item._bdd_line_number = line_number
|
|
76
|
+
|
|
77
|
+
_attach_bdd_tags(item, scenario, example_params)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _send_execution_results(session) -> None:
|
|
81
|
+
"""Report results to the host, unless this was a discovery-only run.
|
|
82
|
+
|
|
83
|
+
Tests that were selected but produced no report — a crash during collection,
|
|
84
|
+
say — are reported as notFound so the host can mark them rather than leave
|
|
85
|
+
them silently pending.
|
|
86
|
+
"""
|
|
87
|
+
if not bridge.pipe_path() or session.config.getoption("--collect-only", default=False):
|
|
88
|
+
return
|
|
89
|
+
|
|
90
|
+
selected = [item.nodeid for item in getattr(session, "items", [])]
|
|
91
|
+
not_found = [nodeid for nodeid in selected if nodeid not in _results]
|
|
92
|
+
|
|
93
|
+
bridge.send_message(
|
|
94
|
+
bridge.execution_payload(_results, str(session.config.rootdir), not_found)
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _attach_bdd_tags(item, scenario, example_params) -> None:
|
|
99
|
+
"""Record the tags and feature name a host needs to label this item.
|
|
100
|
+
|
|
101
|
+
A Scenario Outline row carries the tags of the *specific* Examples block it
|
|
102
|
+
came from, as well as the scenario's own, so `@alpha_examples` on one block
|
|
103
|
+
does not leak onto rows from another. The row is identified by matching its
|
|
104
|
+
parameter values, since pytest-bdd does not record which block produced it.
|
|
105
|
+
"""
|
|
106
|
+
tags = set(getattr(scenario, "tags", set()) or set())
|
|
107
|
+
|
|
108
|
+
if example_params:
|
|
109
|
+
for block in getattr(scenario, "examples", []) or []:
|
|
110
|
+
names = getattr(block, "example_params", [])
|
|
111
|
+
for row in getattr(block, "examples", []) or []:
|
|
112
|
+
# strict=False matches the convention below: a ragged Examples
|
|
113
|
+
# table is a lint concern, not a reason to fail collection.
|
|
114
|
+
if dict(zip(names, row, strict=False)) == example_params:
|
|
115
|
+
tags |= set(getattr(block, "tags", set()) or set())
|
|
116
|
+
break
|
|
117
|
+
|
|
118
|
+
if tags:
|
|
119
|
+
item._bdd_scenario_tags = sorted(tags)
|
|
120
|
+
|
|
121
|
+
feature = getattr(scenario, "feature", None)
|
|
122
|
+
if feature is not None:
|
|
123
|
+
if getattr(feature, "tags", None):
|
|
124
|
+
item._bdd_feature_tags = sorted(feature.tags)
|
|
125
|
+
if getattr(feature, "name", None):
|
|
126
|
+
item._bdd_feature_name = feature.name
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
@pytest.hookimpl(hookwrapper=True)
|
|
130
|
+
def pytest_runtest_makereport(item, call):
|
|
131
|
+
"""Call pytest_big_dill_custom_status and surface the result on the report."""
|
|
132
|
+
outcome = yield
|
|
133
|
+
report = outcome.get_result()
|
|
134
|
+
|
|
135
|
+
custom = item.config.hook.pytest_big_dill_custom_status(report=report, config=item.config)
|
|
136
|
+
if custom is not None:
|
|
137
|
+
report.vscode_custom_status = custom
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def pytest_sessionfinish(session, exitstatus):
|
|
141
|
+
_send_execution_results(session)
|
|
142
|
+
|
|
143
|
+
opt = session.config.getoption("--bdd-lint", default=None)
|
|
144
|
+
if opt is None:
|
|
145
|
+
return
|
|
146
|
+
|
|
147
|
+
step_defs = collect_step_definitions(session)
|
|
148
|
+
step_types = collect_step_type_classes()
|
|
149
|
+
|
|
150
|
+
# Determine which feature files to lint
|
|
151
|
+
if opt == "__all__":
|
|
152
|
+
# First try to discover from collected BDD items
|
|
153
|
+
from_items = {
|
|
154
|
+
Path(session.config.rootdir) / item._bdd_feature_path
|
|
155
|
+
for item in session.items
|
|
156
|
+
if hasattr(item, '_bdd_feature_path')
|
|
157
|
+
}
|
|
158
|
+
if from_items:
|
|
159
|
+
feature_files = list(from_items)
|
|
160
|
+
else:
|
|
161
|
+
# Fall back: scan rootdir for all .feature files
|
|
162
|
+
rootdir = Path(session.config.rootdir)
|
|
163
|
+
feature_files = list(rootdir.rglob("*.feature"))
|
|
164
|
+
else:
|
|
165
|
+
feature_files = [Path(opt)]
|
|
166
|
+
|
|
167
|
+
all_diagnostics: list[tuple[str, LintDiagnostic]] = []
|
|
168
|
+
for feature_path in feature_files:
|
|
169
|
+
diags = _lint_feature_file(feature_path, step_defs, step_types, session.config)
|
|
170
|
+
for d in diags:
|
|
171
|
+
all_diagnostics.append((str(feature_path), d))
|
|
172
|
+
|
|
173
|
+
_emit_lint_results(all_diagnostics, session.config)
|
|
174
|
+
|
|
175
|
+
if any(d.severity == "error" for _, d in all_diagnostics):
|
|
176
|
+
session.exitstatus = 1
|
|
177
|
+
else:
|
|
178
|
+
# Ensure a clean lint always exits 0, even if no tests were collected
|
|
179
|
+
if session.exitstatus == 5: # pytest.ExitCode.NO_TESTS_COLLECTED
|
|
180
|
+
session.exitstatus = 0
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
class _ExamplesRowsAdapter:
|
|
184
|
+
"""Wrap a pytest-bdd Examples object to expose a .rows attribute.
|
|
185
|
+
|
|
186
|
+
``.rows`` returns a list of dicts mapping column names to string values,
|
|
187
|
+
compatible with ``interpolate_scenario`` and user lint hooks.
|
|
188
|
+
"""
|
|
189
|
+
|
|
190
|
+
def __init__(self, examples_obj):
|
|
191
|
+
self._obj = examples_obj
|
|
192
|
+
# strict=False: pytest-bdd guarantees rectangular tables, and a lint pass
|
|
193
|
+
# should still produce diagnostics for a malformed feature rather than raise.
|
|
194
|
+
self.rows = [
|
|
195
|
+
dict(zip(examples_obj.example_params, row, strict=False))
|
|
196
|
+
for row in examples_obj.examples
|
|
197
|
+
]
|
|
198
|
+
|
|
199
|
+
def __getattr__(self, name):
|
|
200
|
+
return getattr(self._obj, name)
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _lint_feature_file(
|
|
204
|
+
path: Path,
|
|
205
|
+
step_defs: list[dict],
|
|
206
|
+
step_types: dict,
|
|
207
|
+
config,
|
|
208
|
+
) -> list[LintDiagnostic]:
|
|
209
|
+
"""Parse and lint a single .feature file, returning all diagnostics."""
|
|
210
|
+
try:
|
|
211
|
+
from pytest_bdd.parser import FeatureParser
|
|
212
|
+
feature = FeatureParser(basedir=str(path.parent), filename=path.name).parse()
|
|
213
|
+
except Exception as exc:
|
|
214
|
+
return [LintDiagnostic(message=f"Failed to parse {path}: {exc}")]
|
|
215
|
+
|
|
216
|
+
diagnostics: list[LintDiagnostic] = []
|
|
217
|
+
|
|
218
|
+
# feature.scenarios is an OrderedDict in pytest-bdd 8.x
|
|
219
|
+
scenarios = feature.scenarios.values() if isinstance(feature.scenarios, dict) else feature.scenarios
|
|
220
|
+
|
|
221
|
+
for scenario in scenarios:
|
|
222
|
+
has_examples = bool(getattr(scenario, 'examples', None))
|
|
223
|
+
|
|
224
|
+
# Parameter validation: every step in every scenario
|
|
225
|
+
for step in scenario.steps:
|
|
226
|
+
step_text = step.name
|
|
227
|
+
line = getattr(step, 'line_number', None)
|
|
228
|
+
for step_def in step_defs:
|
|
229
|
+
diags = validate_step_params(step_text, step_def, step_types, line_number=line)
|
|
230
|
+
diagnostics.extend(diags)
|
|
231
|
+
|
|
232
|
+
if has_examples:
|
|
233
|
+
# Wrap examples to provide .rows (list of dicts) for hook consumers
|
|
234
|
+
wrapped_examples = [_ExamplesRowsAdapter(ex) for ex in scenario.examples]
|
|
235
|
+
|
|
236
|
+
# 1. Outline-level checks (duplicates, large sets, etc.)
|
|
237
|
+
for result_list in config.hook.pytest_big_dill_lint_outline(
|
|
238
|
+
scenario=scenario, examples=wrapped_examples
|
|
239
|
+
):
|
|
240
|
+
if result_list:
|
|
241
|
+
diagnostics.extend(result_list)
|
|
242
|
+
|
|
243
|
+
# 2. Scenario-level checks applied to each interpolated row
|
|
244
|
+
for examples_block in scenario.examples:
|
|
245
|
+
for row in examples_block.as_contexts():
|
|
246
|
+
interpolated = interpolate_scenario(scenario, row)
|
|
247
|
+
for result_list in config.hook.pytest_big_dill_lint_scenario(
|
|
248
|
+
scenario=interpolated
|
|
249
|
+
):
|
|
250
|
+
if result_list:
|
|
251
|
+
diagnostics.extend(result_list)
|
|
252
|
+
else:
|
|
253
|
+
for result_list in config.hook.pytest_big_dill_lint_scenario(scenario=scenario):
|
|
254
|
+
if result_list:
|
|
255
|
+
diagnostics.extend(result_list)
|
|
256
|
+
|
|
257
|
+
return diagnostics
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def _emit_lint_results(
|
|
261
|
+
diagnostics: list[tuple[str, LintDiagnostic]],
|
|
262
|
+
config,
|
|
263
|
+
) -> None:
|
|
264
|
+
"""Route lint diagnostics to stdout (CLI) or IPC (VS Code)."""
|
|
265
|
+
if os.environ.get('TEST_RUN_PIPE'):
|
|
266
|
+
_emit_ipc(diagnostics)
|
|
267
|
+
else:
|
|
268
|
+
_emit_stdout(diagnostics)
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def _emit_stdout(diagnostics: list[tuple[str, LintDiagnostic]]) -> None:
|
|
272
|
+
if not diagnostics:
|
|
273
|
+
print("Big Dill lint: no issues found")
|
|
274
|
+
return
|
|
275
|
+
for path, d in diagnostics:
|
|
276
|
+
loc = f"{path}:{d.line}" if d.line else path
|
|
277
|
+
print(f"{d.severity.upper()}: {loc}: {d.message}")
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def _emit_ipc(diagnostics: list[tuple[str, LintDiagnostic]]) -> None:
|
|
281
|
+
"""Send lint diagnostics to VS Code via the existing IPC pipe."""
|
|
282
|
+
payload = {
|
|
283
|
+
"type": "lintDiagnostics",
|
|
284
|
+
"diagnostics": [
|
|
285
|
+
{
|
|
286
|
+
"path": path,
|
|
287
|
+
"message": d.message,
|
|
288
|
+
"severity": d.severity,
|
|
289
|
+
"line": d.line,
|
|
290
|
+
}
|
|
291
|
+
for path, d in diagnostics
|
|
292
|
+
],
|
|
293
|
+
}
|
|
294
|
+
bridge.send_message(payload)
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
# Accumulated across the run, keyed by node id.
|
|
298
|
+
_results: dict[str, dict] = {}
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def pytest_collection_finish(session) -> None:
|
|
302
|
+
"""Emit the discovered tests and step definitions to the host.
|
|
303
|
+
|
|
304
|
+
Discovery is only sent for a --collect-only run. A host asks for discovery and
|
|
305
|
+
execution separately, so emitting the tree on every test run would be wasted
|
|
306
|
+
work — and the host's execution reader accepts any frame it is given, so the
|
|
307
|
+
extra payloads arrive as empty results rather than being ignored.
|
|
308
|
+
"""
|
|
309
|
+
if not bridge.pipe_path():
|
|
310
|
+
return
|
|
311
|
+
|
|
312
|
+
if not session.config.getoption("--collect-only", default=False):
|
|
313
|
+
return
|
|
314
|
+
|
|
315
|
+
rootdir = str(session.config.rootdir)
|
|
316
|
+
bridge.send_message(bridge.discovery_payload(session.items, rootdir))
|
|
317
|
+
|
|
318
|
+
step_defs = collect_step_definitions(session)
|
|
319
|
+
if step_defs:
|
|
320
|
+
bridge.send_message({"type": "stepDefinitions", "stepDefinitions": step_defs})
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def pytest_runtest_logreport(report) -> None:
|
|
324
|
+
"""Fold each phase report into the results sent at session end."""
|
|
325
|
+
if bridge.pipe_path():
|
|
326
|
+
bridge.record_report(_results, report)
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def pytest_internalerror(excrepr, excinfo) -> None: # noqa: ARG001
|
|
330
|
+
bridge.record_error(f"pytest internal error: {excrepr}")
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def pytest_keyboard_interrupt(excinfo) -> None: # noqa: ARG001
|
|
334
|
+
bridge.record_error("run interrupted")
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def pytest_exception_interact(node, call, report) -> None: # noqa: ARG001
|
|
338
|
+
"""Record collection-time failures, which produce no test report."""
|
|
339
|
+
if report is not None and getattr(report, "when", None) == "collect":
|
|
340
|
+
bridge.record_error(f"collection error in {getattr(node, 'nodeid', node)}: {call.excinfo}")
|