API 参考

此页面包含 pytest API 的完整参考。

常量

pytest.__version__

当前 pytest 版本,字符串形式

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

pytest.HIDDEN_PARAM

8.4 版本新增。

可传递给 Metafunc.parametrizeidspytest.param()id 以在测试名称中隐藏参数集。最多只能使用一次,因为测试名称需要唯一。

pytest.version_tuple

7.0 版本新增。

当前 pytest 版本,元组形式

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

对于预发布版本,最后一个组件将是包含预发布版本的字符串

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

函数

pytest.approx

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

断言两个数字(或两个有序数字序列)在一定容差范围内彼此相等。

由于 浮点算术:问题与限制,我们直觉上期望相等的数字并非总是如此

>>> 0.1 + 0.2 == 0.3
False

在编写测试时,这个问题经常遇到,例如,当确保浮点值符合预期时。处理这个问题的一种方法是断言两个浮点数在适当的容差范围内相等

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

然而,这样的比较编写起来很繁琐,并且难以理解。此外,像上面那样的绝对比较通常不被鼓励,因为没有一个容差适用于所有情况。1e-6 对于大约 1 的数字很好,但对于非常大的数字来说太小,对于非常小的数字来说又太大。最好将容差表示为预期值的一个分数,但那样的相对比较编写起来更加困难,也更不简洁。

approx 类使用尽可能直观的语法执行浮点比较

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

相同的语法也适用于有序数字序列

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

numpy 数组

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

以及 numpy 数组与标量之间的比较

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

仅支持有序序列,因为 approx 需要明确推断序列的相对位置。这意味着不支持 sets 和其他无序序列。

最后,字典的 *值* 也可以进行比较

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

如果两个映射具有相同的键,并且它们各自的值匹配预期的容差,则比较为真。

容差

默认情况下,approx 认为在其预期值 1e-6 的相对容差范围内(即百万分之一)的数字是相等的。如果预期值为 0.0,这种处理会导致令人惊讶的结果,因为除了 0.0 本身之外,没有什么是相对接近 0.0 的。为了更不令人惊讶地处理这种情况,approx 还认为在其预期值 1e-12 的绝对容差范围内的数字是相等的。无穷大和 NaN 是特殊情况。无穷大只被认为等于自身,无论相对容差如何。默认情况下,NaN 不被认为等于任何东西,但你可以通过将 nan_ok 参数设置为 True 来使其等于自身。(这旨在方便比较使用 NaN 表示“无数据”的数组。)

相对和绝对容差都可以通过向 approx 构造函数传递参数来更改

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

如果指定了 abs 但未指定 rel,则比较将完全不考虑相对容差。换句话说,如果两个数字超出指定的绝对容差,即使它们在默认的 1e-6 相对容差范围内,仍将被视为不相等。如果同时指定了 absrel,则只要满足其中一个容差,数字就会被视为相等

>>> 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

非数字类型

你也可以使用 approx 来比较非数字类型,或者包含非数字类型的字典和序列,在这种情况下,它会退回到严格相等。这对于比较可能包含可选值的字典和序列很有用

>>> {"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

如果你正在考虑使用 approx,那么你可能想知道它与其他比较浮点数的好方法相比如何。所有这些算法都基于相对和绝对容差,并且在大多数情况下应该一致,但它们确实存在有意义的差异

  • math.isclose(a, b, rel_tol=1e-9, abs_tol=0.0):如果相对容差相对于 ab 得到满足,或者如果绝对容差得到满足,则为 True。因为相对容差是相对于 ab 计算的,所以此测试是对称的(即 ab 均不是“参考值”)。如果你想与 0.0 比较,你必须指定一个绝对容差,因为默认情况下没有容差。更多信息:math.isclose()

  • numpy.isclose(a, b, rtol=1e-5, atol=1e-8):如果 ab 之间的差异小于相对于 b 的相对容差和绝对容差之和,则为 True。因为相对容差只相对于 b 计算,所以此测试是不对称的,你可以将 b 视为参考值。对序列比较的支持由 numpy.allclose() 提供。更多信息:numpy.isclose

  • unittest.TestCase.assertAlmostEqual(a, b):如果 ab1e-7 的绝对容差范围内,则为 True。不考虑相对容差,因此此函数不适用于非常大或非常小的数字。此外,它仅在 unittest.TestCase 的子类中可用,并且因为它不遵循 PEP8 而显得有些笨拙。更多信息:unittest.TestCase.assertAlmostEqual()

  • a == pytest.approx(b, rel=1e-6, abs=1e-12):如果相对容差相对于 b 得到满足,或者如果绝对容差得到满足,则为 True。因为相对容差只相对于 b 计算,所以此测试是不对称的,你可以将 b 视为参考值。在明确指定绝对容差但未指定相对容差的特殊情况下,只考虑绝对容差。

注意

approx 可以处理 numpy 数组,但如果你需要比较、NaN 或基于 ULP 的容差支持,我们推荐使用 测试支持 中的专用测试助手。

要使用正则表达式匹配字符串,你可以使用 Matches(来自 re_assert 包)。

注意

与内置的相等性不同,此函数认为布尔值与数字零或一不相等。例如

>>> 1 == approx(True)
False

警告

3.2 版本中已更改。

为了避免不一致的行为,>>=<<= 比较会引发 TypeError。以下示例说明了这个问题

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)

在第二个示例中,预期会调用 approx(0.1).__le__(0.1 + 1e-10)。但实际上,使用了 approx(0.1).__lt__(0.1 + 1e-10) 进行比较。这是因为富比较的调用层次结构遵循固定的行为。更多信息请参阅:object.__ge__()

在 3.7.1 版本中更改: approx 遇到非数字类型的字典值或序列元素时,会引发 TypeError

在 6.1.0 版本中更改: approx 对于非数字类型会回退到严格相等,而不是引发 TypeError

pytest.fail

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

fail(reason[, pytrace=True])

使用给定消息显式使正在执行的测试失败。

参数:
  • reason (str) – 向用户显示作为失败原因的消息。

  • pytrace (bool) – 如果为 False,则 msg 表示完整的失败信息,并且不会报告 python 堆栈跟踪。

引发:

pytest.fail.Exception – 引发的异常。

class pytest.fail.Exception

pytest.fail() 引发的异常。

pytest.skip

skip(reason[, allow_module_level=False])

使用给定消息跳过正在执行的测试。

此函数应仅在测试期间(设置、调用或 teardown)或在收集期间使用 allow_module_level 标志调用。此函数也可以在 doctests 中调用。

参数:
  • reason (str) – 向用户显示作为跳过原因的消息。

  • allow_module_level (bool) –

    允许此函数在模块级别调用。在模块级别引发跳过异常将停止模块的执行,并阻止收集模块中的所有测试,甚至包括在 skip 调用之前定义的测试。

    默认为 False。

引发:

pytest.skip.Exception – 引发的异常。

注意

在可能的情况下,最好使用 pytest.mark.skipif 标记来声明在某些条件(如平台不匹配或依赖项缺失)下跳过测试。类似地,使用 # doctest: +SKIP 指令(参见 doctest.SKIP)静态跳过 doctest。

class pytest.skip.Exception

pytest.skip() 引发的异常。

pytest.importorskip

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

导入并返回请求的模块 modname,如果无法导入该模块,则跳过当前测试。

参数:
  • modname (str) – 要导入的模块名称。

  • minversion (str | None) – 如果给定,则导入模块的 __version__ 属性必须至少为该最小版本,否则测试仍将被跳过。

  • reason (str | None) – 如果给定,当模块无法导入时,此原因将作为消息显示。

  • exc_type (type[ImportError] | None) –

    为了跳过模块而应该捕获的异常。必须是 ImportError 或其子类。

    如果模块可以导入但引发 ImportError,pytest 将向用户发出警告,因为用户通常期望找不到模块(这将改为引发 ModuleNotFoundError)。

    可以通过显式传递 exc_type=ImportError 来抑制此警告。

    详见 pytest.importorskip 默认行为,关于 ImportError

返回:

导入的模块。应将其分配给其规范名称。

引发:

pytest.skip.Exception – 如果模块无法导入。

返回类型:

Any

示例

docutils = pytest.importorskip("docutils")

8.2 版本新增: exc_type 参数。

pytest.xfail

xfail(reason='')

强制性地将正在执行的测试或设置函数标记为预期失败,并给出指定原因。

此函数应仅在测试期间(设置、调用或 teardown)调用。

使用 xfail() 后不会执行其他代码(它在内部通过引发异常来实现)。

参数:

reason (str) – 向用户显示作为 xfail 原因的消息。

注意

在可能的情况下,最好使用 pytest.mark.xfail 标记来声明在特定条件(如已知 bug 或缺失功能)下预期失败的测试。

引发:

pytest.xfail.Exception – 引发的异常。

class pytest.xfail.Exception

pytest.xfail() 引发的异常。

pytest.exit

exit(reason[, returncode=None])

退出测试过程。

参数:
  • reason (str) – 作为退出 pytest 的原因显示的消息。reason 仅因为 msg 已弃用而具有默认值。

  • returncode (int | None) – 退出 pytest 时使用的返回码。None 与 0(无错误)相同,与 sys.exit() 相同。

引发:

pytest.exit.Exception – 引发的异常。

class pytest.exit.Exception

pytest.exit() 引发的异常。

pytest.main

教程: 从 Python 代码调用 pytest

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

执行进程内测试运行。

参数:
  • args (list[str] | PathLike[str] | None) – 命令行参数列表。如果为 None 或未给出,则默认为直接从进程命令行 (sys.argv) 读取参数。

  • plugins (Sequence[str | object] | None) – 在初始化期间自动注册的插件对象列表。

返回:

退出代码。

返回类型:

int | ExitCode

pytest.param

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

pytest.mark.parametrize 调用或 参数化夹具 中指定一个参数。

@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
参数:
  • values (object) – 参数集值的可变参数,按顺序排列。

  • marks (MarkDecorator | Collection[MarkDecorator | Mark]) –

    要应用于此参数集的单个标记或标记列表。

    pytest.mark.usefixtures 不能通过此参数添加。

  • id (str | Literal[pytest.HIDDEN_PARAM] | None) –

    要分配给此参数集的 ID。

    8.4 版本新增: pytest.HIDDEN_PARAM 表示从测试名称中隐藏参数集。最多只能使用一次,因为测试名称需要唯一。

pytest.raises

教程: 关于近似相等的断言

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

断言代码块/函数调用引发异常类型或其子类。

参数:
  • expected_exception

    预期的异常类型,或如果预期多种可能的异常类型,则为元组。请注意,传递的异常的子类也将匹配。

    这不是必需参数,你可以选择只使用 match 和/或 check 来验证引发的异常。

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

    如果指定,则为包含正则表达式的字符串,或正则表达式对象,该正则表达式将与异常的字符串表示及其 PEP 678 __notes__ 使用 re.search() 进行测试。

    为了匹配可能包含 特殊字符 的字面字符串,模式可以先用 re.escape() 进行转义。

    (这仅在 pytest.raises 用作上下文管理器时使用,否则会直接传递给函数。当将 pytest.raises 用作函数时,你可以使用:pytest.raises(Exc, func, match="passed on").match("my pattern")。)

  • check (Callable[[BaseException], bool]) –

    8.4 版本新增。

    如果指定,则为可调用对象,它将在检查类型和匹配正则表达式(如果指定)后,以异常作为参数被调用。如果它返回 True,则被视为匹配成功;否则,被视为匹配失败。

pytest.raises 用作上下文管理器,它将捕获给定类型或其任何子类的异常

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

如果代码块没有引发预期的异常(上述示例中的 ZeroDivisionError),或者根本没有引发异常,则检查将失败。

你还可以使用关键字参数 match 来断言异常匹配文本或正则表达式

>>> 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")

match 参数搜索格式化的异常字符串,其中包含任何 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

如果提供了 check 参数,则在传递引发的异常后,它必须返回 True 才能使匹配成功,否则会引发 AssertionError

>>> import errno
>>> with pytest.raises(OSError, check=lambda e: e.errno == errno.EACCES):
...     raise OSError(errno.EACCES, "no permission to view")

上下文管理器会生成一个 ExceptionInfo 对象,可用于检查捕获异常的详细信息

>>> 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"

警告

鉴于 pytest.raises 匹配子类,在使用它匹配 Exception 时要小心,例如这样

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

因为 Exception 是几乎所有异常的基类,所以这很容易隐藏真正的错误,用户编写此代码期望一个特定的异常,但由于重构引入的错误而引发了其他异常。

除非确定你真的想捕获**任何**引发的异常,否则避免使用 pytest.raises 来捕获 Exception

注意

当使用 pytest.raises 作为上下文管理器时,值得注意的是,正常的上下文管理器规则适用,并且引发的异常**必须**是上下文管理器作用域内的最后一行。在那之后,在上下文管理器作用域内的代码行将不会被执行。例如

>>> 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.

相反,必须采用以下方法(注意范围上的差异)

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

预期异常组

当预期封装在 BaseExceptionGroupExceptionGroup 中的异常时,应改为使用 pytest.RaisesGroup

pytest.mark.parametrize 一起使用

使用 pytest.mark.parametrize 时,可以对测试进行参数化,使得一些运行会引发异常而另一些则不会。

有关示例,请参见 参数化条件引发

另请参见

关于近似相等的断言,了解更多示例和详细讨论。

旧式

可以通过传递一个待调用的 lambda 来指定一个可调用对象

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

或者你可以指定一个带有参数的任意可调用对象

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

上述形式完全受支持,但不鼓励用于新代码,因为上下文管理器形式被认为更具可读性且不易出错。

注意

与 Python 中捕获的异常对象类似,显式清除对返回的 ExceptionInfo 对象的局部引用可以帮助 Python 解释器加速其垃圾回收。

清除这些引用打破了引用循环(ExceptionInfo –> 捕获的异常 –> 引发异常的帧栈 –> 当前帧栈 –> 局部变量 –> ExceptionInfo),这使得 Python 会保留该循环中引用的所有对象(包括当前帧中的所有局部变量),直到下一次循环垃圾回收运行。更多详细信息可以在官方 Python 文档的 try 语句 中找到。

pytest.deprecated_call

教程: 确保代码触发弃用警告

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

断言代码会产生 DeprecationWarningPendingDeprecationWarningFutureWarning

此函数可用作上下文管理器

>>> 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

它也可以通过传递一个函数以及 *args**kwargs 来使用,在这种情况下,它将确保调用 func(*args, **kwargs) 会产生上述警告类型之一。返回值是函数的返回值。

在上下文管理器形式中,你可以使用关键字参数 match 来断言警告与文本或正则表达式匹配。

上下文管理器会生成一个 warnings.WarningMessage 对象列表,每个引发的警告对应一个。

pytest.register_assert_rewrite

教程: 断言重写

register_assert_rewrite(*names)[source]

注册一个或多个模块名称以在导入时重写。

此函数将确保此模块或包内的所有模块的断言语句都将被重写。因此,你应确保在模块实际导入之前调用此函数,如果你是使用包的插件,通常在你的 __init__.py 中。

参数:

names (str) – 要注册的模块名称。

pytest.warns

教程: 使用 warns 函数断言警告

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

断言代码引发特定类别的警告。

具体来说,参数 expected_warning 可以是一个警告类或警告类元组,并且 with 块内的代码必须发出至少一个该类或这些类的警告。

此助手生成一个 warnings.WarningMessage 对象列表,每个发出的警告对应一个(无论它是否是 expected_warning)。从 pytest 8.0 开始,当上下文关闭时,未匹配的警告也会重新发出。

此函数可用作上下文管理器

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

在上下文管理器形式中,你可以使用关键字参数 match 来断言警告与文本或正则表达式匹配

>>> 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...

pytest.mark.parametrize 一起使用

使用 pytest.mark.parametrize 时,可以对测试进行参数化,使得一些运行会引发警告而另一些则不会。

这可以通过与异常相同的方式实现,详见 参数化条件引发

pytest.freeze_includes

教程: 冻结 pytest

freeze_includes()[source]

返回 pytest 使用的模块名称列表,这些模块应由 cx_freeze 包含。

标记

标记可用于将元数据应用于**测试函数**(但不能应用于夹具),然后夹具或插件可以访问这些元数据。

pytest.mark.filterwarnings

教程: @pytest.mark.filterwarnings

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

pytest.mark.filterwarnings(filter)
参数:

filter (str) –

一个*警告规范字符串*,由 Python 文档的 警告过滤器 部分中指定的元组 (action, message, category, module, lineno) 的内容组成,以 ":" 分隔。可选字段可以省略。用于过滤的模块名称不会进行正则表达式转义。

例如

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

pytest.mark.parametrize

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

此标记与 pytest.Metafunc.parametrize() 具有相同的签名;请参阅此处。

pytest.mark.skip

教程: 跳过测试函数

无条件跳过测试函数。

pytest.mark.skip(reason=None)
参数:

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

pytest.mark.skipif

教程: 跳过测试函数

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

pytest.mark.skipif(condition, *, reason=None)
参数:
  • condition (boolstr) – 如果条件应跳过,则为 True/False条件字符串

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

pytest.mark.usefixtures

教程: 在类和模块中使用 usefixtures 夹具

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

pytest.mark.usefixtures(*names)
参数:

args – 要使用的夹具名称,以字符串形式。

注意

在钩子中使用 usefixtures 时,它只能在测试设置之前应用于测试函数时加载夹具(例如在 pytest_collection_modifyitems 钩子中)。

另请注意,此标记应用于**夹具**时无效。

pytest.mark.xfail

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

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

pytest.mark.xfail(condition=False, *, reason=None, raises=None, run=True, strict=strict_xfail)
参数:
  • 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,但如果它意外通过,则将**失败**测试套件。这对于标记始终失败的函数特别有用,如果它们意外开始通过(例如,库的新版本修复了已知错误),则应有明确指示。

    默认为 strict_xfail,其默认值为 False

自定义标记

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

例如

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

将创建并将一个 Mark 对象附加到已收集的 Item,夹具或钩子可以通过 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(...)

夹具

教程: 夹具参考

测试函数或其他夹具通过将其声明为参数名来请求夹具。

需要夹具的测试示例

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

需要另一个夹具的夹具示例

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

有关更多详细信息,请查阅完整的 夹具文档

@pytest.fixture

@fixture(fixture_function: Callable[[...], object], *, 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) FixtureFunctionDefinition[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

用于标记夹具工厂函数的装饰器。

此装饰器可用于(带参数或不带参数)定义夹具函数。

夹具函数的名称可在以后引用,以使其在运行测试之前被调用:测试模块或类可以使用 pytest.mark.usefixtures(fixturename) 标记。

测试函数可以直接使用夹具名称作为输入参数,在这种情况下,将注入从夹具函数返回的夹具实例。

夹具可以使用 returnyield 语句向测试函数提供其值。使用 yield 时,yield 语句之后的代码块将作为拆卸代码执行,无论测试结果如何,并且必须只产生一次。

参数:
  • scope

    此夹具共享的范围;可以是 "function" (默认)、"class""module""package""session" 之一。

    此参数也可以是可调用对象,它接收 (fixture_name, config) 作为参数,并且必须返回一个具有上述值之一的 str

    有关更多信息,请参阅文档中的 动态范围

  • params – 可选的参数列表,它将导致夹具函数及其所有使用它的测试被多次调用。当前参数在 request.param 中可用。

  • autouse – 如果为 True,则夹具函数将对所有可见它的测试激活。如果为 False(默认值),则需要显式引用才能激活夹具。

  • ids – 与参数对应的 id 序列,使其成为测试 id 的一部分。如果没有提供 id,它们将根据参数自动生成。

  • name – 夹具的名称。这默认为装饰函数的名称。如果夹具在其定义的同一模块中使用,则夹具的函数名称将被请求夹具的函数参数遮蔽;解决此问题的一种方法是将装饰函数命名为 fixture_<fixturename>,然后使用 @pytest.fixture(name='<fixturename>')

capfd

教程: 如何捕获 stdout/stderr 输出

capfd()[source]

启用对文件描述符 12 写入的文本捕获。

捕获的输出通过 capfd.readouterr() 方法调用提供,该方法返回一个 (out, err) 命名元组。outerr 将是 text 对象。

返回 CaptureFixture[str] 的实例。

示例

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

capfdbinary

教程: 如何捕获 stdout/stderr 输出

capfdbinary()[source]

启用对文件描述符 12 写入的字节捕获。

捕获的输出通过 capfd.readouterr() 方法调用提供,该方法返回一个 (out, err) 命名元组。outerr 将是 byte 对象。

返回 CaptureFixture[bytes] 的实例。

示例

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

caplog

教程: 如何管理日志记录

caplog()[source]

访问和控制日志捕获。

捕获的日志可通过以下属性/方法获取

* 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

返回 pytest.LogCaptureFixture 实例。

final class LogCaptureFixture[source]

提供日志捕获的访问和控制。

property handler: LogCaptureHandler

获取夹具使用的日志处理程序。

get_records(when)[source]

获取某个测试阶段的日志记录。

参数:

when (Literal['setup', 'call', 'teardown']) – 从哪个测试阶段获取记录。有效值为:“setup”、“call”和“teardown”。

返回:

给定阶段捕获的记录列表。

返回类型:

list[LogRecord]

3.4 版本新增。

property text: str

格式化的日志文本。

property records: list[LogRecord]

日志记录列表。

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

一个简化版日志记录的列表,旨在用于断言比较。

元组的格式是

(logger_name, log_level, message)

property messages: list[str]

格式插值的日志消息列表。

与包含用于插值的格式字符串和参数的“records”不同,此列表中的日志消息都经过插值。

与包含处理程序输出的“text”不同,此列表中的日志消息未包含级别、时间戳等修饰,从而使精确比较更可靠。

请注意,不包含回溯或堆栈信息(来自 logging.exception() 或日志函数中的 exc_infostack_info 参数),因为这是由处理程序中的格式化程序添加的。

3.7 版本新增。

clear()[source]

重置日志记录列表和捕获的日志文本。

set_level(level, logger=None)[source]

在测试期间设置日志记录器的阈值级别。

严重程度低于此级别的日志消息将不会被捕获。

3.4 版本更改:此函数更改的日志记录器级别将在测试结束时恢复为初始值。

如果通过 logging.disable() 禁用了请求的日志级别,则会启用它。

参数:
  • level (int | str) – 级别。

  • logger (str | None) – 要更新的日志记录器。如果未给出,则为根日志记录器。

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

上下文管理器,用于设置日志捕获级别。在“with”语句块结束后,级别将恢复为原始值。

如果通过 logging.disable() 禁用了请求的日志级别,则会启用它。

参数:
  • level (int | str) – 级别。

  • logger (str | None) – 要更新的日志记录器。如果未给出,则为根日志记录器。

with filtering(filter_)[source]

上下文管理器,用于在“with”语句块内临时将给定过滤器添加到 caplog 的 handler(),并在块结束时移除该过滤器。

参数:

filter – 自定义 logging.Filter 对象。

7.5 版本新增。

capsys

教程: 如何捕获 stdout/stderr 输出

capsys()[source]

启用对 sys.stdoutsys.stderr 写入的文本捕获。

捕获的输出通过 capsys.readouterr() 方法调用提供,该方法返回一个 (out, err) 命名元组。outerr 将是 text 对象。

返回 CaptureFixture[str] 的实例。

示例

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

capsyscapsysbinarycapfdcapfdbinary 夹具返回的对象。

readouterr()[source]

读取并返回迄今为止捕获的输出,重置内部缓冲区。

返回:

捕获的内容作为带有 outerr 字符串属性的命名元组。

返回类型:

CaptureResult

with disabled()[source]

with 块内临时禁用捕获。

capteesys

教程: 如何捕获 stdout/stderr 输出

capteesys()[source]

启用同时文本捕获并根据 --capture= 将写入 sys.stdoutsys.stderr 的内容进行直通。

捕获的输出通过 capteesys.readouterr() 方法调用提供,该方法返回一个 (out, err) 命名元组。outerr 将是 text 对象。

输出也会被直通,允许它根据 --capture= 进行“实时打印”、报告或两者兼有。

返回 CaptureFixture[str] 的实例。

示例

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

capsysbinary

教程: 如何捕获 stdout/stderr 输出

capsysbinary()[source]

启用对 sys.stdoutsys.stderr 写入的字节捕获。

捕获的输出通过 capsysbinary.readouterr() 方法调用提供,该方法返回一个 (out, err) 命名元组。outerr 将是 bytes 对象。

返回 CaptureFixture[bytes] 的实例。

示例

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

config.cache

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

config.cache 对象允许其他插件和夹具在测试运行之间存储和检索值。要从夹具访问它,请在夹具中请求 pytestconfig 并使用 pytestconfig.cache 获取它。

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

config.cachepytest.Cache 的一个实例

final class Cache[source]

cache 夹具的实例。

mkdir(name)[source]

返回具有给定名称的目录路径对象。

如果目录尚不存在,它将被创建。您可以使用它来管理文件,例如在测试会话之间存储/检索数据库转储。

7.0 版本新增。

参数:

name (str) – 必须是不包含 / 分隔符的字符串。确保名称包含您的插件或应用程序标识符,以防止与其他缓存用户发生冲突。

get(key, default)[source]

返回给定键的缓存值。

如果尚未缓存值或无法读取值,则返回指定的默认值。

参数:
  • key (str) – 必须是 / 分隔的值。通常,第一个名称是您的插件或应用程序的名称。

  • default – 在缓存未命中或缓存值无效的情况下返回的值。

set(key, value)[source]

保存给定键的值。

参数:
  • key (str) – 必须是 / 分隔的值。通常,第一个名称是您的插件或应用程序的名称。

  • value (object) – 必须是基本 Python 类型(包括嵌套类型,如字典列表)的任意组合。

doctest_namespace

教程: 如何运行文档测试

doctest_namespace()[source]

返回一个将注入到文档测试命名空间的 dict 的夹具。

通常,此夹具与另一个 autouse 夹具一起使用

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

更多详细信息:“doctest_namespace”夹具

monkeypatch

教程: 如何打补丁/模拟模块和环境

monkeypatch()[source]

用于打补丁的便捷夹具。

此夹具提供以下方法来修改对象、字典或 os.environ

所有修改将在请求的测试函数或夹具完成后撤销。raising 参数决定如果设置/删除操作没有指定目标,是否会引发 KeyErrorAttributeError

要撤销夹具在受限范围内所做的修改,请使用 context()

返回 MonkeyPatch 实例。

final class MonkeyPatch[source]

方便地打补丁属性/项目/环境变量/系统路径的辅助工具。

monkeypatch 夹具返回。

6.2 版本更改:现在也可以直接用作 pytest.MonkeyPatch(),当夹具不可用时。在这种情况下,请使用 with MonkeyPatch.context() as mp: 或记住显式调用 undo()

classmethod with context()[source]

上下文管理器,返回一个新的 MonkeyPatch 对象,该对象在退出 with 块时撤销在块内完成的任何补丁。

示例

import functools


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

在需要测试结束前撤销一些补丁的情况下很有用,例如模拟可能破坏 pytest 本身的标准库函数(有关此示例,请参阅 #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

在目标上设置属性值,并记住旧值。

例如

import os

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

上面的代码用一个总是返回 "/"lambda 替换了 os.getcwd() 函数。

为方便起见,您可以将字符串指定为 target,它将被解释为带点导入路径,最后一部分是属性名称

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

如果属性不存在,则引发 AttributeError,除非 raising 设置为 False。

在哪里打补丁

monkeypatch.setattr 通过(临时)将名称指向的对象更改为另一个对象来工作。可能有很多名称指向任何单个对象,因此要使补丁工作,您必须确保修补被测试系统使用的名称。

有关完整的解释,请参阅 unittest.mock 文档中的 在哪里打补丁 部分,该解释适用于 unittest.mock.patch(),也适用于 monkeypatch.setattr

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

target 删除属性 name

如果未指定 nametarget 为字符串,则将其解释为带点导入路径,最后一部分是属性名称。

如果属性不存在,则引发 AttributeError,除非 raising 设置为 False。

setitem(dic, name, value)[source]

将字典条目 name 设置为值。

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

从字典中删除 name

如果它不存在,则引发 KeyError,除非 raising 设置为 False。

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

将环境变量 name 设置为 value

如果 prepend 是一个字符,则读取当前环境变量值,并用 prepend 字符连接 value

delenv(name, raising=True)[source]

从环境中删除 name

如果它不存在,则引发 KeyError,除非 raising 设置为 False。

syspath_prepend(path)[source]

path 添加到 sys.path 导入位置列表的前面。

chdir(path)[source]

将当前工作目录更改为指定路径。

参数:

path (str | PathLike[str]) – 要更改到的路径。

undo()[source]

撤销之前的更改。

此调用会消耗撤销堆栈。除非您在撤销调用后进行更多打补丁操作,否则第二次调用它没有效果。

通常无需调用 undo(),因为它在拆卸期间会自动调用。

注意

单个测试函数调用会使用相同的 monkeypatch 夹具。如果测试函数本身和其中一个测试夹具都使用了 monkeypatch,则调用 undo() 将撤销这两个函数中的所有更改。

建议使用 context()

pytestconfig

pytestconfig()[source]

会话范围的夹具,返回会话的 pytest.Config 对象。

示例

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

pytester

6.2 版本新增。

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

它提供了一个空目录,pytest 可以在其中独立执行,并包含编写测试、配置文件和匹配预期输出的功能。

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

pytest_plugins = "pytester"
final class Pytester[source]

用于编写测试/配置文件、隔离执行 pytest 以及匹配预期输出的功能,非常适合 pytest 插件的黑盒测试。

它试图尽可能地将测试运行与外部因素隔离,在初始化期间将当前工作目录修改为 path 和环境变量。

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

parseconfig()runpytest() 一起使用的插件列表。最初这是一个空列表,但可以向列表中添加插件。

在子进程模式下运行时,按名称 (str) 指定插件 - 不支持直接添加插件对象。

property path: Path

用于创建文件/运行测试等的临时目录路径。

make_hook_recorder(pluginmanager)[source]

PytestPluginManager 创建一个新的 HookRecorder

chdir()[source]

进入临时目录。

这在实例化时会自动完成。

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

在测试目录中创建新的文本文件。

参数:
  • ext (str) – 文件应使用的扩展名,包括点,例如 .py

  • args (str) – 所有参数都视为字符串并使用换行符连接。结果作为内容写入文件。文件的名称基于请求此夹具的测试函数。

  • kwargs (str) – 每个关键字都是文件的名称,其值将作为文件内容写入。

返回:

创建的第一个文件。

返回类型:

Path

示例

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

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

要创建二进制文件,请直接使用 pathlib.Path.write_bytes()

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

写入 conftest.py 文件。

参数:

source (str) – 内容。

返回:

conftest.py 文件。

返回类型:

Path

makeini(source)[source]

写入 tox.ini 文件。

参数:

source (str) – 内容。

返回:

tox.ini 文件。

返回类型:

Path

maketoml(source)[source]

写入 pytest.toml 文件。

参数:

source (str) – 内容。

返回:

pytest.toml 文件。

返回类型:

Path

9.0 版本新增。

getinicfg(source)[source]

从 tox.ini 配置文件返回 pytest 部分。

makepyprojecttoml(source)[source]

写入 pyproject.toml 文件。

参数:

source (str) – 内容。

返回:

pyproject.ini 文件。

返回类型:

Path

6.0 版本新增。

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

使用 .py 扩展名的 .makefile() 快捷方式。

默认为带有“.py”扩展名的测试名称,例如 test_foobar.py,覆盖现有文件。

示例

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]

使用 .txt 扩展名的 .makefile() 快捷方式。

默认为带有“.txt”扩展名的测试名称,例如 test_foobar.txt,覆盖现有文件。

示例

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]

将目录添加到 sys.path 列表的前面,默认为 path

当此对象在每个测试结束时销毁时,这将自动撤销。

参数:

path (str | PathLike[str] | None) – 路径。

mkdir(name)[source]

创建一个新的(子)目录。

参数:

name (str | PathLike[str]) – 目录的名称,相对于 pytester 路径。

返回:

创建的目录。

返回类型:

pathlib.Path

mkpydir(name)[source]

创建一个新的 Python 包。

这将创建一个带有空 __init__.py 文件的(子)目录,以便将其识别为 Python 包。

copy_example(name=None)[source]

将文件从项目目录复制到测试目录。

参数:

name (str | None) – 要复制的文件名称。

返回:

复制目录的路径(在 self.path 中)。

返回类型:

pathlib.Path

getnode(config, arg)[source]

获取文件的集合节点。

参数:
返回:

节点。

返回类型:

Collector | Item

getpathnode(path)[source]

返回文件的集合节点。

这类似于 getnode(),但使用 parseconfigure() 来创建(已配置的)pytest Config 实例。

参数:

path (str | PathLike[str]) – 文件路径。

返回:

节点。

返回类型:

Collector | Item

genitems(colitems)[source]

从集合节点生成所有测试项。

这将递归遍历集合节点,并返回其中包含的所有测试项的列表。

参数:

colitems (Sequence[Item | Collector]) – 集合节点。

返回:

收集到的项目。

返回类型:

list[Item]

runitem(source)[source]

运行“test_func”项。

调用测试实例(包含测试方法的类)必须提供一个 .getrunner() 方法,该方法应返回一个可以运行单个项的测试协议的运行器,例如 _pytest.runner.runtestprotocol

inline_runsource(source, *cmdlineargs)[source]

使用 pytest.main() 在进程内运行测试模块。

此运行将“source”写入临时文件并对其运行 pytest.main(),返回一个 HookRecorder 实例作为结果。

参数:
  • source (str) – 测试模块的源代码。

  • cmdlineargs – 任何要使用的额外命令行参数。

inline_genitems(*args)[source]

在进程内运行 pytest.main(['--collect-only'])

运行 pytest.main() 函数以在测试进程本身内运行所有 pytest,就像 inline_run() 一样,但返回一个收集到的项目元组和一个 HookRecorder 实例。

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

在进程内运行 pytest.main(),返回一个 HookRecorder。

运行 pytest.main() 函数以在测试进程本身内部运行所有 pytest。这意味着它可以返回一个 HookRecorder 实例,该实例提供比通过匹配 runpytest() 的 stdout/stderr 更详细的运行结果。

参数:
  • args (str | PathLike[str]) – 传递给 pytest.main() 的命令行参数。

  • pluginspytest.main() 实例应使用的额外插件实例。

  • no_reraise_ctrlc (bool) – 通常我们会重新引发子运行中的键盘中断。如果为 True,则会捕获 KeyboardInterrupt 异常。

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

返回在进程内运行 pytest 的结果,提供与 self.runpytest() 提供的类似接口。

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

根据命令行选项“--runpytest”在线或在子进程中运行 pytest,并返回一个 RunResult

parseconfig(*args)[source]

从给定的命令行参数返回一个新的 pytest pytest.Config 实例。

这将调用 _pytest.config 中的 pytest 引导代码以创建一个新的 pytest.PytestPluginManager 并调用 pytest_cmdline_parse 钩子以创建一个新的 pytest.Config 实例。

如果 plugins 已填充,它们应该是要注册到插件管理器中的插件模块。

parseconfigure(*args)[source]

返回一个新的 pytest 配置的 Config 实例。

返回一个新的 pytest.Config 实例,就像 parseconfig() 一样,但也会调用 pytest_configure 钩子。

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

返回测试函数的测试项。

将源写入 Python 文件并在生成的模块上运行 pytest 的收集,返回请求的函数名的测试项。

参数:
  • source (str | PathLike[str]) – 模块源代码。

  • funcname (str) – 要返回测试项的测试函数名称。

返回:

测试项。

返回类型:

Item

getitems(source)[source]

返回从模块收集到的所有测试项。

将源写入 Python 文件并在生成的模块上运行 pytest 的收集,返回其中包含的所有测试项。

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

返回 source 的模块集合节点。

使用 makepyfile()source 写入文件,然后对其运行 pytest 收集,返回测试模块的集合节点。

参数:
  • source (str | PathLike[str]) – 要收集的模块的源代码。

  • configargs – 传递给 parseconfigure() 的任何额外参数。

  • withinit (bool) – 是否也在同一目录中写入一个 __init__.py 文件以确保它是一个包。

collect_by_name(modcol, name)[source]

从模块集合中返回名称的集合节点。

在模块集合节点中搜索与给定名称匹配的集合节点。

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

调用 subprocess.Popen

调用 subprocess.Popen,确保当前工作目录在 PYTHONPATH 中。

您可能希望改用 run()

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

运行带参数的命令。

使用 subprocess.Popen 运行进程,保存 stdout 和 stderr。

参数:
  • cmdargs (str | PathLike[str]) – 要传递给 subprocess.Popen 的参数序列,路径类对象会自动转换为 str

  • timeout (float | None) – 超时并引发 Pytester.TimeoutExpired 的秒数。

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

    可选的标准输入。

    • 如果它是 CLOSE_STDIN(默认),则此方法调用 subprocess.Popen 并设置 stdin=subprocess.PIPE,在新命令启动后立即关闭标准输入。

    • 如果它是 bytes 类型,这些字节将发送到命令的标准输入。

    • 否则,它将传递给 subprocess.Popen。在这种情况下,请查阅 subprocess.Popenstdin 参数的文档以获取更多信息。

返回:

结果。

返回类型:

RunResult

runpython(script)[source]

使用 sys.executable 作为解释器运行 Python 脚本。

runpython_c(command)[source]

运行 python -c "command"

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

以给定参数作为子进程运行 pytest。

添加到 plugins 列表的任何插件都将使用 -p 命令行选项添加。此外,--basetemp 用于将任何临时文件和目录放置在以“runpytest-”为前缀的编号目录中,以免与正常的编号 pytest 临时文件和目录位置冲突。

参数:
返回:

结果。

返回类型:

RunResult

spawn_pytest(string, expect_timeout=10.0)[source]

使用 pexpect 运行 pytest。

这确保使用正确的 pytest 并设置临时目录位置。

返回 pexpect 子进程。

spawn(cmd, expect_timeout=10.0)[source]

使用 pexpect 运行命令。

返回 pexpect 子进程。

final class RunResult[source]

运行 Pytester 中命令的结果。

ret: int | ExitCode

返回值。

outlines

从标准输出捕获的行列表。

errlines

从标准错误捕获的行列表。

stdout

标准输出的 LineMatcher

使用例如 str(stdout) 重构标准输出,或使用常用的 stdout.fnmatch_lines() 方法。

stderr

标准错误的 LineMatcher

duration

持续时间(秒)。

parseoutcomes()[source]

从解析测试进程生成的终端输出中返回一个结果名词 -> 计数字典。

返回的名词总是复数形式

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

将返回 {"failed": 1, "passed": 1, "warnings": 1, "errors": 1}

classmethod parse_summary_nouns(lines)[source]

从 pytest 终端摘要行中提取名词。

为了保持一致性,它总是返回复数名词

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

将返回 {"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]

断言在测试运行的文本输出中,指定的结果以各自的数字出现(0 表示未发生)。

warningsdeselected 仅在不为 None 时才进行检查。

class LineMatcher[source]

灵活的文本匹配。

这是一个方便的类,用于测试大量文本,例如命令的输出。

构造函数接受一个没有尾随换行符的行列表,即 text.splitlines()

__str__()[source]

返回整个原始文本。

版本 6.2 新增: 旧版本可以使用 str()

fnmatch_lines_random(lines2)[source]

检查行是否以任何顺序存在于输出中(使用 fnmatch.fnmatch())。

re_match_lines_random(lines2)[source]

检查行是否以任何顺序存在于输出中(使用 re.match())。

get_lines_after(fnline)[source]

返回文本中给定行之后的所有行。

给定行可以包含 glob 通配符。

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

检查行是否在输出中存在(使用 fnmatch.fnmatch())。

参数是一个必须匹配且可以使用 glob 通配符的行列表。如果它们不匹配,则调用 pytest.fail()。匹配和不匹配也会作为错误消息的一部分显示。

参数:
  • lines2 (Sequence[str]) – 要匹配的字符串模式。

  • consecutive (bool) – 是否连续匹配行?

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

检查行是否在输出中存在(使用 re.match())。

参数是一个必须使用 re.match 匹配的行列表。如果它们不匹配,则调用 pytest.fail()。

匹配和不匹配也会作为错误消息的一部分显示。

参数:
  • lines2 (Sequence[str]) – 要匹配的字符串模式。

  • consecutive (bool) – 是否连续匹配行?

no_fnmatch_line(pat)[source]

确保捕获的行不匹配给定模式,使用 fnmatch.fnmatch

参数:

pat (str) – 匹配行的模式。

no_re_match_line(pat)[source]

确保捕获的行不匹配给定模式,使用 re.match

参数:

pat (str) – 匹配行的正则表达式。

str()[source]

返回整个原始文本。

final class HookRecorder[source]

记录插件管理器中所有调用的钩子。

钩子记录器由 Pytester 创建。

这将包装插件管理器中的所有钩子调用,在传播正常调用之前记录每个调用。

getcalls(names)[source]

获取所有记录的对给定名称(或名称)的钩子调用。

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

返回其点导入路径匹配的测试报告。

final class RecordedHookCall[source]

记录的钩子调用。

钩子调用的参数设置为属性。例如

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

教程: record_property

record_property()[source]

向调用测试添加额外属性。

用户属性成为测试报告的一部分,并可供配置的报告器(如 JUnit XML)使用。

此夹具可以使用 name, value 调用。该值会自动进行 XML 编码。

示例

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

record_testsuite_property

教程: record_testsuite_property

record_testsuite_property()[source]

将新的 <property> 标签记录为根 <testsuite> 的子级。

这适用于写入有关整个测试套件的全局信息,并与 xunit2 JUnit 系列兼容。

这是一个 session 范围的夹具,它使用 (name, value) 调用。示例

def test_foo(record_testsuite_property):
    record_testsuite_property("ARCH", "PPC")
    record_testsuite_property("STORAGE_TYPE", "CEPH")
参数:
  • name – 属性名称。

  • value – 属性值。将转换为字符串。

警告

目前,此夹具不适用于 pytest-xdist 插件。有关详细信息,请参见 #7767

recwarn

教程: 记录警告

recwarn()[source]

返回一个 WarningsRecorder 实例,该实例记录测试函数发出的所有警告。

有关警告类别的信息,请参见 如何捕获警告

class WarningsRecorder[source]

用于记录引发警告的上下文管理器。

每个记录的警告都是 warnings.WarningMessage 的一个实例。

改编自 warnings.catch_warnings

注意

DeprecationWarningPendingDeprecationWarning 的处理方式不同;请参见 确保代码触发弃用警告

property list: list[WarningMessage]

记录的警告列表。

__getitem__(i)[source]

按索引获取记录的警告。

__iter__()[source]

遍历记录的警告。

__len__()[source]

记录的警告数量。

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

弹出第一个记录的警告,该警告是 cls 的实例,但不是任何其他匹配的子类的实例。如果没有匹配项,则引发 AssertionError

clear()[source]

清除记录的警告列表。

request

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

request 夹具是一个特殊的夹具,提供有关请求测试函数的信息。

class FixtureRequest[source]

request 夹具的类型。

请求对象提供对请求测试上下文的访问权限,并且在夹具参数化时具有 param 属性。

fixturename: Final

正在为其执行此请求的夹具。

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

作用域字符串,可以是“function”、“class”、“module”、“package”、“session”之一。

property fixturenames: list[str]

此请求中所有活动夹具的名称。

abstract property node

底层集合节点(取决于当前请求作用域)。

property config: Config

与此请求关联的 pytest 配置对象。

property function

如果请求具有按函数范围的作用域,则为测试函数对象。

property cls

收集测试函数的类(可以为 None)。

property instance

收集测试函数的实例(可以为 None)。

property module

收集测试函数的 Python 模块对象。

property path: Path

收集测试函数的路径。

property keywords: MutableMapping[str, Any]

底层节点的关键字/标记字典。

property session: Session

Pytest 会话对象。

abstractmethod addfinalizer(finalizer)[source]

添加 finalizer/拆卸函数,以便在请求测试上下文中的最后一个测试执行完成后无参数地调用。

applymarker(marker)[source]

将标记应用于单个测试函数调用。

如果您不想在所有函数调用上都有关键字/标记,则此方法很有用。

参数:

marker (str | MarkDecorator) – 调用 pytest.mark.NAME(...) 创建的对象。

raiseerror(msg)[source]

引发 FixtureLookupError 异常。

参数:

msg (str | None) – 可选的自定义错误消息。

getfixturevalue(argname)[source]

动态运行命名的夹具函数。

尽可能建议通过函数参数声明夹具。但如果您只能在测试设置时决定是否使用另一个夹具,则可以在夹具或测试函数体内部使用此函数来检索它。

此方法可以在测试设置阶段或测试运行阶段使用,但在测试拆卸阶段,夹具的值可能不可用。

参数:

argname (str) – 夹具名称。

引发:

pytest.FixtureLookupError – 如果找不到给定夹具。

subtests

subtests 夹具支持在测试函数内部声明子测试。

教程: 如何使用子测试

class Subtests[source]

子测试夹具,通过 test() 方法支持在测试函数内部声明子测试。

test(msg=None, **kwargs)[source]

子测试的上下文管理器,捕获子测试范围内引发的异常并单独报告断言失败和错误。

用法

def test(subtests):
    for i in range(5):
        with subtests.test("custom message", i=i):
            assert i % 2 == 0
param msg:

如果给出,则在子测试失败时,此消息将显示在测试报告中。

param kwargs:

任意值,也添加到子测试报告中。

testdir

pytester 相同,但提供了一个实例,其方法在适用时返回旧版 py.path.local 对象。

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

final class Testdir[source]

类似于 Pytester,但此类使用旧版 legacy_path 对象。

所有方法都只是转发到内部 Pytester 实例,根据需要将结果转换为 legacy_path 对象。

exception TimeoutExpired
property tmpdir: LocalPath

执行测试的临时目录。

make_hook_recorder(pluginmanager)[source]

参见 Pytester.make_hook_recorder()

chdir()[source]

参见 Pytester.chdir()

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

参见 Pytester.makefile()

makeconftest(source)[source]

参见 Pytester.makeconftest()

makeini(source)[source]

参见 Pytester.makeini()

getinicfg(source)[source]

参见 Pytester.getinicfg()

makepyprojecttoml(source)[source]

参见 Pytester.makepyprojecttoml()

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

参见 Pytester.makepyfile()

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

参见 Pytester.maketxtfile()

syspathinsert(path=None)[source]

参见 Pytester.syspathinsert()

mkdir(name)[source]

参见 Pytester.mkdir()

mkpydir(name)[source]

参见 Pytester.mkpydir()

copy_example(name=None)[source]

参见 Pytester.copy_example()

getnode(config, arg)[source]

参见 Pytester.getnode()

getpathnode(path)[source]

参见 Pytester.getpathnode()

genitems(colitems)[source]

参见 Pytester.genitems()

runitem(source)[source]

参见 Pytester.runitem()

inline_runsource(source, *cmdlineargs)[source]

参见 Pytester.inline_runsource()

inline_genitems(*args)[source]

参见 Pytester.inline_genitems()

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

参见 Pytester.inline_run()

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

参见 Pytester.runpytest_inprocess()

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

参见 Pytester.runpytest()

parseconfig(*args)[source]

参见 Pytester.parseconfig()

parseconfigure(*args)[source]

参见 Pytester.parseconfigure()

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

参见 Pytester.getitem()

getitems(source)[source]

参见 Pytester.getitems()

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

参见 Pytester.getmodulecol()

collect_by_name(modcol, name)[source]

参见 Pytester.collect_by_name()

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

参见 Pytester.popen()

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

参见 Pytester.run()

runpython(script)[source]

参见 Pytester.runpython()

runpython_c(command)[source]

参见 Pytester.runpython_c()

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

参见 Pytester.runpytest_subprocess()

spawn_pytest(string, expect_timeout=10.0)[source]

参见 Pytester.spawn_pytest()

spawn(cmd, expect_timeout=10.0)[source]

参见 Pytester.spawn()

tmp_path

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

tmp_path()[source]

返回一个临时目录(作为 pathlib.Path 对象),该目录对于每个测试函数调用都是唯一的。临时目录创建为基本临时目录的子目录,具有可配置的保留期,如 临时目录位置和保留 中所述。

tmp_path_factory

教程: tmp_path_factory fixture

tmp_path_factoryTempPathFactory 的一个实例。

final class TempPathFactory[source]

在公共基础临时目录下创建临时目录的工厂,如 临时目录位置和保留 中所述。

mktemp(basename, numbered=True)[source]

创建一个由工厂管理的新临时目录。

参数:
  • basename (str) – 目录的基本名称,必须是相对路径。

  • numbered (bool) – 如果为 True,则通过添加一个大于任何现有数字后缀的编号后缀来确保目录是唯一的:basename="foo-"numbered=True 意味着此函数将创建名为 "foo-0""foo-1""foo-2" 等的目录。

返回:

新目录的路径。

返回类型:

Path

getbasetemp()[source]

返回基础临时目录,如果需要则创建它。

返回:

基础临时目录。

返回类型:

Path

tmpdir

教程: tmpdir 和 tmpdir_factory fixture

tmpdir()

返回一个临时目录(作为 legacy_path 对象),该目录对于每个测试函数调用都是唯一的。临时目录创建为基本临时目录的子目录,具有可配置的保留期,如 临时目录位置和保留 中所述。

注意

现在,建议使用 tmp_path

关于 tmpdir 和 tmpdir_factory fixture.

tmpdir_factory

教程: tmpdir 和 tmpdir_factory fixture

tmpdir_factoryTempdirFactory 的一个实例。

final class TempdirFactory[source]

TempPathFactory 实现 py.path.local 的向后兼容包装器。

注意

现在,建议使用 tmp_path_factory

关于 tmpdir 和 tmpdir_factory fixture.

mktemp(basename, numbered=True)[source]

TempPathFactory.mktemp() 相同,但返回一个 py.path.local 对象。

getbasetemp()[source]

TempPathFactory.getbasetemp() 相同,但返回一个 py.path.local 对象。

钩子

教程: 编写插件

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

@pytest.hookimpl

@pytest.hookimpl

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

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

@pytest.hookspec

@pytest.hookspec

pytest 用于标记函数为钩子规范的装饰器。

参见 声明新钩子pluggy.HookspecMarker()

引导钩子

为足够早注册的插件(内部和第三方插件)调用的引导钩子。

pytest_load_initial_conftests(early_config, parser, args)[source]

在命令行选项解析之前,用于实现加载 初始 conftest 文件

参数:
  • early_config (Config) – pytest 配置对象。

  • args (list[str]) – 命令行上传入的参数。

  • parser (Parser) – 用于添加命令行选项。

在 conftest 插件中使用

此钩子不用于 conftest 文件。

pytest_cmdline_parse(pluginmanager, args)[source]

返回一个已初始化 Config,解析指定的参数。

在第一个非 None 结果处停止,参见 firstresult: 在第一个非 None 结果处停止

注意

此钩子仅在使用 pytest.main 执行进程内测试运行时,为传递给 plugins 参数的插件类调用。

参数:
返回:

pytest 配置对象。

返回类型:

Config | None

在 conftest 插件中使用

此钩子不用于 conftest 文件。

pytest_cmdline_main(config)[source]

用于执行主要命令行操作。

默认实现将调用配置钩子和 pytest_runtestloop

在第一个非 None 结果处停止,参见 firstresult: 在第一个非 None 结果处停止

参数:

config (Config) – pytest 配置对象。

返回:

退出代码。

返回类型:

ExitCode | int | None

在 conftest 插件中使用

此钩子仅用于 初始 conftest

初始化钩子

为插件和 conftest.py 文件调用的初始化钩子。

pytest_addoption(parser, pluginmanager)[source]

注册 argparse 风格的选项和 config 风格的配置值,在测试运行开始时调用一次。

参数:

选项稍后可以通过 config 对象访问,分别

config 对象通过 .config 属性传递给许多内部对象,也可以作为 pytestconfig fixture 检索。

注意

此钩子与钩子包装器不兼容。

在 conftest 插件中使用

如果 conftest 插件实现了此钩子,它将在 conftest 注册时立即调用。

此钩子仅用于 初始 conftest

pytest_addhooks(pluginmanager)[source]

在插件注册时调用,允许通过调用 pluginmanager.add_hookspecs(module_or_class, prefix) 添加新钩子。

参数:

pluginmanager (PytestPluginManager) – pytest 插件管理器。

注意

此钩子与钩子包装器不兼容。

在 conftest 插件中使用

如果 conftest 插件实现了此钩子,它将在 conftest 注册时立即调用。

pytest_configure(config)[source]

允许插件和 conftest 文件执行初始配置。

注意

此钩子与钩子包装器不兼容。

参数:

config (Config) – pytest 配置对象。

在 conftest 插件中使用

此钩子在解析命令行选项后,为每个 初始 conftest 文件调用。之后,当其他 conftest 文件注册时,会调用此钩子。

pytest_unconfigure(config)[source]

在测试进程退出前调用。

参数:

config (Config) – pytest 配置对象。

在 conftest 插件中使用

任何 conftest 文件都可以实现此钩子。

pytest_sessionstart(session)[source]

Session 对象创建之后,执行收集并进入运行测试循环之前调用。

参数:

session (Session) – pytest 会话对象。

在 conftest 插件中使用

此钩子仅用于 初始 conftest

pytest_sessionfinish(session, exitstatus)[source]

在整个测试运行结束后,将退出状态返回给系统之前调用。

参数:
  • session (Session) – pytest 会话对象。

  • exitstatus (int | ExitCode) – pytest 将返回给系统的状态。

在 conftest 插件中使用

任何 conftest 文件都可以实现此钩子。

pytest_plugin_registered(plugin, plugin_name, manager)[source]

已注册一个新的 pytest 插件。

参数:
  • plugin (_PluggyPlugin) – 插件模块或实例。

  • plugin_name (str) – 插件注册时使用的名称。

  • manager (PytestPluginManager) – pytest 插件管理器。

注意

此钩子与钩子包装器不兼容。

在 conftest 插件中使用

如果 conftest 插件实现了此钩子,它将在 conftest 注册时立即调用,每个已注册的插件都会调用一次(包括其自身!),之后所有注册的插件也会调用此钩子。

收集钩子

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

pytest_collection(session)[source]

为给定会话执行收集阶段。

在第一个非 None 结果处停止,参见 firstresult: 在第一个非 None 结果处停止。返回值未使用,但仅停止进一步处理。

默认收集阶段如下(有关完整详细信息,请参见各个钩子)

  1. session 作为初始收集器开始

  1. pytest_collectstart(collector)

  2. report = pytest_make_collect_report(collector)

  3. 如果发生交互式异常,则 pytest_exception_interact(collector, call, report)

  4. 对于每个收集到的节点

  1. 如果是一个项,pytest_itemcollected(item)

  2. 如果是一个收集器,则递归进入。

  1. pytest_collectreport(report)

  1. pytest_collection_modifyitems(session, config, items)

  1. 对于任何未选定的项目(可能会多次调用),pytest_deselected(items)

  1. pytest_collection_finish(session)

  2. session.items 设置为收集到的项目列表

  3. session.testscollected 设置为收集到的项目数

您可以实现此钩子以仅在收集之前执行某些操作,例如终端插件使用它来开始显示收集计数器(并返回 None)。

参数:

session (Session) – pytest 会话对象。

在 conftest 插件中使用

此钩子仅用于 初始 conftest

pytest_ignore_collect(collection_path, path, config)[source]

返回 True 以忽略此路径进行收集。

返回 None 以允许其他插件忽略此路径进行收集。

返回 False 将强制忽略此路径进行收集,而不给其他插件忽略此路径的机会。

在调用更具体的钩子之前,会咨询所有文件和目录的此钩子。

在第一个非 None 结果处停止,参见 firstresult: 在第一个非 None 结果处停止

参数:
  • collection_path (pathlib.Path) – 要分析的路径。

  • path (LEGACY_PATH) – 要分析的路径(已弃用)。

  • config (Config) – pytest 配置对象。

版本 7.0.0 中更改: 添加了 collection_path 参数作为 pathlib.Path 等效于 path 参数。path 参数已弃用。

在 conftest 插件中使用

任何 conftest 文件都可以实现此钩子。对于给定的收集路径,只咨询收集路径的父目录中的 conftest 文件(如果路径是目录,则不会咨询其自身的 conftest 文件——目录不能忽略自身!)。

pytest_collect_directory(path, parent)[source]

为给定目录创建一个 Collector,如果无关则返回 None。

版本 8.0 中添加。

为获得最佳结果,返回的收集器应该是 Directory 的子类,但这不是必需的。

新节点需要将指定的 parent 作为父节点。

在第一个非 None 结果处停止,参见 firstresult: 在第一个非 None 结果处停止

参数:

path (pathlib.Path) – 要分析的路径。

参见 使用自定义目录收集器,了解此钩子的简单使用示例。

在 conftest 插件中使用

任何 conftest 文件都可以实现此钩子。对于给定的收集路径,只咨询收集路径的父目录中的 conftest 文件(如果路径是目录,则不会咨询其自身的 conftest 文件——目录不能收集自身!)。

pytest_collect_file(file_path, path, parent)[source]

为给定路径创建一个 Collector,如果无关则返回 None。

为获得最佳结果,返回的收集器应该是 File 的子类,但这不是必需的。

新节点需要将指定的 parent 作为父节点。

参数:
  • file_path (pathlib.Path) – 要分析的路径。

  • path (LEGACY_PATH) – 要收集的路径(已弃用)。

版本 7.0.0 中更改: 添加了 file_path 参数作为 pathlib.Path 等效于 path 参数。path 参数已弃用。

在 conftest 插件中使用

任何 conftest 文件都可以实现此钩子。对于给定文件路径,只咨询文件路径的父目录中的 conftest 文件。

pytest_pycollect_makemodule(module_path, path, parent)[source]

返回一个 pytest.Module 收集器,如果给定路径没有则返回 None。

对于每个匹配的测试模块路径都会调用此钩子。如果您想为不作为测试模块匹配的文件创建测试模块,则需要使用 pytest_collect_file 钩子。

在第一个非 None 结果处停止,参见 firstresult: 在第一个非 None 结果处停止

参数:
  • module_path (pathlib.Path) – 要收集的模块路径。

  • path (LEGACY_PATH) – 要收集的模块路径(已弃用)。

版本 7.0.0 中更改: 添加了 module_path 参数作为 pathlib.Path 等效于 path 参数。

path 参数已弃用,取而代之的是 fspath

在 conftest 插件中使用

任何 conftest 文件都可以实现此钩子。对于给定的父收集器,只咨询收集器目录及其父目录中的 conftest 文件。

为了影响 Python 模块中对象的收集,您可以使用以下钩子

pytest_pycollect_makeitem(collector, name, obj)[source]

返回模块中 Python 对象的自定义项/收集器,如果不存在则返回 None。

在第一个非 None 结果处停止,参见 firstresult: 在第一个非 None 结果处停止

参数:
  • collector (Module | Class) – 模块/类收集器。

  • name (str) – 模块/类中对象的名称。

  • obj (object) – 对象。

返回:

创建的项/收集器。

返回类型:

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

在 conftest 插件中使用

任何 conftest 文件都可以实现此钩子。对于给定的收集器,只咨询收集器目录及其父目录中的 conftest 文件。

pytest_generate_tests(metafunc)[source]

生成对测试函数的(多个)参数化调用。

参数:

metafunc (Metafunc) – 测试函数的 Metafunc 辅助对象。

在 conftest 插件中使用

任何 conftest 文件都可以实现此钩子。对于给定的函数定义,只咨询函数目录及其父目录中的 conftest 文件。

pytest_make_parametrize_id(config, val, argname)[source]

返回给定 val 的用户友好字符串表示形式,该字符串将用于 @pytest.mark.parametrize 调用,如果钩子不了解 val,则返回 None。

如果需要,参数名称可用作 argname

在第一个非 None 结果处停止,参见 firstresult: 在第一个非 None 结果处停止

参数:
  • config (Config) – pytest 配置对象。

  • val (object) – 参数化值。

  • argname (str) – pytest 生成的自动参数名称。

在 conftest 插件中使用

任何 conftest 文件都可以实现此钩子。

影响测试跳过的钩子

pytest_markeval_namespace(config)[source]

在构造用于评估 xfail/skipif 标记中的字符串条件的全局字典时调用。

当标记的条件需要昂贵或无法在收集时获取的对象时,此功能非常有用,而正常布尔条件则需要这样做。

6.2 版本新增。

参数:

config (Config) – pytest 配置对象。

返回:

要添加的附加全局变量字典。

返回类型:

dict[str, Any]

在 conftest 插件中使用

任何 conftest 文件都可以实现此钩子。对于给定项,只咨询项父目录中的 conftest 文件。

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

pytest_collection_modifyitems(session, config, items)[source]

在执行收集后调用。可以原地过滤或重新排序项目。

当项目被取消选择(从 items 中过滤掉)时,必须显式调用钩子 pytest_deselected 并传入被取消选择的项目,以便正确通知其他插件,例如使用 config.hook.pytest_deselected(items=deselected_items)

参数:
  • session (Session) – pytest 会话对象。

  • config (Config) – pytest 配置对象。

  • items (list[Item]) – 项目对象列表。

在 conftest 插件中使用

任何 conftest 插件都可以实现此钩子。

注意

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

pytest_collection_finish(session)[source]

在收集和修改完成后调用。

参数:

session (Session) – pytest 会话对象。

在 conftest 插件中使用

任何 conftest 插件都可以实现此钩子。

测试运行 (runtest) 钩子

所有与 runtest 相关的钩子都接收一个 pytest.Item 对象。

pytest_runtestloop(session)[source]

执行主 runtest 循环(收集完成后)。

默认钩子实现对会话中收集的所有项 (session.items) 执行 runtest 协议,除非收集失败或设置了 collectonly pytest 选项。

如果任何时候调用了 pytest.exit(),则循环立即终止。

如果任何时候设置了 session.shouldfailsession.shouldstop,则在当前项的 runtest 协议完成后终止循环。

参数:

session (Session) – pytest 会话对象。

在第一个非 None 结果处停止,参见 firstresult: 在第一个非 None 结果处停止。返回值未使用,但仅停止进一步处理。

在 conftest 插件中使用

任何 conftest 文件都可以实现此钩子。

pytest_runtest_protocol(item, nextitem)[source]

为单个测试项执行 runtest 协议。

默认的 runtest 协议如下(有关完整详细信息,请参见各个钩子)

  • pytest_runtest_logstart(nodeid, location)

  • 设置阶段
    • call = pytest_runtest_setup(item)(封装在 CallInfo(when="setup") 中)

    • report = pytest_runtest_makereport(item, call)

    • pytest_runtest_logreport(report)

    • 如果发生交互式异常,则 pytest_exception_interact(call, report)

  • 调用阶段,如果设置通过且未设置 setuponly pytest 选项
    • call = pytest_runtest_call(item)(封装在 CallInfo(when="call") 中)

    • report = pytest_runtest_makereport(item, call)

    • pytest_runtest_logreport(report)

    • 如果发生交互式异常,则 pytest_exception_interact(call, report)

  • 拆卸阶段
    • call = pytest_runtest_teardown(item, nextitem)(封装在 CallInfo(when="teardown") 中)

    • report = pytest_runtest_makereport(item, call)

    • pytest_runtest_logreport(report)

    • 如果发生交互式异常,则 pytest_exception_interact(call, report)

  • pytest_runtest_logfinish(nodeid, location)

参数:
  • item (Item) – 执行 runtest 协议的测试项。

  • nextitem (Item | None) – 计划中的下一个测试项(如果这是最后一个则为 None)。

在第一个非 None 结果处停止,参见 firstresult: 在第一个非 None 结果处停止。返回值未使用,但仅停止进一步处理。

在 conftest 插件中使用

任何 conftest 文件都可以实现此钩子。

pytest_runtest_logstart(nodeid, location)[source]

在单个项的 runtest 协议运行开始时调用。

有关 runtest 协议的描述,请参见 pytest_runtest_protocol

参数:
  • nodeid (str) – 项的完整节点 ID。

  • location (tuple[str, int | None, str]) – 一个元组 (filename, lineno, testname),其中 filename 是相对于 config.rootpath 的文件路径,lineno 是从 0 开始的。

在 conftest 插件中使用

任何 conftest 文件都可以实现此钩子。对于给定项,只咨询项目录及其父目录中的 conftest 文件。

pytest_runtest_logfinish(nodeid, location)[source]

在单个项的 runtest 协议运行结束时调用。

有关 runtest 协议的描述,请参见 pytest_runtest_protocol

参数:
  • nodeid (str) – 项的完整节点 ID。

  • location (tuple[str, int | None, str]) – 一个元组 (filename, lineno, testname),其中 filename 是相对于 config.rootpath 的文件路径,lineno 是从 0 开始的。

在 conftest 插件中使用

任何 conftest 文件都可以实现此钩子。对于给定项,只咨询项目录及其父目录中的 conftest 文件。

pytest_runtest_setup(item)[source]

为测试项执行设置阶段。

默认实现对 item 及其所有父项(尚未设置)运行 setup()。这包括获取项所需夹具的值(尚未获取)。

参数:

item (Item) – 项。

在 conftest 插件中使用

任何 conftest 文件都可以实现此钩子。对于给定项,只咨询项目录及其父目录中的 conftest 文件。

pytest_runtest_call(item)[source]

为测试项运行测试(调用阶段)。

默认实现调用 item.runtest()

参数:

item (Item) – 项。

在 conftest 插件中使用

任何 conftest 文件都可以实现此钩子。对于给定项,只咨询项目录及其父目录中的 conftest 文件。

pytest_runtest_teardown(item, nextitem)[source]

为测试项执行拆卸阶段。

默认实现运行终结器并对 item 及其所有父项(需要拆卸的)调用 teardown()。这包括运行项所需夹具的拆卸阶段(如果它们超出范围)。

参数:
  • item (Item) – 项。

  • nextitem (Item | None) – 计划中的下一个测试项(如果没有计划进一步的测试项则为 None)。此参数用于执行精确拆卸,即只调用足够的终结器,以便 nextitem 只需调用 setup 函数。

在 conftest 插件中使用

任何 conftest 文件都可以实现此钩子。对于给定项,只咨询项目录及其父目录中的 conftest 文件。

pytest_runtest_makereport(item, call)[source]

为测试项的 setup、call 和 teardown runtest 阶段创建 TestReport

有关 runtest 协议的描述,请参见 pytest_runtest_protocol

参数:

在第一个非 None 结果处停止,参见 firstresult: 在第一个非 None 结果处停止

在 conftest 插件中使用

任何 conftest 文件都可以实现此钩子。对于给定项,只咨询项目录及其父目录中的 conftest 文件。

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

pytest_pyfunc_call(pyfuncitem)[source]

调用底层测试函数。

在第一个非 None 结果处停止,参见 firstresult: 在第一个非 None 结果处停止

参数:

pyfuncitem (Function) – 函数项。

在 conftest 插件中使用

任何 conftest 文件都可以实现此钩子。对于给定项,只咨询项目录及其父目录中的 conftest 文件。

报告钩子

会话相关报告钩子

pytest_collectstart(collector)[source]

收集器开始收集。

参数:

collector (Collector) – 收集器。

在 conftest 插件中使用

任何 conftest 文件都可以实现此钩子。对于给定的收集器,只咨询收集器目录及其父目录中的 conftest 文件。

pytest_make_collect_report(collector)[source]

执行 collector.collect() 并返回 CollectReport

在第一个非 None 结果处停止,参见 firstresult: 在第一个非 None 结果处停止

参数:

collector (Collector) – 收集器。

在 conftest 插件中使用

任何 conftest 文件都可以实现此钩子。对于给定的收集器,只咨询收集器目录及其父目录中的 conftest 文件。

pytest_itemcollected(item)[source]

我们刚刚收集了一个测试项。

参数:

item (Item) – 项。

在 conftest 插件中使用

任何 conftest 文件都可以实现此钩子。对于给定项,只咨询项目录及其父目录中的 conftest 文件。

pytest_collectreport(report)[source]

收集器完成收集。

参数:

report (CollectReport) – 收集报告。

在 conftest 插件中使用

任何 conftest 文件都可以实现此钩子。对于给定的收集器,只咨询收集器目录及其父目录中的 conftest 文件。

pytest_deselected(items)[source]

为未选定的测试项调用,例如通过关键字。

请注意,此钩子有两个插件集成方面

  • 它可以被实现以接收未选定项的通知

  • 当项目被取消选择时,必须从 pytest_collection_modifyitems 实现中调用它(以正确通知其他插件)。

可能会多次调用。

参数:

items (Sequence[Item]) – 项。

在 conftest 插件中使用

任何 conftest 文件都可以实现此钩子。

pytest_report_header(config, start_path, startdir)[source]

返回一个字符串或字符串列表,作为终端报告的标题信息显示。

参数:
  • config (Config) – pytest 配置对象。

  • start_path (pathlib.Path) – 起始目录。

  • startdir (LEGACY_PATH) – 起始目录(已弃用)。

注意

插件返回的行显示在在其之前运行的插件的行之前。如果您希望您的行最先显示,请使用 trylast=True

版本 7.0.0 中更改: 添加了 start_path 参数作为 pathlib.Path 等效于 startdir 参数。startdir 参数已弃用。

在 conftest 插件中使用

此钩子仅用于 初始 conftest

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

返回一个字符串或字符串列表,在收集成功完成后显示。

这些字符串将显示在标准“collected X items”消息之后。

版本 3.2 中添加。

参数:
  • config (Config) – pytest 配置对象。

  • start_path (pathlib.Path) – 起始目录。

  • startdir (LEGACY_PATH) – 起始目录(已弃用)。

  • items (Sequence[Item]) – 将要执行的 pytest 项目列表;此列表不应修改。

注意

插件返回的行显示在在其之前运行的插件的行之前。如果您希望您的行最先显示,请使用 trylast=True

版本 7.0.0 中更改: 添加了 start_path 参数作为 pathlib.Path 等效于 startdir 参数。startdir 参数已弃用。

在 conftest 插件中使用

任何 conftest 插件都可以实现此钩子。

pytest_report_teststatus(report, config)[source]

返回状态报告的结果类别、短字母和详细单词。

结果类别是用于计算结果的类别,例如“passed”、“skipped”、“error”或空字符串。

短字母随着测试的进行而显示,例如“.”、“s”、“E”或空字符串。

在详细模式下,详细单词随着测试的进行而显示,例如“PASSED”、“SKIPPED”、“ERROR”或空字符串。

pytest 可能会根据报告结果隐式地设置这些样式。要提供显式样式,请为详细单词返回一个元组,例如 "rerun", "R", ("RERUN", {"yellow": True})

参数:
返回:

测试状态。

返回类型:

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

在第一个非 None 结果处停止,参见 firstresult: 在第一个非 None 结果处停止

在 conftest 插件中使用

任何 conftest 插件都可以实现此钩子。

pytest_report_to_serializable(config, report)[source]

将给定报告对象序列化为适合通过网络发送的数据结构,例如转换为 JSON。

参数:

在 conftest 插件中使用

任何 conftest 文件都可以实现此钩子。具体细节可能取决于调用钩子的插件。

pytest_report_from_serializable(config, data)[source]

恢复之前使用 pytest_report_to_serializable 序列化的报告对象。

参数:

config (Config) – pytest 配置对象。

在 conftest 插件中使用

任何 conftest 文件都可以实现此钩子。具体细节可能取决于调用钩子的插件。

pytest_terminal_summary(terminalreporter, exitstatus, config)[source]

向终端摘要报告添加一个部分。

参数:
  • terminalreporter (TerminalReporter) – 内部终端报告器对象。

  • exitstatus (ExitCode) – 将报告回操作系统的退出状态。

  • config (Config) – pytest 配置对象。

版本 4.2 中添加: config 参数。

在 conftest 插件中使用

任何 conftest 插件都可以实现此钩子。

pytest_fixture_setup(fixturedef, request)[source]

执行夹具设置。

参数:
  • fixturedef (FixtureDef[Any]) – 夹具定义对象。

  • request (SubRequest) – 夹具请求对象。

返回:

调用夹具函数的返回值。

返回类型:

object | None

在第一个非 None 结果处停止,参见 firstresult: 在第一个非 None 结果处停止

注意

如果 fixture 函数返回 None,根据 firstresult: 在第一个非 None 结果处停止 选项的行为,此钩子函数的其他实现将继续被调用。

在 conftest 插件中使用

任何 conftest 文件都可以实现此钩子。对于给定的 fixture,只会查阅 fixture 作用域目录及其父目录中的 conftest 文件。

pytest_fixture_post_finalizer(fixturedef, request)[source]

在 fixture 拆卸之后但在缓存清除之前调用,因此 fixture 结果 fixturedef.cached_result 仍然可用(不是 None)。

参数:
  • fixturedef (FixtureDef[Any]) – 夹具定义对象。

  • request (SubRequest) – 夹具请求对象。

在 conftest 插件中使用

任何 conftest 文件都可以实现此钩子。对于给定的 fixture,只会查阅 fixture 作用域目录及其父目录中的 conftest 文件。

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

处理内部 pytest 警告插件捕获的警告。

参数:
  • warning_message (warnings.WarningMessage) – 捕获到的警告。这与 warnings.catch_warnings 生成的对象相同,并包含与 warnings.showwarning() 参数相同的属性。

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

    指示何时捕获警告。可能的值

    • "config": 在 pytest 配置/初始化阶段。

    • "collect": 在测试收集期间。

    • "runtest": 在测试执行期间。

  • nodeid (str) – 项的完整 ID。对于不特定于某个节点的警告,为空字符串。

  • location (tuple[str, int, str] | None) – 可用时,包含有关捕获警告的执行上下文信息(文件名、行号、函数)。当执行上下文在模块级别时,function 评估为 <module>。

6.0 版本新增。

在 conftest 插件中使用

任何 conftest 文件都可以实现此钩子。如果警告特定于某个节点,则只查阅节点父目录中的 conftest 文件。

报告测试执行的核心钩子

pytest_runtest_logreport(report)[source]

处理为项目的 setup、call 和 teardown runtest 阶段生成的 TestReport

有关 runtest 协议的描述,请参见 pytest_runtest_protocol

在 conftest 插件中使用

任何 conftest 文件都可以实现此钩子。对于给定项,只咨询项目录及其父目录中的 conftest 文件。

断言相关钩子

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

返回失败断言表达式中比较的解释。

如果没有自定义解释,则返回 None,否则返回一个字符串列表。字符串将用换行符连接,但字符串中的任何换行符都将被转义。请注意,除第一行外,所有行都将稍微缩进,目的是让第一行作为摘要。

参数:
  • config (Config) – pytest 配置对象。

  • op (str) – 运算符,例如 "==", "!=", "not in"

  • left (object) – 左操作数。

  • right (object) – 右操作数。

在 conftest 插件中使用

任何 conftest 文件都可以实现此钩子。对于给定项,只咨询项目录及其父目录中的 conftest 文件。

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

每当断言通过时调用。

在 5.0 版本中添加。

使用此钩子在通过断言后进行一些处理。原始断言信息在 orig 字符串中可用,pytest 内省的断言信息在 expl 字符串中可用。

此钩子必须通过 enable_assertion_pass_hook 配置选项明确启用。

[pytest]
enable_assertion_pass_hook = true
[pytest]
enable_assertion_pass_hook = true

启用此选项时,您需要清理项目目录和解释器库中的 .pyc 文件,因为断言将需要重新写入。

参数:
  • item (Item) – 当前测试的 pytest item 对象。

  • lineno (int) – assert 语句的行号。

  • orig (str) – 包含原始断言的字符串。

  • expl (str) – 包含断言解释的字符串。

在 conftest 插件中使用

任何 conftest 文件都可以实现此钩子。对于给定项,只咨询项目录及其父目录中的 conftest 文件。

调试/交互钩子

有一些钩子可用于特殊报告或与异常的交互。

pytest_internalerror(excrepr, excinfo)[source]

为内部错误调用。

返回 True 以抑制直接向 sys.stderr 打印 INTERNALERROR 消息的 fallback 处理。

参数:

在 conftest 插件中使用

任何 conftest 插件都可以实现此钩子。

pytest_keyboard_interrupt(excinfo)[source]

为键盘中断调用。

参数:

excinfo (ExceptionInfo[KeyboardInterrupt | Exit]) – 异常信息。

在 conftest 插件中使用

任何 conftest 插件都可以实现此钩子。

pytest_exception_interact(node, call, report)[source]

当引发可能需要交互处理的异常时调用。

可能在收集期间调用(参见 pytest_make_collect_report),在这种情况下 report 是一个 CollectReport

可能在项目 runtest 期间调用(参见 pytest_runtest_protocol),在这种情况下 report 是一个 TestReport

如果引发的异常是内部异常(如 skip.Exception),则不调用此钩子。

参数:

在 conftest 插件中使用

任何 conftest 文件都可以实现此钩子。对于给定的节点,只会查阅节点父目录中的 conftest 文件。

pytest_enter_pdb(config, pdb)[source]

在 pdb.set_trace() 时调用。

插件可以使用它在 Python 调试器进入交互模式之前采取特殊操作。

参数:
  • config (Config) – pytest 配置对象。

  • pdb (pdb.Pdb) – Pdb 实例。

在 conftest 插件中使用

任何 conftest 插件都可以实现此钩子。

pytest_leave_pdb(config, pdb)[source]

离开 pdb 时调用(例如,在 pdb.set_trace() 后继续)。

插件可以使用它在 Python 调试器离开交互模式后采取特殊操作。

参数:
  • config (Config) – pytest 配置对象。

  • pdb (pdb.Pdb) – Pdb 实例。

在 conftest 插件中使用

任何 conftest 插件都可以实现此钩子。

收集树对象

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

节点

class Node[source]

基类: ABC

CollectorItem 的基类,它们是测试收集树的组成部分。

Collector 是树的内部节点,Item 是叶节点。

fspath: LEGACY_PATH

path 属性的 LEGACY_PATH 副本。旨在用于尚未迁移到 pathlib.Path 的方法,例如 Item.reportinfo。将在未来版本中弃用,建议使用 path

name: str

在父节点范围内唯一的名称。

parent

父收集器节点。

config: Config

pytest 配置对象。

session: Session

此节点所属的 pytest 会话。

path: pathlib.Path

此节点从中收集的文件系统路径(可以为 None)。

keywords: MutableMapping[str, Any]

从所有作用域收集的关键字/标记。

own_markers: list[Mark]

属于此节点的标记对象。

extra_keyword_matches: set[str]

允许添加额外关键字以用于匹配。

stash: Stash

插件可以在节点上存储信息供自己使用的地方。

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

节点的公共构造函数。

引入此间接是为了能够从节点构造函数中删除脆弱的逻辑。

子类在覆盖构造时可以使用 super().from_parent(...)

参数:

parent (Node) – 此节点的父节点。

property ihook: HookRelay

用于调用 pytest 钩子的 fspath 敏感钩子代理。

warn(warning)[source]

为此节点发出警告。

警告将在测试会话结束后显示,除非明确抑制。

参数:

warning (Warning) – 要发出的警告实例。

引发:

ValueError – 如果 warning 实例不是 Warning 的子类。

示例用法

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

在 6.2 版本中更改: 现在接受 Warning 的任何子类,而不仅仅是 PytestWarning 子类。

property nodeid: str

一个以 :: 分隔的字符串,表示其收集树地址。

for ... in iter_parents()[source]

迭代所有父收集器,从自身开始并包括自身,直到收集树的根。

在 8.1 版本中添加。

listchain()[source]

返回所有父收集器的列表,从收集树的根开始,直到并包括自身。

add_marker(marker, append=True)[source]

动态地向节点添加标记对象。

参数:
iter_markers(name=None)[source]

迭代节点的所有标记。

参数:

name (str | None) – 如果给出,则按名称属性过滤结果。

返回:

节点的标记迭代器。

返回类型:

Iterator[Mark]

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

迭代节点的所有标记。

参数:

name (str | None) – 如果给出,则按名称属性过滤结果。

返回:

一个 (node, mark) 元组的迭代器。

返回类型:

Iterator[tuple[Node, Mark]]

get_closest_marker(name: str) Mark | None
get_closest_marker(name: str, default: Mark) Mark

返回与名称匹配的第一个标记,从最接近的级别(例如函数)到更远的级别(例如模块级别)。

参数:
  • default – 如果未找到标记,则回退返回值。

  • name – 要过滤的名称。

listextrakeywords()[source]

返回自身和所有父级中的所有额外关键字的集合。

addfinalizer(fin)[source]

注册一个函数,当此节点最终确定时,该函数将在没有参数的情况下被调用。

此方法只能在此节点在设置链中处于活动状态时调用,例如在 self.setup() 期间。

getparent(cls)[source]

获取最接近的父节点(包括自身),它是给定类的实例。

参数:

cls (type[_NodeType]) – 要搜索的节点类。

返回:

如果找到,则为节点。

返回类型:

_NodeType | None

repr_failure(excinfo, style=None)[source]

返回收集或测试失败的表示。

参数:

excinfo (ExceptionInfo[BaseException]) – 失败的异常信息。

收集器

class Collector[source]

基类: Node, ABC

所有收集器的基类。

收集器通过 collect() 创建子级,从而迭代构建收集树。

exception CollectError[source]

基类: Exception

收集过程中的错误,包含自定义消息。

abstractmethod collect()[source]

为此收集器收集子级(项和收集器)。

repr_failure(excinfo)[source]

返回收集失败的表示。

参数:

excinfo (ExceptionInfo[BaseException]) – 失败的异常信息。

config: Config

pytest 配置对象。

name: str

在父节点范围内唯一的名称。

parent

父收集器节点。

path: pathlib.Path

此节点从中收集的文件系统路径(可以为 None)。

session: Session

此节点所属的 pytest 会话。

class Item[source]

基类: Node, ABC

所有测试调用项的基类。

请注意,对于单个函数,可能存在多个测试调用项。

user_properties: list[tuple[str, object]]

一个元组列表 (name, value),其中包含此测试的用户定义属性。

config: Config

pytest 配置对象。

name: str

在父节点范围内唯一的名称。

parent

父收集器节点。

path: pathlib.Path

此节点从中收集的文件系统路径(可以为 None)。

session: Session

此节点所属的 pytest 会话。

abstractmethod runtest()[source]

为此项运行测试用例。

必须由子类实现。

add_report_section(when, key, content)[source]

添加一个新的报告部分,类似于内部添加 stdout 和 stderr 捕获输出的方式。

item.add_report_section("call", "stdout", "report section contents")
参数:
  • when (str) – 可能的捕获状态之一,"setup", "call", "teardown"

  • key (str) – 节的名称,可以随意自定义。Pytest 内部使用 "stdout""stderr"

  • content (str) – 完整的字符串内容。

reportinfo()[source]

获取此项用于测试报告的位置信息。

返回一个包含三个元素的元组

  • 测试路径(默认为 self.path

  • 测试的 0 始行号(默认为 None

  • 要显示的测试名称(默认为 ""

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

返回此项的 (relfspath, lineno, testname) 元组,其中 relfspath 是相对于 config.rootpath 的文件路径,lineno 是一个 0 始行号。

文件

class File[source]

基类: FSCollector, ABC

从文件收集测试的基类。

使用非 Python 测试.

config: Config

pytest 配置对象。

name: str

在父节点范围内唯一的名称。

parent

父收集器节点。

path: pathlib.Path

此节点从中收集的文件系统路径(可以为 None)。

session: Session

此节点所属的 pytest 会话。

FSCollector

class FSCollector[source]

基类: Collector, ABC

文件系统收集器的基类。

path: pathlib.Path

此节点从中收集的文件系统路径(可以为 None)。

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

公共构造函数。

config: Config

pytest 配置对象。

name: str

在父节点范围内唯一的名称。

parent

父收集器节点。

session: Session

此节点所属的 pytest 会话。

会话

final class Session[source]

基类: Collector

收集树的根。

Session 收集作为 pytest 参数给出的初始路径。

exception Interrupted

基类: KeyboardInterrupt

表示测试运行被中断。

exception Failed

基类: Exception

表示测试运行失败而停止。

property startpath: Path

调用 pytest 的路径。

在 7.0.0 版本中添加。

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

路径是初始路径吗?

初始路径是命令行上显式提供给 pytest 的路径。

参数:

with_parents (bool) – 如果设置,如果路径是初始路径的父级,也返回 True。

在 8.0 版本中更改: 添加了 with_parents 参数。

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]

为此会话执行收集阶段。

这由默认的 pytest_collection 钩子实现调用;有关更多详细信息,请参阅此钩子的文档。出于测试目的,它也可以直接在新的 Session 上调用。

此函数通常递归地将从会话收集的任何收集器扩展到其项,并且只返回项。出于测试目的,这可以通过传递 genitems=False 来抑制,在这种情况下,返回值包含这些未扩展的收集器,并且 session.items 为空。

for ... in collect()[source]

为此收集器收集子级(项和收集器)。

config: Config

pytest 配置对象。

name: str

在父节点范围内唯一的名称。

parent

父收集器节点。

path: pathlib.Path

此节点从中收集的文件系统路径(可以为 None)。

session: Session

此节点所属的 pytest 会话。

class Package[source]

基类: Directory

Python 包中文件和目录的收集器——包含 __init__.py 文件的目录。

注意

不包含 __init__.py 文件的目录默认由 Dir 收集。两者都是 Directory 收集器。

在 8.0 版本中更改: 现在继承自 Directory

for ... in collect()[source]

为此收集器收集子级(项和收集器)。

config: Config

pytest 配置对象。

name: str

在父节点范围内唯一的名称。

parent

父收集器节点。

path: pathlib.Path

此节点从中收集的文件系统路径(可以为 None)。

session: Session

此节点所属的 pytest 会话。

模块

class Module[source]

基类: File, PyCollector

Python 模块中测试类和函数的收集器。

collect()[source]

为此收集器收集子级(项和收集器)。

config: Config

pytest 配置对象。

name: str

在父节点范围内唯一的名称。

parent

父收集器节点。

path: pathlib.Path

此节点从中收集的文件系统路径(可以为 None)。

session: Session

此节点所属的 pytest 会话。

class Class[source]

基类: PyCollector

Python 类中测试方法(和嵌套类)的收集器。

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

公共构造函数。

collect()[source]

为此收集器收集子级(项和收集器)。

config: Config

pytest 配置对象。

name: str

在父节点范围内唯一的名称。

parent

父收集器节点。

path: pathlib.Path

此节点从中收集的文件系统路径(可以为 None)。

session: Session

此节点所属的 pytest 会话。

函数

class Function[source]

基类: PyobjMixin, Item

负责设置和执行 Python 测试函数的项。

参数:
  • name – 完整的函数名称,包括由参数化添加的任何修饰(例如 my_func[my_param])。

  • parent – 父节点。

  • config – pytest Config 对象。

  • callspec – 如果给定,此函数已参数化,并且 callspec 包含有关参数化的元信息。

  • callobj – 如果给定,当调用 Function 时将调用的对象,否则将使用 originalnameparent 获取 callobj。

  • keywords – 绑定到函数对象以进行“-k”匹配的关键字。

  • session – pytest Session 对象。

  • fixtureinfo – 此夹具节点已解析的夹具信息。

  • originalname – 用于访问底层函数对象的属性名称。默认为 name。如果名称与原始名称不同,请设置此项,例如当它包含由参数化添加的修饰时(my_func[my_param])。

originalname

原始函数名称,不带任何修饰(例如参数化会在函数名称后添加 "[...]" 后缀),用于从 parent 访问底层函数对象(如果未明确给定 callobj)。

版本 3.0 中添加。

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

公共构造函数。

property function

底层 Python“函数”对象。

property instance

函数绑定到的 Python 实例对象。

如果不是测试方法(例如独立的测试函数、类或模块),则返回 None。

runtest()[source]

执行底层测试函数。

repr_failure(excinfo)[source]

返回收集或测试失败的表示。

参数:

excinfo (ExceptionInfo[BaseException]) – 失败的异常信息。

config: Config

pytest 配置对象。

name: str

在父节点范围内唯一的名称。

parent

父收集器节点。

path: pathlib.Path

此节点从中收集的文件系统路径(可以为 None)。

session: Session

此节点所属的 pytest 会话。

函数定义

class FunctionDefinition[source]

基类: Function

此类是一个临时解决方案,直到我们演进到拥有实际的函数定义节点并设法摆脱 metafunc

runtest()[source]

执行底层测试函数。

config: Config

pytest 配置对象。

name: str

在父节点范围内唯一的名称。

parent

父收集器节点。

path: pathlib.Path

此节点从中收集的文件系统路径(可以为 None)。

session: Session

此节点所属的 pytest 会话。

setup()

执行底层测试函数。

对象

可从 夹具钩子 访问或从 pytest 导入的对象。

调用信息

final class CallInfo[source]

函数调用的结果/异常信息。

excinfo: ExceptionInfo[BaseException] | None

如果调用引发异常,则为捕获的异常。

start: float

调用开始时的系统时间,以纪元秒为单位。

stop: float

调用结束时的系统时间,以纪元秒为单位。

duration: float

调用持续时间,以秒为单位。

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

调用的上下文:“collect”、“setup”、“call”或“teardown”。

property result: TResult

如果调用未引发异常,则为调用的返回值。

仅当 excinfo 为 None 时才能访问。

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

调用 func,将结果包装在 CallInfo 中。

参数:
  • func (Callable[[], _pytest.runner.TResult]) – 要调用的函数。不带参数调用。

  • when (Literal['collect', 'setup', 'call', 'teardown']) – 调用函数的阶段。

  • reraise (type[BaseException] | tuple[type[BaseException], ...] | None) – 如果函数引发异常,则应传播的异常,而不是将其包装在 CallInfo 中。

收集报告

final class CollectReport[source]

基类: BaseReport

收集报告对象。

报告可以包含任意的额外属性。

nodeid: str

规范化的收集节点 ID。

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

测试结果,始终为“passed”、“failed”或“skipped”之一。

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

无或失败表示。

result

收集到的项和收集节点。

sections: list[tuple[str, str]]

字符串元组 (heading, content),包含用于测试报告的额外信息。pytest 用它来添加从 stdoutstderr 捕获的文本和截获的日志事件。其他插件也可以用它来向报告添加任意信息。

property caplog: str

如果启用日志捕获,则返回捕获的日志行。

版本 3.5 中添加。

property capstderr: str

如果启用捕获,则返回从 stderr 捕获的文本。

版本 3.0 中添加。

property capstdout: str

如果启用捕获,则返回从 stdout 捕获的文本。

版本 3.0 中添加。

property count_towards_summary: bool

实验性 此报告是否应计入测试会话结束时显示的总数:“1 passed, 1 failure, etc”。

注意

此函数被认为是实验性的,因此请注意,即使在补丁版本中也可能会更改。

property failed: bool

结果是否为失败。

property fspath: str

报告节点的路径部分,作为字符串。

property head_line: str | None

实验性 此报告的 longrepr 输出显示的首行,在失败时更常见于追溯表示中。

________ Test.foo ________

在上面的示例中,head_line 是“Test.foo”。

注意

此函数被认为是实验性的,因此请注意,即使在补丁版本中也可能会更改。

property longreprtext: str

只读属性,返回 longrepr 的完整字符串表示形式。

版本 3.0 中添加。

property passed: bool

结果是否为通过。

property skipped: bool

结果是否为跳过。

配置

final class Config[source]

访问配置值、插件管理器和插件钩子。

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

保存 pytest.main() 期间传递的参数。

对象属性是只读的。

版本 5.1 中添加。

注意

请注意,环境变量 PYTEST_ADDOPTSaddopts 配置选项由 pytest 处理,不包含在 args 属性中。

访问 InvocationParams 的插件必须意识到这一点。

args: tuple[str, ...]

传递给 pytest.main() 的命令行参数。

plugins: Sequence[str | object] | None

额外插件,可能为 None

dir: Path

调用 pytest.main() 的目录。

class ArgsSource(*values)[source]

指示测试参数的来源。

版本 7.2 中添加。

ARGS = 1

命令行参数。

INVOCATION_DIR = 2

调用目录。

TESTPATHS = 3

“testpaths”配置值。

option

以属性形式访问命令行选项。

类型:

argparse.Namespace

invocation_params

调用 pytest 的参数。

类型:

InvocationParams

pluginmanager

插件管理器处理插件注册和钩子调用。

类型:

PytestPluginManager

stash

插件可以在配置中存储信息以供自己使用的地方。

类型:

Stash

property rootpath: Path

根目录 的路径。

版本 6.1 中添加。

property inipath: Path | None

配置文件 的路径。

版本 6.1 中添加。

add_cleanup(func)[source]

添加一个函数,当 config 对象不再使用时(通常与 pytest_unconfigure 同时发生)调用该函数。

classmethod fromdictargs(option_dict, args)[source]

可用于子进程的构造函数。

issue_config_time_warning(warning, stacklevel)[source]

在“配置”阶段发出并处理警告。

pytest_configure 期间,我们无法使用 catch_warnings_for_item 函数捕获警告,因为不可能在 pytest_configure 周围设置钩子包装器。

此函数主要用于需要在 pytest_configure (或类似阶段)期间发出警告的插件。

参数:
  • warning (Warning) – 警告实例。

  • stacklevel (int) – 转发到 warnings.warn 的堆栈级别。

addinivalue_line(name, line)[source]

向配置选项添加一行。该选项必须已声明,但可能尚未设置,在这种情况下,该行将成为其值的首行。

getini(name)[source]

返回 配置文件 的配置值。

如果配置文件中未定义配置值,则返回通过 parser.addini 注册配置时提供的 default 值。请注意,您可以提供 None 作为有效默认值。

如果通过 parser.addini 注册时未提供 default,则将返回基于传递给 parser.addinitype 参数的默认值。基于 type 的默认值如下: pathspathlistargslinelist:空列表 [] boolFalse string:空字符串 "" int0 float0.0

如果通过 parser.addini 注册配置时既未传递 default 也未传递 type 参数,则该配置被视为字符串,并返回默认空字符串 ''。

如果指定的名称尚未通过先前的 parser.addini 调用(通常来自插件)注册,则会引发 ValueError。

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

返回命令行选项值。

参数:
  • name (str) – 选项的名称。您也可以指定字面量的 --OPT 选项,而不是“dest”选项名称。

  • default (Any) – 如果没有通过 pytest_addoption 声明该名称的选项,则为备用值。请注意,即使选项的值为 None,当选项被声明时,此参数也将被忽略。

  • skip (bool) – 如果为 True,则如果选项未声明或值为 None,则引发 pytest.skip()。请注意,即使为 True,如果指定了默认值,也将返回默认值而不是跳过。

getvalue(name, path=None)[source]

已弃用,请改用 getoption()。

getvalueorskip(name, path=None)[source]

已弃用,请改用 getoption(skip=True)。

VERBOSITY_ASSERTIONS: Final = 'assertions'

失败断言的详细程度类型(请参阅 verbosity_assertions)。

VERBOSITY_TEST_CASES: Final = 'test_cases'

测试用例执行的详细程度类型(请参阅 verbosity_test_cases)。

VERBOSITY_SUBTESTS: Final = 'subtests'

失败子测试的详细程度类型(请参阅 verbosity_subtests)。

get_verbosity(verbosity_type=None)[source]

检索细粒度详细程度类型的详细程度级别。

参数:

verbosity_type (str | None) – 要获取级别的详细程度类型。如果为给定类型配置了级别,则返回该值。如果给定类型不是已知详细程度类型,则返回全局详细程度级别。如果给定类型为 None(默认),则返回全局详细程度级别。

要为细粒度详细程度类型配置级别,配置文件应包含配置名称的设置和详细程度级别的数值。特殊值“auto”可用于显式使用全局详细程度级别。

示例

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

目录

final class Dir[source]

文件系统目录中文件的收集器。

版本 8.0 中添加。

注意

默认情况下,带有 __init__.py 文件的 Python 目录由 Package 收集。两者都是 Directory 收集器。

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

公共构造函数。

参数:
for ... in collect()[source]

为此收集器收集子级(项和收集器)。

config: Config

pytest 配置对象。

name: str

在父节点范围内唯一的名称。

parent

父收集器节点。

path: pathlib.Path

此节点从中收集的文件系统路径(可以为 None)。

session: Session

此节点所属的 pytest 会话。

目录

class Directory[source]

从目录收集文件的基类。

一个基本的目录收集器执行以下操作:遍历目录中的文件和子目录,并通过调用钩子 pytest_collect_directorypytest_collect_file 为它们创建收集器,在此之前检查它们是否未被 pytest_ignore_collect 忽略。

默认的目录收集器是 DirPackage

版本 8.0 中添加。

使用自定义目录收集器.

config: Config

pytest 配置对象。

name: str

在父节点范围内唯一的名称。

parent

父收集器节点。

path: pathlib.Path

此节点从中收集的文件系统路径(可以为 None)。

session: Session

此节点所属的 pytest 会话。

异常信息

final class ExceptionInfo[source]

包装 sys.exc_info() 对象并提供导航回溯的帮助。

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

返回现有异常的 ExceptionInfo。

异常必须具有非 None__traceback__ 属性,否则此函数将因断言错误而失败。这意味着异常必须已引发,或者已使用 with_traceback() 方法添加了回溯。

参数:

exprinfo (str | None) – 一个文本字符串,用于帮助确定我们是否应该从输出中删除 AssertionError。默认为异常消息/__str__()

版本 7.4 中添加。

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

from_exception() 类似,但使用旧式 exc_info 元组。

classmethod from_current(exprinfo=None)[source]

返回与当前回溯匹配的 ExceptionInfo。

警告

实验性 API

参数:

exprinfo (str | None) – 一个文本字符串,用于帮助确定我们是否应该从输出中删除 AssertionError。默认为异常消息/__str__()

classmethod for_later()[source]

返回一个未填充的 ExceptionInfo。

fill_unfilled(exc_info)[source]

使用 for_later() 填充未填充的 ExceptionInfo。

property type: type[E]

异常类。

property value: E

异常值。

property tb: TracebackType

异常原始回溯。

property typename: str

异常的类型名称。

property traceback: Traceback

回溯。

exconly(tryshort=False)[source]

将异常作为字符串返回。

当 'tryshort' 解析为 True,且异常为 AssertionError 时,仅返回异常表示的实际异常部分(即从开头移除 'AssertionError: ')。

errisinstance(exc)[source]

如果异常是 exc 的实例,则返回 True。

请考虑改用 isinstance(excinfo.value, exc)

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

返回此异常信息的字符串表示形式。

参数:
  • showlocals (bool) – 在每个追溯条目中显示局部变量。如果 style=="native",则忽略。

  • style (str) – long|short|line|no|native|value 追溯风格。

  • abspath (bool) – 路径是否应更改为绝对路径或保持不变。

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

    追溯条目的过滤器。

    • 如果为假,则不隐藏任何条目。

    • 如果为真,则隐藏内部条目和包含局部变量 __tracebackhide__ = True 的条目。

    • 如果是一个可调用对象,则将过滤委托给该可调用对象。

    如果 style"native",则忽略。

  • funcargs (bool) – 在每个追溯条目中显示夹具(出于历史原因称为“funcargs”)。

  • truncate_locals (bool) – 当 showlocals==True 时,确保局部变量可以安全地表示为字符串。

  • truncate_args (bool) – 当 showargs==True 时,确保参数可以安全地表示为字符串。

  • chain (bool) – 是否显示 Python 3 中的链式异常。

版本 3.9 中的变化: 添加了 chain 参数。

match(regexp)[source]

使用 re.search() 检查正则表达式 regexp 是否与异常的字符串表示匹配。

如果匹配,则返回 True,否则会引发 AssertionError

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

检查捕获的异常组是否包含匹配的异常。

参数:
  • expected_exception (Type[BaseException] | Tuple[Type[BaseException]]) – 期望的异常类型,如果期望多种可能的异常类型之一,则为元组。

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

    如果指定,则为包含正则表达式的字符串或正则表达式对象,该正则表达式将针对异常及其 PEP-678 <https://peps.pythonlang.cn/pep-0678/> __notes__ 的字符串表示形式使用 re.search() 进行测试。

    为了匹配可能包含 特殊字符 的字面字符串,模式可以先用 re.escape() 进行转义。

  • depth (Optional[int]) – 如果为 None,将在任何嵌套深度搜索匹配的异常。如果 >= 1,则仅当异常位于指定深度时才匹配(深度 = 1 表示顶层异常组中包含的异常)。

版本 8.0 中添加。

警告

这个辅助函数可以很容易地检查特定异常的存在,但对于检查组中是否 包含 任何其他异常 则非常不利。您应该考虑使用 pytest.RaisesGroup

ExitCode

class ExitCode(*values)

编码 pytest 的有效退出代码。

目前用户和插件也可以提供其他退出代码。

在 5.0 版本中添加。

FixtureDef

class FixtureDef[source]

基类: Generic[FixtureValue]

夹具定义的容器。

注意: 目前,只有明确文档化的字段和方法被认为是公共稳定 API。

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

作用域字符串,可以是“function”、“class”、“module”、“package”、“session”之一。

execute(request)[source]

返回此夹具的值,如果未缓存则执行它。

MarkDecorator

class MarkDecorator[source]

用于在测试函数和类上应用标记的装饰器。

MarkDecorators 使用 pytest.mark 创建

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

然后可以作为装饰器应用于测试函数。

@mark2
def test_function():
    pass

当调用 MarkDecorator 时,它执行以下操作:

  1. 如果仅以单个类作为其唯一的定位参数且没有额外的关键字参数进行调用,它会将标记附加到该类,以便自动应用于在该类中找到的所有测试用例。

  2. 如果仅以单个函数作为其唯一的定位参数且没有额外的关键字参数进行调用,它会将标记附加到该函数,其中包含已存储在 MarkDecorator 内部的所有参数。

  3. 在任何其他情况下进行调用时,它返回一个新的 MarkDecorator 实例,其中原始 MarkDecorator 的内容已使用传递给此调用的参数进行更新。

注意: 上述规则阻止了 MarkDecorator 仅存储单个函数或类引用作为其定位参数,而没有额外的关键字或定位参数。您可以通过使用 with_args() 来解决此问题。

property name: str

mark.name 的别名。

property args: tuple[Any, ...]

mark.args 的别名。

property kwargs: Mapping[str, Any]

mark.kwargs 的别名。

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

返回一个添加了额外参数的 MarkDecorator。

与调用 MarkDecorator 不同,即使唯一的参数是可调用对象/类,也可以使用 with_args()。

MarkGenerator

final class MarkGenerator[source]

用于 MarkDecorator 对象的工厂——作为 pytest.mark 单例实例公开。

示例

import pytest


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

test_function 上应用一个“slowtest” Mark

Mark

final class Mark[source]

一个 pytest 标记。

name: str

标记的名称。

args: tuple[Any, ...]

标记装饰器的位置参数。

kwargs: Mapping[str, Any]

标记装饰器的关键字参数。

combined_with(other)[source]

返回一个新的 Mark,它是此 Mark 和另一个 Mark 的组合。

通过附加 args 和合并 kwargs 进行组合。

参数:

other (Mark) – 要组合的标记。

返回类型:

Mark

Metafunc

final class Metafunc[source]

传递给 pytest_generate_tests 钩子的对象。

它们有助于检查测试函数并根据测试配置或在定义测试函数的类或模块中指定的值生成测试。

definition

访问底层 _pytest.python.FunctionDefinition

config

访问测试会话的 pytest.Config 对象。

module

定义测试函数的模块对象。

function

底层的 Python 测试函数。

fixturenames

测试函数所需的夹具名称集合。

cls

定义测试函数的类对象,如果没有则为 None

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

使用给定 argnames 的 argvalues 列表向底层测试函数添加新的调用。参数化在收集阶段执行。如果您需要设置昂贵的资源,请考虑设置 indirect 以在测试设置时而不是收集时执行。

每个测试函数可以多次调用(但仅限于不同的参数名称),在这种情况下,每次调用都会参数化所有先前的参数化,例如:

unparametrized:         t
parametrize ["x", "y"]: t[x], t[y]
parametrize [1, 2]:     t[x-1], t[x-2], t[y-1], t[y-2]
参数:
  • argnames (str | Sequence[str]) – 一个逗号分隔的字符串,表示一个或多个参数名称,或一个参数字符串列表/元组。

  • argvalues (Iterable[ParameterSet | Sequence[object] | object]) –

    argvalues 列表决定了测试以不同的参数值调用的频率。

    如果只指定了一个 argname,则 argvalues 是值的列表。如果指定了 N 个 argname,则 argvalues 必须是 N 元组的列表,其中每个元组元素指定其相应 argname 的值。

  • indirect (bool | Sequence[str]) – 参数名称列表(argnames 的子集)或布尔值。如果为 True,则列表包含 argnames 中的所有名称。与此列表中的 argname 对应的每个 argvalue 都将作为 request.param 传递给其各自的 argname 夹具函数,以便在测试的设置阶段而不是收集时执行更昂贵的设置。

  • ids (Iterable[object | None] | Callable[[Any], object | None] | None) –

    argvalues 的 ID 序列(或生成器),或返回每个 argvalue 部分 ID 的可调用对象。

    对于序列(以及像 itertools.count() 这样的生成器),返回的 ID 应为 stringintfloatboolNone 类型。它们映射到 argvalues 中的相应索引。None 表示使用自动生成的 ID。

    8.4 版本新增: pytest.HIDDEN_PARAM 表示从测试名称中隐藏参数集。最多只能使用一次,因为测试名称需要唯一。

    如果它是一个可调用对象,它将为 argvalues 中的每个条目调用,并且返回值将用作整个集合的自动生成 ID 的一部分(其中各部分用破折号(“-”)连接)。这对于为某些项(例如日期)提供更具体的 ID 非常有用。返回 None 将使用自动生成的 ID。

    如果没有提供 ID,将从 argvalues 自动生成。

  • scope (Literal['session', 'package', 'module', 'class', 'function'] | None) – 如果指定,它表示参数的范围。该范围用于按参数实例对测试进行分组。它还将覆盖任何夹具函数定义的范围,允许使用测试上下文或配置设置动态范围。

Parser

final class Parser[source]

命令行参数和配置文件值的解析器。

变量:

extra_info – 通用参数 -> 值字典,用于在处理命令行参数出错时显示。

getgroup(name, description='', after=None)[source]

获取(或创建)一个命名选项组。

参数:
  • name (str) – 选项组的名称。

  • description (str) – --help 输出的详细描述。

  • after (str | None) – 另一个组的名称,用于排序 --help 输出。

返回:

选项组。

返回类型:

OptionGroup

返回的组对象有一个 addoption 方法,其签名与 parser.addoption 相同,但会在 pytest --help 的输出中显示在各自的组中。

addoption(*opts, **attrs)[source]

注册命令行选项。

参数:
  • opts (str) – 选项名称,可以是短选项或长选项。

  • attrs (Any) – 与 argparse 库的 add_argument() 函数接受的属性相同。

命令行解析后,可以通过 config.option.NAME 在 pytest 配置对象上访问选项,其中 NAME 通常通过传递 dest 属性来设置,例如 addoption("--long", dest="NAME", ...)

parse_known_args(args, namespace=None)[source]

此时解析已知参数。

返回:

一个 argparse 命名空间对象。

返回类型:

Namespace

parse_known_and_unknown_args(args, namespace=None)[source]

此时解析已知参数,并返回剩余的未知标志参数。

返回:

一个元组,包含已知参数的 argparse 命名空间对象和未知标志参数列表。

返回类型:

tuple[Namespace, list[str]]

addini(name, help, type=None, default=<notset>, *, aliases=())[source]

注册配置文件选项。

参数:
  • name (str) – 配置的名称。

  • type (Literal['string', 'paths', 'pathlist', 'args', 'linelist', 'bool', 'int', 'float'] | None) –

    配置的类型。可以是

    • string: 字符串

    • bool: 布尔值

    • args: 字符串列表,以 shell 中的方式分隔

    • linelist: 字符串列表,以换行符分隔

    • paths: pathlib.Path 列表,以 shell 中的方式分隔

    • pathlist: py.path 列表,以 shell 中的方式分隔

    • int: 整数

    • float: 浮点数

    版本 8.4 新增: floatint 类型。

    对于 pathspathlist 类型,它们被认为是相对于配置文件的。如果在没有定义配置文件的情况下执行,它们将被认为是相对于当前工作目录的(例如使用 --override-ini)。

    版本 7.0 新增: paths 变量类型。

    版本 8.1 新增: 在没有配置文件的情况下,使用当前工作目录来解析 pathspathlist

    如果为 None 或未传递,则默认为 string

  • default (Any) – 如果不存在配置文件选项但被查询时的默认值。

  • aliases (Sequence[str]) –

    此选项可以通过其他名称引用。别名解析为规范名称。

    版本 9.0 新增: aliases 参数。

配置键的值可以通过调用 config.getini(name) 来检索。

OptionGroup

class OptionGroup[source]

在自己的部分中显示的一组选项。

addoption(*opts, **attrs)[source]

向此组添加一个选项。

如果指定了长选项的缩短版本,它将在帮助中被抑制。addoption('--twowords', '--two-words') 导致帮助仅显示 --two-words,但 --twowords 被接受 并且 自动目的地在 args.twowords 中。

参数:
  • opts (str) – 选项名称,可以是短选项或长选项。

  • attrs (Any) – 与 argparse 库的 add_argument() 函数接受的属性相同。

PytestPluginManager

final class PytestPluginManager[source]

基类: PluginManager

一个 pluggy.PluginManager,具有额外的 pytest 特定功能

  • 从命令行、PYTEST_PLUGINS 环境变量和加载的插件中发现的 pytest_plugins 全局变量加载插件。

  • 启动期间加载 conftest.py

register(plugin, name=None)[source]

注册插件并返回其名称。

参数:

name (str | None) – 注册插件的名称。如果未指定,将使用 get_canonical_name() 生成名称。

返回:

插件名称。如果该名称被阻止注册,则返回 None

返回类型:

str | None

如果插件已注册,则引发 ValueError

getplugin(name)[source]
hasplugin(name)[source]

返回是否注册了具有给定名称的插件。

import_plugin(modname, consider_entry_points=False)[source]

使用 modname 导入插件。

如果 consider_entry_points 为 True,则入口点名称也会被考虑以查找插件。

add_hookcall_monitoring(before, after)

为所有钩子添加 before/after 跟踪函数。

返回一个撤销函数,调用它会删除添加的跟踪器。

before(hook_name, hook_impls, kwargs) 将在所有钩子调用之前被调用,并接收一个 hookcaller 实例、一个 HookImpl 实例列表和钩子调用的关键字参数。

after(outcome, hook_name, hook_impls, kwargs) 接收与 before 相同的参数,但还接收一个 Result 对象,该对象表示整个钩子调用的结果。

add_hookspecs(module_or_class)

添加在给定 module_or_class 中定义的新钩子规范。

如果函数已被匹配的 HookspecMarker 装饰,则将其识别为钩子规范。

check_pending()

验证所有尚未根据钩子规范验证的钩子都是可选的,否则引发 PluginValidationError

enable_tracing()

启用钩子调用的跟踪。

返回一个撤销函数,调用它会删除添加的跟踪。

get_canonical_name(plugin)

返回插件对象的规范名称。

请注意,插件可能在 register(plugin, name) 的调用者指定的不同名称下注册。要获取已注册插件的名称,请改用 get_name(plugin)

get_hookcallers(plugin)

获取指定插件的所有钩子调用器。

返回:

钩子调用器,如果 plugin 未在此插件管理器中注册,则为 None

返回类型:

list[HookCaller] | None

get_name(plugin)

返回插件注册的名称,如果未注册则返回 None

get_plugin(name)

返回在给定名称下注册的插件(如果有)。

get_plugins()

返回所有已注册插件对象的集合。

has_plugin(name)

返回是否注册了具有给定名称的插件。

is_blocked(name)

返回给定的插件名称是否被阻止。

is_registered(plugin)

返回插件是否已注册。

list_name_plugin()

返回所有已注册插件的 (名称, 插件) 对列表。

list_plugin_distinfo()

返回所有 setuptools 注册插件的 (插件, distinfo) 对列表。

load_setuptools_entrypoints(group, name=None)

通过查询指定的 setuptools group 加载模块。

参数:
  • group (str) – 加载插件的入口点组。

  • name (str | None) – 如果给定,则仅加载具有给定 name 的插件。

返回:

此调用加载的插件数量。

返回类型:

int

set_blocked(name)

阻止给定名称的注册,如果已注册则注销。

subset_hook_caller(name, remove_plugins)

返回命名方法的代理 HookCaller 实例,该实例管理对所有已注册插件(除了 remove_plugins 中的插件)的调用。

unblock(name)

取消阻止名称。

返回名称是否确实被阻止。

unregister(plugin=None, name=None)

注销插件及其所有钩子实现。

插件可以通过插件对象或插件名称指定。如果两者都指定,它们必须一致。

返回未注册的插件,如果未找到则返回 None

project_name: Final

项目名称。

hook: Final

“钩子中继”,用于调用所有已注册插件上的钩子。请参阅 Calling hooks

trace: Final[_tracing.TagTracerSub]

跟踪入口点。请参阅 Built-in tracing

RaisesExc

final class RaisesExc[source]

8.4 版本新增。

这是调用 pytest.raises() 时构造的类,但当您想要指定子异常的要求时,可以将其直接用作 RaisesGroup 的辅助类。

如果您只想指定类型,则不需要此项,因为 RaisesGroup 接受 type[BaseException]

参数:
  • expected_exception (type[BaseException] | tuple[type[BaseException]] | None) –

    预期的类型,或几种可能的类型之一。可以为 None,以便仅使用 match 和/或 check

    类型使用 isinstance() 检查,不需要精确匹配。如果需要精确匹配,可以使用 check 参数。

  • match (str | Pattern[str]) – 要匹配的正则表达式。

  • check (Callable[[BaseException], bool]) – 如果指定,一个可调用对象,它将在检查类型和匹配的正则表达式后(如果指定)以异常作为参数被调用。如果它返回 True,则被认为是匹配成功;否则,被认为是匹配失败。

RaisesExc.matches() 也可以单独使用来检查单个异常。

示例

with RaisesGroup(RaisesExc(ValueError, match="string"))
    ...
with RaisesGroup(RaisesExc(check=lambda x: x.args == (3, "hello"))):
    ...
with RaisesGroup(RaisesExc(check=lambda x: type(x) is ValueError)):
    ...
fail_reason

在调用 matches() 后设置,以提供匹配失败的可读原因。当用作上下文管理器时,该字符串将作为测试失败的原因打印。

matches(exception)[source]

检查异常是否符合此 RaisesExc 的要求。如果失败,将设置 RaisesExc.fail_reason

示例

assert RaisesExc(ValueError).matches(my_exception):
# is equivalent to
assert isinstance(my_exception, ValueError)

# this can be useful when checking e.g. the ``__cause__`` of an exception.
with pytest.raises(ValueError) as excinfo:
    ...
assert RaisesExc(SyntaxError, match="foo").matches(excinfo.value.__cause__)
# above line is equivalent to
assert isinstance(excinfo.value.__cause__, SyntaxError)
assert re.search("foo", str(excinfo.value.__cause__)

RaisesGroup

教程: 关于预期异常组的断言

final class RaisesGroup[source]

8.4 版本新增。

用于检查预期 ExceptionGroup 的上下文管理器。这类似于 pytest.raises(),但允许指定 ExceptionGroup 的结构。ExceptionInfo.group_contains() 也尝试处理异常组,但它在检查您 没有 获得意外异常方面非常糟糕。

捕获行为与 except* 不同,默认情况下对结构更严格。通过使用 allow_unwrapped=Trueflatten_subgroups=True,您可以在预期单个异常时完全匹配 except*

参数:
  • args

    任意数量的异常类型,RaisesGroupRaisesExc,用于指定此异常中包含的异常。所有指定的异常都必须存在于引发的组中,且不能有其他异常

    如果您期望可变数量的异常,您需要使用 pytest.raises(ExceptionGroup) 并手动检查包含的异常。考虑使用 RaisesExc.matches()

    它不关心异常的顺序,因此 RaisesGroup(ValueError, TypeError) 等同于 RaisesGroup(TypeError, ValueError)

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

    如果指定,则为包含正则表达式的字符串或正则表达式对象,该正则表达式将针对异常组及其 PEP 678 __notes__ 的字符串表示形式使用 re.search() 进行测试。

    为了匹配可能包含 特殊字符 的字面字符串,模式可以先用 re.escape() 进行转义。

    请注意,在匹配之前,将从 repr 中删除“ (5 subgroups)”。

  • check (Callable[[E], bool]) – 如果指定,一个可调用对象,它将在成功匹配预期异常后以组作为参数被调用。如果它返回 True,则被认为是匹配成功;否则,被认为是匹配失败。

  • allow_unwrapped (bool) –

    如果期望单个异常或 RaisesExc,即使异常不在异常组内,它也会匹配。

    将此与 matchcheck 或期望多个异常一起使用将引发错误。

  • flatten_subgroups (bool) – 在匹配之前,“展平”引发的异常组中的任何组,提取任何嵌套组中的所有异常。如果没有此选项,它会要求您通过传递 RaisesGroup 作为预期参数来完全指定嵌套结构。

示例

with RaisesGroup(ValueError):
    raise ExceptionGroup("", (ValueError(),))
# match
with RaisesGroup(
    ValueError,
    ValueError,
    RaisesExc(TypeError, match="^expected int$"),
    match="^my group$",
):
    raise ExceptionGroup(
        "my group",
        [
            ValueError(),
            TypeError("expected int"),
            ValueError(),
        ],
    )
# check
with RaisesGroup(
    KeyboardInterrupt,
    match="^hello$",
    check=lambda x: isinstance(x.__cause__, ValueError),
):
    raise BaseExceptionGroup("hello", [KeyboardInterrupt()]) from ValueError
# nested groups
with RaisesGroup(RaisesGroup(ValueError)):
    raise ExceptionGroup("", (ExceptionGroup("", (ValueError(),)),))

# flatten_subgroups
with RaisesGroup(ValueError, flatten_subgroups=True):
    raise ExceptionGroup("", (ExceptionGroup("", (ValueError(),)),))

# allow_unwrapped
with RaisesGroup(ValueError, allow_unwrapped=True):
    raise ValueError

RaisesGroup.matches() 也可以直接用于检查独立的异常组。

匹配算法是贪婪的,这意味着以下情况可能会失败:

with RaisesGroup(ValueError, RaisesExc(ValueError, match="hello")):
    raise ExceptionGroup("", (ValueError("hello"), ValueError("goodbye")))

尽管它通常不关心组中异常的顺序。为了避免上述情况,您应该使用 RaisesExc 指定第一个 ValueError

注意

当引发的异常与预期的异常不匹配时,您将收到详细的错误消息,解释原因。这包括 repr(check)(如果已设置),这在 Python 中可能过于冗长,显示内存位置等等。

如果安装并导入(例如在 conftest.py 中),hypothesis 库将对这个输出进行猴子补丁,以提供更短、更可读的 repr。

fail_reason

在调用 matches() 后设置,以提供匹配失败的可读原因。当用作上下文管理器时,该字符串将作为测试失败的原因打印。

matches(exception: BaseException | None) TypeGuard[ExceptionGroup[ExcT_1]][source]
matches(exception: BaseException | None) TypeGuard[BaseExceptionGroup[BaseExcT_1]]

检查异常是否符合此 RaisesGroup 的要求。如果失败,将设置 RaisesGroup.fail_reason

示例

with pytest.raises(TypeError) as excinfo:
    ...
assert RaisesGroup(ValueError).matches(excinfo.value.__cause__)
# the above line is equivalent to
myexc = excinfo.value.__cause
assert isinstance(myexc, BaseExceptionGroup)
assert len(myexc.exceptions) == 1
assert isinstance(myexc.exceptions[0], ValueError)

TerminalReporter

final class TerminalReporter(config, file=None)[source]
wrap_write(content, *, flush=False, margin=8, line_sep='\n', **markup)[source]

用边距包装消息以显示进度信息。

rewrite(line, **markup)[source]

将终端光标倒回开头并写入给定行。

参数:

erase – 如果为 True,还将添加空格直到终端全宽,以确保正确擦除前一行。

其余的关键字参数是标记指令。

build_summary_stats_line()[source]

构建最后一行摘要统计信息中使用的部分。

摘要统计行是最后显示的行,“=== 12 passed, 2 errors in Xs===”。

此函数构建构成该行文本的“部分”列表,在上面的示例中,它将是:

[
    ("12 passed", {"green": True}),
    ("2 errors", {"red": True}
]

每行的最后一个字典是一个“标记字典”,由 TerminalWriter 用于输出着色。

行的最终颜色也由此函数确定,是返回元组的第二个元素。

TestReport

class TestReport[source]

基类: BaseReport

基本测试报告对象(如果设置和拆卸调用失败,也用于这些调用)。

报告可以包含任意的额外属性。

nodeid: str

规范化的收集节点 ID。

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

一个 (filesystempath, lineno, domaininfo) 元组,表示测试项的实际位置 - 它可能与收集到的位置不同,例如,如果方法继承自不同的模块。filesystempath 可以是相对于 config.rootdir 的。行号是基于 0 的。

keywords: Mapping[str, Any]

一个名称 -> 值字典,包含与测试调用相关联的所有关键字和标记。

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

测试结果,始终为“passed”、“failed”或“skipped”之一。

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

无或失败表示。

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

‘setup’、‘call’ 或 ‘teardown’ 之一,表示 runtest 阶段。

user_properties

用户属性是一个包含测试用户定义属性的元组列表(名称,值)。

sections: list[tuple[str, str]]

字符串元组 (heading, content),包含用于测试报告的额外信息。pytest 用它来添加从 stdoutstderr 捕获的文本和截获的日志事件。其他插件也可以用它来向报告添加任意信息。

duration: float

运行测试所花费的时间。

start: float

调用开始时的系统时间,以纪元秒为单位。

stop: float

调用结束时的系统时间,以纪元秒为单位。

classmethod from_item_and_call(item, call)[source]

使用标准项和调用信息创建并填充 TestReport。

参数:
  • item (Item) – 项。

  • call (CallInfo[None]) – 调用信息。

property caplog: str

如果启用日志捕获,则返回捕获的日志行。

版本 3.5 中添加。

property capstderr: str

如果启用捕获,则返回从 stderr 捕获的文本。

版本 3.0 中添加。

property capstdout: str

如果启用捕获,则返回从 stdout 捕获的文本。

版本 3.0 中添加。

property count_towards_summary: bool

实验性 此报告是否应计入测试会话结束时显示的总数:“1 passed, 1 failure, etc”。

注意

此函数被认为是实验性的,因此请注意,即使在补丁版本中也可能会更改。

property failed: bool

结果是否为失败。

property fspath: str

报告节点的路径部分,作为字符串。

property head_line: str | None

实验性 此报告的 longrepr 输出显示的首行,在失败时更常见于追溯表示中。

________ Test.foo ________

在上面的示例中,head_line 是“Test.foo”。

注意

此函数被认为是实验性的,因此请注意,即使在补丁版本中也可能会更改。

property longreprtext: str

只读属性,返回 longrepr 的完整字符串表示形式。

版本 3.0 中添加。

property passed: bool

结果是否为通过。

property skipped: bool

结果是否为跳过。

TestShortLogReport

class TestShortLogReport[source]

用于存储测试状态结果类别、短字母和详细单词。例如 "rerun", "R", ("RERUN", {"yellow": True})

变量:
  • category – 结果的类别,例如 “passed”“skipped”“error”,或空字符串。

  • letter – 测试进行时显示的短字母,例如 ".""s""E",或空字符串。

  • word – 在详细模式下测试进行时显示的详细单词,例如 "PASSED""SKIPPED""ERROR",或空字符串。

category: str

字段 0 的别名

letter: str

字段 1 的别名

word: str | tuple[str, Mapping[str, bool]]

字段 2 的别名

Result

hook wrappers 中使用的 Result 对象,更多信息请参阅 pluggy 文档中的 Result

Stash

class Stash[source]

Stash 是一种类型安全的异构可变映射,允许键和值类型与其创建位置(即 Stash)分开定义。

通常你会得到一个包含 Stash 的对象,例如 ConfigNode

stash: Stash = some_object.stash

如果模块或插件想将数据存储在此 Stash 中,它会为其键创建 StashKey(在模块级别)。

# At the top-level of the module
some_str_key = StashKey[str]()
some_bool_key = StashKey[bool]()

存储信息

# Value type must match the key.
stash[some_str_key] = "value"
stash[some_bool_key] = True

检索信息

# 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]

7.0 版本新增。

__setitem__(key, value)[source]

为键设置一个值。

__getitem__(key)[source]

获取键的值。

如果键之前未设置,则引发 KeyError

get(key, default)[source]

获取键的值,如果键之前未设置,则返回默认值。

setdefault(key, default)[source]

如果键已设置,则返回其值;否则,将键的值设置为 default 并返回 default。

__delitem__(key)[source]

删除键的值。

如果键之前未设置,则引发 KeyError

__contains__(key)[source]

返回键是否已设置。

__len__()[source]

返回 stash 中存在的项目数量。

class StashKey[source]

基类: Generic[T]

StashKey 是一个用作 Stash 的键的对象。

一个 StashKey 与键值的类型 T 相关联。

一个 StashKey 是唯一的,不能与另一个键冲突。

7.0 版本新增。

全局变量

pytest 在测试模块或 conftest.py 文件中定义某些全局变量时会以特殊方式处理。

collect_ignore

教程: 自定义测试收集

可在 *conftest.py 文件*中声明,以排除测试目录或模块。需要是路径列表(strpathlib.Path 或任何 os.PathLike)。

collect_ignore = ["setup.py"]
collect_ignore_glob

教程: 自定义测试收集

可在 *conftest.py 文件*中声明,以使用 Unix shell 风格的通配符排除测试目录或模块。需要是 list[str],其中 str 可以包含 glob 模式。

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

教程: 标记整个类或模块

可在 *测试模块* 的 **全局** 级别声明,以将一个或多个 标记 应用于所有测试函数和方法。可以是单个标记或标记列表(按从左到右的顺序应用)。

import pytest

pytestmark = pytest.mark.webtest
import pytest

pytestmark = [pytest.mark.integration, pytest.mark.slow]

环境变量

可用于更改 pytest 行为的环境变量。

CI

当设置为非空值时,pytest 承认其正在 CI 进程中运行。另请参阅 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_DEBUG_TEMPROOT

tmp_path 等 fixture 生成的临时目录的根,如 临时目录位置和保留 中所述。

PYTEST_DISABLE_PLUGIN_AUTOLOAD

设置后,通过 入口点打包元数据 禁用插件自动加载。只有在 PYTEST_PLUGINS 中明确指定或使用 -p 的插件才会被加载。另请参阅 –disable-plugin-autoload

PYTEST_PLUGINS

包含逗号分隔的模块列表,这些模块应作为插件加载

export PYTEST_PLUGINS=mymodule.plugin,xdist

另请参阅 -p

PYTEST_THEME

设置用于代码输出的 pygment 样式

PYTEST_THEME_MODE

PYTEST_THEME 设置为 *dark* 或 *light*。

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

异常

exception UsageError

基类: Exception

pytest 使用或调用中的错误。

final exception FixtureLookupError[source]

基类: LookupError

无法返回请求的 fixture (缺少或无效)。

警告

在某些情况下(例如不当使用或已弃用功能)生成的自定义警告。

class PytestWarning

基类: UserWarning

pytest 发出的所有警告的基类。

class PytestAssertRewriteWarning

基类: PytestWarning

pytest 断言重写模块发出的警告。

class PytestCacheWarning

基类: PytestWarning

在各种情况下由缓存插件发出的警告。

class PytestCollectionWarning

基类: PytestWarning

当 pytest 无法收集模块中的文件或符号时发出的警告。

class PytestConfigWarning

基类: PytestWarning

因配置问题而发出的警告。

class PytestDeprecationWarning

基类: PytestWarning, DeprecationWarning

未来版本中将移除的功能的警告类。

class PytestExperimentalApiWarning

基类: PytestWarning, FutureWarning

用于表示 pytest 实验的警告类别。

请谨慎使用,因为 API 可能会在未来版本中更改甚至完全移除。

class PytestReturnNotNoneWarning

基类: PytestWarning

当测试函数返回非 None 值时发出的警告。

详情请参阅 测试函数中返回非 None 值

class PytestRemovedIn9Warning

基类: PytestDeprecationWarning

pytest 9 中将移除的功能的警告类。

class PytestUnknownMarkWarning

基类: PytestWarning

使用未知标记时发出的警告。

详情请参阅 如何用属性标记测试函数

class PytestUnraisableExceptionWarning

基类: PytestWarning

报告了一个无法引发的异常。

无法引发的异常是在 __del__ 实现和类似情况下引发的异常,当异常无法正常引发时。

class PytestUnhandledThreadExceptionWarning

基类: PytestWarning

Thread 中发生了未处理的异常。

此类异常不会正常传播。

有关更多信息,请查阅文档中的 内部 pytest 警告 部分。

配置选项

以下是可写入 pytest.ini(或 .pytest.ini)、pyproject.tomltox.inisetup.cfg 文件中的内置配置选项列表,这些文件通常位于您的仓库根目录。

要详细了解每种文件格式,请参阅 配置文件格式

警告

不建议使用 setup.cfg,除非是非常简单的用例。.cfg 文件使用的解析器与 pytest.initox.ini 不同,这可能会导致难以追踪的问题。如果可能,建议使用后者文件,或 pytest.tomlpyproject.toml 来保存您的 pytest 配置。

配置选项可以通过命令行使用 -o/--override-ini 进行覆盖,该选项也可以多次传递。预期的格式是 name=value。例如:

pytest -o console_output_style=classic -o cache_dir=/tmp/mycache
addopts

将指定的 OPTS 添加到命令行参数集,就好像它们是由用户指定的一样。示例:如果您有此配置文件内容

# content of pytest.toml
[pytest]
addopts = ["--maxfail=2", "-rf"]  # exit after 2 failures, report fail info

发出 pytest test_hello.py 实际上意味着

pytest --maxfail=2 -rf test_hello.py

默认情况下不添加任何选项。

cache_dir

设置缓存插件内容存储的目录。默认目录为 .pytest_cache,它在 rootdir 中创建。目录可以是相对路径或绝对路径。如果设置相对路径,则目录相对于 rootdir 创建。此外,路径可以包含环境变量,这些变量将被扩展。有关缓存插件的更多信息,请参阅 如何在测试运行之间重新运行失败的测试并保持状态

collect_imported_tests

8.4 版本新增。

将其设置为 false 将使 pytest 收集在测试文件中定义的类/函数(而不是从其他地方导入的)。

[pytest]
collect_imported_tests = false
[pytest]
collect_imported_tests = false

默认值: true

pytest 传统上即使类/函数是从另一个文件导入的,也会在测试模块命名空间中收集它们。

例如

# contents of src/domain.py
class Testament: ...


# contents of tests/test_testament.py
from domain import Testament


def test_testament(): ...

在此场景中,使用默认选项,pytest 将从 tests/test_testament.py 中收集 Testament 类,因为它以 Test 开头,即使在这种情况下它是一个在测试模块命名空间中导入的生产类。

在配置文件中将 collected_imported_tests 设置为 false 可以防止这种情况。

consider_namespace_packages

控制 pytest 在收集 Python 模块时是否尝试识别 命名空间包。默认值为 False

如果您正在测试的包是命名空间包的一部分,请设置为 True。命名空间包也支持作为 --pyargs 目标。

只支持 原生命名空间包,没有计划支持 传统命名空间包

在 8.1 版本中添加。

console_output_style

设置运行测试时的控制台输出样式

  • classic: 经典的 pytest 输出。

  • progress: 类似于经典的 pytest 输出,但带有进度指示器。

  • progress-even-when-capture-no: 即使 capture=no,也允许使用进度指示器。

  • count: 类似于 progress,但将进度显示为已完成的测试数量,而不是百分比。

  • times: 显示测试持续时间。

默认是 progress,但如果您喜欢或新模式导致意外问题,可以回退到 classic

[pytest]
console_output_style = "classic"
[pytest]
console_output_style = classic
disable_test_id_escaping_and_forfeit_all_rights_to_community_support

4.4 版本中添加。

pytest 默认会转义用于参数化中的 unicode 字符串中的任何非 ASCII 字符,因为它有几个缺点。但是,如果您想在参数化中使用 unicode 字符串并希望它们在终端中按原样(未转义)显示,请在配置文件中使用此选项

[pytest]
disable_test_id_escaping_and_forfeit_all_rights_to_community_support = true
[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 如果 parametrize 收集到空参数集,则引发异常

[pytest]
empty_parameter_set_mark = "xfail"
[pytest]
empty_parameter_set_mark = xfail

注意

此选项的默认值计划在未来版本中更改为 xfail,因为这被认为不易出错,请参阅 #3155 了解更多详细信息。

enable_assertion_pass_hook

启用 pytest_assertion_pass 钩子。请务必删除任何以前生成的 .pyc 缓存文件。

[pytest]
enable_assertion_pass_hook = true
[pytest]
enable_assertion_pass_hook = true
faulthandler_exit_on_timeout

通过将 exit=True 传递给 faulthandler.dump_traceback_later() 函数,在达到每个测试超时后退出 pytest 进程。这对于避免测试套件(容易使主 Python 解释器陷入死锁状态)浪费 CI 资源特别有用。

此选项默认为“false”。

[pytest]
faulthandler_timeout = 5
faulthandler_exit_on_timeout = true
[pytest]
faulthandler_timeout = 5
faulthandler_exit_on_timeout = true
faulthandler_timeout

如果测试运行时间超过 X 秒(包括 fixture 设置和拆卸),则转储所有线程的回溯。使用 faulthandler.dump_traceback_later() 函数实现,因此所有注意事项均适用。

[pytest]
faulthandler_timeout = 5
[pytest]
faulthandler_timeout = 5

有关更多信息,请参阅 故障处理程序。有关更多信息,请参阅 故障处理程序

filterwarnings

设置一组过滤器和针对匹配警告应采取的操作。默认情况下,在测试会话期间发出的所有警告将在测试会话结束时显示在摘要中。

[pytest]
filterwarnings = ["error", "ignore::DeprecationWarning"]
[pytest]
filterwarnings =
    error
    ignore::DeprecationWarning

这指示 pytest 忽略弃用警告,并将所有其他警告转换为错误。有关更多信息,请参阅 如何捕获警告

junit_duration_report

4.1 版本中添加。

配置持续时间如何记录到 JUnit XML 报告中

  • total(默认值):报告的持续时间包括 setup、call 和 teardown 时间。

  • call:报告的持续时间仅包括 call 时间,不包括 setup 和 teardown。

[pytest]
junit_duration_report = "call"
[pytest]
junit_duration_report = call
junit_family

4.2 版本中添加。

6.1 版本中更改: 默认值更改为 xunit2

配置生成的 JUnit XML 文件的格式。可能的选项是

  • xunit1 (或 legacy): 生成旧式输出,与 xunit 1.0 格式兼容。

  • xunit2: 生成 xunit 2.0 样式输出,应与最新的 Jenkins 版本更兼容。 **这是默认值**。

[pytest]
junit_family = "xunit2"
[pytest]
junit_family = xunit2
junit_log_passing_tests

4.6 版本中添加。

如果 junit_logging != "no",则配置是否将捕获的输出写入 **通过** 测试的 JUnit XML 文件。默认值为 True

[pytest]
junit_log_passing_tests = false
[pytest]
junit_log_passing_tests = False
junit_logging

版本 3.5 中添加。

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"
[pytest]
junit_logging = system-out
junit_suite_name

要设置根测试套件 xml 项的名称,您可以在配置文件中配置 junit_suite_name 选项。

[pytest]
junit_suite_name = "my_suite"
[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
[pytest]
log_auto_indent = false

支持向 logging.log() 调用传递 kwarg extra={"auto_indent": [value]},以指定日志中特定条目的自动缩进行为。extra kwarg 覆盖命令行或配置中指定的值。

log_cli

在测试运行期间启用日志显示(也称为 “实时日志”)。默认值为 False

[pytest]
log_cli = true
[pytest]
log_cli = true
log_cli_date_format

设置一个与 time.strftime() 兼容的字符串,用于格式化实时日志的日期。

[pytest]
log_cli_date_format = "%Y-%m-%d %H:%M:%S"
[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"
[pytest]
log_cli_format = %(asctime)s %(levelname)s %(message)s

更多信息请参见 实时日志

log_cli_level

设置实时日志应捕获的最低日志消息级别。可以使用整数值或级别名称。

[pytest]
log_cli_level = "INFO"
[pytest]
log_cli_level = INFO

更多信息请参见 实时日志

log_date_format

设置一个与 time.strftime() 兼容的字符串,用于格式化日志捕获的日期。

[pytest]
log_date_format = "%Y-%m-%d %H:%M:%S"
[pytest]
log_date_format = %Y-%m-%d %H:%M:%S

有关更多信息,请参阅 如何管理日志记录

log_file

设置相对于当前工作目录的文件名,日志消息应写入该文件,此外还有其他活动的日志记录设施。

[pytest]
log_file = "logs/pytest-logs.txt"
[pytest]
log_file = logs/pytest-logs.txt

有关更多信息,请参阅 如何管理日志记录

log_file_date_format

设置一个与 time.strftime() 兼容的字符串,用于格式化日志文件的日期。

[pytest]
log_file_date_format = "%Y-%m-%d %H:%M:%S"
[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"
[pytest]
log_file_format = %(asctime)s %(levelname)s %(message)s

有关更多信息,请参阅 如何管理日志记录

log_file_level

设置日志文件应捕获的最低日志消息级别。可以使用整数值或级别名称。

[pytest]
log_file_level = "INFO"
[pytest]
log_file_level = INFO

有关更多信息,请参阅 如何管理日志记录

log_file_mode

设置日志文件打开模式。选项为 "w"(重新创建文件,默认值)或 "a"(追加到文件)。

[pytest]
log_file_mode = "a"
[pytest]
log_file_mode = a

有关更多信息,请参阅 如何管理日志记录

log_format

设置一个与 logging 兼容的字符串,用于格式化捕获的日志消息。

[pytest]
log_format = "%(asctime)s %(levelname)s %(message)s"
[pytest]
log_format = %(asctime)s %(levelname)s %(message)s

有关更多信息,请参阅 如何管理日志记录

log_level

设置日志捕获的最低日志消息级别。可以使用整数值或级别名称。

[pytest]
log_level = "INFO"
[pytest]
log_level = INFO

有关更多信息,请参阅 如何管理日志记录

markers

当设置 strict_markers 配置选项时,只允许使用已知的标记——由 pytest 核心或某些插件在代码中定义。

您可以在此设置中列出其他标记以将其添加到白名单,在这种情况下,您可能希望将 strict_markers 设置为 true 以避免未来的回归。

[pytest]
addopts = ["--strict-markers"]
markers = ["slow", "serial"]
[pytest]
strict_markers = true
markers =
    slow
    serial
minversion

指定运行测试所需的最小 pytest 版本。

[pytest]
minversion = 3.0  # will fail if we run with pytest-2.8
[pytest]
minversion = 3.0  # will fail if we run with pytest-2.8
norecursedirs

设置在递归进行测试发现时要避免的目录基本名称模式。单个(fnmatch 样式)模式应用于目录的基本名称,以决定是否递归进入。模式匹配字符

*       matches everything
?       matches any single character
[seq]   matches any character in seq
[!seq]  matches any char not in seq

默认模式是 '*.egg''.*''_darcs''build''CVS''dist''node_modules''venv''{arch}'。设置 norecursedirs 会替换默认值。以下是如何避免某些目录的示例

[pytest]
norecursedirs = [".svn", "_build", "tmp*"]
[pytest]
norecursedirs = .svn _build tmp*

这将告诉 pytest 不要查看典型的 subversion 或 sphinx-build 目录,也不要查看任何以 tmp 为前缀的目录。

此外,pytest 将尝试智能识别并忽略虚拟环境。任何被认为是虚拟环境根目录的目录都不会在测试收集期间考虑,除非给定 --collect-in-virtualenv。另请注意,norecursedirs 优先于 --collect-in-virtualenv;例如,如果您打算在基本目录匹配 '.*' 的虚拟环境中运行测试,您 *必须* 除了使用 --collect-in-virtualenv 标志外,还覆盖 norecursedirs

python_classes

一个或多个名称前缀或 glob 样式模式,用于确定哪些类被视为测试集合。通过在模式之间添加空格来搜索多个 glob 模式。默认情况下,pytest 将任何以 Test 为前缀的类视为测试集合。以下是如何从以 Suite 结尾的类中收集测试的示例

[pytest]
python_classes = ["*Suite"]
[pytest]
python_classes = *Suite

请注意,此选项对 unittest.TestCase 派生类上的方法没有影响,因为 unittest 自己的收集框架用于收集这些测试。

python_files

一个或多个 Glob 风格的文件模式,用于确定哪些 python 文件被视为测试模块。通过在模式之间添加空格来搜索多个 glob 模式。

[pytest]
python_files = ["test_*.py", "check_*.py", "example_*.py"]
[pytest]
python_files = test_*.py check_*.py example_*.py

或每行一个

[pytest]
python_files =
    test_*.py
    check_*.py
    example_*.py

默认情况下,匹配 test_*.py*_test.py 的文件将被视为测试模块。

python_functions

一个或多个名称前缀或 glob 模式,用于确定哪些测试函数和方法被视为测试。通过在模式之间添加空格来搜索多个 glob 模式。默认情况下,pytest 将任何以 test 为前缀的函数视为测试。以下是如何收集以 _test 结尾的测试函数和方法的示例。

[pytest]
python_functions = ["*_test"]
[pytest]
python_functions = *_test

请注意,这对 unittest.TestCase 派生类上的方法没有影响,因为 unittest 自己的收集框架用于收集这些测试。

有关更详细的示例,请参阅 更改命名约定

pythonpath

设置应添加到 python 搜索路径的目录列表。目录将添加到 sys.path 的头部。与 PYTHONPATH 环境变量类似,这些目录将包含在 Python 查找导入模块的位置。路径相对于 rootdir 目录。目录在测试会话期间保留在路径中。

[pytest]
pythonpath = ["src1", "src2"]
[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"]
[pytest]
required_plugins = pytest-django>=3.0.0,<4.0.0 pytest-html pytest-xdist>=1.0.0
strict

如果设置为 true,则启用“严格模式”,这将启用以下选项

插件还可以启用自己的严格性选项。

如果您明确设置了单个严格性选项,它将优先于 strict

注意

如果 pytest 将来添加新的严格性选项,它们也将在严格模式下启用。因此,您应该仅在使用固定/锁定版本的 pytest 时,或者如果您希望在添加新严格性选项时主动采用它们,才启用严格模式。

[pytest]
strict = true
[pytest]
strict = true

9.0 版本新增。

strict_config

如果设置为 true,则在解析配置文件 pytest 部分时遇到的任何警告都将引发错误。

[pytest]
strict_config = true
[pytest]
strict_config = true

您还可以通过 strict 选项启用此选项。

strict_markers

如果设置为 true,则未在配置文件 markers 部分注册的标记将引发错误。

[pytest]
strict_markers = true
[pytest]
strict_markers = true

您还可以通过 strict 选项启用此选项。

strict_parametrization_ids

如果设置为 true,如果 pytest 检测到非唯一参数集 ID,它将发出错误。

如果未设置(默认),pytest 会通过向重复的 ID 添加 01 等来自动处理此问题,使它们唯一。

[pytest]
strict_parametrization_ids = true
[pytest]
strict_parametrization_ids = true

您还可以通过 strict 选项启用此选项。

例如,

import pytest


@pytest.mark.parametrize("letter", ["a", "a"])
def test_letter_is_ascii(letter):
    assert letter.isascii()

将发出错误,因为这两个用例(参数集)都具有相同的自动生成的 ID “a”。

要修复此错误,如果您决定保留重复项,请明确分配唯一的 ID

import pytest


@pytest.mark.parametrize("letter", ["a", "a"], ids=["a0", "a1"])
def test_letter_is_ascii(letter):
    assert letter.isascii()

有关设置 ID 的其他方法,请参阅 parametrizepytest.param()

strict_xfail

如果设置为 true,则默认情况下,标记为 @pytest.mark.xfail 但实际成功的测试将使测试套件失败。有关详细信息,请参阅 strict 参数

[pytest]
strict_xfail = true
[pytest]
strict_xfail = true

您还可以通过 strict 选项启用此选项。

版本 9.0 中的更改: xfail_strict 重命名为 strict_xfailxfail_strict 被接受为 strict_xfail 的别名。

testpaths

设置目录列表,当在命令行中未给出特定目录、文件或测试 ID 时,在从 rootdir 目录执行 pytest 时,应在这些目录中搜索测试。文件系统路径可以使用 shell 风格的通配符,包括递归的 ** 模式。

当所有项目测试都在已知位置时,这很有用,可以加快测试收集速度,并避免意外选择不需要的测试。

[pytest]
testpaths = ["testing", "doc"]
[pytest]
testpaths = testing doc

此配置意味着执行

pytest

与执行以下命令具有相同的实际效果

pytest testing doc
tmp_path_retention_count

根据 tmp_path_retention_policy,我们应该保留多少个会话的 tmp_path 目录。

[pytest]
tmp_path_retention_count = 3
[pytest]
tmp_path_retention_count = 3

默认值: 3

tmp_path_retention_policy

控制哪些由 tmp_path fixture 创建的目录会根据测试结果保留。

  • all: 保留所有测试的目录,无论结果如何。

  • failed: 仅保留结果为 errorfailed 的测试的目录。

  • none: 无论结果如何,目录总是在每个测试结束后删除。

[pytest]
tmp_path_retention_policy = "all"
[pytest]
tmp_path_retention_policy = all

默认值: all

truncation_limit_chars

控制截断断言消息内容的最大字符数。

将值设置为 0 会禁用截断的字符限制。

[pytest]
truncation_limit_chars = 640
[pytest]
truncation_limit_chars = 640

pytest 默认将断言消息截断到一定限制,以防止与大数据进行比较时使控制台输出过载。

默认值: 640

注意

如果 pytest 检测到它正在 CI 上运行,则会自动禁用截断。

truncation_limit_lines

控制截断断言消息内容的最大行数。

将值设置为 0 会禁用截断的行限制。

[pytest]
truncation_limit_lines = 8
[pytest]
truncation_limit_lines = 8

pytest 默认将断言消息截断到一定限制,以防止与大数据进行比较时使控制台输出过载。

默认值: 8

注意

如果 pytest 检测到它正在 CI 上运行,则会自动禁用截断。

usefixtures

将应用于所有测试函数的 fixture 列表;这在语义上与将 @pytest.mark.usefixtures 标记应用于所有测试函数相同。

[pytest]
usefixtures = ["clean_db"]
[pytest]
usefixtures =
    clean_db
verbosity_assertions

专门为断言相关输出设置一个详细级别,覆盖应用程序范围的级别。

[pytest]
verbosity_assertions = "2"
[pytest]
verbosity_assertions = 2

如果未设置,则默认为应用程序范围的详细级别(通过 -v 命令行选项)。特殊值 "auto" 可用于明确使用全局详细级别。

verbosity_subtests

专门为通过的子测试设置详细级别。

[pytest]
verbosity_subtests = "1"
[pytest]
verbosity_subtests = 1

1 或更高将显示通过的子测试的输出(失败的子测试总是会被报告)。可以通过值 0 来抑制通过的子测试输出,这会覆盖 -v 命令行选项。

如果未设置,则默认为应用程序范围的详细级别(通过 -v 命令行选项)。特殊值 "auto" 可用于明确使用全局详细级别。

另请参阅: 如何使用子测试

verbosity_test_cases

专门为测试用例执行相关输出设置一个详细级别,覆盖应用程序范围的级别。

[pytest]
verbosity_test_cases = "2"
[pytest]
verbosity_test_cases = 2

如果未设置,则默认为应用程序范围的详细级别(通过 -v 命令行选项)。特殊值 "auto" 可用于明确使用全局详细级别。

命令行标志

所有命令行标志都可以通过运行 pytest --help 获得

$ pytest --help
usage: pytest [options] [file_or_dir] [file_or_dir] [...]

positional arguments:
  file_or_dir

general:
  -k EXPRESSION         Only run tests which match the given substring
                        expression. An expression is a Python evaluable
                        expression where all names are substring-matched
                        against test names and their parent classes.
                        Example: -k 'test_method or test_other' matches all
                        test functions and classes whose name contains
                        'test_method' or 'test_other', while -k 'not
                        test_method' matches those that don't contain
                        'test_method' in their names. -k 'not test_method
                        and not test_other' will eliminate the matches.
                        Additionally keywords are matched to classes and
                        functions containing extra names in their
                        'extra_keyword_matches' set, as well as functions
                        which have names assigned directly to them. The
                        matching is case-insensitive.
  -m MARKEXPR           Only run tests matching given mark expression. For
                        example: -m 'mark1 and not mark2'.
  --markers             show markers (builtin, plugin and per-project ones).
  -x, --exitfirst       Exit instantly on first error or failed test
  --maxfail=num         Exit after first num failures or errors
  --strict-config       Enables the strict_config option
  --strict-markers      Enables the strict_markers option
  --strict              Enables the strict option
  --fixtures, --funcargs
                        Show available fixtures, sorted by plugin appearance
                        (fixtures with leading '_' are only shown with '-v')
  --fixtures-per-test   Show fixtures per test
  --pdb                 Start the interactive Python debugger on errors or
                        KeyboardInterrupt
  --pdbcls=modulename:classname
                        Specify a custom interactive Python debugger for use
                        with --pdb.For example:
                        --pdbcls=IPython.terminal.debugger:TerminalPdb
  --trace               Immediately break when running each test
  --capture=method      Per-test capturing method: one of fd|sys|no|tee-sys
  -s                    Shortcut for --capture=no
  --runxfail            Report the results of xfail tests as if they were
                        not marked
  --lf, --last-failed   Rerun only the tests that failed at the last run (or
                        all if none failed)
  --ff, --failed-first  Run all tests, but run the last failures first. This
                        may re-order tests and thus lead to repeated fixture
                        setup/teardown.
  --nf, --new-first     Run tests from new files first, then the rest of the
                        tests sorted by file mtime
  --cache-show=[CACHESHOW]
                        Show cache contents, don't perform collection or
                        tests. Optional argument: glob (default: '*').
  --cache-clear         Remove all cache contents at start of test run
  --lfnf, --last-failed-no-failures={all,none}
                        With ``--lf``, determines whether to execute tests
                        when there are no previously (known) failures or
                        when no cached ``lastfailed`` data was found.
                        ``all`` (the default) runs the full test suite
                        again. ``none`` just emits a message about no known
                        failures and exits successfully.
  --sw, --stepwise      Exit on test failure and continue from last failing
                        test next time
  --sw-skip, --stepwise-skip
                        Ignore the first failing test but stop on the next
                        failing test. Implicitly enables --stepwise.
  --sw-reset, --stepwise-reset
                        Resets stepwise state, restarting the stepwise
                        workflow. Implicitly enables --stepwise.

Reporting:
  --durations=N         Show N slowest setup/test durations (N=0 for all)
  --durations-min=N     Minimal duration in seconds for inclusion in slowest
                        list. Default: 0.005 (or 0.0 if -vv is given).
  -v, --verbose         Increase verbosity
  --no-header           Disable header
  --no-summary          Disable summary
  --no-fold-skipped     Do not fold skipped tests in short summary.
  --force-short-summary
                        Force condensed summary output regardless of
                        verbosity level.
  -q, --quiet           Decrease verbosity
  --verbosity=VERBOSE   Set verbosity. Default: 0.
  -r chars              Show extra test summary info as specified by chars:
                        (f)ailed, (E)rror, (s)kipped, (x)failed, (X)passed,
                        (p)assed, (P)assed with output, (a)ll except passed
                        (p/P), or (A)ll. (w)arnings are enabled by default
                        (see --disable-warnings), 'N' can be used to reset
                        the list. (default: 'fE').
  --disable-warnings, --disable-pytest-warnings
                        Disable warnings summary
  -l, --showlocals      Show locals in tracebacks (disabled by default)
  --no-showlocals       Hide locals in tracebacks (negate --showlocals
                        passed through addopts)
  --tb=style            Traceback print mode
                        (auto/long/short/line/native/no)
  --xfail-tb            Show tracebacks for xfail (as long as --tb != no)
  --show-capture={no,stdout,stderr,log,all}
                        Controls how captured stdout/stderr/log is shown on
                        failed tests. Default: all.
  --full-trace          Don't cut any tracebacks (default is to cut)
  --color=color         Color terminal output (yes/no/auto)
  --code-highlight={yes,no}
                        Whether code should be highlighted (only if --color
                        is also enabled). Default: yes.
  --pastebin=mode       Send failed|all info to bpaste.net pastebin service
  --junitxml, --junit-xml=path
                        Create junit-xml style report file at given path
  --junitprefix, --junit-prefix=str
                        Prepend prefix to classnames in junit-xml output

pytest-warnings:
  -W, --pythonwarnings PYTHONWARNINGS
                        Set which warnings to report, see -W option of
                        Python itself

collection:
  --collect-only, --co  Only collect tests, don't execute them
  --pyargs              Try to interpret all arguments as Python packages
  --ignore=path         Ignore path during collection (multi-allowed)
  --ignore-glob=path    Ignore path pattern during collection (multi-
                        allowed)
  --deselect=nodeid_prefix
                        Deselect item (via node id prefix) during collection
                        (multi-allowed)
  --confcutdir=dir      Only load conftest.py's relative to specified dir
  --noconftest          Don't load any conftest.py files
  --keep-duplicates     Keep duplicate tests
  --collect-in-virtualenv
                        Don't ignore tests in a local virtualenv directory
  --continue-on-collection-errors
                        Force test execution even if collection errors occur
  --import-mode={prepend,append,importlib}
                        Prepend/append to sys.path when importing test
                        modules and conftest files. Default: prepend.
  --doctest-modules     Run doctests in all .py modules
  --doctest-report={none,cdiff,ndiff,udiff,only_first_failure}
                        Choose another output format for diffs on doctest
                        failure
  --doctest-glob=pat    Doctests file matching pattern, default: test*.txt
  --doctest-ignore-import-errors
                        Ignore doctest collection errors
  --doctest-continue-on-failure
                        For a given doctest, continue to run after the first
                        failure

test session debugging and configuration:
  -c, --config-file FILE
                        Load configuration from `FILE` instead of trying to
                        locate one of the implicit configuration files.
  --rootdir=ROOTDIR     Define root directory for tests. Can be relative
                        path: 'root_dir', './root_dir',
                        'root_dir/another_dir/'; absolute path:
                        '/home/user/root_dir'; path with variables:
                        '$HOME/root_dir'.
  --basetemp=dir        Base temporary directory for this test run.
                        (Warning: this directory is removed if it exists.)
  -V, --version         Display pytest version and information about
                        plugins. When given twice, also display information
                        about plugins.
  -h, --help            Show help message and configuration info
  -p name               Early-load given plugin module name or entry point
                        (multi-allowed). To avoid loading of plugins, use
                        the `no:` prefix, e.g. `no:doctest`. See also
                        --disable-plugin-autoload.
  --disable-plugin-autoload
                        Disable plugin auto-loading through entry point
                        packaging metadata. Only plugins explicitly
                        specified in -p or env var PYTEST_PLUGINS will be
                        loaded.
  --trace-config        Trace considerations of conftest.py files
  --debug=[DEBUG_FILE_NAME]
                        Store internal tracing debug information in this log
                        file. This file is opened with 'w' and truncated as
                        a result, care advised. Default: pytestdebug.log.
  -o, --override-ini OVERRIDE_INI
                        Override configuration option with "option=value"
                        style, e.g. `-o strict_xfail=True -o
                        cache_dir=cache`.
  --assert=MODE         Control assertion debugging tools.
                        'plain' performs no assertion debugging.
                        'rewrite' (the default) rewrites assert statements
                        in test modules on import to provide assert
                        expression information.
  --setup-only          Only setup fixtures, do not execute tests
  --setup-show          Show setup of fixtures while executing tests
  --setup-plan          Show what fixtures and tests would be executed but
                        don't execute anything

logging:
  --log-level=LEVEL     Level of messages to catch/display. Not set by
                        default, so it depends on the root/parent log
                        handler's effective level, where it is "WARNING" by
                        default.
  --log-format=LOG_FORMAT
                        Log format used by the logging module
  --log-date-format=LOG_DATE_FORMAT
                        Log date format used by the logging module
  --log-cli-level=LOG_CLI_LEVEL
                        CLI logging level
  --log-cli-format=LOG_CLI_FORMAT
                        Log format used by the logging module
  --log-cli-date-format=LOG_CLI_DATE_FORMAT
                        Log date format used by the logging module
  --log-file=LOG_FILE   Path to a file when logging will be written to
  --log-file-mode={w,a}
                        Log file open mode
  --log-file-level=LOG_FILE_LEVEL
                        Log file logging level
  --log-file-format=LOG_FILE_FORMAT
                        Log format used by the logging module
  --log-file-date-format=LOG_FILE_DATE_FORMAT
                        Log date format used by the logging module
  --log-auto-indent=LOG_AUTO_INDENT
                        Auto-indent multiline messages passed to the logging
                        module. Accepts true|on, false|off or an integer.
  --log-disable=LOGGER_DISABLE
                        Disable a logger by name. Can be passed multiple
                        times.

[pytest] configuration options in the first pytest.toml|pytest.ini|tox.ini|setup.cfg|pyproject.toml file found:

  markers (linelist):   Register new markers for test functions
  empty_parameter_set_mark (string):
                        Default marker for empty parametersets
  strict_config (bool): Any warnings encountered while parsing the `pytest`
                        section of the configuration file raise errors
  strict_markers (bool):
                        Markers not registered in the `markers` section of
                        the configuration file raise errors
  strict (bool):        Enables all strictness options, currently:
                        strict_config, strict_markers, strict_xfail,
                        strict_parametrization_ids
  filterwarnings (linelist):
                        Each line specifies a pattern for
                        warnings.filterwarnings. Processed after
                        -W/--pythonwarnings.
  norecursedirs (args): Directory patterns to avoid for recursion
  testpaths (args):     Directories to search for tests when no files or
                        directories are given on the command line
  collect_imported_tests (bool):
                        Whether to collect tests in imported modules outside
                        `testpaths`
  consider_namespace_packages (bool):
                        Consider namespace packages when resolving module
                        names during import
  usefixtures (args):   List of default fixtures to be used with this
                        project
  python_files (args):  Glob-style file patterns for Python test module
                        discovery
  python_classes (args):
                        Prefixes or glob names for Python test class
                        discovery
  python_functions (args):
                        Prefixes or glob names for Python test function and
                        method discovery
  disable_test_id_escaping_and_forfeit_all_rights_to_community_support (bool):
                        Disable string escape non-ASCII characters, might
                        cause unwanted side effects(use at your own risk)
  strict_parametrization_ids (bool):
                        Emit an error if non-unique parameter set IDs are
                        detected
  console_output_style (string):
                        Console output: "classic", or with additional
                        progress information ("progress" (percentage) |
                        "count" | "progress-even-when-capture-no" (forces
                        progress even when capture=no)
  verbosity_test_cases (string):
                        Specify a verbosity level for test case execution,
                        overriding the main level. Higher levels will
                        provide more detailed information about each test
                        case executed.
  strict_xfail (bool):  Default for the strict parameter of xfail markers
                        when not given explicitly (default: False) (alias:
                        xfail_strict)
  tmp_path_retention_count (string):
                        How many sessions should we keep the `tmp_path`
                        directories, according to
                        `tmp_path_retention_policy`.
  tmp_path_retention_policy (string):
                        Controls which directories created by the `tmp_path`
                        fixture are kept around, based on test outcome.
                        (all/failed/none)
  enable_assertion_pass_hook (bool):
                        Enables the pytest_assertion_pass hook. Make sure to
                        delete any previously generated pyc cache files.
  truncation_limit_lines (string):
                        Set threshold of LINES after which truncation will
                        take effect
  truncation_limit_chars (string):
                        Set threshold of CHARS after which truncation will
                        take effect
  verbosity_assertions (string):
                        Specify a verbosity level for assertions, overriding
                        the main level. Higher levels will provide more
                        detailed explanation when an assertion fails.
  junit_suite_name (string):
                        Test suite name for JUnit report
  junit_logging (string):
                        Write captured log messages to JUnit report: one of
                        no|log|system-out|system-err|out-err|all
  junit_log_passing_tests (bool):
                        Capture log information for passing tests to JUnit
                        report:
  junit_duration_report (string):
                        Duration time to report: one of total|call
  junit_family (string):
                        Emit XML for schema: one of legacy|xunit1|xunit2
  doctest_optionflags (args):
                        Option flags for doctests
  doctest_encoding (string):
                        Encoding used for doctest files
  cache_dir (string):   Cache directory path
  log_level (string):   Default value for --log-level
  log_format (string):  Default value for --log-format
  log_date_format (string):
                        Default value for --log-date-format
  log_cli (bool):       Enable log display during test run (also known as
                        "live logging")
  log_cli_level (string):
                        Default value for --log-cli-level
  log_cli_format (string):
                        Default value for --log-cli-format
  log_cli_date_format (string):
                        Default value for --log-cli-date-format
  log_file (string):    Default value for --log-file
  log_file_mode (string):
                        Default value for --log-file-mode
  log_file_level (string):
                        Default value for --log-file-level
  log_file_format (string):
                        Default value for --log-file-format
  log_file_date_format (string):
                        Default value for --log-file-date-format
  log_auto_indent (string):
                        Default value for --log-auto-indent
  faulthandler_timeout (string):
                        Dump the traceback of all threads if a test takes
                        more than TIMEOUT seconds to finish
  faulthandler_exit_on_timeout (bool):
                        Exit the test process if a test takes more than
                        faulthandler_timeout seconds to finish
  verbosity_subtests (string):
                        Specify verbosity level for subtests. Higher levels
                        will generate output for passed subtests. Failed
                        subtests are always reported.
  addopts (args):       Extra command line options
  minversion (string):  Minimally required pytest version
  pythonpath (paths):   Add paths to sys.path
  required_plugins (args):
                        Plugins that must be present for pytest to run

Environment variables:
  CI                       When set to a non-empty value, pytest knows it is running in a CI process and does not truncate summary info
  BUILD_NUMBER             Equivalent to CI
  PYTEST_ADDOPTS           Extra command line options
  PYTEST_PLUGINS           Comma-separated plugins to load during startup
  PYTEST_DISABLE_PLUGIN_AUTOLOAD Set to disable plugin auto-loading
  PYTEST_DEBUG             Set to enable debug tracing of pytest's internals
  PYTEST_DEBUG_TEMPROOT    Override the system temporary directory
  PYTEST_THEME             The Pygments style to use for code output
  PYTEST_THEME_MODE        Set the PYTEST_THEME to be either 'dark' or 'light'


to see available markers type: pytest --markers
to see available fixtures type: pytest --fixtures
(shown according to specified file_or_dir or current dir if not specified; fixtures with leading '_' are only shown with the '-v' option