代码:

# 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打印回溯,所以我将看到在任何函数异常被引发的地方?


当前回答

您是否尝试删除“pytrace=True”?

pytest.fail(exc, pytrace=True) # before
pytest.fail(exc) # after

你试过用“——fulltrace”运行吗?

其他回答

只是添加了另一个“愚蠢”的建议,因为我在现有的答案中没有看到它。本质上,你可以初始化一个错误变量为None,在try/except块中做这件事,然后在那之后检查错误变量的类/值

e = None

try:
    blah()
except Exception as exc:
    e = exc

assert e.__class__ == ValueError # or whatever you expect
assert str(e) == "expected message"

如果您希望为您的测试用例引发一个异常,这里提交的最重要的答案是有用的。如果您的测试可能会引发异常,并且您希望在任何一种情况下都能妥善地处理它,那么它就不是很有用。

如果您有一个可能(而不是将)引发异常的测试用例,我认为这可能是一个更好的选择。

@python.mark.parametrize("request_query, response_code", query_response_dataset)
def test_big_query_submission(request_query, response_code):
    try:
        stats = bigquery.Client().query(request_query)
    except Exception as e:
        assert False, f"Exception raised: {e}"
    assert stats.errors is None

通过这种方式,您可以优雅地失败测试,而不是由于任何原因引发异常导致测试崩溃。

你可以试试

def test_exception():
    with pytest.raises(Exception) as excinfo:   
        function_that_raises_exception()   
    assert str(excinfo.value) == 'some info' 

在pytest中有两种方法来处理这类情况:

使用pytest。提出了功能 使用pytest.mark.xfail装饰器

如文档所述:

使用pytest。当您在测试自己的代码故意引发的异常时,而使用@pytest.mark时,则可能会更好。带有检查函数的Xfail可能更适合于记录未修复的错误(其中测试描述了“应该”发生什么)或依赖关系中的错误。

pytest.raise的用法:

def whatever():
    return 9/0
def test_whatever():
    with pytest.raises(ZeroDivisionError):
        whatever()

使用pytest.mark.xfail:

@pytest.mark.xfail(raises=ZeroDivisionError)
def test_whatever():
    whatever()

pytest.raise的输出:

============================= test session starts ============================
platform linux2 -- Python 2.7.10, pytest-3.2.3, py-1.4.34, pluggy-0.4.0 -- 
/usr/local/python_2.7_10/bin/python
cachedir: .cache
rootdir: /home/user, inifile:
collected 1 item

test_fun.py::test_whatever PASSED


======================== 1 passed in 0.01 seconds =============================

pytest的输出。xfail标记:

============================= test session starts ============================
platform linux2 -- Python 2.7.10, pytest-3.2.3, py-1.4.34, pluggy-0.4.0 -- 
/usr/local/python_2.7_10/bin/python
cachedir: .cache
rootdir: /home/user, inifile:
collected 1 item

test_fun.py::test_whatever xfail

======================== 1 xfailed in 0.03 seconds=============================

如果你想测试特定的错误类型,可以使用try, catch和raise的组合:

#-- test for TypeError
try:
  myList.append_number("a")
  assert False
except TypeError: pass
except: assert False