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'...
更改原程序,修改将来时这个bug
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'...
测试可以在shell中进行
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>\n<html lang="en">\n<head>\n <meta charset="UTF-8">\n <title>index</title>\n</head>\n<body>\n\n <ul>\n \n <li><a href="/polls/1">what weather</a>\n </li>\n <li ><a href ="/polls/1/">what weather</a></li>\n \n </ul>\n\n</body>\n</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>] 通过测试模块可以取出值来,就能进行比较和判断
在一个程序中测试文件写的越多越好,这样就可以避免bug外泄,分别对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) //正常显示
通过这样的测试,可以测出程序中隐藏存在的问题,测试的内容想的越周到越好,测试的覆盖率越高越好,对每一个函数都要根据一定的测试方法进行测试