Skip to content

Commit

Permalink
♻️Refact : PR 코드 리팩토링
Browse files Browse the repository at this point in the history
- post_type에 따라 필터링 된 게시물 관련 코드 리팩토링 및 관련함수 삭제
- ordering 관련 잘못된 값 선택 시 에러메세지 출력할 수 있도록 리팩토링
- 테스트코드 수정
  • Loading branch information
simseulnyang committed Oct 28, 2023
1 parent d1b7ba2 commit 8f66e30
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 111 deletions.
150 changes: 53 additions & 97 deletions posts/tests/views/test_posts_list_view.py
Original file line number Diff line number Diff line change
@@ -1,125 +1,81 @@
import uuid

from django.contrib.auth import get_user_model
from django.contrib.auth.models import User
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APITestCase

from posts.models import HashTag, Post
from users.models import User

User = get_user_model()

class PostListViewTest(APITestCase):
@classmethod
def setUpTestData(cls):
cls.hasgtag = HashTag.objects.create(
name="hashtag",
)
for i in range(1, 6):
cls.users = User.objects.create_user(
email=f"user{i}@example.com",
username=f"testuser{i}",
password="testpassword",
)
cls.posts = Post.objects.create(
content_id=uuid.uuid4(),
post_type="facebook",
title=f"title {i}",
content=f"content {i}",
view_count=i,
like_count=i,
share_count=i,
user=cls.users,
created_at=f"2023-10-1{i}",
updated_at=f"2023-10-2{i}",
)
cls.posts = Post.objects.create(
content_id=uuid.uuid4(),
post_type="twitter",
title=f"title {i}",
content=f"content {i}",
view_count=i,
like_count=i,
share_count=i,
user=cls.users,
created_at=f"2023-10-1{i}",
updated_at=f"2023-10-2{i}",
)
cls.posts = Post.objects.create(
content_id=uuid.uuid4(),
post_type="instagram",
title=f"title {i}",
content=f"content {i}",
view_count=i,
like_count=i,
share_count=i,
user=cls.users,
created_at=f"2023-10-1{i}",
updated_at=f"2023-10-2{i}",
)
cls.posts = Post.objects.create(
content_id=uuid.uuid4(),
post_type="threads",
title=f"title {i}",
content=f"content {i}",
view_count=i,
like_count=i,
share_count=i,
user=cls.users,
created_at=f"2023-10-1{i}",
updated_at=f"2023-10-2{i}",
)
cls.posts.hashtag.set([cls.hasgtag])

class PostListViewTest(APITestCase):
def setUp(self):
pass
# self.access_token = self.client.post(reverse("token_obtain_pair"), self.user_data).data["access"]
# 테스트 사용자 생성
self.user1 = User.objects.create_user(username="testuser1", password="testpass1", email="test1@email.com")
self.user2 = User.objects.create_user(username="testuser2", password="testpass2", email="test2@email.com")

def test_get_posts_list_success(self):
response = self.client.get(
path=reverse("list"),
data={
"type": "facebook",
"hashtag": "hashtag",
},
# HTTP_AUTHORIZATION=f"Bearer {self.access_token}",
)
self.assertEqual(response.status_code, status.HTTP_200_OK)
# 테스트 해시태그 생성
self.hashtag1 = HashTag.objects.create(name="hashtag1")
self.hashtag2 = HashTag.objects.create(name="hashtag2")

def test_get_filtered_post_list_facebook_success(self):
response = self.client.get(
path=reverse("list"),
data={"type": "facebook", "hashtag": "hashtag", "title": "title 1", "content": "content 1"},
# 테스트 게시물 생성
self.post1 = Post.objects.create(
user=self.user1,
post_type="facebook",
title="test title 1",
content="test content 1",
view_count=10,
like_count=5,
share_count=2,
)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.post1.hashtag.set([self.hashtag1])

def test_get_filtered_post_list_twitter_success(self):
response = self.client.get(
path=reverse("list"),
data={"type": "twitter", "hashtag": "hashtag", "title": "title 1", "content": "content 1"},
self.post2 = Post.objects.create(
user=self.user2,
post_type="twitter",
title="test title 2",
content="test content 2",
view_count=20,
like_count=10,
share_count=4,
)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.post2.hashtag.set([self.hashtag2])

def test_get_filtered_post_list_instagram_success(self):
# 추가 게시물 생성
for i in range(3, 6):
post = Post.objects.create(
user=self.user1,
post_type="facebook",
title=f"test title {i}",
content=f"test content {i}",
view_count=10 * i,
like_count=5 * i,
share_count=2 * i,
)
post.hashtag.set([self.hashtag1])

def test_get_posts_list_success(self):
response = self.client.get(
path=reverse("list"),
data={"type": "instagram", "hashtag": "hashtag", "title": "title 1", "content": "content 1"},
data={"type": "all", "hashtag": self.hashtag1.id, "ordering": "created_at", "search": ""},
)
print(response.data) # 서버의 응답 내용 출력
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(len(response.data), 4) # 예상되는 게시물 개수 확인
for item in response.data:
self.assertEqual(item["hashtag"][0]["name"], self.hashtag1.name) # 수정된 부분

def test_get_filtered_post_list_threads_success(self):
def test_get_posts_list_invalid_type(self):
response = self.client.get(
path=reverse("list"),
data={"type": "threads", "hashtag": "hashtag", "title": "title 1", "content": "content 1"},
data={"type": "invalid_type", "hashtag": "hashtag", "ordering": "created_at", "search": ""}, # 잘못된 타입
)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

def test_get_posts_list_fail_invalid_parameter_type(self):
def test_get_posts_list_invalid_ordering(self):
response = self.client.get(
path=reverse("list"),
data={
"type": "facebook1",
"hashtag": "",
},
# HTTP_AUTHORIZATION=f"Bearer {self.access_token}",
data={"type": "all", "hashtag": "hashtag", "ordering": "invalid_ordering", "search": ""}, # 잘못된 ordering 값
)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
21 changes: 7 additions & 14 deletions posts/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ class PostListView(PaginationHandlerMixin, APIView):
status.HTTP_200_OK: PostListSerializer,
},
)
@optionals({"hashtag": None}, {"type": {}})
@optionals({"hashtag": None}, {"type": ["all", "facebook", "twitter", "instagram", "threads"]})
def get(self, request: Request, o: dict) -> Response:
"""
query parameter로 type, search, ordering, hashtag를 받아 게시물 목록을 조회
Expand Down Expand Up @@ -180,24 +180,17 @@ def get(self, request: Request, o: dict) -> Response:
posts = self.get_ordering(posts, ordering)

# post_type에 따라 필터링 된 게시물 목록 가져오기
post_type_list = self.get_post_type_list(posts, post_type)
if post_type != "all":
if post_type not in ["facebook", "twitter", "instagram", "threads"]:
raise InvalidParameterException(f"post_type 값 {post_type}를 잘못 선택하셨습니다.")
posts = posts.filter(post_type=post_type)

# 게시물 목록 serialize
serializer = PostListSerializer(post_type_list, many=True)
serializer = PostListSerializer(posts, many=True)
except Exception as e:
raise UnknownServerErrorException(e)
return Response(serializer.data, status=status.HTTP_200_OK)

def get_post_type_list(self, posts: QuerySet[Post], post_type: str) -> QuerySet[Post]:
if post_type == "all":
post_type = None
return posts

if post_type not in ["facebook", "twitter", "instagram", "threads"]:
raise InvalidParameterException(f"post_type 값 {post_type}를 잘못 선택하셨습니다.")

return posts.filter(post_type=post_type)

def get_ordering(self, posts: QuerySet[Post], ordering: str) -> QuerySet[Post]:
# 사용 가능한 필드 목록
allowed_fields = [
Expand All @@ -216,4 +209,4 @@ def get_ordering(self, posts: QuerySet[Post], ordering: str) -> QuerySet[Post]:
if ordering in allowed_fields:
return posts.order_by(ordering)
else:
return posts.order_by("created_at")
raise InvalidParameterException(f"ordering 값 {ordering}를 잘못 선택하셨습니다.")

0 comments on commit 8f66e30

Please sign in to comment.