Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a session variable in django tests

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?

like image 999
Ben Avatar asked Aug 05 '14 06:08

Ben


People also ask

How does Django keep track of a session?

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).

How do you check session is set or not in Django?

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! ')


1 Answers

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

like image 126
Brachamul Avatar answered Sep 17 '22 13:09

Brachamul