解锁 pytest_configure(config) 的神奇功能:个性化定制你的测试框架

前言

深入理解 pytest-repeat 插件的工作原理这篇文章中,我们看到pytest_repeat源码中有这样一段

def pytest_configure(config):
    config.addinivalue_line(
        'markers',
        'repeat(n): run the given test function `n` times.')
    ...

其实这里的pytest_configure也是一个钩子函数,那这个钩子函数有啥用?如何用?内部运行机制又是怎么样呢?带着这些疑问,我们一起来探索。

pytest_configure(config)是啥?

pytest_configure(config)pytest 中的一个钩子函数,它在pytest 运行前被调用一次,主要用于在测试运行之前进行配置和初始化工作。

我们看看源码中的定义:

@hookspec(historic=True)
def pytest_configure(config: "Config") -> None:
    """Allow plugins and conftest files to perform initial configuration.
​
    This hook is called for every plugin and initial conftest file
    after command line options have been parsed.
​
    After that, the hook is called for other conftest files as they are
    imported.
​
    .. note::
        This hook is incompatible with ``hookwrapper=True``.
​
    :param pytest.Config config: The pytest config object.
    """

pytest 配置文件或测试文件中定义 pytest_configure 函数,pytest 会自动调用它来处理一些常规的初始化、配置和插件注册工作。在 pytest 运行过程中,pytest_configure 函数可以通过config对象来访问 pytest 的各种配置信息和操作方法。

pytest_configure(config)如何使用?

定义全局变量或常量

我们配合conftest.py一起使用。在该模块中,我们可以定义一个pytest_configure(config)` 函数,并在其中定义一些全局变量或常量。我们看示例:

def pytest_configure(config):
    config.my_var = "hello world"

可以看

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值