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

如何使用mocker.patch对Python文件重命名功能进行pytest测试

你原函数需要先补上import os导入语句,否则运行会报错。

测试实现指导

首先你需要先安装pytest和pytest-mock依赖:

pip install pytest pytest-mock

核心测试逻辑说明

你的重命名函数依赖os模块的3个方法,测试时不需要操作真实文件系统,直接用mocker.patch模拟这些方法的返回值、验证调用参数即可:

  • 模拟os.listdir返回自定义的文件名列表,模拟目标目录下的文件情况
  • 模拟os.rename为Mock对象,验证它是否被调用、传入的路径参数是否符合预期

注意:mocker.patch的目标路径需要匹配你函数中实际导入的os模块路径,如果你的重命名函数定义在单独的模块中(比如rename_tool.py),且在该模块顶部写了import os,则需要将patch路径改为rename_tool.os.listdir、rename_tool.os.rename,否则模拟不生效。

完整测试代码示例

假设你的重命名函数定义在file_utils.py文件中,测试文件命名为test_file_utils.py,内容如下:

import os
from file_utils import function  # 导入你写的重命名函数

def test_rename_copy_prefix_files(mocker):
    # 模拟目录下的文件列表,包含3个带copy_前缀的文件,2个不带
    mock_files = ["copy_test1.txt", "copy_report.pdf", "normal_file.jpg", "copy_2024_data.csv", "readme.md"]
    mocker.patch("os.listdir", return_value=mock_files)
    # 模拟os.rename为Mock对象
    mock_rename = mocker.patch("os.rename")

    test_dir = "/test/target/dir"
    result = function(test_dir)

    # 断言返回值正确
    assert result == test_dir
    # 断言rename被调用了3次,对应3个带copy_前缀的文件
    assert mock_rename.call_count == 3
    # 验证每次调用的参数是否符合预期
    mock_rename.assert_any_call(
        os.path.join(test_dir, "copy_test1.txt"),
        os.path.join(test_dir, "test1.txt")
    )
    mock_rename.assert_any_call(
        os.path.join(test_dir, "copy_report.pdf"),
        os.path.join(test_dir, "report.pdf")
    )
    mock_rename.assert_any_call(
        os.path.join(test_dir, "copy_2024_data.csv"),
        os.path.join(test_dir, "data.csv")
    )

def test_no_copy_prefix_files(mocker):
    # 测试没有带copy_前缀的文件的场景
    mock_files = ["normal1.txt", "test.jpg", "data.csv"]
    mocker.patch("os.listdir", return_value=mock_files)
    mock_rename = mocker.patch("os.rename")

    test_dir = "/test/target/dir"
    function(test_dir)

    # 断言没有调用rename
    mock_rename.assert_not_called()

def test_empty_directory(mocker):
    # 测试目录为空的场景
    mocker.patch("os.listdir", return_value=[])
    mock_rename = mocker.patch("os.rename")

    test_dir = "/test/target/dir"
    function(test_dir)

    mock_rename.assert_not_called()

运行测试

在终端执行以下命令即可运行所有测试用例:

pytest test_file_utils.py -v

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 09:09:04