简体   繁体   中英

In Django REST API unittest, how do I send JSON parameters as body in client.get() function?

I'm building a REST API with Django and in some places I need to send HTTP GET with many parameters. Because of that I've decided to send them as JSON in the request.body. Now, the app works fine but not the unit testing. I cannot seem to find a way to send the JSON parameters in the body using the self.client.get(). This is what I'm doing:

import json
from django.test import TestCase
from django.core.urlresolvers import reverse

class RestApiTests(TestCase):
    def test_analysis():
        extra = {'CONTENT_TYPE': 'application/json'}
        resp = self.client.get(reverse('restapi_analysis'), data="{'analysisID': 41}", **extra)
        self.assertEqual(json.loads(resp.content)['statusText'], 'Analysis fetched successfully')

Using this and running the unittests I get the following error:

Traceback (most recent call last):
  File "/home/anascu/svn/django-tc-reporting/tcsite/tcapp/tests/test_restapi.py", line 151, in test_analysis
    resp = self.client.get(reverse('restapi_analysis'), data="{'analysisID': 41}", **extra)
  File "/home/anascu/virtenv/tc-tracker/local/lib/python2.7/site-packages/django/test/client.py", line 439, in get
    response = super(Client, self).get(path, data=data, **extra)
  File "/home/anascu/virtenv/tc-tracker/local/lib/python2.7/site-packages/django/test/client.py", line 240, in get
    'QUERY_STRING':    urlencode(data, doseq=True) or parsed[4],
  File "/home/anascu/virtenv/tc-tracker/local/lib/python2.7/site-packages/django/utils/http.py", line 75, in urlencode
for k, v in query],
ValueError: need more than 1 value to unpack

POST works fine but I need to use GET in this case. Is it even possible? Django version is 1.4.5.

Get方法不创建请求正文,您需要使用postputpatch

I hoped someone knows a hidden feature. Anyway, the workaround I find is the Python Requests module, though in this case one should use the LiveServerTestCase class instead TestCase in Django unit testing. Requests allows sending JSON content in the body.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM