使用django测试客户端发送JSON

问题描述 投票:35回答:6

我正在开发一个django项目,它将作为webhook的端点。 webhook会将一些JSON数据发送到我的端点,然后端点将解析该数据。我正在尝试为它编写单元测试,但我不确定我是否正确地发送了JSON。

我一直在pipeline_endpoint中得到“TypeError:string indices必须是整数”

这是代码:

# tests.py
from django.test import TestCase
from django.test.client import Client
import simplejson

class TestPipeline(TestCase):

    def setUp(self):
        """initialize the Django test client"""
        self.c = Client()

    def test_200(self):
        json_string = u'{"1": {"guid": "8a40135230f21bdb0130f21c255c0007", "portalId": 999, "email": "fake@email"}}'
        json_data = simplejson.loads(json_string)
        self.response = self.c.post('/pipeline-endpoint', json_data, content_type="application/json")
        self.assertEqual(self.response.status_code, "200")

# views.py
from pipeline.prospect import Prospect
import simplejson

def pipeline_endpoint(request):

    #get the data from the json object that came in
    prospects_json = simplejson.loads(request.raw_post_data)
    for p in prospects_json:
        prospect = {
            'email'          : p['email'],
            'hs_id'          : p['guid'],
            'portal'         : p['portalId'],
        }

编辑:整个追溯。

======================================================================
ERROR: test_200 (pipeline.tests.TestPipeline)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "F:\......\pipeline\tests.py", line 31, in test_200
    self.response = self.c.post('/pipeline-endpoint', json_string, content_type="application/json")
  File "C:\Python27\lib\site-packages\django\test\client.py", line 455, in post
    response = super(Client, self).post(path, data=data, content_type=content_type, **extra)
  File "C:\Python27\lib\site-packages\django\test\client.py", line 256, in post
    return self.request(**r)
  File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 111, in get_response
    response = callback(request, *callback_args, **callback_kwargs)
  File "F:\......\pipeline\views.py", line 18, in pipeline_endpoint
    'email'          : p['email'],
TypeError: string indices must be integers

----------------------------------------------------------------------
Ran 1 test in 0.095s

FAILED (errors=1)
Destroying test database for alias 'default'...
django json unit-testing
6个回答
57
投票

@mrmagooey是对的

def test_your_test(self):
    python_dict = {
        "1": {
            "guid": "8a40135230f21bdb0130f21c255c0007",
            "portalId": 999,
            "email": "fake@email"
        }
    }
    response = self.client.post('/pipeline-endpoint/',
                                json.dumps(python_dict),
                                content_type="application/json")

使用json.dumps而不是json.loads


13
投票

尝试:

 self.client.generic('POST', '/url', json.dumps({'json': 'object'})

9
投票

您始终可以使用加载原始请求数据的HttpRequest.body。这样您就可以处理自己的数据处理。

c = Client()
json_str= json.dumps({"data": {"id": 1}})
c.post('/ajax/handler/', data= json_str, content_type='application/json',
                                         HTTP_X_REQUESTED_WITH='XMLHttpRequest')


def index(request):
    ....
    print json.loads(request.body)

4
投票

rest_frameworkAPIClient(这是client_class中的默认APITestCase)负责将dict倾倒到JSON,它通过传递format='json'设置适当的内容类型。

from rest_framework import status
from rest_framework.test import APIClient, APITestCase


class MyTestCase(APITestCase):
    url = '/url'

    def post(self, payload, url=None):
        """
        Helper to send an HTTP post.

        @param (dict) payload: request body

        @returns: response
        """
        if url is None:
            url = self.url

        return self.client.post(url, payload, format='json')

    def test_my_function(self):
        payload = {
            'key': 'value'
        }
        response = self.post(payload)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

2
投票

你可以在字典上使用iteritems来循环

for index, p in prospects_json.iteritems():
  prospect={
    'email': p['email'],
  }

或者

for index in prospect_json:
  prospect={
    'email': prospect_json[ index ]['email']
  }

0
投票

从Django 2.1中添加Guillaume Vincent的答案,我们不再需要使用json.dumps来传递数据。

在Django 2.1中更改:添加了上述JSON序列化。在旧版本中,您可以在将数据传递给post()之前调用json.dumps()以实现相同的功能。

© www.soinside.com 2019 - 2024. All rights reserved.