python – 启动py.test后,在读取请求的数据流后无法访问正文

前端之家收集整理的这篇文章主要介绍了python – 启动py.test后,在读取请求的数据流后无法访问正文前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

下午好.

我正在使用pytest测试基于django-rest-framework的api.我有以下创建新对象的方法(方法取自here):

class JSONResponse(HttpResponse):
    """
    An HttpResponse that renders its content into JSON.
    """

    def __init__(self,data,**kwargs):
        content = JSONRenderer().render(data)
        kwargs['content_type'] = 'application/json'
        super(JSONResponse,self).__init__(content,**kwargs)


@csrf_exempt
@api_view(('POST',))
@permission_classes((IsAuthenticated,))
def create_transaction(request):
    """
    The method takes the data in JSON-format.
    If the data is correct Transaction object will created,otherwise it returns an error also in JSON-format.
    """

    stream = StringIO('[' + request.raw_post_data + ']')
    data = JSONParser().parse(stream)
    serializer = NewTransactionSerializer(data=data,many=True)
    if serializer.is_valid():
        serializer.save()
        return JSONResponse(serializer.data,status=201)
    else:
        return JSONResponse(serializer.errors,status=400)

我写了下一个测试:

@pytest.mark.django_db
def test_create_method(client):
    correct_data = '''{ "var1": "111","var2": "222","var3": 2 }'''
    client.login(username='test2@github.com',password='test')
    data = json.loads(correct_data)
    response  = client.post('/rest2/create_transaction/',format='json')
    content = json.loads(response.content)
    assert content[0]['var1'] == '111'
    assert content[0]['var2'] == '222'
    assert content[0]['var3'] == 2
    assert response['Content-Type'] == 'application/json'
    assert response.status_code == 201

启动pytest时显示以下内容:异常:从请求的数据流中读取后无法访问正文.当我将数据发布到网址时,它就破了.
当我在shell中运行相同的代码时,代码运行没有问题.我是新手测试,可能会错过一些东西,请帮忙.

最佳答案
如果您正在使用django-rest-framework,那么您可以使用request.data而不是尝试自己解析请求中的json

http://www.django-rest-framework.org/api-guide/requests/

 stream = StringIO('[' + request.raw_post_data + ']')
 data = JSONParser().parse(stream)

这可以替换为

data = request.data

猜你在找的Python相关文章