2011-12-20 33 views
27

Tôi đang làm việc trên django một dự án sẽ đóng vai trò điểm cuối cho webhook. Webhook sẽ POST một số dữ liệu JSON tới điểm cuối của tôi, sau đó sẽ phân tích cú pháp dữ liệu đó. Tôi đang cố gắng viết các bài kiểm tra đơn vị cho nó, nhưng tôi không chắc liệu tôi có gửi đúng JSON hay không.Gửi JSON bằng ứng dụng khách thử nghiệm django

tôi tiếp tục nhận được "Lỗi Loại: chỉ số chuỗi phải là số nguyên" trong pipeline_endpoint

Dưới đây là các mã:

# 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": "[email protected]"}}' 
     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'], 
     } 

Edit: toàn bộ traceback.

====================================================================== 
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

Vui lòng hiển thị toàn bộ lượt truy cập –

+0

được cập nhật với traceback! –

+1

Có phải ... vì bạn nên sử dụng 'json.dumps' (với một đối tượng python) thay vì' json.loads' (với một chuỗi), và do đó bạn đang gửi thông qua một đối tượng python với yêu cầu máy khách của bạn, thay vào đó hơn một đối tượng python được tuần tự hóa như một đối tượng json? – mrmagooey

Trả lời

2

Bạn có thể sử dụng iteritems vào từ điển để lặp

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

hoặc cách khác

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

Cảm ơn lời nhắc nhở iteritems() nhưng tôi vẫn đang có một JSONDecodeError. Bất cứ điều gì trông kỳ lạ với JSON. –

+0

Không, trên thực tế nó hoạt động tốt trong vỏ. Bạn có thể cập nhật traceback của mình không? – czarchaic

36

@mrmagooey là đúng

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

sử dụng json.dumps thay vì json.loads

7

Bạn luôn có thể sử dụng HttpRequest.body để tải dữ liệu yêu cầu thô. Bằng cách này bạn có thể xử lý việc xử lý dữ liệu của riêng bạn.

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) 
6

Hãy thử:

+0

Hoạt động tốt với 'GET'! Cảm ơn bạn! – Giordano

1

rest_framework 's APIClient sẽ chăm sóc của bán phá giá dict-JSON và nó đặt kiểu nội dung thích hợp bằng cách thông qua format='json'.

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


class MyTestCase(APITestCase): 
    client_class = APIClient 
    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(status.HTTP_200_OK, response.status_code) 
Các vấn đề liên quan