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

时间:2018-01-17 04:30:47

标签: 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)

但是,我想知道使用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'))

但是,我收到以下错误:

  SimpleTestCase.assertRedirects(response, reverse('pledges:home'))
     

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

有什么办法可以用pytest验证Django的重定向吗?或者我应该使用继承自SimpleTestCase

的类

2 个答案:

答案 0 :(得分:5)

这是一个实例方法,因此它永远不会像类方法那样工作。您应该只需更改一行:

SimpleTestCase.assertRedirects(...)

成:

SimpleTestCase().assertRedirects(...)

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

答案 1 :(得分:0)

我不是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')