def delete_comment(cls, user_id, comment_id): # not necessary to check user_id # if not is_id_valid(user_id): # raise InvalidFieldError("user id is invalid", ["user_id"]) if not is_id_valid(comment_id): raise InvalidFieldError("comment id is invalid", ["comment_id"]) user = DBUser.get_by_id(user_id) if not user: raise UserNotFoundError("User with id = %d does not exist" % user_id) comment = DBComment.get_by_id(comment_id) if not comment: raise CommentNotFoundError(comment_id=comment_id) # only allow commenter/post author to delete comment if comment.user_id != user_id and comment.post.author.id != user_id: raise AccessDeniedError("You cannot delete others comment") try: comment.delete() return comment except: raise
def update_comment(cls, user_id, comment_id, content): # not necessary to check user_id # if not is_id_valid(user_id): # raise InvalidFieldError("user id is invalid", ["user_id"]) if not is_id_valid(comment_id): raise InvalidFieldError("comment id is invalid", ["comment_id"]) commenter = DBUser.get_by_id(user_id) if not commenter: raise UserNotFoundError("User with id = %d does not exist" % user_id) comment = DBComment.get_by_id(comment_id) if not comment: raise CommentNotFoundError(comment_id=comment_id) if len(content) < 10: raise InvalidFieldError("comment is too short", ["content"]) # only allow commenter to update comment if comment.user_id != user_id: raise AccessDeniedError("You cannot edit others comment") comment.content = content try: comment.update() return comment except: raise
def test_delete_comment_by_post_author(self): args={ "user_id": 2, "comment_id": 10, } Comment.delete_comment(**args) comment = DBComment.get_by_id(10) self.assertIsNone(comment)
def test_delete_comment_ideal_case(self): args={ "user_id": 2, "comment_id": 1, } Comment.delete_comment(**args) comment = DBComment.get_by_id(1) self.assertIsNone(comment)
def test_update_comment_ideal_case(self): args={ "user_id": 2, "comment_id": 1, "content": "new comment content here" } cm = Comment.update_comment(**args) self.assertIsNotNone(cm) comment = DBComment.get_by_id(1) self.assertIsNotNone(comment) self.assertEqual(comment.user_id, args["user_id"]) self.assertEqual(comment.content, args["content"])
def test_add_comment_ideal_case(self): args={ "user_id": 1, "post_id": 2, "content": "This is my first comment on this page" } cm = Comment.add_comment(**args) self.assertIsNotNone(cm) comment = DBComment.get_by_id(cm.id) self.assertIsNotNone(comment) self.assertEqual(comment.user_id, args["user_id"]) self.assertEqual(comment.post_id, args["post_id"]) self.assertEqual(comment.content, args["content"])