Skip to content

Instantly share code, notes, and snippets.

@jimr
Last active July 4, 2022 09:40
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jimr/9470633 to your computer and use it in GitHub Desktop.
Save jimr/9470633 to your computer and use it in GitHub Desktop.
Generate fake WSGIRequest objects for use in Django views
def fake_request(method=None, fake_user=False):
'''Returns a fake `WSGIRequest` object that can be passed to viewss.
If `fake_user` is `True`, we attach a random staff member to the request.
Even if not set, you can still do this manually by setting the `user`
attribute on the returned object.
The `GET` and `POST` `QueryDict` objects are mutable::
req = fake_request(mutable=True)
req.GET['q'] = 'abc'
my_view(req)
'''
request = WSGIRequest({
'REQUEST_METHOD': method or 'GET',
'wsgi.input': StringIO(),
})
if fake_user:
# Any staff member will do
request.user = User.objects.filter(
is_staff=True, is_active=True
)[0]
request.GET = QueryDict('', mutable=True)
request.POST = QueryDict('', mutable=True)
return request
@jerryankur
Copy link

better write from where to import StringIO()

@jerryankur
Copy link

jerryankur commented Jul 4, 2022

from django.core.handlers.wsgi import WSGIRequest
from io import StringIO
from django.http import QueryDict

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment