'In Python3, how do you test exception handling within a unit test? [duplicate]
I have several unit tests that I'm working on for an api. The tests use @patch to mock the api calls. Some of the tests I wish to create should trigger exceptions. How do I handle that in a unit test?
Here's what I have so far. Pylint complains about the assertTrue() statements. I'm sure there's a better way to handle exceptions.
@patch('myapi.myapi.requests.request')
def test_auth_failure(self, mock_request):
# Configure the request mock to return an auth failure
# Auth/login (/session) failures return status 200, but without a token!
mock_request.return_value.status_code = 200
mock_request.return_value.content = json.dumps(self.mock_auth_failure)
try:
# Call auth()
self.api.auth()
# Exception should have been raised
self.assertTrue(False)
except exceptions.HTTPUnauthorized:
# Exception caught
self.assertTrue(True)
Additional Information: This is in a class extending from unittest.TestCase. Example:
class MyApiTests(unittest.TestCase):
Solution 1:[1]
If your class (that defines the test_auth_failure method) extends unittest.TestCase, you should use [Python.Docs]: unittest - assertRaises(exception, callable, *args, **kwds):
Replace your try / except clause by:
with self.assertRaises(exceptions.HTTPUnauthorized):
self.api.auth()
or
self.assertRaises(exceptions.HTTPUnauthorized, self.api.auth)
Solution 2:[2]
If you're using pytest there's functionality for that...
import pytest
def test_zero_division():
with pytest.raises(ZeroDivisionError):
1 / 0
https://docs.pytest.org/en/latest/assert.html#assertions-about-expected-exceptions
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | jxramos |
