我知道灯具可以使用其他灯具,但是钩子可以使用灯具吗?我在网上找了很多,但找不到任何帮助。有没有人能指出我在这里做错了什么?
#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’挂钩实例定义: pytest_runtest_setup(item,json_loader)参数{'json_loader'}在挂钩实例中声明,但在挂钩规范中找不到
即使我没有将json_loader作为arg传递给pytest_runtest_setup(),我也会收到一个错误,说"Fixture "json_loader“被直接调用。Fixture不应该被直接调用”
发布于 2019-03-29 19:29:39
目前唯一支持动态实例化fixture的方法似乎是通过request fixture,特别是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'发布于 2020-10-01 15:42:30
有一种方法可以从测试中获得使用过的夹具。
#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)https://stackoverflow.com/questions/55413277
复制相似问题