Opened 14 years ago
Closed 14 years ago
#15736 closed New feature (wontfix)
test.client.RequestFactory doesn't support sessions
Reported by: | Paul Winkler | Owned by: | nobody |
---|---|---|---|
Component: | Testing framework | Version: | 1.3 |
Severity: | Normal | Keywords: | |
Cc: | Preston Timmons | Triage Stage: | Unreviewed |
Has patch: | no | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | no | UI/UX: | no |
Description
I have some helper functions called by various views which take a request as an argument.
I would like to be able to unit-test these.
They are not views exposed by a URL, so I can't use self.client.get(...).
RequestFactory().get('')
would be an ideal way to do this, except that it blows up any code that expects request.session or request.cookies to exist:
$ django-admin.py shell >>> r = RequestFactory().get('/foo') >>> request.session Traceback (most recent call last): File "<console>", line 1, in <module> AttributeError: 'WSGIRequest' object has no attribute 'session'
By contrast, test.client.Client supports sessions just fine.
I was able to get my tests working with this monkeypatch, which just copies the _request implementation
into RequestFactory:
def _session(self): """ Obtains the current session variables. """ if 'django.contrib.sessions' in settings.INSTALLED_APPS: engine = import_module(settings.SESSION_ENGINE) cookie = self.cookies.get(settings.SESSION_COOKIE_NAME, None) if cookie: return engine.SessionStore(cookie.value) return {} def request(self, **request): "Construct a generic request object." req = WSGIRequest(self._base_environ(**request)) req.session = self._session() return req RequestFactory._session = _session RequestFactory.request = request
Change History (4)
comment:1 by , 14 years ago
Summary: | test.client.RequestFactory doesn't support sessions or cookies → test.client.RequestFactory doesn't support sessions |
---|
comment:2 by , 14 years ago
ignore the part about request.cookies, obviously that's supposed to be request.COOKIES which works fine.
comment:3 by , 14 years ago
Cc: | added |
---|
comment:4 by , 14 years ago
Component: | Uncategorized → Testing framework |
---|---|
Resolution: | → wontfix |
Status: | new → closed |
Type: | Uncategorized → New feature |
I think this would be the wrong direction for RequestFactory. In real code, a bare request has no session attribute - that's added only by SessionMiddleware, which is part of a contrib app, not even part of the core framework. Your test failure is correctly telling you that your helper function requires a request object that's been annotated with a session attribute, so your test should explicitly do that annotation in the test setup, if it's a unittest and not an end-to-end test that runs the full request-response cycle (including middleware).
oops, forgot this part of the monkeypatch... request.cookies doesn't exist either:
def request(self, request):