如何解决pytest中出现的‘fixtures not found’错误?
解决pytest "fixtures not found" 错误的方法
你遇到的问题根源是:pytest会自动扫描所有以test_开头的函数并将其当作独立测试用例执行,而test_project_creation和test_create_streams这两个函数依赖了未定义的fixture,所以pytest单独解析它们时会报错——但你在test_workflow里是把它们当作普通函数调用,所以执行逻辑是正常的。
下面是两种可行的解决方法:
1. 重命名内部测试步骤函数(推荐)
把test_project_creation和test_create_streams改成不以test_开头的名称,比如_create_project和_setup_streams,这样pytest就不会把它们识别为独立测试用例,自然不会触发fixture检查。修改后的代码示例:
def test_workflow(): with open("./configs.json",'r') as f: CONFIGS = json.load(f) owner_id = CONFIGS['ownerId'] project_name = CONFIGS['projectConfigs']['projectName'] project_configs = CONFIGS['projectConfigs'] project_configs['ownerId'] = owner_id projectId = _create_project( owner_id= owner_id, project_configs = project_configs, application_configs = CONFIGS['applicationConfigs'][CONFIGS['applicationName']], ) input_video, output_ip, output_port, output_hls_link, input_hls_link = _setup_streams( input_stream_config=CONFIGS['inputStreamConfigs'] ) def _create_project(owner_id, project_configs, application_configs): # 原test_project_creation的逻辑 pass def _setup_streams(input_stream_config): # 原test_create_streams的逻辑 pass
2. 标记排除内部测试步骤
如果不想修改函数名,可以给这些内部步骤函数加上@pytest.mark.skip标记,让pytest跳过对它们的独立执行检查:
import pytest @pytest.mark.skip(reason="仅作为工作流步骤调用,不独立执行") def test_project_creation(owner_id, project_configs, application_configs): # 原函数逻辑 pass @pytest.mark.skip(reason="仅作为工作流步骤调用,不独立执行") def test_create_streams(input_stream_config): # 原函数逻辑 pass def test_workflow(): # 原test_workflow逻辑不变 pass
另外,也可以在项目根目录的conftest.py中添加钩子函数,批量过滤掉这些内部步骤:
import pytest def pytest_collection_modifyitems(config, items): # 指定需要跳过的内部步骤函数名 step_functions = {"test_project_creation", "test_create_streams"} skip_marker = pytest.mark.skip(reason="工作流内部步骤,不独立执行") for item in items: if item.name in step_functions: item.add_marker(skip_marker)
内容的提问来源于stack exchange,提问作者Aseem Kannal
相关产品推荐
相关产品推荐

