是否可以模拟os.scandir及其属性?

2024-06-16 10:48:50 发布

您现在位置:Python中文网/ 问答频道 /正文

for entry in os.scandir(document_dir)
    if os.path.isdir(entry):
    # some code goes here
    else:
        # else the file needs to be in a folder
        file_path = entry.path.replace(os.sep, '/')

在else语句中模拟os.scandir和path属性时遇到问题。我无法模拟在单元测试中创建的模拟对象的属性

with patch("os.scandir") as mock_scandir:
    # mock_scandir.return_value = ["docs.json", ]
    # mock_scandir.side_effect = ["docs.json", ]
    # mock_scandir.return_value.path = PropertyMock(return_value="docs.json")

这些都是我尝试过的选择。非常感谢您的帮助


Tags: pathinjsondocsforreturn属性value
1条回答
网友
1楼 · 发布于 2024-06-16 10:48:50

这取决于你真正需要嘲笑什么。问题是os.scandir返回类型为os.DirEntry的条目。一种可能是使用您自己的mockDirEntry,只实现您需要的方法(在您的示例中,只实现path)。例如,您还必须模拟os.path.isdir。下面是一个独立的示例,介绍如何做到这一点:

import os
from unittest.mock import patch


def get_paths(document_dir):
    # example function containing your code
    paths = []
    for entry in os.scandir(document_dir):
        if os.path.isdir(entry):
            pass
        else:
            # else the file needs to be in a folder
            file_path = entry.path.replace(os.sep, '/')
            paths.append(file_path)
    return paths


class DirEntry:
    def __init__(self, path):
        self.path = path

    def path(self):
        return self.path


@patch("os.scandir")
@patch("os.path.isdir")
def test_sut(mock_isdir, mock_scandir):
    mock_isdir.return_value = False
    mock_scandir.return_value = [DirEntry("docs.json")]
    assert get_paths("anydir") == ["docs.json"]

根据您的实际代码,您可能需要做更多的工作

如果你想修补更多的文件系统函数,你可以考虑使用pyfakefs来代替整个文件系统。对于单个测试来说,这将是过分的,但是对于依赖于文件系统功能的测试套件来说,这是非常方便的

免责声明:我是pyfakefs的贡献者

相关问题 更多 >