If no cookies are set in the client, the session property is an empty dict, therefore, your mistake. Here is the corresponding django.test.client.Client source:
def _session(self): """ Obtains the current session variables. """ if 'django.contrib.sessions' in settings.INSTALLED_APPS: engine = import_module(settings.SESSION_ENGINE) cookie = self.cookies.get(settings.SESSION_COOKIE_NAME, None) if cookie: return engine.SessionStore(cookie.value) return {} session = property(_session)
Since you did not enter the cookie with the key settings.SESSION_COOKIE_NAME , it was not found.
However, you can manually create a session object as follows:
if not self.client.session: engine = import_module(settings.SESSION_ENGINE) self.client.session = engine.SessionStore() self.client.session.save()
So the login handler in Client creates a new session.
EDIT: I realized that you also need to save the session key in a cookie so that the next request uses the same session
Here's a helper function that you can subclass in the Client class, which creates a new session and cookie with recommendations:
def set_session_data(self, key, value): """Shortcut for setting session data regardless of being authenticated""" if not self.client.session:
Note. I am not saying that this is the only way to do this, it is one of the ways that I found out by reading the django source code. The code in this answer is not tested / running, so fine tuning may be required.
Further reading
To find out how SessionStore works, you can look at the django.contrib.sessions module.
To find out how sessions and cookies are handled in Client , you can look at django.test.client.Client .
rzetterberg
source share