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

How to test redirection in Django using pytest?

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

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() missing 1 required positional argument: 'expected_url'

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

的 class

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

SimpleTestCase.assertRedirects(...)

进入:

SimpleTestCase().assertRedirects(...)

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

我不是 pytest 专家,所以可能不够优雅,但您可以检查 Location header 之类的

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