갈루아의 반서재

728x90

More comprehensive tests


아래와 같이 2개의 메서드 추가해서 테스트 실시


polls/tests.py

import datetime


from django.utils import timezone

from django.test import TestCase


from .models import Question



class QuestionMethodTests(TestCase):


    def test_was_published_recently_with_old_question(self):

        time = timezone.now() + datetime.timedelta(days=30)

        old_question = Question(pub_date=time)

        self.assertEqual(old_question.was_published_recently(), False)        

        

    def test_was_published_recently_with_recent_question(self):

        time = timezone.now() - datetime.timedelta(hours=1)

        recent_question = Question(pub_date=time)

        self.assertEqual(recent_question.was_published_recently(), True)



    def test_was_published_recently_with_future_question(self):

        time = timezone.now() + datetime.timedelta(days=30)

        future_question = Question(pub_date=time)

        self.assertEqual(future_question.was_publish



이제 이를 통해 과거, 최근, 미래의 질문을 제대로 구분해내는지 3가지 테스트가 가능해진다.




Test a view


pub_date가 다가올 미래라는 의미는 해당일이 될 때까지는 그 설문이 보여서는 안됨을 의미한다. 이 버그를 이제 수정해보자.



The Django test client


셀에 테스트 환경을 만든다


>>> from django.test.utils import setup_test_environment

>>> setup_test_environment()


테스트 클라이언트 클래스를 가져온다.


>>> from django.test import Client

>>> client = Client()



>>> response = client.get('/')

>>> response.status_code

404

>>> from django.core.urlresovers import reverse

Traceback (most recent call last):

  File "<console>", line 1, in <module>

ImportError: No module named urlresovers

>>> from django.core.urlresolvers import reverse

>>> response = client.get(reverse('polls:index'))

>>> response.status_code

200

>>> response.content

'\n    <ul>\n    \n        <li><a href="/polls/2/">Is this your first visit?</a></li>\n    \n        <li><a href="/polls/3/">Who i                                                                             s your favorite Beatle?</a></li>\n    \n        <li><a href="/polls/1/">What&#39;s up?</a></li>\n    \n    </ul>\n'

>>> reponse = client.get('/polls/')

>>> response.content

'\n    <ul>\n    \n        <li><a href="/polls/2/">Is this your first visit?</a></li>\n    \n        <li><a href="/polls/3/">Who is your favorite Beatle?</a></li>\n    \n        <li><a href="/polls/1/">What&#39;s up?</a></li>\n    \n    </ul>\n'

>>> response.context['latest_question_list']

[<Question: Is this your first visit?>, <Question: Who is your favorite Beatle?>, <Question: What's up?>]

>>>





728x90