From f8edffbb7a5a6c1cb42189a612db54c9babbdec5 Mon Sep 17 00:00:00 2001 From: Nelson Mwirumubi Date: Thu, 16 May 2019 13:01:29 +0300 Subject: [PATCH] chore(refactor-codebase): Refactor comments app - Refactor comments views - Refactor likes views - Refactor unit tests [Starts #166027332] --- authors/apps/comments/tests/base.py | 5 +- authors/apps/comments/tests/test_comment.py | 18 +--- authors/apps/comments/tests/test_likes.py | 111 ++++++++------------ authors/apps/comments/urls.py | 4 +- authors/apps/comments/views.py | 95 ++++++----------- 5 files changed, 80 insertions(+), 153 deletions(-) diff --git a/authors/apps/comments/tests/base.py b/authors/apps/comments/tests/base.py index 871dcfe..768bcdc 100644 --- a/authors/apps/comments/tests/base.py +++ b/authors/apps/comments/tests/base.py @@ -121,13 +121,12 @@ def setUp(self): self.comment_text4 = { "comment": { "body": "This is sample text.", - "first_index": 200, - "last_index": 100, + "first_index": 20, + "last_index": 10, "highlighted_text": "This is sample text." } } - self.user2 = User.objects.create_user( username='test2', email='test2@example.com', password='12345678' ) diff --git a/authors/apps/comments/tests/test_comment.py b/authors/apps/comments/tests/test_comment.py index 416c838..c9406c0 100644 --- a/authors/apps/comments/tests/test_comment.py +++ b/authors/apps/comments/tests/test_comment.py @@ -51,22 +51,18 @@ def test_post_a_comment_article_not_found(self): def test_get_a_comment(self): """Test get a single comment.""" - # post an article url = reverse('comment_list', kwargs={'article_id': 1}) self.client.post(url, self.comment, HTTP_AUTHORIZATION=self.auth_header, format="json") - # get a single article url = reverse('comment_detail', kwargs={'article_id': 1, 'pk': 1}) response = self.client.get(url, HTTP_AUTHORIZATION=self.auth_header) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_get_a_comment_on_article_not_found(self): """Test get a single comment on a non existinng article.""" - # post an article url = reverse('comment_list', kwargs={'article_id': 1}) self.client.post(url, self.comment, HTTP_AUTHORIZATION=self.auth_header, format="json") - # get a single article url = reverse('comment_detail', kwargs={'article_id': 1000, 'pk': 1}) response = self.client.get(url, HTTP_AUTHORIZATION=self.auth_header) self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) @@ -74,11 +70,9 @@ def test_get_a_comment_on_article_not_found(self): def test_get_a_comment_not_found(self): """Test get a single comment on a non existinng article.""" - # post an article post_url = reverse('comment_list', kwargs={'article_id': 1}) self.client.post(post_url, self.comment, HTTP_AUTHORIZATION=self.auth_header, format="json") - # get a single comment url = reverse('comment_detail', kwargs={'article_id': 1, 'pk': 1000}) response = self.client.get(url, HTTP_AUTHORIZATION=self.auth_header) self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) @@ -86,7 +80,6 @@ def test_get_a_comment_not_found(self): def test_update_a_comment(self): """Test update a single comment.""" - # post an article post_url = reverse('comment_list', kwargs={'article_id': 1}) response = self.client.post(post_url, self.comment, HTTP_AUTHORIZATION=self.auth_header, @@ -246,7 +239,7 @@ def test_if_last_or_first_index_is_greater_than_the_body(self): response = self.client.post(url, self.comment_text3, HTTP_AUTHORIZATION=self.auth_header, format="json") - self.assertIn('You should only highlight within the article body.', + self.assertIn('You should only highlight within the article body.', str(response.data)) def test_if_first_index_is_greater_last_index(self): @@ -256,12 +249,3 @@ def test_if_first_index_is_greater_last_index(self): HTTP_AUTHORIZATION=self.auth_header, format="json") self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) - - def test_iff_first_index_is_greater_last_index(self): - """Test whether first index is greater than last index.""" - url = reverse('comment_list', kwargs={'article_id': 1}) - response = self.client.post(url, self.comment_text4, - HTTP_AUTHORIZATION=self.auth_header, - format="json") - self.assertIn('You should only highlight within the article body.', - str(response.data)) diff --git a/authors/apps/comments/tests/test_likes.py b/authors/apps/comments/tests/test_likes.py index d985fd8..8f7a716 100644 --- a/authors/apps/comments/tests/test_likes.py +++ b/authors/apps/comments/tests/test_likes.py @@ -1,9 +1,6 @@ -import json -from rest_framework.test import APIClient, APITestCase -from authors.apps.authentication.models import User from authors.apps.comments.tests.base import BaseTestCase from django.urls import reverse -from rest_framework import status + class TestLikeCommment(BaseTestCase): """Class to test like and unlike a comment.""" @@ -15,10 +12,10 @@ def test_user_to_like_own_comment(self): HTTP_AUTHORIZATION=self.auth_header, format="json") comment_id = response.data['comment']['id'] - self.assertEqual(response.status_code, status.HTTP_201_CREATED) - url1 = reverse('like_comment', kwargs={'article_id':1, 'comment_id':comment_id}) - response1 = self.client.post(url1, - HTTP_AUTHORIZATION=self.auth_header, format="json") + url1 = reverse('like_comment', + kwargs={'article_id': 1, 'pk': comment_id}) + response1 = self.client.post(url1, HTTP_AUTHORIZATION=self.auth_header, + format="json") self.assertEqual(response1.status_code, 403) def test_user_liking_your_own_comment(self): @@ -28,11 +25,12 @@ def test_user_liking_your_own_comment(self): HTTP_AUTHORIZATION=self.auth_header, format="json") comment_id = response.data['comment']['id'] - self.assertEqual(response.status_code, status.HTTP_201_CREATED) - url1 = reverse('like_comment', kwargs={'article_id':1, 'comment_id':comment_id}) - response1 = self.client.post(url1, - HTTP_AUTHORIZATION=self.auth_header, format="json") - self.assertEqual(response1.data['message'], "You can not like your own comment.") + url1 = reverse('like_comment', + kwargs={'article_id': 1, 'pk': comment_id}) + response1 = self.client.post(url1, HTTP_AUTHORIZATION=self.auth_header, + format="json") + self.assertEqual(response1.data['message'], + "You can not like your own comment.") def test_user_to_liking_another_comment(self): """Test liking your own comment.""" @@ -41,10 +39,11 @@ def test_user_to_liking_another_comment(self): HTTP_AUTHORIZATION=self.auth_header, format="json") comment_id = response.data['comment']['id'] - self.assertEqual(response.status_code, status.HTTP_201_CREATED) - url1 = reverse('like_comment', kwargs={'article_id':1, 'comment_id':comment_id}) + url1 = reverse('like_comment', + kwargs={'article_id': 1, 'pk': comment_id}) response1 = self.client.post(url1, - HTTP_AUTHORIZATION=self.auth_header2, format="json") + HTTP_AUTHORIZATION=self.auth_header2, + format="json") self.assertEqual(response1.status_code, 200) def test_user_to_like_another_comment(self): @@ -54,11 +53,13 @@ def test_user_to_like_another_comment(self): HTTP_AUTHORIZATION=self.auth_header, format="json") comment_id = response.data['comment']['id'] - self.assertEqual(response.status_code, status.HTTP_201_CREATED) - url1 = reverse('like_comment', kwargs={'article_id':1, 'comment_id':comment_id}) + url1 = reverse('like_comment', + kwargs={'article_id': 1, 'pk': comment_id}) response1 = self.client.post(url1, - HTTP_AUTHORIZATION=self.auth_header2, format="json") - self.assertEqual(response1.data['success'], "You have successfully liked this comment.") + HTTP_AUTHORIZATION=self.auth_header2, + format="json") + self.assertEqual(response1.data['success'], + "You have successfully liked this comment.") self.assertEqual(response1.status_code, 200) def test_user_to_like_twice_a_comment(self): @@ -68,70 +69,48 @@ def test_user_to_like_twice_a_comment(self): HTTP_AUTHORIZATION=self.auth_header, format="json") comment_id = response.data['comment']['id'] - self.assertEqual(response.status_code, status.HTTP_201_CREATED) - url1 = reverse('like_comment', kwargs={'article_id':1, 'comment_id':comment_id}) + url1 = reverse('like_comment', + kwargs={'article_id': 1, 'pk': comment_id}) response1 = self.client.post(url1, - HTTP_AUTHORIZATION=self.auth_header2, format="json") + HTTP_AUTHORIZATION=self.auth_header2, + format="json") response1 = self.client.post(url1, - HTTP_AUTHORIZATION=self.auth_header2, format="json") - self.assertEqual(response1.data['message'], "Your like has been cancelled") + HTTP_AUTHORIZATION=self.auth_header2, + format="json") + self.assertEqual(response1.data['message'], + "Your like has been cancelled") self.assertEqual(response1.status_code, 200) - def test_user_has_not_liked_a_comment(self): + def test_user_has_liked_a_comment(self): """Test a user has ever liked a comment.""" url = reverse('comment_list', kwargs={'article_id': 1}) response = self.client.post(url, self.comment, HTTP_AUTHORIZATION=self.auth_header, format="json") comment_id = response.data['comment']['id'] - self.assertEqual(response.status_code, status.HTTP_201_CREATED) - url1 = reverse('get_likes', kwargs={'article_id':1, 'comment_id':comment_id}) - response1 = self.client.get(url1, - HTTP_AUTHORIZATION=self.auth_header2, format="json") - self.assertIn('False', str(response1.data)) - - def test_user_has_not_liked_comment(self): - """Test a user has never liked a comment using status code.""" - url = reverse('comment_list', kwargs={'article_id': 1}) - response = self.client.post(url, self.comment, - HTTP_AUTHORIZATION=self.auth_header, - format="json") - comment_id = response.data['comment']['id'] - self.assertEqual(response.status_code, status.HTTP_201_CREATED) - url1 = reverse('get_likes', kwargs={'article_id':1, 'comment_id':comment_id}) + url1 = reverse('like_comment', + kwargs={'article_id': 1, 'pk': comment_id}) + self.client.post(url1, HTTP_AUTHORIZATION=self.auth_header2, + format="json") + url1 = reverse('get_likes', + kwargs={'article_id': 1, 'pk': comment_id}) response1 = self.client.get(url1, - HTTP_AUTHORIZATION=self.auth_header2, format="json") - self.assertEqual(response1.status_code, 200) - - def test_user_has_liked_comment(self): - """Test a user has ever liked a comment using status code.""" - url = reverse('comment_list', kwargs={'article_id': 1}) - response = self.client.post(url, self.comment, - HTTP_AUTHORIZATION=self.auth_header, + HTTP_AUTHORIZATION=self.auth_header2, format="json") - comment_id = response.data['comment']['id'] - self.assertEqual(response.status_code, status.HTTP_201_CREATED) - url0 = reverse('like_comment', kwargs={'article_id':1, 'comment_id':comment_id}) - url1 = reverse('get_likes', kwargs={'article_id':1, 'comment_id':comment_id}) - response2 = response.client.post(url0, - HTTP_AUTHORIZATION=self.auth_header2, format="json") - response1 = self.client.get(url1, - HTTP_AUTHORIZATION=self.auth_header2, format="json") self.assertEqual(response1.status_code, 200) self.assertIn('True', str(response1.data)) - def test_user_has_likes_comment(self): - """Test a user has ever liked a comment using message.""" + def test_user_has_not_liked_a_comment(self): + """Test a user has never liked a comment.""" url = reverse('comment_list', kwargs={'article_id': 1}) response = self.client.post(url, self.comment, HTTP_AUTHORIZATION=self.auth_header, format="json") comment_id = response.data['comment']['id'] - self.assertEqual(response.status_code, status.HTTP_201_CREATED) - url0 = reverse('like_comment', kwargs={'article_id':1, 'comment_id':comment_id}) - url1 = reverse('get_likes', kwargs={'article_id':1, 'comment_id':comment_id}) - response2 = response.client.post(url0, - HTTP_AUTHORIZATION=self.auth_header2, format="json") + url1 = reverse('get_likes', + kwargs={'article_id': 1, 'pk': comment_id}) response1 = self.client.get(url1, - HTTP_AUTHORIZATION=self.auth_header2, format="json") - self.assertIn('True', str(response1.data)) + HTTP_AUTHORIZATION=self.auth_header2, + format="json") + self.assertEqual(response1.status_code, 200) + self.assertIn('False', str(response1.data)) diff --git a/authors/apps/comments/urls.py b/authors/apps/comments/urls.py index 498a85b..5a928e0 100644 --- a/authors/apps/comments/urls.py +++ b/authors/apps/comments/urls.py @@ -8,9 +8,9 @@ name="comment_list"), path('articles//comments//', RetrieveUpdateDeleteComment.as_view(), name="comment_detail"), - path('articles//comments//like/', + path('articles//comments//like/', Like.as_view(), name="like_comment"), - path('articles//comment//', + path('articles//comments//likes/', Like.as_view(), name="get_likes"), path('articles//comments//update_history/', CommentEditHistoryAPIView.as_view(), name="update_history") diff --git a/authors/apps/comments/views.py b/authors/apps/comments/views.py index 4241c34..77c813e 100644 --- a/authors/apps/comments/views.py +++ b/authors/apps/comments/views.py @@ -2,9 +2,7 @@ from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.permissions import IsAuthenticated -from rest_framework.exceptions import NotFound -from authors.apps.articles.models import Article from .models import Comment, Likes from .serializers import CommentSerializer, CommentEditHistorySerializer from .utils import get_article, get_comment @@ -19,15 +17,6 @@ class ListCreateComment(APIView): permission_classes = (IsAuthenticated, ) serializer_class = CommentSerializer - def get_article(self, article_id): - """ - This method returns an article by its id. - """ - try: - return Article.objects.get(id=article_id) - except Article.DoesNotExist: - raise NotFound({"error": "Article not found."}) - @swagger_auto_schema( operation_description="Add a comment to an article.", operation_id="Add a comment to an article.", @@ -38,7 +27,7 @@ def post(self, request, **kwargs): """ This method adds a comment to a particular article. """ - article = self.get_article(kwargs['article_id']) + article = get_article(kwargs['article_id']) comment = request.data.get('comment', {}) comment['article'] = article.id first_index = comment.get('first_index', 0) @@ -49,9 +38,9 @@ def post(self, request, **kwargs): {"Error": "First index and last index must be integers."}, status.HTTP_400_BAD_REQUEST) if first_index > len(article.body) or last_index > len(article.body): - return Response( - {"Error": "You should only highlight within the article body."}, - status.HTTP_400_BAD_REQUEST) + return Response({ + "Error": "You should only highlight within the article body." + }, status.HTTP_400_BAD_REQUEST) if int(first_index) > int(last_index): return Response( {"Error": "First index should be less than Last index."}, @@ -70,7 +59,7 @@ def get(self, request, **kwargs): """ This method returns a list of comments on an article. """ - self.get_article(kwargs['article_id']) + get_article(kwargs['article_id']) queryset = Comment.objects.filter(article=self.kwargs['article_id']) serializer = CommentSerializer(queryset, many=True) return Response({ @@ -86,39 +75,21 @@ class RetrieveUpdateDeleteComment(APIView): queryset = Comment.objects.all() serializer_class = CommentSerializer - def get_article(self, article_id): - """ - Returns an article by its id. - """ - try: - return Article.objects.get(id=article_id) - except Article.DoesNotExist: - raise NotFound({"error": "Article not found."}) - - def get_comment(self, pk): - """ - This method returns a comment by its id. - """ - try: - return Comment.objects.get(pk=pk) - except Comment.DoesNotExist: - raise NotFound({"error": "Comment not found."}) - - def get(self, request, pk, article_id, **kwargs): + def get(self, request, pk, **kwargs): """ This method returns a single comment. """ - self.get_article(article_id) - comment = self.get_comment(pk) + get_article(kwargs['article_id']) + comment = get_comment(pk) serializer = CommentSerializer(comment) return Response({"comment": serializer.data}) - def put(self, request, pk, article_id): + def put(self, request, pk, **kwargs): """ This method updates a single comment. """ - article = self.get_article(article_id) - comment = self.get_comment(pk) + article = get_article(kwargs['article_id']) + comment = get_comment(pk) if comment.author.username == request.user.username: data = {} data['article'] = article.id @@ -134,12 +105,12 @@ def put(self, request, pk, article_id): "error": "You do not have permissions to edit this comment." }, status=status.HTTP_403_FORBIDDEN) - def delete(self, request, pk, article_id): + def delete(self, request, pk, **kwargs): """ This method deletes a single comment. """ - self.get_article(article_id) - comment = self.get_comment(pk) + get_article(kwargs['article_id']) + comment = get_comment(pk) if comment.author.username == request.user.username: comment.delete() return Response({ @@ -157,46 +128,40 @@ class Like(APIView): permission_classes = (IsAuthenticated, ) - def get_comment(self, comment_id): - """search for a comment by id.""" + def get_like(self, pk, username): try: - return Comment.objects.get(id=comment_id) - except Comment.DoesNotExist: - raise NotFound({"error": "The comment does not exist."}) - - def get_like(self, comment_id, username): - try: - return Likes.objects.get(comment=comment_id,commenter_id=username) + return Likes.objects.get(comment=pk, commenter_id=username) except Likes.DoesNotExist: return None def get(self, request, **kwargs): - """Method to check for your like on a comment""" - like = self.get_like(kwargs['comment_id'], request.user.username) + """Method to check for your like on a comment.""" + like = self.get_like(kwargs['pk'], request.user.username) if like: - return Response({"status":True}, status=status.HTTP_200_OK) - return Response({"status":False}, status=status.HTTP_200_OK) + return Response({"status": True}, status=status.HTTP_200_OK) + return Response({"status": False}, status=status.HTTP_200_OK) def post(self, request, **kwargs): - """ Method to like a specific comment.""" - comment = self.get_comment(kwargs['comment_id']) - my_like = self.get_like(kwargs['comment_id'], request.user.username) + """Method to like a specific comment.""" + comment = get_comment(kwargs['pk']) + my_like = self.get_like(kwargs['pk'], request.user.username) if comment.author.username == request.user.username: return Response({ "message": "You can not like your own comment." }, status=status.HTTP_403_FORBIDDEN) elif not my_like: like = Likes(commenter_id=request.user.username, - like=1, comment=comment) + like=1, comment=comment) like.save() - Comment.objects.filter(id=kwargs['comment_id']).update( + Comment.objects.filter(id=kwargs['pk']).update( likes_counter=comment.likes_counter + 1) - return Response({"success": "You have successfully liked this comment."}, - status=status.HTTP_200_OK) + return Response({ + "success": "You have successfully liked this comment." + }, status=status.HTTP_200_OK) else: my_like.delete() - Comment.objects.filter( - id=kwargs['comment_id']).update(likes_counter=comment.likes_counter - 1) + Comment.objects.filter(id=kwargs['pk']).update( + likes_counter=comment.likes_counter - 1) return Response({"message": "Your like has been cancelled"}, status=status.HTTP_200_OK)