How to test 404 NOT FOUND using django testing platform?

I am trying to automate testing 404 pages using the Django 1.4 testing platform.

If I type 127.0.0.1:8000/something/really/weird/ in the address bar of a browser with a development server running, I see a 404 page with the correct status "404 NOT FOUND" (as Firebug shows).

But if I try to use this code for testing:

 from django.test import TestCase class Sample404TestCase(TestCase): def test_wrong_uri_returns_404(self): response = self.client.get('something/really/weird/') self.assertEqual(response.status_code, 404) 

the test does not work with this output:

 $./manage.py test main Creating test database for alias 'default'... .F ====================================================================== FAIL: test_wrong_uri_returns_404 (main.tests.Sample404TestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File ".../main/tests.py", line 12, in test_wrong_uri_returns_404 self.assertEqual(response.status_code, 404) *AssertionError: 200 != 404* ---------------------------------------------------------------------- Ran 2 tests in 0.031s FAILED (failures=1) Destroying test database for alias 'default'... 

I am seriously surprised that I got 200 codes here. Does anyone have any idea why this is happening on earth?

update:

here lies urls.py: http://pastebin.com/DikAVa8T and the actual failure test:

 def test_wrong_uri_returns_404(self): response = self.client.get('/something/really/weird/') self.assertEqual(response.status_code, 404) 

everything happens in the project https://github.com/gbezyuk/django-app-skeleton

+6
source share
2 answers

The problem is that your ViewFor404 class returns a status code of 200. Look at the definition of a Django template:

 class TemplateView(TemplateResponseMixin, View): """ A view that renders a template. """ def get_context_data(self, **kwargs): return { 'params': kwargs } def get(self, request, *args, **kwargs): context = self.get_context_data(**kwargs) return self.render_to_response(context) 

so all your class does is render_to_response, which generates a "200" response.

If you need to override the 404 handler, you should do something similar in the view:

 return HttpResponseNotFound('<h1>Page not found</h1>') 

(I don't know the equivalent in class based views)

Or better yet, can you avoid customizing the view? To customize the 404 display, you can simply create a 404.html template (in your site template / directory) and it will be picked up by Django's error viewer.

+2
source

Try

 response = self.client.get('/something/really/weird/') # note the '/' before something 

127.0.0.1:8000/something/really/weird/ matters /something/really/weird/ in the path relative to the root, not

  • something/really/weird
  • something/really/weird/
  • /something/really/weird
+5
source

Source: https://habr.com/ru/post/915007/


All Articles