在pytest中,如何断言是否引发了异常(从父异常类继承)?

时间:2019-07-23 08:56:16

标签: python python-2.7 inheritance exception pytest

我做了什么

我有一个函数def get_holidays():,它引发了Timeout错误。我的测试函数test_get_holidays_raises_ioerror():首先设置requests.get.side_effect = IOError,然后使用pytest.raises(IOError)断言该函数是否引发IOError

问题所在

理想情况下,这应该会失败,因为我的实际get_holidays()不会引发IOError。但是测试通过了。

可能的原因

这可能是因为Timeout是从IOError类继承的。

我想要的

想特别声明是否引发IOError

代码

from mock import Mock
import requests
from requests import Timeout
import pytest

requests = Mock()

# Actual function to test

def get_holidays():
    try:
        r = requests.get('http://localhost/api/holidays')
        if r.status_code == 200:
            return r.json()
    except Timeout:
        raise Timeout

    return None

# Actual function that tests the above function

def test_get_holidays_raises_ioerror():
    requests.get.side_effect = IOError
    with pytest.raises(IOError):
        get_holidays()

1 个答案:

答案 0 :(得分:0)

pytest在ExceptionInfo对象中捕获异常。您可以在例外之后比较确切的类型。

def test_get_holidays_raises_ioerror():
    requests.get.side_effect = IOError
    with pytest.raises(IOError) as excinfo:
        get_holidays()
    assert type(excinfo.value) is IOError