5
下午好。启动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='[email protected]', password='test')
data = json.loads(correct_data)
response = client.post('/rest2/create_transaction/', data, 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显示以下内容:Exception: You cannot access body after reading from request's data stream
。当我发布数据到网址时,它坏了。 当我在shell中运行相同的代码时,代码运行时没有问题。我对测试很陌生,可能会错过什么,请帮忙。
你可以尝试在加载'response.content'之前创建你的'Content-Type'和'status_code'断言吗?另外,请提供完整的追溯。 – alecxe
它不会改变任何东西,因为之前出现错误。回溯 - http://pastebin.com/ZrHTeFme – aphex
我也有这个问题。将尝试并研究它。 – Gesias