Unit Testing Django Middleware

Adam Donaghy
1 min readOct 11, 2016

--

Until recently unit testing middleware was a bit of a bit of a mystery. Getting unit tests on everything is pretty important, so I figured I should give it a go. To my surprise Python made this stupidly simple!

Using the “mocks” class I can create a mock request, add some data to it in the header, body or wherever else I need. Then this request can be processed by the middleware whenever I call it. It’s that simple!

from myapp.middleware import UserRequestTracking
from mock import Mock
from .models import *
class AnalyiticsMiddlewareTests(TestCase): def setUp(self):
self.middleware = UserRequestTracking()
self.request = Mock()
self.request.META = {
"HTTP_PROFILE_ID" : self.profileId,
"REQUEST_METHOD": "POST",
"HTTP_OPERATING_SYSTEM_VERSION":"ICE CREAM",
"HTTP_PLATFORM":"ANDROID",
"HTTP_APP_VERSION":"1.0.0",
"HTTP_USER_AGENT":"AUTOMATED TEST"
}
self.request.path = '/testURL/'
self.request.session = {}
def test_requestProcessing(self):
response = self.middleware.process_request(self.request)
self.assertIsNone(response)
# Whatever middleware model is referenced
count = MiddlewareModel.objects.all().count()
self.assertEqual(count, 1)

But why shouldn’t you test the middleware with the integration tests that test your views?

Honestly you should do both! Integration tests will work wonders for finding issues with consumption of endpoints or pages. But this is a unit test, testing for a single components, by adding unit tests it makes bugs easier to find, and easier to fix because you know were the problem lies without all the digging to find where the problem starts. Mocks is the best solution for doing that with Django middleware.

--

--