如何使用pytest在Django中测试重定向? [英] How to test redirection in Django using pytest?

查看:226
本文介绍了如何使用pytest在Django中测试重定向?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)

但是,我想知道使用pytest检查重定向的方式是什么

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

但是,出现以下错误:

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

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

E TypeError: assertRedirects() missing 1 required positional argument: 'expected_url'

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

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?

推荐答案

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

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(...)

进入:

SimpleTestCase().assertRedirects(...)

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

i.e. we're creating an instance in order to provide a bound method.

这篇关于如何使用pytest在Django中测试重定向?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆