How to test redirection in Django using pytest?

落爺英雄遲暮 提交于 2020-01-14 10:14:08

问题


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?


回答1:


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.




回答2:


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')


来源:https://stackoverflow.com/questions/48293627/how-to-test-redirection-in-django-using-pytest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!