When testing your applications I sometimes find myself needing to mock a request object. Unfortunately it is quite hard to find a good fake request factory which mimics a normal request.
Django has a class included for this purpose called RequestFactory. However it doesn’t fake the session object, breaking most of my test code. To fix this I wrote a tiny snippet implementing the RequestFactory with session and user support. Hope it helps 🙂
from django.core.handlers.base import BaseHandler from django.test.client import RequestFactory class RequestMock(RequestFactory): def request(self, **request): "Construct a generic request object." request = RequestFactory.request(self, **request) handler = BaseHandler() handler.load_middleware() for middleware_method in handler._request_middleware: if middleware_method(request): raise Exception("Couldn't create request mock object - " "request middleware returned a response") return request