Testing
셸에서 테스트시에 메소드 이름에 test_로 시작하는것만 실행된다.
from django.test import TestCase
from polls_api.serializers import QuestionSerializer,VoteSerializer
from django.contrib.auth.models import User
from polls.models import Question, Choice, Vote
class VoteSerializerTest(TestCase) :
def setUp(self) :
self.user = User.objects.create(username='testuser')
self.question = Question.objects.create(
question_text = 'abc',
owner=self.user,
)
self.choice = Choice.objects.create(
question = self.question,
choice_text=['1']
)
#정상적인 경우의 테스트
def test_vote_serializer(self) :
self.assertEqual(User.objects.all().count(),1)
data = {
'question' : self.question.id,
'choice' : self.choice.id,
'voter' : self.user.id
}
serializer = VoteSerializer(data=data)
self.assertTrue(serializer.is_valid())
vote = serializer.save()
self.assertEqual(vote.question, self.question)
self.assertEqual(vote.choice, self.choice)
self.assertEqual(vote.voter, self.user)
#비정상적인 경우의 테스트
def test_vote_serializer_with_duplicate_vote(self) :
self.assertEqual(User.objects.all().count(),1)
choice1 = Choice.objects.create(
question = self.question,
choice_text=['2']
)
Vote.objects.create(question=self.question, choice=self.choice, voter=self.user)
data = {
'question' : self.question.id,
'choice' : choice1.id,
'voter' : self.user.id
}
serializer = VoteSerializer(data=data)
self.assertFalse(serializer.is_valid()) #유효하지 않다 False인지 확인
def test_vote_serializer_with_unmatched_question_and_choice(self) :
question2 = Question.objects.create(
question_text = 'abc',
owner=self.user,
)
choice2 = Choice.objects.create(
question = question2,
choice_text='1'
)
data = {
'question' : self.question.id,
'choice' : choice2.id,
'voter' : self.user.id
}
serializer = VoteSerializer(data=data)
self.assertFalse(serializer.is_valid())
class QuestionSerializerTestCase(TestCase) :
def test_with_valid_data(self) : #vaild하게 저장되는지 테스트
serializer = QuestionSerializer(data={'question_text' : 'abc'})
self.assertEqual(serializer.is_valid(), True)
new_question = serializer.save()
self.assertIsNotNone(new_question.id) #id가 non인지 아닌지 확인
def test_with_invalid_data(self) : #invalid하게 저장된것 테스트
serializer = QuestionSerializer(data={'question_text' : ''})
self.assertEqual(serializer.is_valid(), False)
polls_api/tests.py
'Django' 카테고리의 다른 글
Django 기본 (0) | 2024.04.28 |
---|---|
유저(User)와 기능(투표, 질문) (0) | 2024.04.28 |
시리얼라이저(Serializer)와 에러(Error) (0) | 2024.04.28 |
뷰(View)와 템플릿(template) (1) | 2024.04.28 |