From 07b5806efab73c24d132f229a9b147bb8202c957 Mon Sep 17 00:00:00 2001 From: JasonHomeWorkstationUbuntu Date: Tue, 20 Oct 2020 21:08:19 +1100 Subject: [PATCH] 5.1 Fixed bug --- first_django_app.md | 21 ++++++++++++++++++++- src/polls/models.py | 5 +++-- 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/first_django_app.md b/first_django_app.md index 0617d9a..ac8d309 100644 --- a/first_django_app.md +++ b/first_django_app.md @@ -486,4 +486,23 @@ Ran 1 test in 0.001s FAILED (failures=1) Destroying test database for alias 'default'... -``` \ No newline at end of file +``` + +解释上述msg: +* python manage.py test polls 将会寻找 polls 应用里的测试代码 +* 它找到了 django.test.TestCase 的一个子类 +* 它创建一个特殊的数据库供测试使用 +* 它在类中寻找测试方法——以 test 开头的方法。 +* 在 test_was_published_recently_with_future_question 方法中,它创建了一个 pub_date 值为 30 天后的 Question 实例。 +* 接着使用 assertls() 方法,发现 was_published_recently() 返回了 True,而我们期望它返回 False。 + +#### Fix the bug + +Fix bug in `polls/models.py` + +```python + def was_published_recently(self): + now = timezone.now() + return now - datetime.timedelta(days=1) <= self.pub_date <= now +``` + diff --git a/src/polls/models.py b/src/polls/models.py index 4e428ec..ba80914 100644 --- a/src/polls/models.py +++ b/src/polls/models.py @@ -1,7 +1,7 @@ import datetime from django.db import models -from django.utils import timezone as djtz +from django.utils import timezone class Question(models.Model): # question_text & pub_date are instances of field @@ -9,7 +9,8 @@ class Question(models.Model): pub_date = models.DateTimeField('date published') def was_published_recently(self): - return self.pub_date >= djtz.now() - datetime.timedelta(days=1) + now = timezone.now() + return now - datetime.timedelta(days=1) <= self.pub_date <= now def __str__(self) -> str: return self.question_text