[Solved]-How to access cookies in Django TestCase request and responses?

16👍

You need to use the response’s client instance:

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

0👍

response.cookies also works…

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=/

…but if you are repeatedly using self.client, doesn’t seems safe:

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 works just fine with repeated self.client requests:

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=/

Side Note

If you want to access user value, this is the syntax:

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

response.client.cookies["user"] is an http.cookies.Morsel object, so accessing the value of the cookie itself, is different than accessing a regular dictionary.

Leave a comment