samedi 30 septembre 2017

Django test: Setting cookie (Django 1.11+)

I have troubles setting cookie in Django test.

class Test_views(TestCase):

    @classmethod
    def setUpClass(cls):
        pwd = '12345'
        cls.c = Client()
        cls.user_1 = UserFactory(password=pwd)
        cls.c.login(username=cls.user_1.username, password=pwd)
        super(Test_views, cls).setUpClass()

    @classmethod
    def tearDownClass(cls):
        super(Test_views, cls).tearDownClass()

    def test_set_cookie(self):
        session = self.c.session
        session['mycookie'] = 'testcookie'
        session.save()
        response = self.c.get(reverse('homepage')) 
        ...

I print the cookies in the Views to be sure:

views.py

... 
def homepage(request):
        print(request.session.keys())
        ...

And indeed, the cookie mycookie doesn't exist.

Apparently, that's the right way to set cookie:

http://ift.tt/2x4qx3K

Aucun commentaire:

Enregistrer un commentaire