Pytest对失败的断言输出比Python默认的更具信息量和实用性。我想在正常运行Python程序时也可以利用这一点,而不仅仅是在执行测试时。是否有一种方法可以在我的脚本中覆盖Python的assert
行为,使用pytest打印堆栈跟踪,同时仍然以python script/pytest_assert.py
方式运行我的程序?
示例程序
def test_foo():
foo = 12
bar = 42
assert foo == bar
if __name__ == '__main__':
test_foo()
$ python script/pytest_assert.py
Traceback (most recent call last):
File "script/pytest_assert.py", line 8, in <module>
test_foo()
File "script/pytest_assert.py", line 4, in test_foo
assert foo == bar
AssertionError
$ pytest script/pytest_assert.py
======================== test session starts ========================
platform linux -- Python 3.5.3, pytest-3.3.2, py-1.5.2, pluggy-0.6.0
rootdir: /usr/local/google/home/danijar, inifile:
collected 1 item
script/pytest_assert.py F [100%]
============================= FAILURES ==============================
_____________________________ test_foo ______________________________
def test_foo():
foo = 12
bar = 42
> assert foo == bar
E assert 12 == 42
script/pytest_assert.py:4: AssertionError
===================== 1 failed in 0.02 seconds =====================
期望的结果
$ python script/pytest_assert.py
Traceback (most recent call last):
File "script/pytest_assert.py", line 8, in <module>
test_foo()
def test_foo():
foo = 12
bar = 42
> assert foo == bar
E assert 12 == 42
script/pytest_assert.py:4: AssertionError
进展更新
我目前为止找到的最接近的方法是这个,但它仅适用于该函数内部的断言,并且会在跟踪中产生大量信息:
import ast
import inspect
from _pytest import assertion
def test_foo():
foo = []
foo.append(13)
foo = foo[-1]
bar = 42
assert foo == bar, 'message'
if __name__ == '__main__':
tree = ast.parse(inspect.getsource(test_foo))
assertion.rewrite.rewrite_asserts(tree)
code = compile(tree, '<name>', 'exec')
ns = {}
exec(code, ns)
ns[test_foo.__name__]()
$ python script/pytest_assert.py
Traceback (most recent call last):
File "script/pytest_assert.py", line 21, in <module>
ns[test_foo.__name__]()
File "<name>", line 6, in test_foo
AssertionError: message
assert 13 == 42
assert
是一个关键字,答案将是“不行,除非重新编译解释器”。必须问的一个问题是:如果你喜欢pytest的输出,为什么不使用pytest呢? - DeepSpace