Marco Lima
Marco Lima

Reputation: 123

How to access cookies in Django TestCase request and responses?

I have a view that sets a cookie using response.set_cookie method. I would like to test if the cookie is being set in a TestCase.

According to docs, the cookie should be accessible in the client object, but client.cookies.items returns an empty list. The cookie is being correctly set in the browser.

Test case:

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

Any ideas?

Upvotes: 12

Views: 4824

Answers (2)

ivanleoncz
ivanleoncz

Reputation: 10005

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.client.cookies)

# Some random testing...

response = self.client.get(f'/apps/library/authors/{author.id}/')
print("\ncookies: ", response.client.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.

Upvotes: 1

Bernhard
Bernhard

Reputation: 8821

You need to use the response's client instance:

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

Upvotes: 17

Related Questions