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

Pytest会话级Fixture无法完全清理参数化测试创建的目录问题求助

Pytest会话级Fixture无法完全清理参数化测试创建的目录问题求助

我现在用Pytest的fixture来清理测试过程中生成的临时文件和目录,这个fixture在大部分测试用例里都正常,但前两个参数化测试创建的目录总是删不干净。下面是简化后的fixture代码:

import pytest
import os
import shutil

@pytest.fixture(scope="session")
def cleanup_environment():
    temp_paths = []  # List to track temporary paths

    yield temp_paths  # Provide the list to tests

    # Sort paths by directory depth (deepest first)
    temp_paths_sorted = sorted(temp_paths, key=lambda p: p.count(os.sep), reverse=True)

    for temp_path in temp_paths_sorted:
        if os.path.exists(temp_path):
            try:
                if os.path.isfile(temp_path):
                    os.remove(temp_path)
                elif os.path.isdir(temp_path):
                    shutil.rmtree(temp_path, ignore_errors=True)
            except Exception as e:
                print(f"Failed to remove {temp_path}: {e}")

    for temp_path in temp_paths_sorted:
        parent_dir = os.path.dirname(temp_path)
        while parent_dir and os.path.exists(parent_dir) and not os.listdir(parent_dir):
            try:
                os.rmdir(parent_dir)
                parent_dir = os.path.dirname(parent_dir)
            except Exception as e:
                print(f"Failed to remove parent directory {parent_dir}: {e}")
                break

以下是我的测试用例:

正常工作的测试用例(目录和文件都能被清理)

def test_create_and_delete_file(cleanup_environment, tmpdir):
    temp_file = tmpdir.join("temp_file.txt")
    temp_file.write("Temporary content")
    cleanup_environment.append(str(temp_file))
    assert temp_file.check(file=True)

def test_create_and_delete_dir(cleanup_environment, tmpdir):
    temp_dir = tmpdir.mkdir("temp_dir")
    cleanup_environment.append(str(temp_dir))
    assert temp_dir.check(dir=True)

清理失败的测试用例(这些测试的目录无法完全删除)

@pytest.mark.parametrize("test_case", ["case1", "case2"])
def test_parameterized_cases(cleanup_environment, tmpdir, test_case):
    temp_dir = tmpdir.mkdir(f"temp_dir_{test_case}")
    cleanup_environment.append(str(temp_dir))
    assert temp_dir.check(dir=True)

在参数化测试的case1和case2中,创建的目录明明已经添加到cleanup_environment列表里了,但就是没法被完全删除。

请问我该怎么调整才能确保所有目录(包括参数化测试生成的)都被正确清理干净?

备注:内容来源于stack exchange,提问作者ege selcuk

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 16:44:52