一、测试
写测试类,在app的tests.py
文件下。
import datetime
from django.utils import timezone
from django.test import TestCase
from .models import Question
class QuestionMethodTests(TestCase):
def test_was_published_recently_with_future_question(self):
"""
was_published_recently() should return 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)
在终端运行。
python manage.py test polls
会显示错误。
其中,运行步骤为:
1、该命令寻找polls
的app
2、发现一个django.test.TestCase
的类
3、创建特殊数据库来测试
4、寻找以test
为名字开始的函数test_was_published_recently_with_future_question
。在调用其中的方法。
修改bug。models.py
中的该函数部分。
def was_published_recently(self):
now = timezone.now()
return now - datetime.timedelta(days=1) <= self.pub_date <= now
更加复杂的测试,应该加入到test.py
文件中。
def test_was_published_recently_with_old_question(self):
"""
was_published_recently() should return False for questions whose
pub_date is older than 1 day.
"""
time = timezone.now() - datetime.timedelta(days=30)
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() should return True for questions whose
pub_date is within the last day.
"""
time = timezone.now() - datetime.timedelta(hours=1)
recent_question = Question(pub_date=time)
self.assertIs(recent_question.was_published_recently(), True)
测试还有别的内容,之后再看。