| 1 |
# mypy: allow-untyped-defs |
| 2 |
from __future__ import annotations |
| 3 |
|
| 4 |
import collections.abc |
| 5 |
from collections.abc import Callable |
| 6 |
from collections.abc import Collection |
| 7 |
from collections.abc import Iterable |
| 8 |
from collections.abc import Iterator |
| 9 |
from collections.abc import Mapping |
| 10 |
from collections.abc import MutableMapping |
| 11 |
from collections.abc import Sequence |
| 12 |
import dataclasses |
| 13 |
import enum |
| 14 |
import inspect |
| 15 |
from typing import Any |
| 16 |
from typing import final |
| 17 |
from typing import NamedTuple |
| 18 |
from typing import overload |
| 19 |
from typing import TYPE_CHECKING |
| 20 |
from typing import TypeVar |
| 21 |
import warnings |
| 22 |
|
| 23 |
from .._code import getfslineno |
| 24 |
from ..compat import NOTSET |
| 25 |
from ..compat import NotSetType |
| 26 |
from _pytest.config import Config |
| 27 |
from _pytest.deprecated import check_ispytest |
| 28 |
from _pytest.deprecated import PARAMETRIZE_NON_COLLECTION_ITERABLE |
| 29 |
from _pytest.outcomes import fail |
| 30 |
from _pytest.raises import AbstractRaises |
| 31 |
from _pytest.scope import ScopeName |
| 32 |
from _pytest.warning_types import PytestCollectionWarning |
| 33 |
from _pytest.warning_types import PytestUnknownMarkWarning |
| 34 |
|
| 35 |
|
| 36 |
if TYPE_CHECKING: |
| 37 |
from ..nodes import Node |
| 38 |
|
| 39 |
|
| 40 |
EMPTY_PARAMETERSET_OPTION = "empty_parameter_set_mark" |
| 41 |
|
| 42 |
|
| 43 |
# Singleton type for HIDDEN_PARAM, as described in: |
| 44 |
# https://www.python.org/dev/peps/pep-0484/#support-for-singleton-types-in-unions |
| 45 |
class _HiddenParam(enum.Enum): |
| 46 |
token = 0 |
| 47 |
|
| 48 |
|
| 49 |
#: Can be used as a parameter set id to hide it from the test name. |
| 50 |
HIDDEN_PARAM = _HiddenParam.token |
| 51 |
|
| 52 |
|
| 53 |
def istestfunc(func) -> bool: |
| 54 |
return callable(func) and getattr(func, "__name__", "<lambda>") != "<lambda>" |
| 55 |
|
| 56 |
|
| 57 |
def get_empty_parameterset_mark( |
| 58 |
config: Config, argnames: Sequence[str], func |
| 59 |
) -> MarkDecorator: |
| 60 |
from ..nodes import Collector |
| 61 |
|
| 62 |
argslisting = ", ".join(argnames) |
| 63 |
|
| 64 |
_fs, lineno = getfslineno(func) |
| 65 |
reason = f"got empty parameter set for ({argslisting})" |
| 66 |
requested_mark = config.getini(EMPTY_PARAMETERSET_OPTION) |
| 67 |
if requested_mark in ("", None, "skip"): |
| 68 |
mark = MARK_GEN.skip(reason=reason) |
| 69 |
elif requested_mark == "xfail": |
| 70 |
mark = MARK_GEN.xfail(reason=reason, run=False) |
| 71 |
elif requested_mark == "fail_at_collect": |
| 72 |
raise Collector.CollectError( |
| 73 |
f"Empty parameter set in '{func.__name__}' at line {lineno + 1}" |
| 74 |
) |
| 75 |
else: |
| 76 |
raise LookupError(requested_mark) |
| 77 |
return mark |
| 78 |
|
| 79 |
|
| 80 |
class ParameterSet(NamedTuple): |
| 81 |
"""A set of values for a set of parameters along with associated marks and |
| 82 |
an optional ID for the set. |
| 83 |
|
| 84 |
Examples:: |
| 85 |
|
| 86 |
pytest.param(1, 2, 3) |
| 87 |
# ParameterSet(values=(1, 2, 3), marks=(), id=None) |
| 88 |
|
| 89 |
pytest.param("hello", id="greeting") |
| 90 |
# ParameterSet(values=("hello",), marks=(), id="greeting") |
| 91 |
|
| 92 |
# Parameter set with marks |
| 93 |
pytest.param(42, marks=pytest.mark.xfail) |
| 94 |
# ParameterSet(values=(42,), marks=(MarkDecorator(...),), id=None) |
| 95 |
|
| 96 |
# From parametrize mark (parameter names + list of parameter sets) |
| 97 |
pytest.mark.parametrize( |
| 98 |
("a", "b", "expected"), |
| 99 |
[ |
| 100 |
(1, 2, 3), |
| 101 |
pytest.param(40, 2, 42, id="everything"), |
| 102 |
], |
| 103 |
) |
| 104 |
# ParameterSet(values=(1, 2, 3), marks=(), id=None) |
| 105 |
# ParameterSet(values=(40, 2, 42), marks=(), id="everything") |
| 106 |
""" |
| 107 |
|
| 108 |
values: Sequence[object | NotSetType] |
| 109 |
marks: Collection[MarkDecorator | Mark] |
| 110 |
id: str | _HiddenParam | None |
| 111 |
|
| 112 |
@classmethod |
| 113 |
def param( |
| 114 |
cls, |
| 115 |
*values: object, |
| 116 |
marks: MarkDecorator | Collection[MarkDecorator | Mark] = (), |
| 117 |
id: str | _HiddenParam | None = None, |
| 118 |
) -> ParameterSet: |
| 119 |
if isinstance(marks, MarkDecorator): |
| 120 |
marks = (marks,) |
| 121 |
else: |
| 122 |
assert isinstance(marks, collections.abc.Collection) |
| 123 |
if any(i.name == "usefixtures" for i in marks): |
| 124 |
raise ValueError( |
| 125 |
"pytest.param cannot add pytest.mark.usefixtures; see " |
| 126 |
"https://docs.pytest.org/en/stable/reference/reference.html#pytest-param" |
| 127 |
) |
| 128 |
|
| 129 |
if id is not None: |
| 130 |
if not isinstance(id, str) and id is not HIDDEN_PARAM: |
| 131 |
raise TypeError( |
| 132 |
"Expected id to be a string or a `pytest.HIDDEN_PARAM` sentinel, " |
| 133 |
f"got {type(id)}: {id!r}", |
| 134 |
) |
| 135 |
return cls(values, marks, id) |
| 136 |
|
| 137 |
@classmethod |
| 138 |
def extract_from( |
| 139 |
cls, |
| 140 |
parameterset: ParameterSet | Sequence[object] | object, |
| 141 |
force_tuple: bool = False, |
| 142 |
) -> ParameterSet: |
| 143 |
"""Extract from an object or objects. |
| 144 |
|
| 145 |
:param parameterset: |
| 146 |
A legacy style parameterset that may or may not be a tuple, |
| 147 |
and may or may not be wrapped into a mess of mark objects. |
| 148 |
|
| 149 |
:param force_tuple: |
| 150 |
Enforce tuple wrapping so single argument tuple values |
| 151 |
don't get decomposed and break tests. |
| 152 |
""" |
| 153 |
if isinstance(parameterset, cls): |
| 154 |
return parameterset |
| 155 |
if force_tuple: |
| 156 |
return cls.param(parameterset) |
| 157 |
else: |
| 158 |
# TODO: Refactor to fix this type-ignore. Currently the following |
| 159 |
# passes type-checking but crashes: |
| 160 |
# |
| 161 |
# @pytest.mark.parametrize(('x', 'y'), [1, 2]) |
| 162 |
# def test_foo(x, y): pass |
| 163 |
return cls(parameterset, marks=[], id=None) # type: ignore[arg-type] |
| 164 |
|
| 165 |
@staticmethod |
| 166 |
def _parse_parametrize_args( |
| 167 |
argnames: str | Sequence[str], |
| 168 |
argvalues: Iterable[ParameterSet | Sequence[object] | object], |
| 169 |
*args, |
| 170 |
**kwargs, |
| 171 |
) -> tuple[Sequence[str], bool]: |
| 172 |
if isinstance(argnames, str): |
| 173 |
# A trailing comma indicates tuple-style: "arg," is equivalent to ("arg",) |
| 174 |
# In this case, argvalues should be a list of tuples, not wrapped values. |
| 175 |
# See https://github.com/pytest-dev/pytest/issues/719 |
| 176 |
has_trailing_comma = argnames.rstrip().endswith(",") |
| 177 |
argnames = [x.strip() for x in argnames.split(",") if x.strip()] |
| 178 |
force_tuple = len(argnames) == 1 and not has_trailing_comma |
| 179 |
else: |
| 180 |
force_tuple = False |
| 181 |
return argnames, force_tuple |
| 182 |
|
| 183 |
@staticmethod |
| 184 |
def _parse_parametrize_parameters( |
| 185 |
argvalues: Iterable[ParameterSet | Sequence[object] | object], |
| 186 |
force_tuple: bool, |
| 187 |
) -> list[ParameterSet]: |
| 188 |
return [ |
| 189 |
ParameterSet.extract_from(x, force_tuple=force_tuple) for x in argvalues |
| 190 |
] |
| 191 |
|
| 192 |
@classmethod |
| 193 |
def _for_parametrize( |
| 194 |
cls, |
| 195 |
argnames: str | Sequence[str], |
| 196 |
argvalues: Iterable[ParameterSet | Sequence[object] | object], |
| 197 |
func, |
| 198 |
config: Config, |
| 199 |
nodeid: str, |
| 200 |
) -> tuple[Sequence[str], list[ParameterSet]]: |
| 201 |
if not isinstance(argvalues, Collection): |
| 202 |
warnings.warn( |
| 203 |
PARAMETRIZE_NON_COLLECTION_ITERABLE.format( |
| 204 |
nodeid=nodeid, |
| 205 |
type_name=type(argvalues).__name__, |
| 206 |
), |
| 207 |
stacklevel=3, |
| 208 |
) |
| 209 |
|
| 210 |
argnames, force_tuple = cls._parse_parametrize_args(argnames, argvalues) |
| 211 |
parameters = cls._parse_parametrize_parameters(argvalues, force_tuple) |
| 212 |
del argvalues |
| 213 |
|
| 214 |
if parameters: |
| 215 |
# Check all parameter sets have the correct number of values. |
| 216 |
for param in parameters: |
| 217 |
if len(param.values) != len(argnames): |
| 218 |
msg = ( |
| 219 |
'{nodeid}: in "parametrize" the number of names ({names_len}):\n' |
| 220 |
" {names}\n" |
| 221 |
"must be equal to the number of values ({values_len}):\n" |
| 222 |
" {values}" |
| 223 |
) |
| 224 |
fail( |
| 225 |
msg.format( |
| 226 |
nodeid=nodeid, |
| 227 |
values=param.values, |
| 228 |
names=argnames, |
| 229 |
names_len=len(argnames), |
| 230 |
values_len=len(param.values), |
| 231 |
), |
| 232 |
pytrace=False, |
| 233 |
) |
| 234 |
else: |
| 235 |
# Empty parameter set (likely computed at runtime): create a single |
| 236 |
# parameter set with NOTSET values, with the "empty parameter set" mark applied to it. |
| 237 |
mark = get_empty_parameterset_mark(config, argnames, func) |
| 238 |
parameters.append( |
| 239 |
ParameterSet( |
| 240 |
values=(NOTSET,) * len(argnames), marks=[mark], id="NOTSET" |
| 241 |
) |
| 242 |
) |
| 243 |
return argnames, parameters |
| 244 |
|
| 245 |
|
| 246 |
@final |
| 247 |
@dataclasses.dataclass(frozen=True) |
| 248 |
class Mark: |
| 249 |
"""A pytest mark.""" |
| 250 |
|
| 251 |
#: Name of the mark. |
| 252 |
name: str |
| 253 |
#: Positional arguments of the mark decorator. |
| 254 |
args: tuple[Any, ...] |
| 255 |
#: Keyword arguments of the mark decorator. |
| 256 |
kwargs: Mapping[str, Any] |
| 257 |
|
| 258 |
#: Source Mark for ids with parametrize Marks. |
| 259 |
_param_ids_from: Mark | None = dataclasses.field(default=None, repr=False) |
| 260 |
#: Resolved/generated ids with parametrize Marks. |
| 261 |
_param_ids_generated: Sequence[str] | None = dataclasses.field( |
| 262 |
default=None, repr=False |
| 263 |
) |
| 264 |
|
| 265 |
def __init__( |
| 266 |
self, |
| 267 |
name: str, |
| 268 |
args: tuple[Any, ...], |
| 269 |
kwargs: Mapping[str, Any], |
| 270 |
param_ids_from: Mark | None = None, |
| 271 |
param_ids_generated: Sequence[str] | None = None, |
| 272 |
*, |
| 273 |
_ispytest: bool = False, |
| 274 |
) -> None: |
| 275 |
""":meta private:""" |
| 276 |
check_ispytest(_ispytest) |
| 277 |
# Weirdness to bypass frozen=True. |
| 278 |
object.__setattr__(self, "name", name) |
| 279 |
object.__setattr__(self, "args", args) |
| 280 |
object.__setattr__(self, "kwargs", kwargs) |
| 281 |
object.__setattr__(self, "_param_ids_from", param_ids_from) |
| 282 |
object.__setattr__(self, "_param_ids_generated", param_ids_generated) |
| 283 |
|
| 284 |
def _has_param_ids(self) -> bool: |
| 285 |
return "ids" in self.kwargs or len(self.args) >= 4 |
| 286 |
|
| 287 |
def combined_with(self, other: Mark) -> Mark: |
| 288 |
"""Return a new Mark which is a combination of this |
| 289 |
Mark and another Mark. |
| 290 |
|
| 291 |
Combines by appending args and merging kwargs. |
| 292 |
|
| 293 |
:param Mark other: The mark to combine with. |
| 294 |
:rtype: Mark |
| 295 |
""" |
| 296 |
assert self.name == other.name |
| 297 |
|
| 298 |
# Remember source of ids with parametrize Marks. |
| 299 |
param_ids_from: Mark | None = None |
| 300 |
if self.name == "parametrize": |
| 301 |
if other._has_param_ids(): |
| 302 |
param_ids_from = other |
| 303 |
elif self._has_param_ids(): |
| 304 |
param_ids_from = self |
| 305 |
|
| 306 |
return Mark( |
| 307 |
self.name, |
| 308 |
self.args + other.args, |
| 309 |
dict(self.kwargs, **other.kwargs), |
| 310 |
param_ids_from=param_ids_from, |
| 311 |
_ispytest=True, |
| 312 |
) |
| 313 |
|
| 314 |
|
| 315 |
# A generic parameter designating an object to which a Mark may |
| 316 |
# be applied -- a test function (callable) or class. |
| 317 |
# Note: a lambda is not allowed, but this can't be represented. |
| 318 |
Markable = TypeVar("Markable", bound=Callable[..., object] | type) |
| 319 |
|
| 320 |
|
| 321 |
@dataclasses.dataclass |
| 322 |
class MarkDecorator: |
| 323 |
"""A decorator for applying a mark on test functions and classes. |
| 324 |
|
| 325 |
``MarkDecorators`` are created with ``pytest.mark``:: |
| 326 |
|
| 327 |
mark1 = pytest.mark.NAME # Simple MarkDecorator |
| 328 |
mark2 = pytest.mark.NAME(name1=value) # Parametrized MarkDecorator |
| 329 |
|
| 330 |
and can then be applied as decorators to test functions:: |
| 331 |
|
| 332 |
@mark2 |
| 333 |
def test_function(): |
| 334 |
pass |
| 335 |
|
| 336 |
When a ``MarkDecorator`` is called, it does the following: |
| 337 |
|
| 338 |
1. If called with a single class as its only positional argument and no |
| 339 |
additional keyword arguments, it attaches the mark to the class so it |
| 340 |
gets applied automatically to all test cases found in that class. |
| 341 |
|
| 342 |
2. If called with a single function as its only positional argument and |
| 343 |
no additional keyword arguments, it attaches the mark to the function, |
| 344 |
containing all the arguments already stored internally in the |
| 345 |
``MarkDecorator``. |
| 346 |
|
| 347 |
3. When called in any other case, it returns a new ``MarkDecorator`` |
| 348 |
instance with the original ``MarkDecorator``'s content updated with |
| 349 |
the arguments passed to this call. |
| 350 |
|
| 351 |
Note: The rules above prevent a ``MarkDecorator`` from storing only a |
| 352 |
single function or class reference as its positional argument with no |
| 353 |
additional keyword or positional arguments. You can work around this by |
| 354 |
using `with_args()`. |
| 355 |
""" |
| 356 |
|
| 357 |
mark: Mark |
| 358 |
|
| 359 |
def __init__(self, mark: Mark, *, _ispytest: bool = False) -> None: |
| 360 |
""":meta private:""" |
| 361 |
check_ispytest(_ispytest) |
| 362 |
self.mark = mark |
| 363 |
|
| 364 |
@property |
| 365 |
def name(self) -> str: |
| 366 |
"""Alias for mark.name.""" |
| 367 |
return self.mark.name |
| 368 |
|
| 369 |
@property |
| 370 |
def args(self) -> tuple[Any, ...]: |
| 371 |
"""Alias for mark.args.""" |
| 372 |
return self.mark.args |
| 373 |
|
| 374 |
@property |
| 375 |
def kwargs(self) -> Mapping[str, Any]: |
| 376 |
"""Alias for mark.kwargs.""" |
| 377 |
return self.mark.kwargs |
| 378 |
|
| 379 |
@property |
| 380 |
def markname(self) -> str: |
| 381 |
""":meta private:""" |
| 382 |
return self.name # for backward-compat (2.4.1 had this attr) |
| 383 |
|
| 384 |
def with_args(self, *args: object, **kwargs: object) -> MarkDecorator: |
| 385 |
"""Return a MarkDecorator with extra arguments added. |
| 386 |
|
| 387 |
Unlike calling the MarkDecorator, with_args() can be used even |
| 388 |
if the sole argument is a callable/class. |
| 389 |
""" |
| 390 |
mark = Mark(self.name, args, kwargs, _ispytest=True) |
| 391 |
return MarkDecorator(self.mark.combined_with(mark), _ispytest=True) |
| 392 |
|
| 393 |
# Type ignored because the overloads overlap with an incompatible |
| 394 |
# return type. Not much we can do about that. Thankfully mypy picks |
| 395 |
# the first match so it works out even if we break the rules. |
| 396 |
@overload |
| 397 |
def __call__(self, arg: Markable) -> Markable: # type: ignore[overload-overlap] |
| 398 |
pass |
| 399 |
|
| 400 |
@overload |
| 401 |
def __call__(self, *args: object, **kwargs: object) -> MarkDecorator: |
| 402 |
pass |
| 403 |
|
| 404 |
def __call__(self, *args: object, **kwargs: object): |
| 405 |
"""Call the MarkDecorator.""" |
| 406 |
if args and not kwargs: |
| 407 |
func = args[0] |
| 408 |
is_class = inspect.isclass(func) |
| 409 |
# For staticmethods/classmethods, the marks are eventually fetched from the |
| 410 |
# function object, not the descriptor, so unwrap. |
| 411 |
unwrapped_func = func |
| 412 |
if isinstance(func, staticmethod | classmethod): |
| 413 |
unwrapped_func = func.__func__ |
| 414 |
if len(args) == 1 and (istestfunc(unwrapped_func) or is_class): |
| 415 |
store_mark(unwrapped_func, self.mark) |
| 416 |
return func |
| 417 |
return self.with_args(*args, **kwargs) |
| 418 |
|
| 419 |
|
| 420 |
def get_unpacked_marks( |
| 421 |
obj: object | type, |
| 422 |
*, |
| 423 |
consider_mro: bool = True, |
| 424 |
) -> list[Mark]: |
| 425 |
"""Obtain the unpacked marks that are stored on an object. |
| 426 |
|
| 427 |
If obj is a class and consider_mro is true, return marks applied to |
| 428 |
this class and all of its super-classes in MRO order. If consider_mro |
| 429 |
is false, only return marks applied directly to this class. |
| 430 |
""" |
| 431 |
if isinstance(obj, type): |
| 432 |
if not consider_mro: |
| 433 |
mark_lists = [obj.__dict__.get("pytestmark", [])] |
| 434 |
else: |
| 435 |
mark_lists = [ |
| 436 |
x.__dict__.get("pytestmark", []) for x in reversed(obj.__mro__) |
| 437 |
] |
| 438 |
mark_list = [] |
| 439 |
for item in mark_lists: |
| 440 |
if isinstance(item, list): |
| 441 |
mark_list.extend(item) |
| 442 |
else: |
| 443 |
mark_list.append(item) |
| 444 |
else: |
| 445 |
mark_attribute = getattr(obj, "pytestmark", []) |
| 446 |
if mark_attribute is None: |
| 447 |
warnings.warn( |
| 448 |
"Module defines a `__getattr__` which returns None for " |
| 449 |
"'pytestmark' instead of raising AttributeError. " |
| 450 |
"Make sure `__getattr__` raises AttributeError for " |
| 451 |
"attributes it does not provide. " |
| 452 |
"See https://github.com/pytest-dev/pytest/issues/8265", |
| 453 |
PytestCollectionWarning, |
| 454 |
stacklevel=2, |
| 455 |
) |
| 456 |
mark_list = [] |
| 457 |
elif isinstance(mark_attribute, list): |
| 458 |
mark_list = mark_attribute |
| 459 |
else: |
| 460 |
mark_list = [mark_attribute] |
| 461 |
return list(normalize_mark_list(mark_list)) |
| 462 |
|
| 463 |
|
| 464 |
def normalize_mark_list( |
| 465 |
mark_list: Iterable[Mark | MarkDecorator], |
| 466 |
) -> Iterable[Mark]: |
| 467 |
""" |
| 468 |
Normalize an iterable of Mark or MarkDecorator objects into a list of marks |
| 469 |
by retrieving the `mark` attribute on MarkDecorator instances. |
| 470 |
|
| 471 |
:param mark_list: marks to normalize |
| 472 |
:returns: A new list of the extracted Mark objects |
| 473 |
""" |
| 474 |
for mark in mark_list: |
| 475 |
mark_obj = getattr(mark, "mark", mark) |
| 476 |
if not isinstance(mark_obj, Mark): |
| 477 |
raise TypeError(f"got {mark_obj!r} instead of Mark") |
| 478 |
yield mark_obj |
| 479 |
|
| 480 |
|
| 481 |
def store_mark(obj, mark: Mark) -> None: |
| 482 |
"""Store a Mark on an object. |
| 483 |
|
| 484 |
This is used to implement the Mark declarations/decorators correctly. |
| 485 |
""" |
| 486 |
assert isinstance(mark, Mark), mark |
| 487 |
|
| 488 |
from ..fixtures import getfixturemarker |
| 489 |
|
| 490 |
if getfixturemarker(obj) is not None: |
| 491 |
fail( |
| 492 |
"Marks cannot be applied to fixtures.\n" |
| 493 |
"See docs: https://docs.pytest.org/en/stable/deprecations.html#applying-a-mark-to-a-fixture-function" |
| 494 |
) |
| 495 |
|
| 496 |
# Always reassign name to avoid updating pytestmark in a reference that |
| 497 |
# was only borrowed. |
| 498 |
obj.pytestmark = [*get_unpacked_marks(obj, consider_mro=False), mark] |
| 499 |
|
| 500 |
|
| 501 |
# Typing for builtin pytest marks. This is cheating; it gives builtin marks |
| 502 |
# special privilege, and breaks modularity. But practicality beats purity... |
| 503 |
if TYPE_CHECKING: |
| 504 |
|
| 505 |
class _SkipMarkDecorator(MarkDecorator): |
| 506 |
@overload # type: ignore[override,no-overload-impl] |
| 507 |
def __call__(self, arg: Markable) -> Markable: ... |
| 508 |
|
| 509 |
@overload |
| 510 |
def __call__(self, reason: str = ...) -> MarkDecorator: ... |
| 511 |
|
| 512 |
class _SkipifMarkDecorator(MarkDecorator): |
| 513 |
def __call__( # type: ignore[override] |
| 514 |
self, |
| 515 |
condition: str | bool = ..., |
| 516 |
*conditions: str | bool, |
| 517 |
reason: str = ..., |
| 518 |
) -> MarkDecorator: ... |
| 519 |
|
| 520 |
class _XfailMarkDecorator(MarkDecorator): |
| 521 |
@overload # type: ignore[override,no-overload-impl] |
| 522 |
def __call__(self, arg: Markable) -> Markable: ... |
| 523 |
|
| 524 |
@overload |
| 525 |
def __call__( |
| 526 |
self, |
| 527 |
condition: str | bool = True, |
| 528 |
*conditions: str | bool, |
| 529 |
reason: str = ..., |
| 530 |
run: bool = ..., |
| 531 |
raises: None |
| 532 |
| type[BaseException] |
| 533 |
| tuple[type[BaseException], ...] |
| 534 |
| AbstractRaises[BaseException] = ..., |
| 535 |
strict: bool = ..., |
| 536 |
) -> MarkDecorator: ... |
| 537 |
|
| 538 |
class _ParametrizeMarkDecorator(MarkDecorator): |
| 539 |
def __call__( # type: ignore[override] |
| 540 |
self, |
| 541 |
argnames: str | Sequence[str], |
| 542 |
argvalues: Iterable[ParameterSet | Sequence[object] | object], |
| 543 |
# TODO(pytest10): Change to below after PARAMETRIZE_NON_COLLECTION_ITERABLE deprecation. |
| 544 |
# Overload doesn't work, see #14606. |
| 545 |
# argvalues: Collection[ParameterSet | Sequence[object] | object], |
| 546 |
*, |
| 547 |
indirect: bool | Sequence[str] = ..., |
| 548 |
ids: Iterable[None | str | float | int | bool | _HiddenParam] |
| 549 |
| Callable[[Any], object | None] |
| 550 |
| None = ..., |
| 551 |
scope: ScopeName | None = ..., |
| 552 |
) -> MarkDecorator: ... |
| 553 |
|
| 554 |
class _UsefixturesMarkDecorator(MarkDecorator): |
| 555 |
def __call__(self, *fixtures: str) -> MarkDecorator: # type: ignore[override] |
| 556 |
... |
| 557 |
|
| 558 |
class _FilterwarningsMarkDecorator(MarkDecorator): |
| 559 |
def __call__(self, *filters: str) -> MarkDecorator: # type: ignore[override] |
| 560 |
... |
| 561 |
|
| 562 |
|
| 563 |
@final |
| 564 |
class MarkGenerator: |
| 565 |
"""Factory for :class:`MarkDecorator` objects - exposed as |
| 566 |
a ``pytest.mark`` singleton instance. |
| 567 |
|
| 568 |
Example:: |
| 569 |
|
| 570 |
import pytest |
| 571 |
|
| 572 |
|
| 573 |
@pytest.mark.slowtest |
| 574 |
def test_function(): |
| 575 |
pass |
| 576 |
|
| 577 |
applies a 'slowtest' :class:`Mark` on ``test_function``. |
| 578 |
""" |
| 579 |
|
| 580 |
# See TYPE_CHECKING above. |
| 581 |
if TYPE_CHECKING: |
| 582 |
skip: _SkipMarkDecorator |
| 583 |
skipif: _SkipifMarkDecorator |
| 584 |
xfail: _XfailMarkDecorator |
| 585 |
parametrize: _ParametrizeMarkDecorator |
| 586 |
usefixtures: _UsefixturesMarkDecorator |
| 587 |
filterwarnings: _FilterwarningsMarkDecorator |
| 588 |
|
| 589 |
def __init__(self, *, _ispytest: bool = False) -> None: |
| 590 |
check_ispytest(_ispytest) |
| 591 |
self._config: Config | None = None |
| 592 |
self._markers: set[str] = set() |
| 593 |
|
| 594 |
def __getattr__(self, name: str) -> MarkDecorator: |
| 595 |
"""Generate a new :class:`MarkDecorator` with the given name.""" |
| 596 |
if name[0] == "_": |
| 597 |
raise AttributeError("Marker name must NOT start with underscore") |
| 598 |
|
| 599 |
if self._config is not None: |
| 600 |
# We store a set of markers as a performance optimisation - if a mark |
| 601 |
# name is in the set we definitely know it, but a mark may be known and |
| 602 |
# not in the set. We therefore start by updating the set! |
| 603 |
if name not in self._markers: |
| 604 |
for line in self._config.getini("markers"): |
| 605 |
# example lines: "skipif(condition): skip the given test if..." |
| 606 |
# or "hypothesis: tests which use Hypothesis", so to get the |
| 607 |
# marker name we split on both `:` and `(`. |
| 608 |
marker = line.split(":")[0].split("(")[0].strip() |
| 609 |
self._markers.add(marker) |
| 610 |
|
| 611 |
# If the name is not in the set of known marks after updating, |
| 612 |
# then it really is time to issue a warning or an error. |
| 613 |
if name not in self._markers: |
| 614 |
# Raise a specific error for common misspellings of "parametrize". |
| 615 |
if name in ["parameterize", "parametrise", "parameterise"]: |
| 616 |
__tracebackhide__ = True |
| 617 |
fail(f"Unknown '{name}' mark, did you mean 'parametrize'?") |
| 618 |
|
| 619 |
strict_markers = self._config.getini("strict_markers") |
| 620 |
if strict_markers is None: |
| 621 |
strict_markers = self._config.getini("strict") |
| 622 |
if strict_markers: |
| 623 |
fail( |
| 624 |
f"{name!r} not found in `markers` configuration option", |
| 625 |
pytrace=False, |
| 626 |
) |
| 627 |
|
| 628 |
warnings.warn( |
| 629 |
f"Unknown pytest.mark.{name} - is this a typo? You can register " |
| 630 |
"custom marks to avoid this warning - for details, see " |
| 631 |
"https://docs.pytest.org/en/stable/how-to/mark.html", |
| 632 |
PytestUnknownMarkWarning, |
| 633 |
2, |
| 634 |
) |
| 635 |
|
| 636 |
return MarkDecorator(Mark(name, (), {}, _ispytest=True), _ispytest=True) |
| 637 |
|
| 638 |
|
| 639 |
MARK_GEN = MarkGenerator(_ispytest=True) |
| 640 |
|
| 641 |
|
| 642 |
@final |
| 643 |
class NodeKeywords(MutableMapping[str, Any]): |
| 644 |
__slots__ = ("_markers", "node", "parent") |
| 645 |
|
| 646 |
def __init__(self, node: Node) -> None: |
| 647 |
self.node = node |
| 648 |
self.parent = node.parent |
| 649 |
self._markers = {node.name: True} |
| 650 |
|
| 651 |
def __getitem__(self, key: str) -> Any: |
| 652 |
try: |
| 653 |
return self._markers[key] |
| 654 |
except KeyError: |
| 655 |
if self.parent is None: |
| 656 |
raise |
| 657 |
return self.parent.keywords[key] |
| 658 |
|
| 659 |
def __setitem__(self, key: str, value: Any) -> None: |
| 660 |
self._markers[key] = value |
| 661 |
|
| 662 |
# Note: we could've avoided explicitly implementing some of the methods |
| 663 |
# below and use the collections.abc fallback, but that would be slow. |
| 664 |
|
| 665 |
def __contains__(self, key: object) -> bool: |
| 666 |
return key in self._markers or ( |
| 667 |
self.parent is not None and key in self.parent.keywords |
| 668 |
) |
| 669 |
|
| 670 |
def update( # type: ignore[override] |
| 671 |
self, |
| 672 |
other: Mapping[str, Any] | Iterable[tuple[str, Any]] = (), |
| 673 |
**kwds: Any, |
| 674 |
) -> None: |
| 675 |
self._markers.update(other) |
| 676 |
self._markers.update(kwds) |
| 677 |
|
| 678 |
def __delitem__(self, key: str) -> None: |
| 679 |
raise ValueError("cannot delete key in keywords dict") |
| 680 |
|
| 681 |
def __iter__(self) -> Iterator[str]: |
| 682 |
# Doesn't need to be fast. |
| 683 |
yield from self._markers |
| 684 |
if self.parent is not None: |
| 685 |
for keyword in self.parent.keywords: |
| 686 |
# self._marks and self.parent.keywords can have duplicates. |
| 687 |
if keyword not in self._markers: |
| 688 |
yield keyword |
| 689 |
|
| 690 |
def __len__(self) -> int: |
| 691 |
# Doesn't need to be fast. |
| 692 |
return sum(1 for keyword in self) |
| 693 |
|
| 694 |
def __repr__(self) -> str: |
| 695 |
return f"<NodeKeywords for node {self.node}>" |