5.1 Fixed bug

master
Jason Zhu 2020-10-20 21:08:19 +11:00
parent 550eed5dad
commit 07b5806efa
2 changed files with 23 additions and 3 deletions

View File

@ -487,3 +487,22 @@ Ran 1 test in 0.001s
FAILED (failures=1)
Destroying test database for alias 'default'...
```
解释上述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
```

View File

@ -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