我正在开发一个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'...
答案 0 :(得分:55)
@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
答案 1 :(得分:13)
尝试:
self.client.generic('POST', '/url', json.dumps({'json': 'object'})
答案 2 :(得分: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)
答案 3 :(得分:4)
rest_framework
' APIClient
(这是APITestCase
中的默认client_class
)负责将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)
答案 4 :(得分:3)
从 Django 3.0 开始:
<块引用>如果您提供 content_type 作为 application/json,则数据为 如果是字典、列表或元组,则使用 json.dumps() 进行序列化。 默认使用 DjangoJSONEncoder 进行序列化,并且可以 通过向客户端提供 json_encoder 参数来覆盖。这 put()、patch() 和 delete() 请求也会发生序列化。
response = client.post(
f'/customer/{customer.id}/edit',
{'email': new_email},
content_type='application/json'
)
答案 5 :(得分:2)
您可以在词典上使用iteritems
来循环
for index, p in prospects_json.iteritems():
prospect={
'email': p['email'],
}
或者
for index in prospect_json:
prospect={
'email': prospect_json[ index ]['email']
}
答案 6 :(得分:0)
在纪尧姆·文森特(Guillaume Vincent)的回答中,从Django 2.1开始,我们不再需要使用json.dumps传递数据。
在Django 2.1中已更改: 上面介绍了JSON序列化。在旧版本中,您可以在将数据传递给post()之前对数据调用json.dumps()以实现相同的目的。