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?

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.