接上一章,我们创建一个关于“最近发布”的bug
修改polls 应用里的 tests.py 文件:
import datetime
from django.test import TestCase
from django.utils import timezone
from .models import Question
class QuestionModelTests(TestCase):
def test_was_published_recently_with_future_question(self):
"""
was_published_recently() returns False for questions whose pub_date
is in the future.
"""
time = timezone.now() + datetime.timedelta(days=30)
future_question = Question(pub_date=time)
self.assertIs(future_question.was_published_recently(), False)
这段代码 创建了一个 django.test.TestCase 的子类,并添加了一个方法,此方法创建一个 pub_date 是未来某天的 Question 实例。然后检查它的 was_published_recently() 方法的返回值——它 应该 是 False
添加上测试代码后就可以运行测试了:
py manage.py test polls
将会看到如下结果 :
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
F
======================================================================
FAIL: test_was_published_recently_with_future_question (polls.tests.QuestionModelTests)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/path/to/mysite/polls/tests.py", line 16, in test_was_published_recently_with_future_question
self.assertIs(future_question.was_published_recently(), False)
AssertionError: True is not False
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (failures=1)
Destroying test database for alias 'default'...