是否可以模拟 os.scandir 及其属性?
Is it possible to mock os.scandir and its attributes?
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, '/')
我在模拟 os.scandir 和 else 语句中的路径属性时遇到问题。我无法模拟我在单元测试中创建的模拟对象 属性。
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")
这些都是我试过的选项。非常感谢任何帮助。
这取决于您真正需要模拟的内容。问题是 os.scandir
returns 个 os.DirEntry
类型的条目。一种可能性是使用您自己的模拟 DirEntry
并仅实现您需要的方法(在您的示例中,仅 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 的贡献者。
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, '/')
我在模拟 os.scandir 和 else 语句中的路径属性时遇到问题。我无法模拟我在单元测试中创建的模拟对象 属性。
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")
这些都是我试过的选项。非常感谢任何帮助。
这取决于您真正需要模拟的内容。问题是 os.scandir
returns 个 os.DirEntry
类型的条目。一种可能性是使用您自己的模拟 DirEntry
并仅实现您需要的方法(在您的示例中,仅 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 的贡献者。