django官方demo翻译简化版 五

本章讲解基于django的自动化测试

编写第一个自动化测试

确认第一个bug

我们在django的demo里确认了一个Bug:Question.was_published_recently()方法会返回True假如问题发布的时间在最近时间内,但是假如问题发布的时间在未来的话,这个计算方式也会返回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

因为未来的事情并不是最近,所以这种很明显是错的。

编写测试来发现这个问题

刚才我们的调试过程就是我们的自动化代码要做的事情,现在我们把上述过程转换为代码写到自动化代码里。

django的应用的tests.py就是我们应该把测试写在这里面。测试系统会自动检测这个文件里的名称以test开头的文件:

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)

这里我们可以在将来创建一个django.test.TestCase 的子类,这个子类有一个包括了Question实例的方法。然后我们就可以检查was_published_recently()的输出结果--这个结果就会是False。

运行测试

在控制台,我们可以使用如下命令运行测试:

$ python manage.py test polls

然后,我们会看到如下结果:

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'...

上述过程可以用下面的这个过程来解释:

  • manage.py test polls会自动查找polls应用里的test文件
  • 它会查找django.test.TestCase 的子类
  • 然后它会查找子类里面名称以test开头的那些方法
  • 在test_was_published_recently_with_future_question方法中它编写了一个拥有pub_date的时间在未来30天后的Question实例
  • 最后会使用assertIs() 方法,它会发现was_published_recently()会返回True,这个和我们的预期结果不一致

这个测试会通知我们测试失败了而且当出现失败时会告诉我们哪里有问题

修复bug

我们已经知道这个bug出现的原因是由于设置了pub_date的值是未来的。那么我们可以对这个models.py的代码做修改如下:

polls/models.py


def was_published_recently(self):
    now = timezone.now()
    return now - datetime.timedelta(days=1) <= self.pub_date <= now

然后我们再次运行测试:

Creating test database for alias 'default'...
System check identified no issues (0 silenced).
.
----------------------------------------------------------------------
Ran 1 test in 0.001s

OK
Destroying test database for alias 'default'...

在确定了这个bug后,我们写了个测试去发现它,然后修复这个bug。

更全面的测试

到了这一步后,我们可以进一步确定was_published_recently()这个方法的正确性;实际上,假如我们在修复了一个Bug后又同时引入了另一个bug的话,那会很尴尬。

那么我们需要对这个方法做更多的测试:

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)

写完上述代码后,我们就对这个方法有了三个测试方法来确保它运行正常。

polls 这个demo是个很简单的应用,它变的复杂度越来越高后,我们也可以确定我们编写了测试的那部分代码会运行良好。

对VIEW做测试

 我们的demo,polls相对来讲是不严谨的:它可以 发布任何时期的问题。我们应该修改下这一块。未来的问题应该只有在那一刻到达的时候才显示出来。

测试view

当我们修复上述bug的时候,我们先写了测试然后写修复的代码。实际上这是一种很明显的测试驱动的的模式,但是它并不关心它的命令是怎么实现的。

在我们的第一个测试里,我们更关注代码的网络行为的代码。在这里,我们更关注它的网络表现行为。

在我们尝试修复任何东西前,我们先关注一下我们即将使用的工具。

django测试客户端

django提供了一个测试客户端用来模拟用户与view之间的交互。我们可以在tests.py或者shell中使用它。

启动shell:

python manage.py shell
>>> from django.test.utils import setup_test_environment
>>> setup_test_environment()

setup_test_environment()提供了一个测试用的模板系统来获取请求的属性或者响应内容。注意这个方法并不会设置一个测试数据库,所以下述运行的结果可能会和现有的数据库结果不一致。这可能会得到没有预期的结果如果你在settings.py文件里配置的TIME_ZONE不对的话。你可以在运行前,检查一下这个配置项。

下一步,我们需要引入一些测试类(晚点在 tests.py 里,我们将会使用 django.test.TestCase类,这个类有自己的客户端,所以后面我们不需要这些测试类)。

>>> 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&#x27;s up?</a></li>\n    \n    </ul>\n\n'
>>> response.context['latest_question_list']
<QuerySet [<Question: What's up?>]>

重构VIEW

polls里展示了一些没有到发布时间的问题,现在我们修复这个问题。

在前面我们使用了基于类的视图方式,基于ListView::

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]

我们需要修改下get_queryset()方法,使他通过和timezone.now()比较来确定日期。首先我们需要导包:

polls/views.py

from django.utils import timezone

然后修改get_queryset 方法:

polls/views.py

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]

Question.objects.filter(pub_date__lte=timezone.now())会返回一个日期早于timezone.now的结果。

测试新的view

现在你可以创建任何时期的问题来看下是否显示正常。如果你担心对项目有影响,你可以在shell中创建一个测试:

polls/tests.py

from django.urls import reverse

然后我们会快速的创建几个问题以及新的测试类:

polls/tests.py


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_questions 没有新建任何问题,但是用来验证这个信息:“No polls are available.”并且用来验证latest_question_list是空的。注意下,django.test.TestCase

也自带了断言方法。在上述代码中,我们使用了assertContains() and assertQuerysetEqual()

在test_past_question中,我们创建了一个符合条件的问题。

在test_future_question里,我们创建了一个在将来才会出现的问题。创建的数据只是用来测试的,并不会写进数据库,所以测试完毕后不会新增脏数据。

诸如此类。在实际中,我们会使用测试来测试应用的输入及网站显示效果,以及系统里的任何变动是符合我们的预期的。

测试DetailView

尽管我们在网页上不会看到未来的问题,但是假如我们猜到了正确的URL的话也可以查询到。所以我们需要给DetailView添加一个类似的限制条件:

polls/views.py


class DetailView(generic.DetailView):
    ...
    def get_queryset(self):
        """
        Excludes any questions that aren't published yet.
        """
        return Question.objects.filter(pub_date__lte=timezone.now())

当然,我们也会使用测试来确保过去的问题可以展示,但是未来日期的问题不会展示:

polls/tests.py


class QuestionDetailViewTests(TestCase):
    def test_future_question(self):
        """
        The detail view of a question with a pub_date in the future
        returns a 404 not found.
        """
        future_question = create_question(question_text='Future question.', days=5)
        url = reverse('polls:detail', args=(future_question.id,))
        response = self.client.get(url)
        self.assertEqual(response.status_code, 404)

    def test_past_question(self):
        """
        The detail view of a question with a pub_date in the past
        displays the question's text.
        """
        past_question = create_question(question_text='Past Question.', days=-5)
        url = reverse('polls:detail', args=(past_question.id,))
        response = self.client.get(url)
        self.assertContains(response, past_question.question_text)

更多的测试想法

我们应该给ResultsView添加同样的get_queryset方法来进行测试。

 我们也可以增加更多的测试来提升我们的应用。比如,假如一个问题发布了但是没有可选择答案的话会显得比较蠢。所以我们的view应该检测这种情况,然后避免这种情况。我们的测试也会新建一个没有任何答案的问题然后会测试它没有被发布。有答案的问题也会被发布。

也许管理员可以看到未发布的问题,但是普通用户不能看到。那么我们的view应该提现出这种情况。最后说一下,无论你添加了什么代码都应该给它增加对应的测试代码。

还有一个比较重要的点就是,我们需要经常注意查看我们的测试代码,看下我们是否编写的测试太多,太冗余。

测试越多越好

可能我们会觉得我们的测试开始越来越超出我们的掌控了。在这种节奏下,我们的测试代码将会远远的超过我们的应用代码并且与我们的剩余代码对比来看,这种重复毫无美感。

没关系。让他们增加。对大部分的来讲,你可能写一次测试代码然后就会忘掉它们。只要你还在编写你的程序,那么它们就会一直执行它有用的功能。

有一些测试应该经常更新的。假如我们修改了我们的views那么只有被发布的Questions才会被展示。那么早先写的关于这部分的测试代码就会失败。那么这些失败的测试我们也需要更新。

在我们开发的过程中,我们可能会发现我们的测试代码有点冗余了。即使这其实在测试里面并不是一个问题,在测试里冗余其实是个好的事情。

只要你的测试是合理安排的,那么它们就不会是不好管理的。好的经验法则告诉我们应该包括如下:

  • 给每个model或者view都分别新建一个TestClass
  • 给你要测试的每个场景单独分配一个测试方法
  • 测试方法的名称简单明了的表达它的功能

进一步的测试 

这篇里限于篇幅只是讲了最基本的测试。还有更多更好的想法及更好的工具来进行测试。

比如,我们在测试views及model的展示逻辑的时候,我们就可以通过selenium这个工具来对html页面的展示情况进行测试。这些工具可以让你检测django代码是否运行良好以及JavaScript是否执行良好。看到测试启动一个浏览器,然后像人一样操作浏览器是很有意思的事情。django提供了LiveServerTestCase去促进集成一些类似于selenium的工具。

假如你的应用比较复杂,那么你可以通过持续集成工具来实现自动或者部分自动话的进行测试,在你每次提交代码的时候。

一个更好的检测你的应用的方式是现场检测代码覆盖率。这种方法也对检测无效代码或者健壮性不够的代码很有效。假如你无法对代码进行任何测试,那么它通常意味着代码需要被重构或者被移除。覆盖率会帮助确认无效代码。

 

posted @ 2020-05-22 17:33  逗蚂蚁  阅读(281)  评论(0)    收藏  举报