10

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.

Any ideas?

EDIT: adding test case

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

The last statement returns an empty list.

cyberdelia
  • 5,343
  • 1
  • 19
  • 16
Marco Lima
  • 103
  • 1
  • 6
  • 2
    It would be helpful to see the test case. – Mark Lavin May 24 '12 at 14:00
  • 1
    I can't reproduce the behavior you are describing and looking through the `TestClient` source it seems clear that cookies should be available on the client and the response https://github.com/django/django/blob/master/django/test/client.py#L411 If you are using the session middleware then at a minimum you would have a session cookie. – Mark Lavin May 24 '12 at 19:43

1 Answers1

16

You need to use the response's client instance:

response = self.client.get(url)
response.client.cookies.items()
Bernhard
  • 8,583
  • 4
  • 41
  • 42
  • Why does this work instead of `self.client.cokies.items()`? – Flimm Jan 13 '16 at 17:00
  • I can't remember. According to the current documentation it should work with self.client.cookies in version 1.6+. I haven't checked older docs, but maybe in 1.3 (or so) the test client did not capture the cookies and only the response client did. – Bernhard Jan 14 '16 at 09:55