[Django]-How to unittest "new style" Django middleware

9πŸ‘

βœ…

As you can see, the middleware simply implements a __call__ magic method. This means the instance of this class is callable.

The difference between the old-style and new-style middleware is that the new middleware is simply a callable that returns a callable – first you call it with a get_response callback, and then you call the returned callable with the actual request. get_response is a callable provided/injected by Django itself, and it’s a function used to either return the view response, or the next middleware in the chain.

So, in order to test your SessionMiddleware, you could do the following:

import mock

def test_middleware(self):
    get_response = mock.MagicMock()
    request = self.factory.get('/')

    middleware = SessionMiddleware(get_response)
    response = middleware(request)

    # ensure get_response has been returned 
    # (or not, if your middleware does something else)
    self.assertEqual(get_response.return_value, response)
    
πŸ‘€samu

Leave a comment