Today we will learn about python unittest and look through python unit test example programs. In previous tutorial we learned about python zip function.

今天,我们将学习python unittest并浏览python unittest示例程序。 在上一教程中,我们了解了python zip函数 。

Python单元测试 (Python unittest)

Python unittest module is used to test a unit of source code. Suppose, you need to test your project. You know what kind of data the function will return. After writing huge code, you need to check it whether the output is correct or not.

Python unittest模块用于测试源代码单元。 假设您需要测试您的项目。 您知道函数将返回哪种数据。 编写大量代码后,您需要检查其输出是否正确。

Normally, what we do is printing the output and match it with the reference output file or check the output manually.

通常,我们要做的是打印输出并将其与参考输出文件匹配,或者手动检查输出。

To reduce this pain, Python has introduced unittest module. Using this module you can check the output of the function by some simple code. In this tutorial we will discuss about basic usage of Python unittest module and write some python unit test cases to test a class functions.

为了减轻这种痛苦,Python引入了unittest模块。 使用此模块,您可以通过一些简单的代码来检查函数的输出。 在本教程中,我们将讨论Python unittest模块的基本用法,并编写一些python单元测试用例来测试类功能。

Python单元测试示例源 (Python Unit Test Example Source)

First of all we have to write some code to unit test them. We will have a Python class.

首先,我们必须编写一些代码以对其进行单元测试。 我们将有一个Python类 。

The main purpose of the class is to store and retrieve person’s name. So, we write set_name() function to store the data and get_name() function to retrieve name from the class.

该类的主要目的是存储和检索人的名字。 因此,我们编写了set_name()函数来存储数据,并get_name()函数来从类中检索名称。

class Person:name = []def set_name(self, user_name):self.name.append(user_name)return len(self.name) - 1def 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))

We named the class file as Person.py. And the output of the above code will be like below.

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

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

Python单元测试结构 (Python unittest structure)

Now, let’s learn how to code for unit testing. An individual testcase is created by subclassing unittest.TestCase. By overriding or adding appropriate functions, we can add logic to test. The following code will be succeeded if a is equals to b.

现在,让我们学习如何为单元测试编写代码。 通过将unittest.TestCase子类化来创建单个测试用例。 通过覆盖或添加适当的功能,我们可以添加逻辑进行测试。 如果a等于b,则以下代码将成功。

import unittestclass Testing(unittest.TestCase):def test_string(self):a = 'some'b = 'some'self.assertEqual(a, b)def test_boolean(self):a = Trueb = Trueself.assertEqual(a, b)if __name__ == '__main__':unittest.main()

如何运行python unittest模块 (How to run python unittest module)

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:

如果您使用的是PyCharm IDE,则只需按ctrl + shift + F10即可运行unittest模块。 否则,您可以使用命令提示符运行此模块。 例如,我们将用于单元测试的文件命名为Basic_Test.py 。 因此,运行python unittest的命令将是:


$python3.6 -m unittest Basic_Test.Testing


$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


$python3.6 -m unittest -v Basic_Test.Testing

By using the PyCharm, we get the below output.

通过使用PyCharm,我们得到以下输出。

Python单元测试结果和基本功能 (Python Unit Test Outcome & Basic Functions)

This unittest has 3 possible outcomes. They are mentioned below:

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

  1. OK: If all test cases are passed, the output shows OK.OK:如果所有测试用例都通过,则输出显示OK。
  2. Failure: If any of test cases failed and raised an AssertionError exception失败:如果任何测试用例失败并引发AssertionError异常
  3. Error: If any exception other than AssertionError exception is raised.错误:如果引发除AssertionError异常以外的任何异常。

There are several function under unittest module. They are listed below.

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)
方法 检查
assertEqual(a,b) a == b
assertNotEqual(a,b) a!= b
assertTrue(x) bool(x)是True
assertFalse(x) bool(x)为False
assertIs(a,b) a是b
assertIs(a,b) a是b
assertIsNot(a,b) a不是b
assertIsNone(x) x为无
assertIsNotNone(x) x不是None
assertIn(a,b) a in b
assertNotIn(a,b) a不在b中
assertIsInstance(a,b) isinstance(a,b)
assertNotIsInstance(a,b) 不是isinstance(a,b)

Python单元测试示例 (Python unit test example)

Now it’s time to write unit tests for our source class Person. In this class we have implemented two function – get_name() and set_name().

现在是时候为源类Person编写单元测试了。 在此类中,我们实现了两个函数– get_name()set_name()

Now, we will test those function using unittest. So we have designed two test cases for those two function. Have a look at the following code, you will understand it easily.

现在,我们将使用unittest测试这些功能。 因此,我们针对这两个功能设计了两个测试用例。 看看下面的代码,您将很容易理解。

import unittest# This is the class we want to test. So, we need to import it
import Person as PersonClassclass Test(unittest.TestCase):"""The basic class that inherits unittest.TestCase"""person = PersonClass.Person()  # instantiate the Person Classuser_id = []  # variable that stores obtained user_iduser_name = []  # variable that stores person name# test case function to check the Person.set_name functiondef 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 namename = 'name' + str(i)# store the name into the list variableself.user_name.append(name)# get the user id obtained from the functionuser_id = self.person.set_name(name)# check if the obtained user id is null or notself.assertIsNotNone(user_id)  # null user id will fail the test# store the user id to the listself.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 functiondef 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 informationprint("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 nameif i < length:# if the two name not matches it will fail the test caseself.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 messageself.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()

Note that the unittest module executes the test functions in the order of their name, not in the order they are defined. And since we want our set_name test to execute first, we have named our test case functions as test_0_set_name and test_1_get_name.

请注意,unittest模块按其名称的顺序而不是按其定义的顺序执行测试功能。 并且由于我们希望首先执行set_name测试,因此我们将测试用例函数命名为test_0_set_nametest_1_get_name

Python单元测试示例输出 (Python Unit Test Example Output)

Below images show the output produced by our unit test program – both in normal mode and in verbose mode.

下图显示了我们的单元测试程序在正常模式和详细模式下产生的输出。

$ python3.6 -m unittest -v PersonTest.Test
test_0_set_name (PersonTest.Test) ... Start set_name testuser_id length =  4
[0, 1, 2, 3]
user_name length =  4
['name0', 'name1', 'name2', 'name3']Finish set_name testok
test_1_get_name (PersonTest.Test) ...
Start get_name testuser_id length =  4
user_name length =  4
Testing for get_name no user test
Testing for get_name no user testFinish get_name testok----------------------------------------------------------------------
Ran 2 tests in 0.000sOK
$

That’s all about Python unittest tutorial. To learn more, read the Official Documentation. For any further query please use the comment box.

Python unittest –单元测试示例相关推荐

  1. python单元测试框架-Python unittest单元测试框架总结

    什么是单元测试 单元测试是用来对一个模块.一个函数或者一个类来进行正确性检验的测试工作. 比如对于函数abs(),我们可以编写的测试用例为: (1)输入正数,比如1.1.2.0.99,期待返回值与输入 ...

  2. python自动化测试-【自动化测试】Python - unittest单元测试框架

    一.测试模型 下面这部分来自于某书籍资料,拿过来,按需参考一下: 测试模型 (1)线性测试 1.概念: 通过录制或编写对应应用程序的操作步骤产生的线性脚本.单纯的来模拟用户完整的操作场景.(操作,重复 ...

  3. Python - unittest单元测试框架(全)

    一.简介 1.unittest的作用 unittest是Python内置的单元测试框架,主要用于单元测试,具备编写用例.组织用例.执行用例.输出报告等作用. 2.单元测试框架的优点 单元测试是通过一段 ...

  4. python装饰器执行顺序_python unittest单元测试框架-3用例执行顺序、多级目录、装饰器、fixtures...

    1.用例执行顺序 unittest默认会按照ascii码的顺序,依次执行.类名--方法名排序,使用discover也是默认排序.如果不想使用默认排序,就使用testsuite测试集的方式. impor ...

  5. python简单单元测试示范卷_Python 单元测试的简单示例

    这篇文章主要为大家详细介绍了Python 单元测试的简单示例,具有一定的参考价值,可以用来参考一下. 对python这个高级语言感兴趣的小伙伴,下面一起跟随512笔记的小编两巴掌来看看吧! 以前我是不 ...

  6. python 单元测试_聊聊 Python 的单元测试框架(一):unittest

    本文首发于 HelloGitHub 公众号,并发表于 Prodesire 博客. 前言 说到 Python 的单元测试框架,想必接触过 Python 的朋友脑袋里第一个想到的就是 unittest. ...

  7. python unittest断言_python unittest之断言及示例

    assert.png 前言 python unintest单元测试框架提供了一整套内置的断言方法. 如果断言失败,则抛出一个AssertionError,并标识该测试为失败状态 如果异常,则当做错误来 ...

  8. python split()方法_聊聊 Python 的单元测试框架(一):unittest

    本文首发于 HelloGitHub 公众号,并发表于 Prodesire 博客. 前言 说到 Python 的单元测试框架,想必接触过 Python 的朋友脑袋里第一个想到的就是 unittest. ...

  9. 聊聊 Python 的单元测试框架(一):unittest

    作者:HelloGitHub-Prodesire HelloGitHub 的<讲解开源项目>系列,项目地址:https://github.com/HelloGitHub-Team/Arti ...

最新文章

  1. 任铄 计算机操作系统,计算机组成与体系结构-CSDN.PDF
  2. 刚刚,CVPR 2021论文接收结果「开奖了」
  3. 八、日志分析系统Nginx,Beats,Kibana和Logstash
  4. 大工14春 计算机文化基础 在线测试,大工14春《计算机文化基础》在线测试I含答案.doc...
  5. (王道408考研数据结构)第八章排序-第三节2:堆与堆排序
  6. Mysql数据库设计规范之三数据库SQL开发规范
  7. sql主键_SQL主键
  8. 双击事件 转载 http://blog.sina.com.cn/s/blog_739365a30100vk8p.html
  9. oracle 客户端怎样配置,oracle 之客户端配置
  10. 网络编程项目 (网络词典)
  11. xp重启计算机的快捷键,xp电脑关机重启快捷键是什么
  12. 瞎琢磨先生のJava工具类
  13. 让智能家居照顾老年人的生活
  14. 纯C语言实战-打字游戏
  15. 使用python3完成英文词频统计
  16. 为发烧而生:个人电脑诞生记
  17. linux指令lpr,linux命令 test/lpr
  18. 福大 计算机网络教学平台,福州大学现代教育技术中心
  19. chrome字符串编码转换
  20. 在CANoe/CANalyzer中如何截取/分段CAN Log文件(自定义时间段)

热门文章

  1. [转载] 根据Python常见面试题来谈谈 Python 闭包
  2. 判断是否包含某个头文件
  3. ByteToByte64String、Base64StringToBytes
  4. 固定日期时间倒计时,倒计时不可点击,普通倒计时
  5. 微软Power BI 每月功能更新系列——3月Power BI 新功能学习
  6. AndroidStudio 内存泄漏分析 Memory Monitor
  7. RPM方式安装MySQL5.5.48 (Aliyun CentOS 7.0 卸载MySQL5.7)
  8. [转]Time Tracker Starter Kit 简介
  9. Pytorch(0)降低学习率torch.optim.lr_scheduler.ReduceLROnPlateau类
  10. 数据结构上机实践第八周项目9-广义表算法库及应用