代码:

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


当前回答

pytest.raise (Exception)是你所需要的。

Code

import pytest

def test_passes():
    with pytest.raises(Exception) as e_info:
        x = 1 / 0

def test_passes_without_info():
    with pytest.raises(Exception):
        x = 1 / 0

def test_fails():
    with pytest.raises(Exception) as e_info:
        x = 1 / 1

def test_fails_without_info():
    with pytest.raises(Exception):
        x = 1 / 1

# Don't do this. Assertions are caught as exceptions.
def test_passes_but_should_not():
    try:
        x = 1 / 1
        assert False
    except Exception:
        assert True

# Even if the appropriate exception is caught, it is bad style,
# because the test result is less informative
# than it would be with pytest.raises(e)
# (it just says pass or fail.)

def test_passes_but_bad_style():
    try:
        x = 1 / 0
        assert False
    except ZeroDivisionError:
        assert True

def test_fails_but_bad_style():
    try:
        x = 1 / 1
        assert False
    except ZeroDivisionError:
        assert True

输出

============================================================================================= test session starts ==============================================================================================
platform linux2 -- Python 2.7.6 -- py-1.4.26 -- pytest-2.6.4
collected 7 items 

test.py ..FF..F

=================================================================================================== FAILURES ===================================================================================================
__________________________________________________________________________________________________ test_fails __________________________________________________________________________________________________

    def test_fails():
        with pytest.raises(Exception) as e_info:
>           x = 1 / 1
E           Failed: DID NOT RAISE

test.py:13: Failed
___________________________________________________________________________________________ test_fails_without_info ____________________________________________________________________________________________

    def test_fails_without_info():
        with pytest.raises(Exception):
>           x = 1 / 1
E           Failed: DID NOT RAISE

test.py:17: Failed
___________________________________________________________________________________________ test_fails_but_bad_style ___________________________________________________________________________________________

    def test_fails_but_bad_style():
        try:
            x = 1 / 1
>           assert False
E           assert False

test.py:43: AssertionError
====================================================================================== 3 failed, 4 passed in 0.02 seconds ======================================================================================

请注意,e_info保存了异常对象,因此您可以从中提取详细信息。例如,如果您想检查异常调用堆栈或内部的另一个嵌套异常。

其他回答

正确的方法是使用pytest。但我在这里的评论中找到了另一种有趣的方法,我想把它留给未来的读者:

try:
    thing_that_rasises_typeerror()
    assert False
except TypeError:
    assert True

你可以试试

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

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

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

@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

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

在pytest中有两种处理异常的方法:

使用pytest。引发以编写关于引发异常的断言 使用@pytest.mark.xfail

1. 使用pytest.raises

从文档中可以看出:

为了编写关于引发异常的断言,可以使用pytest。作为上下文管理器引发

例子:

只主张一个例外:

import pytest


def test_zero_division():
    with pytest.raises(ZeroDivisionError):
        1 / 0

raise (ZeroDivisionError)表示 在接下来的代码块中应该引发一个ZeroDivisionError异常。如果没有引发异常,则测试失败。如果测试引发不同的异常,则测试失败。

如果你需要访问实际的异常信息:

import pytest

def f():
    f()

def test_recursion_depth():
    with pytest.raises(RuntimeError) as excinfo:
        f()
    assert "maximum recursion" in str(excinfo.value)

excinfo是一个ExceptionInfo实例,它是实际引发的异常的包装器。主要的属性是.type, .value和.traceback。

2. 使用@pytest.mark.xfail

也可以为pytest.mark.xfail指定一个raise参数。

import pytest

@pytest.mark.xfail(raises=IndexError)
def test_f():
    l = [1, 2, 3]
    l[10]

@pytest.mark.xfail(raise =IndexError)表示 在接下来的代码块中应该引发IndexError异常。如果抛出IndexError异常,则测试被标记为xfailed (x).如果没有抛出异常,则测试被标记为xpassed (x).如果抛出不同的异常,则测试失败。

注: 使用pytest。当您在测试自己的代码故意引发的异常时,而使用@pytest.mark时,则可能会更好。带有检查函数的Xfail可能更好地用于记录未修复的错误或依赖关系中的错误。 您可以将匹配关键字参数传递给上下文管理器(pytest.raise),以测试正则表达式是否与异常的字符串表示匹配。(查看更多)

在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=============================