Unit testing Django JSON View Unit testing Django JSON View json json

Unit testing Django JSON View


Final edit

I originally stated that header HTTP_X_REQUESTED_WITH='XMLHttpRequest' was necessary in the post call but this is currently false while in tests. This header is necessary for the csrf middleware but csrf is disabled in tests. However, I still believe it is a good practice to put in test even if middleware disables csrf since most javascript library already pass this header by default when doing ajax. Also, if another piece of code that is not disabled ever use the is_ajax method, you won't need to debug your unittest for hours to figure out that the header was missing.

The problem is with the content-type because when django gets a value in there that is different than text/html, it doesn't use the default post data handling which is to format your data like in a query: type=book&author=JohnDoe for example.

Then the fixed code is:

response = self.client.post(reverse('ajax_view'),                            {'form':json_string},                             HTTP_X_REQUESTED_WITH='XMLHttpRequest')

Here's how I'm using it myself:

post_data = {     "jsonrpc" : "2.0", "method": method, "params" : params, "id" : id }return client.post('/api/json/',                     json.dumps(post_data), "text/json",                                HTTP_X_REQUESTED_WITH='XMLHttpRequest')

to do some json-rpc. Notice that since I pass a different content-type than the default value, my data is passed as is in the post request.


Thank you to @Eric_Fortin for turning me on to the header, it does not however resolve my issue with the malformed query dictionary using 'client.post'. Once I made the change from POST to GET with the XMLHttpRequest header my query dictionary straitened itself out. Here is the current solution:

response = self.client.get(reverse('ajax_view'),                           {'form':json_string},'json',                           HTTP_X_REQUESTED_WITH='XMLHttpRequest')

this is only a partial answer since this request is going to change data on the server and should be POST not a GET.

Edit:

Here is the final code in my test that works for passing a JSON string via POST to my view:

response = self.client.post(reverse('ajax_view'),                            {'form':json.dumps(json_dict)})

Now printing from the view shows that the query dictionary is well formed.

<QueryDict: {u'form': [u'{"resource": {"status": "reviewed", "name": "Resource Test", "description": "Unit Test"}}']}>

I found the answer while tinkering with one of my co-workers, removing the content_type 'json' fixed the malformed query dictionary. The view that is being tested does not make use of or call the 'HttpRequest.is_ajax()', sending the header XMLHttpRequest' has no impact on my issue, though including the header would constitute good-form since this post is an ajax request.