pytest 钩子可以使用夹具吗?

vas*_*r c 6 python pytest

我知道夹具可以使用其他夹具,但是钩子可以使用夹具吗?我在网上搜索了很多,但没有得到任何帮助。如果我在这里做错了,有人可以指出吗?

#conftest.py

@pytest.fixture()
def json_loader(request):   
    """Loads the data from given JSON file"""
    def _loader(filename):
        import json
        with open(filename, 'r') as f:
            data = json.load(f)
        return data
    return _loader



def pytest_runtest_setup(item,json_loader): #hook fails to use json_loader
    data = json_loader("some_file.json") 
    print(data) 
    #do something useful here with data
Run Code Online (Sandbox Code Playgroud)

运行时出现以下错误。

pluggy.manager.PluginValidationError: 插件 'C:\some_path\conftest.py' for hook 'pytest_runtest_setup' hookimpl 定义:pytest_runtest_setup(item, json_loader) Argument(s) {'json_loader'} 在 hookimpl 中声明但找不到在钩子规范中

即使我没有将 json_loader 作为 arg 传递给 pytest_runtest_setup(),我也会收到一条错误消息,指出“Fixture“json_loader”被直接调用。Fixtures 并不意味着被直接调用”

Ant*_*ile 3

似乎当前唯一支持的动态实例化装置的方法是通过装置request,特别是getfixturevalue方法

在 pytest 挂钩中的测试时间之前无法访问此功能,但您可以自己使用固定装置来完成相同的任务

这是一个(人为的)示例:

import pytest

@pytest.fixture
def load_data():
    def f(fn):
        # This is a contrived example, in reality you'd load data
        return f'data from {fn}'
    return f


TEST_DATA = None


@pytest.fixture(autouse=True)
def set_global_loaded_test_data(request):
    global TEST_DATA
    data_loader = request.getfixturevalue('load_data')
    orig, TEST_DATA = TEST_DATA, data_loader(f'{request.node.name}.txt')
    yield   
    TEST_DATA = orig


def test_foo():
    assert TEST_DATA == 'data from test_foo.txt'
Run Code Online (Sandbox Code Playgroud)

  • 那么,我们不是有办法让hook直接使用fixture吗?钩子使用固定装置的有效用例不是吗?我很惊讶我在 pytest 文档中没有看到任何对此的帮助,也没有任何人在任何地方提到它。 (7认同)