长时间侦听,第一次调用者。
我编写了一个python 2.7方法,该方法在具有一些类似find
功能的给定目录上执行递归扫描(使用scandir
),即,您可以指定mindepth
和maxdepth
):
def scan_tree(self, search_path, max_levels=-1, min_levels=-1, _level=0):
"""Recursively yield DirEntry objects for given directory."""
max_out = max_levels > -1 and _level == max_levels
min_out = min_levels > -1 and _level <= min_levels
for entry in scandir(search_path):
if entry.is_dir(follow_symlinks=False) and not max_out:
for child in self._scan_tree(entry.path, max_levels,
min_levels, _level + 1):
if not child.is_dir(follow_symlinks=False):
yield child
elif not min_out:
yield entry
问题是,我一生都无法找出编写单元测试的最佳/正确方法,该单元测试将允许我正确mock
递归scandir
调用并测试最小和最大扫描参数的行为。
通常我会使用scandir.walk
进行扫描(我已经编写了一个适当的可测试版本),但我确实需要有关scandir
吐出的DirEntry
实例的信息。
任何想法将不胜感激。谢谢!
我可以提出一个替代解决方案:
创建目录结构
扭转局面:问问自己"我想要什么?我认为它有一个固定的目录结构来测试。我们可以改用 makedirs 等os
包函数来创建这样的结构,并简单地调用真正的scandir
,但将search_path
固定为固定的"testdir":当前工作目录的子目录。
例如,执行以下操作:
basedir = os.path.dirname(__file__)
os.makedirs(os.path.join(basedir, '/testdirectory/first/second'))
os.makedirs(os.path.join(basedir, '/testdirectory/another/'))
"""You can create some additional empty files and directories if you want"""
"""(...)"""
"""Do the rest of your work here"""
然后,作为错误处理程序中的清理操作和测试结束时,不要忘记调用以下命令来删除临时文件:
shutil.rmtree(os.path.join(basedir, '/testdirectory/'))
使用真实目录的好处是,我们可以让python对操作系统差异和特性的抽象继续工作,而不必重新创建它们以使测试代码正确模拟真实的东西会遇到什么。
此答案中的代码示例中没有异常处理。您必须自己添加。