我有一个使用response.set_cookie方法设置cookie的视图。我想测试一下cookie是否设置在TestCase中。根据docs,cookie应该可以在客户端对象中访问,但是client.cookies.items返回一个空列表。在浏览器中正确设置Cookie。测试用例:
response.set_cookie
TestCase
client.cookies.items
>>> response = self.client.get(url) >>> self.client.cookies.items() []
有什么想法吗?
dffbzjpn1#
您需要使用响应的客户端示例:
response = self.client.get(url) response.client.cookies.items()
wdebmtf22#
response.cookies也能用
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,似乎并不安全:
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.client.cookies
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值,这是语法:
user
response.client.cookies["user"].value >>> 154
response.client.cookies["user"]是一个http.cookies.Morsel对象,因此访问cookie本身的value与访问常规字典不同。
response.client.cookies["user"]
value
2条答案
按热度按时间dffbzjpn1#
您需要使用响应的客户端示例:
wdebmtf22#
response.cookies
也能用但如果你反复使用
self.client
,似乎并不安全:response.client.cookies
可以很好地处理重复的self.client
请求:旁注
如果你想访问
user
值,这是语法:response.client.cookies["user"]
是一个http.cookies.Morsel对象,因此访问cookie本身的value
与访问常规字典不同。