在pytest中,如何断言是否引发了异常(该异常是从父异常类继承的)? [英] In pytest, how to assert if an exception (which is inherited from a parent exception class) is raised?

查看:106
本文介绍了在pytest中,如何断言是否引发了异常(该异常是从父异常类继承的)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了什么:

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

I have a function def get_holidays(): which raises a Timeout error. My test function test_get_holidays_raises_ioerror(): first sets requests.get.side_effect = IOError and then uses pytest.raises(IOError) to assert if that function raises an IOError.

问题所在:

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

Ideally this should fail, since my actual get_holidays() does not raise an IOError. But the test passes.

可能的原因:

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

This might be because Timeout is inherited from the IOError class.

我想要的:

想特别声明是否提高了IOError.

Want to assert specifically if IOError is raised.

代码:

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()

推荐答案

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

pytest captures the exception in an ExceptionInfo object. You can compare the exact type after the exception.

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

这篇关于在pytest中,如何断言是否引发了异常(该异常是从父异常类继承的)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆