干货 | 利用 pytest 玩转数据驱动测试框架

简介: ## pytest架构是什么?首先,来看一个 pytest 的例子:```def test_a(): print(123)``````collected 1 itemtest_a.py .
更多技术文章分享和免费资料领取
https://qrcode.ceba.ceshiren.com/link?name=article&project_id=qrcode&from=Aliyun&timestamp=1650008721

pytest架构是什么?

首先,来看一个 pytest 的例子:

def test_a():

  print(123)
collected 1 item

test_a.py .                                                                                                            [100%]

============ 1 passed in 0.02s =======================

输出结果很简单:收集到 1 个用例,并且这条测试用例执行通过。
此时思考两个问题:
1.pytest 如何收集到用例的?
2.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 像是包装盒,将 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>

这里科普一下,python 的 package 和 module 都是真实存在的对象,你可以从 obj 属性中看到,比如 Module 的 obj 属性如下:

如果理解了 pytest 的包裹用途,非常好!我们进行下一步讨论:如何构造 pytest 的 item ?

以下面代码为例:

def test_a:

    print(123)

构造 pytest 的 item ,需要:
3.构建 Package
4.构建 Module
5.构建 Function
以构建 Function 为例,需要调用其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 就是模拟 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

这就涉及元编程技术:动态构建 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”。
可以利用 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 ==

⬇️ 点击“阅读原文”,提升测试核心竞争力!
原文链接

⬇️ 点击“下方链接”,提升测试核心竞争力!

更多技术文章分享和免费资料领取
https://qrcode.ceba.ceshiren.com/link?name=article&project_id=qrcode&from=Aliyun&timestamp=1650008721
相关文章
|
1天前
|
测试技术 数据库
深入理解软件测试中的自动化框架选择
【5月更文挑战第18天】 在快速发展的软件行业中,自动化测试已成为提升测试效率、保障产品质量的重要手段。选择合适的自动化测试框架对于实现高效、可靠的测试过程至关重要。本文将探讨不同的自动化测试框架特点,分析其适用场景,并讨论如何基于项目需求和团队技能进行最佳选择。
|
2天前
|
XML 敏捷开发 测试技术
深入理解自动化测试框架的设计原则
【5月更文挑战第17天】 在软件开发的复杂多变的环境中,自动化测试已成为确保产品质量和加快上市速度的关键因素。本文旨在探讨自动化测试框架的设计原则,包括其结构、可扩展性、复用性和易维护性。通过分析当前流行的自动化测试框架的特点,结合实例说明如何构建一个高效、可靠的自动化测试系统。文章将重点讨论模块化设计、数据驱动测试、关键字驱动测试以及行为驱动开发(BDD)等关键概念,并提供具体的实施策略和最佳实践,以帮助读者构建或优化现有的自动化测试框架。
|
3天前
|
敏捷开发 测试技术 持续交付
深入理解自动化测试框架:以Selenium为例
【5月更文挑战第16天】 随着软件行业的迅猛发展,质量保障变得愈加重要。自动化测试作为确保软件质量的重要环节,其效率和可靠性受到了广泛关注。本文旨在深入探讨自动化测试框架的构建与优化,特别是以Selenium框架为例,分析其在实际应用中的优势、常见问题以及解决方案。通过具体案例分析,揭示如何提高自动化测试的稳定性和灵活性,从而更好地服务于敏捷开发和持续集成流程。
19 5
|
4天前
|
监控 数据挖掘 定位技术
Spartacus 测试,后台修改 product price 数据后,添加到 Cart 时,会带出来最新的价格吗
Spartacus 测试,后台修改 product price 数据后,添加到 Cart 时,会带出来最新的价格吗
16 2
|
4天前
|
设计模式 敏捷开发 监控
深入理解自动化测试框架的设计原则与实践
【5月更文挑战第15天】在软件工程的领域里,自动化测试已成为提高软件开发效率、保障产品质量的重要手段。本文将深入探讨自动化测试框架的设计原则及其在实际项目中的应用实践。通过分析设计模式、模块化、可扩展性等关键因素,揭示构建高效、可靠自动化测试框架的策略和方法。同时,结合实际案例,展示如何在多变的测试需求中保持测试框架的稳定性和灵活性。
|
4天前
|
测试技术 iOS开发
pytest Mark标记测试用例
使用`pytest.mark`进行测试用例分组和筛选,如`@pytest.mark.webtest`。通过`pytest -m`参数执行特定标记的用例,例如`pytest -s test_command_param.py -m webtest`。同时,pytest支持内置的skip、skipif和xfail功能来管理特殊用例:skip始终跳过,skipif条件满足时跳过,xfail则标记预期失败的测试。
5 0
|
4天前
|
jenkins 测试技术 持续交付
Pytest测试框架
Pytest是一个功能强大的测试框架,支持单元测试和复杂功能测试,可结合Requests和Selenium等进行接口和自动化测试。它拥有超过315个插件,兼容unittest,并能与Allure、Jenkins集成实现持续集成。安装可通过pip或Pycharm。Pytest遵循特定命名规则,测试用例由名称、步骤和断言组成。断言用于验证预期结果,当失败时程序会终止。Pytest提供setup/teardown机制来管理测试前后的资源。
16 3
|
4天前
|
网络协议 安全 测试技术
性能工具之emqtt-bench BenchMark 测试示例
【4月更文挑战第19天】在前面两篇文章中介绍了emqtt-bench工具和MQTT的入门压测,本文示例 emqtt_bench 对 MQTT Broker 做 Beachmark 测试,让大家对 MQTT消息中间 BenchMark 测试有个整体了解,方便平常在压测工作查阅。
133 7
性能工具之emqtt-bench BenchMark 测试示例
|
4天前
|
机器学习/深度学习 数据采集 人工智能
【专栏】AI在软件测试中的应用,如自动执行测试用例、识别缺陷和优化测试设计
【4月更文挑战第27天】本文探讨了AI在软件测试中的应用,如自动执行测试用例、识别缺陷和优化测试设计。AI辅助工具利用机器学习、自然语言处理和图像识别提高效率,但面临数据质量、模型解释性、维护更新及安全性挑战。未来,AI将更注重用户体验,提升透明度,并在保护隐私的同时,通过联邦学习等技术共享知识。AI在软件测试领域的前景广阔,但需解决现有挑战。
|
4天前
|
测试技术
如何管理测试用例?测试用例有什么管理工具?YesDev
该文档介绍了测试用例和测试用例库的管理。测试用例是描述软件测试方案的详细步骤,包括测试目标、环境、输入、步骤和预期结果。测试用例库用于组织和管理这些用例,强调简洁性、完整性和可维护性。管理者可以创建、删除、重命名用例库,搜索和管理用例,以及通过层级目录结构来组织用例。此外,还支持通过Excel导入和导出测试用例,以及使用脑图查看用例关系。后台管理允许配置全局别名,如用例状态、优先级和执行结果。

热门文章

最新文章