-
-
Save jerryankur/9bdf9ac2873669b7c387f7c76ce42e78 to your computer and use it in GitHub Desktop.
Generate fake WSGIRequest objects for use in Django views
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
from io import StringIO