1

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.

mehdi lotfi
  • 11,194
  • 18
  • 82
  • 128
  • Why did you make the `data` as string? It can just be `{'analysisID': 41}` removed double quotes for JSON. I guess that is creating the entire problem. – iraycd May 25 '14 at 10:00
  • https://github.com/django/django/blob/stable/1.4.x/django/utils/http.py#L75 See here the query `dict` not `string` – iraycd May 25 '14 at 10:05
  • Indeed if I remove the `data` and double quotes I won't get the previous error but I don't get the JSON object into body either. The dictionary will be passed as normal `QUERY_STRING` and end up in a `QueryDict`. – Adrian Nascu May 25 '14 at 11:37

2 Answers2

0

Get method does not create request body, you need to use post, put or patch.

zymud
  • 2,221
  • 16
  • 24
0

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.