使用django测试客户端发送JSON

Har*_*ody 36 django json unit-testing

我正在开发一个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")
Run Code Online (Sandbox Code Playgroud)

# 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'],
        }
Run Code Online (Sandbox Code Playgroud)

编辑:整个追溯.

======================================================================
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'...
Run Code Online (Sandbox Code Playgroud)

Gui*_*ent 60

@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")
Run Code Online (Sandbox Code Playgroud)

json.dumps而不是json.loads


Chr*_*amb 13

尝试:

 self.client.generic('POST', '/url', json.dumps({'json': 'object'})
Run Code Online (Sandbox Code Playgroud)


小智 10

从 Django 3.0 开始,您只需添加content_type=\'application/json\'数据并将其作为 Python 字典传递即可。

\n

来自 Django 文档(“发出请求”部分):

\n
\n

如果您将 content_type 提供为 application/json,则数据\xe2\x80\x99 是字典、列表或元组,\n则使用 json.dumps() 进行序列化。\n默认情况下使用 DjangoJSONEncoder 执行序列化,并且\n可以覆盖通过向客户端提供 json_encoder 参数。put()、patch() 和delete() 请求也会发生这种\n序列化。

\n
\n
response = client.post(\n    f\'/customer/{customer.id}/edit\',\n    {\'email\': new_email},\n    content_type=\'application/json\'\n)\n
Run Code Online (Sandbox Code Playgroud)\n


ame*_*ara 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)
Run Code Online (Sandbox Code Playgroud)


Duš*_*ďar 5

rest_frameworkAPIClient(这是默认client_classAPITestCase)开倾倒照顾dictJSON,它通过使设置适当的内容类型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)
Run Code Online (Sandbox Code Playgroud)


cza*_*aic 2

您可以使用iteritems字典来循环

for index, p in prospects_json.iteritems():
  prospect={
    'email': p['email'],
  }
Run Code Online (Sandbox Code Playgroud)

或者替代地

for index in prospect_json:
  prospect={
    'email': prospect_json[ index ]['email']
  }
Run Code Online (Sandbox Code Playgroud)