You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用pytest fixture创建含多PIL生成图片的指定结构临时目录?

实现pytest临时目录结构并生成测试图片

首先确保安装依赖:

pip install pytest pillow

创建测试文件(比如test_image_setup.py),代码如下:

import pytest
from PIL import Image

@pytest.fixture
def structured_test_dir(tmp_path):
    # 构建要求的目录结构
    root_data_dir = tmp_path / "tests" / "test_data"
    
    # 遍历需要创建的子目录
    subdirs = ["Test_0", "test_1"]
    for subdir in subdirs:
        target_dir = root_data_dir / subdir
        # 递归创建目录(包括父目录)
        target_dir.mkdir(parents=True, exist_ok=True)
        
        # 生成并保存两张白色图片
        for img_idx in [1, 2]:
            img = Image.new("RGB", (128, 128), color='white')
            img.save(target_dir / f"image_{img_idx}")
    
    return root_data_dir

def test_directory_and_images(structured_test_dir):
    # 验证目录结构和图片是否生成成功
    subdirs = ["Test_0", "test_1"]
    for subdir in subdirs:
        dir_path = structured_test_dir / subdir
        assert dir_path.is_dir()
        assert (dir_path / "image_1").is_file()
        assert (dir_path / "image_2").is_file()

关键说明:

  • tmp_path是pytest内置的fixture,会自动创建临时目录,测试完成后自动清理,无需手动处理文件残留。
  • mkdir(parents=True)会自动创建所有缺失的父目录(比如tests/test_data),exist_ok=True避免重复创建目录时抛出异常。
  • 用循环批量生成目录和图片,避免重复代码,结构更清晰。

内容的提问来源于stack exchange,提问作者gyaha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 18:27:28