如何在Django TestCase请求和响应中访问cookie?

ttvkxqim  于 2023-10-21  发布在  Go
关注(0)|答案(2)|浏览(131)

我有一个使用response.set_cookie方法设置cookie的视图。我想测试一下cookie是否设置在TestCase中。
根据docs,cookie应该可以在客户端对象中访问,但是client.cookies.items返回一个空列表。在浏览器中正确设置Cookie。
测试用例:

>>> response = self.client.get(url)
>>> self.client.cookies.items()
[]

有什么想法吗?

dffbzjpn

dffbzjpn1#

您需要使用响应的客户端示例:

response = self.client.get(url)
response.client.cookies.items()
wdebmtf2

wdebmtf22#

response.cookies也能用

response = self.client.get(f'/authors/{author.id}/')
print(response.cookies)
>>> Set-Cookie: user=154; expires=Tue, 17 Oct 2028 00:31:19 GMT; Max-Age=3600; Path=/

但如果你反复使用self.client,似乎并不安全:

response = self.client.get(f'/apps/library/authors/{author.id}/')
print("cookies: ", response.cookies)

# Some random testing...

response = self.client.get(f'/apps/library/authors/{author.id}/')
print("cookies: ", response.cookies)

>>> cookies:  Set-Cookie: user=584; expires=Tue, 17 Oct 2028 02:34:41 GMT; Max-Age=157680000; Path=/
>>> cookies:

response.client.cookies可以很好地处理重复的self.client请求:

response = self.client.get(f'/apps/library/authors/{author.id}/')
print("\ncookies: ", response.cookies)

# Some random testing...

response = self.client.get(f'/apps/library/authors/{author.id}/')
print("\ncookies: ", response.cookies)

>>> cookies:  Set-Cookie: user=97; expires=Tue, 17 Oct 2028 02:44:40 GMT; Max-Age=157680000; Path=/
>>> cookies:  Set-Cookie: user=97; expires=Tue, 17 Oct 2028 02:44:40 GMT; Max-Age=157680000; Path=/

旁注

如果你想访问user值,这是语法:

response.client.cookies["user"].value
>>> 154

response.client.cookies["user"]是一个http.cookies.Morsel对象,因此访问cookie本身的value与访问常规字典不同。

相关问题