Adding a session to a Django request generated by RequestFactory

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:

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.

Advertisements
This entry was posted in django and tagged . Bookmark the permalink.

5 Responses to Adding a session to a Django request generated by RequestFactory

  1. gcetusic says:

    Exactly what I needed!

  2. Excellent! how can we do it with mock ?

  3. Wayne Ye says:

    Solve the issue within 1 minute by reading this, thanks!

  4. Bogdan says:

    Very ty for this mock)

  5. JIBBER!!!! says:

    Nice one thanks. Still works in 2016!!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s