Reputation: 105
What I have done :
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
.
What the issue is :
Ideally this should fail, since my actual get_holidays()
does not raise an IOError
. But the test passes.
Possible reason :
This might be because Timeout
is inherited from the IOError
class.
What I want :
Want to assert specifically if IOError
is raised.
Code :
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()
Upvotes: 1
Views: 3348
Reputation: 621
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
Upvotes: 0