#11475: test.Client.session.save() raises error for anonymous users ----------------------------------------+----------------------------------- Reporter: egma...@gmail.com | Owner: nobody Status: new | Milestone: Component: Testing framework | Version: 1.1-beta-1 Resolution: | Keywords: Stage: Unreviewed | Has_patch: 0 Needs_docs: 0 | Needs_tests: 0 Needs_better_patch: 0 | ----------------------------------------+----------------------------------- Comment (by kra...@canonical.org):
Aha! Now I understand. 1. Until you've gotten back a cookie from the middleware (which *does* run from `Client.get`) you don't have the session object. Instead you get the stupid useless empty dict. 2. Obviously you don't get a cookie until after you make a request. (Unless you call `Client.login`.) 3. But even if you make a request, Django won't set the cookie unless the view tries to store something in `request.session`. 4. At that point `self.client.session` will give you a useful object, but it's not the same object the view will use, so if you want to communicate with the view, you have to call `.save()` on it. 5. But you can't just say `self.client.session['foo'] = 'bar'; self.client.session.save()` because, as explained in my previous two comments, you get a separate session object for each time you say `self.client.session`. Instead you have to say `s = self.client.session; s['foo'] = 'bar'; s.save()`, and then everything will work. So now I know. It's not a bug, really; it's just that Django-under-test behaves in a way that makes it error-prone to write unit tests for. It might still be useful to factor out the code in `Client.login` that creates a session and saves the session cookie without making an HTTP request, for tests that want to set up test session data without having to go through whatever series of views are necessary for a real person to set that data. Maybe this is some kind of a Django FAQ. -- Ticket URL: <http://code.djangoproject.com/ticket/11475#comment:4> Django <http://code.djangoproject.com/> The Web framework for perfectionists with deadlines. --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Django updates" group. To post to this group, send email to django-updates@googlegroups.com To unsubscribe from this group, send email to django-updates+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-updates?hl=en -~----------~----~----~----~------~----~------~--~---