如何测试需要文件存在的方法?

Chu*_*uck 9 python unit-testing

我第一次使用Python创建了一个库,我正试图利用这个项目中的机会来学习单元测试.我写了第一个方法,我想为它编写一些单元测试.(是的,我知道TDD要求我先写测试,我会到那里,真的.)

该方法相当简单,但它期望该类具有file属性集,该属性指向现有文件,并且该文件是某种类型的存档(目前仅使用zip文件,tar,rar等. ,稍后补充).该方法应该返回存档中的文件数.

我在我的项目中创建了一个文件夹,files其中包含一些示例文件,我手动测试了该方法,并且它到目前为止仍然有效.手动测试如下所示,位于archive_file.py文件中:

if __name__ == '__main__':
    archive = ArchiveFile()

    script_path = path.realpath(__file__)
    parent_dir = path.abspath(path.join(script_path, os.pardir))
    targ_dir = path.join(parent_dir, 'files')
    targ_file = path.join(targ_dir, 'test.zip' )

    archive.file = targ_file

    print(archive.file_count())
Run Code Online (Sandbox Code Playgroud)

我所做的就是确保所印刷的内容是我所期望的内容test.zip.

这是file_count看起来像:

def file_count(self):
    """Return the number of files in the archive."""
    if self.file == None:
        return -1

    with ZipFile(self.file) as zip:
        members = zip.namelist()
        # Remove folder members if there are any.
        pruned = [item for item in members if not item.endswith('/')]
        return len(pruned)
Run Code Online (Sandbox Code Playgroud)

由于某些原因,我直接将其转换为单元测试似乎是错误的,其中一些原因可能无效.我指望测试文件相对于当前脚本文件的精确位置,我需要大量手动创建的存档文件样本,以确保我测试的变量足够多,当然,我是手动将返回值与我期望的值进行比较,因为我知道测试档案中有多少文件.

似乎对我来说,这应该是自动的,尽可能的,但它似乎也这样做将是非常复杂的.

为这样的类方法创建单元测试的正确方法是什么?

Chu*_*uck 0

Oasiscircledm03514在这方面非常有帮助,并最终引导我找到了正确的答案,特别是 dm 对后续问题的回答。

需要做的是使用该mock库创建一个假版本,ZipFile该假版本不会反对实际上不存在文件,而是在使用该nameslist方法时返回有效列表。

@unittest.mock.patch('comicfile.ZipFile')
def test_page_count(self, mock_zip_file):
    comic_file = ComicFile()
    members = ['dir/', 'dir/file1', 'dir/file2']
    mock_zip_file.return_value.__enter__.return_value.namelist.return_value \
                = members
    self.assertEqual(2, self.comic_file.page_count())
Run Code Online (Sandbox Code Playgroud)

上面的部分__enter__.return_value是必要的,因为在正在测试的代码中,ZipFile实例是在上下文管理器中创建的。