首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何正确断言异常在pytest中被引发?

如何正确断言异常在pytest中被引发?
EN

Stack Overflow用户
提问于 2014-04-28 17:33:45
回答 6查看 276.8K关注 0票数 444

代码:

代码语言:javascript
复制
# coding=utf-8
import pytest


def whatever():
    return 9/0

def test_whatever():
    try:
        whatever()
    except ZeroDivisionError as exc:
        pytest.fail(exc, pytrace=True)

输出:

代码语言:javascript
复制
================================ 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函数中哪里抛出了异常?

EN

回答 6

Stack Overflow用户

发布于 2014-05-07 18:10:10

你的意思是这样的吗:

代码语言:javascript
复制
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'
票数 223
EN

Stack Overflow用户

发布于 2017-05-25 00:24:51

你可以试试

代码语言:javascript
复制
def test_exception():
    with pytest.raises(Exception) as excinfo:   
        function_that_raises_exception()   
    assert str(excinfo.value) == 'some info' 
票数 54
EN

Stack Overflow用户

发布于 2018-08-22 12:55:16

正确的方法是使用pytest.raises,但我在评论here中找到了有趣的替代方法,并希望将其保存下来,供这个问题的未来读者使用:

代码语言:javascript
复制
try:
    thing_that_rasises_typeerror()
    assert False
except TypeError:
    assert True
票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23337471

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档