前面那个bug是:当 pub_date 为未来某天时, Question.was_published_recently() 应该返回 False,实际却返回True。
所以可以这样修改下代码 :
def was_published_recently(self):
now = timezone.now()
return now - datetime.timedelta(days=1) <= self.pub_date <= now
修改后重新运行测试:
py manage.py test polls
结果是:
Creating test database for alias ‘default’…
System check identified no issues (0 silenced).
Ran 1 test in 0.001s
OK
Destroying test database for alias ‘default’…
上面的测试只是测试了发布时间是未来的情况,没有测试下发布时间是早于一天前的以及是一天内的(也就是最近发布),所以需要完善下测试代码:
def test_was_published_recently_with_old_question(self):
"""
was_published_recently() returns False for questions whose pub_date
is older than 1 day.
"""
time = timezone.now() - datetime.timedelta(days=1, seconds=1)
old_question = Question(pub_date=time)
self.assertIs(old_question.was_published_recently(), False)
def test_was_published_recently_with_recent_question(self):
"""
was_published_recently() returns True for questions whose pub_date
is within the last day.
"""
time = timezone.now() - datetime.timedelta(hours=23, minutes=59, seconds=59)
recent_question = Question(pub_date=time)
self.assertIs(recent_question.was_published_recently(), True)
现在,我们有三个测试来确保 Question.was_published_recently() 方法对于过去,最近,和将来的三种情况都返回正确的值。