Django 入门学习总结6 - 测试

news2024/9/20 16:40:30

1、介绍自动化测试

测试的主要工作是检查代码的运行情况。测试有全覆盖和部分覆盖。

自动测试表示测试工作由系统自动完成。

在大型系统中,有许多组件有很复杂的交互。一个小的变化可能会带来意想不到的后果

测试能发现问题,并以此解决问题。

测试驱动开发

在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)

在终端中输入以下命令,对投票系统进行测试:

python manage.py test polls

则输出以下信息。

表明系统有bug,测试失败。

修改文件polls/models.py为:

def was_published_recently(self):
        now = timezone.now()
        return now - datetime.timedelta(days=1) <= self.pub_date <= now

重新测试,则bug消失。

更复杂的测试

在测试文件中输入更多的测试方法:

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)

现在有三个测试方法,分别对应于过去、最近和未来的问题。

可以在客户端建立测试环境来对网页进行测试。

在命令提示符下输入:

python manage.py shell

from django.test.utils import setup_test_environment

setup_test_environment()

导入客户端

from django.test import Client

建立一个客户端实例对象

client = Client()

修改polls/tests.py文件:

from django.urls import reverse

添加以下内容:

def create_question(question_text, days):
        """
        Create a question with the given `question_text` and published the
        given number of `days` offset to now (negative for questions published
        in the past, positive for questions that have yet to be published).
        """
        time = timezone.now() + datetime.timedelta(days=days)
        return Question.objects.create(question_text=question_text, pub_date=time)


    class QuestionIndexViewTests(TestCase):
        def test_no_questions(self):
            """
            If no questions exist, an appropriate message is displayed.
            """
            response = self.client.get(reverse("polls:index"))
            self.assertEqual(response.status_code, 200)
            self.assertContains(response, "No polls are available.")
            self.assertQuerySetEqual(response.context["latest_question_list"], [])

        def test_past_question(self):
            """
            Questions with a pub_date in the past are displayed on the
            index page.
            """
            question = create_question(question_text="Past question.", days=-30)
            response = self.client.get(reverse("polls:index"))
            self.assertQuerySetEqual(
                response.context["latest_question_list"],
                [question],
            )

        def test_future_question(self):
            """
            Questions with a pub_date in the future aren't displayed on
            the index page.
            """
            create_question(question_text="Future question.", days=30)
            response = self.client.get(reverse("polls:index"))
            self.assertContains(response, "No polls are available.")
            self.assertQuerySetEqual(response.context["latest_question_list"], [])

        def test_future_question_and_past_question(self):
            """
            Even if both past and future questions exist, only past questions
            are displayed.
            """
            question = create_question(question_text="Past question.", days=-30)
            create_question(question_text="Future question.", days=30)
            response = self.client.get(reverse("polls:index"))
            self.assertQuerySetEqual(
                response.context["latest_question_list"],
                [question],
            )

        def test_two_past_questions(self):
            """
            The questions index page may display multiple questions.
            """
            question1 = create_question(question_text="Past question 1.", days=-30)
            question2 = create_question(question_text="Past question 2.", days=-5)
            response = self.client.get(reverse("polls:index"))
            self.assertQuerySetEqual(
                response.context["latest_question_list"],
                [question2, question1],
            )

在polls/views.py中,添加以下内容:

class DetailView(generic.DetailView):
        ...

        def get_queryset(self):
            """
            Excludes any questions that aren't published yet.
            """
            return Question.objects.filter(pub_date__lte=timezone.now())

在polls/tests.py中,添加以下的内容:

class QuestionDetailViewTests(TestCase):
        def test_future_question(self):
            """
            The detail view of a question with a pub_date in the future
            returns a 404 not found.
            """
            future_question = create_question(question_text="Future question.", days=5)
            url = reverse("polls:detail", args=(future_question.id,))
            response = self.client.get(url)
            self.assertEqual(response.status_code, 404)

        def test_past_question(self):
            """
            The detail view of a question with a pub_date in the past
            displays the question's text.
            """
            past_question = create_question(question_text="Past Question.", days=-5)
            url = reverse("polls:detail", args=(past_question.id,))
            response = self.client.get(url)
            self.assertContains(response, past_question.question_text)

错误更:如果使用self.assertQuerySetEqual 收到一条错误消息“DeviceTest object has no attribute assertQuerySetEqual

应将assertQuerySetEqual  替换为:assertEqual

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1231264.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Azure Machine Learning - 什么是 Azure AI 搜索?

Azure AI 搜索&#xff08;以前称为“Azure 认知搜索”&#xff09;在传统和对话式搜索应用程序中针对用户拥有的内容提供大规模的安全信息检索。 关注TechLead&#xff0c;分享AI全维度知识。作者拥有10年互联网服务架构、AI产品研发经验、团队管理经验&#xff0c;同济本复旦…

8、创建第一个鸿蒙页面并实现页面跳转

一、创建页面 1、新建页面 在项目的"pages"目录上右键&#xff0c;选择”新建“——”page" 2、录入页面的名称 在“Page name”中输入页面的名称&#xff0c;并点击“Finish”完成创建 3、以下为创建的新页面 2、注册页面 新建的页面会自动在“resources”…

Python---PyCharm调试技巧--Step over(F8)、Step into(F7)

Step over&#xff08;F8&#xff09;&#xff1a;代码一步一步向下执行&#xff0c;但是遇到了函数以后&#xff0c;不进入函数体内部&#xff0c;直接返回函数的最终的执行结果。------------遇到函数跳过&#xff0c;直接执行最后的结果。 Step into&#xff08;F7&#xf…

SpringBoot——静态资源及原理

优质博文&#xff1a;IT-BLOG-CN 一、使用 SpringBoot 的步骤 【1】创建SpringBoot应用&#xff0c;选中自己需要的模块。 【2】SpringBoot已经默认将这些场景配置好&#xff0c;只需要在配置文件中指定少量配置就可以运行起来。 【3】编写业务逻辑代码。 二、自动配置原理 …

iceberg学习笔记(2)—— 与Hive集成

前置知识&#xff1a; 1.了解hadoop基础知识&#xff0c;并能够搭建hadoop集群 2.了解hive基础知识 3.Iceberg学习笔记&#xff08;1&#xff09;—— 基础知识-CSDN博客 可以参考&#xff1a; Hadoop基础入门&#xff08;1&#xff09;&#xff1a;框架概述及集群环境搭建_TH…

归并排序详解:递归实现+非递归实现(图文详解+代码)

文章目录 归并排序1.递归实现2.非递归实现 归并排序 时间复杂度&#xff1a;O ( N * logzN ) 每一层都是N,有log2N层空间复杂度&#xff1a;O&#xff08;N&#xff09;&#xff0c;每个区间都会申请内存&#xff0c;最后申请的数组大小和array大小相同稳定性&#xff1a;稳定 …

【Java程序员面试专栏 算法训练篇】二叉树高频面试算法题

一轮的算法训练完成后,对相关的题目有了一个初步理解了,接下来进行专题训练,以下这些题目就是二叉树相关汇总的高频题目 遍历二叉树 遍历二叉树,分为递归和迭代两种方式,递归类似于DFS,迭代类似于BFS,【算法训练-二叉树 一】【遍历二叉树】前序遍历、中序遍历、后续遍…

OpenCV快速入门:直方图、掩膜、模板匹配和霍夫检测

文章目录 前言一、直方图基础1.1 直方图的概念和作用1.2 使用OpenCV生成直方图1.3 直方图归一化1.3.1 直方图归一化原理1.3.2 直方图归一化公式1.3.3 直方图归一化代码示例1.3.4 OpenCV内置方法&#xff1a;normalize()1.3.4.1 normalize()方法介绍1.3.4.2 normalize()方法参数…

C语言——1.入门须知

文章目录 1.C语言的简要概述1.1.C语言类比自然语言1.2.计算机语言的发展1.3.C语言在当今的地位1.4.C语言的优势和劣势1.4.1.C语言的优势1.4.2.C语言的劣势 2.C语言的应用场景3.C语言的学习路径3.1.学习目的3.2.学习路径3.3.学习资源3.3.1.推荐书籍3.3.2.推荐课程3.3.3.推荐题库…

安全项目简介

安全项目 基线检查 密码 复杂度有效期 用户访问和身份验证 禁用administrator禁用guest认证失败锁定 安全防护软件操作系统安全配置 关闭自动播放 文件和目录权限端口限制安全审计… 等保测评 是否举办了安全意识培训是否有应急响应预案有无第一负责人 工作内容 测评准备…

Linux操作系统使用及C高级编程-D6-D8Linux shell脚本

利用shell命令写的脚本文件&#xff0c;后缀是.sh shell脚本是一个解释型语言&#xff0c;不需要编译&#xff0c;可直接执行 书写&#xff1a;vi test.sh #!/bin/bash&#xff1a;说明使用的是/bin目录下的bash 说明完后即可编写脚本文件 bash test.sh&#xff1a;运行文…

逻辑漏洞(越权)

逻辑漏洞&#xff08;越权&#xff09; 0x01 何为逻辑漏洞 逻辑漏洞是指&#xff0c;在编写程序的时&#xff0c;一个流程处理处理逻辑&#xff0c;不够谨慎或逻辑不完整&#xff0c;从而造成验证失效、敏感信息暴露等问题&#xff0c;这类问题很难利用工具去发现&#xff0c…

『亚马逊云科技产品测评』活动征文|基于next.js搭建一个企业官网

『亚马逊云科技产品测评』活动征文&#xff5c;基于next.js搭建一个企业官网 授权声明&#xff1a;本篇文章授权活动官方亚马逊云科技文章转发、改写权&#xff0c;包括不限于在 Developer Centre, 知乎&#xff0c;自媒体平台&#xff0c;第三方开发者媒体等亚马逊云科技官方…

UDP网络套接字编程

先来说说数据在网络上的传输过程吧&#xff0c;我们知道系统其实终究是根据冯诺依曼来构成的&#xff0c;而网络数据是怎么发的呢&#xff1f; 其实很简单&#xff0c;网络有五层。如下&#xff1a; 如上图&#xff0c;我们知道的是&#xff0c;每层对应的操作系统中的那些地方…

Attingo:西部数据部分SSD存在硬件设计制造缺陷

今年5月&#xff0c;西部数据SanDisk Extreme Pro硬盘陆续有用户反馈有故障发生&#xff0c;用户反馈最多的问题是数据丢失和硬件损坏。8月份&#xff0c;因为这个事情&#xff0c;还被爆出&#xff0c;西部数据面临用户的集体诉讼。 近期&#xff0c;有一个专门从事数据恢复的…

【赠书第6期】MATLAB科学计算从入门到精通

文章目录 前言 1 安装与配置 2 变量定义 3 数据处理 4 绘图 5 算法设计 6 程序调试 7 推荐图书 8 粉丝福利 前言 MATLAB 是一种高级的科学计算和数据可视化平台。它由 MathWorks 公司开发&#xff0c;是科学研究、数据分析和工程实践中非常常用的一种软件工具。本文将…

PC 477B西门子触摸屏维修6AV7853-0AE20-1AA0

西门子触摸屏维修故障有&#xff1a;上电黑屏, 花屏,暗屏,触摸失灵,按键损坏,电源板,高压板故障,液晶,主板坏等,内容错乱、进不了系统界面、无背光、背光暗、有背光无字符&#xff0c;上电无任何显示 &#xff0c;Power灯不亮但其他一切正常&#xff0c;双串口无法通讯 &#x…

力扣-414.第三大的数(两种解法)

文章目录 第三大的数解法一&#xff08;排序加遍历对比&#xff09;解法二&#xff08;遍历一遍加迭代&#xff09; 第三大的数 题目&#xff1a; 给你一个非空数组&#xff0c;返回此数组中第三大的数 。如果不存在&#xff0c;则返回数组中最大的数。 示例 1&#xff1a; 输…

【VRTK】【VR开发】【Unity】7-配置交互能力和向量追踪

【前情提要】 目前为止,我们虽然设定了手模型和动画,还能够正确根据输入触发动作,不过还未能与任何物体互动。要互动,需要给手部设定相应的Interactor能力。 【配置Interactor的抓取功能】 在Hierarchy中选中[VRTK_CAMERA_RIGS_SETUP] ➤ Camera Rigs, Tracked Alias ➤ …