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

再次运行测试,通过。

相关推荐
u***32437 小时前
使用python进行PostgreSQL 数据库连接
数据库·python·postgresql
青瓷程序设计9 小时前
动物识别系统【最新版】Python+TensorFlow+Vue3+Django+人工智能+深度学习+卷积神经网络算法
人工智能·python·深度学习
tobebetter95279 小时前
How to manage python versions on windows
开发语言·windows·python
F_D_Z9 小时前
数据集相关类代码回顾理解 | sns.distplot\%matplotlib inline\sns.scatterplot
python·深度学习·matplotlib
daidaidaiyu10 小时前
一文入门 LangGraph 开发
python·ai
不知更鸟11 小时前
前端报错:快速解决Django接口404问题
前端·python·django
4***721311 小时前
【玩转全栈】----Django模板语法、请求与响应
数据库·python·django
c***421011 小时前
Django视图与URLs路由详解
数据库·django·sqlite
梁正雄11 小时前
1、python基础语法
开发语言·python
2***656312 小时前
数据库操作与数据管理——Rust 与 SQLite 的集成
数据库·rust·sqlite