【发布时间】:2014-02-18 06:41:37
【问题描述】:
下午好。
我正在使用 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。当我将数据发布到 url 时它坏了。
当我在 shell 中运行相同的代码时,代码运行没有问题。我是测试新手,可能会遗漏一些东西,请帮忙。
【问题讨论】:
-
您能否在加载
response.content之前尝试做出Content-Type和status_code断言?另外,请提供完整的追溯。 -
它没有改变任何东西,因为错误出现在之前。回溯 - pastebin.com/ZrHTeFme
-
我也遇到了这个问题。会尝试调查一下。
标签: python django http-post django-rest-framework pytest