相关疑难解决方法(0)

Django:测试页面是否已重定向到所需的URL

在我的django应用程序中,我有一个身份验证系统.因此,如果我没有登录并尝试访问某个配置文件的个人信息,我会被重定向到登录页面.

现在,我需要为此编写一个测试用例.我得到的浏览器的回复是:

GET /myprofile/data/some_id/ HTTP/1.1 302 0
GET /account/login?next=/myprofile/data/some_id/ HTTP/1.1 301 0
GET /account/login?next=/myprofile/data/some_id/ HTTP/1.1 200 6533
Run Code Online (Sandbox Code Playgroud)

我该如何写测试?这就是我到目前为止:

self.client.login(user="user", password="passwd")
response = self.client.get('/myprofile/data/some_id/')
self.assertEqual(response.status,200)
self.client.logout()
response = self.client.get('/myprofile/data/some_id/')
Run Code Online (Sandbox Code Playgroud)

接下来会发生什么?

python django django-testing

57
推荐指数
4
解决办法
4万
查看次数

如何使用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

python django pytest pytest-django

4
推荐指数
2
解决办法
635
查看次数

标签 统计

django ×2

python ×2

django-testing ×1

pytest ×1

pytest-django ×1