pytest如何检测文件夹存在性,仅在目录不存在时执行fixture创建逻辑
解决方案
os.mkdir仅支持创建不存在的目录,路径已存在时会直接抛出FileExistsError,可通过两种方式修改fixture实现按需创建目录:
方案1:手动判断路径存在性(兼容全Python版本)
手动判断目标路径是否存在,仅不存在时执行创建操作,可自定义存在时的处理逻辑:
import os import pytest @pytest.fixture(scope="module", autouse=True) def set_up(): root_path = os.getcwd() test_output_path = os.path.join(root_path, 'test-output') folders = ['folder1', 'folder2', 'folder3'] # 校验test-output目录 if not os.path.exists(test_output_path): os.mkdir(test_output_path) # 校验子目录 for folder in folders: folder_path = os.path.join(test_output_path, folder) if not os.path.exists(folder_path): os.mkdir(folder_path) def test_folders(set_up): print('created folders')
方案2:使用os.makedirs的exist_ok参数(推荐,Python3.2+支持)
os.makedirs支持递归创建目录,设置exist_ok=True后会自动跳过已存在的路径,不会抛出异常,代码更简洁:
import os import pytest @pytest.fixture(scope="module", autouse=True) def set_up(): root_path = os.getcwd() test_output_path = os.path.join(root_path, 'test-output') folders = ['folder1', 'folder2', 'folder3'] # 创建test-output,已存在则跳过 os.makedirs(test_output_path, exist_ok=True) # 创建子目录,已存在则跳过 for folder in folders: folder_path = os.path.join(test_output_path, folder) os.makedirs(folder_path, exist_ok=True) def test_folders(set_up): print('created folders')
附加说明:如果需要每次测试都使用干净的空目录,避免旧文件干扰测试结果,可以在fixture中加入后置销毁逻辑:
@pytest.fixture(scope="module", autouse=True) def set_up(): root_path = os.getcwd() test_output_path = os.path.join(root_path, 'test-output') folders = ['folder1', 'folder2', 'folder3'] # 前置逻辑:创建目录 os.makedirs(test_output_path, exist_ok=True) for folder in folders: os.makedirs(os.path.join(test_output_path, folder), exist_ok=True) yield # 此处暂停,执行测试用例 # 后置逻辑:测试完成后删除测试输出目录 import shutil shutil.rmtree(test_output_path)
内容的提问来源于stack exchange,提问作者viktor_dmitry
相关产品推荐
相关产品推荐

