3

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):
jjwdesign
  • 3,272
  • 8
  • 41
  • 66

2 Answers2

6

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

jxramos
  • 7,356
  • 6
  • 57
  • 105
3

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)
CristiFati
  • 38,250
  • 9
  • 50
  • 87