Pytest:复制OSError的单元测试

2024-10-02 00:39:05 发布

您现在位置:Python中文网/ 问答频道 /正文

如何复制OSError,以便知道我的异常工作

def write_file():
    try: 
        with open('file.txt', "w+") as f:
            f.write("sth")
        f.close()
    except OSError as e:
        logging.error("OSError occured")

我想使用pytest为函数write_file()编写单元测试。如何模拟OSError


Tags: txtcloseloggingdefaswitherroropen
2条回答

您必须模拟open()调用。您可以使用standard library ^{} function,或者使用^{} ^{} fixture;我个人更喜欢在这里使用标准库:

import pytest
import logging
from unittest import mock
from module_under_test import write_file

def test_write_file_error(caplog):
    caplog.clear()
    with mock.patch("module_under_test.open") as mock_open:
        mock_open.side_effect = OSError
        write_file()

    assert caplog.record_tuples == [("root", logging.ERROR, "OSError occured")]

mock.patch()上下文管理器安装程序在module_under_test全局命名空间中放置模拟的open对象,屏蔽内置的open()函数。将side_effect属性设置为异常可确保调用模拟对象将引发该异常

模拟open()远比尝试创建确切的文件系统环境容易,在这种环境下,内置的open()函数将引发异常。此外,您正在测试自己的代码如何正确处理OSError,而不是open()是否按设计工作

一些旁注:

  • 不需要调用f.close();您将打开的文件用作上下文管理器(with ... as f:),因此无论在with块中发生什么,它都会自动关闭
  • 正确的拼写是发生(doubler):-)
  • 当您不打算使用异常的e引用时,不要使用except OSError as e:;删除as e部分
  • 如果使用^{} function,那么异常和完整回溯将作为ERROR级消息捕获到日志中
def write_file():
    try: 
        with open('file.txt', "w+") as f:
            f.write("sth")
    except OSError:
        logging.exception("Failed to write to file.txt")

您需要做两件事:

  1. 使用OSError使open()失败。为了实现这一点,you could use
@pytest.fixture(scope="function")
def change_test_dir(request):
    os.chdir('/')
    yield
    os.chdir(request.config.invocation_dir)

因为我假设你不被允许在/中写作

  1. 您想测试是否发生了正确的logging错误。见here

相关问题 更多 >

    热门问题