I'm trying to test a PUT method in django rest framework. I get HttpResponsePermanentRedirect instead of response object. My views for a put method are set to send status 200 after successful update.
Error:
self.assertEqual(response.data, serializer.data) AttributeError: 'HttpResponsePermanentRedirect' object has no attribute 'data'
tests.py
class PostTestGetAndPutMethod(APITestCase):
def setup(self):
Post.objects.create(title="POST CREATED", content="POST WAS CREATED")
Post.objects.create(title="POST CREATED 2", content="POST WAS CREATED 2")
Post.objects.create(title="POST CREATED 3", content="POST WAS CREATED 3")
def test_get_posts(self):
'''
Ensure we can get list of posts
'''
# get API response
response = self.client.get(reverse('posts'))
# get data from DB
posts = Post.objects.all()
# convert it to JSON
serializer = PostSerializer(posts, many=True)
# check the status
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.data, serializer.data)
def test_update_put_post(self):
'''
Check if we can update post
'''
data = {'title': 'POST MODIFIED', 'content': 'CONTENT MODIFIED'}
response = self.client.put('/posts/1', data)
serializer = PostSerializer(data)
self.assertEqual(response.data, serializer.data)
self.assertEqual(response.status_code, status.HTTP_200_OK)
views.py
@api_view(['GET', 'PUT', 'DELETE'])
def post_detail(request, pk):
"""
Retrieve, update or delete a code snippet.
"""
try:
post = Post.objects.get(pk=pk)
except Post.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.method == 'GET':
serializer = PostSerializer(post)
return Response(data=serializer.data, status=status.HTTP_200_OK)
elif request.method == 'PUT':
serializer = PostSerializer(post, data=data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_200_OK)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
elif request.method == 'DELETE':
post.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
Aucun commentaire:
Enregistrer un commentaire