Django(6)-django项目自动化测试

Django 应用的测试应该写在应用的 tests.py 文件里。测试系统会自动的在所有以 tests 开头的文件里寻找并执行测试代码。

我们的 polls 应用现在有一个小 bug 需要被修复:我们的要求是如果 Question 是在一天之内发布的, Question.was_published_recently() 方法将会返回 True ,然而现在这个方法在 Question 的 pub_date 字段比当前时间还晚时也会返回 True(这是个 Bug)。

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

polls/test.py

python 复制代码
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)

运行

bash 复制代码
$ 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。

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

修复缺陷:

polls/models.py

python 复制代码
def was_published_recently(self):
    now = timezone.now()
    return now - datetime.timedelta(days=1) <= self.pub_date <= now

再次运行测试,通过。

相关推荐
甄心爱学习11 小时前
【项目实训(个人11)】
python·个人开发
zhangfeng113311 小时前
国家超算中心 htc 如果只有gpu资源 没有cpu资源 操作文件的时候会不会很卡呢
人工智能·pytorch·python·机器学习
jiayong2311 小时前
01 检查 Python 版本与环境
开发语言·python
阿哟阿哟11 小时前
vna.3.1.9.cn.jar设置成中文界面
python·pycharm·jar
XZ-07000111 小时前
MySQL-综合应用(Python+Html)
python·mysql·html
噜噜噜阿鲁~11 小时前
python学习笔记 | 11.4、面向对象高级编程-定制类
笔记·python·学习
站大爷IP12 小时前
Python闭包变量作用域踩坑实录,原来我们都想错了
python
zzj_26261012 小时前
实验七 Python 文件操作与异常处理
开发语言·python
菜到离谱但坚持12 小时前
零门槛学LangChain:AI开发从入门到实战
python·langchain·prompt·rag
Access开发易登软件12 小时前
Access 用 VBA 操作 SQLite,不用装任何驱动
jvm·数据库·sqlite·vba·access·access开发