Failed to check persistent sessions in Django 1.1

As part of the registration process for my site, I have several views that set up session data. Later views depend on the established session data. All this works fine in the browser, however, when I try to check it, the session data seems to be lost between requests, which makes testing impossible. Here is a simple example of the problem I am having. I would expect get_name to gain access to the ['name'] session and return 200, however session data would be lost and get_name would return 302.

>>> c = Client()
>>> r = c.post(reverse(set_name))
>>> r = c.post(reverse(get_name))
>>> r.status_code
200

def set_name(request):  
    request.session['name'] = 'name'
    return HttpResponse()

def get_name(request):
    try:
        name = request.session['name']
    except KeyError:
        return redirect(reverse(set_name))
    return HttpResponse(name)
+3
source share
1 answer

Sessions are tested quite inconveniently in Django. First you need to configure the session mechanism.

class TestSession(TestCase):
"""A class for working with sessions - working.

http://groups.google.com/group/django-users/browse_thread/thread/5278e2f2b9e6da13?pli=1

To modify the session in the client do:
session = self.client.session
session['key'] = 'value'
session.save()
"""

def setUp(self):
    """Do the session preparation magic here"""
    super(TestSession, self).setUp()

    from django.conf import settings
    from django.utils.importlib import import_module
    engine = import_module(settings.SESSION_ENGINE)
    store = engine.SessionStore()
    store.save()  # we need to make load() work, or the cookie is worthless
    self.client.cookies[settings.SESSION_COOKIE_NAME] = store.session_key 

. .

+2

Source: https://habr.com/ru/post/1791261/


All Articles