How to generate a fake HTTP (WSGIRequest) request object for unit test in Python?

In a Python Django project, we want a unit test to feed a HTTP POST request into the function under test. The cURL sample command below shows our test settings.

The cURL approach starts from the web server’s endpoint and triggers the entire logic path, but we want the unit test to focus on a specific function taking in the request argument. And, we got hint from this post with the below sample Python source code to fake a HTTP request for testing.

Our Question:

See the -d argument of the cURL command, we wonder how to feed the request body in the faked object.

Technical Details:

  • The cURL command:
curl http://127.0.0.1:8000/api/transaction/ --insecure \
    --verbose \
    -d '<env:Envelope ... >
  <env:Header>
    ...
  </env:Header>
  <env:Body>
    ...
  </env:Body>
</env:Envelope>
'
  • The Python sample source code for faking a HTTP request:
from django.core.handlers.wsgi import WSGIRequest
from io import StringIO
from django.contrib.auth.models import AnonymousUser

def GetFakeRequest(path='/', user=None):
    """ Construct a fake request(WSGIRequest) object"""
    req = WSGIRequest({
        'REQUEST_METHOD': 'GET',
        'PATH_INFO': path,
        'wsgi.input': StringIO()})

    req.user = AnonymousUser() if user is None else user
    return req

Have you already tried the RequestFactory from django?

1 Like