Skip to content

Commit

Permalink
테스트: 마이페이지 API 초기 테스트 및 시리얼라이저 부분 수정
Browse files Browse the repository at this point in the history
- 마이페이지 업데이트를 create 메서드를 통해 적용
- 클라이언트 테스트에서 파일 업로드 있을시
  media_type="application/form-data"로 해야 오류 없음
- 오류있는 테스트 재점검
  • Loading branch information
Sahayana committed Nov 15, 2023
1 parent 360b25e commit a80d238
Show file tree
Hide file tree
Showing 11 changed files with 277 additions and 60 deletions.
43 changes: 11 additions & 32 deletions apps/account/v1/apis/mypage_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@
from apps.account.models import CustomUser, UserProfileImage
from apps.account.services.user_service import UserService
from apps.account.v1.serializers.user_serializer import (
UserProfileImageSerializer,
UserReadSerializer,
UserUpdateSerializer,
)
from apps.friend.services.friend_selector import FriendSelector
from apps.friend.services.friend_service import FriendService


class MyPageViewSet(viewsets.ModelViewSet):
Expand All @@ -36,7 +36,7 @@ def get_serializer_class(self):

if self.action == "list":
serializer_class = UserReadSerializer
elif self.action in ["update", "partial_update"]:
elif self.action == "create":
serializer_class = UserUpdateSerializer
return serializer_class

Expand All @@ -47,22 +47,22 @@ def list(self, request, *args, **kwargs):
friend_requests = FriendSelector.get_recieved_requests(user_id=user.id)
youtubes = cache.get_or_set(
cache_key.USER_YOUTUBE.format(user_id=user.id),
self.get_queryset().youtube.all(),
self.get_queryset().get().youtube.all(),
timeout=86400,
)
news = cache.get_or_set(
cache_key.USER_NEWS.format(user_id=user.id),
self.get_queryset().news.all(),
self.get_queryset().get().news.all(),
timeout=86400,
)
books = cache.get_or_set(
cache_key.USER_BOOK.format(user_id=user.id),
self.get_queryset().book.all(),
self.get_queryset().get().book.all(),
timeout=86400,
)
shoppings = cache.get_or_set(
cache_key.USER_SHOPPING.format(user_id=user.id),
self.get_queryset().shopping.all(),
self.get_queryset().get().shopping.all(),
timeout=86400,
)

Expand All @@ -79,38 +79,17 @@ def list(self, request, *args, **kwargs):
context, status=status.HTTP_200_OK, template_name="account/mypage.html"
)

def update(self, request, *args, **kwargs):
def create(self, request, *args, **kwargs):
"""회원 정보를 업데이트 합니다."""

user = request.user
serializer = self.get_serializer(instance=user, data=request.data, partial=True)

request_data = {
"nickname": request.data.get("nickname"),
"password": request.data.get("password"),
"bio": request.data.get("bio"),
"profile_image": request.data.get("img"),
}

serializer = self.get_serializer(data=request_data)

if serializer.is_valid(raise_exception=True):
validated_data = serializer.validated_data

user.email = validated_data["email"]
user.nickname = validated_data["nickname"]
user.bio = validated_data["bio"]

if validated_data.get("profile_image"):
img = validated_data["profile_image"]
UserProfileImage.objects.create(user_id=user.id, img=img)

if validated_data.get("password"):
password = validated_data["password"]
user.set_password(password)
if serializer.is_valid():
serializer.save()

user.save()
data = {"msg": "ok", "data": UserReadSerializer(instance=user).data}

data = {"msg": "ok", "user": UserReadSerializer(instance=user).data}
return Response(data=data, status=status.HTTP_200_OK)
return Response(
data=serializer.error_messages, status=status.HTTP_400_BAD_REQUEST
Expand Down
12 changes: 5 additions & 7 deletions apps/account/v1/apis/user_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,13 +39,11 @@ def post(self, request, *args, **kwargs):
""" "
회원가입을 통해 유저를 생성합니다.
"""
request_data = {
"email": request.data.get("email"),
"nickname": request.data.get("nickname"),
"password": request.data.get("password"),
"bio": request.data.get("bio"),
"profile_image": request.data.get("img", None),
}

request_data = request.data.copy()

if request.data.get("img"):
request_data.update({"profile_image": request.data["img"]})

is_present = UserSelector.check_email_duplication(email=request_data["email"])

Expand Down
19 changes: 15 additions & 4 deletions apps/account/v1/serializers/user_serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,16 @@
from apps.account.services.user_selector import UserSelector


class UserProfileImageSerializer(serializers.Serializer):
profile_image = serializers.ImageField(write_only=True)


class UserCreateSerializer(serializers.ModelSerializer):

email = serializers.CharField(required=True)
nickname = serializers.CharField(required=True)
password = serializers.CharField(write_only=True)
profile_image = serializers.ImageField(required=False)
profile_image = serializers.ImageField(required=False, write_only=True)

class Meta:
model = CustomUser
Expand All @@ -21,12 +25,19 @@ class UserUpdateSerializer(serializers.ModelSerializer):

nickname = serializers.CharField(required=False)
password = serializers.CharField(required=False, write_only=True)
profile_image = serializers.ImageField(required=False)
bio = serializers.CharField(required=False)
profile_image = serializers.ImageField(required=False, write_only=True)

class Meta:
model = CustomUser
fields = ("nickname", "password", "profile_image", "bio")
fields = ("nickname", "password", "bio", "profile_image")

def update(self, instance, validated_data):
if validated_data.get("profile_image"):
img = validated_data.pop("profile_image")
UserProfileImage.objects.create(user_id=instance.id, img=img)

return super().update(instance, validated_data)


class UserReadSerializer(serializers.ModelSerializer):
Expand Down Expand Up @@ -54,7 +65,7 @@ def get_profile_image(self, obj):
profile_img = UserProfileImage.objects.filter(user_id=obj.id).first()
if not profile_img:
return DEFAULT_IMG
return profile_img.img
return profile_img.img.url


class UserLikeKeywordSerilaizer(serializers.ModelSerializer):
Expand Down
10 changes: 9 additions & 1 deletion apps/account/v1/urls.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
from django.urls import path
from django.urls import include, path
from rest_framework.routers import DefaultRouter
from rest_framework_simplejwt.views import TokenBlacklistView

from apps.account.v1.apis import user_api
from apps.account.v1.apis.mypage_api import MyPageViewSet

app_name = "account"

router = DefaultRouter()
router.register("mypage", MyPageViewSet, "mypage")

urlpatterns = [
path("", include(router.urls)),
path("signup", user_api.SignUpView.as_view(), name="signup"),
path(
"signup/verification/<str:uidb64>/<str:token>",
Expand All @@ -17,4 +24,5 @@
user_api.TemporaryPasswordView.as_view(),
name="temporary_password",
),
path("logout", TokenBlacklistView.as_view(), name="logout"),
]
2 changes: 1 addition & 1 deletion apps/friend/v1/apis/friend_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ def list(self, request, *args, **kwargs):
user = request.user
recommend_friend = cache.get_or_set(
cache_key.RECOMMEND_FRIEND.format(user_id=user.id),
FriendService.recommend_friend(user_id=user.id),
FriendService.recommend_friend(user=user),
timeout=86400,
)
context = {
Expand Down
22 changes: 11 additions & 11 deletions static/js/base.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,19 @@ $(document).ready(function () {

// 친구 리스트 이동
let friendListIcon = $(".user_icon");
friendListIcon.on('click', function(){
window.location.href = `/accounts/friends/`;
friendListIcon.on('click', function () {
window.location.href = `/friend/v1/friends`;
})

// 마이페이지 이동
let myPageIcon = $(".mypage_icon");
myPageIcon.on('click', function(){
window.location.href = `/accounts/mypage/`;
myPageIcon.on('click', function () {
window.location.href = `/account/v1/mypage`;
})

// 채팅 이동
let ChatIcon = $(".chat_icon");
ChatIcon.on('click', function(){
ChatIcon.on('click', function () {
window.location.href = `/api/search/`;
})
})
Expand All @@ -27,19 +27,19 @@ function switch_chat() {
$('#left_wrap').empty();
$('#left_wrap').load("/api/search/chat");
$('#right_wrap').load("/api/search/recommend");
setTimeout(function(){
setTimeout(function () {
reload();
console.log('recommend_toggle!! -> ', document.getElementById('recommend_toggle'))
}, 500)
console.log('switch_chat()!')
}

function toggle_recommend(){
function toggle_recommend() {
let toggle_menu = document.getElementById('toggle_content')
if(toggle_menu.style.display!=='none'){
toggle_menu.style.display='none'
if (toggle_menu.style.display !== 'none') {
toggle_menu.style.display = 'none'
}
else{
toggle_menu.style.display='block'
else {
toggle_menu.style.display = 'block'
}
}
11 changes: 11 additions & 0 deletions tests/account/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import pytest
from django.core.files import File
from django.core.files.uploadedfile import SimpleUploadedFile
from PIL import Image

from apps.account.constants import TEST_IMG_NAME
Expand Down Expand Up @@ -39,3 +40,13 @@ def get_test_image():
file.seek(0)

return File(file=file, name=name)


@pytest.fixture()
def simple_upload_image():
image_data = BytesIO()
image = Image.new("RGB", (100, 100), "white")
image.save(image_data, format="png")
image_data.seek(0)

return SimpleUploadedFile("test.png", image_data.read(), content_type="image/png")
23 changes: 23 additions & 0 deletions tests/account/services/test_user_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,3 +82,26 @@ def test_유저_좋아요_컨텐츠_노출_off_변경시_필드_변경():
user = UserService.like_public_setting(user_id=user.id, value=value)

assert user.is_like_public is False


def test_유저_탙퇴시_is_deleted_필드값_변경():

user = UserFactory.create(is_active=True)
deleted_user = UserService.delete_user_account(user_id=user.id)

assert deleted_user.is_deleted is True


def test_유저_임시비밀번호_발송_비밀번호_체크_확인(mocker):

user = UserFactory.create(is_active=True)
temp_str = "temporary"

mocker.patch(
"apps.account.services.user_service.random_string_generator",
return_value=temp_str,
)

after_user = UserService.change_temporary_password(user_id=user.id)

assert after_user.check_password(temp_str) is True
Loading

0 comments on commit a80d238

Please sign in to comment.