API 参考

API Reference

本页包含 pytest API 的完整参考。

常量

Constants

pytest.__version__

当前 pytest 版本,以字符串形式:

>>> import pytest
>>> pytest.__version__
'7.0.0'

pytest.version_tuple

Added in version 7.0.

当前的 pytest 版本,以元组形式表示:

>>> import pytest
>>> pytest.version_tuple
(7, 0, 0)

对于预发行版本,最后一个组件将是一个字符串,表示预发行版本:

>>> import pytest
>>> pytest.version_tuple
(7, 0, '0rc1')

函数

Functions

pytest.approx

approx(expected, rel=None, abs=None, nan_ok=False)[source]

Assert that two numbers (or two ordered sequences of numbers) are equal to each other within some tolerance.

Due to the Floating-Point Arithmetic: Issues and Limitations, numbers that we would intuitively expect to be equal are not always so:

>>> 0.1 + 0.2 == 0.3
False

This problem is commonly encountered when writing tests, e.g. when making sure that floating-point values are what you expect them to be. One way to deal with this problem is to assert that two floating-point numbers are equal to within some appropriate tolerance:

>>> abs((0.1 + 0.2) - 0.3) < 1e-6
True

However, comparisons like this are tedious to write and difficult to understand. Furthermore, absolute comparisons like the one above are usually discouraged because there’s no tolerance that works well for all situations. 1e-6 is good for numbers around 1, but too small for very big numbers and too big for very small ones. It’s better to express the tolerance as a fraction of the expected value, but relative comparisons like that are even more difficult to write correctly and concisely.

The approx class performs floating-point comparisons using a syntax that’s as intuitive as possible:

>>> from pytest import approx
>>> 0.1 + 0.2 == approx(0.3)
True

The same syntax also works for ordered sequences of numbers:

>>> (0.1 + 0.2, 0.2 + 0.4) == approx((0.3, 0.6))
True

numpy arrays:

>>> import numpy as np                                                          
>>> np.array([0.1, 0.2]) + np.array([0.2, 0.4]) == approx(np.array([0.3, 0.6])) 
True

And for a numpy array against a scalar:

>>> import numpy as np                                         
>>> np.array([0.1, 0.2]) + np.array([0.2, 0.1]) == approx(0.3) 
True

Only ordered sequences are supported, because approx needs to infer the relative position of the sequences without ambiguity. This means sets and other unordered sequences are not supported.

Finally, dictionary values can also be compared:

>>> {'a': 0.1 + 0.2, 'b': 0.2 + 0.4} == approx({'a': 0.3, 'b': 0.6})
True

The comparison will be true if both mappings have the same keys and their respective values match the expected tolerances.

Tolerances

By default, approx considers numbers within a relative tolerance of 1e-6 (i.e. one part in a million) of its expected value to be equal. This treatment would lead to surprising results if the expected value was 0.0, because nothing but 0.0 itself is relatively close to 0.0. To handle this case less surprisingly, approx also considers numbers within an absolute tolerance of 1e-12 of its expected value to be equal. Infinity and NaN are special cases. Infinity is only considered equal to itself, regardless of the relative tolerance. NaN is not considered equal to anything by default, but you can make it be equal to itself by setting the nan_ok argument to True. (This is meant to facilitate comparing arrays that use NaN to mean “no data”.)

Both the relative and absolute tolerances can be changed by passing arguments to the approx constructor:

>>> 1.0001 == approx(1)
False
>>> 1.0001 == approx(1, rel=1e-3)
True
>>> 1.0001 == approx(1, abs=1e-3)
True

If you specify abs but not rel, the comparison will not consider the relative tolerance at all. In other words, two numbers that are within the default relative tolerance of 1e-6 will still be considered unequal if they exceed the specified absolute tolerance. If you specify both abs and rel, the numbers will be considered equal if either tolerance is met:

>>> 1 + 1e-8 == approx(1)
True
>>> 1 + 1e-8 == approx(1, abs=1e-12)
False
>>> 1 + 1e-8 == approx(1, rel=1e-6, abs=1e-12)
True

You can also use approx to compare nonnumeric types, or dicts and sequences containing nonnumeric types, in which case it falls back to strict equality. This can be useful for comparing dicts and sequences that can contain optional values:

>>> {"required": 1.0000005, "optional": None} == approx({"required": 1, "optional": None})
True
>>> [None, 1.0000005] == approx([None,1])
True
>>> ["foo", 1.0000005] == approx([None,1])
False

If you’re thinking about using approx, then you might want to know how it compares to other good ways of comparing floating-point numbers. All of these algorithms are based on relative and absolute tolerances and should agree for the most part, but they do have meaningful differences:

  • math.isclose(a, b, rel_tol=1e-9, abs_tol=0.0): True if the relative tolerance is met w.r.t. either a or b or if the absolute tolerance is met. Because the relative tolerance is calculated w.r.t. both a and b, this test is symmetric (i.e. neither a nor b is a “reference value”). You have to specify an absolute tolerance if you want to compare to 0.0 because there is no tolerance by default. More information: math.isclose().

  • numpy.isclose(a, b, rtol=1e-5, atol=1e-8): True if the difference between a and b is less that the sum of the relative tolerance w.r.t. b and the absolute tolerance. Because the relative tolerance is only calculated w.r.t. b, this test is asymmetric and you can think of b as the reference value. Support for comparing sequences is provided by numpy.allclose(). More information: numpy.isclose.

  • unittest.TestCase.assertAlmostEqual(a, b): True if a and b are within an absolute tolerance of 1e-7. No relative tolerance is considered , so this function is not appropriate for very large or very small numbers. Also, it’s only available in subclasses of unittest.TestCase and it’s ugly because it doesn’t follow PEP8. More information: unittest.TestCase.assertAlmostEqual().

  • a == pytest.approx(b, rel=1e-6, abs=1e-12): True if the relative tolerance is met w.r.t. b or if the absolute tolerance is met. Because the relative tolerance is only calculated w.r.t. b, this test is asymmetric and you can think of b as the reference value. In the special case that you explicitly specify an absolute tolerance but not a relative tolerance, only the absolute tolerance is considered.

Note

approx can handle numpy arrays, but we recommend the specialised test helpers in Test support (numpy.testing) if you need support for comparisons, NaNs, or ULP-based tolerances.

To match strings using regex, you can use Matches from the re_assert package.

Warning

Changed in version 3.2.

In order to avoid inconsistent behavior, TypeError is raised for >, >=, < and <= comparisons. The example below illustrates the problem:

assert approx(0.1) > 0.1 + 1e-10  # calls approx(0.1).__gt__(0.1 + 1e-10)
assert 0.1 + 1e-10 > approx(0.1)  # calls approx(0.1).__lt__(0.1 + 1e-10)

In the second example one expects approx(0.1).__le__(0.1 + 1e-10) to be called. But instead, approx(0.1).__lt__(0.1 + 1e-10) is used to comparison. This is because the call hierarchy of rich comparisons follows a fixed behavior. More information: object.__ge__()

Changed in version 3.7.1: approx raises TypeError when it encounters a dict value or sequence element of nonnumeric type.

Changed in version 6.1.0: approx falls back to strict equality for nonnumeric types instead of raising TypeError.

pytest.fail

Tutorial: 如何使用 skip 和 xfail 处理无法成功的测试

fail(reason[, pytrace=True])[source]

Explicitly fail an executing test with the given message.

Parameters:
  • reason (str) – The message to show the user as reason for the failure.

  • pytrace (bool) – If False, msg represents the full failure information and no python traceback will be reported.

Raises:

pytest.fail.Exception – The exception that is raised.

class pytest.fail.Exception

The exception raised by pytest.fail().

pytest.skip

skip(reason[, allow_module_level=False])[source]

Skip an executing test with the given message.

This function should be called only during testing (setup, call or teardown) or during collection by using the allow_module_level flag. This function can be called in doctests as well.

Parameters:
  • reason (str) – The message to show the user as reason for the skip.

  • allow_module_level (bool) –

    Allows this function to be called at module level. Raising the skip exception at module level will stop the execution of the module and prevent the collection of all tests in the module, even those defined before the skip call.

    Defaults to False.

Raises:

pytest.skip.Exception – The exception that is raised.

Note

It is better to use the pytest.mark.skipif marker when possible to declare a test to be skipped under certain conditions like mismatching platforms or dependencies. Similarly, use the # doctest: +SKIP directive (see doctest.SKIP) to skip a doctest statically.

class pytest.skip.Exception

The exception raised by pytest.skip().

pytest.importorskip

importorskip(modname, minversion=None, reason=None, *, exc_type=None)[source]

Import and return the requested module modname, or skip the current test if the module cannot be imported.

Parameters:
  • modname (str) – The name of the module to import.

  • minversion (str | None) – If given, the imported module’s __version__ attribute must be at least this minimal version, otherwise the test is still skipped.

  • reason (str | None) – If given, this reason is shown as the message when the module cannot be imported.

  • exc_type (type[ImportError] | None) –

    The exception that should be captured in order to skip modules. Must be ImportError or a subclass.

    If the module can be imported but raises ImportError, pytest will issue a warning to the user, as often users expect the module not to be found (which would raise ModuleNotFoundError instead).

    This warning can be suppressed by passing exc_type=ImportError explicitly.

    See pytest.importorskip default behavior regarding ImportError for details.

Returns:

The imported module. This should be assigned to its canonical name.

Raises:

pytest.skip.Exception – If the module cannot be imported.

Return type:

Any

Example:

docutils = pytest.importorskip("docutils")

Added in version 8.2: The exc_type parameter.

pytest.xfail

xfail(reason='')[source]

Imperatively xfail an executing test or setup function with the given reason.

This function should be called only during testing (setup, call or teardown).

No other code is executed after using xfail() (it is implemented internally by raising an exception).

Parameters:

reason (str) – The message to show the user as reason for the xfail.

Note

It is better to use the pytest.mark.xfail marker when possible to declare a test to be xfailed under certain conditions like known bugs or missing features.

Raises:

pytest.xfail.Exception – The exception that is raised.

class pytest.xfail.Exception

The exception raised by pytest.xfail().

pytest.exit

exit(reason[, returncode=None])[source]

Exit testing process.

Parameters:
  • reason (str) – The message to show as the reason for exiting pytest. reason has a default value only because msg is deprecated.

  • returncode (int | None) – Return code to be used when exiting pytest. None means the same as 0 (no error), same as sys.exit().

Raises:

pytest.exit.Exception – The exception that is raised.

class pytest.exit.Exception

The exception raised by pytest.exit().

pytest.main

Tutorial: 从 Python 代码调用 pytest

main(args=None, plugins=None)[source]

Perform an in-process test run.

Parameters:
  • args (list[str] | PathLike[str] | None) – List of command line arguments. If None or not given, defaults to reading arguments directly from the process command line (sys.argv).

  • plugins (Sequence[str | object] | None) – List of plugin objects to be auto-registered during initialization.

Returns:

An exit code.

Return type:

int | ExitCode

pytest.param

param(*values[, id][, marks])[source]

Specify a parameter in pytest.mark.parametrize calls or parametrized fixtures.

@pytest.mark.parametrize(
    "test_input,expected",
    [
        ("3+5", 8),
        pytest.param("6*9", 42, marks=pytest.mark.xfail),
    ],
)
def test_eval(test_input, expected):
    assert eval(test_input) == expected
Parameters:

pytest.raises

Tutorial: 关于预期异常的断言

with raises(expected_exception: type[E] | tuple[type[E], ...], *, match: str | Pattern[str] | None = ...) RaisesContext[E] as excinfo[source]
with raises(expected_exception: type[E] | tuple[type[E], ...], func: Callable[[...], Any], *args: Any, **kwargs: Any) ExceptionInfo[E] as excinfo

Assert that a code block/function call raises an exception type, or one of its subclasses.

Parameters:
  • expected_exception – The expected exception type, or a tuple if one of multiple possible exception types are expected. Note that subclasses of the passed exceptions will also match.

  • match (str | re.Pattern[str] | None) –

    If specified, a string containing a regular expression, or a regular expression object, that is tested against the string representation of the exception and its PEP 678 __notes__ using re.search().

    To match a literal string that may contain special characters, the pattern can first be escaped with re.escape().

    (This is only used when pytest.raises is used as a context manager, and passed through to the function otherwise. When using pytest.raises as a function, you can use: pytest.raises(Exc, func, match="passed on").match("my pattern").)

Use pytest.raises as a context manager, which will capture the exception of the given type, or any of its subclasses:

>>> import pytest
>>> with pytest.raises(ZeroDivisionError):
...    1/0

If the code block does not raise the expected exception (ZeroDivisionError in the example above), or no exception at all, the check will fail instead.

You can also use the keyword argument match to assert that the exception matches a text or regex:

>>> with pytest.raises(ValueError, match='must be 0 or None'):
...     raise ValueError("value must be 0 or None")

>>> with pytest.raises(ValueError, match=r'must be \d+$'):
...     raise ValueError("value must be 42")

The match argument searches the formatted exception string, which includes any PEP-678 __notes__:

>>> with pytest.raises(ValueError, match=r"had a note added"):  
...     e = ValueError("value must be 42")
...     e.add_note("had a note added")
...     raise e

The context manager produces an ExceptionInfo object which can be used to inspect the details of the captured exception:

>>> with pytest.raises(ValueError) as exc_info:
...     raise ValueError("value must be 42")
>>> assert exc_info.type is ValueError
>>> assert exc_info.value.args[0] == "value must be 42"

Warning

Given that pytest.raises matches subclasses, be wary of using it to match Exception like this:

with pytest.raises(Exception):  # Careful, this will catch ANY exception raised.
    some_function()

Because Exception is the base class of almost all exceptions, it is easy for this to hide real bugs, where the user wrote this expecting a specific exception, but some other exception is being raised due to a bug introduced during a refactoring.

Avoid using pytest.raises to catch Exception unless certain that you really want to catch any exception raised.

Note

When using pytest.raises as a context manager, it’s worthwhile to note that normal context manager rules apply and that the exception raised must be the final line in the scope of the context manager. Lines of code after that, within the scope of the context manager will not be executed. For example:

>>> value = 15
>>> with pytest.raises(ValueError) as exc_info:
...     if value > 10:
...         raise ValueError("value must be <= 10")
...     assert exc_info.type is ValueError  # This will not execute.

Instead, the following approach must be taken (note the difference in scope):

>>> with pytest.raises(ValueError) as exc_info:
...     if value > 10:
...         raise ValueError("value must be <= 10")
...
>>> assert exc_info.type is ValueError

Using with pytest.mark.parametrize

When using pytest.mark.parametrize it is possible to parametrize tests such that some runs raise an exception and others do not.

See 参数化条件提升 for an example.

See also

关于预期异常的断言 for more examples and detailed discussion.

Legacy form

It is possible to specify a callable by passing a to-be-called lambda:

>>> raises(ZeroDivisionError, lambda: 1/0)
<ExceptionInfo ...>

or you can specify an arbitrary callable with arguments:

>>> def f(x): return 1/x
...
>>> raises(ZeroDivisionError, f, 0)
<ExceptionInfo ...>
>>> raises(ZeroDivisionError, f, x=0)
<ExceptionInfo ...>

The form above is fully supported but discouraged for new code because the context manager form is regarded as more readable and less error-prone.

Note

Similar to caught exception objects in Python, explicitly clearing local references to returned ExceptionInfo objects can help the Python interpreter speed up its garbage collection.

Clearing those references breaks a reference cycle (ExceptionInfo –> caught exception –> frame stack raising the exception –> current frame stack –> local variables –> ExceptionInfo) which makes Python keep all objects referenced from that cycle (including all local variables in the current frame) alive until the next cyclic garbage collection run. More detailed information can be found in the official Python documentation for the try statement.

pytest.deprecated_call

Tutorial: 确保代码触发弃用警告

with deprecated_call(*, match: str | Pattern[str] | None = ...) WarningsRecorder[source]
with deprecated_call(func: Callable[[...], T], *args: Any, **kwargs: Any) T

Assert that code produces a DeprecationWarning or PendingDeprecationWarning or FutureWarning.

This function can be used as a context manager:

>>> import warnings
>>> def api_call_v2():
...     warnings.warn('use v3 of this api', DeprecationWarning)
...     return 200

>>> import pytest
>>> with pytest.deprecated_call():
...    assert api_call_v2() == 200

It can also be used by passing a function and *args and **kwargs, in which case it will ensure calling func(*args, **kwargs) produces one of the warnings types above. The return value is the return value of the function.

In the context manager form you may use the keyword argument match to assert that the warning matches a text or regex.

The context manager produces a list of warnings.WarningMessage objects, one for each warning raised.

pytest.register_assert_rewrite

Tutorial: 断言重写

register_assert_rewrite(*names)[source]

Register one or more module names to be rewritten on import.

This function will make sure that this module or all modules inside the package will get their assert statements rewritten. Thus you should make sure to call this before the module is actually imported, usually in your __init__.py if you are a plugin using a package.

Parameters:

names (str) – The module names to register.

pytest.warns

Tutorial: 使用 warns 函数断言警告

with warns(expected_warning: type[Warning] | tuple[type[Warning], ...] = <class 'Warning'>, *, match: str | ~typing.Pattern[str] | None = None) WarningsChecker[source]
with warns(expected_warning: type[Warning] | tuple[type[Warning], ...], func: Callable[[...], T], *args: Any, **kwargs: Any) T

Assert that code raises a particular class of warning.

Specifically, the parameter expected_warning can be a warning class or tuple of warning classes, and the code inside the with block must issue at least one warning of that class or classes.

This helper produces a list of warnings.WarningMessage objects, one for each warning emitted (regardless of whether it is an expected_warning or not). Since pytest 8.0, unmatched warnings are also re-emitted when the context closes.

This function can be used as a context manager:

>>> import pytest
>>> with pytest.warns(RuntimeWarning):
...    warnings.warn("my warning", RuntimeWarning)

In the context manager form you may use the keyword argument match to assert that the warning matches a text or regex:

>>> with pytest.warns(UserWarning, match='must be 0 or None'):
...     warnings.warn("value must be 0 or None", UserWarning)

>>> with pytest.warns(UserWarning, match=r'must be \d+$'):
...     warnings.warn("value must be 42", UserWarning)

>>> with pytest.warns(UserWarning):  # catch re-emitted warning
...     with pytest.warns(UserWarning, match=r'must be \d+$'):
...         warnings.warn("this is not here", UserWarning)
Traceback (most recent call last):
  ...
Failed: DID NOT WARN. No warnings of type ...UserWarning... were emitted...

Using with pytest.mark.parametrize

When using pytest.mark.parametrize it is possible to parametrize tests such that some runs raise a warning and others do not.

This could be achieved in the same way as with exceptions, see 参数化条件提升 for an example.

pytest.freeze_includes

Tutorial: 冻结 pytest

freeze_includes()[source]

Return a list of module names used by pytest that should be included by cx_freeze.

Marks

标记可以用于为 *测试函数*(但不能用于 fixtures)应用元数据,这些元数据可以被 fixtures 或插件访问。

pytest.mark.filterwarnings

教程: @pytest.mark.filterwarnings

为标记的测试项添加警告过滤器。

pytest.mark.filterwarnings(filter)
Parameters:

filter (str) –

一个 警告规格字符串,由元组 (action, message, category, module, lineno) 的内容组成, 这些内容在 Python 文档的 The Warnings Filter 部分中有说明,用 ":" 分隔。可选字段可以省略。 传递用于过滤的模块名称不会进行正则表达式转义。

例如:

@pytest.mark.filterwarnings("ignore:.*usage will be deprecated.*:DeprecationWarning")
def test_foo(): ...

pytest.mark.parametrize

教程: 如何参数化fixtures和测试函数

此标记与 pytest.Metafunc.parametrize() 的签名相同;请参见该部分。

pytest.mark.skip

教程: 跳过测试函数

无条件跳过测试函数。

pytest.mark.skip(reason=None)
Parameters:

reason (str) – 跳过测试函数的原因。

pytest.mark.skipif

教程: 跳过测试函数

如果条件为 True,则跳过测试函数。

pytest.mark.skipif(condition, *, reason=None)
Parameters:
  • condition (bool or str) – 如果条件应该被跳过则为 True/False,或者是一个 条件字符串

  • reason (str) – 跳过测试函数的原因。

pytest.mark.usefixtures

教程: 在类和模块中通过 usefixtures 使用 fixture

将测试函数标记为使用给定的 fixture 名称。

pytest.mark.usefixtures(*names)
Parameters:

args – 要使用的 fixture 名称,以字符串形式表示。

Note

在钩子中使用 usefixtures 时,仅在测试设置之前应用于测试函数时可以加载 fixtures (例如在 pytest_collection_modifyitems 钩子中)。

还要注意,此标记对 fixtures 的应用没有效果。

pytest.mark.xfail

教程: XFail:将测试函数标记为预期失败

将测试函数标记为 预期失败

pytest.mark.xfail(condition=False, *, reason=None, raises=None, run=True, strict=xfail_strict)
Parameters:
  • condition (Union[bool, str]) – 标记测试函数为 xfail 的条件(True/False 或一个 条件字符串)。如果是 bool,还必须指定 reason (见 条件字符串)。

  • reason (str) – 测试函数被标记为 xfail 的原因。

  • raises (Type[Exception]) – 预期由测试函数引发的异常类(或类元组);其他异常将导致测试失败。 注意,传入类的子类也会匹配(类似于 except 语句的工作方式)。

  • run (bool) – 测试函数是否应该实际执行。如果为 False,函数将始终 xfail,并且不会执行(如果函数发生段错误,这很有用)。

  • strict (bool) –

    • 如果为 False,则如果函数失败,将在终端输出中显示为 xfailed,如果函数通过,则显示为 xpass。在这两种情况下,这不会导致测试套件整体失败。这对于标记 不稳定 测试(随机失败的测试)特别有用,以便稍后处理。

    • 如果为 True,则如果函数失败,将在终端输出中显示为 xfailed,但如果意外通过,则将 导致 测试套件失败。这对于标记总是失败的函数特别有用,如果它们意外开始通过,应该有明确的指示(例如,库的新版本修复了已知的 bug)。

    默认为 xfail_strict,默认值为 False

自定义marks

Custom marks

标记是使用工厂对象 pytest.mark 动态创建的,并作为装饰器应用。

例如:

@pytest.mark.timeout(10, "slow", method="thread")
def test_function(): ...

将创建并附加一个 Mark 对象到收集的 Item,然后可以通过 fixtures 或 hooks 使用 Node.iter_markers 访问该对象。 mark 对象将具有以下属性:

mark.args == (10, "slow")
mark.kwargs == {"method": "thread"}

使用多个自定义标记的示例:

@pytest.mark.timeout(10, "slow", method="thread")
@pytest.mark.slow
def test_function(): ...

当使用 Node.iter_markersNode.iter_markers_with_node 处理多个标记时,离函数最近的标记将优先被迭代。上述示例将导致 @pytest.mark.slow 紧接着 @pytest.mark.timeout(...)

Fixtures

教程: Fixtures 参考

Fixtures 通过将其声明为参数名,由测试函数或其他 fixtures 请求。

需要 fixture 的测试示例:

def test_output(capsys):
    print("hello")
    out, err = capsys.readouterr()
    assert out == "hello\n"

需要另一个 fixture 的 fixture 示例:

@pytest.fixture
def db_session(tmp_path):
    fn = tmp_path / "db.file"
    return connect(fn)

有关更多详细信息,请参阅完整的 fixtures 文档

@pytest.fixture

@fixture(fixture_function: FixtureFunction, *, scope: Literal['session', 'package', 'module', 'class', 'function'] | Callable[[str, Config], Literal['session', 'package', 'module', 'class', 'function']] = 'function', params: Iterable[object] | None = None, autouse: bool = False, ids: Sequence[object | None] | Callable[[Any], object | None] | None = None, name: str | None = None) FixtureFunction[source]
@fixture(fixture_function: None = None, *, scope: Literal['session', 'package', 'module', 'class', 'function'] | Callable[[str, Config], Literal['session', 'package', 'module', 'class', 'function']] = 'function', params: Iterable[object] | None = None, autouse: bool = False, ids: Sequence[object | None] | Callable[[Any], object | None] | None = None, name: str | None = None) FixtureFunctionMarker

Decorator to mark a fixture factory function.

This decorator can be used, with or without parameters, to define a fixture function.

The name of the fixture function can later be referenced to cause its invocation ahead of running tests: test modules or classes can use the pytest.mark.usefixtures(fixturename) marker.

Test functions can directly use fixture names as input arguments in which case the fixture instance returned from the fixture function will be injected.

Fixtures can provide their values to test functions using return or yield statements. When using yield the code block after the yield statement is executed as teardown code regardless of the test outcome, and must yield exactly once.

Parameters:
  • scope

    The scope for which this fixture is shared; one of "function" (default), "class", "module", "package" or "session".

    This parameter may also be a callable which receives (fixture_name, config) as parameters, and must return a str with one of the values mentioned above.

    See 动态 scope in the docs for more information.

  • params – An optional list of parameters which will cause multiple invocations of the fixture function and all of the tests using it. The current parameter is available in request.param.

  • autouse – If True, the fixture func is activated for all tests that can see it. If False (the default), an explicit reference is needed to activate the fixture.

  • ids – Sequence of ids each corresponding to the params so that they are part of the test id. If no ids are provided they will be generated automatically from the params.

  • name – The name of the fixture. This defaults to the name of the decorated function. If a fixture is used in the same module in which it is defined, the function name of the fixture will be shadowed by the function arg that requests the fixture; one way to resolve this is to name the decorated function fixture_<fixturename> and then use @pytest.fixture(name='<fixturename>').

capfd

Tutorial: 如何捕获 stdout/stderr 输出

capfd()[source]

Enable text capturing of writes to file descriptors 1 and 2.

The captured output is made available via capfd.readouterr() method calls, which return a (out, err) namedtuple. out and err will be text objects.

Returns an instance of CaptureFixture[str].

Example:

def test_system_echo(capfd):
    os.system('echo "hello"')
    captured = capfd.readouterr()
    assert captured.out == "hello\n"

capfdbinary

Tutorial: 如何捕获 stdout/stderr 输出

capfdbinary()[source]

Enable bytes capturing of writes to file descriptors 1 and 2.

The captured output is made available via capfd.readouterr() method calls, which return a (out, err) namedtuple. out and err will be byte objects.

Returns an instance of CaptureFixture[bytes].

Example:

def test_system_echo(capfdbinary):
    os.system('echo "hello"')
    captured = capfdbinary.readouterr()
    assert captured.out == b"hello\n"

caplog

Tutorial: 如何管理日志记录

caplog()[source]

Access and control log capturing.

Captured logs are available through the following properties/methods:

* caplog.messages        -> list of format-interpolated log messages
* caplog.text            -> string containing formatted log output
* caplog.records         -> list of logging.LogRecord instances
* caplog.record_tuples   -> list of (logger_name, level, message) tuples
* caplog.clear()         -> clear captured records and formatted log output string

Returns a pytest.LogCaptureFixture instance.

final class LogCaptureFixture[source]

Provides access and control of log capturing.

property handler: LogCaptureHandler

Get the logging handler used by the fixture.

get_records(when)[source]

Get the logging records for one of the possible test phases.

Parameters:

when (Literal['setup', 'call', 'teardown']) – Which test phase to obtain the records from. Valid values are: “setup”, “call” and “teardown”.

Returns:

The list of captured records at the given stage.

Return type:

list[LogRecord]

Added in version 3.4.

property text: str

The formatted log text.

property records: list[LogRecord]

The list of log records.

property record_tuples: list[tuple[str, int, str]]

A list of a stripped down version of log records intended for use in assertion comparison.

The format of the tuple is:

(logger_name, log_level, message)

property messages: list[str]

A list of format-interpolated log messages.

Unlike ‘records’, which contains the format string and parameters for interpolation, log messages in this list are all interpolated.

Unlike ‘text’, which contains the output from the handler, log messages in this list are unadorned with levels, timestamps, etc, making exact comparisons more reliable.

Note that traceback or stack info (from logging.exception() or the exc_info or stack_info arguments to the logging functions) is not included, as this is added by the formatter in the handler.

Added in version 3.7.

clear()[source]

Reset the list of log records and the captured log text.

set_level(level, logger=None)[source]

Set the threshold level of a logger for the duration of a test.

Logging messages which are less severe than this level will not be captured.

Changed in version 3.4: The levels of the loggers changed by this function will be restored to their initial values at the end of the test.

Will enable the requested logging level if it was disabled via logging.disable().

Parameters:
  • level (int | str) – The level.

  • logger (str | None) – The logger to update. If not given, the root logger.

with at_level(level, logger=None)[source]

Context manager that sets the level for capturing of logs. After the end of the ‘with’ statement the level is restored to its original value.

Will enable the requested logging level if it was disabled via logging.disable().

Parameters:
  • level (int | str) – The level.

  • logger (str | None) – The logger to update. If not given, the root logger.

with filtering(filter_)[source]

Context manager that temporarily adds the given filter to the caplog’s handler() for the ‘with’ statement block, and removes that filter at the end of the block.

Parameters:

filter – A custom logging.Filter object.

Added in version 7.5.

capsys

Tutorial: 如何捕获 stdout/stderr 输出

capsys()[source]

Enable text capturing of writes to sys.stdout and sys.stderr.

The captured output is made available via capsys.readouterr() method calls, which return a (out, err) namedtuple. out and err will be text objects.

Returns an instance of CaptureFixture[str].

Example:

def test_output(capsys):
    print("hello")
    captured = capsys.readouterr()
    assert captured.out == "hello\n"
class CaptureFixture[source]

Object returned by the capsys, capsysbinary, capfd and capfdbinary fixtures.

readouterr()[source]

Read and return the captured output so far, resetting the internal buffer.

Returns:

The captured content as a namedtuple with out and err string attributes.

Return type:

CaptureResult

with disabled()[source]

Temporarily disable capturing while inside the with block.

capsysbinary

Tutorial: 如何捕获 stdout/stderr 输出

capsysbinary()[source]

Enable bytes capturing of writes to sys.stdout and sys.stderr.

The captured output is made available via capsysbinary.readouterr() method calls, which return a (out, err) namedtuple. out and err will be bytes objects.

Returns an instance of CaptureFixture[bytes].

Example:

def test_output(capsysbinary):
    print("hello")
    captured = capsysbinary.readouterr()
    assert captured.out == b"hello\n"

config.cache

教程: 如何重新运行失败的测试并在测试运行之间保持状态

config.cache 对象允许其他插件和 fixtures 在测试运行之间存储和检索值。要从 fixtures 中访问它,请将 pytestconfig 请求到您的 fixture 中,并通过 pytestconfig.cache 获取。

在底层, cache 插件使用 json 标准库模块的简单 dumps/loads API。

config.cachepytest.Cache 的一个实例:

final class Cache[source]

Instance of the cache fixture.

members:

doctest_namespace

Tutorial: 如何运行文档测试

doctest_namespace()[source]

Fixture that returns a dict that will be injected into the namespace of doctests.

Usually this fixture is used in conjunction with another autouse fixture:

@pytest.fixture(autouse=True)
def add_np(doctest_namespace):
    doctest_namespace["np"] = numpy

For more details: ‘doctest_namespace’ fixture.

monkeypatch

Tutorial: 如何使用 猴子补丁/mock 模块和环境

monkeypatch()[source]

A convenient fixture for monkey-patching.

The fixture provides these methods to modify objects, dictionaries, or os.environ:

All modifications will be undone after the requesting test function or fixture has finished. The raising parameter determines if a KeyError or AttributeError will be raised if the set/deletion operation does not have the specified target.

To undo modifications done by the fixture in a contained scope, use context().

Returns a MonkeyPatch instance.

final class MonkeyPatch[source]

Helper to conveniently monkeypatch attributes/items/environment variables/syspath.

Returned by the monkeypatch fixture.

Changed in version 6.2: Can now also be used directly as pytest.MonkeyPatch(), for when the fixture is not available. In this case, use with MonkeyPatch.context() as mp: or remember to call undo() explicitly.

classmethod with context()[source]

Context manager that returns a new MonkeyPatch object which undoes any patching done inside the with block upon exit.

Example:

import functools


def test_partial(monkeypatch):
    with monkeypatch.context() as m:
        m.setattr(functools, "partial", 3)

Useful in situations where it is desired to undo some patches before the test ends, such as mocking stdlib functions that might break pytest itself if mocked (for examples of this see #3290).

setattr(target: str, name: object, value: ~_pytest.monkeypatch.Notset = <notset>, raising: bool = True) None[source]
setattr(target: object, name: str, value: object, raising: bool = True) None

Set attribute value on target, memorizing the old value.

For example:

import os

monkeypatch.setattr(os, "getcwd", lambda: "/")

The code above replaces the os.getcwd() function by a lambda which always returns "/".

For convenience, you can specify a string as target which will be interpreted as a dotted import path, with the last part being the attribute name:

monkeypatch.setattr("os.getcwd", lambda: "/")

Raises AttributeError if the attribute does not exist, unless raising is set to False.

Where to patch

monkeypatch.setattr works by (temporarily) changing the object that a name points to with another one. There can be many names pointing to any individual object, so for patching to work you must ensure that you patch the name used by the system under test.

See the section Where to patch in the unittest.mock docs for a complete explanation, which is meant for unittest.mock.patch() but applies to monkeypatch.setattr as well.

delattr(target, name=<notset>, raising=True)[source]

Delete attribute name from target.

If no name is specified and target is a string it will be interpreted as a dotted import path with the last part being the attribute name.

Raises AttributeError it the attribute does not exist, unless raising is set to False.

setitem(dic, name, value)[source]

Set dictionary entry name to value.

delitem(dic, name, raising=True)[source]

Delete name from dict.

Raises KeyError if it doesn’t exist, unless raising is set to False.

setenv(name, value, prepend=None)[source]

Set environment variable name to value.

If prepend is a character, read the current environment variable value and prepend the value adjoined with the prepend character.

delenv(name, raising=True)[source]

Delete name from the environment.

Raises KeyError if it does not exist, unless raising is set to False.

syspath_prepend(path)[source]

Prepend path to sys.path list of import locations.

chdir(path)[source]

Change the current working directory to the specified path.

Parameters:

path (str | PathLike[str]) – The path to change into.

undo()[source]

Undo previous changes.

This call consumes the undo stack. Calling it a second time has no effect unless you do more monkeypatching after the undo call.

There is generally no need to call undo(), since it is called automatically during tear-down.

Note

The same monkeypatch fixture is used across a single test function invocation. If monkeypatch is used both by the test function itself and one of the test fixtures, calling undo() will undo all of the changes made in both functions.

Prefer to use context() instead.

pytestconfig

pytestconfig()[source]

Session-scoped fixture that returns the session’s pytest.Config object.

Example:

def test_foo(pytestconfig):
    if pytestconfig.get_verbosity() > 0:
        ...

pytester

Added in version 6.2.

提供一个 Pytester 实例,可以用来运行和测试 pytest 本身。

它提供了一个空目录,pytest 可以在隔离环境中执行,并包含编写测试、配置文件以及与预期输出匹配的工具。

要使用它,请在您的最上层 conftest.py 文件中包含:

pytest_plugins = "pytester"
final class Pytester[source]

Facilities to write tests/configuration files, execute pytest in isolation, and match against expected output, perfect for black-box testing of pytest plugins.

It attempts to isolate the test run from external factors as much as possible, modifying the current working directory to path and environment variables during initialization.

exception TimeoutExpired[source]
plugins: list[str | object]

A list of plugins to use with parseconfig() and runpytest(). Initially this is an empty list but plugins can be added to the list. The type of items to add to the list depends on the method using them so refer to them for details.

property path: Path

Temporary directory path used to create files/run tests from, etc.

make_hook_recorder(pluginmanager)[source]

Create a new HookRecorder for a PytestPluginManager.

chdir()[source]

Cd into the temporary directory.

This is done automatically upon instantiation.

makefile(ext, *args, **kwargs)[source]

Create new text file(s) in the test directory.

Parameters:
  • ext (str) – The extension the file(s) should use, including the dot, e.g. .py.

  • args (str) – All args are treated as strings and joined using newlines. The result is written as contents to the file. The name of the file is based on the test function requesting this fixture.

  • kwargs (str) – Each keyword is the name of a file, while the value of it will be written as contents of the file.

Returns:

The first created file.

Return type:

Path

Examples:

pytester.makefile(".txt", "line1", "line2")

pytester.makefile(".ini", pytest="[pytest]\naddopts=-rs\n")

To create binary files, use pathlib.Path.write_bytes() directly:

filename = pytester.path.joinpath("foo.bin")
filename.write_bytes(b"...")
makeconftest(source)[source]

Write a conftest.py file.

Parameters:

source (str) – The contents.

Returns:

The conftest.py file.

Return type:

Path

makeini(source)[source]

Write a tox.ini file.

Parameters:

source (str) – The contents.

Returns:

The tox.ini file.

Return type:

Path

getinicfg(source)[source]

Return the pytest section from the tox.ini config file.

makepyprojecttoml(source)[source]

Write a pyproject.toml file.

Parameters:

source (str) – The contents.

Returns:

The pyproject.ini file.

Return type:

Path

Added in version 6.0.

makepyfile(*args, **kwargs)[source]

Shortcut for .makefile() with a .py extension.

Defaults to the test name with a ‘.py’ extension, e.g test_foobar.py, overwriting existing files.

Examples:

def test_something(pytester):
    # Initial file is created test_something.py.
    pytester.makepyfile("foobar")
    # To create multiple files, pass kwargs accordingly.
    pytester.makepyfile(custom="foobar")
    # At this point, both 'test_something.py' & 'custom.py' exist in the test directory.
maketxtfile(*args, **kwargs)[source]

Shortcut for .makefile() with a .txt extension.

Defaults to the test name with a ‘.txt’ extension, e.g test_foobar.txt, overwriting existing files.

Examples:

def test_something(pytester):
    # Initial file is created test_something.txt.
    pytester.maketxtfile("foobar")
    # To create multiple files, pass kwargs accordingly.
    pytester.maketxtfile(custom="foobar")
    # At this point, both 'test_something.txt' & 'custom.txt' exist in the test directory.
syspathinsert(path=None)[source]

Prepend a directory to sys.path, defaults to path.

This is undone automatically when this object dies at the end of each test.

Parameters:

path (str | PathLike[str] | None) – The path.

mkdir(name)[source]

Create a new (sub)directory.

Parameters:

name (str | PathLike[str]) – The name of the directory, relative to the pytester path.

Returns:

The created directory.

Return type:

pathlib.Path

mkpydir(name)[source]

Create a new python package.

This creates a (sub)directory with an empty __init__.py file so it gets recognised as a Python package.

copy_example(name=None)[source]

Copy file from project’s directory into the testdir.

Parameters:

name (str | None) – The name of the file to copy.

Returns:

Path to the copied directory (inside self.path).

Return type:

pathlib.Path

getnode(config, arg)[source]

Get the collection node of a file.

Parameters:
Returns:

The node.

Return type:

Collector | Item

getpathnode(path)[source]

Return the collection node of a file.

This is like getnode() but uses parseconfigure() to create the (configured) pytest Config instance.

Parameters:

path (str | PathLike[str]) – Path to the file.

Returns:

The node.

Return type:

Collector | Item

genitems(colitems)[source]

Generate all test items from a collection node.

This recurses into the collection node and returns a list of all the test items contained within.

Parameters:

colitems (Sequence[Item | Collector]) – The collection nodes.

Returns:

The collected items.

Return type:

list[Item]

runitem(source)[source]

Run the “test_func” Item.

The calling test instance (class containing the test method) must provide a .getrunner() method which should return a runner which can run the test protocol for a single item, e.g. _pytest.runner.runtestprotocol.

inline_runsource(source, *cmdlineargs)[source]

Run a test module in process using pytest.main().

This run writes “source” into a temporary file and runs pytest.main() on it, returning a HookRecorder instance for the result.

Parameters:
  • source (str) – The source code of the test module.

  • cmdlineargs – Any extra command line arguments to use.

inline_genitems(*args)[source]

Run pytest.main(['--collect-only']) in-process.

Runs the pytest.main() function to run all of pytest inside the test process itself like inline_run(), but returns a tuple of the collected items and a HookRecorder instance.

inline_run(*args, plugins=(), no_reraise_ctrlc=False)[source]

Run pytest.main() in-process, returning a HookRecorder.

Runs the pytest.main() function to run all of pytest inside the test process itself. This means it can return a HookRecorder instance which gives more detailed results from that run than can be done by matching stdout/stderr from runpytest().

Parameters:
  • args (str | PathLike[str]) – Command line arguments to pass to pytest.main().

  • plugins – Extra plugin instances the pytest.main() instance should use.

  • no_reraise_ctrlc (bool) – Typically we reraise keyboard interrupts from the child run. If True, the KeyboardInterrupt exception is captured.

runpytest_inprocess(*args, **kwargs)[source]

Return result of running pytest in-process, providing a similar interface to what self.runpytest() provides.

runpytest(*args, **kwargs)[source]

Run pytest inline or in a subprocess, depending on the command line option “–runpytest” and return a RunResult.

parseconfig(*args)[source]

Return a new pytest pytest.Config instance from given commandline args.

This invokes the pytest bootstrapping code in _pytest.config to create a new pytest.PytestPluginManager and call the pytest_cmdline_parse hook to create a new pytest.Config instance.

If plugins has been populated they should be plugin modules to be registered with the plugin manager.

parseconfigure(*args)[source]

Return a new pytest configured Config instance.

Returns a new pytest.Config instance like parseconfig(), but also calls the pytest_configure hook.

getitem(source, funcname='test_func')[source]

Return the test item for a test function.

Writes the source to a python file and runs pytest’s collection on the resulting module, returning the test item for the requested function name.

Parameters:
  • source (str | PathLike[str]) – The module source.

  • funcname (str) – The name of the test function for which to return a test item.

Returns:

The test item.

Return type:

Item

getitems(source)[source]

Return all test items collected from the module.

Writes the source to a Python file and runs pytest’s collection on the resulting module, returning all test items contained within.

getmodulecol(source, configargs=(), *, withinit=False)[source]

Return the module collection node for source.

Writes source to a file using makepyfile() and then runs the pytest collection on it, returning the collection node for the test module.

Parameters:
  • source (str | PathLike[str]) – The source code of the module to collect.

  • configargs – Any extra arguments to pass to parseconfigure().

  • withinit (bool) – Whether to also write an __init__.py file to the same directory to ensure it is a package.

collect_by_name(modcol, name)[source]

Return the collection node for name from the module collection.

Searches a module collection node for a collection node matching the given name.

Parameters:
popen(cmdargs, stdout=-1, stderr=-1, stdin=NotSetType.token, **kw)[source]

Invoke subprocess.Popen.

Calls subprocess.Popen making sure the current working directory is in PYTHONPATH.

You probably want to use run() instead.

run(*cmdargs, timeout=None, stdin=NotSetType.token)[source]

Run a command with arguments.

Run a process using subprocess.Popen saving the stdout and stderr.

Parameters:
  • cmdargs (str | PathLike[str]) – The sequence of arguments to pass to subprocess.Popen, with path-like objects being converted to str automatically.

  • timeout (float | None) – The period in seconds after which to timeout and raise Pytester.TimeoutExpired.

  • stdin (_pytest.compat.NotSetType | bytes | IO[Any] | int) –

    Optional standard input.

    • If it is CLOSE_STDIN (Default), then this method calls subprocess.Popen with stdin=subprocess.PIPE, and the standard input is closed immediately after the new command is started.

    • If it is of type bytes, these bytes are sent to the standard input of the command.

    • Otherwise, it is passed through to subprocess.Popen. For further information in this case, consult the document of the stdin parameter in subprocess.Popen.

Returns:

The result.

Return type:

RunResult

runpython(script)[source]

Run a python script using sys.executable as interpreter.

runpython_c(command)[source]

Run python -c "command".

runpytest_subprocess(*args, timeout=None)[source]

Run pytest as a subprocess with given arguments.

Any plugins added to the plugins list will be added using the -p command line option. Additionally --basetemp is used to put any temporary files and directories in a numbered directory prefixed with “runpytest-” to not conflict with the normal numbered pytest location for temporary files and directories.

Parameters:
Returns:

The result.

Return type:

RunResult

spawn_pytest(string, expect_timeout=10.0)[source]

Run pytest using pexpect.

This makes sure to use the right pytest and sets up the temporary directory locations.

The pexpect child is returned.

spawn(cmd, expect_timeout=10.0)[source]

Run a command using pexpect.

The pexpect child is returned.

final class RunResult[source]

The result of running a command from Pytester.

ret: int | ExitCode

The return value.

outlines

List of lines captured from stdout.

errlines

List of lines captured from stderr.

stdout

LineMatcher of stdout.

Use e.g. str(stdout) to reconstruct stdout, or the commonly used stdout.fnmatch_lines() method.

stderr

LineMatcher of stderr.

duration

Duration in seconds.

parseoutcomes()[source]

Return a dictionary of outcome noun -> count from parsing the terminal output that the test process produced.

The returned nouns will always be in plural form:

======= 1 failed, 1 passed, 1 warning, 1 error in 0.13s ====

Will return {"failed": 1, "passed": 1, "warnings": 1, "errors": 1}.

classmethod parse_summary_nouns(lines)[source]

Extract the nouns from a pytest terminal summary line.

It always returns the plural noun for consistency:

======= 1 failed, 1 passed, 1 warning, 1 error in 0.13s ====

Will return {"failed": 1, "passed": 1, "warnings": 1, "errors": 1}.

assert_outcomes(passed=0, skipped=0, failed=0, errors=0, xpassed=0, xfailed=0, warnings=None, deselected=None)[source]

Assert that the specified outcomes appear with the respective numbers (0 means it didn’t occur) in the text output from a test run.

warnings and deselected are only checked if not None.

class LineMatcher[source]

Flexible matching of text.

This is a convenience class to test large texts like the output of commands.

The constructor takes a list of lines without their trailing newlines, i.e. text.splitlines().

__str__()[source]

Return the entire original text.

Added in version 6.2: You can use str() in older versions.

fnmatch_lines_random(lines2)[source]

Check lines exist in the output in any order (using fnmatch.fnmatch()).

re_match_lines_random(lines2)[source]

Check lines exist in the output in any order (using re.match()).

get_lines_after(fnline)[source]

Return all lines following the given line in the text.

The given line can contain glob wildcards.

fnmatch_lines(lines2, *, consecutive=False)[source]

Check lines exist in the output (using fnmatch.fnmatch()).

The argument is a list of lines which have to match and can use glob wildcards. If they do not match a pytest.fail() is called. The matches and non-matches are also shown as part of the error message.

Parameters:
  • lines2 (Sequence[str]) – String patterns to match.

  • consecutive (bool) – Match lines consecutively?

re_match_lines(lines2, *, consecutive=False)[source]

Check lines exist in the output (using re.match()).

The argument is a list of lines which have to match using re.match. If they do not match a pytest.fail() is called.

The matches and non-matches are also shown as part of the error message.

Parameters:
  • lines2 (Sequence[str]) – string patterns to match.

  • consecutive (bool) – match lines consecutively?

no_fnmatch_line(pat)[source]

Ensure captured lines do not match the given pattern, using fnmatch.fnmatch.

Parameters:

pat (str) – The pattern to match lines.

no_re_match_line(pat)[source]

Ensure captured lines do not match the given pattern, using re.match.

Parameters:

pat (str) – The regular expression to match lines.

str()[source]

Return the entire original text.

final class HookRecorder[source]

Record all hooks called in a plugin manager.

Hook recorders are created by Pytester.

This wraps all the hook calls in the plugin manager, recording each call before propagating the normal calls.

getcalls(names)[source]

Get all recorded calls to hooks with the given names (or name).

matchreport(inamepart='', names=('pytest_runtest_logreport', 'pytest_collectreport'), when=None)[source]

Return a testreport whose dotted import path matches.

final class RecordedHookCall[source]

A recorded call to a hook.

The arguments to the hook call are set as attributes. For example:

calls = hook_recorder.getcalls("pytest_runtest_setup")
# Suppose pytest_runtest_setup was called once with `item=an_item`.
assert calls[0].item is an_item

record_property

Tutorial: record_property fixture

record_property()[source]

Add extra properties to the calling test.

User properties become part of the test report and are available to the configured reporters, like JUnit XML.

The fixture is callable with name, value. The value is automatically XML-encoded.

Example:

def test_function(record_property):
    record_property("example_key", 1)

record_testsuite_property

Tutorial: record_testsuite_property fixture

record_testsuite_property()[source]

Record a new <property> tag as child of the root <testsuite>.

This is suitable to writing global information regarding the entire test suite, and is compatible with xunit2 JUnit family.

This is a session-scoped fixture which is called with (name, value). Example:

def test_foo(record_testsuite_property):
    record_testsuite_property("ARCH", "PPC")
    record_testsuite_property("STORAGE_TYPE", "CEPH")
Parameters:
  • name – The property name.

  • value – The property value. Will be converted to a string.

Warning

Currently this fixture does not work with the pytest-xdist plugin. See #7767 for details.

recwarn

Tutorial: 记录警告

recwarn()[source]

Return a WarningsRecorder instance that records all warnings emitted by test functions.

See 如何捕获警告 for information on warning categories.

class WarningsRecorder[source]

A context manager to record raised warnings.

Each recorded warning is an instance of warnings.WarningMessage.

Adapted from warnings.catch_warnings.

Note

DeprecationWarning and PendingDeprecationWarning are treated differently; see 确保代码触发弃用警告.

property list: list[WarningMessage]

The list of recorded warnings.

__getitem__(i)[source]

Get a recorded warning by index.

__iter__()[source]

Iterate through the recorded warnings.

__len__()[source]

The number of recorded warnings.

pop(cls=<class 'Warning'>)[source]

Pop the first recorded warning which is an instance of cls, but not an instance of a child class of any other match. Raises AssertionError if there is no match.

clear()[source]

Clear the list of recorded warnings.

request

示例: 根据命令行选项将不同的值传递给测试函数

request 固件是一个特殊的固件,提供请求测试函数的信息。

class FixtureRequest[source]

The type of the request fixture.

A request object gives access to the requesting test context and has a param attribute in case the fixture is parametrized.

fixturename: Final

Fixture for which this request is being performed.

property scope: Literal['session', 'package', 'module', 'class', 'function']

Scope string, one of “function”, “class”, “module”, “package”, “session”.

property fixturenames: list[str]

Names of all active fixtures in this request.

abstract property node

Underlying collection node (depends on current request scope).

property config: Config

The pytest config object associated with this request.

property function

Test function object if the request has a per-function scope.

property cls

Class (can be None) where the test function was collected.

property instance

Instance (can be None) on which test function was collected.

property module

Python module object where the test function was collected.

property path: Path

Path where the test function was collected.

property keywords: MutableMapping[str, Any]

Keywords/markers dictionary for the underlying node.

property session: Session

Pytest session object.

abstractmethod addfinalizer(finalizer)[source]

Add finalizer/teardown function to be called without arguments after the last test within the requesting test context finished execution.

applymarker(marker)[source]

Apply a marker to a single test function invocation.

This method is useful if you don’t want to have a keyword/marker on all function invocations.

Parameters:

marker (str | MarkDecorator) – An object created by a call to pytest.mark.NAME(...).

raiseerror(msg)[source]

Raise a FixtureLookupError exception.

Parameters:

msg (str | None) – An optional custom error message.

getfixturevalue(argname)[source]

Dynamically run a named fixture function.

Declaring fixtures via function argument is recommended where possible. But if you can only decide whether to use another fixture at test setup time, you may use this function to retrieve it inside a fixture or test function body.

This method can be used during the test setup phase or the test run phase, but during the test teardown phase a fixture’s value may not be available.

Parameters:

argname (str) – The fixture name.

Raises:

pytest.FixtureLookupError – If the given fixture could not be found.

testdir

pytester 相同,但在适用时提供返回传统的 py.path.local 对象的实例方法。

新代码应避免使用 testdir,而应使用 pytester

final class Testdir[source]

Similar to Pytester, but this class works with legacy legacy_path objects instead.

All methods just forward to an internal Pytester instance, converting results to legacy_path objects as necessary.

exception TimeoutExpired
property tmpdir: LocalPath

Temporary directory where tests are executed.

make_hook_recorder(pluginmanager)[source]

See Pytester.make_hook_recorder().

chdir()[source]

See Pytester.chdir().

makefile(ext, *args, **kwargs)[source]

See Pytester.makefile().

makeconftest(source)[source]

See Pytester.makeconftest().

makeini(source)[source]

See Pytester.makeini().

getinicfg(source)[source]

See Pytester.getinicfg().

makepyprojecttoml(source)[source]

See Pytester.makepyprojecttoml().

makepyfile(*args, **kwargs)[source]

See Pytester.makepyfile().

maketxtfile(*args, **kwargs)[source]

See Pytester.maketxtfile().

syspathinsert(path=None)[source]

See Pytester.syspathinsert().

mkdir(name)[source]

See Pytester.mkdir().

mkpydir(name)[source]

See Pytester.mkpydir().

copy_example(name=None)[source]

See Pytester.copy_example().

getnode(config, arg)[source]

See Pytester.getnode().

getpathnode(path)[source]

See Pytester.getpathnode().

genitems(colitems)[source]

See Pytester.genitems().

runitem(source)[source]

See Pytester.runitem().

inline_runsource(source, *cmdlineargs)[source]

See Pytester.inline_runsource().

inline_genitems(*args)[source]

See Pytester.inline_genitems().

inline_run(*args, plugins=(), no_reraise_ctrlc=False)[source]

See Pytester.inline_run().

runpytest_inprocess(*args, **kwargs)[source]

See Pytester.runpytest_inprocess().

runpytest(*args, **kwargs)[source]

See Pytester.runpytest().

parseconfig(*args)[source]

See Pytester.parseconfig().

parseconfigure(*args)[source]

See Pytester.parseconfigure().

getitem(source, funcname='test_func')[source]

See Pytester.getitem().

getitems(source)[source]

See Pytester.getitems().

getmodulecol(source, configargs=(), withinit=False)[source]

See Pytester.getmodulecol().

collect_by_name(modcol, name)[source]

See Pytester.collect_by_name().

popen(cmdargs, stdout=-1, stderr=-1, stdin=NotSetType.token, **kw)[source]

See Pytester.popen().

run(*cmdargs, timeout=None, stdin=NotSetType.token)[source]

See Pytester.run().

runpython(script)[source]

See Pytester.runpython().

runpython_c(command)[source]

See Pytester.runpython_c().

runpytest_subprocess(*args, timeout=None)[source]

See Pytester.runpytest_subprocess().

spawn_pytest(string, expect_timeout=10.0)[source]

See Pytester.spawn_pytest().

spawn(cmd, expect_timeout=10.0)[source]

See Pytester.spawn().

tmp_path

Tutorial: 如何在测试中使用临时目录和文件

tmp_path()[source]

Return a temporary directory path object which is unique to each test function invocation, created as a sub directory of the base temporary directory.

By default, a new base temporary directory is created each test session, and old bases are removed after 3 sessions, to aid in debugging. This behavior can be configured with tmp_path_retention_count and tmp_path_retention_policy. If --basetemp is used then it is cleared each session. See 临时目录位置和保留.

The returned object is a pathlib.Path object.

tmp_path_factory

Tutorial: tmp_path_factory fixture

tmp_path_factory is an instance of TempPathFactory:

final class TempPathFactory[source]

Factory for temporary directories under the common base temp directory.

The base directory can be configured using the --basetemp option.

mktemp(basename, numbered=True)[source]

Create a new temporary directory managed by the factory.

Parameters:
  • basename (str) – Directory base name, must be a relative path.

  • numbered (bool) – If True, ensure the directory is unique by adding a numbered suffix greater than any existing one: basename="foo-" and numbered=True means that this function will create directories named "foo-0", "foo-1", "foo-2" and so on.

Returns:

The path to the new directory.

Return type:

Path

getbasetemp()[source]

Return the base temporary directory, creating it if needed.

Returns:

The base temporary directory.

Return type:

Path

tmpdir

Tutorial: tmpdir 和 tmpdir_factory fixtures

tmpdir()

Return a temporary directory path object which is unique to each test function invocation, created as a sub directory of the base temporary directory.

By default, a new base temporary directory is created each test session, and old bases are removed after 3 sessions, to aid in debugging. If --basetemp is used then it is cleared each session. See 临时目录位置和保留.

The returned object is a legacy_path object.

Note

These days, it is preferred to use tmp_path.

About the tmpdir and tmpdir_factory fixtures.

tmpdir_factory

教程: tmpdir 和 tmpdir_factory fixtures

tmpdir_factoryTempdirFactory 的一个实例:

final class TempdirFactory[source]

Backward compatibility wrapper that implements py.path.local for TempPathFactory.

Note

These days, it is preferred to use tmp_path_factory.

About the tmpdir and tmpdir_factory fixtures.

mktemp(basename, numbered=True)[source]

Same as TempPathFactory.mktemp(), but returns a py.path.local object.

getbasetemp()[source]

Same as TempPathFactory.getbasetemp(), but returns a py.path.local object.

Hooks

教程: 编写插件

参考所有可以通过 conftest.py 文件插件 实现的钩子。

@pytest.hookimpl

@pytest.hookimpl

pytest 的装饰器用于将函数标记为钩子实现。

编写钩子函数pluggy.HookimplMarker().

@pytest.hookspec

@pytest.hookspec

pytest 的装饰器用于将函数标记为钩子实现。

声明新钩子 and pluggy.HookspecMarker().

引导钩子

Bootstrapping hooks

引导钩子用于早期注册的插件(内部和第三方插件)。

pytest_load_initial_conftests(early_config, parser, args)[source]

Called to implement the loading of initial conftest files ahead of command line option parsing.

Parameters:
  • early_config (Config) – The pytest config object.

  • args (list[str]) – Arguments passed on the command line.

  • parser (Parser) – To add command line options.

Use in conftest plugins

This hook is not called for conftest files.

pytest_cmdline_parse(pluginmanager, args)[source]

Return an initialized Config, parsing the specified args.

Stops at first non-None result, see firstresult: 在第一个非 None 结果处停止.

Note

This hook is only called for plugin classes passed to the plugins arg when using pytest.main to perform an in-process test run.

Parameters:
  • pluginmanager (PytestPluginManager) – The pytest plugin manager.

  • args (list[str]) – List of arguments passed on the command line.

Returns:

A pytest config object.

Return type:

Config | None

Use in conftest plugins

This hook is not called for conftest files.

pytest_cmdline_main(config)[source]

Called for performing the main command line action.

The default implementation will invoke the configure hooks and pytest_runtestloop.

Stops at first non-None result, see firstresult: 在第一个非 None 结果处停止.

Parameters:

config (Config) – The pytest config object.

Returns:

The exit code.

Return type:

ExitCode | int | None

Use in conftest plugins

This hook is only called for initial conftests.

初始化钩子

Initialization hooks

初始化挂钩调用插件和 conftest.py 文件。

pytest_addoption(parser, pluginmanager)[source]

Register argparse-style options and ini-style config values, called once at the beginning of a test run.

Parameters:

Options can later be accessed through the config object, respectively:

The config object is passed around on many internal objects via the .config attribute or can be retrieved as the pytestconfig fixture.

Note

This hook is incompatible with hook wrappers.

Use in conftest plugins

If a conftest plugin implements this hook, it will be called immediately when the conftest is registered.

This hook is only called for initial conftests.

pytest_addhooks(pluginmanager)[source]

Called at plugin registration time to allow adding new hooks via a call to pluginmanager.add_hookspecs(module_or_class, prefix).

Parameters:

pluginmanager (PytestPluginManager) – The pytest plugin manager.

Note

This hook is incompatible with hook wrappers.

Use in conftest plugins

If a conftest plugin implements this hook, it will be called immediately when the conftest is registered.

pytest_configure(config)[source]

Allow plugins and conftest files to perform initial configuration.

Note

This hook is incompatible with hook wrappers.

Parameters:

config (Config) – The pytest config object.

Use in conftest plugins

This hook is called for every initial conftest file after command line options have been parsed. After that, the hook is called for other conftest files as they are registered.

pytest_unconfigure(config)[source]

Called before test process is exited.

Parameters:

config (Config) – The pytest config object.

Use in conftest plugins

Any conftest file can implement this hook.

pytest_sessionstart(session)[source]

Called after the Session object has been created and before performing collection and entering the run test loop.

Parameters:

session (Session) – The pytest session object.

Use in conftest plugins

This hook is only called for initial conftests.

pytest_sessionfinish(session, exitstatus)[source]

Called after whole test run finished, right before returning the exit status to the system.

Parameters:
  • session (Session) – The pytest session object.

  • exitstatus (int | ExitCode) – The status which pytest will return to the system.

Use in conftest plugins

Any conftest file can implement this hook.

pytest_plugin_registered(plugin, plugin_name, manager)[source]

A new pytest plugin got registered.

Parameters:
  • plugin (_PluggyPlugin) – The plugin module or instance.

  • plugin_name (str) – The name by which the plugin is registered.

  • manager (PytestPluginManager) – The pytest plugin manager.

Note

This hook is incompatible with hook wrappers.

Use in conftest plugins

If a conftest plugin implements this hook, it will be called immediately when the conftest is registered, once for each plugin registered thus far (including itself!), and for all plugins thereafter when they are registered.

收集钩子

Collection hooks

pytest 调用以下钩子来收集文件和目录:

pytest_collection(session)[source]

Perform the collection phase for the given session.

Stops at first non-None result, see firstresult: 在第一个非 None 结果处停止. The return value is not used, but only stops further processing.

The default collection phase is this (see individual hooks for full details):

  1. Starting from session as the initial collector:

  1. pytest_collectstart(collector)

  2. report = pytest_make_collect_report(collector)

  3. pytest_exception_interact(collector, call, report) if an interactive exception occurred

  4. For each collected node:

  1. If an item, pytest_itemcollected(item)

  2. If a collector, recurse into it.

  1. pytest_collectreport(report)

  1. pytest_collection_modifyitems(session, config, items)

  1. pytest_deselected(items) for any deselected items (may be called multiple times)

  1. pytest_collection_finish(session)

  2. Set session.items to the list of collected items

  3. Set session.testscollected to the number of collected items

You can implement this hook to only perform some action before collection, for example the terminal plugin uses it to start displaying the collection counter (and returns None).

Parameters:

session (Session) – The pytest session object.

Use in conftest plugins

This hook is only called for initial conftests.

pytest_ignore_collect(collection_path, path, config)[source]

Return True to ignore this path for collection.

Return None to let other plugins ignore the path for collection.

Returning False will forcefully not ignore this path for collection, without giving a chance for other plugins to ignore this path.

This hook is consulted for all files and directories prior to calling more specific hooks.

Stops at first non-None result, see firstresult: 在第一个非 None 结果处停止.

Parameters:
  • collection_path (pathlib.Path) – The path to analyze.

  • path (LEGACY_PATH) – The path to analyze (deprecated).

  • config (Config) – The pytest config object.

Changed in version 7.0.0: The collection_path parameter was added as a pathlib.Path equivalent of the path parameter. The path parameter has been deprecated.

Use in conftest plugins

Any conftest file can implement this hook. For a given collection path, only conftest files in parent directories of the collection path are consulted (if the path is a directory, its own conftest file is not consulted - a directory cannot ignore itself!).

pytest_collect_directory(path, parent)[source]

Create a Collector for the given directory, or None if not relevant.

Added in version 8.0.

For best results, the returned collector should be a subclass of Directory, but this is not required.

The new node needs to have the specified parent as a parent.

Stops at first non-None result, see firstresult: 在第一个非 None 结果处停止.

Parameters:

path (pathlib.Path) – The path to analyze.

See 使用自定义目录收集器 for a simple example of use of this hook.

Use in conftest plugins

Any conftest file can implement this hook. For a given collection path, only conftest files in parent directories of the collection path are consulted (if the path is a directory, its own conftest file is not consulted - a directory cannot collect itself!).

pytest_collect_file(file_path, path, parent)[source]

Create a Collector for the given path, or None if not relevant.

For best results, the returned collector should be a subclass of File, but this is not required.

The new node needs to have the specified parent as a parent.

Parameters:
  • file_path (pathlib.Path) – The path to analyze.

  • path (LEGACY_PATH) – The path to collect (deprecated).

Changed in version 7.0.0: The file_path parameter was added as a pathlib.Path equivalent of the path parameter. The path parameter has been deprecated.

Use in conftest plugins

Any conftest file can implement this hook. For a given file path, only conftest files in parent directories of the file path are consulted.

pytest_pycollect_makemodule(module_path, path, parent)[source]

Return a pytest.Module collector or None for the given path.

This hook will be called for each matching test module path. The pytest_collect_file hook needs to be used if you want to create test modules for files that do not match as a test module.

Stops at first non-None result, see firstresult: 在第一个非 None 结果处停止.

Parameters:
  • module_path (pathlib.Path) – The path of the module to collect.

  • path (LEGACY_PATH) – The path of the module to collect (deprecated).

Changed in version 7.0.0: The module_path parameter was added as a pathlib.Path equivalent of the path parameter.

The path parameter has been deprecated in favor of fspath.

Use in conftest plugins

Any conftest file can implement this hook. For a given parent collector, only conftest files in the collector’s directory and its parent directories are consulted.

要影响 Python 模块中对象的收集,可以使用以下钩子:

pytest_pycollect_makeitem(collector, name, obj)[source]

Return a custom item/collector for a Python object in a module, or None.

Stops at first non-None result, see firstresult: 在第一个非 None 结果处停止.

Parameters:
  • collector (Module | Class) – The module/class collector.

  • name (str) – The name of the object in the module/class.

  • obj (object) – The object.

Returns:

The created items/collectors.

Return type:

None | Item | Collector | list[Item | Collector]

Use in conftest plugins

Any conftest file can implement this hook. For a given collector, only conftest files in the collector’s directory and its parent directories are consulted.

pytest_generate_tests(metafunc)[source]

Generate (multiple) parametrized calls to a test function.

Parameters:

metafunc (Metafunc) – The Metafunc helper for the test function.

Use in conftest plugins

Any conftest file can implement this hook. For a given function definition, only conftest files in the functions’s directory and its parent directories are consulted.

pytest_make_parametrize_id(config, val, argname)[source]

Return a user-friendly string representation of the given val that will be used by @pytest.mark.parametrize calls, or None if the hook doesn’t know about val.

The parameter name is available as argname, if required.

Stops at first non-None result, see firstresult: 在第一个非 None 结果处停止.

Parameters:
  • config (Config) – The pytest config object.

  • val (object) – The parametrized value.

  • argname (str) – The automatic parameter name produced by pytest.

Use in conftest plugins

Any conftest file can implement this hook.

影响测试跳过的钩子:

pytest_markeval_namespace(config)[source]

Called when constructing the globals dictionary used for evaluating string conditions in xfail/skipif markers.

This is useful when the condition for a marker requires objects that are expensive or impossible to obtain during collection time, which is required by normal boolean conditions.

Added in version 6.2.

Parameters:

config (Config) – The pytest config object.

Returns:

A dictionary of additional globals to add.

Return type:

dict[str, Any]

Use in conftest plugins

Any conftest file can implement this hook. For a given item, only conftest files in parent directories of the item are consulted.

收集完成后,您可以修改项目的顺序,删除或以其他方式修改测试项目:

pytest_collection_modifyitems(session, config, items)[source]

Called after collection has been performed. May filter or re-order the items in-place.

When items are deselected (filtered out from items), the hook pytest_deselected must be called explicitly with the deselected items to properly notify other plugins, e.g. with config.hook.pytest_deselected(deselected_items).

Parameters:
  • session (Session) – The pytest session object.

  • config (Config) – The pytest config object.

  • items (list[Item]) – List of item objects.

Use in conftest plugins

Any conftest plugin can implement this hook.

Note

如果此钩子在 conftest.py 文件中实现,它始终接收所有收集的项目,而不仅仅是 在实现它的 conftest.py 下的项目。

pytest_collection_finish(session)[source]

Called after collection has been performed and modified.

Parameters:

session (Session) – The pytest session object.

Use in conftest plugins

Any conftest plugin can implement this hook.

测试运行钩子

Test running (runtest) hooks

所有与运行测试相关的钩子接收一个 pytest.Item 对象。

pytest_runtestloop(session)[source]

Perform the main runtest loop (after collection finished).

The default hook implementation performs the runtest protocol for all items collected in the session (session.items), unless the collection failed or the collectonly pytest option is set.

If at any point pytest.exit() is called, the loop is terminated immediately.

If at any point session.shouldfail or session.shouldstop are set, the loop is terminated after the runtest protocol for the current item is finished.

Parameters:

session (Session) – The pytest session object.

Stops at first non-None result, see firstresult: 在第一个非 None 结果处停止. The return value is not used, but only stops further processing.

Use in conftest plugins

Any conftest file can implement this hook.

pytest_runtest_protocol(item, nextitem)[source]

Perform the runtest protocol for a single test item.

The default runtest protocol is this (see individual hooks for full details):

  • pytest_runtest_logstart(nodeid, location)

  • Setup phase:
    • call = pytest_runtest_setup(item) (wrapped in CallInfo(when="setup"))

    • report = pytest_runtest_makereport(item, call)

    • pytest_runtest_logreport(report)

    • pytest_exception_interact(call, report) if an interactive exception occurred

  • Call phase, if the setup passed and the setuponly pytest option is not set:
    • call = pytest_runtest_call(item) (wrapped in CallInfo(when="call"))

    • report = pytest_runtest_makereport(item, call)

    • pytest_runtest_logreport(report)

    • pytest_exception_interact(call, report) if an interactive exception occurred

  • Teardown phase:
    • call = pytest_runtest_teardown(item, nextitem) (wrapped in CallInfo(when="teardown"))

    • report = pytest_runtest_makereport(item, call)

    • pytest_runtest_logreport(report)

    • pytest_exception_interact(call, report) if an interactive exception occurred

  • pytest_runtest_logfinish(nodeid, location)

Parameters:
  • item (Item) – Test item for which the runtest protocol is performed.

  • nextitem (Item | None) – The scheduled-to-be-next test item (or None if this is the end my friend).

Stops at first non-None result, see firstresult: 在第一个非 None 结果处停止. The return value is not used, but only stops further processing.

Use in conftest plugins

Any conftest file can implement this hook.

pytest_runtest_logstart(nodeid, location)[source]

Called at the start of running the runtest protocol for a single item.

See pytest_runtest_protocol for a description of the runtest protocol.

Parameters:
  • nodeid (str) – Full node ID of the item.

  • location (tuple[str, int | None, str]) – A tuple of (filename, lineno, testname) where filename is a file path relative to config.rootpath and lineno is 0-based.

Use in conftest plugins

Any conftest file can implement this hook. For a given item, only conftest files in the item’s directory and its parent directories are consulted.

pytest_runtest_logfinish(nodeid, location)[source]

Called at the end of running the runtest protocol for a single item.

See pytest_runtest_protocol for a description of the runtest protocol.

Parameters:
  • nodeid (str) – Full node ID of the item.

  • location (tuple[str, int | None, str]) – A tuple of (filename, lineno, testname) where filename is a file path relative to config.rootpath and lineno is 0-based.

Use in conftest plugins

Any conftest file can implement this hook. For a given item, only conftest files in the item’s directory and its parent directories are consulted.

pytest_runtest_setup(item)[source]

Called to perform the setup phase for a test item.

The default implementation runs setup() on item and all of its parents (which haven’t been setup yet). This includes obtaining the values of fixtures required by the item (which haven’t been obtained yet).

Parameters:

item (Item) – The item.

Use in conftest plugins

Any conftest file can implement this hook. For a given item, only conftest files in the item’s directory and its parent directories are consulted.

pytest_runtest_call(item)[source]

Called to run the test for test item (the call phase).

The default implementation calls item.runtest().

Parameters:

item (Item) – The item.

Use in conftest plugins

Any conftest file can implement this hook. For a given item, only conftest files in the item’s directory and its parent directories are consulted.

pytest_runtest_teardown(item, nextitem)[source]

Called to perform the teardown phase for a test item.

The default implementation runs the finalizers and calls teardown() on item and all of its parents (which need to be torn down). This includes running the teardown phase of fixtures required by the item (if they go out of scope).

Parameters:
  • item (Item) – The item.

  • nextitem (Item | None) – The scheduled-to-be-next test item (None if no further test item is scheduled). This argument is used to perform exact teardowns, i.e. calling just enough finalizers so that nextitem only needs to call setup functions.

Use in conftest plugins

Any conftest file can implement this hook. For a given item, only conftest files in the item’s directory and its parent directories are consulted.

pytest_runtest_makereport(item, call)[source]

Called to create a TestReport for each of the setup, call and teardown runtest phases of a test item.

See pytest_runtest_protocol for a description of the runtest protocol.

Parameters:

Stops at first non-None result, see firstresult: 在第一个非 None 结果处停止.

Use in conftest plugins

Any conftest file can implement this hook. For a given item, only conftest files in the item’s directory and its parent directories are consulted.

要深入理解,您可以查看 _pytest.runner 中这些钩子的默认实现,也可以查看 _pytest.pdb,它与 _pytest.capture 和其输入/输出捕获交互,以便在测试失败时立即进入交互式调试。

pytest_pyfunc_call(pyfuncitem)[source]

Call underlying test function.

Stops at first non-None result, see firstresult: 在第一个非 None 结果处停止.

Parameters:

pyfuncitem (Function) – The function item.

Use in conftest plugins

Any conftest file can implement this hook. For a given item, only conftest files in the item’s directory and its parent directories are consulted.

报告钩子

Reporting hooks

与会话相关的报告钩子:

pytest_collectstart(collector)[source]

Collector starts collecting.

Parameters:

collector (Collector) – The collector.

Use in conftest plugins

Any conftest file can implement this hook. For a given collector, only conftest files in the collector’s directory and its parent directories are consulted.

pytest_make_collect_report(collector)[source]

Perform collector.collect() and return a CollectReport.

Stops at first non-None result, see firstresult: 在第一个非 None 结果处停止.

Parameters:

collector (Collector) – The collector.

Use in conftest plugins

Any conftest file can implement this hook. For a given collector, only conftest files in the collector’s directory and its parent directories are consulted.

pytest_itemcollected(item)[source]

We just collected a test item.

Parameters:

item (Item) – The item.

Use in conftest plugins

Any conftest file can implement this hook. For a given item, only conftest files in the item’s directory and its parent directories are consulted.

pytest_collectreport(report)[source]

Collector finished collecting.

Parameters:

report (CollectReport) – The collect report.

Use in conftest plugins

Any conftest file can implement this hook. For a given collector, only conftest files in the collector’s directory and its parent directories are consulted.

pytest_deselected(items)[source]

Called for deselected test items, e.g. by keyword.

Note that this hook has two integration aspects for plugins:

  • it can be implemented to be notified of deselected items

  • it must be called from pytest_collection_modifyitems implementations when items are deselected (to properly notify other plugins).

May be called multiple times.

Parameters:

items (Sequence[Item]) – The items.

Use in conftest plugins

Any conftest file can implement this hook.

pytest_report_header(config, start_path, startdir)[source]

Return a string or list of strings to be displayed as header info for terminal reporting.

Parameters:
  • config (Config) – The pytest config object.

  • start_path (pathlib.Path) – The starting dir.

  • startdir (LEGACY_PATH) – The starting dir (deprecated).

Note

Lines returned by a plugin are displayed before those of plugins which ran before it. If you want to have your line(s) displayed first, use trylast=True.

Changed in version 7.0.0: The start_path parameter was added as a pathlib.Path equivalent of the startdir parameter. The startdir parameter has been deprecated.

Use in conftest plugins

This hook is only called for initial conftests.

pytest_report_collectionfinish(config, start_path, startdir, items)[source]

Return a string or list of strings to be displayed after collection has finished successfully.

These strings will be displayed after the standard “collected X items” message.

Added in version 3.2.

Parameters:
  • config (Config) – The pytest config object.

  • start_path (pathlib.Path) – The starting dir.

  • startdir (LEGACY_PATH) – The starting dir (deprecated).

  • items (Sequence[Item]) – List of pytest items that are going to be executed; this list should not be modified.

Note

Lines returned by a plugin are displayed before those of plugins which ran before it. If you want to have your line(s) displayed first, use trylast=True.

Changed in version 7.0.0: The start_path parameter was added as a pathlib.Path equivalent of the startdir parameter. The startdir parameter has been deprecated.

Use in conftest plugins

Any conftest plugin can implement this hook.

pytest_report_teststatus(report, config)[source]

Return result-category, shortletter and verbose word for status reporting.

The result-category is a category in which to count the result, for example “passed”, “skipped”, “error” or the empty string.

The shortletter is shown as testing progresses, for example “.”, “s”, “E” or the empty string.

The verbose word is shown as testing progresses in verbose mode, for example “PASSED”, “SKIPPED”, “ERROR” or the empty string.

pytest may style these implicitly according to the report outcome. To provide explicit styling, return a tuple for the verbose word, for example "rerun", "R", ("RERUN", {"yellow": True}).

Parameters:
Returns:

The test status.

Return type:

TestShortLogReport | tuple[str, str, str | tuple[str, Mapping[str, bool]]]

Stops at first non-None result, see firstresult: 在第一个非 None 结果处停止.

Use in conftest plugins

Any conftest plugin can implement this hook.

pytest_report_to_serializable(config, report)[source]

Serialize the given report object into a data structure suitable for sending over the wire, e.g. converted to JSON.

Parameters:

Use in conftest plugins

Any conftest file can implement this hook. The exact details may depend on the plugin which calls the hook.

pytest_report_from_serializable(config, data)[source]

Restore a report object previously serialized with pytest_report_to_serializable.

Parameters:

config (Config) – The pytest config object.

Use in conftest plugins

Any conftest file can implement this hook. The exact details may depend on the plugin which calls the hook.

pytest_terminal_summary(terminalreporter, exitstatus, config)[source]

Add a section to terminal summary reporting.

Parameters:
  • terminalreporter (TerminalReporter) – The internal terminal reporter object.

  • exitstatus (ExitCode) – The exit status that will be reported back to the OS.

  • config (Config) – The pytest config object.

Added in version 4.2: The config parameter.

Use in conftest plugins

Any conftest plugin can implement this hook.

pytest_fixture_setup(fixturedef, request)[source]

Perform fixture setup execution.

Parameters:
  • fixturedef (FixtureDef[Any]) – The fixture definition object.

  • request (SubRequest) – The fixture request object.

Returns:

The return value of the call to the fixture function.

Return type:

object | None

Stops at first non-None result, see firstresult: 在第一个非 None 结果处停止.

Note

If the fixture function returns None, other implementations of this hook function will continue to be called, according to the behavior of the firstresult: 在第一个非 None 结果处停止 option.

Use in conftest plugins

Any conftest file can implement this hook. For a given fixture, only conftest files in the fixture scope’s directory and its parent directories are consulted.

pytest_fixture_post_finalizer(fixturedef, request)[source]

Called after fixture teardown, but before the cache is cleared, so the fixture result fixturedef.cached_result is still available (not None).

Parameters:
  • fixturedef (FixtureDef[Any]) – The fixture definition object.

  • request (SubRequest) – The fixture request object.

Use in conftest plugins

Any conftest file can implement this hook. For a given fixture, only conftest files in the fixture scope’s directory and its parent directories are consulted.

pytest_warning_recorded(warning_message, when, nodeid, location)[source]

Process a warning captured by the internal pytest warnings plugin.

Parameters:
  • warning_message (warnings.WarningMessage) – The captured warning. This is the same object produced by warnings.catch_warnings, and contains the same attributes as the parameters of warnings.showwarning().

  • when (Literal['config', 'collect', 'runtest']) –

    Indicates when the warning was captured. Possible values:

    • "config": during pytest configuration/initialization stage.

    • "collect": during test collection.

    • "runtest": during test execution.

  • nodeid (str) – Full id of the item. Empty string for warnings that are not specific to a particular node.

  • location (tuple[str, int, str] | None) – When available, holds information about the execution context of the captured warning (filename, linenumber, function). function evaluates to <module> when the execution context is at the module level.

Added in version 6.0.

Use in conftest plugins

Any conftest file can implement this hook. If the warning is specific to a particular node, only conftest files in parent directories of the node are consulted.

用于报告测试执行的中心钩子:

pytest_runtest_logreport(report)[source]

Process the TestReport produced for each of the setup, call and teardown runtest phases of an item.

See pytest_runtest_protocol for a description of the runtest protocol.

Use in conftest plugins

Any conftest file can implement this hook. For a given item, only conftest files in the item’s directory and its parent directories are consulted.

与断言相关的钩子:

pytest_assertrepr_compare(config, op, left, right)[source]

Return explanation for comparisons in failing assert expressions.

Return None for no custom explanation, otherwise return a list of strings. The strings will be joined by newlines but any newlines in a string will be escaped. Note that all but the first line will be indented slightly, the intention is for the first line to be a summary.

Parameters:
  • config (Config) – The pytest config object.

  • op (str) – The operator, e.g. "==", "!=", "not in".

  • left (object) – The left operand.

  • right (object) – The right operand.

Use in conftest plugins

Any conftest file can implement this hook. For a given item, only conftest files in the item’s directory and its parent directories are consulted.

pytest_assertion_pass(item, lineno, orig, expl)[source]

Called whenever an assertion passes.

Added in version 5.0.

Use this hook to do some processing after a passing assertion. The original assertion information is available in the orig string and the pytest introspected assertion information is available in the expl string.

This hook must be explicitly enabled by the enable_assertion_pass_hook ini-file option:

[pytest]
enable_assertion_pass_hook=true

You need to clean the .pyc files in your project directory and interpreter libraries when enabling this option, as assertions will require to be re-written.

Parameters:
  • item (Item) – pytest item object of current test.

  • lineno (int) – Line number of the assert statement.

  • orig (str) – String with the original assertion.

  • expl (str) – String with the assert explanation.

Use in conftest plugins

Any conftest file can implement this hook. For a given item, only conftest files in the item’s directory and its parent directories are consulted.

调试/交互钩子

Debugging/Interaction hooks

有一些钩子可以用于特殊报告或异常交互:

pytest_internalerror(excrepr, excinfo)[source]

Called for internal errors.

Return True to suppress the fallback handling of printing an INTERNALERROR message directly to sys.stderr.

Parameters:

Use in conftest plugins

Any conftest plugin can implement this hook.

pytest_keyboard_interrupt(excinfo)[source]

Called for keyboard interrupt.

Parameters:

excinfo (ExceptionInfo[KeyboardInterrupt | Exit]) – The exception info.

Use in conftest plugins

Any conftest plugin can implement this hook.

pytest_exception_interact(node, call, report)[source]

Called when an exception was raised which can potentially be interactively handled.

May be called during collection (see pytest_make_collect_report), in which case report is a CollectReport.

May be called during runtest of an item (see pytest_runtest_protocol), in which case report is a TestReport.

This hook is not called if the exception that was raised is an internal exception like skip.Exception.

Parameters:

Use in conftest plugins

Any conftest file can implement this hook. For a given node, only conftest files in parent directories of the node are consulted.

pytest_enter_pdb(config, pdb)[source]

Called upon pdb.set_trace().

Can be used by plugins to take special action just before the python debugger enters interactive mode.

Parameters:
  • config (Config) – The pytest config object.

  • pdb (pdb.Pdb) – The Pdb instance.

Use in conftest plugins

Any conftest plugin can implement this hook.

pytest_leave_pdb(config, pdb)[source]

Called when leaving pdb (e.g. with continue after pdb.set_trace()).

Can be used by plugins to take special action just after the python debugger leaves interactive mode.

Parameters:
  • config (Config) – The pytest config object.

  • pdb (pdb.Pdb) – The Pdb instance.

Use in conftest plugins

Any conftest plugin can implement this hook.

收集树对象

Collection tree objects

这些是构成收集树的收集器和项目类(统称为“节点”)。

Node

class Node[source]

Bases: ABC

Base class of Collector and Item, the components of the test collection tree.

Collector's are the internal nodes of the tree, and Item's are the leaf nodes.

fspath: LEGACY_PATH

A LEGACY_PATH copy of the path attribute. Intended for usage for methods not migrated to pathlib.Path yet, such as Item.reportinfo. Will be deprecated in a future release, prefer using path instead.

name: str

A unique name within the scope of the parent node.

parent

The parent collector node.

config: Config

The pytest config object.

session: Session

The pytest session this node is part of.

path: pathlib.Path

Filesystem path where this node was collected from (can be None).

keywords: MutableMapping[str, Any]

Keywords/markers collected from all scopes.

own_markers: list[Mark]

The marker objects belonging to this node.

extra_keyword_matches: set[str]

Allow adding of extra keywords to use for matching.

stash: Stash

A place where plugins can store information on the node for their own use.

classmethod from_parent(parent, **kw)[source]

Public constructor for Nodes.

This indirection got introduced in order to enable removing the fragile logic from the node constructors.

Subclasses can use super().from_parent(...) when overriding the construction.

Parameters:

parent (Node) – The parent node of this Node.

property ihook: HookRelay

fspath-sensitive hook proxy used to call pytest hooks.

warn(warning)[source]

Issue a warning for this Node.

Warnings will be displayed after the test session, unless explicitly suppressed.

Parameters:

warning (Warning) – The warning instance to issue.

Raises:

ValueError – If warning instance is not a subclass of Warning.

Example usage:

node.warn(PytestWarning("some message"))
node.warn(UserWarning("some message"))

Changed in version 6.2: Any subclass of Warning is now accepted, rather than only PytestWarning subclasses.

property nodeid: str

A ::-separated string denoting its collection tree address.

for ... in iter_parents()[source]

Iterate over all parent collectors starting from and including self up to the root of the collection tree.

Added in version 8.1.

listchain()[source]

Return a list of all parent collectors starting from the root of the collection tree down to and including self.

add_marker(marker, append=True)[source]

Dynamically add a marker object to the node.

Parameters:
  • marker (str | MarkDecorator) – The marker.

  • append (bool) – Whether to append the marker, or prepend it.

iter_markers(name=None)[source]

Iterate over all markers of the node.

Parameters:

name (str | None) – If given, filter the results by the name attribute.

Returns:

An iterator of the markers of the node.

Return type:

Iterator[Mark]

for ... in iter_markers_with_node(name=None)[source]

Iterate over all markers of the node.

Parameters:

name (str | None) – If given, filter the results by the name attribute.

Returns:

An iterator of (node, mark) tuples.

Return type:

Iterator[tuple[Node, Mark]]

get_closest_marker(name: str) Mark | None[source]
get_closest_marker(name: str, default: Mark) Mark

Return the first marker matching the name, from closest (for example function) to farther level (for example module level).

Parameters:
  • default – Fallback return value if no marker was found.

  • name – Name to filter by.

listextrakeywords()[source]

Return a set of all extra keywords in self and any parents.

addfinalizer(fin)[source]

Register a function to be called without arguments when this node is finalized.

This method can only be called when this node is active in a setup chain, for example during self.setup().

getparent(cls)[source]

Get the closest parent node (including self) which is an instance of the given class.

Parameters:

cls (type[_NodeType]) – The node class to search for.

Returns:

The node, if found.

Return type:

_NodeType | None

repr_failure(excinfo, style=None)[source]

Return a representation of a collection or test failure.

Parameters:

excinfo (ExceptionInfo[BaseException]) – Exception information for the failure.

Collector

class Collector[source]

Bases: Node, ABC

Base class of all collectors.

Collector create children through collect() and thus iteratively build the collection tree.

exception CollectError[source]

Bases: Exception

An error during collection, contains a custom message.

abstractmethod collect()[source]

Collect children (items and collectors) for this collector.

repr_failure(excinfo)[source]

Return a representation of a collection failure.

Parameters:

excinfo (ExceptionInfo[BaseException]) – Exception information for the failure.

name: str

A unique name within the scope of the parent node.

parent

The parent collector node.

config: Config

The pytest config object.

session: Session

The pytest session this node is part of.

path: pathlib.Path

Filesystem path where this node was collected from (can be None).

Item

class Item[source]

Bases: Node, ABC

Base class of all test invocation items.

Note that for a single function there might be multiple test invocation items.

user_properties: list[tuple[str, object]]

A list of tuples (name, value) that holds user defined properties for this test.

name: str

A unique name within the scope of the parent node.

parent

The parent collector node.

config: Config

The pytest config object.

session: Session

The pytest session this node is part of.

path: pathlib.Path

Filesystem path where this node was collected from (can be None).

abstractmethod runtest()[source]

Run the test case for this item.

Must be implemented by subclasses.

add_report_section(when, key, content)[source]

Add a new report section, similar to what’s done internally to add stdout and stderr captured output:

item.add_report_section("call", "stdout", "report section contents")
Parameters:
  • when (str) – One of the possible capture states, "setup", "call", "teardown".

  • key (str) – Name of the section, can be customized at will. Pytest uses "stdout" and "stderr" internally.

  • content (str) – The full contents as a string.

reportinfo()[source]

Get location information for this item for test reports.

Returns a tuple with three elements:

  • The path of the test (default self.path)

  • The 0-based line number of the test (default None)

  • A name of the test to be shown (default "")

property location: tuple[str, int | None, str]

Returns a tuple of (relfspath, lineno, testname) for this item where relfspath is file path relative to config.rootpath and lineno is a 0-based line number.

File

class File[source]

Bases: FSCollector, ABC

Base class for collecting tests from a file.

使用非 Python 测试.

name: str

A unique name within the scope of the parent node.

parent

The parent collector node.

config: Config

The pytest config object.

session: Session

The pytest session this node is part of.

path: pathlib.Path

Filesystem path where this node was collected from (can be None).

FSCollector

class FSCollector[source]

Bases: Collector, ABC

Base class for filesystem collectors.

path: pathlib.Path

Filesystem path where this node was collected from (can be None).

classmethod from_parent(parent, *, fspath=None, path=None, **kw)[source]

The public constructor.

name: str

A unique name within the scope of the parent node.

parent

The parent collector node.

config: Config

The pytest config object.

session: Session

The pytest session this node is part of.

Session

final class Session[source]

Bases: Collector

The root of the collection tree.

Session collects the initial paths given as arguments to pytest.

exception Interrupted

Bases: KeyboardInterrupt

Signals that the test run was interrupted.

exception Failed

Bases: Exception

Signals a stop as failed test run.

property startpath: Path

The path from which pytest was invoked.

Added in version 7.0.0.

isinitpath(path, *, with_parents=False)[source]

Is path an initial path?

An initial path is a path explicitly given to pytest on the command line.

Parameters:

with_parents (bool) – If set, also return True if the path is a parent of an initial path.

Changed in version 8.0: Added the with_parents parameter.

perform_collect(args: Sequence[str] | None = None, genitems: Literal[True] = True) Sequence[Item][source]
perform_collect(args: Sequence[str] | None = None, genitems: bool = True) Sequence[Item | Collector]

Perform the collection phase for this session.

This is called by the default pytest_collection hook implementation; see the documentation of this hook for more details. For testing purposes, it may also be called directly on a fresh Session.

This function normally recursively expands any collectors collected from the session to their items, and only items are returned. For testing purposes, this may be suppressed by passing genitems=False, in which case the return value contains these collectors unexpanded, and session.items is empty.

for ... in collect()[source]

Collect children (items and collectors) for this collector.

name: str

A unique name within the scope of the parent node.

parent

The parent collector node.

config: Config

The pytest config object.

session: Session

The pytest session this node is part of.

path: pathlib.Path

Filesystem path where this node was collected from (can be None).

Package

class Package[source]

Bases: Directory

Collector for files and directories in a Python packages – directories with an __init__.py file.

Note

Directories without an __init__.py file are instead collected by Dir by default. Both are Directory collectors.

Changed in version 8.0: Now inherits from Directory.

for ... in collect()[source]

Collect children (items and collectors) for this collector.

name: str

A unique name within the scope of the parent node.

parent

The parent collector node.

config: Config

The pytest config object.

session: Session

The pytest session this node is part of.

path: pathlib.Path

Filesystem path where this node was collected from (can be None).

Module

class Module[source]

Bases: File, PyCollector

Collector for test classes and functions in a Python module.

collect()[source]

Collect children (items and collectors) for this collector.

name: str

A unique name within the scope of the parent node.

parent

The parent collector node.

config: Config

The pytest config object.

session: Session

The pytest session this node is part of.

path: pathlib.Path

Filesystem path where this node was collected from (can be None).

Class

class Class[source]

Bases: PyCollector

Collector for test methods (and nested classes) in a Python class.

classmethod from_parent(parent, *, name, obj=None, **kw)[source]

The public constructor.

collect()[source]

Collect children (items and collectors) for this collector.

name: str

A unique name within the scope of the parent node.

parent

The parent collector node.

config: Config

The pytest config object.

session: Session

The pytest session this node is part of.

path: pathlib.Path

Filesystem path where this node was collected from (can be None).

Function

class Function[source]

Bases: PyobjMixin, Item

Item responsible for setting up and executing a Python test function.

Parameters:
  • name – The full function name, including any decorations like those added by parametrization (my_func[my_param]).

  • parent – The parent Node.

  • config – The pytest Config object.

  • callspec – If given, this function has been parametrized and the callspec contains meta information about the parametrization.

  • callobj – If given, the object which will be called when the Function is invoked, otherwise the callobj will be obtained from parent using originalname.

  • keywords – Keywords bound to the function object for “-k” matching.

  • session – The pytest Session object.

  • fixtureinfo – Fixture information already resolved at this fixture node..

  • originalname – The attribute name to use for accessing the underlying function object. Defaults to name. Set this if name is different from the original name, for example when it contains decorations like those added by parametrization (my_func[my_param]).

originalname

Original function name, without any decorations (for example parametrization adds a "[...]" suffix to function names), used to access the underlying function object from parent (in case callobj is not given explicitly).

Added in version 3.0.

classmethod from_parent(parent, **kw)[source]

The public constructor.

property function

Underlying python ‘function’ object.

property instance

Python instance object the function is bound to.

Returns None if not a test method, e.g. for a standalone test function, a class or a module.

runtest()[source]

Execute the underlying test function.

repr_failure(excinfo)[source]

Return a representation of a collection or test failure.

Parameters:

excinfo (ExceptionInfo[BaseException]) – Exception information for the failure.

name: str

A unique name within the scope of the parent node.

parent

The parent collector node.

config: Config

The pytest config object.

session: Session

The pytest session this node is part of.

path: pathlib.Path

Filesystem path where this node was collected from (can be None).

FunctionDefinition

class FunctionDefinition[source]

Bases: Function

This class is a stop gap solution until we evolve to have actual function definition nodes and manage to get rid of metafunc.

runtest()[source]

Execute the underlying test function.

name: str

A unique name within the scope of the parent node.

parent

The parent collector node.

config: Config

The pytest config object.

session: Session

The pytest session this node is part of.

path: pathlib.Path

Filesystem path where this node was collected from (can be None).

setup()

Execute the underlying test function.

对象

Objects

可从 fixtureshooks 访问或从 pytest 导入的对象。

CallInfo

final class CallInfo[source]

Result/Exception info of a function invocation.

excinfo: ExceptionInfo[BaseException] | None

The captured exception of the call, if it raised.

start: float

The system time when the call started, in seconds since the epoch.

stop: float

The system time when the call ended, in seconds since the epoch.

duration: float

The call duration, in seconds.

when: Literal['collect', 'setup', 'call', 'teardown']

The context of invocation: “collect”, “setup”, “call” or “teardown”.

property result: TResult

The return value of the call, if it didn’t raise.

Can only be accessed if excinfo is None.

classmethod from_call(func, when, reraise=None)[source]

Call func, wrapping the result in a CallInfo.

Parameters:
  • func (Callable[[], _pytest.runner.TResult]) – The function to call. Called without arguments.

  • when (Literal['collect', 'setup', 'call', 'teardown']) – The phase in which the function is called.

  • reraise (type[BaseException] | tuple[type[BaseException], ...] | None) – Exception or exceptions that shall propagate if raised by the function, instead of being wrapped in the CallInfo.

CollectReport

final class CollectReport[source]

Bases: BaseReport

Collection report object.

Reports can contain arbitrary extra attributes.

nodeid: str

Normalized collection nodeid.

outcome: Literal['passed', 'failed', 'skipped']

Test outcome, always one of “passed”, “failed”, “skipped”.

longrepr: None | ExceptionInfo[BaseException] | tuple[str, int, str] | str | TerminalRepr

None or a failure representation.

result

The collected items and collection nodes.

sections: list[tuple[str, str]]

Tuples of str (heading, content) with extra information for the test report. Used by pytest to add text captured from stdout, stderr, and intercepted logging events. May be used by other plugins to add arbitrary information to reports.

property caplog: str

Return captured log lines, if log capturing is enabled.

Added in version 3.5.

property capstderr: str

Return captured text from stderr, if capturing is enabled.

Added in version 3.0.

property capstdout: str

Return captured text from stdout, if capturing is enabled.

Added in version 3.0.

property count_towards_summary: bool

Experimental Whether this report should be counted towards the totals shown at the end of the test session: “1 passed, 1 failure, etc”.

Note

This function is considered experimental, so beware that it is subject to changes even in patch releases.

property failed: bool

Whether the outcome is failed.

property fspath: str

The path portion of the reported node, as a string.

property head_line: str | None

Experimental The head line shown with longrepr output for this report, more commonly during traceback representation during failures:

________ Test.foo ________

In the example above, the head_line is “Test.foo”.

Note

This function is considered experimental, so beware that it is subject to changes even in patch releases.

property longreprtext: str

Read-only property that returns the full string representation of longrepr.

Added in version 3.0.

property passed: bool

Whether the outcome is passed.

property skipped: bool

Whether the outcome is skipped.

Config

final class Config[source]

Access to configuration values, pluginmanager and plugin hooks.

Parameters:
final class InvocationParams(*, args, plugins, dir)[source]

Holds parameters passed during pytest.main().

The object attributes are read-only.

Added in version 5.1.

Note

Note that the environment variable PYTEST_ADDOPTS and the addopts ini option are handled by pytest, not being included in the args attribute.

Plugins accessing InvocationParams must be aware of that.

args: tuple[str, ...]

The command-line arguments as passed to pytest.main().

plugins: Sequence[str | object] | None

Extra plugins, might be None.

dir: Path

The directory from which pytest.main() was invoked. :type: pathlib.Path

class ArgsSource(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Indicates the source of the test arguments.

Added in version 7.2.

ARGS = 1

Command line arguments.

INVOCATION_DIR = 2

Invocation directory.

TESTPATHS = 3

‘testpaths’ configuration value.

option

Access to command line option as attributes.

Type:

argparse.Namespace

invocation_params

The parameters with which pytest was invoked.

Type:

InvocationParams

pluginmanager

The plugin manager handles plugin registration and hook invocation.

Type:

PytestPluginManager

stash

A place where plugins can store information on the config for their own use.

Type:

Stash

property rootpath: Path

The path to the rootdir.

Type:

pathlib.Path

Added in version 6.1.

property inipath: Path | None

The path to the configfile.

Added in version 6.1.

add_cleanup(func)[source]

Add a function to be called when the config object gets out of use (usually coinciding with pytest_unconfigure).

classmethod fromdictargs(option_dict, args)[source]

Constructor usable for subprocesses.

issue_config_time_warning(warning, stacklevel)[source]

Issue and handle a warning during the “configure” stage.

During pytest_configure we can’t capture warnings using the catch_warnings_for_item function because it is not possible to have hook wrappers around pytest_configure.

This function is mainly intended for plugins that need to issue warnings during pytest_configure (or similar stages).

Parameters:
  • warning (Warning) – The warning instance.

  • stacklevel (int) – stacklevel forwarded to warnings.warn.

addinivalue_line(name, line)[source]

Add a line to an ini-file option. The option must have been declared but might not yet be set in which case the line becomes the first line in its value.

getini(name)[source]

Return configuration value from an ini file.

If a configuration value is not defined in an ini file, then the default value provided while registering the configuration through parser.addini will be returned. Please note that you can even provide None as a valid default value.

If default is not provided while registering using parser.addini, then a default value based on the type parameter passed to parser.addini will be returned. The default values based on type are: paths, pathlist, args and linelist : empty list [] bool : False string : empty string ""

If neither the default nor the type parameter is passed while registering the configuration through parser.addini, then the configuration is treated as a string and a default empty string ‘’ is returned.

If the specified name hasn’t been registered through a prior parser.addini call (usually from a plugin), a ValueError is raised.

getoption(name, default=<NOTSET>, skip=False)[source]

Return command line option value.

Parameters:
  • name (str) – Name of the option. You may also specify the literal --OPT option instead of the “dest” option name.

  • default – Fallback value if no option of that name is declared via pytest_addoption. Note this parameter will be ignored when the option is declared even if the option’s value is None.

  • skip (bool) – If True, raise pytest.skip() if option is undeclared or has a None value. Note that even if True, if a default was specified it will be returned instead of a skip.

getvalue(name, path=None)[source]

Deprecated, use getoption() instead.

getvalueorskip(name, path=None)[source]

Deprecated, use getoption(skip=True) instead.

VERBOSITY_ASSERTIONS: Final = 'assertions'

Verbosity type for failed assertions (see verbosity_assertions).

VERBOSITY_TEST_CASES: Final = 'test_cases'

Verbosity type for test case execution (see verbosity_test_cases).

get_verbosity(verbosity_type=None)[source]

Retrieve the verbosity level for a fine-grained verbosity type.

Parameters:

verbosity_type (str | None) – Verbosity type to get level for. If a level is configured for the given type, that value will be returned. If the given type is not a known verbosity type, the global verbosity level will be returned. If the given type is None (default), the global verbosity level will be returned.

To configure a level for a fine-grained verbosity type, the configuration file should have a setting for the configuration name and a numeric value for the verbosity level. A special value of “auto” can be used to explicitly use the global verbosity level.

Example:

# content of pytest.ini
[pytest]
verbosity_assertions = 2
pytest -v
print(config.get_verbosity())  # 1
print(config.get_verbosity(Config.VERBOSITY_ASSERTIONS))  # 2

Dir

final class Dir[source]

Collector of files in a file system directory.

Added in version 8.0.

Note

Python directories with an __init__.py file are instead collected by Package by default. Both are Directory collectors.

classmethod from_parent(parent, *, path)[source]

The public constructor.

Parameters:
for ... in collect()[source]

Collect children (items and collectors) for this collector.

name: str

A unique name within the scope of the parent node.

parent

The parent collector node.

config: Config

The pytest config object.

session: Session

The pytest session this node is part of.

path: pathlib.Path

Filesystem path where this node was collected from (can be None).

Directory

class Directory[source]

Base class for collecting files from a directory.

A basic directory collector does the following: goes over the files and sub-directories in the directory and creates collectors for them by calling the hooks pytest_collect_directory and pytest_collect_file, after checking that they are not ignored using pytest_ignore_collect.

The default directory collectors are Dir and Package.

Added in version 8.0.

使用自定义目录收集器.

name: str

A unique name within the scope of the parent node.

parent

The parent collector node.

config: Config

The pytest config object.

session: Session

The pytest session this node is part of.

path: pathlib.Path

Filesystem path where this node was collected from (can be None).

ExceptionInfo

final class ExceptionInfo[source]

Wraps sys.exc_info() objects and offers help for navigating the traceback.

classmethod from_exception(exception, exprinfo=None)[source]

Return an ExceptionInfo for an existing exception.

The exception must have a non-None __traceback__ attribute, otherwise this function fails with an assertion error. This means that the exception must have been raised, or added a traceback with the with_traceback() method.

Parameters:

exprinfo (str | None) – A text string helping to determine if we should strip AssertionError from the output. Defaults to the exception message/__str__().

Added in version 7.4.

classmethod from_exc_info(exc_info, exprinfo=None)[source]

Like from_exception(), but using old-style exc_info tuple.

classmethod from_current(exprinfo=None)[source]

Return an ExceptionInfo matching the current traceback.

Warning

Experimental API

Parameters:

exprinfo (str | None) – A text string helping to determine if we should strip AssertionError from the output. Defaults to the exception message/__str__().

classmethod for_later()[source]

Return an unfilled ExceptionInfo.

fill_unfilled(exc_info)[source]

Fill an unfilled ExceptionInfo created with for_later().

property type: type[E]

The exception class.

property value: E

The exception value.

property tb: TracebackType

The exception raw traceback.

property typename: str

The type name of the exception.

property traceback: Traceback

The traceback.

exconly(tryshort=False)[source]

Return the exception as a string.

When ‘tryshort’ resolves to True, and the exception is an AssertionError, only the actual exception part of the exception representation is returned (so ‘AssertionError: ‘ is removed from the beginning).

errisinstance(exc)[source]

Return True if the exception is an instance of exc.

Consider using isinstance(excinfo.value, exc) instead.

getrepr(showlocals=False, style='long', abspath=False, tbfilter=True, funcargs=False, truncate_locals=True, truncate_args=True, chain=True)[source]

Return str()able representation of this exception info.

Parameters:
  • showlocals (bool) – Show locals per traceback entry. Ignored if style=="native".

  • style (str) – long|short|line|no|native|value traceback style.

  • abspath (bool) – If paths should be changed to absolute or left unchanged.

  • tbfilter (bool | Callable[[ExceptionInfo[BaseException]], Traceback]) –

    A filter for traceback entries.

    • If false, don’t hide any entries.

    • If true, hide internal entries and entries that contain a local variable __tracebackhide__ = True.

    • If a callable, delegates the filtering to the callable.

    Ignored if style is "native".

  • funcargs (bool) – Show fixtures (“funcargs” for legacy purposes) per traceback entry.

  • truncate_locals (bool) – With showlocals==True, make sure locals can be safely represented as strings.

  • truncate_args (bool) – With showargs==True, make sure args can be safely represented as strings.

  • chain (bool) – If chained exceptions in Python 3 should be shown.

Changed in version 3.9: Added the chain parameter.

match(regexp)[source]

Check whether the regular expression regexp matches the string representation of the exception using re.search().

If it matches True is returned, otherwise an AssertionError is raised.

group_contains(expected_exception, *, match=None, depth=None)[source]

Check whether a captured exception group contains a matching exception.

Parameters:
  • expected_exception (Type[BaseException] | Tuple[Type[BaseException]]) – The expected exception type, or a tuple if one of multiple possible exception types are expected.

  • match (str | Pattern[str] | None) –

    If specified, a string containing a regular expression, or a regular expression object, that is tested against the string representation of the exception and its PEP-678 <https://peps.python.org/pep-0678/> __notes__ using re.search().

    To match a literal string that may contain special characters, the pattern can first be escaped with re.escape().

  • depth (Optional[int]) – If None, will search for a matching exception at any nesting depth. If >= 1, will only match an exception if it’s at the specified depth (depth = 1 being the exceptions contained within the topmost exception group).

Added in version 8.0.

ExitCode

final class ExitCode(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Encodes the valid exit codes by pytest.

Currently users and plugins may supply other exit codes as well.

Added in version 5.0.

OK = 0

Tests passed.

TESTS_FAILED = 1

Tests failed.

INTERRUPTED = 2

pytest was interrupted.

INTERNAL_ERROR = 3

An internal error got in the way.

USAGE_ERROR = 4

pytest was misused.

NO_TESTS_COLLECTED = 5

pytest couldn’t find tests.

FixtureDef

final class FixtureDef[source]

Bases: Generic[FixtureValue]

A container for a fixture definition.

Note: At this time, only explicitly documented fields and methods are considered public stable API.

property scope: Literal['session', 'package', 'module', 'class', 'function']

Scope string, one of “function”, “class”, “module”, “package”, “session”.

execute(request)[source]

Return the value of this fixture, executing it if not cached.

MarkDecorator

class MarkDecorator[source]

A decorator for applying a mark on test functions and classes.

MarkDecorators are created with pytest.mark:

mark1 = pytest.mark.NAME  # Simple MarkDecorator
mark2 = pytest.mark.NAME(name1=value)  # Parametrized MarkDecorator

and can then be applied as decorators to test functions:

@mark2
def test_function():
    pass

When a MarkDecorator is called, it does the following:

  1. If called with a single class as its only positional argument and no additional keyword arguments, it attaches the mark to the class so it gets applied automatically to all test cases found in that class.

  2. If called with a single function as its only positional argument and no additional keyword arguments, it attaches the mark to the function, containing all the arguments already stored internally in the MarkDecorator.

  3. When called in any other case, it returns a new MarkDecorator instance with the original MarkDecorator’s content updated with the arguments passed to this call.

Note: The rules above prevent a MarkDecorator from storing only a single function or class reference as its positional argument with no additional keyword or positional arguments. You can work around this by using with_args().

property name: str

Alias for mark.name.

property args: tuple[Any, ...]

Alias for mark.args.

property kwargs: Mapping[str, Any]

Alias for mark.kwargs.

with_args(*args, **kwargs)[source]

Return a MarkDecorator with extra arguments added.

Unlike calling the MarkDecorator, with_args() can be used even if the sole argument is a callable/class.

MarkGenerator

final class MarkGenerator[source]

Factory for MarkDecorator objects - exposed as a pytest.mark singleton instance.

Example:

import pytest


@pytest.mark.slowtest
def test_function():
    pass

applies a ‘slowtest’ Mark on test_function.

Mark

final class Mark[source]

A pytest mark.

name: str

Name of the mark.

args: tuple[Any, ...]

Positional arguments of the mark decorator.

kwargs: Mapping[str, Any]

Keyword arguments of the mark decorator.

combined_with(other)[source]

Return a new Mark which is a combination of this Mark and another Mark.

Combines by appending args and merging kwargs.

Parameters:

other (Mark) – The mark to combine with.

Return type:

Mark

Metafunc

final class Metafunc[source]

Objects passed to the pytest_generate_tests hook.

They help to inspect a test function and to generate tests according to test configuration or values specified in the class or module where a test function is defined.

definition

Access to the underlying _pytest.python.FunctionDefinition.

config

Access to the pytest.Config object for the test session.

module

The module object where the test function is defined in.

function

Underlying Python test function.

fixturenames

Set of fixture names required by the test function.

cls

Class object where the test function is defined in or None.

parametrize(argnames, argvalues, indirect=False, ids=None, scope=None, *, _param_mark=None)[source]

Add new invocations to the underlying test function using the list of argvalues for the given argnames. Parametrization is performed during the collection phase. If you need to setup expensive resources see about setting indirect to do it rather than at test setup time.

Can be called multiple times per test function (but only on different argument names), in which case each call parametrizes all previous parametrizations, e.g.

unparametrized:         t
parametrize ["x", "y"]: t[x], t[y]
parametrize [1, 2]:     t[x-1], t[x-2], t[y-1], t[y-2]
Parameters:
  • argnames (str | Sequence[str]) – A comma-separated string denoting one or more argument names, or a list/tuple of argument strings.

  • argvalues (Iterable[_pytest.mark.structures.ParameterSet | Sequence[object] | object]) –

    The list of argvalues determines how often a test is invoked with different argument values.

    If only one argname was specified argvalues is a list of values. If N argnames were specified, argvalues must be a list of N-tuples, where each tuple-element specifies a value for its respective argname.

  • indirect (bool | Sequence[str]) – A list of arguments’ names (subset of argnames) or a boolean. If True the list contains all names from the argnames. Each argvalue corresponding to an argname in this list will be passed as request.param to its respective argname fixture function so that it can perform more expensive setups during the setup phase of a test rather than at collection time.

  • ids (Iterable[object | None] | Callable[[Any], object | None] | None) –

    Sequence of (or generator for) ids for argvalues, or a callable to return part of the id for each argvalue.

    With sequences (and generators like itertools.count()) the returned ids should be of type string, int, float, bool, or None. They are mapped to the corresponding index in argvalues. None means to use the auto-generated id.

    If it is a callable it will be called for each entry in argvalues, and the return value is used as part of the auto-generated id for the whole set (where parts are joined with dashes (“-“)). This is useful to provide more specific ids for certain items, e.g. dates. Returning None will use an auto-generated id.

    If no ids are provided they will be generated automatically from the argvalues.

  • scope (Literal['session', 'package', 'module', 'class', 'function'] | None) – If specified it denotes the scope of the parameters. The scope is used for grouping tests by parameter instances. It will also override any fixture-function defined scope, allowing to set a dynamic scope using test context or configuration.

Parser

final class Parser[source]

Parser for command line arguments and ini-file values.

Variables:

extra_info – Dict of generic param -> value to display in case there’s an error processing the command line arguments.

getgroup(name, description='', after=None)[source]

Get (or create) a named option Group.

Parameters:
  • name (str) – Name of the option group.

  • description (str) – Long description for –help output.

  • after (str | None) – Name of another group, used for ordering –help output.

Returns:

The option group.

Return type:

OptionGroup

The returned group object has an addoption method with the same signature as parser.addoption but will be shown in the respective group in the output of pytest --help.

addoption(*opts, **attrs)[source]

Register a command line option.

Parameters:
  • opts (str) – Option names, can be short or long options.

  • attrs (Any) – Same attributes as the argparse library’s add_argument() function accepts.

After command line parsing, options are available on the pytest config object via config.option.NAME where NAME is usually set by passing a dest attribute, for example addoption("--long", dest="NAME", ...).

parse_known_args(args, namespace=None)[source]

Parse the known arguments at this point.

Returns:

An argparse namespace object.

Return type:

Namespace

parse_known_and_unknown_args(args, namespace=None)[source]

Parse the known arguments at this point, and also return the remaining unknown arguments.

Returns:

A tuple containing an argparse namespace object for the known arguments, and a list of the unknown arguments.

Return type:

tuple[Namespace, list[str]]

addini(name, help, type=None, default=<notset>)[source]

Register an ini-file option.

Parameters:
  • name (str) – Name of the ini-variable.

  • type (Literal['string', 'paths', 'pathlist', 'args', 'linelist', 'bool'] | None) –

    Type of the variable. Can be:

    • string: a string

    • bool: a boolean

    • args: a list of strings, separated as in a shell

    • linelist: a list of strings, separated by line breaks

    • paths: a list of pathlib.Path, separated as in a shell

    • pathlist: a list of py.path, separated as in a shell

    For paths and pathlist types, they are considered relative to the ini-file. In case the execution is happening without an ini-file defined, they will be considered relative to the current working directory (for example with --override-ini).

    Added in version 7.0: The paths variable type.

    Added in version 8.1: Use the current working directory to resolve paths and pathlist in the absence of an ini-file.

    Defaults to string if None or not passed.

  • default (Any) – Default value if no ini-file option exists but is queried.

The value of ini-variables can be retrieved via a call to config.getini(name).

OptionGroup

class OptionGroup[source]

A group of options shown in its own section.

addoption(*opts, **attrs)[source]

Add an option to this group.

If a shortened version of a long option is specified, it will be suppressed in the help. addoption('--twowords', '--two-words') results in help showing --two-words only, but --twowords gets accepted and the automatic destination is in args.twowords.

Parameters:
  • opts (str) – Option names, can be short or long options.

  • attrs (Any) – Same attributes as the argparse library’s add_argument() function accepts.

PytestPluginManager

final class PytestPluginManager[source]

Bases: PluginManager

A pluggy.PluginManager with additional pytest-specific functionality:

  • Loading plugins from the command line, PYTEST_PLUGINS env variable and pytest_plugins global variables found in plugins being loaded.

  • conftest.py loading during start-up.

register(plugin, name=None)[source]

Register a plugin and return its name.

Parameters:

name (str | None) – The name under which to register the plugin. If not specified, a name is generated using get_canonical_name().

Returns:

The plugin name. If the name is blocked from registering, returns None.

Return type:

str | None

If the plugin is already registered, raises a ValueError.

getplugin(name)[source]
hasplugin(name)[source]

Return whether a plugin with the given name is registered.

import_plugin(modname, consider_entry_points=False)[source]

Import a plugin with modname.

If consider_entry_points is True, entry point names are also considered to find a plugin.

add_hookcall_monitoring(before, after)

Add before/after tracing functions for all hooks.

Returns an undo function which, when called, removes the added tracers.

before(hook_name, hook_impls, kwargs) will be called ahead of all hook calls and receive a hookcaller instance, a list of HookImpl instances and the keyword arguments for the hook call.

after(outcome, hook_name, hook_impls, kwargs) receives the same arguments as before but also a Result object which represents the result of the overall hook call.

add_hookspecs(module_or_class)

Add new hook specifications defined in the given module_or_class.

Functions are recognized as hook specifications if they have been decorated with a matching HookspecMarker.

check_pending()

Verify that all hooks which have not been verified against a hook specification are optional, otherwise raise PluginValidationError.

enable_tracing()

Enable tracing of hook calls.

Returns an undo function which, when called, removes the added tracing.

get_canonical_name(plugin)

Return a canonical name for a plugin object.

Note that a plugin may be registered under a different name specified by the caller of register(plugin, name). To obtain the name of a registered plugin use get_name(plugin) instead.

get_hookcallers(plugin)

Get all hook callers for the specified plugin.

Returns:

The hook callers, or None if plugin is not registered in this plugin manager.

Return type:

list[HookCaller] | None

get_name(plugin)

Return the name the plugin is registered under, or None if is isn’t.

get_plugin(name)

Return the plugin registered under the given name, if any.

get_plugins()

Return a set of all registered plugin objects.

has_plugin(name)

Return whether a plugin with the given name is registered.

is_blocked(name)

Return whether the given plugin name is blocked.

is_registered(plugin)

Return whether the plugin is already registered.

list_name_plugin()

Return a list of (name, plugin) pairs for all registered plugins.

list_plugin_distinfo()

Return a list of (plugin, distinfo) pairs for all setuptools-registered plugins.

load_setuptools_entrypoints(group, name=None)

Load modules from querying the specified setuptools group.

Parameters:
  • group (str) – Entry point group to load plugins.

  • name (str | None) – If given, loads only plugins with the given name.

Returns:

The number of plugins loaded by this call.

Return type:

int

set_blocked(name)

Block registrations of the given name, unregister if already registered.

subset_hook_caller(name, remove_plugins)

Return a proxy HookCaller instance for the named method which manages calls to all registered plugins except the ones from remove_plugins.

unblock(name)

Unblocks a name.

Returns whether the name was actually blocked.

unregister(plugin=None, name=None)

Unregister a plugin and all of its hook implementations.

The plugin can be specified either by the plugin object or the plugin name. If both are specified, they must agree.

Returns the unregistered plugin, or None if not found.

project_name: Final

The project name.

hook: Final

The “hook relay”, used to call a hook on all registered plugins. See Calling hooks.

trace: Final[_tracing.TagTracerSub]

The tracing entry point. See Built-in tracing.

TerminalReporter

final class TerminalReporter(config, file=None)[source]
wrap_write(content, *, flush=False, margin=8, line_sep='\n', **markup)[source]

Wrap message with margin for progress info.

rewrite(line, **markup)[source]

Rewinds the terminal cursor to the beginning and writes the given line.

Parameters:

erase – If True, will also add spaces until the full terminal width to ensure previous lines are properly erased.

The rest of the keyword arguments are markup instructions.

build_summary_stats_line()[source]

Build the parts used in the last summary stats line.

The summary stats line is the line shown at the end, “=== 12 passed, 2 errors in Xs===”.

This function builds a list of the “parts” that make up for the text in that line, in the example above it would be:

[
    ("12 passed", {"green": True}),
    ("2 errors", {"red": True}
]

That last dict for each line is a “markup dictionary”, used by TerminalWriter to color output.

The final color of the line is also determined by this function, and is the second element of the returned tuple.

TestReport

final class TestReport[source]

Bases: BaseReport

Basic test report object (also used for setup and teardown calls if they fail).

Reports can contain arbitrary extra attributes.

nodeid: str

Normalized collection nodeid.

location: tuple[str, int | None, str]

A (filesystempath, lineno, domaininfo) tuple indicating the actual location of a test item - it might be different from the collected one e.g. if a method is inherited from a different module. The filesystempath may be relative to config.rootdir. The line number is 0-based.

keywords: Mapping[str, Any]

A name -> value dictionary containing all keywords and markers associated with a test invocation.

outcome: Literal['passed', 'failed', 'skipped']

Test outcome, always one of “passed”, “failed”, “skipped”.

longrepr: None | ExceptionInfo[BaseException] | tuple[str, int, str] | str | TerminalRepr

None or a failure representation.

when: str | None

One of ‘setup’, ‘call’, ‘teardown’ to indicate runtest phase.

user_properties

User properties is a list of tuples (name, value) that holds user defined properties of the test.

sections: list[tuple[str, str]]

Tuples of str (heading, content) with extra information for the test report. Used by pytest to add text captured from stdout, stderr, and intercepted logging events. May be used by other plugins to add arbitrary information to reports.

duration: float

Time it took to run just the test.

start: float

The system time when the call started, in seconds since the epoch.

stop: float

The system time when the call ended, in seconds since the epoch.

classmethod from_item_and_call(item, call)[source]

Create and fill a TestReport with standard item and call info.

Parameters:
  • item (Item) – The item.

  • call (CallInfo[None]) – The call info.

property caplog: str

Return captured log lines, if log capturing is enabled.

Added in version 3.5.

property capstderr: str

Return captured text from stderr, if capturing is enabled.

Added in version 3.0.

property capstdout: str

Return captured text from stdout, if capturing is enabled.

Added in version 3.0.

property count_towards_summary: bool

Experimental Whether this report should be counted towards the totals shown at the end of the test session: “1 passed, 1 failure, etc”.

Note

This function is considered experimental, so beware that it is subject to changes even in patch releases.

property failed: bool

Whether the outcome is failed.

property fspath: str

The path portion of the reported node, as a string.

property head_line: str | None

Experimental The head line shown with longrepr output for this report, more commonly during traceback representation during failures:

________ Test.foo ________

In the example above, the head_line is “Test.foo”.

Note

This function is considered experimental, so beware that it is subject to changes even in patch releases.

property longreprtext: str

Read-only property that returns the full string representation of longrepr.

Added in version 3.0.

property passed: bool

Whether the outcome is passed.

property skipped: bool

Whether the outcome is skipped.

TestShortLogReport

class TestShortLogReport[source]

Used to store the test status result category, shortletter and verbose word. For example "rerun", "R", ("RERUN", {"yellow": True}).

Variables:
  • category – The class of result, for example “passed”, “skipped”, “error”, or the empty string.

  • letter – The short letter shown as testing progresses, for example ".", "s", "E", or the empty string.

  • word – Verbose word is shown as testing progresses in verbose mode, for example "PASSED", "SKIPPED", "ERROR", or the empty string.

category: str

Alias for field number 0

letter: str

Alias for field number 1

word: str | tuple[str, Mapping[str, bool]]

Alias for field number 2

Result

hook 包装器 中使用的结果对象,请参阅 pluggy 文档中的 Result 以了解更多信息。

Stash

class Stash[source]

Stash is a type-safe heterogeneous mutable mapping that allows keys and value types to be defined separately from where it (the Stash) is created.

Usually you will be given an object which has a Stash, for example Config or a Node:

stash: Stash = some_object.stash

If a module or plugin wants to store data in this Stash, it creates StashKeys for its keys (at the module level):

# At the top-level of the module
some_str_key = StashKey[str]()
some_bool_key = StashKey[bool]()

To store information:

# Value type must match the key.
stash[some_str_key] = "value"
stash[some_bool_key] = True

To retrieve the information:

# The static type of some_str is str.
some_str = stash[some_str_key]
# The static type of some_bool is bool.
some_bool = stash[some_bool_key]

Added in version 7.0.

__setitem__(key, value)[source]

Set a value for key.

__getitem__(key)[source]

Get the value for key.

Raises KeyError if the key wasn’t set before.

get(key, default)[source]

Get the value for key, or return default if the key wasn’t set before.

setdefault(key, default)[source]

Return the value of key if already set, otherwise set the value of key to default and return default.

__delitem__(key)[source]

Delete the value for key.

Raises KeyError if the key wasn’t set before.

__contains__(key)[source]

Return whether key was set.

__len__()[source]

Return how many items exist in the stash.

class StashKey[source]

Bases: Generic[T]

StashKey is an object used as a key to a Stash.

A StashKey is associated with the type T of the value of the key.

A StashKey is unique and cannot conflict with another key.

Added in version 7.0.

全局变量

Global Variables

pytest 对在测试模块或 conftest.py 文件中定义的一些全局变量采取特殊处理。

collect_ignore

教程: 自定义测试收集

可以在 conftest.py 文件 中声明,以排除测试目录或模块。 需要是一个路径的列表(str, pathlib.Path 或任何 os.PathLike)。


collect_ignore = [“setup.py”]

collect_ignore_glob

教程: 自定义测试收集

可以在 conftest.py 文件 中声明,以使用 Unix shell 风格的通配符排除测试目录或模块。 需要是 list[str],其中 str 可以包含通配模式。


collect_ignore_glob = [”*_ignore.py”]

pytest_plugins

教程: 在测试模块或 conftest 文件中请求/加载插件

可以在 测试模块conftest.py 文件全局 级别声明,以注册附加插件。 可以是一个 strSequence[str]

pytest_plugins = "myapp.testsupport.myplugin"
pytest_plugins = ("myapp.testsupport.tools", "myapp.testsupport.regression")
pytestmark

教程: 标记整个类或模块

可以在 测试模块全局 级别声明,以将一个或多个 marks 应用到所有测试函数和方法。 可以是单个标记或标记列表(按从左到右的顺序应用)。

import pytest

pytestmark = pytest.mark.webtest
import pytest

pytestmark = [pytest.mark.integration, pytest.mark.slow]

环境变量

Environment Variables

可以用来改变 pytest 行为的环境变量。

CI

当设置时(无论值如何),pytest 认可它正在 CI 过程中运行。是 BUILD_NUMBER 变量的替代。另见 CI Pipelines

BUILD_NUMBER

当设置时(无论值如何),pytest 认可它正在 CI 过程中运行。是 CI 变量的替代。另见 CI Pipelines

PYTEST_ADDOPTS

这包含一个命令行(由 py:mod:shlex 模块解析),将被 前置 到用户提供的命令行,更多信息见 内置配置文件选项

PYTEST_VERSION

该环境变量在 pytest 会话开始时定义,之后未定义。 它包含 pytest.__version__ 的值,除此之外可以用来轻松检查代码是否在 pytest 运行中执行。

PYTEST_CURRENT_TEST

该变量不应该由用户设置,而是由 pytest 内部设置为当前测试的名称,以便其他进程可以检查它,更多信息见 PYTEST_CURRENT_TEST 环境变量

PYTEST_DEBUG

当设置时,pytest 将打印跟踪和调试信息。

PYTEST_DISABLE_PLUGIN_AUTOLOAD

当设置时,通过 entry point packaging metadata 禁用插件自动加载。仅加载明确指定的插件。

PYTEST_PLUGINS

包含应作为插件加载的模块的以逗号分隔的列表:

export PYTEST_PLUGINS=mymodule.plugin,xdist
PYTEST_THEME

设置要用于代码输出的 pygment style

PYTEST_THEME_MODE

PYTEST_THEME 设置为 darklight

PY_COLORS

当设置为 1 时,pytest 将在终端输出中使用颜色。 当设置为 0 时,pytest 将不使用颜色。 PY_COLORS 优先于 NO_COLORFORCE_COLOR

NO_COLOR

当设置为非空字符串(无论值如何)时,pytest 将不在终端输出中使用颜色。 PY_COLORS 优先于 NO_COLOR,而 NO_COLOR 优先于 FORCE_COLOR。 有关其他支持此社区标准的库,请参见 no-color.org

FORCE_COLOR

当设置为非空字符串(无论值如何)时,pytest 将在终端输出中使用颜色。 PY_COLORSNO_COLOR 优先于 FORCE_COLOR

异常

Exceptions

final exception UsageError[source]

Bases: Exception

Error in pytest usage or invocation.

final exception FixtureLookupError[source]

Bases: LookupError

Could not return a requested fixture (missing or invalid).

告警

Warnings

在某些情况下(例如不当使用或弃用的功能)会生成自定义警告。

class PytestWarning

Bases: UserWarning

Base class for all warnings emitted by pytest.

class PytestAssertRewriteWarning

Bases: PytestWarning

Warning emitted by the pytest assert rewrite module.

class PytestCacheWarning

Bases: PytestWarning

Warning emitted by the cache plugin in various situations.

class PytestCollectionWarning

Bases: PytestWarning

Warning emitted when pytest is not able to collect a file or symbol in a module.

class PytestConfigWarning

Bases: PytestWarning

Warning emitted for configuration issues.

class PytestDeprecationWarning

Bases: PytestWarning, DeprecationWarning

Warning class for features that will be removed in a future version.

class PytestExperimentalApiWarning

Bases: PytestWarning, FutureWarning

Warning category used to denote experiments in pytest.

Use sparingly as the API might change or even be removed completely in a future version.

class PytestRemovedIn9Warning

Bases: PytestDeprecationWarning

Warning class for features that will be removed in pytest 9.

class PytestUnknownMarkWarning

Bases: PytestWarning

Warning emitted on use of unknown markers.

See 如何用属性标记测试函数 for details.

class PytestUnraisableExceptionWarning

Bases: PytestWarning

An unraisable exception was reported.

Unraisable exceptions are exceptions raised in __del__ implementations and similar situations when the exception cannot be raised as normal.

class PytestUnhandledThreadExceptionWarning

Bases: PytestWarning

An unhandled exception occurred in a Thread.

Such exceptions don’t propagate normally.

有关更多信息,请参阅文档中的 内部 pytest 警告 部分。

配置选项

Configuration Options

这是一个内置配置选项的列表,可以写入 pytest.ini (或 .pytest.ini)、pyproject.tomltox.inisetup.cfg 文件,通常位于您仓库的根目录。

要详细了解每种文件格式,请参见 配置文件格式

Warning

除了非常简单的用例外,不推荐使用 setup.cfg.cfg 文件使用与 pytest.initox.ini 不同的解析器,这可能会导致难以追踪的问题。 如果可能,建议使用后者文件或 pyproject.toml 来保存您的 pytest 配置。

可以通过使用 -o/--override-ini 在命令行中覆盖配置选项,也可以多次传递。预期格式为 name=value。例如:

pytest -o console_output_style=classic -o cache_dir=/tmp/mycache
addopts

将指定的 OPTS 添加到命令行参数集,就好像它们是由用户指定的一样。例如:如果您的 ini 文件内容是:

# content of pytest.ini
[pytest]
addopts = --maxfail=2 -rf  # 在 2 次失败后退出,报告失败信息

发出 pytest test_hello.py 实际上意味着:

pytest --maxfail=2 -rf test_hello.py

默认是不添加任何选项。

cache_dir

设置缓存插件内容存储的目录。默认目录为 .pytest_cache,它在 rootdir 中创建。目录可以是 相对或绝对路径。如果设置相对路径,则目录相对于 rootdir 创建。此外,路径可以包含环境变量,这些变量将被扩展。有关缓存插件的更多信息,请参阅 如何重新运行失败的测试并在测试运行之间保持状态

consider_namespace_packages

控制 pytest 是否应尝试识别收集 Python 模块时的 namespace packages。 默认值为 False

如果您正在测试的包是命名空间包的一部分,请设置为 True

仅支持 native namespace packages,不打算支持 legacy namespace packages

Added in version 8.1.

console_output_style

设置运行测试时的控制台输出样式:

  • classic: 经典的 pytest 输出。

  • progress: 类似经典 pytest 输出,但带有进度指示器。

  • progress-even-when-capture-no: 即使 capture=no 也允许使用进度指示器。

  • count: 类似进度,但显示已完成测试的数量而不是百分比。

默认值为 progress,但如果您更喜欢经典模式或新模式导致意外问题,可以回退到 classic

# content of pytest.ini
[pytest]
console_output_style = classic
disable_test_id_escaping_and_forfeit_all_rights_to_community_support

Added in version 4.4.

pytest 默认会转义在参数化中使用的任何非 ASCII 字符,因为这样做有几个缺点。 如果您希望在参数化中使用 Unicode 字符串,并在终端中看到未转义的字符串,请在 pytest.ini 中使用此选项:

[pytest]
disable_test_id_escaping_and_forfeit_all_rights_to_community_support = True

但请注意,这可能会导致不希望的副作用,甚至取决于所使用的操作系统和当前安装的插件而导致错误,因此请自行承担风险。

默认值:False

参见 @pytest.mark.parametrize: 参数化测试函数

doctest_encoding

用于解码带有文档字符串的文本文件的默认编码。 参见 pytest 如何处理 doctests

doctest_optionflags

一个或多个来自标准 doctest 模块的 doctest 标志名称。 参见 pytest 如何处理 doctests

empty_parameter_set_mark

允许选择在参数化中为空参数集的操作。

  • skip 跳过带有空参数集的测试(默认)

  • xfail 将带有空参数集的测试标记为 xfail(run=False)

  • fail_at_collect 如果参数化收集了一个空参数集,则引发异常

# content of pytest.ini
[pytest]
empty_parameter_set_mark = xfail

Note

此选项的默认值计划在未来的版本中更改为 xfail,因为这被认为更不易出错,详细信息请参见 #3155

faulthandler_timeout

如果测试运行时间超过 X 秒(包括 fixture 设置和拆卸),则转储所有线程的回溯。使用 faulthandler.dump_traceback_later() 函数实现,因此所有相关警告都适用。

# content of pytest.ini
[pytest]
faulthandler_timeout=5

有关更多信息,请参见 故障处理

filterwarnings

设置应该针对匹配警告采取的过滤器和操作列表。默认情况下,测试会话期间发出的所有警告将在测试会话结束时的总结中显示。

# content of pytest.ini
[pytest]
filterwarnings =
    error
    ignore::DeprecationWarning

这告诉 pytest 忽略弃用警告并将所有其他警告转换为错误。有关更多信息,请参见 如何捕获警告

junit_duration_report

Added in version 4.1.

配置持续时间如何记录到 JUnit XML 报告中:

  • total (默认值):报告的持续时间包括设置、调用和拆卸时间。

  • call:报告的持续时间仅包括调用时间,不包括设置和拆卸。

[pytest]
junit_duration_report = call
junit_family

Added in version 4.2.

Changed in version 6.1: 默认值更改为 xunit2

配置生成的 JUnit XML 文件的格式。可能的选项有:

  • xunit1 (或 legacy):生成旧样式输出,与 xunit 1.0 格式兼容。

  • xunit2:生成 xunit 2.0 样式输出,应与最新的 Jenkins 版本更兼容。 这是默认值

[pytest]
junit_family = xunit2
junit_logging

Added in version 3.5.

Changed in version 5.4: 添加了 logallout-err 选项。

配置捕获的输出是否应写入 JUnit XML 文件。有效值为:

  • log:仅写入 logging 捕获的输出。

  • system-out:写入捕获的 stdout 内容。

  • system-err:写入捕获的 stderr 内容。

  • out-err:同时写入捕获的 stdoutstderr 内容。

  • all:写入捕获的 loggingstdoutstderr 内容。

  • no (默认值):不写入捕获的输出。

[pytest]
junit_logging = system-out
junit_log_passing_tests

Added in version 4.6.

如果 junit_logging != "no",则配置捕获的输出是否应为 通过 的测试写入 JUnit XML 文件。默认值为 True

[pytest]
junit_log_passing_tests = False
junit_suite_name

要设置根测试套件 XML 项目的名称,可以在配置文件中配置 junit_suite_name 选项:

[pytest]
junit_suite_name = my_suite
log_auto_indent

允许对多行日志消息进行选择性自动缩进。

支持命令行选项 --log-auto-indent [value] 和配置选项 log_auto_indent = [value] 来设置 所有日志记录的自动缩进行为。

[value] 可以是:
  • True 或 “On” - 动态自动缩进多行日志消息

  • False 或 “Off” 或 0 - 不自动缩进多行日志消息(默认行为)

  • [正整数] - 按 [value] 空格自动缩进多行日志消息

[pytest]
log_auto_indent = False

支持将关键字参数 extra={"auto_indent": [value]} 传递给 logging.log() 的调用,以指定日志中特定条目的自动缩进行为。extra 关键字参数会覆盖命令行或配置中指定的值。

log_cli

在测试运行期间启用日志显示(也称为 “实时日志记录”)。默认值为 False

[pytest]
log_cli = True
log_cli_date_format

设置一个与 time.strftime() 兼容的字符串,用于格式化实时日志记录中的日期。

[pytest]
log_cli_date_format = %Y-%m-%d %H:%M:%S

有关更多信息,请参见 实时日志

log_cli_format

设置一个与 logging 兼容的字符串,用于格式化实时日志记录消息。

[pytest]
log_cli_format = %(asctime)s %(levelname)s %(message)s

有关更多信息,请参见 实时日志

log_cli_level

设置应为实时日志记录捕获的最低日志消息级别。可以使用整数值或级别名称。

[pytest]
log_cli_level = INFO

有关更多信息,请参见 实时日志

log_date_format

设置一个与 time.strftime() 兼容的字符串,用于格式化日志捕获中的日期。

[pytest]
log_date_format = %Y-%m-%d %H:%M:%S

有关更多信息,请参见 如何管理日志记录

log_file

设置一个相对于当前工作目录的文件名,用于写入日志消息,此外还可以使用其他活动的日志记录设施。

[pytest]
log_file = logs/pytest-logs.txt

有关更多信息,请参见 如何管理日志记录

log_file_date_format

设置一个与 time.strftime() 兼容的字符串,用于格式化日志文件中的日期。

[pytest]
log_file_date_format = %Y-%m-%d %H:%M:%S

有关更多信息,请参见 如何管理日志记录

log_file_format

设置一个与 logging 兼容的字符串,用于格式化重定向到日志文件的日志消息。

[pytest]
log_file_format = %(asctime)s %(levelname)s %(message)s

有关更多信息,请参见 如何管理日志记录

log_file_level

设置应为日志文件捕获的最低日志消息级别。可以使用整数值或级别名称。

[pytest]
log_file_level = INFO

有关更多信息,请参见 如何管理日志记录

log_format

设置一个与 logging 兼容的字符串,用于格式化捕获的日志消息。

[pytest]
log_format = %(asctime)s %(levelname)s %(message)s

有关更多信息,请参见 如何管理日志记录

log_level

设置应为日志捕获的最低日志消息级别。可以使用整数值或级别名称。

[pytest]
log_level = INFO

有关更多信息,请参见 如何管理日志记录

markers

当使用 --strict-markers--strict 命令行参数时, 仅允许已知标记——由核心 pytest 或某个插件在代码中定义的标记。

您可以在此设置中列出其他标记,以将其添加到白名单中, 在这种情况下,您可能想将 --strict-markers 添加到 addopts 中,以避免未来的回归:

[pytest]
addopts = --strict-markers
markers =
    slow
    serial

Note

强烈建议使用 --strict-markers--strict 仅保留用于 向后兼容,可能会使其他人感到困惑,因为它仅适用于 标记,而不适用于其他选项。

minversion

指定运行测试所需的最低 pytest 版本。

# content of pytest.ini
[pytest]
minversion = 3.0  # 如果使用 pytest-2.8 运行,将失败
norecursedirs

设置在递归查找测试时要避免的目录基名模式。单个(fnmatch 风格)模式 应用于目录的基名,以决定是否递归进入它。 模式匹配字符:

*       匹配所有内容
?       匹配任意单个字符
[seq]   匹配 seq 中的任意字符
[!seq]  匹配不在 seq 中的任意字符

默认模式为 '*.egg''.*''_darcs''build''CVS''dist''node_modules''venv''{arch}'。 设置 norecursedirs 会替换默认值。以下是避免某些目录的示例:

[pytest]
norecursedirs = .svn _build tmp*

这将告诉 pytest 不要查看典型的 Subversion 或 sphinx-build 目录或任何以 tmp 为前缀的目录。

此外,pytest 将尝试智能识别并忽略 虚拟环境。任何被认为是虚拟环境根目录的目录 在测试收集期间将不会被考虑,除非 给定 --collect-in-virtualenv。还请注意,norecursedirs 优先于 --collect-in-virtualenv;例如,如果您打算 在与 '.*' 匹配的基础目录中的虚拟环境中运行测试, 您 必须 在使用 --collect-in-virtualenv 标志的同时覆盖 norecursedirs

python_classes

一个或多个名称前缀或通配符样式的模式,用于确定哪些类 被视为测试收集的对象。通过在模式之间添加空格来搜索多个通配符模式。 默认情况下,pytest 会将任何以 Test 开头的类视为测试收集。 下面是一个示例,演示如何从以 Suite 结尾的类中收集测试:

[pytest]
python_classes = *Suite

请注意,unittest.TestCase 派生的类始终会被收集 ,无论此选项如何,因为使用 unittest 自身的收集框架来收集这些测试。

python_files

一个或多个通配符样式的文件模式,用于确定哪些 Python 文件 被视为测试模块。通过在模式之间添加空格来搜索多个通配符模式:

[pytest]
python_files = test_*.py check_*.py example_*.py

或每行一个:

[pytest]
python_files =
    test_*.py
    check_*.py
    example_*.py

默认情况下,匹配 test_*.py*_test.py 的文件将被视为 测试模块。

python_functions

一个或多个名称前缀或通配符模式,用于确定哪些测试函数 和方法被视为测试。通过在模式之间添加空格来搜索多个通配符模式。 默认情况下,pytest 会将任何以 test 开头的函数视为测试。 下面是一个示例,演示如何收集以 _test 结尾的测试函数和方法:

[pytest]
python_functions = *_test

请注意,这对存在于 unittest.TestCase 派生类上的方法没有影响, 因为使用 unittest 自身的收集框架来收集这些测试。

请参见 更改命名约定 以获取更详细的示例。

pythonpath

设置应添加到 Python 搜索路径的目录列表。 目录将被添加到 sys.path 的开头。 类似于 PYTHONPATH 环境变量,这些目录将 包含在 Python 查找导入模块的路径中。 路径相对于 rootdir 目录。 目录在测试会话期间将保留在路径中。

[pytest]
pythonpath = src1 src2
required_plugins

一个以空格分隔的插件列表,pytest 运行时必须存在。 插件可以列出,也可以不带版本说明,直接跟在名称后面。 不允许不同版本说明之间有空白。 如果找不到其中任何一个插件,则会发出错误。

[pytest]
required_plugins = pytest-django>=3.0.0,<4.0.0 pytest-html pytest-xdist>=1.0.0
testpaths

设置应在从 rootdir 目录执行 pytest 时 搜索测试的目录列表,当命令行中未指定特定目录、文件或测试 ID 时。 文件系统路径可以使用 shell 风格的通配符,包括递归 ** 模式。

当所有项目测试都位于已知位置时,这很有用,以加速 测试收集并避免意外拾取不需要的测试。

[pytest]
testpaths = testing doc

该配置意味着执行:

pytest

与执行:

pytest testing doc

有相同的实际效果。

tmp_path_retention_count

应根据 tmp_path_retention_policy 保留多少个 tmp_path 目录会话。

[pytest]
tmp_path_retention_count = 3

默认值: 3

tmp_path_retention_policy

控制由 tmp_path 固件创建的哪些目录被保留, 基于测试结果。

  • all: 保留所有测试的目录,无论结果如何。

  • failed: 仅保留结果为 errorfailed 的测试目录。

  • none: 目录在每个测试结束后始终被删除,无论结果如何。

[pytest]
tmp_path_retention_policy = all

默认值: all

truncation_limit_chars

控制用于截断断言消息内容的最大字符数。

将值设置为 0 将禁用截断的字符限制。

[pytest]
truncation_limit_chars = 640

pytest 默认将断言消息截断到一定限制,以防止与大量数据比较导致控制台输出过载。

默认值: 640

Note

如果 pytest 检测到正在 运行于 CI,则会自动禁用截断。

truncation_limit_lines

控制用于截断断言消息内容的最大行数。

将值设置为 0 将禁用截断的行限制。

[pytest]
truncation_limit_lines = 8

pytest 默认将断言消息截断到一定限制,以防止与大量数据比较导致控制台输出过载。

默认值: 8

Note

如果 pytest 检测到正在 运行于 CI,则会自动禁用截断。

usefixtures

将应用于所有测试函数的固件列表;在语义上,这与将 @pytest.mark.usefixtures 标记应用于所有测试函数是相同的。

[pytest]
usefixtures =
    clean_db
verbosity_assertions

设置专门用于断言相关输出的详细级别,覆盖应用程序的整体级别。

[pytest]
verbosity_assertions = 2

默认为应用程序的整体详细级别(通过 -v 命令行选项)。可以使用特殊值 “auto” 来显式使用全局详细级别。

verbosity_test_cases

设置专门用于测试用例执行相关输出的详细级别,覆盖应用程序的整体级别。

[pytest]
verbosity_test_cases = 2

默认为应用程序的整体详细级别(通过 -v 命令行选项)。可以使用特殊值 “auto” 来显式使用全局详细级别。

xfail_strict

如果设置为 True,则标记为 @pytest.mark.xfail 的测试如果实际成功,默认将导致 测试套件失败。 更多信息,请参见 strict 参数

[pytest]
xfail_strict = True

命令行标志

Command-line Flags

所有命令行标志可以通过运行 pytest --help 获取:

$ pytest --help
使用: pytest [选项] [文件或目录] [文件或目录] [...]

位置参数:
    文件或目录

一般:
    -k 表达式             仅运行匹配给定子字符串
                        表达式的测试。表达式是一个可在 Python 中评估
                        的表达式,其中所有名称都与测试名称及其父类
                        进行子字符串匹配。
                        示例: -k 'test_method or test_other' 匹配所有
                        名称包含 'test_method' 或 'test_other' 的测试函数和类,
                        而 -k 'not test_method' 匹配那些名称中不包含
                        'test_method' 的测试。 -k 'not test_method
                        and not test_other' 将消除匹配。
                        此外,关键字也会与包含额外名称的类和
                        函数进行匹配,这些额外名称在它们的
                        'extra_keyword_matches' 集中,以及直接
                        分配给它们的函数名称。匹配不区分大小写。
    -m MARKEXPR           仅运行与给定标记表达式匹配的测试。例如:
                        -m 'mark1 and not mark2'。
    --markers             显示标记(内置、插件和每个项目的标记)。
    -x, --exitfirst       在第一个错误或失败测试时立即退出
    --fixtures, --funcargs
                        显示可用的固件,按插件出现顺序排序
                        (以 '_' 开头的固件仅在 '-v' 时显示)
    --fixtures-per-test   显示每个测试的固件
    --pdb                 在错误或键盘中断时启动交互式 Python 调试器
    --pdbcls=模块名:类名
                        指定用于 --pdb 的自定义交互式 Python 调试器。
                        例如:
                        --pdbcls=IPython.terminal.debugger:TerminalPdb
    --trace               在运行每个测试时立即中断
    --capture=方法        每个测试的捕获方法:fd|sys|no|tee-sys 之一
    -s                    --capture=no 的快捷方式
    --runxfail            将 xfail 测试的结果报告为未标记
    --lf, --last-failed   仅重新运行上次运行中失败的测试(如果没有失败则全部)
    --ff, --failed-first  运行所有测试,但优先运行上次失败的测试。这
                        可能会重新排序测试,从而导致重复的固件
                        设置/拆卸。
    --nf, --new-first     优先运行新文件中的测试,然后运行按文件修改时间
                        排序的其余测试
    --cache-show=[CACHESHOW]
                        显示缓存内容,不执行收集或
                        测试。可选参数:通配符(默认:'*')。
    --cache-clear         在测试运行开始时移除所有缓存内容
    --lfnf={all,none}, --last-failed-no-failures={all,none}
                        与 ``--lf`` 一起使用时,决定是否在没有
                        之前(已知)失败或未找到任何缓存的
                        ``lastfailed`` 数据时执行测试。
                        ``all`` (默认)再次运行完整的测试套件。
                        ``none`` 仅发出关于没有已知
                        失败的消息并成功退出。
    --sw, --stepwise      在测试失败时退出,并在下次从上次失败的
                        测试继续
    --sw-skip, --stepwise-skip
                        忽略第一个失败的测试,但在下一个
                        失败的测试上停止。隐式启用 --stepwise。

报告:
    --durations=N         显示 N 个最慢的设置/测试持续时间(N=0 显示全部)
    --durations-min=N     包含在最慢列表中的最小持续时间(秒)。默认: 0.005。
    -v, --verbose         增加详细程度
    --no-header           禁用标题
    --no-summary          禁用摘要
    --no-fold-skipped     不在短摘要中折叠被跳过的测试。
    -q, --quiet           减少详细程度
    --verbosity=VERBOSE   设置详细程度。默认: 0。
    -r 字符              显示额外的测试摘要信息,字符包括:
                        (f)ailed, (E)rror, (s)kipped, (x)failed, (X)passed,
                        (p)assed, (P)assed with output, (a)ll except passed
                        (p/P), 或 (A)ll. (w)arnings 默认启用
                        (见 --disable-warnings),'N' 可用于重置
                        列表。(默认: 'fE')。
    --disable-warnings, --disable-pytest-warnings
                        禁用警告摘要
    -l, --showlocals      在回溯中显示局部变量(默认禁用)
    --no-showlocals       隐藏回溯中的局部变量(否定通过 addopts
                        传递的 --showlocals)
    --tb=样式            回溯打印模式
                        (auto/long/short/line/native/no)
    --xfail-tb            显示 xfail 的回溯(只要 --tb != no)
    --show-capture={no,stdout,stderr,log,all}
                        控制在失败测试中显示捕获的 stdout/stderr/log 的方式。默认:all。
    --full-trace          不截断任何回溯(默认是截断)
    --color=颜色         彩色终端输出(yes/no/auto)
    --code-highlight={yes,no}
                        是否突出显示代码(仅在 --color
                        也启用时)。默认:yes。
    --pastebin=模式       将失败|全部信息发送到 bpaste.net pastebin 服务
    --junit-xml=路径      在给定路径创建 junit-xml 风格的报告文件
    --junit-prefix=字符串 在 junit-xml 输出中为类名添加前缀

pytest-warnings:
    -W PYTHONWARNINGS, --pythonwarnings=PYTHONWARNINGS
                        设置要报告的警告,参见 Python 自身的 -W 选项
    --maxfail=num         在第一个 num 次失败或错误后退出
    --strict-config       在解析配置文件的 `pytest` 部分时遇到的任何警告都会引发错误
    --strict-markers      在配置文件的 `markers` 部分未注册的标记将引发错误
    --strict              (已弃用)--strict-markers 的别名
    -c FILE, --config-file=FILE
                        从 `FILE` 加载配置,而不是尝试定位隐式配置文件之一。
    --continue-on-collection-errors
                        即使发生收集错误也强制执行测试
    --rootdir=ROOTDIR     定义测试的根目录。可以是相对路径:
                        'root_dir','./root_dir',
                        'root_dir/another_dir/';绝对路径:
                        '/home/user/root_dir';带变量的路径:
                        '$HOME/root_dir'。

收集:
    --collect-only, --co  仅收集测试,不执行它们
    --pyargs              尝试将所有参数解释为 Python 包
    --ignore=path         在收集期间忽略路径(允许多次)
    --ignore-glob=path    在收集期间忽略路径模式(允许多次)
    --deselect=nodeid_prefix
                        在收集期间取消选择项目(通过节点 ID 前缀)
                        (允许多次)
    --confcutdir=dir      仅加载与指定目录相对的 conftest.py
    --noconftest          不加载任何 conftest.py 文件
    --keep-duplicates     保留重复的测试
    --collect-in-virtualenv
                        不忽略本地虚拟环境目录中的测试
    --import-mode={prepend,append,importlib}
                        导入测试模块和 conftest 文件时添加到 sys.path。
                        默认:prepend。
    --doctest-modules     运行所有 .py 模块中的文档测试
    --doctest-report={none,cdiff,ndiff,udiff,only_first_failure}
                        为文档测试失败选择另一种输出格式
    --doctest-glob=pat    文档测试文件匹配模式,默认:test*.txt
    --doctest-ignore-import-errors
                        忽略文档测试收集错误
    --doctest-continue-on-failure
                        对于给定的文档测试,在第一次失败后继续运行

测试会话调试和配置:
    --basetemp=dir        此次测试运行的基础临时目录。
                        (警告:如果该目录存在将被删除。)
    -V, --version         显示 pytest 版本和插件信息。重复给出时,还会显示插件信息。
    -h, --help            显示帮助信息和配置信息
    -p name               早期加载给定插件模块名称或入口点
                        (允许多次)。要避免加载插件,使用
                        `no:` 前缀,例如 `no:doctest`。
    --trace-config        跟踪 conftest.py 文件的考虑
    --debug=[DEBUG_FILE_NAME]
                        将内部跟踪调试信息存储在此日志文件中。该文件以 'w' 打开并被截断,
                        请小心使用。默认:pytestdebug.log。
    -o OVERRIDE_INI, --override-ini=OVERRIDE_INI
                        使用 "option=value" 风格覆盖 ini 选项,例如:
                        `-o xfail_strict=True -o cache_dir=cache`。
    --assert=模式         控制断言调试工具。
                        'plain' 不执行任何断言调试。
                        'rewrite'(默认)在导入测试模块时重写断言语句以提供断言
                        表达式信息。
    --setup-only          仅设置固件,不执行测试
    --setup-show          在执行测试时显示固件的设置
    --setup-plan          显示将要执行的固件和测试,但不执行任何内容

logging:
    --log-level=LEVEL     捕获/显示的消息级别。默认情况下未设置,因此取决于根/父日志处理程序的有效级别,默认为 "WARNING"。
    --log-format=LOG_FORMAT
                        日志模块使用的日志格式
    --log-date-format=LOG_DATE_FORMAT
                        日志模块使用的日期格式
    --log-cli-level=LOG_CLI_LEVEL
                        CLI 日志级别
    --log-cli-format=LOG_CLI_FORMAT
                        日志模块使用的日志格式
    --log-cli-date-format=LOG_CLI_DATE_FORMAT
                        日志模块使用的日期格式
    --log-file=LOG_FILE   日志将写入的文件路径
    --log-file-mode={w,a}
                        日志文件打开模式
    --log-file-level=LOG_FILE_LEVEL
                        日志文件的日志级别
    --log-file-format=LOG_FILE_FORMAT
                        日志模块使用的日志格式
    --log-file-date-format=LOG_FILE_DATE_FORMAT
                        日志模块使用的日期格式
    --log-auto-indent=LOG_AUTO_INDENT
                        自动缩进传递给日志模块的多行消息。接受 true|on、false|off 或整数。
    --log-disable=LOGGER_DISABLE
                        通过名称禁用日志记录器。可以多次传递。

[pytest] ini 选项在找到的第一个 pytest.ini|tox.ini|setup.cfg|pyproject.toml 文件中:

    markers (linelist):   为测试函数注册新标记
    empty_parameter_set_mark (string):
                        空参数集的默认标记
    norecursedirs (args): 避免递归的目录模式
    testpaths (args):     在命令行未给出文件或目录时搜索测试的目录
    filterwarnings (linelist):
                        每行指定一个模式用于
                        warnings.filterwarnings。在 -W/--pythonwarnings 之后处理。
    consider_namespace_packages (bool):
                        在导入期间解析模块名称时考虑命名空间包
    usefixtures (args):   要与此项目一起使用的默认固件列表
    python_files (args):  Python 测试模块发现的 glob 样式文件模式
    python_classes (args):
                        Python 测试类发现的前缀或 glob 名称
    python_functions (args):
                        Python 测试函数和方法发现的前缀或 glob 名称
    disable_test_id_escaping_and_forfeit_all_rights_to_community_support (bool):
                        禁用字符串转义非 ASCII 字符,可能导致不必要的副作用(自担风险使用)
    console_output_style (string):
                        控制台输出:“经典”或带有附加进度信息(“进度” (百分比) | “计数” | “即使捕获=no 也进度” (强制即使捕获=no 也显示进度)
    verbosity_test_cases (string):
                        为测试用例执行指定一个详细程度,覆盖主级别。更高的级别将提供有关每个执行测试用例的更多详细信息。
    xfail_strict (bool):  当未明确给出时,xfail 标记的严格参数的默认值(默认:False)
    tmp_path_retention_count (string):
                        根据 `tmp_path_retention_policy`,应保留多少个 `tmp_path` 目录。
    tmp_path_retention_policy (string):
                        控制基于测试结果保留哪些由 `tmp_path` 固件创建的目录。
                        (all/failed/none)
    enable_assertion_pass_hook (bool):
                        启用 pytest_assertion_pass 钩子。确保删除任何先前生成的 pyc 缓存文件。
    verbosity_assertions (string):
                        为断言指定一个详细程度,覆盖主级别。更高的级别将在断言失败时提供更详细的解释。
    junit_suite_name (string):
                        JUnit 报告的测试套件名称
    junit_logging (string):
                        将捕获的日志消息写入 JUnit 报告:可以是 no|log|system-out|system-err|out-err|all
    junit_log_passing_tests (bool):
                        捕获通过测试的日志信息以便写入 JUnit 报告:
    junit_duration_report (string):
                        报告的持续时间:可以是 total|call
    junit_family (string):
                        发出 XML 的模式:可以是 legacy|xunit1|xunit2
    doctest_optionflags (args):
                        文档测试的选项标志
    doctest_encoding (string):
                        文档测试文件使用的编码
    cache_dir (string):   缓存目录路径
    log_level (string):   --log-level 的默认值
    log_format (string):  --log-format 的默认值
    log_date_format (string):
                        --log-date-format 的默认值
    log_cli (bool):       在测试运行期间启用日志显示(也称为“实时日志”)
    log_cli_level (string):
                        --log-cli-level 的默认值
    log_cli_format (string):
                        --log-cli-format 的默认值
    log_cli_date_format (string):
                        --log-cli-date-format 的默认值
    log_file (string):    --log-file 的默认值
    log_file_mode (string):
                        --log-file-mode 的默认值
    log_file_level (string):
                        --log-file-level 的默认值
    log_file_format (string):
                        --log-file-format 的默认值
    log_file_date_format (string):
                        --log-file-date-format 的默认值
    log_auto_indent (string):
                        --log-auto-indent 的默认值
    pythonpath (paths):   添加路径到 sys.path
    faulthandler_timeout (string):
                        如果测试运行超过 TIMEOUT 秒,转储所有线程的回溯信息
    addopts (args):       附加命令行选项
    minversion (string):  最小要求的 pytest 版本
    required_plugins (args):
                        pytest 运行时必须存在的插件

环境变量:
    CI                       设置时(无论值如何),pytest 知道它正在 CI 进程中运行,并且不会截断摘要信息
    BUILD_NUMBER             等同于 CI
    PYTEST_ADDOPTS           附加命令行选项
    PYTEST_PLUGINS           启动时加载的逗号分隔插件
    PYTEST_DISABLE_PLUGIN_AUTOLOAD 设置为禁用插件自动加载
    PYTEST_DEBUG             设置以启用 pytest 内部的调试跟踪

要查看可用的标记,请输入:pytest --markers
要查看可用的固件,请输入:pytest --fixtures
(根据指定的 file_or_dir 或当前目录显示,如果未指定;以'_'开头的固件仅在使用 '-v' 选项时显示)