Writing your first Django app, part 5 | Django documentation | Django

自动测试介绍

何为自动测试

测试有系统自动完成。你只需要一次性的编写测试代码,当程序代码变更后,不需要对原来的测试人工再重新测试一遍。系统可以自动运行原来编写的测试代码。

创建自动测试的原因

节约时间,

发现问题,并阻止问题发生

经过测试,是代码被使用的前提

促进团队合作

测试的策略

测试驱动开发(现有测试,再开发)

测试代码越早越好

需要变更或需要修改错误是编写测试代码

编写测试代码

创建测试来发现错误

修改app的test.py文件

运行测试

Terminal命令:python manage.py test polls

修改代码,重新测试成功。结果如下:

测试网页结果

手动测试模拟

django的shell中使用测试的例子,如图

上面是手工过程的结果,Django已经定义基于上述手工过程的方法。

测试列表显示页面

在test.py 中做变更,测试polls/index的网址是否能区分 pub_date 在过去和在将来的区别。

def create_question(question_text, days):"""Create a question with the given `question_text` and published thegiven number of `days` offset to now (negative for questions publishedin the past, positive for questions that have yet to be published)."""time = timezone.now() + datetime.timedelta(days=days)return Question.objects.create(question_text=question_text, pub_date=time)class QuestionIndexViewTests(TestCase):def test_no_questions(self):"""If no questions exist, an appropriate message is displayed."""response = self.client.get(reverse("polls:index"))self.assertEqual(response.status_code, 200)self.assertContains(response, "No polls are available.")self.assertQuerySetEqual(response.context["latest_question_list"], [])def test_past_question(self):"""Questions with a pub_date in the past are displayed on theindex page."""question = create_question(question_text="Past question.", days=-30)response = self.client.get(reverse("polls:index"))self.assertQuerySetEqual(response.context["latest_question_list"],[question],)

另外在class QuestionIndexViewTests定义其他方法:

测试详细显示页面

对于输入的未来问题,输入问题ID的网址,不会显示未来问题。测试中对于未来的问题返回404,对于过去的问题,要显示问题的内容。

class QuestionDetailViewTests(TestCase):def test_future_question(self):"""The detail view of a question with a pub_date in the futurereturns a 404 not found."""future_question = create_question(question_text="Future question.", days=5)url = reverse("polls:detail", args=(future_question.id,))response = self.client.get(url)self.assertEqual(response.status_code, 404)def test_past_question(self):"""The detail view of a question with a pub_date in the pastdisplays the question's text."""past_question = create_question(question_text="Past Question.", days=-5)url = reverse("polls:detail", args=(past_question.id,))response = self.client.get(url)self.assertContains(response, past_question.question_text)

在terminal里运行,python manage.py test polls。

有三条测试失败。根据系统提示进行了相关的修正。其中还修复了一个没有发现的问题。

测试策略:

测试程序可能会超过代码数量。这个并不重要。测试是越多越好的,测试并不怕冗余。测试过程的黄金原则:

  • 对于每个模型和视图都建立单独的 “测试类”
  • 每个测试方法只测试一个功能
  • 给每个测试方法起个能描述其功能的名字