weixin_33720452 2016-12-06 12:26 采纳率: 0%
浏览 39

Django和JSON / AJAX测试

I tried looking around for an answer and gave it a great many tries, but there's something strange going on here. I got some functions in my view that operate on JSON data that comes in via AJAX. Currently I'm trying to do some unit testing on these.

In my test case I have:

kwargs = {'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'}
url = '/<correct_url>/upload/'
data = {
                "id" : p.id
}

c = Client()
response = c.delete(url, data, **kwargs)

content_unicode = response.content.decode('utf-8')
content = json.loads(content_unicode)

p.id is just an integer that comes from a model I'm using.

I then have a function that is being tested, parts of which looks like follows:

def delete_ajax(self, request, *args, **kwargs):
    print (request.body)
    body_unicode = request.body.decode('utf-8')
    print (body_unicode)
    body_json = json.loads(body_unicode)

The first print statement yields:

.....b"{'id': 1}"

The other one:

{'id': 1}

and finally I get an error for fourth line as follows:

json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

What's going wrong here? I understand that correct JSON format should be {"id": 1} and that's what I'm sending from my test case. But somewhere along the way single-quotes are introduced into the mix causing me head ache.

Any thoughts?

  • 写回答

1条回答 默认 最新

  • 衫裤跑路 2016-12-06 12:50
    关注

    You need to pass a json string to Client.delete(), not a Python dict:

    kwargs = {'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'}
    url = '/<correct_url>/upload/'
    data = json.dumps({
     "id" : p.id
     })
    
    c = Client()
    response = c.delete(url, data, **kwargs)
    

    You should also set the content-type header to "application/json" and check the content-type header in your view but that's another topic.

    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改