I'm writing a unittest class to ensure a method tests for a success, and then tests for an Exception. I'm passing a response that should trigger the exception, but in the testing method it does not get raised. Of note, I can manually make the exception raise in the actual method.
Test class:
class TestAPI(TestCase):
def test_send_method(self):
with mock.patch('requests.post') as mock_request:
mock_response = mock.Mock()
mock_response.json.return_value = {
"success": "true"
}
mock_request.return_value = mock_response
send_method() // THIS WORKS NICELY
# Test that errors from the API are handled correctly.
with self.assertRaises(SendException):
mock_response.status_code = 500
mock_response.json.return_value = {
'errors': 'An error has occurred.',
}
send_method() // THIS RAISES NO EXCEPTION
As I said, It's odd because I can manually trigger the 500 status code in the actual method and it raises fine. I can even change the initial mock response success to err and it will raise in the actual method. Why would it not raise in the unittest?
Method being tested:
class SendException(Exception):
pass
def send_method():
session_headers = {
"Content-Type": "application/json",
}
session_body = {
"send": "yes"
}
session_url = u'{}'.format(URL)
session_response = requests.post(session_url, json=session_body, headers=session_headers)
try:
if(session_response.json().get('errors') is not None):
raise SendException(
'Returned error with status {}: {}'.format(
session_response.status_code,
session_response.json().get('errors')
)
)
except ValueError as err:
raise SendException(
'Responded with non-json and status code {}. Error: {} - Response Text: {}'.format(
session_response.status_code,
err,
session_response.text
)
)