我有一个Django应用程序,该应用程序必须具有以下行为:如果请求没有Content-Type
标头,它将返回错误响应。
为了测试此行为,我需要发出不带Content-Type
标头的HTTP请求。
我使用了Client
的类django.test
模块。这有很多方法,包括以下一种:
post(path, data=None, content_type=MULTIPART_CONTENT, follow=False, secure=False, **extra)
在提供的路径上发出POST请求,并返回一个Response对象,如下所述。
[...]
如果提供content_type(例如,
text/xml
用于XML有效负载),则数据内容将在POST请求中使用content_type
HTTPContent-Type
标头按原样发送。如果您不提供的值
content_type
,则数据中的值将以的内容类型传输multipart/form-data
。在这种情况下,数据中的键值对将被编码为多部分消息,并用于创建POST数据有效负载。
文档说Content-Type
,无论是否传递content_type
参数,总是在请求上设置标头。
那么,我还必须以其他什么方式构造一个没有Content-Type
头的请求呢?
您可以通过类RequestFactory构建自定义的请求实例。
生成请求后,您可以在将请求实例传递到视图之前对其进行修改。
以RequestFactory文档页面中的示例为起点,可以执行以下操作:
from django.test import TestCase, RequestFactory
from .views import my_view
class SimpleTest(TestCase):
def setUp(self):
# Every test needs access to the request factory.
self.factory = RequestFactory()
def test_details(self):
# Create an instance of a POST request.
request = self.factory.post('/your/url', data={'your':'data'})
# NOW you can customise your request instance!
# (i.e. remove the Content-Type header)
request.META.pop('CONTENT_TYPE', None)
# Actually use the request to test my_view()
# as if it were deployed at /customer/details
response = my_view(request)
self.assertEqual(response.status_code, 400)
该request.META
仅仅是一个标准的Python字典(如解释在这里),所以你可以使用
del request.META['CONTENT_TYPE']
而不是pop()
删除它,但前提是您必须确定该键将在字典中。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句