Skip to content

Instantly share code, notes, and snippets.

@jerryankur
Forked from jimr/fake_request.py
Last active July 4, 2022 09:40
Show Gist options
  • Save jerryankur/9bdf9ac2873669b7c387f7c76ce42e78 to your computer and use it in GitHub Desktop.
Save jerryankur/9bdf9ac2873669b7c387f7c76ce42e78 to your computer and use it in GitHub Desktop.
Generate fake WSGIRequest objects for use in Django views
from django.core.handlers.wsgi import WSGIRequest
from io import StringIO
from django.http import QueryDict
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
Author

from io import StringIO

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