下午好。
我正在使用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/', 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中运行相同的代码时,代码运行没有问题。我是新手测试,可能会错过一些东西,请帮忙。
答案 0 :(得分:4)
如果您正在使用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