@dialecte/cli 0.6.0 → 0.8.0
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.
- package/README.md +35 -2003
- package/dist/cli.js +67190 -40066
- package/dist/corpus/manifest.json +692 -0
- package/dist/corpus/overrides/fhir-xhtml.xsd +17 -0
- package/dist/corpus/overrides/xlink.xsd +102 -0
- package/dist/corpus/overrides/xml.xsd +35 -0
- package/dist/dialecte_tdd_pytest.py +792 -0
- package/dist/lookups.d.ts +367 -13
- package/dist/lookups.js +2330 -26
- package/dist/schemas/config-list.schema.json +121 -0
- package/dist/schemas/config-yml.schema.json +52 -0
- package/dist/schemas/dialecterc.schema.json +33 -0
- package/dist/schemas/lot-risk.schema.json +32 -0
- package/dist/schemas/risk-line.schema.json +49 -0
- package/dist/schemas/rules.schema.json +51 -0
- package/dist/schemas/scope-change.schema.json +103 -0
- package/dist/tdd-node-reporter.js +167 -0
- package/dist/tdd-reporter.js +2 -0
- package/package.json +43 -5
|
@@ -0,0 +1,792 @@
|
|
|
1
|
+
"""The cli's pytest plugin: writes what a run saw to the file named by DIALECTE_TDD_REPORT.
|
|
2
|
+
|
|
3
|
+
Loaded with `-p dialecte_tdd_pytest`. The report is one JSON list, one entry per test file collected: its
|
|
4
|
+
collection errors, its cases (name, state, def line, errors, source, skip mark in a collect), the files it
|
|
5
|
+
used (conftests, the modules its imports and its conftests' imports resolve to, the files opened while it was collected and while its
|
|
6
|
+
cases ran) and its own code (module-level and test-class statements, imports by what they resolve to, never the
|
|
7
|
+
test functions), and the own code of its base text when DIALECTE_TDD_BASE_TEXTS names a JSON file of base texts. Imports the standard library and pytest only; Python 3.8 or later, pytest 7 or later.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import ast
|
|
11
|
+
import copy
|
|
12
|
+
import errno
|
|
13
|
+
import fnmatch
|
|
14
|
+
import hashlib
|
|
15
|
+
import importlib.machinery
|
|
16
|
+
import importlib.util
|
|
17
|
+
import json
|
|
18
|
+
import os
|
|
19
|
+
import pathlib
|
|
20
|
+
import re
|
|
21
|
+
import sys
|
|
22
|
+
|
|
23
|
+
import pytest
|
|
24
|
+
|
|
25
|
+
REPORT_VARIABLE = "DIALECTE_TDD_REPORT"
|
|
26
|
+
NAMES_VARIABLE = "DIALECTE_TDD_NAMES"
|
|
27
|
+
ROOT_VARIABLE = "DIALECTE_TDD_ROOT"
|
|
28
|
+
BASE_TEXTS_VARIABLE = "DIALECTE_TDD_BASE_TEXTS"
|
|
29
|
+
OWN_CODE_VARIABLE = "DIALECTE_TDD_OWN_CODE"
|
|
30
|
+
# a parametrize call's literal values, which each case's row covers
|
|
31
|
+
ROWS_PLACEHOLDER = "<rows>"
|
|
32
|
+
# between the parts of an own-code identity: its scope, its kind, its target, its names
|
|
33
|
+
OWN_CODE_SEPARATOR = "\0"
|
|
34
|
+
NAME_SEPARATOR = " > "
|
|
35
|
+
ROW_SEPARATOR = "\0"
|
|
36
|
+
UNMAPPABLE_NAME_ERROR = "UnmappableCaseName"
|
|
37
|
+
UNMAPPABLE_NAME_MESSAGE = (
|
|
38
|
+
"the case name holds ' > ': it cannot be mapped back to a node id; give the parameter an id without it"
|
|
39
|
+
)
|
|
40
|
+
COLLECTION_ERROR_LINE = re.compile(r"^E\s+([A-Za-z_][\w.]*)(?::\s?(.*))?$")
|
|
41
|
+
CACHE_FOLDER = "__pycache__"
|
|
42
|
+
# the context managers that assert their body raises or warns
|
|
43
|
+
EXPECTING_CALLS = ("raises", "warns")
|
|
44
|
+
|
|
45
|
+
# what the run saw so far: the test files by path in collection order, the cases by node id, the file
|
|
46
|
+
# whose collection or case is running now (the files opened then are its), the parsed sources by path
|
|
47
|
+
RUN = {
|
|
48
|
+
"modules": {},
|
|
49
|
+
"cases": {},
|
|
50
|
+
"opening": None,
|
|
51
|
+
"trees": {},
|
|
52
|
+
"conftest_imports": {},
|
|
53
|
+
"audited": False,
|
|
54
|
+
"collect_only": False,
|
|
55
|
+
"root": None,
|
|
56
|
+
"config": None,
|
|
57
|
+
"base_texts": {},
|
|
58
|
+
"base_trees": {},
|
|
59
|
+
"collected_lines": {},
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@pytest.hookimpl(tryfirst=True)
|
|
64
|
+
def pytest_configure(config):
|
|
65
|
+
"""Turns xdist off (the cases run in this process, so these hooks see them) and starts noting opened files."""
|
|
66
|
+
if getattr(config.option, "numprocesses", None):
|
|
67
|
+
config.option.numprocesses = 0
|
|
68
|
+
if hasattr(config.option, "dist"):
|
|
69
|
+
config.option.dist = "no"
|
|
70
|
+
RUN["collect_only"] = bool(config.getoption("collectonly"))
|
|
71
|
+
RUN["config"] = config
|
|
72
|
+
RUN["base_texts"] = read_base_texts()
|
|
73
|
+
RUN["root"] = os.path.realpath(os.environ.get(ROOT_VARIABLE) or str(config.rootpath))
|
|
74
|
+
if not RUN["audited"]:
|
|
75
|
+
sys.addaudithook(note_opened_file)
|
|
76
|
+
RUN["audited"] = True
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def note_opened_file(event, arguments):
|
|
80
|
+
"""Audit hook: a file opened while a test file is collected or one of its cases runs is a file it used."""
|
|
81
|
+
if event != "open" or RUN["opening"] is None:
|
|
82
|
+
return
|
|
83
|
+
try:
|
|
84
|
+
path = arguments[0]
|
|
85
|
+
if isinstance(path, int):
|
|
86
|
+
return
|
|
87
|
+
RUN["modules"][RUN["opening"]]["opened"].add(os.path.abspath(os.fsdecode(path)))
|
|
88
|
+
except Exception: # noqa: BLE001 - an audit hook never breaks the open it watches
|
|
89
|
+
return
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
@pytest.hookimpl(hookwrapper=True)
|
|
93
|
+
def pytest_make_collect_report(collector):
|
|
94
|
+
"""Notes the files a test file opens while it is collected, and the error that stops its collection."""
|
|
95
|
+
if not isinstance(collector, pytest.Module):
|
|
96
|
+
yield
|
|
97
|
+
return
|
|
98
|
+
path = os.path.abspath(str(collector.path))
|
|
99
|
+
module = module_record(path)
|
|
100
|
+
RUN["opening"] = path
|
|
101
|
+
outcome = yield
|
|
102
|
+
RUN["opening"] = None
|
|
103
|
+
report = outcome.get_result()
|
|
104
|
+
if report.failed:
|
|
105
|
+
module["errors"].append(collection_error(report))
|
|
106
|
+
return
|
|
107
|
+
try:
|
|
108
|
+
module["name"] = collector.obj.__name__
|
|
109
|
+
except Exception: # noqa: BLE001 - a module that did not import has no name to follow
|
|
110
|
+
module["name"] = None
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def pytest_collection_modifyitems(session, config, items):
|
|
114
|
+
"""Leaves out the test files a conftest leaves out of discovery, then keeps only the cases DIALECTE_TDD_NAMES
|
|
115
|
+
lists (their full names), when it lists any."""
|
|
116
|
+
ignored = {path for path in RUN["modules"] if is_ignored(session=session, config=config, path=path)}
|
|
117
|
+
for path in ignored:
|
|
118
|
+
del RUN["modules"][path]
|
|
119
|
+
# every test function collected, deselected ones too: none of them is own code of its file
|
|
120
|
+
for item in items:
|
|
121
|
+
path = os.path.abspath(str(item.path))
|
|
122
|
+
node = function_node(
|
|
123
|
+
path=path,
|
|
124
|
+
classes=item.nodeid.split("::")[1:-1],
|
|
125
|
+
name=getattr(item, "originalname", None) or item.name,
|
|
126
|
+
)
|
|
127
|
+
if node is not None:
|
|
128
|
+
RUN["collected_lines"].setdefault(path, set()).add(node.lineno)
|
|
129
|
+
listed = os.environ.get(NAMES_VARIABLE)
|
|
130
|
+
names = set(json.loads(listed)) if listed else None
|
|
131
|
+
kept = [
|
|
132
|
+
item
|
|
133
|
+
for item in items
|
|
134
|
+
if os.path.abspath(str(item.path)) not in ignored and (names is None or case_name(item) in names)
|
|
135
|
+
]
|
|
136
|
+
kept_items = set(kept)
|
|
137
|
+
left = [item for item in items if item not in kept_items]
|
|
138
|
+
if left:
|
|
139
|
+
config.hook.pytest_deselected(items=left)
|
|
140
|
+
items[:] = kept
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def is_ignored(session, config, path):
|
|
144
|
+
"""pytest's own ignore hook leaves the file out of discovery (`collect_ignore`, `collect_ignore_glob`, a
|
|
145
|
+
conftest's `pytest_ignore_collect`): pytest 8 and 9 still collect a file named on the command line, which a
|
|
146
|
+
plain run of the package would never collect."""
|
|
147
|
+
collection_path = pathlib.Path(path)
|
|
148
|
+
hook = session.gethookproxy(collection_path)
|
|
149
|
+
return bool(hook.pytest_ignore_collect(collection_path=collection_path, config=config))
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def pytest_collection_finish(session):
|
|
153
|
+
"""Records each case the run holds, in collection order, under its test file."""
|
|
154
|
+
for item in session.items:
|
|
155
|
+
path = os.path.abspath(str(item.path))
|
|
156
|
+
record = case_record(item)
|
|
157
|
+
RUN["cases"][item.nodeid] = record
|
|
158
|
+
module_record(path)["cases"].append(record)
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
@pytest.hookimpl(tryfirst=True)
|
|
162
|
+
def pytest_runtest_protocol(item, nextitem):
|
|
163
|
+
"""Attributes the files opened while a case runs (setup to teardown) to its test file."""
|
|
164
|
+
RUN["opening"] = os.path.abspath(str(item.path))
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
@pytest.hookimpl(trylast=True)
|
|
168
|
+
def pytest_runtest_logfinish(nodeid, location):
|
|
169
|
+
"""Ends the attribution of opened files to the case's test file."""
|
|
170
|
+
RUN["opening"] = None
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
@pytest.hookimpl(hookwrapper=True, tryfirst=True)
|
|
174
|
+
def pytest_runtest_makereport(item, call):
|
|
175
|
+
"""Reads each phase's final report into the case's state and errors (xfail -> skipped, strict xpass -> failed)."""
|
|
176
|
+
outcome = yield
|
|
177
|
+
record = RUN["cases"].get(item.nodeid)
|
|
178
|
+
if record is None or record.get("unmappable"):
|
|
179
|
+
return
|
|
180
|
+
report = outcome.get_result()
|
|
181
|
+
if report.failed:
|
|
182
|
+
record["state"] = "failed"
|
|
183
|
+
record["errors"].append(phase_error(item=item, call=call, report=report))
|
|
184
|
+
elif report.skipped and call.when in ("setup", "call"):
|
|
185
|
+
record["state"] = "skipped"
|
|
186
|
+
elif report.passed and call.when == "call":
|
|
187
|
+
record["state"] = "passed"
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def pytest_sessionfinish(session, exitstatus):
|
|
191
|
+
"""Writes the report: the test files with their errors, cases and dependencies."""
|
|
192
|
+
path = os.environ.get(REPORT_VARIABLE)
|
|
193
|
+
if not path:
|
|
194
|
+
return
|
|
195
|
+
modules = [module_report(file, module, RUN["base_texts"]) for file, module in RUN["modules"].items()]
|
|
196
|
+
with open(path, "w", encoding="utf-8") as report:
|
|
197
|
+
json.dump(modules, report)
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def module_record(path):
|
|
201
|
+
"""The record of a test file, made on first sight."""
|
|
202
|
+
if path not in RUN["modules"]:
|
|
203
|
+
RUN["modules"][path] = {"errors": [], "cases": [], "opened": set(), "name": None}
|
|
204
|
+
return RUN["modules"][path]
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def module_report(path, module, base_texts):
|
|
208
|
+
"""A test file as the cli reads it, with the own code of its base text when one was given."""
|
|
209
|
+
text, tree = parsed(path)
|
|
210
|
+
name = module["name"] or module_name_of(path)
|
|
211
|
+
report = {
|
|
212
|
+
"file": path,
|
|
213
|
+
"runner": "pytest",
|
|
214
|
+
"errors": module["errors"],
|
|
215
|
+
"cases": [
|
|
216
|
+
{key: value for key, value in case.items() if key != "unmappable"} for case in module["cases"]
|
|
217
|
+
],
|
|
218
|
+
"dependencies": sorted(dependencies_of(path=path, module=module)),
|
|
219
|
+
}
|
|
220
|
+
if os.environ.get(OWN_CODE_VARIABLE) != "1":
|
|
221
|
+
return report
|
|
222
|
+
collected = RUN["collected_lines"].get(path, set())
|
|
223
|
+
report["ownCode"] = own_code_of(
|
|
224
|
+
path=path, text=text, tree=tree, module_name=name, is_test=lambda node: node.lineno in collected
|
|
225
|
+
)
|
|
226
|
+
base_text = base_texts.get(os.path.relpath(os.path.realpath(path), RUN["root"] or ""))
|
|
227
|
+
if base_text is not None:
|
|
228
|
+
try:
|
|
229
|
+
base_tree = ast.parse(base_text)
|
|
230
|
+
except (SyntaxError, ValueError):
|
|
231
|
+
base_tree = None
|
|
232
|
+
report["baseOwnCode"] = own_code_of(
|
|
233
|
+
path=path, text=base_text, tree=base_tree, module_name=name, is_test=is_test_by_pattern
|
|
234
|
+
)
|
|
235
|
+
return report
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def read_base_texts():
|
|
239
|
+
"""The base texts the cli gave, by path relative to the package root; none when it gave none."""
|
|
240
|
+
path = os.environ.get(BASE_TEXTS_VARIABLE)
|
|
241
|
+
if not path:
|
|
242
|
+
return {}
|
|
243
|
+
try:
|
|
244
|
+
with open(path, encoding="utf-8") as texts:
|
|
245
|
+
return {os.path.normpath(key): value for key, value in json.load(texts).items()}
|
|
246
|
+
except (OSError, ValueError, AttributeError):
|
|
247
|
+
# an unreadable file loses the base own code only, never the report
|
|
248
|
+
return {}
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def is_test_by_pattern(node):
|
|
252
|
+
"""A function of a base text is a test when pytest's `python_functions` names it and no fixture decorates it (the
|
|
253
|
+
base text did not run: its collection is not known)."""
|
|
254
|
+
return matches_option(name=node.name, option="python_functions") and not any(
|
|
255
|
+
is_fixture(decorator) for decorator in node.decorator_list
|
|
256
|
+
)
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def is_fixture(decorator):
|
|
260
|
+
"""`@fixture`, `@pytest.fixture`, called or not."""
|
|
261
|
+
called = decorator.func if isinstance(decorator, ast.Call) else decorator
|
|
262
|
+
name = called.attr if isinstance(called, ast.Attribute) else getattr(called, "id", None)
|
|
263
|
+
return name == "fixture"
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def own_code_of(path, text, tree, module_name, is_test):
|
|
267
|
+
"""The file's own code: each module-level statement and each statement of a test class body (scoped by its
|
|
268
|
+
class names), a test class's header (its decorators, bases and keywords) in the scope holding it, imports once
|
|
269
|
+
per binding by what they resolve to and their names (an import nested in a statement by its target too), never a
|
|
270
|
+
test function (`is_test`: the functions pytest collected, by their def line) nor a leading docstring; each with its text and the sha256 of its scope and identity (`ast.dump`: formatting and comments
|
|
271
|
+
left out, its output the running Python's: an interpreter changed between the red and the move refuses the move)."""
|
|
272
|
+
if tree is None:
|
|
273
|
+
return []
|
|
274
|
+
is_package = os.path.basename(path) == "__init__.py"
|
|
275
|
+
package = module_name if is_package else module_name.rpartition(".")[0]
|
|
276
|
+
statements = []
|
|
277
|
+
|
|
278
|
+
def add(scope, node, identity, shown=None):
|
|
279
|
+
statements.append(
|
|
280
|
+
{
|
|
281
|
+
"text": shown if shown is not None else ast.get_source_segment(text, node) or "",
|
|
282
|
+
"hash": hashlib.sha256(OWN_CODE_SEPARATOR.join([*scope, identity]).encode("utf-8")).hexdigest(),
|
|
283
|
+
}
|
|
284
|
+
)
|
|
285
|
+
|
|
286
|
+
def collect(body, scope):
|
|
287
|
+
for position, node in enumerate(body):
|
|
288
|
+
if position == 0 and is_docstring(node):
|
|
289
|
+
continue
|
|
290
|
+
imported = import_identities(node=node, package=package)
|
|
291
|
+
if imported is not None:
|
|
292
|
+
for identity in imported:
|
|
293
|
+
add(scope, node, identity)
|
|
294
|
+
elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and is_test(node):
|
|
295
|
+
continue
|
|
296
|
+
elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.decorator_list:
|
|
297
|
+
add(scope, node, ast.dump(resolved_imports(node=node, package=package)), shown=decorated_text(text, node))
|
|
298
|
+
elif isinstance(node, ast.ClassDef) and matches_option(name=node.name, option="python_classes"):
|
|
299
|
+
header = copy.copy(node)
|
|
300
|
+
header.body = []
|
|
301
|
+
add(scope, node, ast.dump(header), shown=class_header_text(text=text, node=node))
|
|
302
|
+
collect(node.body, [*scope, node.name])
|
|
303
|
+
else:
|
|
304
|
+
add(scope, node, ast.dump(resolved_imports(node=node, package=package)))
|
|
305
|
+
|
|
306
|
+
collect(tree.body, [])
|
|
307
|
+
return statements
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def is_docstring(node):
|
|
311
|
+
"""A string standing alone as a statement: a module's or a class's docstring when it comes first."""
|
|
312
|
+
return (
|
|
313
|
+
isinstance(node, ast.Expr) and isinstance(node.value, ast.Constant) and isinstance(node.value.value, str)
|
|
314
|
+
)
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def decorated_text(text, node):
|
|
318
|
+
"""A decorated definition as written: its decorators, then its own text."""
|
|
319
|
+
decorators = ["@" + (ast.get_source_segment(text, decorator) or "") for decorator in node.decorator_list]
|
|
320
|
+
return "\n".join([*decorators, ast.get_source_segment(text, node) or ""])
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def class_header_text(text, node):
|
|
324
|
+
"""A class's header as written: its decorators, then its `class` line."""
|
|
325
|
+
decorators = ["@" + (ast.get_source_segment(text, decorator) or "") for decorator in node.decorator_list]
|
|
326
|
+
first = (ast.get_source_segment(text, node) or "").split("\n")[0]
|
|
327
|
+
return "\n".join([*decorators, first])
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def resolved_imports(node, package):
|
|
331
|
+
"""A copy of the statement whose nested imports name what they resolve to (a relative import in a `try` hashed by
|
|
332
|
+
its file, not its spelling); the statement itself when it holds none."""
|
|
333
|
+
if not any(isinstance(inner, (ast.Import, ast.ImportFrom)) for inner in ast.walk(node)):
|
|
334
|
+
return node
|
|
335
|
+
copied = copy.deepcopy(node)
|
|
336
|
+
for inner in ast.walk(copied):
|
|
337
|
+
if isinstance(inner, ast.ImportFrom):
|
|
338
|
+
inner.module = import_target(absolute_module(node=inner, package=package))
|
|
339
|
+
inner.level = 0
|
|
340
|
+
elif isinstance(inner, ast.Import):
|
|
341
|
+
for alias in inner.names:
|
|
342
|
+
alias.asname = alias.asname or alias.name.partition(".")[0]
|
|
343
|
+
alias.name = import_target(alias.name)
|
|
344
|
+
return copied
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def absolute_module(node, package):
|
|
348
|
+
"""The module a `from ... import` names, a relative one resolved against the package; its dotted spelling when it
|
|
349
|
+
cannot be (such a module fails to import, so its cases never pass)."""
|
|
350
|
+
base = node.module or ""
|
|
351
|
+
if not node.level:
|
|
352
|
+
return base
|
|
353
|
+
try:
|
|
354
|
+
return importlib.util.resolve_name("." * node.level + base, package)
|
|
355
|
+
except (ImportError, ValueError):
|
|
356
|
+
return "." * node.level + base
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
def import_identities(node, package):
|
|
360
|
+
"""One identity per binding of an import: its kind, the file or module it resolves to, its imported and local
|
|
361
|
+
names; None for any other statement."""
|
|
362
|
+
if isinstance(node, ast.Import):
|
|
363
|
+
return [
|
|
364
|
+
OWN_CODE_SEPARATOR.join(
|
|
365
|
+
["import", import_target(alias.name), "", alias.asname or alias.name.partition(".")[0]]
|
|
366
|
+
)
|
|
367
|
+
for alias in node.names
|
|
368
|
+
]
|
|
369
|
+
if isinstance(node, ast.ImportFrom):
|
|
370
|
+
target = import_target(absolute_module(node=node, package=package))
|
|
371
|
+
return [
|
|
372
|
+
OWN_CODE_SEPARATOR.join(["import", target, alias.name, alias.asname or alias.name])
|
|
373
|
+
for alias in node.names
|
|
374
|
+
]
|
|
375
|
+
return None
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
def import_target(name):
|
|
379
|
+
"""The package file a module name resolves to (relative to the package root), else the module name itself. Never
|
|
380
|
+
imports anything: a module the run did not import is found on its parent's path only when that parent is
|
|
381
|
+
imported (or on sys.path for a top-level one)."""
|
|
382
|
+
file = getattr(sys.modules.get(name), "__file__", None)
|
|
383
|
+
if not file:
|
|
384
|
+
parent, _, last = name.rpartition(".")
|
|
385
|
+
search = getattr(sys.modules.get(parent), "__path__", None) if parent else None
|
|
386
|
+
try:
|
|
387
|
+
spec = importlib.machinery.PathFinder.find_spec(last, search) if search or not parent else None
|
|
388
|
+
except Exception: # noqa: BLE001 - a finder failing names the module by its name, never stops the report
|
|
389
|
+
spec = None
|
|
390
|
+
file = getattr(spec, "origin", None) if spec else None
|
|
391
|
+
if not file or not os.path.isfile(file):
|
|
392
|
+
return name
|
|
393
|
+
real = os.path.realpath(source_path(os.path.abspath(file)))
|
|
394
|
+
if not is_under_root(real):
|
|
395
|
+
return name
|
|
396
|
+
return pathlib.PurePath(os.path.relpath(real, RUN["root"])).as_posix()
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
def matches_option(name, option):
|
|
400
|
+
"""The name is a test function or class by pytest's `python_functions` / `python_classes`: a prefix, or a glob."""
|
|
401
|
+
config = RUN["config"]
|
|
402
|
+
patterns = config.getini(option) if config is not None else []
|
|
403
|
+
return any(
|
|
404
|
+
fnmatch.fnmatch(name, pattern) if any(mark in pattern for mark in "*?[") else name.startswith(pattern)
|
|
405
|
+
for pattern in patterns
|
|
406
|
+
)
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
def case_name(item):
|
|
410
|
+
"""The case's full name: its node id after the file, the parts joined with ' > '."""
|
|
411
|
+
return NAME_SEPARATOR.join(item.nodeid.split("::")[1:])
|
|
412
|
+
|
|
413
|
+
|
|
414
|
+
def case_record(item):
|
|
415
|
+
"""A case as collected: its name, its def line, its source, its skip mark in a collect; skipped until it runs."""
|
|
416
|
+
parts = item.nodeid.split("::")[1:]
|
|
417
|
+
path = os.path.abspath(str(item.path))
|
|
418
|
+
node = function_node(path=path, classes=parts[:-1], name=getattr(item, "originalname", None) or item.name)
|
|
419
|
+
record = {"name": NAME_SEPARATOR.join(parts), "state": "skipped", "project": "", "errors": []}
|
|
420
|
+
if node is not None:
|
|
421
|
+
record["location"] = {"line": node.lineno, "column": node.col_offset + 1}
|
|
422
|
+
record["source"] = case_source(path=path, node=node, item=item)
|
|
423
|
+
else:
|
|
424
|
+
record["location"] = {"line": (item.location[1] or 0) + 1, "column": 1}
|
|
425
|
+
if RUN["collect_only"]:
|
|
426
|
+
record["skipMarked"] = is_skip_marked(item)
|
|
427
|
+
if any(NAME_SEPARATOR in part for part in parts):
|
|
428
|
+
record["state"] = "failed"
|
|
429
|
+
record["errors"].append({"name": UNMAPPABLE_NAME_ERROR, "message": UNMAPPABLE_NAME_MESSAGE, "frames": []})
|
|
430
|
+
record["unmappable"] = True
|
|
431
|
+
return record
|
|
432
|
+
|
|
433
|
+
|
|
434
|
+
def is_skip_marked(item):
|
|
435
|
+
"""A skip mark or a true skipif marks the case (a condition that cannot be read does not)."""
|
|
436
|
+
try:
|
|
437
|
+
from _pytest.skipping import evaluate_skip_marks
|
|
438
|
+
|
|
439
|
+
return evaluate_skip_marks(item) is not None
|
|
440
|
+
except Exception: # noqa: BLE001 - an unreadable condition is decided by the run, not here
|
|
441
|
+
return False
|
|
442
|
+
|
|
443
|
+
|
|
444
|
+
def parsed(path):
|
|
445
|
+
"""The text and the syntax tree of a Python file (None for the tree when it does not parse), read once."""
|
|
446
|
+
if path not in RUN["trees"]:
|
|
447
|
+
try:
|
|
448
|
+
with open(path, encoding="utf-8") as source:
|
|
449
|
+
text = source.read()
|
|
450
|
+
except OSError:
|
|
451
|
+
text = ""
|
|
452
|
+
try:
|
|
453
|
+
tree = ast.parse(text)
|
|
454
|
+
except (SyntaxError, ValueError):
|
|
455
|
+
tree = None
|
|
456
|
+
RUN["trees"][path] = (text, tree)
|
|
457
|
+
return RUN["trees"][path]
|
|
458
|
+
|
|
459
|
+
|
|
460
|
+
def function_node(path, classes, name, tree=None):
|
|
461
|
+
"""The definition of the case's function: the last `def <name>` in the classes of its node id (in `tree`, else in
|
|
462
|
+
the file's own tree)."""
|
|
463
|
+
tree = tree if tree is not None else parsed(path)[1]
|
|
464
|
+
if tree is None:
|
|
465
|
+
return None
|
|
466
|
+
body = tree.body
|
|
467
|
+
for class_name in classes:
|
|
468
|
+
found = [node for node in body if isinstance(node, ast.ClassDef) and node.name == class_name]
|
|
469
|
+
if not found:
|
|
470
|
+
return None
|
|
471
|
+
body = found[-1].body
|
|
472
|
+
functions = [
|
|
473
|
+
node for node in body if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name == name
|
|
474
|
+
]
|
|
475
|
+
return functions[-1] if functions else None
|
|
476
|
+
|
|
477
|
+
|
|
478
|
+
def is_parametrize(decorator):
|
|
479
|
+
"""The decorator is a `...parametrize(...)` call."""
|
|
480
|
+
return (
|
|
481
|
+
isinstance(decorator, ast.Call)
|
|
482
|
+
and isinstance(decorator.func, ast.Attribute)
|
|
483
|
+
and decorator.func.attr == "parametrize"
|
|
484
|
+
)
|
|
485
|
+
|
|
486
|
+
|
|
487
|
+
def case_source(path, node, item):
|
|
488
|
+
"""The function's text without its parametrize decorators, and the text of the case's row of each of them."""
|
|
489
|
+
text = parsed(path)[0]
|
|
490
|
+
decorators = [
|
|
491
|
+
"@" + (ast.get_source_segment(text, decorator) or "")
|
|
492
|
+
for decorator in node.decorator_list
|
|
493
|
+
if not is_parametrize(decorator)
|
|
494
|
+
]
|
|
495
|
+
call = "\n".join(decorators + [ast.get_source_segment(text, node) or ""])
|
|
496
|
+
source = {"call": call}
|
|
497
|
+
# each parametrize call but its literal values (the case's row stands for those): its names, ids, indirect, scope
|
|
498
|
+
settings = [parametrize_settings(decorator) for decorator in node.decorator_list if is_parametrize(decorator)]
|
|
499
|
+
if settings:
|
|
500
|
+
source["parametrize"] = ROW_SEPARATOR.join(settings)
|
|
501
|
+
base = base_function_node(path=path, item=item)
|
|
502
|
+
if base is not None:
|
|
503
|
+
source["baseParametrize"] = ROW_SEPARATOR.join(
|
|
504
|
+
parametrize_settings(decorator) for decorator in base.decorator_list if is_parametrize(decorator)
|
|
505
|
+
)
|
|
506
|
+
callspec = getattr(item, "callspec", None)
|
|
507
|
+
if callspec is None:
|
|
508
|
+
return source
|
|
509
|
+
rows = [
|
|
510
|
+
row
|
|
511
|
+
for row in (
|
|
512
|
+
row_text(text=text, decorator=decorator, indices=callspec.indices)
|
|
513
|
+
for decorator in node.decorator_list
|
|
514
|
+
if is_parametrize(decorator)
|
|
515
|
+
)
|
|
516
|
+
if row is not None
|
|
517
|
+
]
|
|
518
|
+
if rows:
|
|
519
|
+
source["row"] = ROW_SEPARATOR.join(rows)
|
|
520
|
+
return source
|
|
521
|
+
|
|
522
|
+
|
|
523
|
+
def base_function_node(path, item):
|
|
524
|
+
"""The case's function in the file's base text, when the cli gave it and it defines that function."""
|
|
525
|
+
key = os.path.relpath(os.path.realpath(path), RUN["root"] or "")
|
|
526
|
+
base_text = RUN["base_texts"].get(key)
|
|
527
|
+
if base_text is None:
|
|
528
|
+
return None
|
|
529
|
+
if key not in RUN["base_trees"]:
|
|
530
|
+
try:
|
|
531
|
+
RUN["base_trees"][key] = ast.parse(base_text)
|
|
532
|
+
except (SyntaxError, ValueError):
|
|
533
|
+
RUN["base_trees"][key] = None
|
|
534
|
+
tree = RUN["base_trees"][key]
|
|
535
|
+
if tree is None:
|
|
536
|
+
return None
|
|
537
|
+
return function_node(
|
|
538
|
+
path=path,
|
|
539
|
+
classes=item.nodeid.split("::")[1:-1],
|
|
540
|
+
name=getattr(item, "originalname", None) or item.name,
|
|
541
|
+
tree=tree,
|
|
542
|
+
)
|
|
543
|
+
|
|
544
|
+
|
|
545
|
+
def parametrize_settings(decorator):
|
|
546
|
+
"""A parametrize call as `ast.dump` reads it, its literal values replaced by one placeholder: a change of names,
|
|
547
|
+
ids, indirect, scope or of a values expression shows, a row added does not."""
|
|
548
|
+
copied = copy.deepcopy(decorator)
|
|
549
|
+
values = argument_of(copied, 1, "argvalues")
|
|
550
|
+
if isinstance(values, (ast.List, ast.Tuple)):
|
|
551
|
+
placeholder = ast.Constant(value=ROWS_PLACEHOLDER)
|
|
552
|
+
if len(copied.args) > 1:
|
|
553
|
+
copied.args[1] = placeholder
|
|
554
|
+
else:
|
|
555
|
+
for given in copied.keywords:
|
|
556
|
+
if given.arg == "argvalues":
|
|
557
|
+
given.value = placeholder
|
|
558
|
+
return ast.dump(copied)
|
|
559
|
+
|
|
560
|
+
|
|
561
|
+
def argument_of(decorator, position, keyword):
|
|
562
|
+
"""A call's argument given by its position or by its keyword."""
|
|
563
|
+
if len(decorator.args) > position:
|
|
564
|
+
return decorator.args[position]
|
|
565
|
+
for given in decorator.keywords:
|
|
566
|
+
if given.arg == keyword:
|
|
567
|
+
return given.value
|
|
568
|
+
return None
|
|
569
|
+
|
|
570
|
+
|
|
571
|
+
def row_text(text, decorator, indices):
|
|
572
|
+
"""The text of the row the case runs, when the decorator's values are a literal list or tuple."""
|
|
573
|
+
names = argument_of(decorator, 0, "argnames")
|
|
574
|
+
values = argument_of(decorator, 1, "argvalues")
|
|
575
|
+
if not isinstance(values, (ast.List, ast.Tuple)):
|
|
576
|
+
return None
|
|
577
|
+
if isinstance(names, ast.Constant) and isinstance(names.value, str):
|
|
578
|
+
first = names.value.split(",")[0].strip()
|
|
579
|
+
elif isinstance(names, (ast.List, ast.Tuple)) and names.elts and isinstance(names.elts[0], ast.Constant):
|
|
580
|
+
first = names.elts[0].value
|
|
581
|
+
else:
|
|
582
|
+
return None
|
|
583
|
+
index = indices.get(first)
|
|
584
|
+
if index is None or index >= len(values.elts):
|
|
585
|
+
return None
|
|
586
|
+
return ast.get_source_segment(text, values.elts[index])
|
|
587
|
+
|
|
588
|
+
|
|
589
|
+
def collection_error(report):
|
|
590
|
+
"""The error that stopped a test file's collection: the exception pytest wrapped, else its last `E` line."""
|
|
591
|
+
call = getattr(report, "call", None)
|
|
592
|
+
excinfo = getattr(call, "excinfo", None)
|
|
593
|
+
if excinfo is not None:
|
|
594
|
+
error = excinfo.value
|
|
595
|
+
while type(error).__name__ == "CollectError" and (error.__cause__ or error.__context__):
|
|
596
|
+
error = error.__cause__ or error.__context__
|
|
597
|
+
if type(error).__name__ != "CollectError":
|
|
598
|
+
return {"name": type(error).__name__, "message": str(error), "frames": []}
|
|
599
|
+
text = str(report.longrepr)
|
|
600
|
+
for line in reversed(text.splitlines()):
|
|
601
|
+
match = COLLECTION_ERROR_LINE.match(line)
|
|
602
|
+
if match:
|
|
603
|
+
return {
|
|
604
|
+
"name": match.group(1).split(".")[-1],
|
|
605
|
+
"message": match.group(2) or "",
|
|
606
|
+
"frames": [],
|
|
607
|
+
}
|
|
608
|
+
return {"name": "CollectError", "message": text, "frames": []}
|
|
609
|
+
|
|
610
|
+
|
|
611
|
+
def phase_error(item, call, report):
|
|
612
|
+
"""The error of a failed phase: its exception's type, message, frames from the test function inward, and
|
|
613
|
+
whether the innermost frame in the test file lies inside an `assert` statement."""
|
|
614
|
+
test_path = os.path.abspath(str(item.path))
|
|
615
|
+
excinfo = call.excinfo
|
|
616
|
+
if excinfo is None:
|
|
617
|
+
return {"name": "Failed", "message": str(report.longrepr), "frames": [], "inAssertion": False}
|
|
618
|
+
frames = frames_of(excinfo=excinfo, test_path=test_path)
|
|
619
|
+
test_frame = next((frame for frame in frames if frame["file"] == test_path), None)
|
|
620
|
+
error = {
|
|
621
|
+
"name": excinfo.typename,
|
|
622
|
+
"message": str(excinfo.value),
|
|
623
|
+
"frames": frames,
|
|
624
|
+
"inAssertion": test_frame is not None and is_in_assert(path=test_path, line=test_frame["line"]),
|
|
625
|
+
}
|
|
626
|
+
# an OSError's code as node names it (ENOENT): what the error is, never read from its message
|
|
627
|
+
code = errno.errorcode.get(getattr(excinfo.value, "errno", None) or -1)
|
|
628
|
+
if isinstance(excinfo.value, OSError) and code:
|
|
629
|
+
error["code"] = code
|
|
630
|
+
return error
|
|
631
|
+
|
|
632
|
+
|
|
633
|
+
def is_hidden(frame, excinfo):
|
|
634
|
+
"""The frame asks to be left out of tracebacks (`__tracebackhide__`, a value or a function of the error)."""
|
|
635
|
+
hide = frame.f_locals.get("__tracebackhide__", frame.f_globals.get("__tracebackhide__", False))
|
|
636
|
+
if callable(hide):
|
|
637
|
+
try:
|
|
638
|
+
return bool(hide(excinfo))
|
|
639
|
+
except Exception: # noqa: BLE001 - a broken hide function hides nothing
|
|
640
|
+
return False
|
|
641
|
+
return bool(hide)
|
|
642
|
+
|
|
643
|
+
|
|
644
|
+
def frames_of(excinfo, test_path):
|
|
645
|
+
"""The traceback's frames innermost first, cut to the test file's first frame and below, hidden ones left out."""
|
|
646
|
+
entries = []
|
|
647
|
+
traceback = excinfo.tb
|
|
648
|
+
while traceback is not None:
|
|
649
|
+
frame = traceback.tb_frame
|
|
650
|
+
entries.append((frame, os.path.abspath(frame.f_code.co_filename), traceback.tb_lineno))
|
|
651
|
+
traceback = traceback.tb_next
|
|
652
|
+
start = next((index for index, entry in enumerate(entries) if entry[1] == test_path), 0)
|
|
653
|
+
kept = [
|
|
654
|
+
{"file": path, "line": line, "column": 1}
|
|
655
|
+
for frame, path, line in entries[start:]
|
|
656
|
+
if not is_hidden(frame, excinfo)
|
|
657
|
+
]
|
|
658
|
+
return list(reversed(kept))
|
|
659
|
+
|
|
660
|
+
|
|
661
|
+
def is_in_assert(path, line):
|
|
662
|
+
"""The line lies inside an assertion of the file: an `assert` statement, or the body of a `with` of
|
|
663
|
+
`pytest.raises(...)` / `pytest.warns(...)`."""
|
|
664
|
+
tree = parsed(path)[1]
|
|
665
|
+
if tree is None:
|
|
666
|
+
return False
|
|
667
|
+
return any(
|
|
668
|
+
(isinstance(node, ast.Assert) and node.lineno <= line <= end_line_of(node))
|
|
669
|
+
or (isinstance(node, (ast.With, ast.AsyncWith)) and is_expecting_body_line(node=node, line=line))
|
|
670
|
+
for node in ast.walk(tree)
|
|
671
|
+
)
|
|
672
|
+
|
|
673
|
+
|
|
674
|
+
def end_line_of(node):
|
|
675
|
+
"""The last line of a node (its first one on a Python without end positions)."""
|
|
676
|
+
return getattr(node, "end_lineno", None) or node.lineno
|
|
677
|
+
|
|
678
|
+
|
|
679
|
+
def is_expecting_body_line(node, line):
|
|
680
|
+
"""The line lies in the body of a `with` one of whose items is a `raises(...)` / `warns(...)` call."""
|
|
681
|
+
if not node.body or not any(is_expecting_call(item.context_expr) for item in node.items):
|
|
682
|
+
return False
|
|
683
|
+
return node.body[0].lineno <= line <= end_line_of(node.body[-1])
|
|
684
|
+
|
|
685
|
+
|
|
686
|
+
def is_expecting_call(expression):
|
|
687
|
+
"""The expression is a call of `raises` or `warns`, bare or as an attribute (`pytest.raises(...)`)."""
|
|
688
|
+
if not isinstance(expression, ast.Call):
|
|
689
|
+
return False
|
|
690
|
+
function = expression.func
|
|
691
|
+
name = function.attr if isinstance(function, ast.Attribute) else getattr(function, "id", None)
|
|
692
|
+
return name in EXPECTING_CALLS
|
|
693
|
+
|
|
694
|
+
|
|
695
|
+
def source_path(path):
|
|
696
|
+
"""A compiled file in `__pycache__` read as the source next to its folder; any other path as it is."""
|
|
697
|
+
folder, name = os.path.split(path)
|
|
698
|
+
if os.path.basename(folder) == CACHE_FOLDER and name.endswith(".pyc"):
|
|
699
|
+
return os.path.join(os.path.dirname(folder), name.split(".")[0] + ".py")
|
|
700
|
+
return path
|
|
701
|
+
|
|
702
|
+
|
|
703
|
+
def is_under_root(path):
|
|
704
|
+
"""The path lies under the package root the cli named (the rootdir without it)."""
|
|
705
|
+
root = RUN["root"] or ""
|
|
706
|
+
real = os.path.realpath(path)
|
|
707
|
+
return real == root or real.startswith(root.rstrip(os.sep) + os.sep)
|
|
708
|
+
|
|
709
|
+
|
|
710
|
+
def dependencies_of(path, module):
|
|
711
|
+
"""The package files a test file used: conftests up to the rootdir, the imports of the test file and of each
|
|
712
|
+
conftest followed, files opened."""
|
|
713
|
+
found = {source_path(opened) for opened in module["opened"]}
|
|
714
|
+
conftests = conftests_of(path)
|
|
715
|
+
found |= conftests
|
|
716
|
+
for conftest in conftests:
|
|
717
|
+
found |= conftest_imports(conftest)
|
|
718
|
+
if module["name"]:
|
|
719
|
+
found |= imported_files(path=path, module_name=module["name"], seen=set())
|
|
720
|
+
found.discard(path)
|
|
721
|
+
return {file for file in found if is_under_root(file) and os.path.isfile(file)}
|
|
722
|
+
|
|
723
|
+
|
|
724
|
+
def conftest_imports(path):
|
|
725
|
+
"""The package files a conftest's imports resolve to, followed through their own imports; read once."""
|
|
726
|
+
if path not in RUN["conftest_imports"]:
|
|
727
|
+
RUN["conftest_imports"][path] = imported_files(path=path, module_name=module_name_of(path), seen=set())
|
|
728
|
+
return RUN["conftest_imports"][path]
|
|
729
|
+
|
|
730
|
+
|
|
731
|
+
def module_name_of(path):
|
|
732
|
+
"""The name the file was imported under (`sys.modules`), else its file name without `.py`."""
|
|
733
|
+
for name, imported in list(sys.modules.items()):
|
|
734
|
+
file = getattr(imported, "__file__", None)
|
|
735
|
+
if file and source_path(os.path.abspath(file)) == path:
|
|
736
|
+
return name
|
|
737
|
+
return os.path.splitext(os.path.basename(path))[0]
|
|
738
|
+
|
|
739
|
+
|
|
740
|
+
def conftests_of(path):
|
|
741
|
+
"""The conftest.py of the test file's folder and of each parent up to the rootdir (or the package root)."""
|
|
742
|
+
found = set()
|
|
743
|
+
folder = os.path.dirname(path)
|
|
744
|
+
root = RUN["root"] or folder
|
|
745
|
+
while True:
|
|
746
|
+
candidate = os.path.join(folder, "conftest.py")
|
|
747
|
+
if os.path.isfile(candidate):
|
|
748
|
+
found.add(candidate)
|
|
749
|
+
parent = os.path.dirname(folder)
|
|
750
|
+
if folder == root or parent == folder or not is_under_root(parent):
|
|
751
|
+
return found
|
|
752
|
+
folder = parent
|
|
753
|
+
|
|
754
|
+
|
|
755
|
+
def imported_names(tree, module_name, is_package):
|
|
756
|
+
"""The module names the file's import statements name (relative ones resolved against its package)."""
|
|
757
|
+
package = module_name if is_package else module_name.rpartition(".")[0]
|
|
758
|
+
names = []
|
|
759
|
+
for node in ast.walk(tree):
|
|
760
|
+
if isinstance(node, ast.Import):
|
|
761
|
+
names.extend(alias.name for alias in node.names)
|
|
762
|
+
elif isinstance(node, ast.ImportFrom):
|
|
763
|
+
base = node.module or ""
|
|
764
|
+
if node.level:
|
|
765
|
+
try:
|
|
766
|
+
base = importlib.util.resolve_name("." * node.level + base, package)
|
|
767
|
+
except (ImportError, ValueError):
|
|
768
|
+
continue
|
|
769
|
+
if base:
|
|
770
|
+
names.append(base)
|
|
771
|
+
names.extend(base + "." + alias.name if base else alias.name for alias in node.names)
|
|
772
|
+
return names
|
|
773
|
+
|
|
774
|
+
|
|
775
|
+
def imported_files(path, module_name, seen):
|
|
776
|
+
"""The package files the file's imports resolve to (`sys.modules`), followed through their own imports."""
|
|
777
|
+
tree = parsed(path)[1]
|
|
778
|
+
if tree is None:
|
|
779
|
+
return set()
|
|
780
|
+
found = set()
|
|
781
|
+
is_package = os.path.basename(path) == "__init__.py"
|
|
782
|
+
for name in imported_names(tree, module_name, is_package):
|
|
783
|
+
file = getattr(sys.modules.get(name), "__file__", None)
|
|
784
|
+
if not file:
|
|
785
|
+
continue
|
|
786
|
+
file = source_path(os.path.abspath(file))
|
|
787
|
+
if file in seen or not is_under_root(file) or not file.endswith(".py"):
|
|
788
|
+
continue
|
|
789
|
+
seen.add(file)
|
|
790
|
+
found.add(file)
|
|
791
|
+
found |= imported_files(path=file, module_name=name, seen=seen)
|
|
792
|
+
return found
|