16 应用测试
编写第一个测试程序
先在admin后台创建一个发布日期在未来的question,在shell中验证这个bug
>>> import datetime
>>> from django.utils import timezone
>>> from polls.models import Question
>>> q.was_published_recently()
True
通过自动化测试来完成这个操作
Models.py
def was_published_recently(self):
now = timezone.now()
return now - datetime.timedelta(days=1) <= self.pub_date <= now
test.py
from django.test import TestCase
import datetime
from django.utils import timezone
from .models import Question
# Create your tests here.
'''
问卷测试
'''
def test_was_published_recently_with_old_question(self):
"""
日期超过1天的将返回False。这里创建了一个30天前发布的实例。
"""
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):
"""
最近一天内的将返回True。这里创建了一个1小时内发布的实例。
"""
time = timezone.now() - datetime.timedelta(hours=1)
recent_question = Question(pub_date=time)
self.assertIs(recent_question.was_published_recently(), True)
17 测试一个视图
测试用客户端
>>> from django.test.utils import setup_test_environment
>>> setup_test_environment
<function setup_test_environment at 0x0310DC00>
>>>
>>> from django.test import Client #导入客户端
>>> client=Client()#创建一个实例
>>> response=client.get('/')#从/获取响应
Not Found: /
>>> response.status_code#从这个地址返回的是404
404
>>> from django.urls import reverse
>>> response=client.get(reverse('polls:index'))#通过polls获取内容
>>> response.status_code
200
>>> response.content#取得response的正文内容
b'\n <ul>\n \n <li>\n \n\n <a href="/polls/3/">\n test case\n </a>\n\n \n <a href="/polls/3/">
\n test case\n </a>\n </li>\n \n <li>\n \n\n <a href="/polls/2/">\n what is your name ?\n
</a>\n\n \n <a href="/polls/2/">\n what is your name ?\n </a>\n </li>\n \n <li>\n \n\n
<a href="/polls/1/">\n what is up?\n </a>\n\n \n <a href="/polls/1/">\n what is up?\n </a>\n
</li>\n \n </ul>\n'
>>>
修改views.py
# 最近的5个调查问卷
def get_queryset(self):
# return Question.objects.order_by('-pub_date')[:5]
#查询的结果在当前时间之前,不包含将来的时间
return Question.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[:5]
编写自动作测试
from django.test import TestCase
import datetime
from django.utils import timezone
from .models import Question
from django.urls import reverse
# Create your tests here.
'''
问卷测试
'''
def test_was_published_recently_with_old_question(self):
"""
日期超过1天的将返回False。这里创建了一个30天前发布的实例。
"""
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):
"""
最近一天内的将返回True。这里创建了一个1小时内发布的实例。
"""
time = timezone.now() - datetime.timedelta(hours=1)
recent_question = Question(pub_date=time)
self.assertIs(recent_question.was_published_recently(), True)
'''
创建question,
question_text 问卷的文本内容
days 当前时间的偏移天数,负值表过去,正值表将来
'''
def create_question(question_text, days):
time = timezone.now() + datetime.timedelta(days=days)
return Question.objects.create(question_text=question_text, pub_date=time)
class QuestionViewTests(TestCase):
#
def test_index_viewwith_no_questions(self):
response = self.client.get(reverse('polls:index'))
# 返回状态码正常
self.assertEquals(response.status_code, 200)
self.assertContains(response, 'no polls are available.')
self.assertQuerysetEqual(response.context['latest_question_list'], [])
def test_index_view_with_a_past_question(self):
""" 发布日期在过去的问卷将在index页面显示。 """
create_question(question_text="Past question.", days=-30)
response = self.client.get(reverse('polls:index'))
self.assertQuerysetEqual(
response.context['latest_question_list'],
['<Question: Past question.>']
)
def test_index_view_with_a_future_question(self):
""" 发布日期在将来的问卷不会在index页面显示 """
create_question(question_text="Future question.", days=30)
response = self.client.get(reverse('polls:index'))
self.assertContains(response, "No polls are available.")
self.assertQuerysetEqual(response.context['latest_question_list'], [])
def test_index_view_with_future_question_and_past_question(self):
""" 即使同时存在过去和将来的问卷,也只有过去的问卷会被显示。 """
create_question(question_text="Past question.", days=-30)
create_question(question_text="Future question.", days=30)
response = self.client.get(reverse('polls:index'))
self.assertQuerysetEqual(
response.context['latest_question_list'],
['<Question: Past question.>']
)
def test_index_view_with_two_past_questions(self):
""" index页面可以同时显示多个问卷。 """
create_question(question_text="Past question 1.", days=-30)
create_question(question_text="Past question 2.", days=-5)
response = self.client.get(reverse('polls:index'))
self.assertQuerysetEqual(
response.context['latest_question_list'],
['<Question: Past question 2.>', '<Question: Past question 1.>']
)