如果文件丢失,我如何可重复地 (py) 测试打开文件的代码的故障模式?

How can I reproducibly (py)test the failure mode of code that opens a file if the file is missing?

我想编写一个 pytest 案例,用于在文件不存在的情况下打开文件的函数的行为。

我认为问题归结为另一个问题,即“我如何确定文件系统上不存在文件路径?”

import pytest

def file_content(file_name):
    with open(file_name, "r") as f:
        return f.read()

def test_file_content_file_not_found():
    file_name_of_inexistent_file = "???"
    with pytest.raises(FileNotFoundError):
        file_content(file_name_of_inexistent_file)

test_file_content_file_not_found()

"???" 表示我认为一些很棒的工具实现了一种合理且安全的方式来生成文件名或模拟文件系统,以确保保证失败,但也不需要更改文件系统。

目前,我有一个小的辅助函数可以生成随机字符串,测试它们是否是现有文件,如果不是则返回。这样我就可以模拟所需的行为。但是,我想一定有更标准的方法来实现这一点。

最简单的方法是使用内置 tmp_path fixture 生成一个唯一的空目录:

def test_does_not_exist(tmp_path):
    with pytest.raises(FileNotFoundError):
        file_content(tmp_path.joinpath('dne'))

tmp_path 是根据测试生成的,开始时为空,因此 dne 永远不会存在

如果您想要一个通用的非 pytest 解决方案,您可以直接使用 tempfile.TemporaryDirectory

with tempfile.TemporaryDirectory() as tmpdir:
    with pytest.raises(FileNotFoundError):
        file_content(os.path.join(tmpdir, 'dne'))

免责声明:我是 pytest 核心开发人员