Learning Django Unit test of a Jsonresponse POST
Question: I've written a **view** to handle post and get request:

    
    
    from django.http import JsonResponse, request
    import json
    
    def Dati(request):
    if request.method == 'GET':
        dati = externalfunction()
        return JsonResponse(dati)
    
    elif request.method == 'POST':
        data = json.loads(request.POST['json'])
        for item in data:
             print " POST DA clIENT:", item, data[item]
    
        # FEEDBACK 
        resp = {"ok":"ricevuto"}
        return JsonResponse(resp)
    

here is the **test.py**

    
    
    from rest_framework.test import APIClient
    from myapp.views import Dati
    
    class ComPageTest(TestCase):
    
    def test_url_resolves_to_vista_Dati(self):
        found = resolve('/mixd/') 
        self.assertEqual(found.func, Dati) 
    
    def test_Dati_GET(self):
        client = APIClient()
        response = client.get('/mixd/')   
        self.assertIn(b'power', response.content)
    
    def test_Dati_POST(self):
        client = APIClient()
        response = client.post('/mixd/', {'power': 'on'}, format='json')
        self.assertIn(b'ok', response.content)
    

the GET test run fine, the POST return this error:

    
    
        2015-08-09 10:32:49,131 - ERROR - Internal Server Error: /mixd/
    Traceback (most recent call last):
      File "/home/x/.virtualenvs/venvv/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 132, in get_response
    /datastructures.py", line 322, in __getitem__
        raise MultiValueDictKeyError(repr(key))
    MultiValueDictKeyError: "'json'"
    *** MultiValueDictKeyError: "'json'"
    

if I access the page manually everything seems fine POST seems to work. is
there some special syntax to follow?


Answer: Your `post data` is seem as

    
    
    {'power': 'on'}
    

Then `request.POST['json']` will get `MultiValueDictKeyError: "'json'"` ?.Try

    
    
    client.post('/mixd/', json.dumps({'power': 'on'}),
                                    content_type="application/json")
    

And then change

    
    
    data = json.loads(request.POST['json'])
    

to

    
    
    data = json.loads(request.body)   #request.raw_post_data on Django < 1.4)
    

