[Django]-Testing django: reason for unexpected http status code

4👍

Sounds like you should split your tests up into proper unit tests and test smaller units of code. Use Django’s request factory and test only the view code. Or split your view into smaller functions and test them individually.

Using Django’s test client is more of an integration test than a unittest as it tests url routing, database, middleware, templates etc

👤Carl

4👍

You replaced the useful message from assertEqual with a less usefull message, namely the URL that failed (third argument to assertEqual).

You have done this because the same test method tests multiple URLs. That is a bad practice. Each test method should test one thing. DRY doesn’t apply to unit-testing (or at least it is more important that each test method test one thing, and one thing only).

Say you knew the offending status code, it would be more obvious to find from where it stemmed. Say it was 404, well then, perhaps the object was not found, perhaps it was 300-something, perhaps you don’t have proper permissions and are being redirected to a login page.

Any real programming error would fail with a normal exception and a useful stacktrace.

If you are concerned with the logic inside a particular view, split the logic into multiple testable units.

In this particular case, my money would be on bad PK or missing permissions though.

Regarding your mocking, try something like:

with patch.object(HttpResponseBase, '__init__', None):
    response = client.get(url)

2👍

I used this solution to find the problem:

import django
django.http.response.HttpResponseBase.__init__=None
response=client.get(url)

This results in a stacktrace, where I can see where the HttpResponse was created.

Of course this is just a temporary solution for debugging. I tried the same with mock, but this failed since I am not a mock expert (yet).

Leave a comment