Bug to set session in Django Test?

24 views
Skip to first unread message

ThePhi

unread,
Sep 30, 2017, 6:30:25 AM9/30/17
to Django users
 Hi!

I have troubles setting cookie in Django test.

class Test_views(TestCase):

    def test_set_cookie(self):
        session = self.client.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.


Is it a bug?

Tim Graham

unread,
Sep 30, 2017, 2:56:01 PM9/30/17
to Django users
There's a test in Django's test suite for this: https://github.com/django/django/blob/fd866c25d1665b73aff0d8312c414ae6f69812a3/tests/test_client_regress/tests.py#L1009-L1015

I guess you'll need to figure out how your project differs from that.

ThePhi

unread,
Oct 1, 2017, 3:07:16 AM10/1/17
to Django users
Thanks.
I've run the test in a django virtualenv, and it's working so I guess Django isn't broken...

But I've copied:

in tests.py
class TestDataMixin:

   
@classmethod
   
def setUpTestData(cls):
        cls
.u1 = User.objects.create_user(username='testclient', password='password')
        cls
.staff = User.objects.create_user(username='staff', password='password', is_staff=True)

class SessionTests(TestDataMixin, TestCase):

   
def test_session_initiale(self): # NOT WORKING
        session
= self.client.session
        session
['session_var'] = 'foo'
        session
.save()

        response
= self.client.get('/check_session/')
       
self.assertEqual(response.content, b'foo')



But I still get the error:
    self.assertEqual(response.content, b'foo')
AssertionError: b'NO' != b'foo'



ThePhi

unread,
Oct 1, 2017, 4:43:41 AM10/1/17
to Django users
SOLVED!

I was using the wrong SESSION_ENGINE in settings:

SESSION_ENGINE = 'django.contrib.sessions.backends.signed_cookies'

I forgot that I've done that...

Reply all
Reply to author
Forward
0 new messages