软件测试/测试开发丨利用 pytest 玩转数据驱动测试框架
ccwgpt 2024-11-02 11:03 23 浏览 0 评论
公众号搜索:TestingStudio 霍格沃兹测试开发的干货都很硬核
pytest架构是什么?
首先,来看一个 pytest 的例子:
def test_a():
print(123)
collected 1 item
test_a.py . [100%]
============ 1 passed in 0.02s =======================
输出结果很简单:收集到 1 个用例,并且这条测试用例执行通过。
此时思考两个问题:
- pytest 如何收集到用例的?
- pytest 如何把 python 代码,转换成 pytest 测试用例(又称 item) ?
pytest如何做到收集到用例的?
这个很简单,遍历执行目录,如果发现目录的模块中存在符合“ pytest 测试用例要求的 python 对象”,就将之转换为 pytest 测试用例。
比如编写以下 hook 函数:
def pytest_collect_file(path, parent):
print("hello", path)
hello C:\Users\yuruo\Desktop\tmp\tmp123\tmp\testcase__init__.py
hello C:\Users\yuruo\Desktop\tmp\tmp123\tmp\testcase\conftest.py
hello C:\Users\yuruo\Desktop\tmp\tmp123\tmp\testcase\test_a.py
会看到所有文件内容。
如何构造pytest的item?
pytest 像是包装盒,将 python 对象包裹起来,比如下图:
当写好 python 代码时:
def test_a:
print(123)
会被包裹成 Function :
<Function test_a>
可以从 hook 函数中查看细节:
def pytest_collection_modifyitems(session, config, items):
pass
于是,理解包裹过程就是解开迷题的关键。pytest 是如何包裹 python 对象的?
下面代码只有两行,看似简单,但暗藏玄机!
def test_a:
print(123)
把代码位置截个图,如下:
我们可以说,上述代码是处于“testcase包”下的 “test_a.py模块”的“test_a函数”, pytest 生成的测试用例也要有这些信息:
处于“testcase包”下的 “test_a.py模块”的“test_a测试用例:
把上述表达转换成下图:
pytest 使用 parent 属性表示上图层级关系,比如 Module 是 Function 的上级, Function 的 parent 属性如下:
<Function test_a>:
parent: <Module test_parse.py>
当然 Module 的 parent 就是 Package:
<Module test_parse.py>:
parent: <Package tests>
注意大小写:Module 是 pytest 的类,用于包裹 python 的 module 。Module 和 module 表示不同意义。
这里科普一下,python 的 package 和 module 都是真实存在的对象,你可以从 obj 属性中看到,比如 Module 的 obj 属性如下:
如果理解了 pytest 的包裹用途,非常好!我们进行下一步讨论:如何构造 pytest 的 item ?
以下面代码为例:
def test_a:
print(123)
构造 pytest 的 item ,需要:
- 构建 Package
- 构建 Module
- 构建 Function
以构建 Function 为例,需要调用其from_parent()方法进行构建,其过程如下图:
从函数名from_parent,就可以猜测出,“构建 Function”一定与其 parent 有不小联系!又因为 Function 的 parent 是 Module :
根据下面 Function 的部分代码(位于 python.py 文件):
class Function(PyobjMixin, nodes.Item):
# 用于创建测试用例
@classmethod
def from_parent(cls, parent, **kw):
"""The public constructor."""
return super().from_parent(parent=parent, **kw)
# 获取实例
def _getobj(self):
assert self.parent is not None
return getattr(self.parent.obj, self.originalname) # type: ignore[attr-defined]
# 运行测试用例
def runtest(self) -> None:
"""Execute the underlying test function."""
self.ihook.pytest_pyfunc_call(pyfuncitem=self)
得出结论,可以利用 Module 构建 Function!其调用伪代码如下:
Function.from_parent(Module)
既然可以利用 Module 构建 Function, 那如何构建 Module ?
当然是利用 Package 构建 Module!
Module.from_parent(Package)
既然可以利用 Package 构建 Module 那如何构建 Package ?
别问了,快成套娃了,请看下图调用关系:
pytest 从 Config 开始,层层构建,直到 Function !Function 是 pytest 的最小执行单元。
如何手动构建item?
手动构建 item 就是模拟 pytest 构建 Function 的过程。也就是说,需要创建 Config ,然后利用 Config 创建 Session ,然后利用 Session 创建 Package ,…,最后创建 Function。
其实没这么复杂, pytest 会自动创建好 Config, Session和 Package ,这三者不用手动创建。
比如编写以下 hook 代码,打断点查看其 parent 参数:
def pytest_collect_file(path, parent):
pass
如果遍历的路径是某个包(可从path参数中查看具体路径),比如下图的包:
其 parent 参数就是 Package ,此时可以利用这个 Package 创建 Module :
编写如下代码即可构建 pytest 的 Module ,如果发现是 yaml 文件,就根据 yaml 文件内容动态创建 Module 和 module :
from _pytest.python import Module, Package
def pytest_collect_file(path, parent):
if path.ext == ".yaml":
pytest_module = Module.from_parent(parent, fspath=path)
# 返回自已定义的 python module
pytest_module._getobj = lambda : MyModule
return pytest_module
需要注意,上面代码利用猴子补丁改写了 _getobj 方法,为什么这么做?
Module 利用 _getobj 方法寻找并导入(import语句) path 包下的 module ,其源码如下:
# _pytest/python.py Module
class Module(nodes.File, PyCollector):
def _getobj(self):
return self._importtestmodule()
def _importtestmodule(self):
# We assume we are only called once per module.
importmode = self.config.getoption("--import-mode")
try:
# 关键代码:从路径导入 module
mod = import_path(self.fspath, mode=importmode)
except SyntaxError as e:
raise self.CollectError(
ExceptionInfo.from_current().getrepr(style="short")
) from e
# 省略部分代码...
但是,如果使用数据驱动,即用户创建的数据文件 test_parse.yaml ,它不是 .py 文件,不会被 python 识别成 module (只有 .py 文件才能被识别成 module)。
这时,就不能让 pytest 导入(import语句) test_parse.yaml ,需要动态改写 _getobj ,返回自定义的 module !
因此,可以借助 lambda 表达式返回自定义的 module :
lambda : MyModule
如何自定义module
这就涉及元编程技术:动态构建 python 的 module ,并向 module 中动态加入类或者函数:
import types
# 动态创建 module
module = types.ModuleType(name)
def function_template(*args, **kwargs):
print(123)
# 向 module 中加入函数
setattr(module, "test_abc", function_template)
综上,将自己定义的 module 放入 pytest 的 Module 中即可生成 item :
# conftest.py
import types
from _pytest.python import Module
def pytest_collect_file(path, parent):
if path.ext == ".yaml":
pytest_module = Module.from_parent(parent, fspath=path)
# 动态创建 module
module = types.ModuleType(path.purebasename)
def function_template(*args, **kwargs):
print(123)
# 向 module 中加入函数
setattr(module, "test_abc", function_template)
pytest_module._getobj = lambda: module
return pytest_module
创建一个 yaml 文件,使用 pytest 运行:
======= test session starts ====
platform win32 -- Python 3.8.1, pytest-6.2.4, py-1.10.0, pluggy-0.13.1
rootdir: C:\Users\yuruo\Desktop\tmp
plugins: allure-pytest-2.8.11, forked-1.3.0, rerunfailures-9.1.1, timeout-1.4.2, xdist-2.2.1
collected 1 item
test_a.yaml 123
.
======= 1 passed in 0.02s =====
PS C:\Users\yuruo\Desktop\tmp>
现在停下来,回顾一下,我们做了什么?
借用 pytest hook ,将 .yaml 文件转换成 python module。
作为一个数据驱动测试框架,我们没做什么?
没有解析 yaml 文件内容!上述生成的 module ,其内的函数如下:
def function_template(*args, **kwargs):
print(123)
只是简单打印 123 。数据驱动测试框架需要解析 yaml 内容,根据内容动态生成函数或类。比如下面 yaml 内容:
test_abc:
- print: 123
表达的含义是“定义函数 test_abc,该函数打印 123”。
注意:关键字含义应该由你决定,这里仅给一个 demo 演示!
可以利用 yaml.safe_load 加载 yaml 内容,并进行关键字解析,其中path.strpath代表 yaml 文件的地址:
import types
import yaml
from _pytest.python import Module
def pytest_collect_file(path, parent):
if path.ext == ".yaml":
pytest_module = Module.from_parent(parent, fspath=path)
# 动态创建 module
module = types.ModuleType(path.purebasename)
# 解析 yaml 内容
with open(path.strpath) as f:
yam_content = yaml.safe_load(f)
for function_name, steps in yam_content.items():
def function_template(*args, **kwargs):
"""
函数模块
"""
# 遍历多个测试步骤 [print: 123, print: 456]
for step_dic in steps:
# 解析一个测试步骤 print: 123
for step_key, step_value in step_dic.items():
if step_key == "print":
print(step_value)
# 向 module 中加入函数
setattr(module, function_name, function_template)
pytest_module._getobj = lambda: module
return pytest_module
上述测试用例运行结果如下:
=== test session starts ===
platform win32 -- Python 3.8.1, pytest-6.2.4, py-1.10.0, pluggy-0.13.1
rootdir: C:\Users\yuruo\Desktop\tmp
plugins: allure-pytest-2.8.11, forked-1.3.0, rerunfailures-9.1.1, timeout-1.4.2, xdist-2.2.1
collected 1 item
test_a.yaml 123
.
=== 1 passed in 0.02s ====
当然,也支持复杂一些的测试用例:
test_abc:
- print: 123
- print: 456
test_abd:
- print: 123
- print: 456
其结果如下:
== test session starts ==
platform win32 -- Python 3.8.1, pytest-6.2.4, py-1.10.0, pluggy-0.13.1
rootdir: C:\Users\yuruo\Desktop\tmp
plugins: allure-pytest-2.8.11, forked-1.3.0, rerunfailures-9.1.1, timeout-1.4.2, xdist-2.2.1
collected 2 items
test_a.yaml 123
456
.123
456
.
== 2 passed in 0.02s ==
利用pytest创建数据驱动测试框架就介绍到这里啦,希望能给大家带来一定的帮助。大家有什么不懂的地方或者有疑惑也可以留言讨论哈,让我们共同进步呦!
相关推荐
- MFC、Qt、WPF?该用哪个?(mfc和wpf区别)
-
MFC、Qt和WPF都是流行的框架和工具,用于开发图形用户界面(GUI)应用程序。选择哪个框架取决于你的具体需求和偏好。MFC(MicrosoftFoundationClass)是微软提供的框架,...
- 一款WPF开发的通讯调试神器(支持Modbus RTU、MQTT调试)
-
我们致力于探索、分享和推荐最新的实用技术栈、开源项目、框架和实用工具。每天都有新鲜的开源资讯等待你的发现!项目介绍Wu.CommTool是一个基于C#、WPF、Prism、MaterialDesign...
- 关于面试资深C#、WPF开发工程师的面试流程和问题
-
一、开场(2-3分钟)1.欢迎应聘者,简单介绍公司和面试流程。2.询问应聘者是否对公司或岗位有初步的问题。二、项目经验与技术应用(10-20分钟)1.让应聘者详细介绍几个他参与过的C#、...
- C# WPF MVVM模式Prism框架下事件发布与订阅
-
01—前言处理同模块不同窗体之间的通信和不同模块之间不同窗体的通信,Prism提供了一种事件机制,可以在应用程序中低耦合的模块之间进行通信,该机制基于事件聚合器服务,允许发布者和订阅者之间通过事件进行...
- WPF 机械类组件动画制作流程简述(wps上怎么画机械结构简图)
-
WPF机械类组件动画制作流程简述独立观察员2025年3月4日一、创建组件创建组件用户控件,将组件的各部分“零件”(图片)拼装在一起,形成组件的默认状态:二、给运动部分加上Rend...
- C#上位机WinForm和WPF选哪个?工控老油条的"血泪史"
-
作为一个从互联网卷进工控坑的"跨界难民",在这会摸鱼的时间咱就扯一下上位机开发选框架这档子破事。当年我抱着WPF的酷炫动画一头扎进车间,结果被产线老师傅一句"你这花里胡哨的玩意...
- 【一文扫盲】WPF、Winform、Electron有什么区别?
-
近年来,随着软件开发的不断发展,开发人员面临着选择适合他们项目的各种框架和工具的挑战。在桌面应用程序开发领域,WPF、Winform和Electron是三个备受关注的技术。本文将介绍这三者的区别,帮助...
- 一个开源、免费、强大且美观的WPF控件库
-
我们致力于探索、分享和推荐最新的实用技术栈、开源项目、框架和实用工具。每天都有新鲜的开源资讯等待你的发现!项目介绍HandyControl是一套基于WPF(WindowsPresentationF...
- WPF 根据系统主题自动切换浅色与深色模式
-
WPF根据系统主题自动切换浅色与深色模式控件名:Resources作者:WPFDevelopersOrg-驚鏵原文链接[1]:https://github.com/WPFDevelopers...
- WPF与WinForm的本质区别(wpf与maui)
-
在Windows应用程序开发中,WinForm和WPF是两种主要的技术框架。它们各自有不同的设计理念、渲染机制和开发模式。本文将详细探讨WPF与WinForm的本质区别,并通过示例进行说明。渲染机制W...
- Win10/Win11效率神器再进化:微软发布PowerToys 0.90.0版本
-
IT之家4月1日消息,微软今天(4月1日)更新PowerToys,在最新发布的0.90.0版本中,修复多个BUG之外,引入多项功能更新,为Windows10、Windows...
- 一款非常漂亮的WPF管理系统(wpf架构及特性)
-
我们致力于探索、分享和推荐最新的实用技术栈、开源项目、框架和实用工具。每天都有新鲜的开源资讯等待你的发现!WPFManager项目介绍该项目是一款WPF开发的管理系统,数据库采用的MSSqlserv...
- WPF 实现描点导航(wpf按钮的点击事件)
-
WPF实现描点导航控件名:NavScrollPanel作者:WPFDevelopersOrg-驚鏵原文链接[1]:https://github.com/WPFDevelopersOrg/WPF...
- 微软更新基于Win11的Validation OS 2504:增强 .NET与WPF
-
IT之家5月1日消息,科技媒体NeoWin今天(5月1日)发布博文,报道称微软公司更新基于Windows11的ValidationOS,增强支持.NET和WPF,并优...
- WPF的技术架构与优势(wpf的前景)
-
WindowsPresentationFoundation(WPF)是一个现代化的用户界面框架,专为构建Windows应用程序而设计。它通过分层的技术架构和丰富的功能集,提供了全面的应用程...
你 发表评论:
欢迎- 一周热门
- 最近发表
- 标签列表
-
- MVC框架 (46)
- spring框架 (46)
- 框架图 (58)
- bootstrap框架 (43)
- flask框架 (53)
- quartz框架 (51)
- abp框架 (47)
- jpa框架 (47)
- laravel框架 (46)
- express框架 (43)
- springmvc框架 (49)
- 分布式事务框架 (65)
- scrapy框架 (52)
- java框架spring (43)
- grpc框架 (55)
- orm框架有哪些 (43)
- ppt框架 (48)
- 内联框架 (52)
- winform框架 (46)
- gui框架 (44)
- cad怎么画框架 (58)
- ps怎么画框架 (47)
- ssm框架实现登录注册 (49)
- oracle字符串长度 (48)
- oracle提交事务 (47)