Last active
July 4, 2022 09:40
-
-
Save jimr/9470633 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
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 |
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
better write from where to import StringIO()