我想模拟os.path.exists方法的行为,这样当os.path.exists报告文件/文件夹不存在时,我可以验证我的脚本是否正常运行。
@when("Service starts with input file that does not exist")
def step_impl(context):
"""
:type context: behave.runner.Context
"""
json_file_path = "fake_file_path"
mock_os_path = mock.Mock()
mock_os_path.exists.return_value = False
context.returncode = dicom_send_service.launch(json_file_path)
mock_os_path.exists.assert_called_once_with(json_file_abspath)
如何将模拟注入我的脚本?我试着用
@mock.patch("mymodule.os.path")
@when("Service starts with input file that does not exist")
def step_impl(context, mock_os_path):
但是,当我运行方法时,python返回:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/behave/model.py", line 1456, in run
match.run(runner.context)
File "/usr/local/lib/python2.7/dist-packages/behave/model.py", line 1903, in run
self.func(context, *args, **kwargs)
TypeError: step_impl() takes exactly 2 arguments (1 given)
正如您所看到的,step_impl方法基于声明需要2个参数,但是BDD只用1(上下文值)调用它,并且没有拾取模拟注释。
以下是我正在测试的代码:
import os
def validate(json_file_path):
"""Method which validates the JSON file, an error message is returned if the file fails verification.
json_file_path -- the path to the file with the message configuration details"""
if not os.path.exists(json_file_path):
return "Could not find file at path {0}".format(json_file_path)
...
return ""
def launch(json_file_path):
error_message = valid(json_file_path)
if error_message:
print(error_message)
return 1
答案 0 :(得分:4)
所以要回答我自己的问题,你必须使用with mock.patch
语法:
with mock.patch('name of thing to mock') as name_of_mock:
所以我上面的例子会变成:
@when("Service starts with input file that does not exist")
def step_impl(context):
"""
:type context: behave.runner.Context
"""
json_file_path = "fake_file_path"
# This is where the magic happens
with mock.patch ('os.path') as mock_os_path:
mock_os_path.exists.return_value = False
context.returncode = dicom_send_service.launch(json_file_path)
mock_os_path.exists.assert_called_once_with(json_file_abspath)
我已经对它进行了测试,它就像一个魅力。比使用Java中的Mockito或Powermock等其他模拟框架要容易得多。