| 1 |
# mypy: allow-untyped-defs |
| 2 |
"""Support for skip/xfail functions and markers.""" |
| 3 |
|
| 4 |
from __future__ import annotations |
| 5 |
|
| 6 |
from collections.abc import Generator |
| 7 |
from collections.abc import Mapping |
| 8 |
import dataclasses |
| 9 |
import os |
| 10 |
import platform |
| 11 |
import sys |
| 12 |
import traceback |
| 13 |
|
| 14 |
from _pytest.config import Config |
| 15 |
from _pytest.config import hookimpl |
| 16 |
from _pytest.config.argparsing import Parser |
| 17 |
from _pytest.mark.structures import Mark |
| 18 |
from _pytest.nodes import Item |
| 19 |
from _pytest.outcomes import fail |
| 20 |
from _pytest.outcomes import skip |
| 21 |
from _pytest.outcomes import xfail |
| 22 |
from _pytest.raises import AbstractRaises |
| 23 |
from _pytest.reports import BaseReport |
| 24 |
from _pytest.reports import TestReport |
| 25 |
from _pytest.runner import CallInfo |
| 26 |
from _pytest.stash import StashKey |
| 27 |
|
| 28 |
|
| 29 |
def pytest_addoption(parser: Parser) -> None: |
| 30 |
group = parser.getgroup("general") |
| 31 |
group.addoption( |
| 32 |
"--runxfail", |
| 33 |
action="store_true", |
| 34 |
dest="runxfail", |
| 35 |
default=False, |
| 36 |
help="Report the results of xfail tests as if they were not marked", |
| 37 |
) |
| 38 |
|
| 39 |
parser.addini( |
| 40 |
"strict_xfail", |
| 41 |
"Default for the strict parameter of xfail " |
| 42 |
"markers when not given explicitly (default: False) (alias: xfail_strict)", |
| 43 |
type="bool", |
| 44 |
# None => fallback to `strict`. |
| 45 |
default=None, |
| 46 |
aliases=["xfail_strict"], |
| 47 |
) |
| 48 |
|
| 49 |
|
| 50 |
def pytest_configure(config: Config) -> None: |
| 51 |
if config.option.runxfail: |
| 52 |
# yay a hack |
| 53 |
import pytest |
| 54 |
|
| 55 |
old = pytest.xfail |
| 56 |
config.add_cleanup(lambda: setattr(pytest, "xfail", old)) |
| 57 |
|
| 58 |
def nop(*args, **kwargs): |
| 59 |
pass |
| 60 |
|
| 61 |
nop.Exception = xfail.Exception # type: ignore[attr-defined] |
| 62 |
setattr(pytest, "xfail", nop) |
| 63 |
|
| 64 |
config.addinivalue_line( |
| 65 |
"markers", |
| 66 |
"skip(reason=None): skip the given test function with an optional reason. " |
| 67 |
'Example: skip(reason="no way of currently testing this") skips the ' |
| 68 |
"test.", |
| 69 |
) |
| 70 |
config.addinivalue_line( |
| 71 |
"markers", |
| 72 |
"skipif(condition, ..., *, reason=...): " |
| 73 |
"skip the given test function if any of the conditions evaluate to True. " |
| 74 |
"Example: skipif(sys.platform == 'win32') skips the test if we are on the win32 platform. " |
| 75 |
"See https://docs.pytest.org/en/stable/reference/reference.html#pytest-mark-skipif", |
| 76 |
) |
| 77 |
config.addinivalue_line( |
| 78 |
"markers", |
| 79 |
"xfail(condition, ..., *, reason=..., run=True, raises=None, strict=strict_xfail): " |
| 80 |
"mark the test function as an expected failure if any of the conditions " |
| 81 |
"evaluate to True. Optionally specify a reason for better reporting " |
| 82 |
"and run=False if you don't even want to execute the test function. " |
| 83 |
"If only specific exception(s) are expected, you can list them in " |
| 84 |
"raises, and if the test fails in other ways, it will be reported as " |
| 85 |
"a true failure. See https://docs.pytest.org/en/stable/reference/reference.html#pytest-mark-xfail", |
| 86 |
) |
| 87 |
|
| 88 |
|
| 89 |
def evaluate_condition(item: Item, mark: Mark, condition: object) -> tuple[bool, str]: |
| 90 |
"""Evaluate a single skipif/xfail condition. |
| 91 |
|
| 92 |
If an old-style string condition is given, it is eval()'d, otherwise the |
| 93 |
condition is bool()'d. If this fails, an appropriately formatted pytest.fail |
| 94 |
is raised. |
| 95 |
|
| 96 |
Returns (result, reason). The reason is only relevant if the result is True. |
| 97 |
""" |
| 98 |
# String condition. |
| 99 |
if isinstance(condition, str): |
| 100 |
globals_ = { |
| 101 |
"os": os, |
| 102 |
"sys": sys, |
| 103 |
"platform": platform, |
| 104 |
"config": item.config, |
| 105 |
} |
| 106 |
for dictionary in reversed( |
| 107 |
item.ihook.pytest_markeval_namespace(config=item.config) |
| 108 |
): |
| 109 |
if not isinstance(dictionary, Mapping): |
| 110 |
raise ValueError( |
| 111 |
f"pytest_markeval_namespace() needs to return a dict, got {dictionary!r}" |
| 112 |
) |
| 113 |
globals_.update(dictionary) |
| 114 |
if hasattr(item, "obj"): |
| 115 |
globals_.update(item.obj.__globals__) |
| 116 |
try: |
| 117 |
filename = f"<{mark.name} condition>" |
| 118 |
condition_code = compile(condition, filename, "eval") |
| 119 |
result = eval(condition_code, globals_) |
| 120 |
except SyntaxError as exc: |
| 121 |
msglines = [ |
| 122 |
f"Error evaluating {mark.name!r} condition", |
| 123 |
" " + condition, |
| 124 |
" " + " " * (exc.offset or 0) + "^", |
| 125 |
"SyntaxError: invalid syntax", |
| 126 |
] |
| 127 |
fail("\n".join(msglines), pytrace=False) |
| 128 |
except Exception as exc: |
| 129 |
msglines = [ |
| 130 |
f"Error evaluating {mark.name!r} condition", |
| 131 |
" " + condition, |
| 132 |
*traceback.format_exception_only(exc), |
| 133 |
] |
| 134 |
fail("\n".join(msglines), pytrace=False) |
| 135 |
|
| 136 |
# Boolean condition. |
| 137 |
else: |
| 138 |
try: |
| 139 |
result = bool(condition) |
| 140 |
except Exception as exc: |
| 141 |
msglines = [ |
| 142 |
f"Error evaluating {mark.name!r} condition as a boolean", |
| 143 |
*traceback.format_exception_only(exc), |
| 144 |
] |
| 145 |
fail("\n".join(msglines), pytrace=False) |
| 146 |
|
| 147 |
reason = mark.kwargs.get("reason", None) |
| 148 |
if reason is None: |
| 149 |
if isinstance(condition, str): |
| 150 |
reason = "condition: " + condition |
| 151 |
else: |
| 152 |
# XXX better be checked at collection time |
| 153 |
msg = ( |
| 154 |
f"Error evaluating {mark.name!r}: " |
| 155 |
+ "you need to specify reason=STRING when using booleans as conditions." |
| 156 |
) |
| 157 |
fail(msg, pytrace=False) |
| 158 |
|
| 159 |
return result, reason |
| 160 |
|
| 161 |
|
| 162 |
@dataclasses.dataclass(frozen=True) |
| 163 |
class Skip: |
| 164 |
"""The result of evaluate_skip_marks().""" |
| 165 |
|
| 166 |
reason: str = "unconditional skip" |
| 167 |
|
| 168 |
|
| 169 |
def evaluate_skip_marks(item: Item) -> Skip | None: |
| 170 |
"""Evaluate skip and skipif marks on item, returning Skip if triggered.""" |
| 171 |
for mark in item.iter_markers(name="skipif"): |
| 172 |
if "condition" not in mark.kwargs: |
| 173 |
conditions = mark.args |
| 174 |
else: |
| 175 |
conditions = (mark.kwargs["condition"],) |
| 176 |
|
| 177 |
# Unconditional. |
| 178 |
if not conditions: |
| 179 |
reason = mark.kwargs.get("reason", "") |
| 180 |
return Skip(reason) |
| 181 |
|
| 182 |
# If any of the conditions are true. |
| 183 |
for condition in conditions: |
| 184 |
result, reason = evaluate_condition(item, mark, condition) |
| 185 |
if result: |
| 186 |
return Skip(reason) |
| 187 |
|
| 188 |
for mark in item.iter_markers(name="skip"): |
| 189 |
try: |
| 190 |
return Skip(*mark.args, **mark.kwargs) |
| 191 |
except TypeError as e: |
| 192 |
raise TypeError(str(e) + " - maybe you meant pytest.mark.skipif?") from None |
| 193 |
|
| 194 |
return None |
| 195 |
|
| 196 |
|
| 197 |
@dataclasses.dataclass(frozen=True) |
| 198 |
class Xfail: |
| 199 |
"""The result of evaluate_xfail_marks().""" |
| 200 |
|
| 201 |
__slots__ = ("raises", "reason", "run", "strict") |
| 202 |
|
| 203 |
reason: str |
| 204 |
run: bool |
| 205 |
strict: bool |
| 206 |
raises: ( |
| 207 |
type[BaseException] |
| 208 |
| tuple[type[BaseException], ...] |
| 209 |
| AbstractRaises[BaseException] |
| 210 |
| None |
| 211 |
) |
| 212 |
|
| 213 |
|
| 214 |
def evaluate_xfail_marks(item: Item) -> Xfail | None: |
| 215 |
"""Evaluate xfail marks on item, returning Xfail if triggered.""" |
| 216 |
for mark in item.iter_markers(name="xfail"): |
| 217 |
run = mark.kwargs.get("run", True) |
| 218 |
strict = mark.kwargs.get("strict") |
| 219 |
if strict is None: |
| 220 |
strict = item.config.getini("strict_xfail") |
| 221 |
if strict is None: |
| 222 |
strict = item.config.getini("strict") |
| 223 |
raises = mark.kwargs.get("raises", None) |
| 224 |
if "condition" not in mark.kwargs: |
| 225 |
conditions = mark.args |
| 226 |
else: |
| 227 |
conditions = (mark.kwargs["condition"],) |
| 228 |
|
| 229 |
# Unconditional. |
| 230 |
if not conditions: |
| 231 |
reason = mark.kwargs.get("reason", "") |
| 232 |
return Xfail(reason, run, strict, raises) |
| 233 |
|
| 234 |
# If any of the conditions are true. |
| 235 |
for condition in conditions: |
| 236 |
result, reason = evaluate_condition(item, mark, condition) |
| 237 |
if result: |
| 238 |
return Xfail(reason, run, strict, raises) |
| 239 |
|
| 240 |
return None |
| 241 |
|
| 242 |
|
| 243 |
# Saves the xfail mark evaluation. Can be refreshed during call if None. |
| 244 |
xfailed_key = StashKey[Xfail | None]() |
| 245 |
|
| 246 |
|
| 247 |
@hookimpl(tryfirst=True) |
| 248 |
def pytest_runtest_setup(item: Item) -> None: |
| 249 |
skipped = evaluate_skip_marks(item) |
| 250 |
if skipped: |
| 251 |
raise skip.Exception(skipped.reason, _use_item_location=True) |
| 252 |
|
| 253 |
item.stash[xfailed_key] = xfailed = evaluate_xfail_marks(item) |
| 254 |
if xfailed and not item.config.option.runxfail and not xfailed.run: |
| 255 |
xfail("[NOTRUN] " + xfailed.reason) |
| 256 |
|
| 257 |
|
| 258 |
@hookimpl(wrapper=True) |
| 259 |
def pytest_runtest_call(item: Item) -> Generator[None]: |
| 260 |
xfailed = item.stash.get(xfailed_key, None) |
| 261 |
if xfailed is None: |
| 262 |
item.stash[xfailed_key] = xfailed = evaluate_xfail_marks(item) |
| 263 |
|
| 264 |
if xfailed and not item.config.option.runxfail and not xfailed.run: |
| 265 |
xfail("[NOTRUN] " + xfailed.reason) |
| 266 |
|
| 267 |
try: |
| 268 |
return (yield) |
| 269 |
finally: |
| 270 |
# The test run may have added an xfail mark dynamically. |
| 271 |
xfailed = item.stash.get(xfailed_key, None) |
| 272 |
if xfailed is None: |
| 273 |
item.stash[xfailed_key] = xfailed = evaluate_xfail_marks(item) |
| 274 |
|
| 275 |
|
| 276 |
@hookimpl(wrapper=True) |
| 277 |
def pytest_runtest_makereport( |
| 278 |
item: Item, call: CallInfo[None] |
| 279 |
) -> Generator[None, TestReport, TestReport]: |
| 280 |
rep = yield |
| 281 |
xfailed = item.stash.get(xfailed_key, None) |
| 282 |
if item.config.option.runxfail: |
| 283 |
pass # don't interfere |
| 284 |
elif call.excinfo and isinstance(call.excinfo.value, xfail.Exception): |
| 285 |
assert call.excinfo.value.msg is not None |
| 286 |
rep.wasxfail = call.excinfo.value.msg |
| 287 |
rep.outcome = "skipped" |
| 288 |
elif not rep.skipped and xfailed: |
| 289 |
if call.excinfo: |
| 290 |
raises = xfailed.raises |
| 291 |
if raises is None or ( |
| 292 |
( |
| 293 |
isinstance(raises, type | tuple) |
| 294 |
and isinstance(call.excinfo.value, raises) |
| 295 |
) |
| 296 |
or ( |
| 297 |
isinstance(raises, AbstractRaises) |
| 298 |
and raises.matches(call.excinfo.value) |
| 299 |
) |
| 300 |
): |
| 301 |
rep.outcome = "skipped" |
| 302 |
rep.wasxfail = xfailed.reason |
| 303 |
else: |
| 304 |
rep.outcome = "failed" |
| 305 |
elif call.when == "call": |
| 306 |
if xfailed.strict: |
| 307 |
rep.outcome = "failed" |
| 308 |
rep.longrepr = "[XPASS(strict)] " + xfailed.reason |
| 309 |
else: |
| 310 |
rep.outcome = "passed" |
| 311 |
rep.wasxfail = xfailed.reason |
| 312 |
return rep |
| 313 |
|
| 314 |
|
| 315 |
def pytest_report_teststatus(report: BaseReport) -> tuple[str, str, str] | None: |
| 316 |
if hasattr(report, "wasxfail"): |
| 317 |
if report.skipped: |
| 318 |
return "xfailed", "x", "XFAIL" |
| 319 |
elif report.passed: |
| 320 |
return "xpassed", "X", "XPASS" |
| 321 |
return None |