I already know that one can implement a class that inherits from SimpleTestCase
, and one can test redirection by:
SimpleTestCase.assertRedirects(response, expected_url, status_code=302, target_status_code=200, host=None, msg_prefix='', fetch_redirect_response=True)
However, I am wondering what is the way I can check for redirection using pytest:
@pytest.mark.django_db
def test_redirection_to_home_when_group_does_not_exist(create_social_user):
"""Some docstring defining what the test is checking."""
c = Client()
c.login(username='TEST_USERNAME', password='TEST_PASSWORD')
response = c.get(reverse('pledges:home_group',
kwargs={'group_id': 100}),
follow=True)
SimpleTestCase.assertRedirects(response, reverse('pledges:home'))
However, I am getting the following error:
SimpleTestCase.assertRedirects(response, reverse('pledges:home'))
E TypeError: assertRedirects() missing 1 required positional argument: 'expected_url'
Is there any way I can use pytest to verify redirection with Django? Or I should go the way using a class that inherits from SimpleTestCase
?
pytest-django Documentation. pytest-django is a plugin for pytest that provides a set of useful tools for testing Django applications and projects.
shortcuts and for redirection to the Django official website we just pass the full URL to the 'redirect' method as string, and for the second example (the viewArticle view) the 'redirect' method takes the view name and his parameters as arguments.
Django's unit tests use a Python standard library module: unittest . This module defines tests using a class-based approach.
pytest.mark. django_db([transaction=False, reset_sequences=False, databases=None]) This is used to mark a test function as requiring the database. It will ensure the database is set up correctly for the test. Each test will run in its own transaction which will be rolled back at the end of the test.
This is an instance method, so it will never work like a class method. You should be able to simply change the line:
SimpleTestCase.assertRedirects(...)
into:
SimpleTestCase().assertRedirects(...)
i.e. we're creating an instance in order to provide a bound method.
I'm not an expert with pytest so probably is not elegant but you can check for the Location
header like
test_whatever(self, user):
client = Client()
url = reverse('admin:documents_document_add')
client.force_login(user)
response = client.post(url, {<something>})
# if the document is added correctly we redirect
assert response.status_code == 302
assert response['Location'] == reverse('admin:documents_document_changelist')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With