API 参考¶
此页面包含 pytest API 的完整参考。
常量¶
pytest.__version__¶
当前 pytest 版本,字符串形式
>>> import pytest
>>> pytest.__version__
'7.0.0'
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相对容差范围内,仍将被视为不相等。如果同时指定了abs和rel,则只要满足其中一个容差,数字就会被视为相等>>> 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):如果相对容差相对于a或b得到满足,或者如果绝对容差得到满足,则为 True。因为相对容差是相对于a和b计算的,所以此测试是对称的(即a或b均不是“参考值”)。如果你想与0.0比较,你必须指定一个绝对容差,因为默认情况下没有容差。更多信息:math.isclose()。numpy.isclose(a, b, rtol=1e-5, atol=1e-8):如果a和b之间的差异小于相对于b的相对容差和绝对容差之和,则为 True。因为相对容差只相对于b计算,所以此测试是不对称的,你可以将b视为参考值。对序列比较的支持由numpy.allclose()提供。更多信息:numpy.isclose。unittest.TestCase.assertAlmostEqual(a, b):如果a和b在1e-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])¶
使用给定消息显式使正在执行的测试失败。
- 参数:
- 引发:
pytest.fail.Exception – 引发的异常。
- class pytest.fail.Exception¶
由
pytest.fail()引发的异常。
pytest.skip¶
- skip(reason[, allow_module_level=False])¶
使用给定消息跳过正在执行的测试。
此函数应仅在测试期间(设置、调用或 teardown)或在收集期间使用
allow_module_level标志调用。此函数也可以在 doctests 中调用。- 参数:
- 引发:
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.skip.Exception – 如果模块无法导入。
- 返回类型:
示例
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¶
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
预期异常组
当预期封装在
BaseExceptionGroup或ExceptionGroup中的异常时,应改为使用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
断言代码会产生
DeprecationWarning或PendingDeprecationWarning或FutureWarning。此函数可用作上下文管理器
>>> 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¶
教程: 断言重写
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
标记¶
标记可用于将元数据应用于**测试函数**(但不能应用于夹具),然后夹具或插件可以访问这些元数据。
pytest.mark.filterwarnings¶
教程: @pytest.mark.filterwarnings
向标记的测试项添加警告过滤器。
pytest.mark.parametrize¶
教程: 如何参数化夹具和测试函数
此标记与 pytest.Metafunc.parametrize() 具有相同的签名;请参阅此处。
pytest.mark.skip¶
教程: 跳过测试函数
无条件跳过测试函数。
pytest.mark.skipif¶
教程: 跳过测试函数
如果条件为 True,则跳过测试函数。
pytest.mark.usefixtures¶
将测试函数标记为使用给定的夹具名称。
- pytest.mark.usefixtures(*names)¶
- 参数:
args – 要使用的夹具名称,以字符串形式。
注意
在钩子中使用 usefixtures 时,它只能在测试设置之前应用于测试函数时加载夹具(例如在 pytest_collection_modifyitems 钩子中)。
另请注意,此标记应用于**夹具**时无效。
pytest.mark.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_markers 或 Node.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)标记。测试函数可以直接使用夹具名称作为输入参数,在这种情况下,将注入从夹具函数返回的夹具实例。
夹具可以使用
return或yield语句向测试函数提供其值。使用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¶
- capfd()[source]¶
启用对文件描述符
1和2写入的文本捕获。捕获的输出通过
capfd.readouterr()方法调用提供,该方法返回一个(out, err)命名元组。out和err将是text对象。返回
CaptureFixture[str]的实例。示例
def test_system_echo(capfd): os.system('echo "hello"') captured = capfd.readouterr() assert captured.out == "hello\n"
capfdbinary¶
- capfdbinary()[source]¶
启用对文件描述符
1和2写入的字节捕获。捕获的输出通过
capfd.readouterr()方法调用提供,该方法返回一个(out, err)命名元组。out和err将是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”。
- 返回:
给定阶段捕获的记录列表。
- 返回类型:
3.4 版本新增。
- property record_tuples: list[tuple[str, int, str]]¶
一个简化版日志记录的列表,旨在用于断言比较。
元组的格式是
(logger_name, log_level, message)
- property messages: list[str]¶
格式插值的日志消息列表。
与包含用于插值的格式字符串和参数的“records”不同,此列表中的日志消息都经过插值。
与包含处理程序输出的“text”不同,此列表中的日志消息未包含级别、时间戳等修饰,从而使精确比较更可靠。
请注意,不包含回溯或堆栈信息(来自
logging.exception()或日志函数中的exc_info或stack_info参数),因为这是由处理程序中的格式化程序添加的。3.7 版本新增。
- set_level(level, logger=None)[source]¶
在测试期间设置日志记录器的阈值级别。
严重程度低于此级别的日志消息将不会被捕获。
3.4 版本更改:此函数更改的日志记录器级别将在测试结束时恢复为初始值。
如果通过
logging.disable()禁用了请求的日志级别,则会启用它。
- with at_level(level, logger=None)[source]¶
上下文管理器,用于设置日志捕获级别。在“with”语句块结束后,级别将恢复为原始值。
如果通过
logging.disable()禁用了请求的日志级别,则会启用它。
- with filtering(filter_)[source]¶
上下文管理器,用于在“with”语句块内临时将给定过滤器添加到 caplog 的
handler(),并在块结束时移除该过滤器。- 参数:
filter – 自定义
logging.Filter对象。
7.5 版本新增。
capsys¶
- capsys()[source]¶
启用对
sys.stdout和sys.stderr写入的文本捕获。捕获的输出通过
capsys.readouterr()方法调用提供,该方法返回一个(out, err)命名元组。out和err将是text对象。返回
CaptureFixture[str]的实例。示例
def test_output(capsys): print("hello") captured = capsys.readouterr() assert captured.out == "hello\n"
- class CaptureFixture[source]¶
由
capsys、capsysbinary、capfd和capfdbinary夹具返回的对象。
capteesys¶
- capteesys()[source]¶
启用同时文本捕获并根据
--capture=将写入sys.stdout和sys.stderr的内容进行直通。捕获的输出通过
capteesys.readouterr()方法调用提供,该方法返回一个(out, err)命名元组。out和err将是text对象。输出也会被直通,允许它根据
--capture=进行“实时打印”、报告或两者兼有。返回
CaptureFixture[str]的实例。示例
def test_output(capteesys): print("hello") captured = capteesys.readouterr() assert captured.out == "hello\n"
capsysbinary¶
- capsysbinary()[source]¶
启用对
sys.stdout和sys.stderr写入的字节捕获。捕获的输出通过
capsysbinary.readouterr()方法调用提供,该方法返回一个(out, err)命名元组。out和err将是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.cache 是 pytest.Cache 的一个实例
- final class Cache[source]¶
cache夹具的实例。- mkdir(name)[source]¶
返回具有给定名称的目录路径对象。
如果目录尚不存在,它将被创建。您可以使用它来管理文件,例如在测试会话之间存储/检索数据库转储。
7.0 版本新增。
- 参数:
name (str) – 必须是不包含
/分隔符的字符串。确保名称包含您的插件或应用程序标识符,以防止与其他缓存用户发生冲突。
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参数决定如果设置/删除操作没有指定目标,是否会引发KeyError或AttributeError。要撤销夹具在受限范围内所做的修改,请使用
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。如果未指定
name且target为字符串,则将其解释为带点导入路径,最后一部分是属性名称。如果属性不存在,则引发 AttributeError,除非
raising设置为 False。
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和环境变量。- plugins: list[str | object]¶
与
parseconfig()和runpytest()一起使用的插件列表。最初这是一个空列表,但可以向列表中添加插件。在子进程模式下运行时,按名称 (str) 指定插件 - 不支持直接添加插件对象。
- make_hook_recorder(pluginmanager)[source]¶
为
PytestPluginManager创建一个新的HookRecorder。
- makefile(ext, *args, **kwargs)[source]¶
在测试目录中创建新的文本文件。
- 参数:
- 返回:
创建的第一个文件。
- 返回类型:
示例
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"...")
- 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.
- copy_example(name=None)[source]¶
将文件从项目目录复制到测试目录。
- 参数:
name (str | None) – 要复制的文件名称。
- 返回:
复制目录的路径(在
self.path中)。- 返回类型:
- getnode(config, arg)[source]¶
获取文件的集合节点。
- 参数:
config (Config) – 一个 pytest 配置。参见
parseconfig()和parseconfigure()来创建它。
- 返回:
节点。
- 返回类型:
- getpathnode(path)[source]¶
返回文件的集合节点。
这类似于
getnode(),但使用parseconfigure()来创建(已配置的)pytest Config 实例。
- 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()的命令行参数。plugins –
pytest.main()实例应使用的额外插件实例。no_reraise_ctrlc (bool) – 通常我们会重新引发子运行中的键盘中断。如果为 True,则会捕获 KeyboardInterrupt 异常。
- 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 的收集,返回请求的函数名的测试项。
- getmodulecol(source, configargs=(), *, withinit=False)[source]¶
返回
source的模块集合节点。使用
makepyfile()将source写入文件,然后对其运行 pytest 收集,返回测试模块的集合节点。- 参数:
configargs – 传递给
parseconfigure()的任何额外参数。withinit (bool) – 是否也在同一目录中写入一个
__init__.py文件以确保它是一个包。
- collect_by_name(modcol, name)[source]¶
从模块集合中返回名称的集合节点。
在模块集合节点中搜索与给定名称匹配的集合节点。
- 参数:
modcol (Collector) – 模块集合节点;参见
getmodulecol()。name (str) – 要返回的节点的名称。
- 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.Popen中stdin参数的文档以获取更多信息。
- 返回:
结果。
- 返回类型:
- runpytest_subprocess(*args, timeout=None)[source]¶
以给定参数作为子进程运行 pytest。
添加到
plugins列表的任何插件都将使用-p命令行选项添加。此外,--basetemp用于将任何临时文件和目录放置在以“runpytest-”为前缀的编号目录中,以免与正常的编号 pytest 临时文件和目录位置冲突。
- final class RunResult[source]¶
运行
Pytester中命令的结果。- 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}。
- class LineMatcher[source]¶
灵活的文本匹配。
这是一个方便的类,用于测试大量文本,例如命令的输出。
构造函数接受一个没有尾随换行符的行列表,即
text.splitlines()。- fnmatch_lines_random(lines2)[source]¶
检查行是否以任何顺序存在于输出中(使用
fnmatch.fnmatch())。
- re_match_lines_random(lines2)[source]¶
检查行是否以任何顺序存在于输出中(使用
re.match())。
- fnmatch_lines(lines2, *, consecutive=False)[source]¶
检查行是否在输出中存在(使用
fnmatch.fnmatch())。参数是一个必须匹配且可以使用 glob 通配符的行列表。如果它们不匹配,则调用 pytest.fail()。匹配和不匹配也会作为错误消息的一部分显示。
- re_match_lines(lines2, *, consecutive=False)[source]¶
检查行是否在输出中存在(使用
re.match())。参数是一个必须使用
re.match匹配的行列表。如果它们不匹配,则调用 pytest.fail()。匹配和不匹配也会作为错误消息的一部分显示。
record_property¶
教程: record_property
record_testsuite_property¶
- record_testsuite_property()[source]¶
将新的
<property>标签记录为根<testsuite>的子级。这适用于写入有关整个测试套件的全局信息,并与
xunit2JUnit 系列兼容。这是一个
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。注意
DeprecationWarning和PendingDeprecationWarning的处理方式不同;请参见 确保代码触发弃用警告。
request¶
request 夹具是一个特殊的夹具,提供有关请求测试函数的信息。
- class FixtureRequest[source]¶
request夹具的类型。请求对象提供对请求测试上下文的访问权限,并且在夹具参数化时具有
param属性。- property scope: Literal['session', 'package', 'module', 'class', 'function']¶
作用域字符串,可以是“function”、“class”、“module”、“package”、“session”之一。
- abstract property node¶
底层集合节点(取决于当前请求作用域)。
- property function¶
如果请求具有按函数范围的作用域,则为测试函数对象。
- property cls¶
收集测试函数的类(可以为 None)。
- property instance¶
收集测试函数的实例(可以为 None)。
- property module¶
收集测试函数的 Python 模块对象。
- property keywords: MutableMapping[str, Any]¶
底层节点的关键字/标记字典。
- applymarker(marker)[source]¶
将标记应用于单个测试函数调用。
如果您不想在所有函数调用上都有关键字/标记,则此方法很有用。
- 参数:
marker (str | MarkDecorator) – 调用
pytest.mark.NAME(...)创建的对象。
- getfixturevalue(argname)[source]¶
动态运行命名的夹具函数。
尽可能建议通过函数参数声明夹具。但如果您只能在测试设置时决定是否使用另一个夹具,则可以在夹具或测试函数体内部使用此函数来检索它。
此方法可以在测试设置阶段或测试运行阶段使用,但在测试拆卸阶段,夹具的值可能不可用。
- 参数:
argname (str) – 夹具名称。
- 引发:
pytest.FixtureLookupError – 如果找不到给定夹具。
subtests¶
subtests 夹具支持在测试函数内部声明子测试。
教程: 如何使用子测试
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]
-
- makeconftest(source)[source]
-
- makeini(source)[source]
-
- getinicfg(source)[source]
-
- makepyprojecttoml(source)[source]
参见
Pytester.makepyprojecttoml()。
- makepyfile(*args, **kwargs)[source]
-
- maketxtfile(*args, **kwargs)[source]
-
- syspathinsert(path=None)[source]
-
- mkdir(name)[source]
参见
Pytester.mkdir()。
- mkpydir(name)[source]
-
- copy_example(name=None)[source]
-
- getnode(config, arg)[source]
-
- getpathnode(path)[source]
- genitems(colitems)[source]
-
- runitem(source)[source]
- inline_runsource(source, *cmdlineargs)[source]
- inline_genitems(*args)[source]
- inline_run(*args, plugins=(), no_reraise_ctrlc=False)[source]
-
- runpytest_inprocess(*args, **kwargs)[source]
参见
Pytester.runpytest_inprocess()。
- runpytest(*args, **kwargs)[source]
-
- parseconfig(*args)[source]
-
- parseconfigure(*args)[source]
-
- getitem(source, funcname='test_func')[source]
- getitems(source)[source]
- getmodulecol(source, configargs=(), withinit=False)[source]
- 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]
-
- runpython_c(command)[source]
- runpytest_subprocess(*args, timeout=None)[source]
参见
Pytester.runpytest_subprocess()。
- spawn_pytest(string, expect_timeout=10.0)[source]
-
- spawn(cmd, expect_timeout=10.0)[source]
参见
Pytester.spawn()。
tmp_path¶
教程: 如何在测试中使用临时目录和文件
- tmp_path()[source]¶
返回一个临时目录(作为
pathlib.Path对象),该目录对于每个测试函数调用都是唯一的。临时目录创建为基本临时目录的子目录,具有可配置的保留期,如 临时目录位置和保留 中所述。
tmp_path_factory¶
tmp_path_factory 是 TempPathFactory 的一个实例。
tmpdir¶
教程: tmpdir 和 tmpdir_factory fixture
- tmpdir()¶
返回一个临时目录(作为 legacy_path 对象),该目录对于每个测试函数调用都是唯一的。临时目录创建为基本临时目录的子目录,具有可配置的保留期,如 临时目录位置和保留 中所述。
tmpdir_factory¶
教程: tmpdir 和 tmpdir_factory fixture
tmpdir_factory 是 TempdirFactory 的一个实例。
- final class TempdirFactory[source]¶
为
TempPathFactory实现py.path.local的向后兼容包装器。- mktemp(basename, numbered=True)[source]¶
与
TempPathFactory.mktemp()相同,但返回一个py.path.local对象。
- getbasetemp()[source]¶
与
TempPathFactory.getbasetemp()相同,但返回一个py.path.local对象。
钩子¶
教程: 编写插件
所有可由 conftest.py 文件 和 插件 实现的钩子参考。
@pytest.hookimpl¶
- @pytest.hookimpl¶
pytest 用于标记函数为钩子实现的装饰器。
@pytest.hookspec¶
- @pytest.hookspec¶
pytest 用于标记函数为钩子规范的装饰器。
参见 声明新钩子 和
pluggy.HookspecMarker()。
引导钩子¶
为足够早注册的插件(内部和第三方插件)调用的引导钩子。
- pytest_load_initial_conftests(early_config, parser, args)[source]¶
在命令行选项解析之前,用于实现加载 初始 conftest 文件。
在 conftest 插件中使用¶
此钩子不用于 conftest 文件。
- pytest_cmdline_parse(pluginmanager, args)[source]¶
返回一个已初始化
Config,解析指定的参数。在第一个非 None 结果处停止,参见 firstresult: 在第一个非 None 结果处停止。
注意
此钩子仅在使用 pytest.main 执行进程内测试运行时,为传递给
plugins参数的插件类调用。- 参数:
pluginmanager (PytestPluginManager) – pytest 插件管理器。
- 返回:
pytest 配置对象。
- 返回类型:
Config | None
在 conftest 插件中使用¶
此钩子不用于 conftest 文件。
- pytest_cmdline_main(config)[source]¶
用于执行主要命令行操作。
默认实现将调用配置钩子和
pytest_runtestloop。在第一个非 None 结果处停止,参见 firstresult: 在第一个非 None 结果处停止。
在 conftest 插件中使用¶
此钩子仅用于 初始 conftest。
初始化钩子¶
为插件和 conftest.py 文件调用的初始化钩子。
- pytest_addoption(parser, pluginmanager)[source]¶
注册 argparse 风格的选项和 config 风格的配置值,在测试运行开始时调用一次。
- 参数:
parser (Parser) – 要添加命令行选项,请调用
parser.addoption(...)。要添加配置文件值,请调用parser.addini(...)。pluginmanager (PytestPluginManager) – pytest 插件管理器,可用于安装
hookspec()或hookimpl(),并允许一个插件调用另一个插件的钩子来改变命令行选项的添加方式。
选项稍后可以通过
config对象访问,分别config.getoption(name)用于检索命令行选项的值。config.getini(name)用于检索从配置文件中读取的值。
config 对象通过
.config属性传递给许多内部对象,也可以作为pytestconfigfixture 检索。注意
此钩子与钩子包装器不兼容。
在 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]¶
在整个测试运行结束后,将退出状态返回给系统之前调用。
在 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 结果处停止。返回值未使用,但仅停止进一步处理。
默认收集阶段如下(有关完整详细信息,请参见各个钩子)
从
session作为初始收集器开始
pytest_collectstart(collector)report = pytest_make_collect_report(collector)如果发生交互式异常,则
pytest_exception_interact(collector, call, report)对于每个收集到的节点
如果是一个项,
pytest_itemcollected(item)如果是一个收集器,则递归进入。
pytest_collectreport(report)
pytest_collection_modifyitems(session, config, items)
对于任何未选定的项目(可能会多次调用),
pytest_deselected(items)
pytest_collection_finish(session)将
session.items设置为收集到的项目列表将
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 结果处停止。
- 参数:
- 返回:
创建的项/收集器。
- 返回类型:
在 conftest 插件中使用¶
任何 conftest 文件都可以实现此钩子。对于给定的收集器,只咨询收集器目录及其父目录中的 conftest 文件。
- pytest_generate_tests(metafunc)[source]¶
生成对测试函数的(多个)参数化调用。
在 conftest 插件中使用¶
任何 conftest 文件都可以实现此钩子。对于给定的函数定义,只咨询函数目录及其父目录中的 conftest 文件。
- pytest_make_parametrize_id(config, val, argname)[source]¶
返回给定
val的用户友好字符串表示形式,该字符串将用于 @pytest.mark.parametrize 调用,如果钩子不了解val,则返回 None。如果需要,参数名称可用作
argname。在第一个非 None 结果处停止,参见 firstresult: 在第一个非 None 结果处停止。
在 conftest 插件中使用¶
任何 conftest 文件都可以实现此钩子。
影响测试跳过的钩子
- pytest_markeval_namespace(config)[source]¶
在构造用于评估 xfail/skipif 标记中的字符串条件的全局字典时调用。
当标记的条件需要昂贵或无法在收集时获取的对象时,此功能非常有用,而正常布尔条件则需要这样做。
6.2 版本新增。
在 conftest 插件中使用¶
任何 conftest 文件都可以实现此钩子。对于给定项,只咨询项父目录中的 conftest 文件。
收集完成后,您可以修改项目的顺序,删除或以其他方式修改测试项目
- pytest_collection_modifyitems(session, config, items)[source]¶
在执行收集后调用。可以原地过滤或重新排序项目。
当项目被取消选择(从
items中过滤掉)时,必须显式调用钩子pytest_deselected并传入被取消选择的项目,以便正确通知其他插件,例如使用config.hook.pytest_deselected(items=deselected_items)。在 conftest 插件中使用¶
任何 conftest 插件都可以实现此钩子。
注意
如果在 conftest.py 文件中实现此钩子,它总是接收所有收集到的项目,而不仅仅是其实现的 conftest.py 下的项目。
测试运行 (runtest) 钩子¶
所有与 runtest 相关的钩子都接收一个 pytest.Item 对象。
- pytest_runtestloop(session)[source]¶
执行主 runtest 循环(收集完成后)。
默认钩子实现对会话中收集的所有项 (
session.items) 执行 runtest 协议,除非收集失败或设置了collectonlypytest 选项。如果任何时候调用了
pytest.exit(),则循环立即终止。如果任何时候设置了
session.shouldfail或session.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)
- 调用阶段,如果设置通过且未设置
setuponlypytest 选项 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)
在第一个非 None 结果处停止,参见 firstresult: 在第一个非 None 结果处停止。返回值未使用,但仅停止进一步处理。
在 conftest 插件中使用¶
任何 conftest 文件都可以实现此钩子。
- pytest_runtest_logstart(nodeid, location)[source]¶
在单个项的 runtest 协议运行开始时调用。
有关 runtest 协议的描述,请参见
pytest_runtest_protocol。- 参数:
在 conftest 插件中使用¶
任何 conftest 文件都可以实现此钩子。对于给定项,只咨询项目录及其父目录中的 conftest 文件。
- pytest_runtest_logfinish(nodeid, location)[source]¶
在单个项的 runtest 协议运行结束时调用。
有关 runtest 协议的描述,请参见
pytest_runtest_protocol。- 参数:
在 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()。这包括运行项所需夹具的拆卸阶段(如果它们超出范围)。- 参数:
在 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})。- 参数:
report (CollectReport | TestReport) – 要返回状态的报告对象。
config (Config) – pytest 配置对象。
- 返回:
测试状态。
- 返回类型:
TestShortLogReport | tuple[str, str, str | tuple[str, Mapping[str, bool]]]
在第一个非 None 结果处停止,参见 firstresult: 在第一个非 None 结果处停止。
在 conftest 插件中使用¶
任何 conftest 插件都可以实现此钩子。
- pytest_report_to_serializable(config, report)[source]¶
将给定报告对象序列化为适合通过网络发送的数据结构,例如转换为 JSON。
- 参数:
config (Config) – pytest 配置对象。
report (CollectReport | TestReport) – 报告。
在 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,否则返回一个字符串列表。字符串将用换行符连接,但字符串中的任何换行符都将被转义。请注意,除第一行外,所有行都将稍微缩进,目的是让第一行作为摘要。
- 参数:
在 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 文件,因为断言将需要重新写入。
- 参数:
在 conftest 插件中使用¶
任何 conftest 文件都可以实现此钩子。对于给定项,只咨询项目录及其父目录中的 conftest 文件。
调试/交互钩子¶
有一些钩子可用于特殊报告或与异常的交互。
- pytest_internalerror(excrepr, excinfo)[source]¶
为内部错误调用。
返回 True 以抑制直接向 sys.stderr 打印 INTERNALERROR 消息的 fallback 处理。
- 参数:
excrepr (ExceptionRepr) – 异常表示对象。
excinfo (ExceptionInfo[BaseException]) – 异常信息。
在 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),则不调用此钩子。- 参数:
call (CallInfo[Any]) – 调用信息。包含异常。
report (CollectReport | TestReport) – 收集或测试报告。
在 conftest 插件中使用¶
任何 conftest 文件都可以实现此钩子。对于给定的节点,只会查阅节点父目录中的 conftest 文件。
收集树对象¶
这些是构成收集树的收集器和项类(统称为“节点”)。
节点¶
- class Node[source]¶
基类:
ABCCollector和Item的基类,它们是测试收集树的组成部分。Collector是树的内部节点,Item是叶节点。- fspath: LEGACY_PATH¶
path属性的LEGACY_PATH副本。旨在用于尚未迁移到pathlib.Path的方法,例如Item.reportinfo。将在未来版本中弃用,建议使用path。
- parent¶
父收集器节点。
- path: pathlib.Path¶
此节点从中收集的文件系统路径(可以为 None)。
- classmethod from_parent(parent, **kw)[source]¶
节点的公共构造函数。
引入此间接是为了能够从节点构造函数中删除脆弱的逻辑。
子类在覆盖构造时可以使用
super().from_parent(...)。- 参数:
parent (Node) – 此节点的父节点。
- warn(warning)[source]¶
为此节点发出警告。
警告将在测试会话结束后显示,除非明确抑制。
- 参数:
warning (Warning) – 要发出的警告实例。
- 引发:
ValueError – 如果
warning实例不是 Warning 的子类。
示例用法
node.warn(PytestWarning("some message")) node.warn(UserWarning("some message"))
在 6.2 版本中更改: 现在接受
Warning的任何子类,而不仅仅是PytestWarning子类。
- add_marker(marker, append=True)[source]¶
动态地向节点添加标记对象。
- 参数:
marker (str | MarkDecorator) – 标记。
append (bool) – 是追加标记还是前置标记。
- get_closest_marker(name: str) Mark | None¶
- get_closest_marker(name: str, default: Mark) Mark
返回与名称匹配的第一个标记,从最接近的级别(例如函数)到更远的级别(例如模块级别)。
- 参数:
default – 如果未找到标记,则回退返回值。
name – 要过滤的名称。
- 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]¶
-
所有收集器的基类。
收集器通过
collect()创建子级,从而迭代构建收集树。- repr_failure(excinfo)[source]¶
返回收集失败的表示。
- 参数:
excinfo (ExceptionInfo[BaseException]) – 失败的异常信息。
- parent¶
父收集器节点。
- path: pathlib.Path¶
此节点从中收集的文件系统路径(可以为 None)。
项¶
- class Item[source]¶
-
所有测试调用项的基类。
请注意,对于单个函数,可能存在多个测试调用项。
- parent¶
父收集器节点。
- path: pathlib.Path¶
此节点从中收集的文件系统路径(可以为 None)。
- add_report_section(when, key, content)[source]¶
添加一个新的报告部分,类似于内部添加 stdout 和 stderr 捕获输出的方式。
item.add_report_section("call", "stdout", "report section contents")
文件¶
- class File[source]¶
基类:
FSCollector,ABC从文件收集测试的基类。
- parent¶
父收集器节点。
- path: pathlib.Path¶
此节点从中收集的文件系统路径(可以为 None)。
FSCollector¶
会话¶
- final class Session[source]¶
基类:
Collector收集树的根。
Session收集作为 pytest 参数给出的初始路径。- exception Interrupted¶
-
表示测试运行被中断。
- 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为空。
- parent¶
父收集器节点。
- path: pathlib.Path¶
此节点从中收集的文件系统路径(可以为 None)。
包¶
模块¶
类¶
- class Class[source]¶
基类:
PyCollectorPython 类中测试方法(和嵌套类)的收集器。
- parent¶
父收集器节点。
- path: pathlib.Path¶
此节点从中收集的文件系统路径(可以为 None)。
函数¶
- class Function[source]¶
基类:
PyobjMixin,Item负责设置和执行 Python 测试函数的项。
- 参数:
name – 完整的函数名称,包括由参数化添加的任何修饰(例如
my_func[my_param])。parent – 父节点。
config – pytest Config 对象。
callspec – 如果给定,此函数已参数化,并且 callspec 包含有关参数化的元信息。
callobj – 如果给定,当调用 Function 时将调用的对象,否则将使用
originalname从parent获取 callobj。keywords – 绑定到函数对象以进行“-k”匹配的关键字。
session – pytest Session 对象。
fixtureinfo – 此夹具节点已解析的夹具信息。
originalname – 用于访问底层函数对象的属性名称。默认为
name。如果名称与原始名称不同,请设置此项,例如当它包含由参数化添加的修饰时(my_func[my_param])。
- originalname¶
原始函数名称,不带任何修饰(例如参数化会在函数名称后添加
"[...]"后缀),用于从parent访问底层函数对象(如果未明确给定callobj)。版本 3.0 中添加。
- property function¶
底层 Python“函数”对象。
- property instance¶
函数绑定到的 Python 实例对象。
如果不是测试方法(例如独立的测试函数、类或模块),则返回 None。
- repr_failure(excinfo)[source]¶
返回收集或测试失败的表示。
另请参见
- 参数:
excinfo (ExceptionInfo[BaseException]) – 失败的异常信息。
- parent¶
父收集器节点。
- path: pathlib.Path¶
此节点从中收集的文件系统路径(可以为 None)。
函数定义¶
对象¶
调用信息¶
- final class CallInfo[source]¶
函数调用的结果/异常信息。
- excinfo: ExceptionInfo[BaseException] | None¶
如果调用引发异常,则为捕获的异常。
- 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收集报告对象。
报告可以包含任意的额外属性。
- longrepr: None | ExceptionInfo[BaseException] | tuple[str, int, str] | str | TerminalRepr¶
无或失败表示。
- result¶
收集到的项和收集节点。
- sections: list[tuple[str, str]]¶
字符串元组
(heading, content),包含用于测试报告的额外信息。pytest 用它来添加从stdout、stderr捕获的文本和截获的日志事件。其他插件也可以用它来向报告添加任意信息。
- property count_towards_summary: bool¶
实验性 此报告是否应计入测试会话结束时显示的总数:“1 passed, 1 failure, etc”。
注意
此函数被认为是实验性的,因此请注意,即使在补丁版本中也可能会更改。
配置¶
- final class Config[source]¶
访问配置值、插件管理器和插件钩子。
- 参数:
pluginmanager (PytestPluginManager) – 一个 pytest PluginManager。
invocation_params (InvocationParams) – 包含有关
pytest.main()调用的参数的对象。
- final class InvocationParams(*, args, plugins, dir)[source]¶
保存
pytest.main()期间传递的参数。对象属性是只读的。
版本 5.1 中添加。
注意
请注意,环境变量
PYTEST_ADDOPTS和addopts配置选项由 pytest 处理,不包含在args属性中。访问
InvocationParams的插件必须意识到这一点。- args: tuple[str, ...]¶
传递给
pytest.main()的命令行参数。
- dir: Path¶
调用
pytest.main()的目录。
- class ArgsSource(*values)[source]¶
指示测试参数的来源。
版本 7.2 中添加。
- ARGS = 1¶
命令行参数。
- INVOCATION_DIR = 2¶
调用目录。
- TESTPATHS = 3¶
“testpaths”配置值。
- option¶
以属性形式访问命令行选项。
- invocation_params¶
调用 pytest 的参数。
- 类型:
- pluginmanager¶
插件管理器处理插件注册和钩子调用。
- issue_config_time_warning(warning, stacklevel)[source]¶
在“配置”阶段发出并处理警告。
在
pytest_configure期间,我们无法使用catch_warnings_for_item函数捕获警告,因为不可能在pytest_configure周围设置钩子包装器。此函数主要用于需要在
pytest_configure(或类似阶段)期间发出警告的插件。
- getini(name)[source]¶
返回 配置文件 的配置值。
如果配置文件中未定义配置值,则返回通过
parser.addini注册配置时提供的default值。请注意,您可以提供None作为有效默认值。如果通过
parser.addini注册时未提供default,则将返回基于传递给parser.addini的type参数的默认值。基于type的默认值如下:paths、pathlist、args和linelist:空列表[]bool:Falsestring:空字符串""int:0float:0.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,如果指定了默认值,也将返回默认值而不是跳过。
- 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 -vprint(config.get_verbosity()) # 1 print(config.get_verbosity(Config.VERBOSITY_ASSERTIONS)) # 2
目录¶
- final class Dir[source]¶
文件系统目录中文件的收集器。
版本 8.0 中添加。
- classmethod from_parent(parent, *, path)[source]¶
公共构造函数。
- 参数:
parent (nodes.Collector) – 此 Dir 的父收集器。
path (pathlib.Path) – 目录的路径。
- parent¶
父收集器节点。
- path: pathlib.Path¶
此节点从中收集的文件系统路径(可以为 None)。
目录¶
- class Directory[source]¶
从目录收集文件的基类。
一个基本的目录收集器执行以下操作:遍历目录中的文件和子目录,并通过调用钩子
pytest_collect_directory和pytest_collect_file为它们创建收集器,在此之前检查它们是否未被pytest_ignore_collect忽略。版本 8.0 中添加。
- parent¶
父收集器节点。
- path: pathlib.Path¶
此节点从中收集的文件系统路径(可以为 None)。
异常信息¶
- 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__()。
- property value: E¶
异常值。
- property tb: TracebackType¶
异常原始回溯。
- property traceback: Traceback¶
回溯。
- exconly(tryshort=False)[source]¶
将异常作为字符串返回。
当 'tryshort' 解析为 True,且异常为 AssertionError 时,仅返回异常表示的实际异常部分(即从开头移除 'AssertionError: ')。
- 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¶
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时,它执行以下操作:如果仅以单个类作为其唯一的定位参数且没有额外的关键字参数进行调用,它会将标记附加到该类,以便自动应用于在该类中找到的所有测试用例。
如果仅以单个函数作为其唯一的定位参数且没有额外的关键字参数进行调用,它会将标记附加到该函数,其中包含已存储在
MarkDecorator内部的所有参数。在任何其他情况下进行调用时,它返回一个新的
MarkDecorator实例,其中原始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¶
Metafunc¶
- final class Metafunc[source]¶
传递给
pytest_generate_tests钩子的对象。它们有助于检查测试函数并根据测试配置或在定义测试函数的类或模块中指定的值生成测试。
- definition¶
- 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 应为string、int、float、bool或None类型。它们映射到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]¶
获取(或创建)一个命名选项组。
- 参数:
- 返回:
选项组。
- 返回类型:
返回的组对象有一个
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", ...)。
- 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 新增:
float和int类型。对于
paths和pathlist类型,它们被认为是相对于配置文件的。如果在没有定义配置文件的情况下执行,它们将被认为是相对于当前工作目录的(例如使用--override-ini)。版本 7.0 新增:
paths变量类型。版本 8.1 新增: 在没有配置文件的情况下,使用当前工作目录来解析
paths和pathlist。如果为
None或未传递,则默认为string。default (Any) – 如果不存在配置文件选项但被查询时的默认值。
此选项可以通过其他名称引用。别名解析为规范名称。
版本 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。
- 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加载模块。
- 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参数。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)): ...
- 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=True和flatten_subgroups=True,您可以在预期单个异常时完全匹配 except*。- 参数:
args –
任意数量的异常类型,
RaisesGroup或RaisesExc,用于指定此异常中包含的异常。所有指定的异常都必须存在于引发的组中,且不能有其他异常。如果您期望可变数量的异常,您需要使用
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,即使异常不在异常组内,它也会匹配。将此与
match、check或期望多个异常一起使用将引发错误。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。- 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¶
TestReport¶
- class TestReport[source]¶
基类:
BaseReport基本测试报告对象(如果设置和拆卸调用失败,也用于这些调用)。
报告可以包含任意的额外属性。
- location: tuple[str, int | None, str]¶
一个 (filesystempath, lineno, domaininfo) 元组,表示测试项的实际位置 - 它可能与收集到的位置不同,例如,如果方法继承自不同的模块。filesystempath 可以是相对于
config.rootdir的。行号是基于 0 的。
- longrepr: None | ExceptionInfo[BaseException] | tuple[str, int, str] | str | TerminalRepr¶
无或失败表示。
- user_properties¶
用户属性是一个包含测试用户定义属性的元组列表(名称,值)。
- sections: list[tuple[str, str]]¶
字符串元组
(heading, content),包含用于测试报告的额外信息。pytest 用它来添加从stdout、stderr捕获的文本和截获的日志事件。其他插件也可以用它来向报告添加任意信息。
- property count_towards_summary: bool¶
实验性 此报告是否应计入测试会话结束时显示的总数:“1 passed, 1 failure, etc”。
注意
此函数被认为是实验性的,因此请注意,即使在补丁版本中也可能会更改。
TestShortLogReport¶
Result¶
在 hook wrappers 中使用的 Result 对象,更多信息请参阅 pluggy 文档中的 Result。
Stash¶
- class Stash[source]¶
Stash是一种类型安全的异构可变映射,允许键和值类型与其创建位置(即Stash)分开定义。通常你会得到一个包含
Stash的对象,例如Config或Node。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 版本新增。
全局变量¶
pytest 在测试模块或 conftest.py 文件中定义某些全局变量时会以特殊方式处理。
- collect_ignore¶
教程: 自定义测试收集
可在 *conftest.py 文件*中声明,以排除测试目录或模块。需要是路径列表(str、pathlib.Path 或任何 os.PathLike)。
collect_ignore = ["setup.py"]
- collect_ignore_glob¶
教程: 自定义测试收集
可在 *conftest.py 文件*中声明,以使用 Unix shell 风格的通配符排除测试目录或模块。需要是 list[str],其中 str 可以包含 glob 模式。
collect_ignore_glob = ["*_ignore.py"]
- pytest_plugins¶
教程: 在测试模块或 conftest 文件中要求/加载插件
可在 *测试模块* 和 *conftest.py 文件* 的 **全局** 级别声明,以注册额外的插件。可以是 str 或 Sequence[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_COLOR 和 FORCE_COLOR。
- NO_COLOR¶
当设置为非空字符串时(无论其值如何),pytest 将不在终端输出中使用颜色。PY_COLORS 优先于 NO_COLOR,而 NO_COLOR 又优先于 FORCE_COLOR。有关支持此社区标准的其他库,请参阅 no-color.org。
- FORCE_COLOR¶
当设置为非空字符串时(无论其值如何),pytest 将在终端输出中使用颜色。PY_COLORS 和 NO_COLOR 优先于 FORCE_COLOR。
异常¶
- final exception FixtureLookupError[source]¶
基类:
LookupError无法返回请求的 fixture (缺少或无效)。
警告¶
在某些情况下(例如不当使用或已弃用功能)生成的自定义警告。
- class PytestWarning¶
基类:
UserWarningpytest 发出的所有警告的基类。
- class PytestAssertRewriteWarning¶
基类:
PytestWarningpytest 断言重写模块发出的警告。
- 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¶
-
pytest 9 中将移除的功能的警告类。
- class PytestUnknownMarkWarning¶
基类:
PytestWarning使用未知标记时发出的警告。
详情请参阅 如何用属性标记测试函数。
- class PytestUnraisableExceptionWarning¶
基类:
PytestWarning报告了一个无法引发的异常。
无法引发的异常是在
__del__实现和类似情况下引发的异常,当异常无法正常引发时。
- class PytestUnhandledThreadExceptionWarning¶
基类:
PytestWarning在
Thread中发生了未处理的异常。此类异常不会正常传播。
有关更多信息,请查阅文档中的 内部 pytest 警告 部分。
配置选项¶
以下是可写入 pytest.ini(或 .pytest.ini)、pyproject.toml、tox.ini 或 setup.cfg 文件中的内置配置选项列表,这些文件通常位于您的仓库根目录。
要详细了解每种文件格式,请参阅 配置文件格式。
警告
不建议使用 setup.cfg,除非是非常简单的用例。.cfg 文件使用的解析器与 pytest.ini 和 tox.ini 不同,这可能会导致难以追踪的问题。如果可能,建议使用后者文件,或 pytest.toml 或 pyproject.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
默认值:
truepytest 传统上即使类/函数是从另一个文件导入的,也会在测试模块命名空间中收集它们。
例如
# 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。
- 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 版本中更改: 添加了
log、all、out-err选项。配置是否将捕获的输出写入 JUnit XML 文件。有效值为
log: 仅写入捕获的logging输出。system-out: 写入捕获的stdout内容。system-err: 写入捕获的stderr内容。out-err: 写入捕获的stdout和stderr内容。all: 写入捕获的logging、stdout和stderr内容。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()调用传递 kwargextra={"auto_indent": [value]},以指定日志中特定条目的自动缩进行为。extrakwarg 覆盖命令行或配置中指定的值。
- 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 添加
0、1等来自动处理此问题,使它们唯一。[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 的其他方法,请参阅
parametrize和pytest.param()。
- strict_xfail¶
如果设置为
true,则默认情况下,标记为@pytest.mark.xfail但实际成功的测试将使测试套件失败。有关详细信息,请参阅 strict 参数。[pytest] strict_xfail = true
[pytest] strict_xfail = true
您还可以通过
strict选项启用此选项。版本 9.0 中的更改: 从
xfail_strict重命名为strict_xfail。xfail_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_pathfixture 创建的目录会根据测试结果保留。all: 保留所有测试的目录,无论结果如何。failed: 仅保留结果为error或failed的测试的目录。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