Pytest执行unittest TestSuite(测试套件)的实现方法
作者:韩志超 时间:2023-12-23 06:05:14
前言
TestSuite一直是unittest的灵活与精髓之处,在繁多的测试用例中,可以任意挑选和组合各种用例集,比如smoke用例集、
level1用例集、
webtest用例集、
bug回归用例集
等等,当然这些TestSuite需要我们提前定义好,并把用例加载进去。Pytest采取的是完全不同的用例组织和运行方式。用例的运行主要基于名称匹配;组织则基于用例目录,用例命名格式及用例mark标签, 这种方式省去了麻烦的提前定义TestSuite及加载用例的过程,执行时通过路径/用例名格式/不同的标签组合来动态匹配出要执行的用例,使用更加灵活。然而,从原有的unittest框架转向pytest怀抱时仍不得不面临这样一个问题:我原先定义好的TestSuite怎么执行?
实现方法
主要思路:
①迭代遍历TestSuite中的所有case得到每个case的路径test_demo.TestDemo.test_a
②将case路径转化为Pytest支持的运行格式test_demo.py::TestDemo::test_a并组成一个case名称列表供Pytest调用。
示例用例: test_demo.py:
import unittest
class TestDemo(unittest.TestCase):
def test_a(self):
print("a")
def test_b(self):
print("b")
示例测试套件:demo.py:
import unittest
import pytest
from test_demo import TestDemo
suite = unittest.TestSuite()
suite.addTests([TestDemo('test_a'), TestDemo('test_b')])
# 因为suite中可能会存在嵌套, 所以我们要迭代取出其中所有的用例:
def collect(suite):
cases = [] # 用于存放Pytest支持的用例路径字符串
def _collect(tests): # 递归,如果下级元素还是TestSuite则继续往下找
if isinstance(tests, unittest.TestSuite):
[_collect(i) for i in tests if tests.countTestCases() != 0]
else:
_path = tests.id().split(".") # case.id()可以获取用例路径(字符串)
_path[0] += ".py"
cases.append("::".join(_path)) # 如果下级元素是TestCase,则添加到TestSuite中
_collect(suite)
return cases
if __name__ == '__main__':
cases = collect(suite)
pytest.main([*cases, "-v"])
# pytest.main(cases) # 不加额外参数的化可直接执行cases
来源:https://www.jianshu.com/p/6a05ccd3ca94
标签:Pytest,unittest,TestSuite,测试套件
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python3.3使用tkinter开发猜数字游戏示例
2023-09-05 06:53:02
深入浅析Python代码规范性检测
2023-08-23 21:16:55
![](https://img.aspxhome.com/file/2023/7/62617_0s.png)
python类中super() 的使用解析
2022-12-02 09:08:10
SQL server高级应用 收藏版
2012-10-07 11:04:06
Oracle 存储过程总结 二、字符串处理相关函数
2009-07-07 10:28:00
pandas 数据结构之Series的使用方法
2022-08-13 15:56:39
IIS上设置301跳转,实现ASP带参数跳转
2011-04-08 12:52:00
微信小程序前端如何调用python后端的模型详解
2023-03-12 06:29:13
![](https://img.aspxhome.com/file/2023/0/131060_0s.png)
Python中设置变量访问权限的方法
2023-09-13 15:42:15
asp检测文件编码方法
2007-10-03 14:27:00
pandas创建DataFrame的方式小结
2021-10-25 13:26:23
![](https://img.aspxhome.com/file/2023/2/86632_0s.png)
Golang import本地包和导入问题相关详解
2024-01-30 09:35:37
![](https://img.aspxhome.com/file/2023/2/103722_0s.png)
keras模型保存为tensorflow的二进制模型方式
2022-12-21 07:20:08
Python使用random和tertools模块解一些经典概率问题
2023-03-08 13:11:37
Python HTML解析器BeautifulSoup用法实例详解【爬虫解析器】
2023-05-21 01:32:42
ASP 验证码的程序及原理
2010-04-24 15:56:00
jquery的$(document).ready()和onload的加载顺序
2023-08-23 18:57:40
用python实现一幅春联实例代码
2021-07-23 09:25:41
![](https://img.aspxhome.com/file/2023/1/133371_0s.jpg)
vue-seamless-scroll无缝滚动组件使用方法详解
2024-04-29 13:07:51
![](https://img.aspxhome.com/file/2023/2/132982_0s.gif)
tensorflow实现将ckpt转pb文件的方法
2023-03-24 19:05:05