【问题标题】:Python: How can I test a recursive method?Python:如何测试递归方法?
【发布时间】:2017-03-23 22:00:15
【问题描述】:

长时间聆听,第一次来电。

我编写了一个 python 2.7 方法,该方法对具有一些 find 类似功能的给定目录执行递归扫描(使用 scandir)(即,您可以指定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

问题是,我一生都无法找出编写单元测试的最佳/正确方法,这将使我能够正确地mock递归scandir调用 测试我的最小和最大扫描参数的行为。

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

任何想法将不胜感激。谢谢!

【问题讨论】:

  • 我能够通过使用scandir 作为基础设置walk-like 方法(即返回一个(root, dir_entries, file_entries) 的元组)并使用类似的方法来回到可测试状态mock 最初为 walk 工作的策略,但我很想弄清楚如何处理最初的递归问题。谢谢!

标签: python-2.7 recursion scandir


【解决方案1】:

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

创建您的目录结构

扭转局面:问问自己“我想要什么?”。我认为它有一个固定的目录结构来测试。我们可以使用os 包函数如makedirs 来创建这样的结构,并简单地调用真正的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 对操作系统差异和特性的抽象继续起作用,而不必重新创建它们以使测试代码正确地模仿真实事物会遇到的情况。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-29
    • 2011-01-15
    • 1970-01-01
    • 1970-01-01
    • 2017-04-12
    • 2018-08-04
    • 2015-08-21
    • 1970-01-01
    相关资源
    最近更新 更多