[英]test for post API receiving status code 200 instead of 201
My test for my post method API receive status code 200 but should 201 I tried to find where is problem but i couldn't. 我对发布方法API的测试收到状态代码200,但应该201我试图找到问题所在,但我没有。 It would be easier if i would get error status 4xx but i have no idea why post method could receive code 200. My API view works fine so this must be problem with test code but I really don't have idea what may cause this problem.
如果我将收到错误状态4xx,但我不知道为什么post方法为什么可以接收代码200,这会更容易。我的API视图工作正常,因此这一定是测试代码存在的问题,但是我真的不知道可能导致此问题的原因。 Maybe I'm wrong and status code 200 is ok, but I think that post method should receive status 201.
也许我错了,状态码200可以,但是我认为post方法应该接收状态201。
test_api.py test_api.py
def test_post_logged_in(self):
product = Product.objects.get(id=1)
self.client.login(username='test', password='test123')
data = {
'nick': self.user.id,
'rate': '1/5',
'content': 'here is comment',
'product': product.id
}
response = self.client.post(reverse('add_comments', kwargs={'id': product.id}), data, format='json')
self.assertEqual(response.status_code, 201, f'expected Response code 201, instead get {response.status_code}')
views.py views.py
class CreateComment(APIView):
def get_object(self, id):
try:
return Product.objects.get(id=id)
except Product.DoesNotExist:
raise Http404
def get(self,request, id):
product = self.get_object(id)
serializer = ProductSerializer(product)
return Response(serializer.data)
def post(self, request,id):
serializer = CommentSerializer(data=request.data)
if serializer.is_valid():
serializer.save(nick=request.user, product=self.get_object(id))
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
In your post()
, you need to return status.HTTP_201_CREATED if successful. 在
post()
,您需要返回status.HTTP_201_CREATED如果成功。
Try this: 尝试这个:
def post(self, request,id):
serializer = CommentSerializer(data=request.data)
if serializer.is_valid():
serializer.save(nick=request.user, product=self.get_object(id))
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.