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