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

时间:2019-03-29 08:31:20

标签: 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

运行时出现以下错误。

pluggy.manager.PluginValidationError:钩子'pytest_runtest_setup'的插件'C:\ some_path \ conftest.py' hookimpl定义:pytest_runtest_setup(item,json_loader) 参数{'json_loader'}在hookimpl中声明,但在hookspec中找不到

即使我没有将json_loader作为arg传递给pytest_runtest_setup(),我也会收到一条错误消息,内容为“直接调用Fixx“ json_loader”。灯具不应该直接调用”

2 个答案:

答案 0 :(得分:1)

目前似乎唯一支持动态实例化夹具的方法是通过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'

答案 1 :(得分:0)

有一种方法可以从测试中获得用过的夹具。

#Conftest.py#

def pytest_runtest_makereport(item, call):
    if call.when == 'call':
        cif_fixture = item.funcargs["your_cool_fixture"]
        print(cif_fixture)

#test_file.py#
@pytest.fixture(scope="module")
def your_cool_fixture(request):
    return "Hi from fixture"


def test_firsttest(your_cool_fixture):
    print(your_cool_fixture)