| 1 |
# content of conftest.py |
| 2 |
from __future__ import annotations |
| 3 |
|
| 4 |
import pytest |
| 5 |
|
| 6 |
|
| 7 |
def pytest_collect_file(parent, file_path): |
| 8 |
if file_path.suffix == ".yaml" and file_path.name.startswith("test"): |
| 9 |
return YamlFile.from_parent(parent, path=file_path) |
| 10 |
|
| 11 |
|
| 12 |
class YamlFile(pytest.File): |
| 13 |
def collect(self): |
| 14 |
# We need a yaml parser, e.g. PyYAML. |
| 15 |
import yaml |
| 16 |
|
| 17 |
raw = yaml.safe_load(self.path.open(encoding="utf-8")) |
| 18 |
for name, spec in sorted(raw.items()): |
| 19 |
yield YamlItem.from_parent(self, name=name, spec=spec) |
| 20 |
|
| 21 |
|
| 22 |
class YamlItem(pytest.Item): |
| 23 |
def __init__(self, *, spec, **kwargs): |
| 24 |
super().__init__(**kwargs) |
| 25 |
self.spec = spec |
| 26 |
|
| 27 |
def runtest(self): |
| 28 |
for name, value in sorted(self.spec.items()): |
| 29 |
# Some custom test execution (dumb example follows). |
| 30 |
if name != value: |
| 31 |
raise YamlException(self, name, value) |
| 32 |
|
| 33 |
def repr_failure(self, excinfo): |
| 34 |
"""Called when self.runtest() raises an exception.""" |
| 35 |
if isinstance(excinfo.value, YamlException): |
| 36 |
return "\n".join( |
| 37 |
[ |
| 38 |
"usecase execution failed", |
| 39 |
" spec failed: {1!r}: {2!r}".format(*excinfo.value.args), |
| 40 |
" no further details known at this point.", |
| 41 |
] |
| 42 |
) |
| 43 |
return super().repr_failure(excinfo) |
| 44 |
|
| 45 |
def reportinfo(self): |
| 46 |
return self.path, 0, f"usecase: {self.name}" |
| 47 |
|
| 48 |
|
| 49 |
class YamlException(Exception): |
| 50 |
"""Custom exception for error reporting.""" |