python [manage.py](http://manage.py) test
로 코드가 제대로 작동하는지 테스트 했지만 해결되지 않음ㅋㅋclass NoticeView(APIView):
def post(self, request):
notice_serializer = NoticeSerializer(data=request.data)
print(notice_serializer)
if notice_serializer.is_valid():
notice_serializer.save()
return Response({"message": "공지사항 작성에 성공했다북"}, status=status.HTTP_200_OK)
else:
print(notice_serializer.errors)
return Response({"message": "공지사항 작성에 실패했다북"}, status=status.HTTP_400_BAD_REQUEST)
from django.urls import path
from . import views
urlpatterns = [
path('', views.NoticeView.as_view(), name='notice'),
path('list_notice', views.NoticeListView.as_view(), name='list_notice'),
]
from django.test import TestCase
from .models import Notice as NoticeModel
from user.models import User as UserModel
from rest_framework.test import APITestCase
from django.urls import reverse
class NoticeTest(APITestCase):
def setUp(self):
self.user = UserModel.objects.create_user('admin', '123')
title = "거뮤니티 ver.1.0 개발노트"
content = "회원가입, 로그인, 공지사항, 질문 답글 게시판이 추가되었습니다"
self.data = {
"user" : self.user.id,
"title" : title,
"content": content
}
self.notice = NoticeModel.objects.create(**self.data)
self.user = NoticeModel.objects.all()
def test_notice(self):
response = self.client.post(reverse('notice'), self.data)
print(f'이건 포스트 -> {response.data}')
self.assertEqual(response.status_code,200)
Traceback (most recent call last):
File "K:\coder_ys\gomunity\webmaster\tests.py", line 20, in setUp
self.notice = NoticeModel.objects.create(**self.data)
File "K:\coder_ys\gomunity\venv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "K:\coder_ys\gomunity\venv\lib\site-packages\django\db\models\query.py", line 512, in create
obj = self.model(**kwargs)
File "K:\coder_ys\gomunity\venv\lib\site-packages\django\db\models\base.py", line 541, in __init__
_setattr(self, field.name, rel_obj)
File "K:\coder_ys\gomunity\venv\lib\site-packages\django\db\models\fields\related_descriptors.py", line 235, in __set__
raise ValueError(
ValueError: Cannot assign "1": "Notice.user" must be a "User" instance.
로직 재설계
POSTMAN 테스트
test.py 코드 작성
개념 파악하기
의사코드
코딩
class NoticeView(APIView):
def post(self, request):
request.data['user'] = request.user
notice_serializer = NoticeSerializer(data=request.data)
if notice_serializer.is_valid():
notice_serializer.save()
return Response({"message":"공지사항 작성 성공했다북"} notice_serializer.data, status=status.HTTP_200_OK)
else:
return Response({"message":"공지사항 작성 실패했다북"} notice_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class NotionTest(APITestCase):
@classmethod
def setUpTestData(cls):
cls.user_data = {'username':'taein', 'password':'1234'}
cls.article_data = {'title':'아 어렵다 열받아','content':'힘을내요 슈퍼파월'}
cls.user = User.objects.create_user('taein', '1234')
def setUp(self):
self.access_token = self.client.post(reverse('token_obtain_pair'), self.data).data['access']
class NoticeTest(APITestCase):
@classmethod
def setUpTestData(cls):
cls.user_data = {'username' : 'heejeong', 'password': '1234'}
cls.notice_data = {'title' : '안녕' , 'content' : '반갑습니다'}
cls.user = User.objects.create_user('heejeong', '1234')
def setUp(self):
self.acceess_token = self.client.post(reverse('token_obtain_pair'), self.data).data['access']
def test_post_notice(self):
response = self.client.post(reverse("notice"), cls.notice_data)
self.assertEqual(response.status_code, 200)
print(NoticeSerializer().errors)
와 같이 errors 메서드로 출력해서 확인해 볼 수 있다