| 1 |
""" |
| 2 |
Allows configuring optional test markers in config, see pyproject.toml. |
| 3 |
|
| 4 |
Run optional tests with `pytest --run-optional=...`. |
| 5 |
|
| 6 |
Mark tests to run only if an optional test ISN'T selected by prepending the mark with |
| 7 |
"no_". |
| 8 |
|
| 9 |
You can specify a "no_" prefix straight in config, in which case you can mark tests |
| 10 |
to run when this tests ISN'T selected by omitting the "no_" prefix. |
| 11 |
|
| 12 |
Specifying the name of the default behavior in `--run-optional=` is harmless. |
| 13 |
|
| 14 |
Adapted from https://pypi.org/project/pytest-optional-tests/, (c) 2019 Reece Hart |
| 15 |
""" |
| 16 |
|
| 17 |
import itertools |
| 18 |
import logging |
| 19 |
import re |
| 20 |
from functools import lru_cache |
| 21 |
from typing import TYPE_CHECKING, Any |
| 22 |
|
| 23 |
import pytest |
| 24 |
from pytest import StashKey |
| 25 |
|
| 26 |
log = logging.getLogger(__name__) |
| 27 |
|
| 28 |
|
| 29 |
if TYPE_CHECKING: |
| 30 |
from _pytest.config import Config |
| 31 |
from _pytest.config.argparsing import Parser |
| 32 |
from _pytest.mark.structures import MarkDecorator |
| 33 |
from _pytest.nodes import Node |
| 34 |
|
| 35 |
|
| 36 |
ALL_POSSIBLE_OPTIONAL_MARKERS = StashKey[frozenset[str]]() |
| 37 |
ENABLED_OPTIONAL_MARKERS = StashKey[frozenset[str]]() |
| 38 |
|
| 39 |
|
| 40 |
def pytest_addoption(parser: "Parser") -> None: |
| 41 |
group = parser.getgroup("collect") |
| 42 |
group.addoption( |
| 43 |
"--run-optional", |
| 44 |
action="append", |
| 45 |
dest="run_optional", |
| 46 |
default=None, |
| 47 |
help="Optional test markers to run; comma-separated", |
| 48 |
) |
| 49 |
parser.addini("optional-tests", "List of optional tests markers", "linelist") |
| 50 |
|
| 51 |
|
| 52 |
def pytest_configure(config: "Config") -> None: |
| 53 |
"""Optional tests are markers. |
| 54 |
|
| 55 |
Use the syntax in https://docs.pytest.org/en/stable/mark.html#registering-marks. |
| 56 |
""" |
| 57 |
# Extract the configured optional-tests from pytest's ini config in a |
| 58 |
# version-agnostic way. Depending on pytest version, the value can be a |
| 59 |
# string, a list of strings, or a ConfigValue wrapper (with a `.value` attr). |
| 60 |
raw_ot_ini: Any = config.inicfg.get("optional-tests") |
| 61 |
ot_ini_lines: list[str] = [] |
| 62 |
if raw_ot_ini: |
| 63 |
value = getattr(raw_ot_ini, "value", raw_ot_ini) |
| 64 |
if isinstance(value, str): |
| 65 |
ot_ini_lines = value.strip().split("\n") |
| 66 |
elif isinstance(value, list): |
| 67 |
# Best-effort coercion to strings; pytest inis are textual. |
| 68 |
ot_ini_lines = [str(v) for v in value] |
| 69 |
else: |
| 70 |
# Fallback: ignore unexpected shapes (non-iterable, etc.). |
| 71 |
ot_ini_lines = [] |
| 72 |
|
| 73 |
ot_markers: set[str] = set() |
| 74 |
ot_run: set[str] = set() |
| 75 |
marker_re = re.compile(r"^\s*(?P<no>no_)?(?P<marker>\w+)(:\s*(?P<description>.*))?") |
| 76 |
# Iterate over configured markers discovered above. |
| 77 |
for ot in ot_ini_lines: |
| 78 |
m = marker_re.match(ot) |
| 79 |
if not m: |
| 80 |
raise ValueError(f"{ot!r} doesn't match pytest marker syntax") |
| 81 |
|
| 82 |
marker = (m.group("no") or "") + m.group("marker") |
| 83 |
description = m.group("description") |
| 84 |
config.addinivalue_line("markers", f"{marker}: {description}") |
| 85 |
config.addinivalue_line( |
| 86 |
"markers", f"{no(marker)}: run when `{marker}` not passed" |
| 87 |
) |
| 88 |
ot_markers.add(marker) |
| 89 |
|
| 90 |
# collect requested optional tests |
| 91 |
passed_args = config.getoption("run_optional") |
| 92 |
if passed_args: |
| 93 |
ot_run.update(itertools.chain.from_iterable(a.split(",") for a in passed_args)) |
| 94 |
ot_run |= {no(excluded) for excluded in ot_markers - ot_run} |
| 95 |
ot_markers |= {no(m) for m in ot_markers} |
| 96 |
|
| 97 |
log.info("optional tests to run: %s", ot_run) |
| 98 |
unknown_tests = ot_run - ot_markers |
| 99 |
if unknown_tests: |
| 100 |
raise ValueError(f"Unknown optional tests wanted: {unknown_tests!r}") |
| 101 |
|
| 102 |
store = config._store |
| 103 |
store[ALL_POSSIBLE_OPTIONAL_MARKERS] = frozenset(ot_markers) |
| 104 |
store[ENABLED_OPTIONAL_MARKERS] = frozenset(ot_run) |
| 105 |
|
| 106 |
|
| 107 |
def pytest_collection_modifyitems(config: "Config", items: "list[Node]") -> None: |
| 108 |
store = config._store |
| 109 |
all_possible_optional_markers = store[ALL_POSSIBLE_OPTIONAL_MARKERS] |
| 110 |
enabled_optional_markers = store[ENABLED_OPTIONAL_MARKERS] |
| 111 |
|
| 112 |
for item in items: |
| 113 |
all_markers_on_test = {m.name for m in item.iter_markers()} |
| 114 |
optional_markers_on_test = all_markers_on_test & all_possible_optional_markers |
| 115 |
if not optional_markers_on_test or ( |
| 116 |
optional_markers_on_test & enabled_optional_markers |
| 117 |
): |
| 118 |
continue |
| 119 |
log.info("skipping non-requested optional: %s", item) |
| 120 |
item.add_marker(skip_mark(frozenset(optional_markers_on_test))) |
| 121 |
|
| 122 |
|
| 123 |
@lru_cache |
| 124 |
def skip_mark(tests: frozenset[str]) -> "MarkDecorator": |
| 125 |
names = ", ".join(sorted(tests)) |
| 126 |
return pytest.mark.skip(reason=f"Marked with disabled optional tests ({names})") |
| 127 |
|
| 128 |
|
| 129 |
@lru_cache |
| 130 |
def no(name: str) -> str: |
| 131 |
if name.startswith("no_"): |
| 132 |
return name[len("no_") :] |
| 133 |
return "no_" + name |