This works
def test_access_to_home_with_location(self):
self.client.login(username=self.user.get_username(), password='pass')
session = self.client.session
session['location'] = [42]
session.save()
response = self.client.get(reverse('home'))
But this
def test_access_to_home_with_location(self):
session = self.client.session
session['location'] = [42]
session.save()
response = self.client.get(reverse('home'))
breaks with
======================================================================
ERROR: test_access_to_home_with_location (posts.tests.HomeViewTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "tests.py", line 32, in test_access_to_home_with_location
session.save()
AttributeError: 'dict' object has no attribute 'save'
So it seems with out calling self.client.login()
self.client.session
is just an empty dictionary. Is there a way to initialize it as a session object?
Django uses a cookie containing a special session id to identify each browser and its associated session with the site. The actual session data is stored in the site database by default (this is more secure than storing the data in a cookie, where they are more vulnerable to malicious users).
So we have already a session, this session has 'test' as a key and we want to check if this session exists. if 'test' in request. session: print('yes! ')
Please note that workarounds are no longer necessary. The original question's snippet which did not work should now work :
session = self.client.session
session['location'] = [42]
session.save()
https://docs.djangoproject.com/en/2.0/topics/testing/tools/#django.test.Client.session
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With