django初学教程 投票应用 05 自动化测试

https://docs.djangoproject.com/zh-hans/3.2/intro/tutorial05/

第一个测试

存在bug

was_published_recently方法:当Question是在一天之内发布的时,该方法返回True。

# polls/models.py
    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

当前bug:当pub_date字段比当前时间晚时,即pub_date为将来时,也会返回True。

在shell中测试:

创建测试

在tests.py文件中添加自动化测试代码:

# 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)

运行测试

终端输入:

python manage.py test polls

运行结果:

以下是自动化测试的运行过程:

  • 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,而我们期望它返回 False

测试系统通知我们哪些测试样例失败了,和造成测试失败的代码所在的行号。

修复bug

修改model中的 was_published_recently() 方法,只有pub_date是过去时才返回True:

# polls/models.py
def was_published_recently(self):
    now = timezone.now()
    return now - datetime.timedelta(days=1) <= self.pub_date <= now

重新运行测试,结果ok:

全面测试

增加两个测试,确保 was_published_recently() 方法对于一天以前的问题返回False,对于一天内的问题返回True。

# 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)

测试视图

bug:当pub_date为未来时,这个Question在pub_date之前应该是不可见的。

Django测试工具之Client

Client用于模拟用户和视图层代码的交互。

在shell中配置测试环境:

>>> from django.test.utils import setup_test_environment
>>> setup_test_environment() # 提供模板渲染器,可以给responses添加额外属性

# 创建客户端实例
>>> from django.test import Client
>>> 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?>]>

shell框:

改善视图代码

改进 get_queryset() 方法:将pub_date与timezone.now()进行比较,判断是否显示Question。

# 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]

lte表示less than or equal,小于等于;gte表示greater than or equal to,大于等于。ltgt类似。

测试新视图

启动服务器,创建发布时间在过去和将来的Question:

pub_date设置在未来时,index中不会显示:

# polls/tests.py
from django.urls import reverse

# 快捷函数create_question用于创建投票问题
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.
        """
        question = create_question(question_text="Past question.", days=-30)
        response = self.client.get(reverse('polls:index'))
        self.assertQuerysetEqual(
            response.context['latest_question_list'],
            [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.
        """
        question = 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],
        )

    def test_two_past_questions(self):
        """
        The questions index page may display multiple questions.
        """
        question1 = create_question(question_text="Past question 1.", days=-30)
        question2 = create_question(question_text="Past question 2.", days=-5)
        response = self.client.get(reverse('polls:index'))
        self.assertQuerysetEqual(
            response.context['latest_question_list'],
            [question2, question1],
        )

assertContains() 断言参数1response中存在第二个参数"No polls are available."内容。

assertQuerysetEqual()断言参数1匹配参数2中的某个值。

测试DetailView

注意,虽然index中没有第4个未来时问题,但是直接输入URL访问可以查看问题:

为了避免用户直接通过猜测的URL访问到未来日期的pub_date添加约束

# 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())

再访问出现404,说明约束有效:

增加测试:

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)

测试建议

  • 对于每个模型和视图都建立单独的 TestClass
  • 每个测试方法只测试一个功能
  • 给每个测试方法起个能描述其功能的名字
posted @ 2021-09-04 00:06  ikventure  阅读(127)  评论(0)    收藏  举报