代码:
# coding=utf-8
import pytest
def whatever():
return 9/0
def test_whatever():
try:
whatever()
except ZeroDivisionError as exc:
pytest.fail(exc, pytrace=True)
输出:
================================ test session starts =================================
platform linux2 -- Python 2.7.3 -- py-1.4.20 -- pytest-2.5.2
plugins: django, cov
collected 1 items
pytest_test.py F
====================================== FAILURES ======================================
___________________________________ test_whatever ____________________________________
def test_whatever():
try:
whatever()
except ZeroDivisionError as exc:
> pytest.fail(exc, pytrace=True)
E Failed: integer division or modulo by zero
pytest_test.py:12: Failed
============================== 1 failed in 1.16 seconds ==============================
如何使 pytest 打印回溯,所以我会看到 whatever
函数中的哪里引发了异常?
原文由 Gill Bates 发布,翻译遵循 CC BY-SA 4.0 许可协议
pytest.raises(Exception)
是你所需要的。代码
输出
请注意,
e_info
保存异常对象,以便您可以从中提取详细信息。例如,如果您想检查异常调用堆栈或内部的另一个嵌套异常。