1. 什么是自动化测试
检查代码正确性的一些简单的程序。
运行自动化测试 $ python manage.py test FirstApp
1.1. 测试建议:
- 对每个模型/视图都建立单独的 TestClass
- 每个测试方法只测试一个功能
- 测试方法命名能描述其功能
- 如果你无法测试一段代码,通常说明这段代码需要被重构或者删除
2. 创建一个自动化测试
import datetimefrom django.test import TestCasefrom django.urls import reversefrom django.utils import timezonefrom .models import Question # 引入需要测试的模型# 测试模型class QuestionModelTest(TestCase): # 每个测试类都是 TestCase 子类def test_was_recently_published_with_future_question(self):"""未来发布的问题,不应该属于近期发布"""time = timezone.now() + datetime.timedelta(days=30)future_question = Question(pub_date=time) # 创建一个 pub_date 时 Question 实例# 检查实例的 was_recently_published() 返回值是否为 Falseself.assertIs(future_question.was_recently_published(), False)# 不属于测试的函数def create_question(question_text, days):"""创建问题:根据给定的问题文字,和距离现在的天数(负数为过去,正数为将来)封装了创建投票的流程,减少重复代码"""time = timezone.now() + datetime.timedelta(days=days)return Question.objects.create(question_text=question_text, pub_date=time)# 测试视图class QuestionIndexViewTest(TestCase):"""测试首页视图运行"""def test_no_questions(self):"""如果没有问题存在,需要返回合适的信息"""response = self.client.get(reverse('firstapp:index'))self.assertEqual(response.status_code, 200)self.assertContains(response, '暂无问题')self.assertQuerysetEqual(response.context['latest_question_list'], [])def test_future_question_and_past_question(self):"""如果过去和将来问题都有,只有过去的能显示在首页上"""create_question(question_text='过去的问题', days=-30)create_question(question_text='将来的问题', days=30)response = self.client.get(reverse('firstapp:index'))self.assertQuerysetEqual(response.context['latest_question_list'], ['<Question: 过去的问题>'])
