如何解决如何修补或模拟python单元测试中的后续API调用?
我具有以下功能
def test_dir_creation():
if not os.path.exists(root_dir_path):
raise Exception("Root dir don't exits")
if not os.path.exists(log_dir_path):
raise Exception("Log dir don't exits")
if not os.path.exists(subscription_handle_dir_path):
raise Exception("subscription_handle_dir_path dir don't exits")
我要测试三个条件,我的测试用例如下-
@mock.patch("os.path.exists",return_value=False)
def test_args_parser_when_root_dir_dont_exists(*mocks):
with pytest.raises(Exception) as excinfo:
args_parser()
expected_message = "Root dir don't exits"
assert expected_message in str(excinfo)
此测试用例有效,但我也想测试其他两个条件,该怎么做?
我如何修补类似os.path.exists(log_dir_path)== False的东西?
解决方法
在您的示例中,您正在嘲笑整个功能的调用 。如果您想要模拟更改行为,建议使用上下文管理器。
import os.path
def do_test():
with mock.patch('os.path.exists',return_value='hello'):
assert os.path.exists() == 'hello'
with mock.patch('os.path.exists',return_value=-5):
assert os.path.exists() == -5
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。