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.