自定义失败断言解释
使用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 | # content of conftest.py |
运行test_foocompare.py模块,控制台会输出一下信息:
1 | E assert Comparing Foo instances: |
自定义失败断言信息时通过重写断言表达式实现的,我们可以通过在代码中关闭”断言重写“功能:
关闭特定模块的断言重写:在docstring中增加PYTEST_DONT_REWRITE字符串
1
2
3
4
5
6"""
PYTEST_DONT_REWRITE
"""
......
python test code
......关闭所有模块的断言重写:使用–assert=plain
1
pytest --assert=plain