学习Jsonresponse POST的Django单元测试

时间:2015-08-09 08:46:30

标签: django unit-testing django-rest-framework

我写了视图来处理发布和获取请求:

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)

这是 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)

GET测试运行正常,POST返回此错误:

    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'"

如果我手动访问该页面,一切似乎很好POST似乎工作。 是否有一些特殊的语法可供使用?

1 个答案:

答案 0 :(得分:1)

您的Intent intent = new Intent(); intent.setAction(Intent.ACTION_SEND); intent.setType("image/*"); String uri = Imageurl; intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(uri))); startActivity(intent); 似乎是

post data

然后{'power': 'on'} 将获得request.POST['json']?。尝试

MultiValueDictKeyError: "'json'"

然后改变

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

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