一、测试项目
1.1 测试原理
在应用目录下,所有以tests
开关的文件,都被认为是测试。
django会自动在其中寻找测试代码。
本次测试发布时间。
如果发布时间在一天之内,was_published_recently
会返回true
,
而如果时间是未来时间,也会返回true,
下面我们将测试这个bug。
1.2 编写测试代码
在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)
1.3 启动测试
python manage.py test polls
1.4 回顾测试流程
1、python manage.py test polls
会寻找polls应用中的测试代码。
2、找到一个django.test.TestCase
的子类。
3、创建一个特殊数据库供测试使用。
4、寻找以test开头的方法。
5、在assertls方法中,我们预期返回false,结果返回了true,测试失败。
6、测试系统通知测试结果,返回失败行号。
1.5 修复bug
我们在polls/models.py中修改如下内容:
def was_published_recently(self):
now = timezone.now()
return now - datetime.timedelta(days=1) <= self.pub_date <= now
重新启动测试:
测试通过。
1.6 编写更全面的测试
增加测试代码,确保代码对于过去、现在、将来都返回正确的值。
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)
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)
如图,3个测试全部通过。
二、视图测试
2.1 Client环境测试
python manage.py shell
from django.test.utils import setup_test_environment
setup_test_environment()
from django.test import Client
# create an instance of the client for our use
client = Client()