jeudi 15 mars 2018

POST document with Django RequestFactory instead of form data

I'd like to build a request for testing middleware, but I don't want POST requests to always assume I'm sending form data. Is there a way to set request.body on a request generated from django.test.RequestFactory?

I.e., I'd like to do something like:

from django.test import RequestFactory
import json

factory = RequestFactory(content_type='application/json')
data = {'message':'A test message'}
body = json.dumps(data)
request = factory.post('/a/test/path/', body)

# And have request.body be the encoded version of `body`

The code above will fail the test because my middleware needs the data to be passed as the document in request.body not as form data in request.POST. However, RequestFactory always sends the data as form data.

I can do this with django.test.Client:

from django.test import Client
import json

client = Client()
data = {'message':'A test message'}
body = json.dumps(data)
response = client.post('/a/test/path/', body, content_type='application/json')

I'd like to do the same thing with django.test.RequestFactory.

Aucun commentaire:

Enregistrer un commentaire