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|
|"""Annotate a request object with a session"""|
|middleware = SessionMiddleware()|
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.