自动化测试简介
测试,是用来检查代码正确性的一些简单的程序。
测试在不同的层次中都存在。有些测试只关注某个很小的细节(某个模型的某个地方的返回值是否满足预期),而另一些测试可能检查对某个软件的一些列操作(某一用户输入序列是否造成了预期的结果?)。
测试的优点:
- 测试节约可以节约时间
- 测试不仅能发现错误,而且能预防错误
- 测试使你的代码更由有吸引力
- 测试有利于团队协作
编写测试
polls应用里有一个小bug,要求是如果Question是在一天之内发布的,Question.was_published_recently()方法将会返回True,然而现在这个方法在Question的pub_date字段比当前时间还晚时也会返回True。
通过shell命令
python manage.py shell
>>> import datetime
>>> from django.utils import timezone
>>> from polls.models import Question
>>> # create a Question instance with pub_date 30 days in the future
>>> future_question = Question(pub_date=timezone.now() + datetime.timedelta(days=30))
>>> # was it published recently?
>>> future_question.was_published_recently()
True
因为将来发生的肯定不是的最近发生的,所以代码明显是错的。
创建测试暴露bug
按照惯例,Django应用的测试应该写在应用的tests.py文件里,测试系统会自动的所有以tests开头的文件里寻找并执行测试代码。
将下面的代码写入polls应用里的test.py文件内
# poll/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)
创建一个django.test.TestCase的子类,并添加了一个方法,此方法创建一个pub_date时未来某天的Question实例。然后检查它的was_publisher_recently()方法的返回值。它应该是False。
运行测试
在终端中,运行测试
python manage.py test polls
运行结果
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
F
======================================================================
FAIL: test_was_published_recently_with_future_question (polls.tests.QuestionModelTests)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/path/to/mysite/polls/tests.py", line 16, in test_was_published_recently_with_future_question
self.assertIs(future_question.was_published_recently(), False)
AssertionError: True is not False
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (failures=1)
Destroying test database for alias 'default'...
自动化测试的运行过程:
- 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。
测试系统通过哪些测试样例失败了,和造成测试失败的代码所在的行号。
修复bug
当pub_data为未来某天时,Question.was_published_recently()应该返回False,修改models.py里的方法,让它只在日期时过去式的时候才返回True。
# polls/models.py
def was_published_recently(self):
now = timezone.now()
return now - datetime.timedelta(days=1) <= self.pub_date <= now
更全面的测试
有些时候在修复bug时不小心引入另一个bug。
在tests.py再增加两个测试,来更全面的测试这个方法。
# polls/tests.py
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)
使用三个测试来确保Question.was_published_recently()方法对于过去,最近,和将来的三种情况都返回正确的值。
测试视图
Django测试工具之Client,Django提供了一个供测试使用的Client来模拟用户和视图层代码的交互。
可以再test.py甚至是shell中使用它。
python manage.py shell
>>> from django.test.utils import setup_test_environment
>>> setup_test_environment()
setup_test_enviroment()提供了一个模板渲染器,允许为responses添加一些额外的属性,例如response.context,未安装此app无法使用此功能,输出的内容可能由于数据库内容的不同而不同。
>>> from django.test import Client
>>> # create an instance of the client for our use
>>> client = Client()
>>> # get a response from '/'
>>> response = client.get('/')
Not Found: /
>>> # we should expect a 404 from that address; if you instead see an
>>> # "Invalid HTTP_HOST header" error and a 400 response, you probably
>>> # omitted the setup_test_environment() call described earlier.
>>> response.status_code
404
>>> # on the other hand we should expect to find something at '/polls/'
>>> # we'll use 'reverse()' rather than a hardcoded URL
>>> from django.urls import reverse
>>> response = client.get(reverse('polls:index'))
>>> response.status_code
200
>>> response.content
b'\n <ul>\n \n <li><a href="/polls/1/">What's up?</a></li>\n \n </ul>\n\n'
>>> response.context['latest_question_list']
<QuerySet [<Question: What's up?>]>
现在的投票会显示将来的投票(pub_date值是未来的某天)。
# polls/views.py
class IndexView(generic.ListView):
template_name = 'polls/index.html'
context_object_name = 'latest_question_list'
def get_queryset(self):
"""Return the last five published questions."""
return Question.objects.order_by('-pub_date')[:5]
修改后代码
# polls/views.py
from django.utils import timezone
def get_queryset(self):
"""
Return the last five published questions (not including those set to be
published in the future).
"""
return Question.objects.filter(
pub_date__lte=timezone.now()
).order_by('-pub_date')[:5]
测试新视图
编写polls/tests.py
from django.urls import reverse
def create_question(question_text, days):
"""
Create a question with the given `question_text` and published the
given number of `days` offset to now (negative for questions published
in the past, positive for questions that have yet to be published).
"""
time = timezone.now() + datetime.timedelta(days=days)
return Question.objects.create(question_text=question_text, pub_date=time)
class QuestionIndexViewTests(TestCase):
def test_no_questions(self):
"""
If no questions exist, an appropriate message is displayed.
"""
response = self.client.get(reverse('polls:index'))
self.assertEqual(response.status_code, 200)
self.assertContains(response, "No polls are available.")
self.assertQuerysetEqual(response.context['latest_question_list'], [])
def test_past_question(self):
"""
Questions with a pub_date in the past are displayed on the
index page.
"""
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_future_question(self):
"""
Questions with a pub_date in the future aren't displayed on
the index page.
"""
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_future_question_and_past_question(self):
"""
Even if both past and future questions exist, only past questions
are displayed.
"""
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_two_past_questions(self):
"""
The questions index page may display multiple questions.
"""
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.>']
)
快捷函数create_question,它封装了创建投票的流程,减少了重复代码。
- test_no_question方法里没有创建任何投票,检查返回的网页上有没有“No polls are available”
- test_past_question方法中,创建一个投票并检查他是否出现在列表中
- test_future_question中,创建pub_date在未来某天的投票。