2024-10-02 00:39:05 发布
网友
如何复制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
write_file()
OSError
您必须模拟open()调用。您可以使用standard library ^{} function,或者使用^{} ^{} fixture;我个人更喜欢在这里使用标准库:
open()
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属性设置为异常可确保调用模拟对象将引发该异常
mock.patch()
module_under_test
open
side_effect
模拟open()远比尝试创建确切的文件系统环境容易,在这种环境下,内置的open()函数将引发异常。此外,您正在测试自己的代码如何正确处理OSError,而不是open()是否按设计工作
一些旁注:
f.close()
with ... as f:
with
e
except OSError as e:
as e
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")
您需要做两件事:
@pytest.fixture(scope="function") def change_test_dir(request): os.chdir('/') yield os.chdir(request.config.invocation_dir)
因为我假设你不被允许在/中写作
/
logging
您必须模拟} function ,或者使用^{} ^{} fixture ;我个人更喜欢在这里使用标准库:
open()
调用。您可以使用standard library ^{mock.patch()
上下文管理器安装程序在module_under_test
全局命名空间中放置模拟的open
对象,屏蔽内置的open()
函数。将side_effect
属性设置为异常可确保调用模拟对象将引发该异常模拟
open()
远比尝试创建确切的文件系统环境容易,在这种环境下,内置的open()
函数将引发异常。此外,您正在测试自己的代码如何正确处理OSError
,而不是open()
是否按设计工作一些旁注:
f.close()
;您将打开的文件用作上下文管理器(with ... as f:
),因此无论在with
块中发生什么,它都会自动关闭李>e
引用时,不要使用except OSError as e:
;删除as e
部分李>ERROR
级消息捕获到日志中李>您需要做两件事:
OSError
使open()
失败。为了实现这一点,you could use因为我假设你不被允许在
/
中写作logging
错误。见here相关问题 更多 >
编程相关推荐