Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to follow Django redirect using django-pytest?

In setting up a ArchiveIndexView in Django I am able to successfully display a list of items in a model by navigating to the page myself.

When going to write the test in pytest to verify navigating to the page "checklist_GTD/archive/" succeeds, the test fails with the message:

>       assert response.status_code == 200
E       assert 301 == 200
E        +  where 301 = <HttpResponsePermanentRedirect status_code=301, "text/html; charset=utf-8", url="/checklist_GTD/archive/">.status_code

test_archive.py:4: AssertionError

I understand there is a way to follow the request to get the final status_code. Can someone help me with how this done in pytest-django, similar to this question? The documentation on pytest-django does not have anything on redirects. Thanks.

like image 222
Scott Skiles Avatar asked Jan 09 '18 11:01

Scott Skiles


People also ask

How to redirect link in Django?

In Django, redirection is accomplished using the 'redirect' method. The 'redirect' method takes as argument: The URL you want to be redirected to as string A view's name. In the above example, first we imported redirect from django.

Does Django test use Pytest?

pytest-django Documentation. pytest-django is a plugin for pytest that provides a set of useful tools for testing Django applications and projects.

Does Django use Pytest or Unittest?

Django's unit tests use a Python standard library module: unittest . This module defines tests using a class-based approach.


1 Answers

pytest-django provides both an unauthenticated client and a logged-in admin_client as fixtures. Really simplifies this sort of thing. Assuming for the moment that you're using admin_client because you just want to test the redirect as easily as possible, without having to log in manually:

def test_something(admin_client):
    response = admin_client.get(url, follow=True)
    assert response.status_code == 200

If you want to log in a standard user:

def test_something(client):
    # Create user here, then:
    client.login(username="foo", password="bar")
    response = client.get(url, follow=True)
    assert response.status_code == 200

By using follow=True in either of these, the response.status_code will equal the return code of the page after the redirect, rather than the access to the original URL. Therefore, it should resolve to 200, not 301.

I think it's not documented in pytest-django because the option is inherited from the Django test client it subclasses from (making requests).

like image 175
shacker Avatar answered Sep 24 '22 13:09

shacker