Abe*_*Abe 24 django ajax json unit-testing
我有一个django应用程序,有几个视图通过POST请求接受json对象.json对象是中等复杂的,有几层嵌套,所以我使用json库来解析raw_post_data,如下所示:
def handle_ajax_call(request):
post_json = json.loads(request.raw_post_data)
... (do stuff with json query)
Run Code Online (Sandbox Code Playgroud)
接下来,我想为这些视图编写测试.不幸的是,我无法弄清楚如何将json对象传递给客户端.这是我的代码的最简单的版本:
def test_ajax_call(self):
c = Client()
call_command('loadfixtures', 'temp-fixtures-1') #Custom command to populate the DB
J = {
some_info : {
attr1 : "AAAA",
attr2 : "BBBB",
list_attr : [ "x", "y", "z" ]
},
more_info : { ... },
info_list : [ 1, 22, 23, 24, 5, 26, 7 ]
}
J_string = json.dumps(J)
response = c.post('/ajax/call/', data=J_string )
Run Code Online (Sandbox Code Playgroud)
当我运行测试时,它失败了:
AttributeError: 'str' object has no attribute 'items'
Run Code Online (Sandbox Code Playgroud)
如何在Client.post方法中传递JSON对象?
Dan*_*man 52
文档似乎暗示如果您传递content_type
参数client.post
,它会将data
值视为文档并直接POST.试试这个:
response = c.post('/ajax/call/', content_type='application/json', data=J_string)
Run Code Online (Sandbox Code Playgroud)