Python: 如何测试递归方法?

Python: How can I test a recursive method?

长期听众,第一次来电。

我写了一个 python 2.7 方法,它对给定的目录执行递归扫描(使用 scandir),该目录有一些 find-like 功能(即,您可以指定 mindepthmaxdepth):

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

问题是,我这辈子都想不出 best/proper 编写单元测试的方法,让我可以 mock 递归 scandir正确调用 测试我的最小和最大扫描参数的行为。

通常我会使用 scandir.walk 进行扫描(我已经编写了一个适当的可测试版本),但我确实需要 DirEntry 个实例的信息 scandir吐出来。

如有任何想法,我们将不胜感激。谢谢!

我可以提供一个替代解决方案:

创建目录结构

扭转局面:问问自己 'what is it I want?'。我认为它有一个固定的目录结构来测试。我们可以用makedirsos包函数来创建这样的结构体,直接调用真正的scandir,但固定search_path为固定的[=33] =]:当前工作目录的子目录。

例如做类似的事情:

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 对 OS 差异和特性的抽象继续工作,而不必重新创建它们来进行测试代码正确地模仿了真实的东西会遇到什么。

此答案中的代码示例中没有异常处理。您必须自己添加。