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

再次运行测试,通过。

相关推荐
金銀銅鐵15 分钟前
斐波那契数列的个位数出现的周期是多少?
python·数学
whcyhhh1 小时前
头歌实践教学平台:数据科学与大数据技术导论(十二)
大数据·开发语言·python·数据清洗
qq_316411032 小时前
专业的腹腔镜医疗器械物联网APP开发服务商
python
阿童木写作2 小时前
跨境电商翻译利器,批量图片视频翻译+智能抠图工具
python·音视频
绘梨衣5473 小时前
异步任务队列-学习2
爬虫·python·学习·任务队列
用户8356290780514 小时前
使用 Python 在 Excel 中插入 OLE 对象
后端·python
one3124 小时前
高精度MEMS电容式倾角传感器:原理、结构与Python三维可视化
开发语言·python
深蓝海拓5 小时前
基于QtPy (PySide6) 的PLC-HMI工程实战记录(七)创建适合HMI项目的数字输入/显示类部件
python
MartinYeung55 小时前
[论文学习]MPIB:医疗提示注入基准——针对LLM临床安全性的系统性评估
人工智能·python·学习