编写插件¶
为你的项目实现本地 conftest 插件或可在多个项目(包括第三方项目)中使用的pip-可安装插件都非常容易。如果你只想使用但不想编写插件,请参阅如何安装和使用插件。
插件包含一个或多个钩子函数。编写钩子解释了如何自己编写钩子函数的基本原理和细节。pytest
通过调用以下插件的良好定义的钩子来实现配置、收集、运行和报告的所有方面:
内置插件:从 pytest 内部的
_pytest
目录加载。conftest.py 插件:在测试目录中自动发现的模块。
原则上,每个钩子调用都是一个 1:N
的 Python 函数调用,其中 N
是给定规范的注册实现函数的数量。所有规范和实现都遵循 pytest_
前缀命名约定,这使得它们易于区分和查找。
工具启动时的插件发现顺序¶
pytest
在工具启动时按以下方式加载插件模块:
通过扫描命令行中的
-p no:name
选项来阻止该插件加载(即使内置插件也可以通过此方式阻止)。这发生在正常命令行解析之前。加载所有内置插件。
通过扫描命令行中的
-p name
选项并加载指定的插件。这发生在正常命令行解析之前。加载所有通过已安装第三方包入口点注册的插件,除非设置了
PYTEST_DISABLE_PLUGIN_AUTOLOAD
环境变量。加载所有通过
PYTEST_PLUGINS
环境变量指定的插件。加载所有“初始”
conftest.py
文件确定测试路径:如果命令行中指定,则使用命令行指定的路径;否则,如果定义了
testpaths
且从根目录运行,则使用testpaths
;否则,使用当前目录。对于每个测试路径,加载相对于测试路径目录部分的
conftest.py
和test*/conftest.py
(如果存在)。在加载conftest.py
文件之前,加载其所有父目录中的conftest.py
文件。加载conftest.py
文件后,如果存在,则递归加载其中pytest_plugins
变量中指定的所有插件。
conftest.py: 本地按目录划分的插件¶
本地 conftest.py
插件包含目录特定的钩子实现。钩子会话和测试运行活动将调用文件中定义的所有钩子,这些 conftest.py
文件更接近文件系统的根目录。以下是实现 pytest_runtest_setup
钩子的示例,以便它在 a
子目录的测试中被调用,而不是在其他目录中被调用:
a/conftest.py:
def pytest_runtest_setup(item):
# called for running each test in 'a' directory
print("setting up", item)
a/test_sub.py:
def test_sub():
pass
test_flat.py:
def test_flat():
pass
以下是你可能运行它的方式:
pytest test_flat.py --capture=no # will not show "setting up"
pytest a/test_sub.py --capture=no # will show "setting up"
注意
如果你的 conftest.py
文件不位于 Python 包目录(即不包含 __init__.py
的目录),那么“import conftest”可能会产生歧义,因为你的 PYTHONPATH
或 sys.path
上可能还有其他 conftest.py
文件。因此,最佳实践是项目要么将 conftest.py
放在包范围内,要么从不从 conftest.py
文件中导入任何内容。
注意
由于 pytest 在启动时发现插件的方式,有些钩子不能在不是初始的 conftest.py 文件中实现。详见每个钩子的文档。
编写自己的插件¶
如果你想编写一个插件,有很多真实的例子可以借鉴:
自定义收集示例插件:在 Yaml 文件中指定测试的基本示例
提供 pytest 自身功能的内置插件
提供额外功能的许多外部插件
所有这些插件都实现了钩子和/或fixtures来扩展和添加功能。
注意
请务必查看优秀的cookiecutter-pytest-plugin项目,它是一个用于编写插件的cookiecutter 模板。
该模板提供了一个极佳的起点,包括一个可工作的插件、通过 tox 运行的测试、一份全面的 README 文件以及预配置的入口点。
另外,当你的插件有一些你之外的满意用户时,也请考虑向 pytest-dev 贡献你的插件。
使你的插件可被他人安装¶
如果你想让你的插件能够被外部使用,你可以为你的发行版定义一个所谓的入口点,以便 pytest
能够找到你的插件模块。入口点是打包工具提供的一个功能。
pytest 会查找 pytest11
入口点来发现其插件,因此你可以通过在 pyproject.toml
文件中定义它来使你的插件可用。
# sample ./pyproject.toml file
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[project]
name = "myproject"
classifiers = [
"Framework :: Pytest",
]
[project.entry-points.pytest11]
myproject = "myproject.pluginmodule"
如果一个包以这种方式安装,pytest
将加载 myproject.pluginmodule
作为插件,该插件可以定义钩子。通过 pytest --trace-config
确认注册。
注意
请确保在你的 PyPI 分类器列表中包含 Framework :: Pytest
,以便用户轻松找到你的插件。
断言重写¶
pytest
的主要功能之一是使用普通的 assert 语句以及在断言失败时对表达式进行详细内省。这是通过“断言重写”实现的,它在 AST 编译为字节码之前修改已解析的 AST。这是通过在 pytest
启动时尽早安装的 PEP 302 导入钩子完成的,该钩子在模块导入时执行重写。然而,由于我们不想测试与生产环境中运行的字节码不同的代码,此钩子仅重写测试模块本身(由 python_files
配置选项定义)以及作为插件一部分的任何模块。任何其他导入的模块都不会被重写,将发生正常的断言行为。
如果你的其他模块中有断言辅助函数,并且你需要启用断言重写,你需要明确地要求 pytest
在导入这些模块之前重写它们。
- register_assert_rewrite(*names)[source]
注册一个或多个模块名,以便在导入时进行重写。
此函数将确保此模块或包内的所有模块的断言语句都将被重写。因此,你应该确保在模块实际导入之前调用此函数,通常如果你是一个使用包的插件,则在你的 __init__.py 中调用。
- 参数:
names (str) – 要注册的模块名称。
当你编写使用包创建的 pytest 插件时,这一点尤其重要。导入钩子只将 conftest.py
文件和 pytest11
入口点中列出的任何模块视为插件。例如,考虑以下包:
pytest_foo/__init__.py
pytest_foo/plugin.py
pytest_foo/helper.py
以及以下典型的 setup.py
提取:
setup(..., entry_points={"pytest11": ["foo = pytest_foo.plugin"]}, ...)
在这种情况下,只有 pytest_foo/plugin.py
会被重写。如果辅助模块也包含需要重写的断言语句,则需要在导入之前将其标记为重写。最简单的方法是在 __init__.py
模块中将其标记为重写,因为当包中的模块被导入时,__init__.py
总是会首先被导入。这样,plugin.py
仍然可以正常导入 helper.py
。pytest_foo/__init__.py
的内容需要如下所示:
import pytest
pytest.register_assert_rewrite("pytest_foo.helper")
在测试模块或 conftest 文件中要求/加载插件¶
你可以在测试模块或 conftest.py
文件中使用 pytest_plugins
来要求插件。
pytest_plugins = ["name1", "name2"]
当测试模块或 conftest 插件加载时,指定的插件也会被加载。任何模块都可以被视为插件,包括内部应用程序模块。
pytest_plugins = "myapp.testsupport.myplugin"
pytest_plugins
是递归处理的,因此请注意,在上面的示例中,如果 myapp.testsupport.myplugin
也声明了 pytest_plugins
,则该变量的内容也将作为插件加载,依此类推。
注意
在非根目录的 conftest.py
文件中使用 pytest_plugins
变量来要求插件已被弃用。
这一点很重要,因为 conftest.py
文件实现了按目录的钩子实现,但一旦插件被导入,它将影响整个目录树。为了避免混淆,在任何不在测试根目录的 conftest.py
文件中定义 pytest_plugins
已被弃用,并将引发警告。
这种机制使得在应用程序内甚至外部应用程序之间共享 fixtures 变得容易,而无需使用 入口点打包元数据技术创建外部插件。
通过 pytest_plugins
导入的插件也将自动标记为断言重写(参见 pytest.register_assert_rewrite()
)。然而,要使其生效,模块必须尚未被导入;如果在处理 pytest_plugins
语句时它已被导入,将产生警告,并且插件内部的断言将不会被重写。要解决此问题,你可以在模块导入之前自己调用 pytest.register_assert_rewrite()
,或者安排代码延迟导入直到插件注册之后。
按名称访问其他插件¶
如果一个插件想要与其他插件的代码协作,它可以通过插件管理器获取引用,如下所示:
plugin = config.pluginmanager.get_plugin("name_of_plugin")
如果你想查看现有插件的名称,请使用 --trace-config
选项。
注册自定义标记¶
如果你的插件使用任何标记,你应该注册它们,以便它们出现在 pytest 的帮助文本中,并且不会引起虚假警告。例如,以下插件将为所有用户注册 cool_marker
和 mark_with
:
def pytest_configure(config):
config.addinivalue_line("markers", "cool_marker: this one is for cool tests.")
config.addinivalue_line(
"markers", "mark_with(arg, arg2): this marker takes arguments."
)
测试插件¶
pytest 带有一个名为 pytester
的插件,它可以帮助你编写插件代码的测试。该插件默认是禁用的,因此在使用它之前必须启用它。
你可以通过在测试目录中的 conftest.py
文件中添加以下行来完成此操作:
# content of conftest.py
pytest_plugins = ["pytester"]
或者你可以在命令行中通过 -p pytester
选项调用 pytest。
这将允许你使用 pytester
fixture 来测试你的插件代码。
让我们用一个例子来演示你可以用这个插件做什么。假设我们开发了一个插件,它提供了一个 fixture hello
,该 fixture 产生一个函数,我们可以用一个可选参数调用这个函数。如果我们不提供值,它将返回字符串 Hello World!
;如果我们提供字符串值,它将返回 Hello {value}!
。
import pytest
def pytest_addoption(parser):
group = parser.getgroup("helloworld")
group.addoption(
"--name",
action="store",
dest="name",
default="World",
help='Default "name" for hello().',
)
@pytest.fixture
def hello(request):
name = request.config.getoption("name")
def _hello(name=None):
if not name:
name = request.config.getoption("name")
return f"Hello {name}!"
return _hello
现在,pytester
fixture 提供了一个方便的 API,用于创建临时的 conftest.py
文件和测试文件。它还允许我们运行测试并返回一个结果对象,通过该对象我们可以断言测试的结果。
def test_hello(pytester):
"""Make sure that our plugin works."""
# create a temporary conftest.py file
pytester.makeconftest(
"""
import pytest
@pytest.fixture(params=[
"Brianna",
"Andreas",
"Floris",
])
def name(request):
return request.param
"""
)
# create a temporary pytest test file
pytester.makepyfile(
"""
def test_hello_default(hello):
assert hello() == "Hello World!"
def test_hello_name(hello, name):
assert hello(name) == "Hello {0}!".format(name)
"""
)
# run all tests with pytest
result = pytester.runpytest()
# check that all 4 tests passed
result.assert_outcomes(passed=4)
此外,在运行 pytest 之前,可以将示例复制到 pytester
的隔离环境中。这样我们就可以将测试逻辑抽象到单独的文件中,这对于更长的测试和/或更长的 conftest.py
文件特别有用。
请注意,为了使 pytester.copy_example
工作,我们需要在 pytest.ini
中设置 pytester_example_dir
,以告知 pytest 在何处查找示例文件。
# content of pytest.ini
[pytest]
pytester_example_dir = .
# content of test_example.py
def test_plugin(pytester):
pytester.copy_example("test_example.py")
pytester.runpytest("-k", "test_example")
def test_example():
pass
$ pytest
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y
rootdir: /home/sweet/project
configfile: pytest.ini
collected 2 items
test_example.py .. [100%]
============================ 2 passed in 0.12s =============================
有关 runpytest()
返回的结果对象及其提供的方法的更多信息,请查阅 RunResult
文档。