victory的博客

长安一片月,万户捣衣声

0%

pytest | 自定义失败断言解释

自定义失败断言解释

使用pytest测试代码块(Code Block)或函数(Functions)时,通常使用assert语句对代码块或函数的执行结果与预期结果进行比较,从而判断代码块或函数的正确性。如果在测试过程中某测试用例中的断言失败,即代码块或函数的实际执行结果与预期结果不一致,pytest将会报告错误信息。

在pytest中我们可以通过实现pytest_assertrepr_coompare钩子函数(Hook Function)来自定义失败断言的错误信息。

pytest_assertrepr_coompare钩子函数的语法如下:

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

​ Return explanation for comparisons in failing assert expressions.(返回失败断言表达式的解释信息)

​ Parameters:

config (Config) – The pytest config object.(pytest配置对象)

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

left (object) – The left operand.(操作数1)

right (object) – The right operand.(操作数2)

通过钩子函数自定义错误断言信息的例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# content of conftest.py
from test_foocompare import Foo

# 钩子函数,自定义断言信息
def pytest_assertrepr_compare(op, left, right):
# 若Foo对象作相等断言(==)时失败,则输入自定义信息
if isinstance(left, Foo) and isinstance(right, Foo) and op == "==":
return [
"Comparing Foo instances:",
f" vals: {left.val} != {right.val}",
]

# content of test_foocompare.py
class Foo:
def __init__(self, val):
self.val = val

def __eq__(self, other):
return self.val == other.val


def test_compare():
f1 = Foo(1)
f2 = Foo(2)
assert f1 == f2

运行test_foocompare.py模块,控制台会输出一下信息:

1
2
E       assert Comparing Foo instances:
E vals: 1 != 2

自定义失败断言信息时通过重写断言表达式实现的,我们可以通过在代码中关闭”断言重写“功能:

  • 关闭特定模块的断言重写:在docstring中增加PYTEST_DONT_REWRITE字符串

    1
    2
    3
    4
    5
    6
    """
    PYTEST_DONT_REWRITE
    """
    ......
    python test code
    ......
  • 关闭所有模块的断言重写:使用–assert=plain

    1
    pytest --assert=plain