unittest模块:单元测试
由于pytest是基于unittest的,它也能支持对使用unittest编写的测试用例的测试。举个例子,测试用例文件test_func1.py
,test_func2.py
都放在tests/
目录下,那么只要执行pytest tests/
就会自动寻找该目录下的test_*.py
和*_test.py
命名的文件,检查其中的unittest.TestCase
的子类并运行它们的test_*
函数,它支持unittest.skip
等特性,参考链接
unittest浅析,通过元类实现按书写顺序执行单元测试函数
utx,一个基于unittest的功能很多的测试用代码库
metaclass的用法
为了实现按书写顺序执行单元测试函数,找了一些资料,最后实现了这个功能,代码如下:
import unittest
from unittest import TestLoader
from fnmatch import fnmatchcaseclass UnittestMetaclass(type):def __new__(cls, name, bases, attrs):# add 'attrs_by_writing_order' attribute containing writing order of all attributes and functionsattrs["attrs_by_writing_order"] = list(attrs.keys())return super().__new__(cls, name, bases, attrs)# TestLoader默认按照函数的字母序进行测试,有时候我们的函数是需要依次执行的,要安装书写的
# 顺序执行,因此这里重写TestLoader的sortTestMethodsUsing,不另做排序,即可按照书写顺序执行
# 但是打印错误日志的时候,是先打印Error再打印Fail,在二者都有的时候打印顺序还是会跟执行顺序
# 有所不同,但是没有关系,Error在前警示作用比较强,也挺好的,只要执行顺序能按照我们想要的来就可以了
class OrderedTestLoader(TestLoader):"""This TestLoader will load testFnNames in the code writing order"""# copied from getTestCaseNames() of TestLoader and make some modificationdef getTestCaseNames(self, testCaseClass):"""Return a sorted sequence of method names found within testCaseClass"""def shouldIncludeMethod(attrname):if not attrname.startswith(self.testMethodPrefix):return FalsetestFunc = getattr(testCaseClass, attrname)if not callable(testFunc):return FalsefullName = f'%s.%s.%s' % (testCaseClass.__module__, testCaseClass.__qualname__, attrname)return self.testNamePatterns is None or \any(fnmatchcase(fullName, pattern) for pattern in self.testNamePatterns)testFnNames = list(filter(shouldIncludeMethod, testCaseClass.attrs_by_writing_order))return testFnNames# 声明一个类,从unittest.TestCase类派生,默认情况下每一个以test开头的成员函数都会被当作单元测试函数
# NOTE: 每个测试函数的名字必须以test开头,否则将不会被自动执行(不想参与测试的函数请不要以test开头命名)
class TestDemo(unittest.TestCase, metaclass=UnittestMetaclass):r"""Author: zhang.haojian本测试类的测试结果为".FF..E.","."表示测试通过,"F"表示不通过,"E"表示在执行测试函数时发生了并非由assert*系列函数引发的异常测试结果的输出顺序是按函数名的字母序,与代码中的函数声明顺序不一定一致形如FAIL: 测试函数名 (测试类名) 的是一个测试函数不通过时的提示行,下接断言异常信息,请核对代码并修改至测试通过之后再提交如果所有样例都通过,最后会输出"OK",否则会输出FAILED (failures=2, errors=1)的字眼,告诉用户有几个样例failure了,有几个样例error了"""def setUp(self):# 在运行每一个测试方法前都会先执行setUp函数,若setUp()方法引发异常,测试方法将不会被运行passdef tearDown(self):# 若setUp()成功运行,无论测试方法是否成功,都会运行tearDown(),这里可以放一些后处理的代码passdef test_equal(self):s = "this is a demo function"# assertEqual determine whether two objects are equalself.assertEqual(s, "this is a demo function")def test_equal2(self):s = "this is another demo function"self.assertEqual(s, "this is a demo function")def test_in(self):l = ["a", "b"]# assertIn determine whether the member is in containerself.assertIn("c", l)def test_isinstance(self):s = "I am a string"# assertIsInstance determine whether the variable is instance of a certain type self.assertIsInstance(s, str)def test_bool(self):d = {"a": "ABC"}# assertTrue determine whether the condition is Trueself.assertTrue(d["a"].isupper())def test_error(self):# raise an errorraise RuntimeError("a RuntimeError")def test_assert_raise(self):def change_tuple(t):t[0] = 1d = (1, 2)# assertRaises catch an expected error with known typeself.assertRaises(TypeError, change_tuple, d)# assertRaisesRegex catch an expected error with known type and messageself.assertRaisesRegex(TypeError, "'tuple' object does not support item assignment", change_tuple, d)# they can be used in context environmentwith self.assertRaisesRegex(TypeError, "'tuple' object does not support item assignment") as cm:d[0] = 1if __name__ == "__main__":# `unittest.main()` is the standard usage to start testing, here we use a customed# TestLoader to keep executing order of functions the same as their writing orderunittest.main(testLoader=OrderedTestLoader())
unittest模块:单元测试相关推荐
- [转载] python面面观单元测试_python 使用unittest进行单元测试
参考链接: 使用Unittest在Python中进行单元测试 importunittestimportHTMLTestRunner"""Python中有一个自带的单元测试 ...
- Python+Selenium 自动化测试 6. Unittest模块学习
unittest单元测试框架不仅可以适用于单元测试,还可以适用WEB自动化测试用例的开发与执行,该测试框架可组织执行测试用例,并且提供了丰富的断言方法,判断测试用例是否通过,最终生成测试结果. 源码例 ...
- 自动化测试——unittest框架(单元测试)
目录 一.unittest框架解析 1.1unittest的5个重要概念 1.1测试用例的编写及代码 1.2断言 1.3用例的执行顺序 1.4测试用例综合管理框架 1.5HTML报告生成 参考博文 一 ...
- boost的chrono模块单元测试的测试程序
boost的chrono模块单元测试的测试程序 实现功能 C++实现代码 实现功能 boost的chrono模块单元测试的测试程序 C++实现代码 #define _CRT_SECURE_NO_WAR ...
- 第二章 使用unittest模块扩展功能测试
2.1使用功能测试驱动开放一个最简单的应用 # functional_tests.py # -*- coding: utf-8 -*- from selenium import webdriverbr ...
- Python unittest 模块
一.Unittest 的几个基本概念 TestCase :要写的具体的测试用例 TestSuite: 多个测试用例集合(或测试套件/测试集) TestLoader:用来加载 TestCase 到 Te ...
- 什么是单元测试(UnitTest),单元测试的作用是什么
单元测试(unit testing),是指对软件中的最小可测试单元进行检查和验证.对于单元测试中单元的含义,一般来说,要根据实际情况去判定其具体含义,如C语言中单元指一个函数,Java里单元指一个类, ...
- python unit test 访问开发代码,使用Python的unittest模块作为testrunner时,如何在测试前运行初始化代码?...
How can a user of a library run his own initialization code (setting debug levels of loggers for exa ...
- 好全面的python笔记,那我就笑纳了
注:本笔记基于python2.6而编辑,尽量的偏向3.x的语法 Python的特色 1.简单 2.易学 3.免费.开源 4.高层语言: 封装内存管理等 5.可移植性: 程序如果避免使用依赖于系统的特性 ...
- python 的内置模块
常见的Python内置模块: sys模块:系统文件模块: time模块:包含各种提供日期.时间功能的类和函数: datetime模块:时间处理模块: random模块: 随机 : OS模块: 系统操作 ...
最新文章
- javascript深入理解js闭包
- Python argparse模块基本用法
- LiveVideoStackCon 2019北京 Day One精彩瞬间
- 线程与消息循环的关系
- Jetty 9.1上的Java WebSockets(JSR-356)
- MySQL ALTER TABLE报错Duplicate entry 'xxx' for key 'PRIMARY'解决方法
- hdu 1625(floyd判环)
- 【Flink】HttpClient 报错 I/O SocketException caught when processing request to Connection Reset
- JS实现数字千位符格式化方法
- IT草根的江湖之路之七: 挑战,刚刚开始
- plc编程有哪些方法?
- 如何搭建监狱高清1080P OTT/IPTV电视系统
- Visual studio2012密钥 vs2012密钥 本人亲测 真实有效
- Win7梦幻桌面字体有问题怎么办
- 第十一章:项目风险管理 - (11.1 规划风险管理)
- 【无人机】【2017.10】无人机(UAV)在地学野外工作中建立增强型虚拟野外指南(EVFG)的作用研究
- dev c++缺省源
- win10安装vs2015出现“安装包丢失或损坏”解决办法
- 大地坐标系转换地心坐标系
- 剪辑过的视频md5会改变