pythondjangopytestpytest-django

How to test redirection in Django using pytest?


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?


Solution

  • 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.