英文:
Assertion Error vs Assert in pytest, why do I get different error messages when running pytest
问题
以下是您要翻译的内容:
I have following dummy test cases in python and I am trying to have a better understanding of the error messages produced by pytest.
when I run these 4 test cases I get the following errors
FAILED test_assert_false_2 - AssertionError: assert 'abc' in 'defab'
FAILED test_1 - assert 0
FAILED test_2 - assert 3 < 2
FAILED test_3 - assert 1 > 2
why do I get AssertionError in first case and just assert in following cases
def test_assert_false_2():
assert 'abc' in 'defab'
def test_1():
assert 1
assert 0
def test_2():
assert 3 < 2
def test_3():
a = 2
b = 1
assert b > a
英文:
I have following dummy test cases in python and I am trying to have a better understanding of the error messages produced by pytest.
when I run these 4 test cases I get the following errors
FAILED test_assert_false_2 - AssertionError: assert 'abc' in 'defab'
FAILED test_1 - assert 0
FAILED test_2 - assert 3 < 2
FAILED test_3 - assert 1 > 2
why do I get AssertionError in first case and just assert in following cases
def test_assert_false_2():
assert 'abc' in 'defab'
def test_1():
assert 1
assert 0
def test_2():
assert 3 < 2
def test_3():
a = 2
b = 1
assert b > a
答案1
得分: 1
Pytest试图在断言失败时提供更多的调试信息,它通过在运行之前重写断言语句,并将内省信息放入断言失败消息中来实现这一目的。因此,在不同断言上的日志消息之间存在差异。
您可以通过在pytest命令后添加--assert plain来关闭这个功能:
pytest --assert plain
有关更多信息,请参考pytest的--help选项:
--assert=MODE 控制断言调试工具。
'plain' 不执行断言调试。
'rewrite'(默认值)在导入测试模块时重写断言语句以提供断言表达式信息。
您还可以仅为特定模块禁用断言重写,方法是在其文档字符串中添加PYTEST_DONT_REWRITE
:
https://docs.pytest.org/en/7.1.x/how-to/assert.html#assertion-introspection-details
英文:
Pytest tries to provide more debugging information on failed asserts, it does that by rewriting assert statements before they are run and putting introspection information into the assertion failure message. Thus the discrepancy between log messages on different asserts.
You can turn that off by adding --asserts plain to your pytest command
pytest --asserts plain
More info from pytest --help
--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.
You can also disable assert rewriting only for a specific module by adding PYTEST_DONT_REWRITE
to its docstring
https://docs.pytest.org/en/7.1.x/how-to/assert.html#assertion-introspection-details
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论