0

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 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I almost got it before your answer, but you were still faster. The content-type checking is the next thing to take care of :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.