Request dummies

If you ever need to create a Django request for testing purposes you can use this:

  1.  
  2. import urllib
  3. from urlparse import urlparse, urlunparse, urlsplit
  4. from django.test.client import FakePayload
  5. from django.conf import settings
  6. from django.conf.urls.defaults import *
  7. from django.http import HttpRequest, HttpResponse
  8. from django.utils.http import urlencode
  9. from django.core.handlers.wsgi import WSGIRequest
  10. from django.http import SimpleCookie
  11.  
  12. def create_request(path, data={}, method="GET"):
  13. parsed = urlparse(path)
  14. environ = {
  15. 'HTTP_COOKIE': SimpleCookie().output(header='', sep='; '),
  16. 'REMOTE_ADDR': '127.0.0.1',
  17. 'SCRIPT_NAME': '',
  18. 'SERVER_NAME': 'testserver',
  19. 'SERVER_PORT': '80',
  20. 'SERVER_PROTOCOL': 'HTTP/1.1',
  21. 'wsgi.version': (1,0),
  22. 'wsgi.url_scheme': 'http',
  23. 'wsgi.errors': None,
  24. 'wsgi.multiprocess': True,
  25. 'wsgi.multithread': False,
  26. 'wsgi.run_once': False,
  27. 'CONTENT_TYPE': 'text/html; charset=utf-8',
  28. 'PATH_INFO': urllib.unquote(parsed[2]),
  29. 'QUERY_STRING': urlencode(data, doseq=True) or parsed[4],
  30. 'REQUEST_METHOD': method,
  31. 'wsgi.input': FakePayload('')
  32. }
  33. return WSGIRequest(environ)
  34.  

It is pretty much a copy&paste from different parts of Django source code. Once you get this dummy request you can invoke actions directly (functions from your views.py)

Enjoyed reading this post?
Subscribe to the RSS feed and have all new posts delivered straight to you.