The Django RequestFactory is a useful tool for writing unit tests against Django views. I was using it to test some code that interacts with Cartridge, and ran into trouble because the RequestFactory doesn’t annotate request objects with Session objects, which is what Cartridge expects.
Turns out you can add the sessions by manually invoking the relevant middleware:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.contrib.sessions.middleware import SessionMiddleware | |
def add_session_to_request(request): | |
"""Annotate a request object with a session""" | |
middleware = SessionMiddleware() | |
middleware.process_request(request) | |
request.session.save() |
Note that saving the session object seems to be required in order to generate the associated session_key field, which the Cartridge code was looking for.
Exactly what I needed!
Excellent! how can we do it with mock ?
Solve the issue within 1 minute by reading this, thanks!
Very ty for this mock)
Nice one thanks. Still works in 2016!!
Thank you, Still works in 2018!!