Getting / Setting session key in Django Unit Tests

835 views Asked by At

I'm saving the session_key to an object to associate data to anonymous users. In Unit Tests, I'm trying to use the Test Client to set a fixed key, but the key changes during a POST request. An example:

// tests.py

def test_post(self):
    session_key = "123"
    session = self.client.session
    session['session_key'] = session_key
    session.save()

    response = self.client.post('/post-url/')
    self.assertEquals(response.content, session_key)
    # AssertionError: b'str60i3gjpvru8f7mellsdf2y3xd2jgh' != '123'


// views.py

@require_http_methods(['POST'])
def ajax_post(request):
    return HttpResponse(request.session.session_key)

Based on this comment, I tried to include another GET response response = self.client.get('/') before the session_key was changed, but it doesn't seem to help.

What am I doing wrong?

EDIT: I am using Django 1.9.6, Python 3.4. Changed question title after Daniel Roseman's answer.

1

There are 1 answers

1
Daniel Roseman On BEST ANSWER

I'm not quite sure what you're doing here. session['session_key'] is not the same as session.session_key; the former is simply another value in the session.

But there's no reason to do anything explicit with the session key. It should be a purely opaque value, which your code never interacts with. If you want to associate data with an anonymous user's session, you should be storing the data in the session, not the other way round.