前言
在深入理解 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"
可以看