2016-06-14 39 views
0

我试图在DRF中编写一个单元测试,将畸形的json发布到客户端。然而,由于client.post期望一个python字典,它序列化为一个json字符串,我如何发送格式错误的json字符串来测试响应?如何在django单元测试(django REST框架)中发送格式错误的数据

def test_create_resource_malformed_data(self): 
     """ Send malformed data """ 
     malformed_data = '{"malformed":"json"}' 
     test_response = self.client.post(self.url_create, malformed_data, format="json") 

相关回溯:

File "/anaconda/lib/python3.4/site-packages/rest_framework/test.py", line 66, in _encode_data 
ret = renderer.render(data) 
File "/anaconda/lib/python3.4/site-packages/rest_framework/renderers.py", line 160, in render 
view = renderer_context['view'] 
KeyError: 'view' 

回答

2

documentation for Client(其余框架APIClient扩展Django的Client):

如果您提供content_type(如text/xml一个XML有效载荷),对数据内容将在POST请求中按原样发送原样,使用HTTP内容类型头中的。

所以,你可以这样做:

malformed_data = '{"malformed":"json"}' 
test_response = self.client.post(self.url_create, malformed_data, 
           content_type="application/json") 
+0

很好,谢谢solarissmoke :) – Liz