Python unittest - 单元测试示例

2023-11-16

今天我们将学习Python单元测试并浏览Python单元测试示例程序。在之前的教程中我们了解了python zip 函数.

Python单元测试

Python unittest 模块用于测试源代码单元。假设,您需要测试您的项目。您知道该函数将返回什么样的数据。写完大段代码后,需要检查输出是否正确。通常,我们所做的是打印输出并将其与参考输出文件进行匹配或手动检查输出。为了减轻这种痛苦,Python 引入了unittest 模块。使用此模块,您可以通过一些简单的代码检查函数的输出。在本教程中,我们将讨论 Python unittest 模块的基本用法,并编写一些 python 单元测试用例来测试类函数。

Python 单元测试示例源

首先,我们必须编写一些代码来对它们进行单元测试。我们将会有一个Python类。该类的主要目的是存储和检索人名。所以,我们写set_name()功能来存储数据和get_name()函数从类中检索名称。

class Person:
    name = []

    def set_name(self, user_name):
        self.name.append(user_name)
        return len(self.name) - 1

    def get_name(self, user_id):
        if user_id >= len(self.name):
            return 'There is no such user'
        else:
            return self.name[user_id]


if __name__ == '__main__':
    person = Person()
    print('User Abbas has been added with id ', person.set_name('Abbas'))
    print('User associated with id 0 is ', person.get_name(0))

我们将类文件命名为Person.py。上述代码的输出如下所示。

$ python3.6 Person.py 
User Abbas has been added with id  0
User associated with id 0 is  Abbas
$

Python单元测试结构

现在,让我们学习如何编写单元测试代码。单独的测试用例是通过子类化创建的unittest.TestCase。通过重写或添加适当的函数,我们可以添加要测试的逻辑。如果a等于b,则以下代码将成功。

import unittest


class Testing(unittest.TestCase):
    def test_string(self):
        a = 'some'
        b = 'some'
        self.assertEqual(a, b)

    def test_boolean(self):
        a = True
        b = True
        self.assertEqual(a, b)

if __name__ == '__main__':
    unittest.main()

如何运行python单元测试模块

If you’re using PyCharm IDE, you can simply press ctrl+shift+F10 to run unittest module. Otherwise you can use command prompt to run this module. For example, we named the file for unit-testing as Basic_Test.py. So the command to run python unittest will be: $python3.6 -m unittest Basic_Test.Testing If you want to see the verbose, then the command will be; $python3.6 -m unittest -v Basic_Test.Testing By using the PyCharm, we get the below output. Python unittest, python unit test example

Python单元测试结果及基本功能

该单元测试有 3 种可能的结果。下面提到了它们:

  1. OK:如果所有测试用例均通过,则输出显示 OK。
  2. Failure:如果任何测试用例失败并引发 AssertionError 异常
  3. Error:如果引发除 AssertionError 异常之外的任何异常。

unittest模块下有几个函数。下面列出了它们。

Method Checks that
assertEqual(a,b) a==b
assertNotEqual(a,b) a != b
assertTrue(x) bool(x) is True
assertFalse(x) bool(x) is False
assertIs(a,b) a is b
assertIs(a,b) a is b
assertIsNot(a, b) a is not b
assertIsNone(x) x is None
assertIsNotNone(x) x is not None
assertIn(a, b) a in b
assertNotIn(a, b) a not in b
assertIsInstance(a, b) isinstance(a, b)
assertNotIsInstance(a, b) not isinstance(a, b)

Python 单元测试示例

现在是时候为我们的源类编写单元测试了Person。在这个类中我们实现了两个函数 -get_name() and set_name()。现在,我们将使用测试这些功能unittest。因此我们为这两个功能设计了两个测试用例。看看下面的代码,你就很容易理解了。

import unittest

# This is the class we want to test. So, we need to import it
import Person as PersonClass


class Test(unittest.TestCase):
    """
    The basic class that inherits unittest.TestCase
    """
    person = PersonClass.Person()  # instantiate the Person Class
    user_id = []  # variable that stores obtained user_id
    user_name = []  # variable that stores person name

    # test case function to check the Person.set_name function
    def test_0_set_name(self):
        print("Start set_name test\n")
        """
        Any method which starts with ``test_`` will considered as a test case.
        """
        for i in range(4):
            # initialize a name
            name = 'name' + str(i)
            # store the name into the list variable
            self.user_name.append(name)
            # get the user id obtained from the function
            user_id = self.person.set_name(name)
            # check if the obtained user id is null or not
            self.assertIsNotNone(user_id)  # null user id will fail the test
            # store the user id to the list
            self.user_id.append(user_id)
        print("user_id length = ", len(self.user_id))
        print(self.user_id)
        print("user_name length = ", len(self.user_name))
        print(self.user_name)
        print("\nFinish set_name test\n")

    # test case function to check the Person.get_name function
    def test_1_get_name(self):
        print("\nStart get_name test\n")
        """
        Any method that starts with ``test_`` will be considered as a test case.
        """
        length = len(self.user_id)  # total number of stored user information
        print("user_id length = ", length)
        print("user_name length = ", len(self.user_name))
        for i in range(6):
            # if i not exceed total length then verify the returned name
            if i < length:
                # if the two name not matches it will fail the test case
                self.assertEqual(self.user_name[i], self.person.get_name(self.user_id[i]))
            else:
                print("Testing for get_name no user test")
                # if length exceeds then check the 'no such user' type message
                self.assertEqual('There is no such user', self.person.get_name(i))
        print("\nFinish get_name test\n")


if __name__ == '__main__':
    # begin the unittest.main()
    unittest.main()

请注意,unittest 模块按照测试函数的名称顺序执行测试函数,而不是按照它们定义的顺序。由于我们希望首先执行 set_name 测试,因此我们将测试用例函数命名为test_0_set_name and test_1_get_name.

Python 单元测试示例输出

Below images show the output produced by our unit test program - both in normal mode and in verbose mode. Python unit test example python unittest tutorial

$ python3.6 -m unittest -v PersonTest.Test
test_0_set_name (PersonTest.Test) ... Start set_name test

user_id length =  4
[0, 1, 2, 3]
user_name length =  4
['name0', 'name1', 'name2', 'name3']

Finish set_name test

ok
test_1_get_name (PersonTest.Test) ... 
Start get_name test

user_id length =  4
user_name length =  4
Testing for get_name no user test
Testing for get_name no user test

Finish get_name test

ok

----------------------------------------------------------------------
Ran 2 tests in 0.000s

OK
$

这就是 Python 单元测试教程的全部内容。要了解更多信息,请阅读官方文档。如有任何进一步疑问,请使用评论框。 :)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python unittest - 单元测试示例 的相关文章

  • 如何屏蔽 PyTorch 权重参数中的权重?

    我正在尝试在 PyTorch 中屏蔽 强制为零 特定权重值 我试图掩盖的权重是这样定义的def init class LSTM MASK nn Module def init self options inp dim super LSTM
  • 如何在 Ubuntu 上安装 Python 模块

    我刚刚用Python写了一个函数 然后 我想将其做成模块并安装在我的 Ubuntu 11 04 上 这就是我所做的 创建 setup py 和 function py 文件 使用 Python2 7 setup py sdist 构建分发文
  • 使用 Django 的 post_save() 信号

    我有两张桌子 class Advertisement models Model created at models DateTimeField auto now add True author email models EmailField
  • 获取单个方程的脚本

    在文本文件中输入 a 2 8 b 3 9 c 4 8 d 5 9 e a b f c d g 0 6 h 1 7 i e g j f h output i j 期望的输出 输出 2 8 3 9 0 6 4 8 5 9 1 7 如果输入文件名
  • 类属性在功能上依赖于其他类属性

    我正在尝试使用静态类属性来定义另一个静态类属性 我认为可以通过以下代码来实现 f lambda s s 1 class A foo foo bar f A foo 然而 这导致NameError name A is not defined
  • 如何自动替换多个文件的文本内容中的字符?

    我有一个文件夹 myfolder包含许多乳胶表 我需要替换其中每个字符 即替换任何minus sign by an en dash 只是为了确定 我们正在替换连字符INSIDE该文件夹中的所有 tex 文件 我不关心 tex 文件名 手动执
  • NLTK、搭配问题:需要解包的值太多(预期为 2)

    我尝试使用 NLTK 检索搭配 但出现错误 我使用内置的古腾堡语料库 I wrote alice nltk corpus gutenberg fileids 7 al nltk corpus gutenberg words alice al
  • Python3 查找 2 个列表中有多少个差异才能相等

    假设我们有 2 个列表 always具有相同的长度和always包含字符串 list1 sot sot ts gg gg gg list2 gg gg gg gg gg sot 我们需要找到 其中有多少项list2应该改变 以便它等于lis
  • python ttk treeview:如何选择并设置焦点在一行上?

    我有一个 ttk Treeview 小部件 其中包含一些数据行 如何设置焦点并选择 突出显示 指定项目 tree focus set 什么也没做 tree selection set 0 抱怨 尽管小部件明显填充了超过零个项目 但未找到项目
  • 将 subprocess.Popen 的输出通过管道传输到文件

    我需要启动一些长时间运行的进程subprocess Popen 并希望拥有stdout and stderr从每个自动管道到单独的日志文件 每个进程将同时运行几分钟 我想要两个日志文件 stdout and stderr 每个进程当进程运行
  • VSCode pytest 测试发现失败

    Pytest 测试发现失败 用户界面指出 Test discovery error please check the configuration settings for the tests 输出窗口显示 Test Discovery fa
  • Python 中的这种赋值方式叫什么? a = b = 真

    我知道关于元组拆包 http docs python org tutorial datastructures html tuples and sequences但是当一行中有多个等号时 这个赋值被称为什么 阿拉a b True 它总是让我有
  • 在谷歌C​​olab中使用cv2.imshow()

    我正在尝试通过输入视频来对视频进行对象检测 cap cv2 VideoCapture video3 mp4 在处理部分之后 我想使用实时对象检测来显示视频 while True ret image np cap read Expand di
  • Python Flask 是否定义了路由顺序?

    在我看来 我的设置类似于以下内容 app route test def test app route
  • Python 矩阵每一行的总和

    lista 1 2 3 4 5 6 7 8 9 print lista def filas lista res for elemento in lista x sum lista elemento res append x print re
  • WindowsError:[错误 5] 访问被拒绝

    我一直在尝试终止一个进程 但我的所有选项都给出了 Windows 访问被拒绝错误 我通过以下方式打开进程 一个python脚本 test subprocess Popen sys executable testsc py 我想杀死那个进程
  • 是否可以写一个负的python类型注释

    这可能听起来不合理 但现在我需要否定类型注释 我的意思是这样的 an int Not Iterable a string Iterable 这是因为我为一个函数编写了一个重载 而 mypy 不理解我 我的功能看起来像这样 overload
  • 从 dask 数据框中的日期时间序列获取年份和星期?

    如果我有一个 Pandas 数据框和一个日期时间类型的列 我可以按如下方式获取年份 df year df date dt year 对于 dask 数据框 这是行不通的 如果我先计算 像这样 df year df date compute
  • 具有指定置信区间的 Seaborn 条形图

    我想在 Seaborn 条形图上绘制置信区间 但我已经计算出置信区间 如何让 Seaborn 绘制我的置信区间而不是尝试自行计算它们 例如 假设我有以下 pandas DataFrame x pd DataFrame Group 1 0 5
  • 如何识别图形线条

    我有以下格式的路径的 x y 数据 示例仅用于说明 seq p1 p2 0 20 2 3 1 20 2 4 2 20 4 4 3 22 5 5 4 22 5 6 5 23 6 2 6 23 6 3 7 23 6 4 每条路径都有多个点 它们

随机推荐

  • 如何在 CentOS 7 上安装更新

    让您的 CentOS 系统保持最新的安全更新是整体系统安全最重要的部分之一 如果您不使用最新的安全补丁更新操作系统的软件包 您的计算机将容易受到攻击 推荐的方法是使用 yum cron 自动更新 另一种选择是手动更新系统 在本教程中 我们将
  • 如何在 Debian Linux 10 Linux 上安装 VirtualBox

    虚拟盒子是一款开源跨平台虚拟化软件 允许您同时运行多个来宾操作系统 虚拟机 本教程介绍如何在 Debian 10 Buster 上安装最新的 VirtualBox 先决条件 为了能够在 Debian 上安装软件包 您需要以具有 sudo 权
  • Linux 中的 Cd 命令(更改目录)

    The cd 更改目录 命令用于更改 Linux 和其他类 Unix 操作系统中的当前工作目录 它是在 Linux 终端上工作时最基本 最常用的命令之一 The 当前工作目录是用户当前正在其中工作的目录 文件夹 每次与命令提示符交互时 您都
  • 如何在 Debian 9 上安装 Plex 媒体服务器

    Plex 是一款流媒体服务器 可让您组织视频 音乐和照片收藏 并将它们随时随地流式传输到您的所有设备 本教程介绍了如何安装Plex 媒体服务器在 Debian 9 上 先决条件 您登录时必须拥有的用户须藤权限能够安装软件包 安装 Plex
  • 如何在 CentOS 7 上安装 Vagrant

    Vagrant是一个用于构建和管理虚拟机环境的开源命令行工具 默认情况下 Vagrant 可以在 VirtualBox Hyper V 和 Docker 之上配置计算机 其他提供商如 Libvirt KVM VMware 和 AWS 可以通
  • 如何在 Ubuntu 18.04 上安装和配置 Redis

    Redis 是一个开源的内存数据结构存储 它可以用作数据库 缓存和消息代理 并支持各种数据结构 如字符串 哈希 列表 集合等 Redis 通过 Redis Sentinel 提供高可用性 包括监控 通知 自动故障转移 它还通过 Redis
  • 如何在 Ubuntu 18.04 上安装 IntelliJ IDEA

    智能IDEA是一个功能齐全的 IDEJVM和安卓开发 它具有内置的调试支持 Docker and Docker 组合支持 嵌入式Git控制 集成了主要的构建自动化工具 例如Maven and Gradle 语法高亮 代码完成 ssh终端 代
  • 如何在 Debian 9 上安装 Tomcat 8.5

    Apache Tomcat 是一个开源应用程序服务器 支持 Java Servlet JavaServer Pages Java 表达式语言和 Java WebSocket 技术 它是当今世界上使用最广泛的应用程序和 Web 服务器之一 本
  • Linux 中的命令

    at是一个命令行实用程序 允许您安排在特定时间执行的命令 创建的职位at仅执行一次 在这篇文章中 我们将解释如何使用at及其配套实用程序batch atq atrm查看 删除和创建稍后执行的作业 安装中at 根据分布情况 at您的 Linu
  • 如何在 Ubuntu 18.04 上安装 Webmin

    Webmin是一个用于 Linux UNIX 系统管理的开源 Web 控制面板 Webmin 允许您管理用户 组 磁盘配额以及配置最流行的服务 包括 Web FTP 电子邮件和数据库服务器 在本教程中 我们将向您展示如何在 Ubuntu 1
  • 如何在 Ubuntu 20.04 上安装 Nvidia 驱动程序

    本文介绍如何在 Ubuntu 20 04 上安装 NVIDIA 驱动程序 如果您的 Ubuntu 机器有 NVIDIA GPU 您可以选择开源驱动程序Nouveau以及 NVIDIA 的专有驱动程序 默认情况下 Ubuntu 使用 Nouv
  • 如何列出和删除 UFW 防火墙规则

    UFW 代表简单防火墙 是一个用户友好的前端 用于管理 iptables netfilter 防火墙规则 它是默认的防火墙配置工具Ubuntu并且也可用于其他流行的 Linux 发行版 例如Debian和 Arch Linux 在本教程中
  • 如何在 Vue.js 中使用样式和类绑定

    介绍 在本文中 您将了解 Vue js 中的动态样式和类绑定 随着v bind style指令 您将在单击事件上可视化字体大小 和v bind class 您将观察如何将多个类应用于元素 虽然这可以通过 DOM 操作实现 但 Vue js
  • SQL 类似 - SQL 不类似

    SQL LIKE 与 WHERE 子句一起使用来搜索列的模式 通配符是用于指定模式的通配符 有两个通配符与 LIKE 运算符一起使用 用百分比来表示一次 多次或不出现的情况 下划线用于表示单个字符 To use SQL LIKE opera
  • Spring Security 基于角色的访问授权示例

    今天我们将研究 Spring Security 基于角色的访问和授权示例 然而 在阅读这篇文章之前 请先阅读我之前关于 Spring 4 Security MVC 登录注销示例 以获取有关 Spring 4 Security 的一些基本知识
  • 如何在 Python 3 中构造 For 循环

    在计算机编程中使用循环使我们能够自动化并多次重复类似的任务 在本教程中 我们将介绍 Pythonfor loop A for循环基于循环计数器或循环变量实现代码的重复执行 这意味着for当进入循环之前已知迭代次数时 最常使用循环 这与whi
  • Python静态方法

    Python静态方法 In this quick post we will learn how to create and use a Python static method We will also have a look at wha
  • 如何在 Ubuntu 14.04 上使用 Let's Encrypt 保护 HAProxy

    介绍 Let s Encrypt 是一个新的证书颁发机构 CA 它提供了一种获取和安装免费 TLS SSL 证书的简单方法 从而在 Web 服务器上启用加密的 HTTPS 它通过提供软件客户端 Certbot 来简化流程 该客户端尝试自动执
  • 如何在 Ruby 中使用数组

    介绍 An array是一个表示值列表的数据结构 称为elements 数组允许您在单个变量中存储多个值 在 Ruby 中 数组可以包含任何数据类型 包括数字 字符串和其他 Ruby 对象 这可以压缩和组织您的代码 使其更具可读性和可维护性
  • Python unittest - 单元测试示例

    今天我们将学习Python单元测试并浏览Python单元测试示例程序 在之前的教程中我们了解了python zip 函数 Python单元测试 Python unittest 模块用于测试源代码单元 假设 您需要测试您的项目 您知道该函数将