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 的容差支持,我们建议使用 Test support (numpy.testing) 中的专用测试辅助函数。注意
与内置的相等性不同,此函数认为布尔值不等于数值零或一。例如
>>> 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])[source]¶
以给定消息显式地使正在执行的测试失败。
- 参数:
- 引发:
pytest.fail.Exception – 引发的异常。
- class pytest.fail.Exception¶
由
pytest.fail()
引发的异常。
pytest.skip¶
- skip(reason[, allow_module_level=False])[source]¶
以给定消息跳过正在执行的测试。
此函数只能在测试期间(setup、call 或 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.importorskip 关于 ImportError 的默认行为 的详细信息,请参阅。
- 返回:
导入的模块。这应该分配给其规范名称。
- 引发:
pytest.skip.Exception – 如果无法导入模块。
- 返回类型:
示例
docutils = pytest.importorskip("docutils")
8.2 版本新增:
exc_type
参数。
pytest.xfail¶
- xfail(reason='')[source]¶
以给定原因强制 xfail 正在执行的测试或 setup 函数。
此函数只能在测试期间(setup、call 或 teardown)调用。
使用
xfail()
后不执行其他代码(它通过内部引发异常实现)。- 参数:
reason (str) – 作为 xfail 原因显示给用户的消息。
注意
尽可能使用 pytest.mark.xfail 标记来声明在某些条件(如已知错误或缺失功能)下 xfail 测试。
- 引发:
pytest.xfail.Exception – 引发的异常。
- class pytest.xfail.Exception¶
由
pytest.xfail()
引发的异常。
pytest.exit¶
- exit(reason[, returncode=None])[source]¶
退出测试过程。
- 参数:
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 调用或参数化的 fixtures 中指定参数。
@pytest.mark.parametrize( "test_input,expected", [ ("3+5", 8), pytest.param("6*9", 42, marks=pytest.mark.xfail), ], ) def test_eval(test_input, expected): assert eval(test_input) == expected
- 参数:
values (object) – 参数集值的可变参数,按顺序排列。
marks (MarkDecorator | Collection[MarkDecorator | Mark]) –
要应用于此参数集的单个标记或标记列表。
不能通过此参数添加 pytest.mark.usefixtures。
id (str | Literal[pytest.HIDDEN_PARAM] | None) –
为此参数集分配的 ID。
8.4 版本新增: pytest.HIDDEN_PARAM 表示从测试名称中隐藏参数集。最多只能使用 1 次,因为测试名称需要是唯一的。
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) –
如果指定,则为包含正则表达式的字符串或正则表达式对象,它将使用
re.search()
与异常的字符串表示及其PEP 678__notes__
进行测试。要匹配可能包含特殊字符的字面字符串,可以首先使用
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¶
- 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
标记¶
标记可用于将元数据应用于 测试函数(但不能应用于 fixtures),然后 fixtures 或插件可以访问这些元数据。
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=xfail_strict)¶
- 参数:
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
,但如果它意外通过,则将导致测试套件 失败。这对于标记总是失败的函数特别有用,如果它们意外地开始通过(例如,某个库的新版本修复了已知错误),则应该有明确的指示。
默认为
xfail_strict
,其默认值为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
语句后面的代码块将作为 teardown 代码执行,无论测试结果如何,并且必须精确地 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)¶
在测试期间设置日志记录器的阈值级别。
严重程度低于此级别的日志消息将不会被捕获。
在 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(capsys): 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¶
教程: 如何运行 doctests
- doctest_namespace()[source]¶
返回一个
dict
,该字典将被注入到 doctest 命名空间中的夹具。通常,此夹具与另一个
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]¶
一个方便的辅助类,用于对属性/项/环境变量/syspath 进行猴子补丁。
由
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 本身的
stdlib
函数(有关示例,请参见 #3290)。
- setattr(target: str, name: object, value: ~_pytest.monkeypatch.Notset = <notset>, raising: bool = True) None ¶
- setattr(target: object, name: str, value: object, raising: bool = True) None
在目标上设置属性值,并记住旧值。
例如
import os monkeypatch.setattr(os, "getcwd", lambda: "/")
上述代码将
os.getcwd()
函数替换为始终返回"/"
的lambda
。为方便起见,您可以将字符串指定为
target
,它将被解释为带点导入路径,其中最后一部分是属性名称monkeypatch.setattr("os.getcwd", lambda: "/")
如果属性不存在,则引发
AttributeError
,除非raising
设置为 False。在哪里打补丁
monkeypatch.setattr
的工作原理是(临时)将名称指向的对象更改为另一个对象。可能有很多名称指向任何单个对象,因此要使补丁生效,您必须确保对被测系统使用的名称进行补丁。有关完整解释,请参阅
unittest.mock
文档中的 在哪里打补丁 部分,该部分是为unittest.mock.patch()
编写的,但也适用于monkeypatch.setattr
。
- delattr(target, name=<notset>, raising=True)¶
从
target
中删除属性name
。如果未指定
name
且target
是字符串,它将被解释为带点导入路径,其中最后一部分是属性名称。如果属性不存在,则引发 AttributeError,除非
raising
设置为 False。
- setitem(dic, name, value)¶
将字典条目
name
设置为值。
- delitem(dic, name, raising=True)¶
从字典中删除
name
。如果它不存在,则引发
KeyError
,除非raising
设置为 False。
- setenv(name, value, prepend=None)¶
将环境变量
name
设置为value
。如果
prepend
是一个字符,则读取当前环境变量值,并将其与prepend
字符连接起来,前置到value
。
- delenv(name, raising=True)¶
从环境中删除
name
。如果它不存在,则引发
KeyError
,除非raising
设置为 False。
- syspath_prepend(path)¶
将
path
前置到sys.path
导入位置列表。
pytestconfig¶
- pytestconfig()¶
会话范围的夹具,返回会话的
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¶
用于编写测试/配置文件、独立执行 pytest 和匹配预期输出的设施,非常适合 pytest 插件的黑盒测试。
它尽量隔离测试运行与外部因素,在初始化期间将当前工作目录更改为
path
并修改环境变量。- exception TimeoutExpired¶
- plugins: list[str | object]¶
与
parseconfig()
和runpytest()
一起使用的插件列表。最初这是一个空列表,但可以向列表中添加插件。要添加到列表中的项目类型取决于使用它们的方法,因此请参阅它们以获取详细信息。
- make_hook_recorder(pluginmanager)¶
为
PytestPluginManager
创建一个新的HookRecorder
。
- chdir()¶
进入临时目录。
这在实例化时自动完成。
- makefile(ext, *args, **kwargs)¶
在测试目录中创建新的文本文件。
- 参数:
- 返回:
创建的第一个文件。
- 返回类型:
示例
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]¶
.makefile()的快捷方式,带有.py扩展名。
默认为带有“.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]¶
.makefile()的快捷方式,带有.txt扩展名。
默认为带有“.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
,确保当前工作目录在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¶
从stdout捕获的行列表。
- errlines¶
从stderr捕获的行列表。
- stdout¶
stdout的
LineMatcher
。例如,使用
str(stdout)
来重建stdout,或使用常用的stdout.fnmatch_lines()
方法。
- stderr¶
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_testsuite_property¶
教程: 记录测试套件属性
- record_testsuite_property()[source]¶
将新的
<property>
标签记录为根<testsuite>
的子标签。这适用于编写关于整个测试套件的全局信息,并与
xunit2
JUnit系列兼容。这是一个
session
作用域的夹具,通过(name, value)
调用。示例:def test_foo(record_testsuite_property): record_testsuite_property("ARCH", "PPC") record_testsuite_property("STORAGE_TYPE", "CEPH")
- 参数:
name – 属性名称。
value – 属性值。将被转换为字符串。
警告
目前此夹具不适用于pytest-xdist插件。详情请参阅#7767。
recwarn¶
教程: 记录警告
- recwarn()[source]¶
返回一个
WarningsRecorder
实例,该实例记录测试函数发出的所有警告。有关警告类别的信息,请参阅如何捕获警告。
- class WarningsRecorder[source]¶
一个上下文管理器,用于记录引发的警告。
每个记录的警告都是
warnings.WarningMessage
的一个实例。改编自
warnings.catch_warnings
。注意
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 – 如果找不到给定夹具。
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
的一个实例
- final class TempPathFactory[source]¶
通用基本临时目录下的临时目录工厂,如 临时目录位置和保留期 中所述。
tmpdir¶
教程: tmpdir 和 tmpdir_factory 固定装置
- tmpdir()¶
返回一个临时目录(作为 legacy_path 对象),该目录对于每个测试函数调用都是唯一的。临时目录创建为基本临时目录的子目录,具有可配置的保留期,详见 临时目录位置和保留期。
tmpdir_factory¶
教程: tmpdir 和 tmpdir_factory 固定装置
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 插件中使用¶
此钩子仅针对 初始 conftests 调用。
初始化钩子¶
为插件和 conftest.py
文件调用的初始化钩子。
- pytest_addoption(parser, pluginmanager)[source]¶
注册 argparse 风格的选项和 ini 风格的配置值,在测试运行开始时调用一次。
- 参数:
parser (Parser) – 要添加命令行选项,请调用
parser.addoption(...)
。要添加 ini 文件值,请调用parser.addini(...)
。pluginmanager (PytestPluginManager) – pytest 插件管理器,可用于安装
hookspec()
或hookimpl()
,并允许一个插件调用另一个插件的钩子以更改命令行选项的添加方式。
选项以后可以通过
config
对象访问,分别通过:config.getoption(name)
获取命令行选项的值。config.getini(name)
获取从 ini 风格文件中读取的值。
config 对象通过
.config
属性传递给许多内部对象,或者可以作为pytestconfig
固定装置检索。注意
此钩子与钩子包装器不兼容。
在 conftest 插件中使用¶
如果 conftest 插件实现此钩子,它将在 conftest 注册时立即被调用。
此钩子仅针对 初始 conftests 调用。
- 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 插件中使用¶
此钩子仅针对 初始 conftests 调用。
- 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 插件中使用¶
此钩子仅针对 初始 conftests 调用。
- 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 协议,除非收集失败或设置了collectonly
pytest 选项。如果在任何时候调用
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)
- 调用阶段,如果设置成功且未设置
setuponly
pytest 选项 call = pytest_runtest_call(item)
(封装在CallInfo(when="call")
中)report = pytest_runtest_makereport(item, call)
pytest_runtest_logreport(report)
如果发生交互式异常,则为
pytest_exception_interact(call, report)
- 调用阶段,如果设置成功且未设置
- 拆卸阶段
call = pytest_runtest_teardown(item, nextitem)
(包装在CallInfo(when="teardown")
中)report = pytest_runtest_makereport(item, call)
pytest_runtest_logreport(report)
如果发生交互式异常,则为
pytest_exception_interact(call, report)
pytest_runtest_logfinish(nodeid, location)
在第一个非 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()
。这包括获取项所需的(尚未获取的)fixture 值。- 参数:
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()
。这包括运行项所需的 fixture 的拆卸阶段(如果它们超出范围)。- 参数:
在 conftest 插件中使用¶
任何 conftest 文件都可以实现此钩子。对于给定的项,只考虑该项所在目录及其父目录中的 conftest 文件。
- pytest_runtest_makereport(item, call)[source]¶
调用以创建
TestReport
,用于测试项的 setup、call 和 teardown runtest 阶段。有关 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 插件中使用¶
此钩子仅针对 初始 conftests 调用。
- 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]¶
执行 fixture 设置。
- 参数:
fixturedef (FixtureDef[Any]) – fixture 定义对象。
request (SubRequest) – fixture 请求对象。
- 返回:
调用 fixture 函数的返回值。
- 返回类型:
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]) – fixture 定义对象。
request (SubRequest) – fixture 请求对象。
在 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
ini 文件选项显式启用[pytest] enable_assertion_pass_hook=true
启用此选项时,您需要清理项目目录和解释器库中的 .pyc 文件,因为断言将需要重新写入。
- 参数:
在 conftest 插件中使用¶
任何 conftest 文件都可以实现此钩子。对于给定的项,只考虑该项所在目录及其父目录中的 conftest 文件。
调试/交互钩子¶
有少数钩子可用于特殊报告或与异常交互
- pytest_internalerror(excrepr, excinfo)[source]¶
为内部错误调用。
返回 True 以抑制直接打印 INTERNALERROR 消息到 sys.stderr 的回退处理。
- 参数:
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]¶
基类:
ABC
Collector
和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]¶
Node 的公共构造函数。
引入此间接是为了能够从节点构造函数中移除脆弱的逻辑。
子类在覆盖构造时可以使用
super().from_parent(...)
。- 参数:
parent (Node) – 此 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 [source]¶
- get_closest_marker(name: str, default: Mark) Mark
返回与名称匹配的第一个标记,从最近级别(例如函数)到更远级别(例如模块级别)。
- 参数:
default – 如果未找到标记,则作为备用返回值。
name – 用于过滤的名称。
- addfinalizer(fin)[source]¶
注册一个函数,当此节点被终结时,不带参数地调用它。
此方法只能在此节点在 setup 链中处于活动状态时调用,例如在 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]¶
添加一个新的报告部分,类似于内部用于添加标准输出和标准错误捕获输出的方式
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]¶
基类:
PyCollector
用于收集 Python 类中测试方法(和嵌套类)的收集器。
- parent¶
父收集器节点。
- path: pathlib.Path¶
此节点从中收集到的文件系统路径(可能为 None)。
函数¶
- class Function[source]¶
基类:
PyobjMixin
,Item
负责设置和执行 Python 测试函数的项。
- 参数:
name – 完整的函数名称,包括任何装饰,例如参数化添加的装饰(
my_func[my_param]
)。parent – 父节点。
config – pytest Config 对象。
callspec – 如果给定,此函数已参数化,并且 callspec 包含有关参数化的元信息。
callobj – 如果给定,当 Function 被调用时将调用的对象,否则将从
parent
使用originalname
获取 callobj。keywords – 绑定到函数对象用于“-k”匹配的关键字。
session – pytest Session 对象。
fixtureinfo – 此 fixture 节点上已解析的 fixture 信息。
originalname – 用于访问底层函数对象的属性名称。默认为
name
。如果名称与原始名称不同,请设置此项,例如当它包含参数化添加的装饰时(my_func[my_param]
)。
- originalname¶
原始函数名称,不带任何装饰(例如参数化会在函数名称中添加“[...]”后缀),用于从
parent
访问底层函数对象(如果未明确给定callobj
)。3.0 版本新增。
- property function¶
底层 Python ‘function’ 对象。
- property instance¶
函数绑定到的 Python 实例对象。
如果不是测试方法,例如独立的测试函数、类或模块,则返回 None。
- repr_failure(excinfo)[source]¶
返回收集或测试失败的表示。
另请参阅
- 参数:
excinfo (ExceptionInfo[BaseException]) – 失败的异常信息。
- parent¶
父收集器节点。
- path: pathlib.Path¶
此节点从中收集到的文件系统路径(可能为 None)。
函数定义¶
对象¶
可从 fixture 或 钩子 访问或从 pytest
导入的对象。
CallInfo¶
- 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 中。
CollectReport¶
- final class CollectReport[source]¶
基类:
BaseReport
收集报告对象。
报告可以包含任意额外的属性。
- longrepr: None | ExceptionInfo[BaseException] | tuple[str, int, str] | str | TerminalRepr¶
None 或失败表示。
- 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 插件管理器。
invocation_params (InvocationParams) – 包含有关
pytest.main()
调用参数的对象。
- final class InvocationParams(*, args, plugins, dir)[source]¶
保存调用
pytest.main()
时传递的参数。对象属性为只读。
5.1 版本新增。
注意
请注意,环境变量
PYTEST_ADDOPTS
和addopts
ini 选项由 pytest 处理,不包含在args
属性中。访问
InvocationParams
的插件必须意识到这一点。- args: tuple[str, ...]¶
传递给
pytest.main()
的命令行参数。
- dir: Path¶
调用
pytest.main()
的目录。:type: pathlib.Path
- 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]¶
在“configure”阶段发出并处理警告。
在
pytest_configure
期间,我们无法使用catch_warnings_for_item
函数捕获警告,因为无法在pytest_configure
周围使用钩子包装器。此函数主要用于需要在
pytest_configure
(或类似阶段)期间发出警告的插件。
- getini(name)[source]¶
从 ini 文件 返回配置值。
如果配置文件中未定义某个配置值,则将返回通过
parser.addini
注册配置时提供的default
值。请注意,您甚至可以提供None
作为有效的默认值。如果使用
parser.addini
注册时未提供default
,则会根据传递给parser.addini
的type
参数返回一个默认值。基于type
的默认值如下:paths
、pathlist
、args
和linelist
:空列表[]
;bool
:False
;string
:空字符串""
;int
:0
;float
: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
)。
- get_verbosity(verbosity_type=None)[source]¶
检索细粒度详细程度类型的详细级别。
- 参数:
verbosity_type (str | None) – 要获取级别的详细程度类型。如果为给定类型配置了级别,则将返回该值。如果给定类型不是已知的详细程度类型,则将返回全局详细程度级别。如果给定类型为 None(默认值),则将返回全局详细程度级别。
要为细粒度详细程度类型配置级别,配置文件应包含配置名称的设置和详细程度级别的数字值。特殊值“auto”可用于显式使用全局详细程度级别。
示例
# content of pytest.ini [pytest] verbosity_assertions = 2
pytest -v
print(config.get_verbosity()) # 1 print(config.get_verbosity(Config.VERBOSITY_ASSERTIONS)) # 2
Dir¶
- final class Dir[source]¶
文件系统目录中的文件收集器。
8.0 版本新增。
- classmethod from_parent(parent, *, path)[source]¶
公共构造函数。
- 参数:
parent (nodes.Collector) – 此 Dir 的父收集器。
path (pathlib.Path) – 目录的路径。
- parent¶
父收集器节点。
- path: pathlib.Path¶
此节点从中收集到的文件系统路径(可能为 None)。
Directory¶
- class Directory[source]¶
从目录收集文件的基类。
一个基本的目录收集器执行以下操作:遍历目录中的文件和子目录,并检查它们是否未被
pytest_ignore_collect
忽略后,通过调用钩子pytest_collect_directory
和pytest_collect_file
为它们创建收集器。8.0 版本新增。
- parent¶
父收集器节点。
- path: pathlib.Path¶
此节点从中收集到的文件系统路径(可能为 None)。
ExceptionInfo¶
- final class ExceptionInfo[source]¶
包装 sys.exc_info() 对象并提供导航 traceback 的帮助。
- 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]¶
返回与当前 traceback 匹配的 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]) –
回溯条目的过滤器。
如果为 false,则不隐藏任何条目。
如果为 true,则隐藏内部条目和包含局部变量
__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¶
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 表示从测试名称中隐藏参数集。最多只能使用 1 次,因为测试名称需要是唯一的。
如果它是可调用对象,则会为
argvalues
中的每个条目调用它,并且返回值用作整个集合自动生成 ID 的一部分(其中各部分用破折号(“-”)连接)。这对于为某些项目(例如日期)提供更具体的 ID 很有用。返回None
将使用自动生成的 ID。如果未提供 ID,将根据 argvalues 自动生成。
scope (Literal['session', 'package', 'module', 'class', 'function'] | None) – 如果指定,则表示参数的范围。范围用于按参数实例对测试进行分组。它还将覆盖任何夹具函数定义的范围,允许使用测试上下文或配置设置动态范围。
Parser¶
- final class Parser[source]¶
命令行参数和 ini 文件值的解析器。
- 变量:
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>)[source]¶
注册一个 ini 文件选项。
- 参数:
name (str) – ini 变量的名称。
type (Literal['string', 'paths', 'pathlist', 'args', 'linelist', 'bool'] | None) –
变量类型。可以是
string
:一个字符串bool
:一个布尔值args
:一个字符串列表,如 shell 中分隔linelist
:一个字符串列表,按行分隔paths
:一个pathlib.Path
列表,如 shell 中分隔pathlist
:一个py.path
列表,如 shell 中分隔int
:一个整数float
:一个浮点数
版本 8.4 新增:
float
和int
类型。对于
paths
和pathlist
类型,它们被视为相对于 ini 文件。如果执行时未定义 ini 文件,它们将被视为相对于当前工作目录(例如使用--override-ini
)。版本 7.0 新增:
paths
变量类型。版本 8.1 新增: 在没有 ini 文件的情况下,使用当前工作目录解析
paths
和pathlist
。如果为
None
或未传递,则默认为string
。default (Any) – 如果 ini 文件选项不存在但被查询,则为默认值。
ini 变量的值可以通过调用
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]¶
-
一个具有额外 pytest 特有功能的
pluggy.PluginManager
从命令行、
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¶
项目名称。
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
参数。
- :kwparam str | Pattern[str] match
要匹配的正则表达式。
- 参数:
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) –
如果指定,则是一个包含正则表达式的字符串或正则表达式对象,它将使用
re.search()
对异常组的字符串表示及其 PEP 678__notes__
进行测试。要匹配可能包含特殊字符的字面字符串,可以首先使用
re.escape()
对模式进行转义。请注意,“ (5 subgroups)”将在匹配前从
repr
中移除。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¶
- final class TestReport[source]¶
基类:
BaseReport
基本测试报告对象(如果 setup 和 teardown 调用失败,也会使用此对象)。
报告可以包含任意额外的属性。
- location: tuple[str, int | None, str]¶
一个 (filesystempath, lineno, domaininfo) 元组,表示测试项的实际位置——它可能与收集到的位置不同,例如如果方法是从不同的模块继承的。filesystempath 可以是相对于
config.rootdir
的相对路径。行号是基于 0 的。
- longrepr: None | ExceptionInfo[BaseException] | tuple[str, int, str] | str | TerminalRepr¶
None 或失败表示。
- user_properties¶
用户属性是一个 (名称, 值) 元组列表,其中包含测试的用户定义属性。
- sections: list[tuple[str, str]]¶
包含测试报告额外信息的字符串元组
(heading, content)
。pytest 使用它来添加从stdout
、stderr
捕获的文本和拦截的日志事件。其他插件可以使用它向报告添加任意信息。
- property count_towards_summary: bool¶
实验性 此报告是否应计入测试会话结束时显示的总数:“1 passed, 1 failure, etc”。
注意
此函数被认为是实验性的,因此请注意,它即使在补丁发布中也可能会发生变化。
TestShortLogReport¶
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 版本新增。
全局变量¶
当在测试模块或 conftest.py
文件中定义时,pytest 会以特殊方式处理一些全局变量。
- 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.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 进程中运行。是 BUILD_NUMBER
变量的替代方案。另请参阅 CI 流水线。
- BUILD_NUMBER¶
设置后(无论值如何),pytest 都会识别正在 CI 进程中运行。是 CI 变量的替代方案。另请参阅 CI 流水线。
- 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
等夹具生成的临时目录的根目录,如 临时目录位置和保留 中所述。
- 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¶
基类:
UserWarning
pytest 发出的所有警告的基类。
- class PytestAssertRewriteWarning¶
-
pytest 断言重写模块发出的警告。
- class PytestCacheWarning¶
-
缓存插件在各种情况下发出的警告。
- class PytestCollectionWarning¶
-
当 pytest 无法收集模块中的文件或符号时发出的警告。
- class PytestConfigWarning¶
-
为配置问题发出的警告。
- class PytestDeprecationWarning¶
基类:
PytestWarning
,DeprecationWarning
针对未来版本中将移除的功能的警告类。
- class PytestExperimentalApiWarning¶
基类:
PytestWarning
,FutureWarning
用于表示 pytest 实验的警告类别。
请谨慎使用,因为 API 可能会在未来版本中更改甚至完全移除。
- class PytestRemovedIn9Warning¶
-
用于将在 pytest 9 中移除的功能的警告类。
- class PytestUnknownMarkWarning¶
-
使用未知标记时发出的警告。
有关详细信息,请参阅如何使用属性标记测试函数。
有关更多信息,请查阅文档中的内部 pytest 警告部分。
配置选项¶
以下是可以在 pytest.ini
(或 .pytest.ini
)、pyproject.toml
、tox.ini
或 setup.cfg
文件中写入的内置配置选项列表,这些文件通常位于您的仓库根目录。
要查看每种文件格式的详细信息,请参阅配置文件格式。
警告
不建议使用 setup.cfg
,除非是非常简单的用例。.cfg
文件使用的解析器与 pytest.ini
和 tox.ini
不同,这可能会导致难以追踪的问题。如果可能,建议使用后两者文件或 pyproject.toml
来保存您的 pytest 配置。
配置选项可以通过命令行使用 -o/--override-ini
进行覆盖,该选项也可以多次传递。预期格式为 name=value
。例如
pytest -o console_output_style=classic -o cache_dir=/tmp/mycache
- addopts¶
将指定的
OPTS
添加到命令行参数集中,就像用户指定了它们一样。示例:如果您有此 ini 文件内容# content of pytest.ini [pytest] addopts = --maxfail=2 -rf # 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
默认值:
true
pytest 传统上会收集测试模块命名空间中的类/函数,即使它们是从其他文件导入的。
例如
# contents of src/domain.py class Testament: ... # contents of tests/test_testament.py from domain import Testament def test_testament(): ...
在这种情况下,使用默认选项,pytest 将从
tests/test_testament.py
中收集Testament
类,因为它以Test
开头,即使在这种情况下,它是一个被导入到测试模块命名空间中的生产类。在配置文件中将
collected_imported_tests
设置为false
可以防止这种情况发生。
- consider_namespace_packages¶
控制 pytest 在收集 Python 模块时是否尝试识别命名空间包。默认值为
False
。如果您正在测试的包是命名空间包的一部分,请设置为
True
。8.1 版本新增。
- console_output_style¶
设置运行测试时的控制台输出样式
classic
:经典 pytest 输出。progress
:类似于经典 pytest 输出,但带有进度指示器。progress-even-when-capture-no
:即使在capture=no
时也允许使用进度指示器。count
:类似于进度指示器,但显示已完成测试的数量而不是百分比。times
:显示测试持续时间。
默认值为
progress
,但如果您愿意,或者新模式导致了意外问题,您可以回退到classic
# content of pytest.ini [pytest] console_output_style = classic
- disable_test_id_escaping_and_forfeit_all_rights_to_community_support¶
在 4.4 版中新增。
pytest 默认会转义用于参数化的 Unicode 字符串中的任何非 ASCII 字符,因为它有几个缺点。但是,如果您想在参数化中使用 Unicode 字符串并在终端中原样(未转义)查看它们,请在您的
pytest.ini
中使用此选项。[pytest] disable_test_id_escaping_and_forfeit_all_rights_to_community_support = True
但是请记住,这可能会根据所使用的操作系统和当前安装的插件导致不必要的副作用甚至错误,因此请自行承担风险使用。
默认值:
False
。
- doctest_encoding¶
用于解码带有文档字符串的文本文件的默认编码。查看 pytest 如何处理 doctest。
- doctest_optionflags¶
来自标准
doctest
模块的一个或多个 doctest 标志名称。查看 pytest 如何处理 doctest。
- empty_parameter_set_mark¶
允许为参数化中的空参数集选择操作
skip
:跳过带有空参数集的测试(默认)xfail
:将带有空参数集的测试标记为 xfail(run=False)fail_at_collect
:如果参数化收集到空参数集,则引发异常
# content of pytest.ini [pytest] empty_parameter_set_mark = xfail
注意
此选项的默认值计划在未来版本中更改为
xfail
,因为这被认为更不容易出错,有关详细信息,请参阅#3155。
- faulthandler_timeout¶
如果测试运行时间超过
X
秒(包括 fixture 设置和 teardown),则转储所有线程的堆栈跟踪。使用faulthandler.dump_traceback_later()
函数实现,因此其中的所有注意事项均适用。# content of pytest.ini [pytest] faulthandler_timeout=5
有关更多信息,请参阅故障处理器。
- filterwarnings¶
设置一个过滤器和操作列表,用于处理匹配的警告。默认情况下,测试会话期间发出的所有警告将在测试会话结束时在摘要中显示。
# content of pytest.ini [pytest] filterwarnings = error ignore::DeprecationWarning
这会告诉 pytest 忽略弃用警告,并将所有其他警告转换为错误。有关更多信息,请参阅如何捕获警告。
- junit_duration_report¶
在 4.1 版中新增。
配置持续时间如何记录到 JUnit XML 报告中
total
(默认):报告的持续时间包括 setup、call 和 teardown 时间。call
:报告的持续时间仅包括 call 时间,不包括 setup 和 teardown。
[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
- 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
- junit_log_passing_tests¶
在 4.6 版中新增。
如果
junit_logging != "no"
,则配置是否将捕获的输出写入 JUnit XML 文件,用于通过的测试。默认值为True
。[pytest] junit_log_passing_tests = False
- junit_suite_name¶
要设置根测试套件 XML 项的名称,您可以在配置文件中配置
junit_suite_name
选项[pytest] junit_suite_name = my_suite
- log_auto_indent¶
允许选择性地自动缩进多行日志消息。
支持命令行选项
--log-auto-indent [value]
和配置选项log_auto_indent = [value]
,以设置所有日志记录的自动缩进行为。[value]
可以是True 或“On” - 动态自动缩进多行日志消息
False 或“Off”或 0 - 不自动缩进多行日志消息(默认行为)
[正整数] - 将多行日志消息自动缩进 [value] 个空格
[pytest] log_auto_indent = False
支持将关键字参数
extra={"auto_indent": [value]}
传递给logging.log()
调用,以指定日志中特定条目的自动缩进行为。extra
关键字参数会覆盖命令行或配置文件中指定的值。
- log_cli_date_format¶
设置一个与
time.strftime()
兼容的字符串,用于实时日志的日期格式化。[pytest] log_cli_date_format = %Y-%m-%d %H:%M:%S
有关更多信息,请参阅实时日志。
- log_cli_format¶
设置一个与
logging
兼容的字符串,用于格式化实时日志消息。[pytest] log_cli_format = %(asctime)s %(levelname)s %(message)s
有关更多信息,请参阅实时日志。
- log_date_format¶
设置一个与
time.strftime()
兼容的字符串,用于格式化日志捕获的日期。[pytest] log_date_format = %Y-%m-%d %H:%M:%S
有关更多信息,请参阅如何管理日志记录。
- log_file¶
设置一个相对于当前工作目录的文件名,日志消息将写入该文件,此外还会写入其他活动的日志记录设施。
[pytest] log_file = logs/pytest-logs.txt
有关更多信息,请参阅如何管理日志记录。
- log_file_date_format¶
设置一个与
time.strftime()
兼容的字符串,用于格式化日志文件的日期。[pytest] log_file_date_format = %Y-%m-%d %H:%M:%S
有关更多信息,请参阅如何管理日志记录。
- log_file_format¶
设置一个与
logging
兼容的字符串,用于格式化重定向到日志文件的日志消息。[pytest] log_file_format = %(asctime)s %(levelname)s %(message)s
有关更多信息,请参阅如何管理日志记录。
- log_format¶
设置一个与
logging
兼容的字符串,用于格式化捕获的日志消息。[pytest] log_format = %(asctime)s %(levelname)s %(message)s
有关更多信息,请参阅如何管理日志记录。
- markers¶
当使用
--strict-markers
或--strict
命令行参数时,只允许使用已知标记(由核心 pytest 或某些插件在代码中定义的标记)。您可以在此设置中列出其他标记以将其添加到白名单中,在这种情况下,您可能希望将
--strict-markers
添加到addopts
中以避免未来的回归。[pytest] addopts = --strict-markers markers = slow serial
注意
强烈建议使用
--strict-markers
。--strict
仅为向后兼容性而保留,可能对其他人造成混淆,因为它只适用于标记而不适用于其他选项。
- minversion¶
指定运行测试所需的最低 pytest 版本。
# content of pytest.ini [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
不要查看典型的 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
请注意,
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
默认情况下,匹配
test_*.py
和*_test.py
的文件将被视为测试模块。
- python_functions¶
一个或多个名称前缀或 glob 模式,用于确定哪些测试函数和方法被视为测试。通过在模式之间添加空格来搜索多个 glob 模式。默认情况下,pytest 将任何以
test
为前缀的函数视为测试。以下是如何收集以_test
结尾的测试函数和方法的示例[pytest] python_functions = *_test
请注意,这对于
unittest.TestCase
派生类上的方法没有影响,因为unittest
自己的收集框架用于收集这些测试。有关更多详细示例,请参阅更改命名约定。
- pythonpath¶
设置应添加到 Python 搜索路径的目录列表。目录将添加到
sys.path
的开头。与PYTHONPATH
环境变量类似,这些目录将包含在 Python 查找导入模块的位置中。路径是相对于rootdir目录的。目录在测试会话期间保持在路径中。[pytest] pythonpath = src1 src2
- required_plugins¶
一个空格分隔的插件列表,这些插件必须存在才能运行 pytest。插件可以列出,其名称后面可以直接带或不带版本说明符。不同的版本说明符之间不允许有空格。如果未找到任何一个插件,则会发出错误。
[pytest] required_plugins = pytest-django>=3.0.0,<4.0.0 pytest-html pytest-xdist>=1.0.0
- testpaths¶
设置在从rootdir目录执行 pytest 时,当命令行中未给出特定目录、文件或测试 ID 时,应搜索测试的目录列表。文件系统路径可以使用 shell 风格的通配符,包括递归的
**
模式。当所有项目测试都位于已知位置时非常有用,可以加快测试收集速度并避免意外收集到不想要的测试。
[pytest] testpaths = testing doc
此配置意味着执行
pytest
具有与执行以下命令相同的实际效果
pytest testing doc
- tmp_path_retention_count¶
根据
tmp_path_retention_policy
,我们应该保留多少个tmp_path
目录的会话。[pytest] tmp_path_retention_count = 3
默认值:
3
- tmp_path_retention_policy¶
控制
tmp_path
fixture 创建的哪些目录根据测试结果保留。all
:保留所有测试的目录,无论结果如何。failed
:仅保留结果为error
或failed
的测试的目录。none
:目录在每个测试结束后总是被删除,无论结果如何。
[pytest] tmp_path_retention_policy = all
默认值:
all
- truncation_limit_chars¶
控制断言消息内容截断的最大字符数。
将值设置为
0
会禁用截断的字符限制。[pytest] truncation_limit_chars = 640
pytest 默认会将断言消息截断到一定限制,以防止与大数据比较时使控制台输出过载。
默认值:
640
注意
如果 pytest 检测到它正在CI 上运行,则自动禁用截断。
- truncation_limit_lines¶
控制断言消息内容截断的最大行数。
将值设置为
0
会禁用截断的行数限制。[pytest] truncation_limit_lines = 8
pytest 默认会将断言消息截断到一定限制,以防止与大数据比较时使控制台输出过载。
默认值:
8
注意
如果 pytest 检测到它正在CI 上运行,则自动禁用截断。
- usefixtures¶
将应用于所有测试函数的 fixture 列表;这在语义上与将
@pytest.mark.usefixtures
标记应用于所有测试函数相同。[pytest] usefixtures = clean_db
- verbosity_assertions¶
专门为断言相关输出设置一个详细级别,覆盖应用程序范围的级别。
[pytest] verbosity_assertions = 2
默认为应用程序范围的详细级别(通过
-v
命令行选项)。可以使用特殊值“auto”来明确使用全局详细级别。
- verbosity_test_cases¶
专门为测试用例执行相关输出设置一个详细级别,覆盖应用程序范围的级别。
[pytest] verbosity_test_cases = 2
默认为应用程序范围的详细级别(通过
-v
命令行选项)。可以使用特殊值“auto”来明确使用全局详细级别。
命令行标志¶
所有命令行标志都可以通过运行 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 Any warnings encountered while parsing the `pytest`
section of the configuration file raise errors
--strict-markers Markers not registered in the `markers` section of
the configuration file raise errors
--strict (Deprecated) alias to --strict-markers
--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 ini option with "option=value" style, e.g.
`-o xfail_strict=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] ini-options in the first 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
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)
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.
xfail_strict (bool): Default for the strict parameter of xfail markers
when not given explicitly (default: False)
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
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 (regardless of 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
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