1 回答
TA贡献1866条经验 获得超5个赞
终于解决了这个问题,但不确定这是否是可靠的解决方案。test/common/test_common.py我把我的测试:
def test_method(instance: Interface):
assert type(instance.method()) == int
在tests/common/conftest.py我有有趣的东西:
THIS_PACKAGE = 'tests/common/'
def create_instance_hooks(meta_fixture, name):
tests_node_id = os.path.join(THIS_PACKAGE, '{}.py'.format(name))
def pytest_runtest_protocol(item, nextitem):
split = item.nodeid.split('::')
filename, *test_name = split
if filename == tests_node_id and 'instance' in item.fixturenames:
func_name = meta_fixture.__name__
meta = tuple(item.session._fixturemanager._arg2fixturedefs[func_name])
item._request._arg2fixturedefs['instance'] = meta
@pytest.hookimpl(hookwrapper=True)
def pytest_collect_file(path, parent):
outcome = yield
result = outcome.get_result()
if parent.parent is None:
result.append(
DoctestModule(os.path.join(parent.fspath, THIS_PACKAGE, 'conftest.py'), parent,
nodeid=os.path.join(THIS_PACKAGE, '{}_conf.py'.format(name))))
result.append(Module(os.path.join(parent.fspath, THIS_PACKAGE, 'test_common.py'), parent,
nodeid=tests_node_id))
return pytest_runtest_protocol, pytest_collect_file
在tests/impl1/conftest.py我有
@pytest.fixture
def impl1_instance():
return Impl1()
pytest_runtest_protocol, pytest_collect_file = create_instance_hooks(impl1_instance, 'impl1')
在tests/impl2/conftest.py我有
@pytest.fixture
def impl2_instance():
return Impl2()
pytest_runtest_protocol, pytest_collect_file = create_instance_hooks(impl2_instance, 'impl2')
所以基本上当tests/implN收集测试时,pytest_collect_file钩子添加测试tests/common/test_common.py ,然后当它们运行时,pytest_runtest_protocol钩子添加implN_instance夹具作为实例夹具。因此,如果我只运行 impl1 或 impl2,则运行一组测试,如果我只运行 pytest 测试,则有两组带有适当夹具的测试
添加回答
举报