Django test for 404 erroring because Client expects 200?

Question:

I am trying to test my 404 page to ensure certain elements are present on it.

My test looks like this:

class TestApp404PageIncludesLink(TestCase):
    def setUp(self):
        superuser = UserFactory(is_superuser=True, is_staff=True)
        self.client.force_login(superuser)

    def test_superuser_can_see_link(self):
        response = self.client.get("404")
        self.assertTrue(response.status_code == 404)
        self.assertContains(response, 'href="/special_link/">Specialty</a>')

I am running this test as a logged in user – other tests for other views work fine.

I’m trying to check the 404 page.

It fails with this:

Couldn't retrieve content: Response code was 404 (expected 200)
200 != 404

How do I set up the test so it knows I am trying to get a 404?

Asked By: Hanny

||

Answers:

404 pages typically return a code 200 and say that they failed through the page that you send back.

Answered By: Mr. Turtle

The issue had to do with me not reading the documentation thoroughly enough apparently.

The assertContains takes a status_code argument that by default assumes a status of 200, which a 404 is not. Once I added that to the assertion it was resolved.

    def test_superuser_can_see_link(self):
        response = self.client.get("404")
        self.assertTrue(response.status_code == 404)
        self.assertContains(response, 'href="/special_link/">Specialty</a>', status_code=404)
Answered By: Hanny