[Fixed]-Django: set cookie on test client?

7👍

The client.get method takes a follow argument which allows it to follow redirects:

response = self.client.get('/contact/', follow=True)

25👍

None of the above worked for me (Django1.9, Python3.4). Found this solution here:

from django.test import TestCase    
from http.cookies import SimpleCookie


class TestViewWithCookies(TestCase):

    def test_votes(self):
        self.client.cookies = SimpleCookie({'name': 'bla'})
        response = self.client.get('/vote/2')
        self.assertEqual(response.status_code, 200)

11👍

While the accepted answer is the right approach for this problem, I just want to point out that you can set cookies directly (i.e. approach number (i) as you call it), but not via the test client. Instead you need to use a RequestFactory to construct a request which you can set the cookie on, then pass that directly to the view in question.

So instead of:

response = self.client.get('/contact/')

you do:

request = RequestFactory().get('/contact/')
request.COOKIES['thing'] = 'whatever'
response = contact_view(request)

where contact_view is the view serving /contact/.

10👍

You can set cookies for test client by calling load on cookies attribute which is SimpleCookie object.

from django.core import signing

self.client.cookies.load({
    'example': '123',
    'signed_example': signing.get_cookie_signer('signed_example').sign('123')
})

Django’s test client is stateful – will persist cookies between tests and will ignore expire dates. For removal, you need to manually remove cookie or create a new client. – See docs

— For Python 3 and Django 2+

3👍

This is an old question but maybe this is handy for someone:

from http.cookies import SimpleCookie

from django.test import TestCase, Client


class CookieClientTests(TestCase):
    def test_cookie(self):
        cookies = SimpleCookie()
        cookies["cookie_key"] = "something"
        client = Client(HTTP_COOKIE=cookies.output(header='', sep='; '))

        resp = client.get("/")
        self.assertEqual(200, resp.status_code)
👤sLoK

Leave a comment