Django测试重定向到使用下一个参数登录

2024-04-19 23:47:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试测试非登录用户重定向到登录url。有没有一种方法可以通过传递get参数(例如“next”)来反转\u lazy?我使用的是基于类的视图

class SecretIndexViewTest(TestCase):
    url = reverse_lazy('secret_index')
    login_url = reverse_lazy('login')
    client = Client()

    def test_http_status_code_302(self):
        response = self.client.get(self.url)
        self.assertEqual(response.status_code, 302)
        self.assertRedirects(response, self.login_url,)

以上内容与

Response redirected to '/login?next=/secret', expected '/login'Expected '/login?next=/secret' to equal '/login'.

尝试

class SecretIndexViewTest(TestCase):
    url = reverse_lazy('secret_index')
    login_url = reverse_lazy('login', kwargs={'next': url)
    client = Client()

    def test_http_status_code_302(self):
        response = self.client.get(self.url)
        self.assertEqual(response.status_code, 302)
        self.assertRedirects(response, self.login_url,)

结果是没有反向匹配

django.urls.exceptions.NoReverseMatch: Reverse for 'login' with keyword arguments '{'next': '/secret'}' not found. 1 pattern(s) tried: ['/login$']

将kwargs更改为args将导致相同的错误

我知道我可以处理以下问题,但我正在寻找更好的解决方案

self.assertRedirects(response, self.login_url + f"?next={self.url}",)

login_url = reverse_lazy('login') + f"?next={url}"

Tags: selfclienturlgetsecretresponsestatuslogin
1条回答
网友
1楼 · 发布于 2024-04-19 23:47:47

由于mentioned in the Django documentationreverse(和reverse_lazy)不包含GET参数,因此字符串格式示例是最简单的解决方案之一

The URLconf searches against the requested URL, as a normal Python string. This does not include GET or POST parameters, or the domain name.

For example, in a request to https://www.example.com/myapp/, the URLconf will look for myapp/.

In a request to https://www.example.com/myapp/?page=3, the URLconf will look for myapp/.

The URLconf doesn’t look at the request method. In other words, all request methods – POST, GET, HEAD, etc. – will be routed to the same function for the same URL.

如果您担心对查询字符串进行编码,那么可以使用^{} module中的工具(如urllib.parse.urlencode)对查询进行编码,然后通过连接reverse的路径和编码的查询参数来构建完整的URL

对于像测试这样的简单情况,您确切地知道传递的数据是什么,我倾向于使用简单的字符串格式

相关问题 更多 >