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

再次运行测试,通过。

相关推荐
少林码僧5 小时前
2.31 机器学习神器项目实战:如何在真实项目中应用XGBoost等算法
人工智能·python·算法·机器学习·ai·数据挖掘
智航GIS6 小时前
10.4 Selenium:Web 自动化测试框架
前端·python·selenium·测试工具
jarreyer6 小时前
摄像头相关记录
python
宝贝儿好6 小时前
【强化学习】第六章:无模型控制:在轨MC控制、在轨时序差分学习(Sarsa)、离轨学习(Q-learning)
人工智能·python·深度学习·学习·机器学习·机器人
大、男人6 小时前
python之asynccontextmanager学习
开发语言·python·学习
默默前行的虫虫7 小时前
nicegui文件上传归纳
python
一个没有本领的人7 小时前
UIU-Net运行记录
python
国强_dev7 小时前
Python 的“非直接原因”报错
开发语言·python
副露のmagic7 小时前
更弱智的算法学习 day24
python·学习·算法
廖圣平8 小时前
从零开始,福袋直播间脚本研究【三】《多进程执行selenium》
python·selenium·测试工具