Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django: Testing POST-based views with json objects

I have a django application with several views that accept json objects via POST requests. The json objects are medium-complex with a few layers of nesting, so I'm using the json library to parse raw_post_data, as shown here:

def handle_ajax_call(request):
    post_json = json.loads(request.raw_post_data)

    ... (do stuff with json query)

Next, I want to write tests for these views. Unfortunately, I can't figure out how to pass the json object to the Client. Here's a simplest-case version of my code:

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 )

When I run the test, it fails with:

AttributeError: 'str' object has no attribute 'items'

How can I pass the JSON object in the Client.post method?

like image 768
Abe Avatar asked Aug 03 '12 19:08

Abe


1 Answers

The documentation seems to imply that if you pass a content_type parameter to client.post, it will treat the data value as a document and POST it directly. So try this:

response = c.post('/ajax/call/', content_type='application/json', data=J_string)
like image 163
Daniel Roseman Avatar answered Nov 05 '22 11:11

Daniel Roseman