| 1 | from django.test import Client |
|---|
| 2 | from django.core.handlers.wsgi import WSGIRequest |
|---|
| 3 | from django.core.handlers.base import BaseHandler |
|---|
| 4 | |
|---|
| 5 | class RequestFactory(Client): |
|---|
| 6 | """ |
|---|
| 7 | Class that lets you create mock Request objects for use in testing. |
|---|
| 8 | |
|---|
| 9 | Usage: |
|---|
| 10 | |
|---|
| 11 | rf = RequestFactory() |
|---|
| 12 | get_request = rf.get('/hello/') |
|---|
| 13 | post_request = rf.post('/submit/', {'foo': 'bar'}) |
|---|
| 14 | |
|---|
| 15 | This class re-uses the django.test.client.Client interface, docs here: |
|---|
| 16 | http://www.djangoproject.com/documentation/testing/#the-test-client |
|---|
| 17 | |
|---|
| 18 | Once you have a request object you can pass it to any view function, |
|---|
| 19 | just as if that view had been hooked up using a URLconf. |
|---|
| 20 | |
|---|
| 21 | From: http://www.djangosnippets.org/snippets/963/ |
|---|
| 22 | """ |
|---|
| 23 | def request(self, **request): |
|---|
| 24 | """ |
|---|
| 25 | Similar to parent class, but returns the request object as soon as it |
|---|
| 26 | has created it. |
|---|
| 27 | """ |
|---|
| 28 | environ = { |
|---|
| 29 | 'HTTP_COOKIE': self.cookies, |
|---|
| 30 | 'PATH_INFO': '/', |
|---|
| 31 | 'QUERY_STRING': '', |
|---|
| 32 | 'REQUEST_METHOD': 'GET', |
|---|
| 33 | 'SCRIPT_NAME': '', |
|---|
| 34 | 'SERVER_NAME': 'testserver', |
|---|
| 35 | 'SERVER_PORT': 80, |
|---|
| 36 | 'SERVER_PROTOCOL': 'HTTP/1.1', |
|---|
| 37 | } |
|---|
| 38 | environ.update(self.defaults) |
|---|
| 39 | environ.update(request) |
|---|
| 40 | request = WSGIRequest(environ) |
|---|
| 41 | handler = BaseHandler() |
|---|
| 42 | handler.load_middleware() |
|---|
| 43 | for middleware_method in handler._request_middleware: |
|---|
| 44 | if middleware_method(request): |
|---|
| 45 | raise Exception("Couldn't create request mock object - " |
|---|
| 46 | "request middleware returned a response") |
|---|
| 47 | return request |
|---|
| 48 | |
|---|
| 49 | request_factory = RequestFactory() |
|---|