I am working on unit tests for my API endpoints which I have built using Django rest_framework. I was able to test most of the error codes related to my endpoint except the 500 error code. Is there are way to mock the client function to return 500 error response or any cleaner way in unit test framework?
class UserApiTests(TestCase):
def setUp(self):
self.client = APIClient()
...
def test_retrieve_user(self):
"""Test server failure while retrieving profile for user."""
res = self.client.get(USER_URL)
# Below should return server error
self.assertEqual(res.status_code, status.HTTP_500_INTERNAL_SERVER_ERROR)
The APIClient
class supports the same request interface as Django's standard Client
class so it is possible to use raise_request_exception
argument to control whether to raise exceptions or return a 500 response (set raise_request_exception
to False
for a 500 response).
Changing the setUp()
method should do the trick:
def setUp(self):
self.client = APIClient(raise_request_exception=False)
Here is the documentation and ticket discussing this issue for more info.