代码:
# 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
函数中哪里抛出了异常?
发布于 2014-05-07 18:10:10
你的意思是这样的吗:
def test_raises():
with pytest.raises(Exception) as execinfo:
raise Exception('some info')
# these asserts are identical; you can use either one
assert execinfo.value.args[0] == 'some info'
assert str(execinfo.value) == 'some info'
发布于 2017-05-25 00:24:51
你可以试试
def test_exception():
with pytest.raises(Exception) as excinfo:
function_that_raises_exception()
assert str(excinfo.value) == 'some info'
发布于 2018-08-22 12:55:16
正确的方法是使用pytest.raises
,但我在评论here中找到了有趣的替代方法,并希望将其保存下来,供这个问题的未来读者使用:
try:
thing_that_rasises_typeerror()
assert False
except TypeError:
assert True
https://stackoverflow.com/questions/23337471
复制相似问题