首页 > 其他 > 详细

Django 测试项目5

时间:2020-10-10 15:19:48      阅读:45      评论:0      收藏:0      [点我收藏+]

一、测试项目

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个测试全部通过。
技术分享图片

Django 测试项目5

原文:https://www.cnblogs.com/amnotgcs/p/13792311.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!