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

如何让pytest不删除测试通过的临时目录?

如何让pytest保留所有测试的tmp_path临时目录

默认情况下pytest仅保留失败测试的tmp_path目录,要留存所有测试的临时目录,可通过以下几种方法实现:

方法一:使用官方参数(pytest 7.0+)

从pytest 7.0版本开始,新增了直接控制临时目录清理的参数:

  • --no-cleanup:强制保留所有测试的临时目录,无论测试是否通过
  • --keep-duplicates:避免重复测试的临时目录被覆盖

执行测试时直接添加参数即可:

pytest --no-cleanup --keep-duplicates

方法二:自定义持久化临时目录fixture

如果使用低版本pytest,或需要更灵活的控制,可以自定义fixture替代默认的tmp_path:

import tempfile
from pathlib import Path
import pytest

@pytest.fixture(scope="function")
def persistent_tmp_path():
    # 创建临时目录,注释清理逻辑以保留目录
    tmpdir = tempfile.mkdtemp()
    tmp_path = Path(tmpdir)
    yield tmp_path
    # 移除下面的注释可恢复自动清理,当前状态为保留目录
    # import shutil
    # shutil.rmtree(tmpdir)

测试代码中替换为自定义fixture:

from pathlib import Path

def test_file_to_keep(persistent_tmp_path):
    my_file_to_keep = persistent_tmp_path / "my_file.txt"
    with open(my_file_to_keep, 'w') as out_file:
        out_file.writelines("some good output.")
        
    assert my_file_to_keep.exists()

方法三:全局钩子控制清理行为

在项目根目录创建conftest.py,通过钩子全局禁用临时目录清理,还可统一归集目录:

import pytest
import shutil
from pathlib import Path

def pytest_configure(config):
    # 禁用默认的临时目录自动清理
    config.option.cleanup = False

def pytest_sessionfinish(session, exitstatus):
    # 可选:将所有临时目录复制到指定目录统一管理
    base_tmp_dir = Path(session.config._tmp_path_factory.getbasetemp())
    target_dir = Path("./test_persistent_tmp")
    target_dir.mkdir(parents=True, exist_ok=True)
    
    for tmp_dir in base_tmp_dir.iterdir():
        if tmp_dir.is_dir():
            shutil.copytree(tmp_dir, target_dir / tmp_dir.name)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 11:33:16