I've the need to write some tests for custom handler404 and handler500 in Django, using django test dummy client. The first is easy to test while I have problems with the second.
Basically, problem is that Django test client does not catch the exception and does not route to the proper handler. This is a problem because we need to test that the right custom handler and template are used.
We have a simple middleware class to simulate exceptions for tests:
class HTTPStatusCodeMiddleware(object):
def process_view(self, request, *args):
if 'cookie_500_error' in request.COOKIES:
raise Exception('Test exception')
Code above works fine for manual testing in browser.
Now, tests are:
def test_404_template(self):
c = Client()
url = '/not_existing.html'
response = c.get(url)
self.assertEqual(response.status_code, 404) # success
self.assertTemplateUsed(response, 'custom/404.html') # success
def test_500_template(self):
c = Client()
c.cookies['cookie_500_error'] = '1'
response = c.get('/') # here middleware raises exception!!!
self.assertEqual(response.status_code, 500)
self.assertTemplateUsed(response, 'custom/500.html')
Any idea? I don't have the option to use selenium. Thanks!
Django test client handles only some exceptions (see the docs). All the others are visible in the test and you can test them ;)