在《Python Web开发:测试驱动方法》一书中作者使用的 Django 版本是 1.7,而我使用的是1.9.7版(官网已经更新到1.10了)。这就导致书中给出的代码可能有“过时”的部分。
比如,下面是第三章一个单元测试tests.py
的代码,运行没有问题。但是当第五章引入表单后,相应模板中需在标签内加入CSRF令牌
{% csrf_token %}
。此时再次运行此单元测试会报错。
from django.test import TestCase
from django.core.urlresolvers import resolve
from django.http import HttpRequest
from django.template.loader import render_to_string
from .views import home_page
class HomePageTest(TestCase):
def test_root_url_resolves_to_home_page_view(self):
found = resolve('/')
self.assertEqual(found.func, home_page)
def test_home_page_returns_correct_html(self):
request = HttpRequest()
response = home_page(request)
expected_html = render_to_string('home.html')
self.assertEqual(response.content.decode(), expected_html)
错误信息:
$ python3 manage.py test lists
Creating test database for alias 'default'...
F.
======================================================================
FAIL: test_home_page_returns_correct_html (lists.tests.HomePageTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/panzeyan/PycharmProjects/TDD/superlists/lists/tests.py", line 20, in test_home_page_returns_correct_html
self.assertEqual(response.content.decode(), expected_html)
AssertionError: '\n' != '\n\n
1: