1

This isn't a duplicate of this: AssertionError: 200 != 403

I'm running some automated tests and am having problems with assertions around status codes.

In a regular browser, browsing to my.server/item/22 with a user with bad credentials, gives a custom 403 page:

enter image description here

And the custom page shows correctly:

enter image description here

Hooray, all is well... except when I run the tests:

def test_editor_can_view(self):
    self.logout()
    response = self.client.post(reverse('django.contrib.auth.views.login'), {'username': 'eddie', 'password': 'editor'})
    self.assertEqual(response.status_code,302) # Redirect to homepage, thats ok.
    response = self.client.post(self.get_page(self.item1))
    self.assertEqual(response.status_code,200) # This should work, and does.
    response = self.client.post(self.get_page(self.item2))
    print response
    self.assertEqual(response.status_code,403) # This does not.

In the test output:

======================================================================
FAIL: test_editor_can_view (aristotle_mdr.tests.SupersedePages)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/my_app/tests.py", line 377, in test_editor_can_view
    self.assertEqual(response.status_code,403)
AssertionError: 200 != 403

But inspecting the response shows:

<h1 class="unauthorised">Unauthorised</h1>
<p>
The page you have requested is not

accessible via your current account. You can <a href="/accounts/logout">log out</a> and try with a different accoun
t

or contact an administrator to see why you can't access this page.
</p>

So the user is being told they can't access it correct. So somehow the 403 error is being eaten, and is turned into a 403. Unlike my last question, this is definitely a case where a 403 should be (and in some cases is being) returned.

In urls.py, I have this:

handler403 = 'my_app.views.unauthorised'

And in views.py I have this:

def unauthorised(request, path=''):
    return render(request,"403.html")

Why is this being mangled in the test suite?

Community
  • 1
  • 1
  • That doesn't really answer your question but have a look at WebTest, https://pypi.python.org/pypi/django-webtest it makes this type of testing a lot easier. – François Constant Sep 15 '14 at 04:53

1 Answers1

0

And like that having written the question out, I have found my problem:

django.shortcuts.render can take a status code, and explicitly setting this ensures the correct error code gets back to the test suite.

def unauthorised(request, path=''):
    return render(request,"403.html",status=403)

Although that doesn't quite explain why my browser was getting the right error code.