pytest钩子可以使用固定装置吗?

2024-04-26 03:28:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道固定装置可以使用其他装置,但是吊钩可以使用固定装置吗?我在网上搜了很多东西,但找不到任何帮助。如果我在这里犯了什么错误,有人能指出吗?在

#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

当我运行它时,我得到以下错误。在

在pluggy.manager.plugInvalidateError:插件C:\some\u path\conftest.py'for hook'pytest_runtest_安装' hookimpl定义:pytest_runtest_安装程序(项,json_加载程序) 参数{'json_loader'}在hookimpl中声明,但在hookspec中找不到

即使我没有将json_loader作为参数传递给pytest_runtest_setup(),我也会收到一个错误,说“Fixture”json_loader“是直接调用的”。固定装置不能直接调用”


Tags: pyjsondatareturnpytestdef错误with
1条回答
网友
1楼 · 发布于 2024-04-26 03:28:20

目前支持动态实例化fixture的唯一方法似乎是通过requestfixture,特别是getfixturevalue方法

这在pytest钩子的测试时间之前是不可访问的,但是您可以通过自己使用fixture来完成相同的任务

这里有一个(人为的)例子:

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'

相关问题 更多 >