pytest插件的7种用法

  

下面是有关pytest 插件的 7 种用法的攻略:

1. 钩子函数

pytest 插件可以通过钩子函数来在测试用例运行过程中执行特定的代码。常见的钩子函数有 pytest_load_initial_conftestspytest_addoptionpytest_collection_modifyitems 等。

例如,我们可以通过编写 pytest_addoption 钩子函数来为 pytest 添加自定义命令行参数。具体实现方法如下:

# conftest.py
def pytest_addoption(parser):
    parser.addoption("--myoption", action="store", default="default", help="my custom option")

在上面的代码中,我们使用 pytest_addoption 钩子函数为 pytest 添加了一个叫做 --myoption 的命令行参数。这个参数可以在 pytest 运行时传入,如下所示:

pytest --myoption hello pytest

执行上述命令后,pytest 会将参数传递给钩子函数,我们可以在测试用例中通过 request.config.getoption("--myoption") 获取该参数的值。例如:

# test_demo.py
def test_myoption(request):
    assert request.config.getoption("--myoption") == "hello"

在上面的测试用例中,我们调用了 request.config.getoption 方法来获取传入的 --myoption 参数,并使用 assert 语句来断言该参数的值是否为 "hello"。

2. 插件配置

pytest 插件可以通过 pytest.ini 文件来配置。你可以在 pytest.ini 文件中添加诸如 addoptsmarkerspython_files 等标志和选项,以配置插件的行为。

例如,下面是一个 pytest.ini 文件的示例:

[pytest]
addopts = -v
markers =
     slow: mark test as slow running.

在上面的示例中,我们使用 addopts 选项来指定了运行 pytest 时的参数,该参数告诉 pytest 打印详细日志。同时,我们还添加了一个名为 slow 的标记,以告诉 pytest 运行速度较慢的测试用例。

3. 自定义fixture

pytest 插件也可以通过自定义 fixture 来扩展 pytest 的功能。你可以编写自己的 fixture 函数,并将其与测试用例一起使用。

例如,下面是一个自定义 fixture 的示例:

# conftest.py
import pytest

@pytest.fixture
def myfixture():
    print("I am a fixture!")

在上面的代码中,我们定义了一个名为 myfixture 的 fixture 函数,该函数在每个测试用例执行前都会被调用,并打印一条消息。

# test_demo.py
def test_myfixture(myfixture):
    pass

上述测试用例使用了 myfixture fixture,因此在运行时会首先执行 myfixture 函数,之后再运行测试用例本身。

4. 自定义 Markers

pytest 插件还可以添加自定义 Markers。Markers 是与测试用例相关的标识,可用于过滤、分组和标记测试结果。

例如,下面是一个自定义 Marker 的示例:

# conftest.py
import pytest

@pytest.mark.my_marker
def test_example():
    assert True

在上面的代码中,我们定义了一个名为 my_marker 的 Marker,并将其应用于名为 test_example 测试用例。

在运行 pytest 时,你可以使用 -m 选项来执行某些具有特定 Marker 的测试用例,如下所示:

pytest -v -m my_marker

该命令运行名为 test_example 的测试用例,因为该测试用例被标记了 my_marker 标识。

5. 自定义CLI命令

pytest 插件还可以添加自定义的 CLI 命令,这样你可以快速执行定制化的任务。

例如,下面是一个自定义 CLI 命令的示例:

# conftest.py
def pytest_addoption(parser):
    parser.addoption("--mycli", action="store_true", help="run my custom cli command")

def pytest_cmdline_main(config):
    if config.getoption("--mycli"):
        print("My custom cli command is running!")
        return 0

在上面的代码中,我们定义了一个叫做 mycli 的自定义 CLI 命令。当使用 --mycli 参数运行 pytest 时,pytest 会调用 pytest_cmdline_main 函数并打印出一条消息。

6. 插件之间交互

pytest 插件可以通过钩子实现相互作用,这样你可以编写插件来扩展其他插件的功能,或者插件之间通过共享数据和行为来增强 pytest 的功能。

例如,下面是一个插件之间交互的 Markdown 插件的示例:

# conftest.py
def pytest_configure(config):
    markdown_plugin = config.pluginmanager.getplugin("markdown")
    if markdown_plugin:
        markdown_plugin.add_transform("example", lambda value: f"<p>{value}</p>")

在上面的代码中,我们定义了一个 pytest_configure 钩子,通过 config.pluginmanager.getplugin 获取 markdown 插件实例。之后,我们使用 add_transform 方法为 markdown 插件添加了一个新的转换器,将 example 标记转换为 <p> 标签。

现在,当你在 markdown 文件中写入以下内容时:

This is an [example].

该插件会将其转换为:

<p>This is an example.</p>

7. 自定义收集规则

pytest 插件还可以添加自定义的收集规则,以自定义 pytest 收集测试用例的方式。自定义收集规则是通过修改 pytest 的默认行为,在未经特别标记的情况下,收集或排除特定的测试用例集。可以编写自己的 collector,然后通过 pytest_collect_file 来指定采集规则。

例如,下面是一个名为 test_demo.py 的示例测试用例文件和一个自定义的收集规则:

# conftest.py
import pytest

class MyCustomCollector(pytest.File):
    def collect(self):
        if "my_marker" in self.config.getini("markers"):
            return super().collect()
        else:
            return []

def pytest_collect_file(path, parent):
    if path.ext == ".py":
        return MyCustomCollector(str(path), parent=parent)

在上面的代码中,我们定义了一个名为 MyCustomCollector 的自定义 collector,它通过判断模块是否包含 my_marker 标记来决定是否收集测试用例。接着,在 pytest_collect_file 函数中我们将上述 collector 应用到了所有的 .py 文件中。

运行 pytest 时,如果指定了 my_marker 标记,则 pytest 将收集所有测试用例;否则,pytest 将不会执行测试用例。

以上是关于 pytest 插件的 7 种用法的详细攻略,希望能对你有所帮助。

相关文章