Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test 404 NOT FOUND with django testing framework?

I am trying to automate 404 pages testing using Django 1.4's testing framework.

If I print 127.0.0.1:8000/something/really/weird/ in browser address bar with development server running, I see a 404 page, with correct "404 NOT FOUND" status (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 fails 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'm seriously surprised with getting 200 code here. Anyone have any idea why on earth this is happening?

updated:

here lies urls.py: http://pastebin.com/DikAVa8T and actual failing test is:

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

everything is happening in project https://github.com/gbezyuk/django-app-skeleton

like image 238
Grigoriy Beziuk Avatar asked May 06 '12 07:05

Grigoriy Beziuk


People also ask

How do I test my Django site?

The preferred way to write tests in Django is using the unittest module built-in to the Python standard library. This is covered in detail in the Writing and running tests document. You can also use any other Python test framework; Django provides an API and tools for that kind of integration.

Is Django used for testing?

Django provides a test framework with a small hierarchy of classes that build on the Python standard unittest library. Despite the name, this test framework is suitable for both unit and integration tests. The Django framework adds API methods and tools to help test web and Django-specific behavior.


1 Answers

Try

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

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

  • something/really/weird
  • something/really/weird/
  • /something/really/weird
like image 171
okm Avatar answered Sep 20 '22 16:09

okm