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

Python unittest测试:如何正确Mock子目录结构测试目录删除函数

错误原因

你原来的测试用例存在3个核心问题:

  • 变量名冲突:两个mock.patch的返回值都赋值给了mocked_listdir,后定义的os.remove的mock会覆盖前一个os.listdir的mock,导致os.listdir的返回值没有被正确设置
  • 遗漏mock依赖:原函数逻辑依赖os.path.isdir判断文件类型、shutil.rmtree删除目录,这两个方法没有被mock,会触发真实文件系统操作,也无法验证删除逻辑
  • 断言逻辑错误:直接对mock对象取len是无效操作,你需要验证的是删除方法os.remove和shutil.rmtree的调用次数、调用参数是否符合预期

正确测试用例示例

import os
import shutil
from unittest import mock

# 这里替换为你实际导入rmdir_and_files_with_exceptions的路径
from your_module import rmdir_and_files_with_exceptions

def test_rmdir_and_files_with_exceptions():
    # 一次性mock所有依赖的系统方法
    with mock.patch("os.listdir") as mocked_listdir, \
         mock.patch("os.path.isdir") as mocked_isdir, \
         mock.patch("os.remove") as mocked_remove, \
         mock.patch("shutil.rmtree") as mocked_rmtree:
        
        # 模拟目录下有3个条目:alpha(保留)、beta(目录,要删)、xyz(文件,要删)
        mocked_listdir.return_value = ["alpha", "beta", "xyz"]

        # 模拟isdir的返回结果:beta是目录,其余两个不是
        def mock_isdir(path):
            return path.endswith("beta")
        mocked_isdir.side_effect = mock_isdir

        # 执行被测函数
        rmdir_and_files_with_exceptions(".", exceptions=["alpha"])

        # 校验删除逻辑符合预期
        # 校验目录beta被删除
        mocked_rmtree.assert_called_once_with("./beta")
        # 校验文件xyz被删除
        mocked_remove.assert_called_once_with("./xyz")
        # 校验两个删除方法总调用次数为2,符合预期
        assert mocked_rmtree.call_count + mocked_remove.call_count == 2

补充说明

如果需要覆盖更多场景,可以新增测试用例:

  • 所有条目都是目录的场景
  • 所有条目都是文件的场景
  • 例外列表为空的场景
  • 例外列表包含所有条目的场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 18:06:09