Brian Hicks
Brian Hicks

Reputation: 6413

How do I test a middleware that requires sessions in Django properly?

I'm trying to figure out how to test middleware in django. The middleware I'm writing logs in a user under certain conditions (if a key sent in email is valid). So obviously I'm dependent on django.contrib.auth and django.contrib.sessions.

I'm running into problems testing the login portion. I'm making a request like this:

user = User.objects.create_user('user', '[email protected]', 'password')
key = LoginKey.objects.create(user=user)
request = self.factory.get('/', data={'auth_key': key.hash}) # self.factory is a RequestFactory()
self.middleware.process_request(request) # self.middleware is MyMiddleware()

That fails due to the session not being set. So next, I wrote a little snippet in my test class:

def make_session(self, request):
    SessionMiddleware().process_request(request)

and that fails due to 'User' object has no attribute 'backend'. I'm not sure on the meaning of that, but I suspect I need to run all the middlewares I have installed.

I don't really want to make a fake view for this just to run a middleware, but I can't see another option at this point.

So I just wanted to know, before I have to chase this rabbit all the way down the hole, is there a way of doing this that doesn't require as much duct tape?

Upvotes: 0

Views: 1454

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599926

You should use the test client for this. That will ensure that the middleware is run and the session keys created.

response = self.client.get('/?auth_key=%s' % key.hash)
self.assertTrue(response.context['user'].is_authenticated()) # for example

Upvotes: 1

Related Questions