python - Python中 "renaming files"的单元测试

标签 python python-3.x unit-testing

假设我有以下功能,我需要对其进行单元测试:

def move_files_to(files, path):
for file in files:
    os.rename(file, path + "/" + file)

我对这个话题的看法:

模拟 os.rename 不会导致任何结果,另一方面,拥有文件并重命名它们将是“执行 I/O”,这应该在单元测试中避免。如果我错了,请纠正我。测试在这里有意义吗?

最佳答案

不需要测试os.rename,但是您的代码需要测试。在您的特定情况下,最简单的方法是修补 os.rename:

from unittest.mock import patch

def test_move_files():
    files = ['a.txt', 'b.txt']
    path = 'old'
    expected = [(('a.txt', 'old/a.txt'),),
                (('b.txt', 'old/b.txt'),)]
    with patch('os.rename') as rename:
        move_files_to(files, path)
        assert rename.call_args_list == expected

关于python - Python中 "renaming files"的单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56760486/

相关文章:

python - 通过 python 将一个大字符串拆分为多个包含 'n' 个单词的子字符串

python - 保存带有混合数据的 numpy 数组

python - 正则表达式提取嵌套模式

Python 异或错误

javascript - Jest |测试 moment 函数是否被调用以及返回输出是否正确

python - 你能找出这个关于线性回归的正规方程实现的程序有什么问题吗

python - pandas.to_csv 不显示小数点后两位的浮点值

python - zip 不适用于 imshow : TypeError: Image data cannot be converted to float

unit-testing - 我是否需要在单元测试中取消订阅?

unit-testing - 为 ASP.NET 5 Controller 单元测试添加 session