如何对删除失败的文件进行单元测试?

问题描述 投票:0回答:1

我的代码中有一个os.remove(),有时在本地运行时由于OSError 13 - Permission Denied而失败-因此,我设置了一个try-except。我的自动化测试(Travis CI)在Linux VM实例上运行,因此出于覆盖目的,我不知道如何使os.remove失败。

我有哪些选择-如何强制执行except块?另外,如何使用Python删除文件保护?


Note:不能选择在调用测试方法之前将其从测试代码中删除;该方法本身获取要删除的文件:

from pathlib import Path

paths = [str(x) for x in Path("directory/").iterdir() if 'abc' in x.stem]
if len(paths) > 0:  # if files are removed beforehand, len(paths) == 0
    try:
        [os.remove(p) for p in paths]
    except:
        pass  # stuff here
python automated-tests pytest code-coverage travis-ci
1个回答
0
投票

您可以使用unittest.mock.patch修补os.remove并将OSError指定为side_effect

from unittest.mock import patch

...

with patch('os.remove') as mock_remove:
    mock_remove.side_effect = OSError('Permission Denied')
    try:
        [os.remove(p) for p in paths]
    except OSError as e:
        pass # handle error here
© www.soinside.com 2019 - 2024. All rights reserved.