[Fixed]-How do I simulate connection errors and request timeouts in python unit tests

5👍

Untested code but…

def connection_error():
    raise requests.exceptions.ConnectionError

class TestSuitabilityFunctions(TestCase):
    @patch.object(module_that_youre_testing, "requests")
    def test_connection_error(self, mock_requests):
        mock_requests.get = MagicMock(side_effect=connection_error)
        with self.assertRaises(requests.exceptions.ConnectionError) as cm:
            resp = call_the_api()
        exception = cm.exception
        self.assertEqual(resp, {'request_error': 'ConnectionTimeout'})

… or similar should do the trick. Off the top of my head I can’t remember how assertRaises interacts with errors that are caught. Maybe you don’t even need the assertRaises part.

👤ptr

Leave a comment