如何在pytest运行测试前收集所有测试节点名并创建对应目录?
实现方案
要在session级自动运行的fixture中收集所有测试节点并创建对应目录,可通过以下步骤实现:
方法一:直接通过session fixture获取测试节点
在项目的conftest.py中添加以下代码:
import os import pytest @pytest.fixture(scope='session') def all_test_nodes(request): # 从session中获取pytest已收集的所有测试节点 return request.session.items @pytest.fixture(scope='session', autorun=True) def make_test_folders(all_test_nodes): base_dir = "test_data_archive" # 自定义基础目录 for node in all_test_nodes: # 每个测试节点对应一个子目录,节点名称可直接用node.name target_dir = os.path.join(base_dir, node.name) # exist_ok=True避免目录已存在时抛出异常 os.makedirs(target_dir, exist_ok=True)
方法二:通过钩子提前收集测试节点
如果需要在收集阶段做额外处理,可借助pytest_collection_modifyitems钩子:
import os import pytest def pytest_collection_modifyitems(session, config, items): # 将收集到的测试节点存入config的自定义属性 config._collected_test_nodes = items @pytest.fixture(scope='session') def all_test_nodes(request): return request.config._collected_test_nodes @pytest.fixture(scope='session', autorun=True) def make_test_folders(all_test_nodes): base_dir = "test_data_archive" for node in all_test_nodes: target_dir = os.path.join(base_dir, node.name) os.makedirs(target_dir, exist_ok=True)
关键说明
- 测试节点的
name属性:函数式测试为函数名,类中的测试方法为TestClassName.test_method_name格式,可根据需求拆分或直接使用。 - 若需将同一测试类的方法归入同一目录,可改用
node.parent.name获取测试类名称来构建目录路径。 os.makedirs的exist_ok=True参数必须添加,避免重复运行测试时因目录已存在报错。
内容的提问来源于stack exchange,提问作者J_yang
相关产品推荐
相关产品推荐

