如何使用pytest在Django中测试重定向?

lmi*_*asf 4 python django pytest pytest-django

我已经知道可以实现从继承的类SimpleTestCase,并且可以通过以下方法测试重定向:

SimpleTestCase.assertRedirects(response, expected_url, status_code=302, target_status_code=200, host=None, msg_prefix='', fetch_redirect_response=True)
Run Code Online (Sandbox Code Playgroud)

但是,我想知道使用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'))
Run Code Online (Sandbox Code Playgroud)

但是,我收到以下错误:

  SimpleTestCase.assertRedirects(response, reverse('pledges:home'))
Run Code Online (Sandbox Code Playgroud)

E TypeError:assertRedirects()缺少1个必需的位置参数:'expected_url'

有什么方法可以使用pytest来验证与Django的重定向?还是我应该使用继承自的类SimpleTestCase

gip*_*ipi 7

我不是 pytest 专家,所以可能不太优雅,但你可以检查标题,Location例如

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')
Run Code Online (Sandbox Code Playgroud)


wim*_*wim 5

这是一个实例方法,因此它永远不会像类方法那样工作。您应该能够简单地更改以下行:

SimpleTestCase.assertRedirects(...)
Run Code Online (Sandbox Code Playgroud)

变成:

SimpleTestCase().assertRedirects(...)
Run Code Online (Sandbox Code Playgroud)

即我们正在创建一个实例以提供一个绑定方法。