Django part 5 ---Test

9812 단어 djangotest
전에 제 코드에 버그가 있었어요. 붙여봐요.
polls.models.py
class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date_published')

    def was_published_recently(self):
        #return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
    def __unicode__(self):
        return self.question_text
/////////////////////////////////////////////////////////////////////
was_published_recently()                       ,              
          ,               ,     True,    

테스트를 위한 테스트 파일 추가
polls.test.py
from django.test import TestCase
from django.test.utils import setup_test_environment
import datetime
from django.utils import timezone
from polls.models import Question
from django.core.urlresolvers import reverse
from django.test import Client

class QuestionMethodTests(TestCase):
    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_published_recently(),False)        //              

    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_recently_question(self):                

        time = timezone.now() - datetime.timedelta(hours=1)                      //       
        recent_question = Question(pub_date=time)                                //        
        self.assertEqual(recent_question.was_published_recently(),True)          //           
/////////////////////////////////////////////////////////////////////////
C:\work\pycharm\mysite>python manage.py test polls
Creating test database for alias 'default'...
F
======================================================================
FAIL: test_was_published_recently_with_future_question (polls.tests.QuestionMethodTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\work\pycharm\mysite\polls\tests.py", line 17, in test_was_published_recently_with_future
_question
    self.assertEqual(future_question.was_published_recently(),False)
AssertionError: True != False                                    //       True, AssertionError  False       

----------------------------------------------------------------------
Ran 1 test in 0.037s

FAILED (failures=1)
Destroying test database for alias 'default'...

C:\work\pycharm\mysite>python manage.py test polls
Creating test database for alias 'default'...

원본 프로그램을 변경합니다. 장래에 이 버그를 수정합니다.
polls.models.py
class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date_published')

    def was_published_recently(self):
        now = timezone.now()
        return now - datetime.timedelta(days=1)<= self.pub_date<=now
    def __unicode__(self):
        return self.question_text
       test,       assert       
/////////////////////////////////////////////////////////////////////////////////////
Creating test database for alias 'default'...
.
----------------------------------------------------------------------
Ran 3 test in 0.001s

OK
Destroying test database for alias 'default'...

테스트는 셸에서 할 수 있습니다
C:\work\pycharm\mysite>python manage.py shell
Python 2.7.8 (default, Jun 30 2014, 16:03:49) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from django.test.utils import setup_test_environment
>>> setup_test_environment()
>>> from django.test import Client
>>> client = Client()
>>> response = client.get('/')                                       //get url     
>>> response.status_code
404                                                                 //‘polls/’    ,   '/'     url 
>>> from django.core.urlresolvers import reverse
>>> response = client.get(reverse('polls:index')                    // http://127.0.0.1/polls/index
... )
>>> response.content
'<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>index</title>
</head>
<body>

<ul>

<li><a href="/polls/1">what weather</a>
</li>
<li ><a href ="/polls/1/">what weather</a></li>

</ul>

</body>
</html>' >>> from polls.models import Question >>> from django.utils import timezone >>> q= Question(question_text="who is your favorite job", pub_date=timezone.now()) // question >>> q.save() >>> response=client.get('/polls/') >>> response.context['latest_question_list'] //render_to_response [<Question: who is your favorite job>, <Question: what weather>] ,

한 프로그램에서 테스트 파일을 많이 쓸수록 좋습니다. 이렇게 하면views의 index와detail 방법을 각각 테스트할 수 있습니다.
polls.test.py
class QuestionViewTests(TestCase):
    def test_index_view_with_no_question(self):                                                      //           
        response = self.client.get(reverse('polls:index'))                                           //  polls:index   
        self.assertEqual(response.status_code,200)                                                   //      ,  question,        
        self.assertContains(response, "No polls are avaliable.")                                     //  question,           ”No polls are avaliable“
        self.assertQuerysetEqual(response.context['latest_question_list'],[])                        //    latest_question_list   0

    def test_index_view_with_a_past_question(self):                                                                 //          question
        create_question(question_text="Past question.", days=-30)                                                   //           
        response = self.client.get(reverse('polls:index'))                                                          
        self.assertQuerysetEqual(response.context['latest_question_list'],['<Question: Past question.>'])           //               ,           ,     ,       5 ,      ,      

    def test_index_view_with_a_future_question(self):                                                //            
        create_question(question_text="Future question.", days=30)                                   //            
        response = self.client.get(reverse('polls:index'))                    
        self.assertContains(response,"No polls are avaliable.", status_code=200)                     //                ,      ”No polls are avaliable“
        self.assertQuerysetEqual(response.context['latest_question_list'],[])                        //             ,   

    def test_index_view_with_future_question_and_past_question(self):                                           //            
        create_question(question_text="Past question", days=-30)
        create_question(question_text="Future question", days=30)
        response = self.client.get(reverse('polls:index'))
        self.assertQuerysetEqual(response.context['latest_question_list'],['<Question: Past question>'])        //         ,         

    def test_index_view_with_two_past_question(self):                                                           //           
        create_question(question_text="Past question 1", days=-30)
        create_question(question_text="Past question 2", days=-5)
        response = self.client.get(reverse('polls:index'))
        self.assertQuerysetEqual(response.context['latest_question_list'],['<Question:Past question 2>'],['<Question: Past question 1>'])        //        2,   1,   question2 question1  

class QuestionIndexDetailTests(TestCase):
    def test_detail_view_with_a_future_question(self):                                                         //            
        future_question = create_question(question_text='Future question', days=5) 
        response = self.client.get(reverse('polls:detail', args=(future_question.id)))
        self.assertEqual(response.status_code,404)                                                             //         ,      

    def test_detail_view_with_a_past_question(self):                                                           //            
        past_question = create_question(question_text='Past Question',days=-5)
        response = self.client.get(reverse('polls:detail',args=(past_question.id)))
        self.assertContains(response,past_question.question_text, status_code=200)                             //    

이러한 테스트를 통해 프로그램에 숨겨진 문제점을 측정할 수 있다. 테스트의 내용은 주도면밀하게 생각할수록 좋고 테스트의 범위가 높을수록 좋으며 모든 함수에 대해 일정한 테스트 방법에 따라 테스트를 해야 한다.

좋은 웹페이지 즐겨찾기