"""向浏览器返回真正的HTML响应,添加一个新的测试方法""" from django.test import TestCase from django.urls import resolve from django.http import HttpRequest from django.template.loader import render_to_string from lists.views import home_page class HomePageTest(TestCase): def test_root_url_to_home_page(self): found = resolve('/') # resolve是Django内部函数,用于解析URL,并将其映射到相应的视图函数上 self.assertEqual(found.func, home_page) # 检查解析网站根路径/时,是否能找到home_page def test_home_page_returns_correct_html(self): response = self.client.get('/') # 1 html = response.content.decode('utf8') # 2 self.assertTrue(html.startswith('<html>')) self.assertIn('<title>To-Do lists</title>', html) self.assertTrue(html.strip().endswith('</html>')) self.assertTemplateUsed(response, 'home.html') # 3 """ 代码解析: 1、不是手动创建httprequest对象并调用view函数,直接调用self.client.get,将要测试的url传递给它。 2、我们暂时把旧的测试留在那里,以确保一切正常。就像我们想象的那样。 3、asserttemplateUsed是django测试用例类pro-提供给我们它允许我们检查用于呈现响应的模板(仅适用于测试客户端检索到的响应) """
运行单元测试
python manage.py test Creating test database for alias 'default'... System check identified no issues (0 silenced). .. ---------------------------------------------------------------------- Ran 2 tests in 0.006s OK Destroying test database for alias 'default'...
提交版本
$ git status # 会看见lists/tests.py,views.py,settings.py以及新建的templates文件夹 $ git add . $ git diff --staged $ git commit -m "Refactor home page view to use a template——使用模板重构主页视图"