python-如何模拟BDD步骤文件
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python-如何模拟BDD步骤文件,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2164字,纯文字阅读大概需要4分钟。
内容图文
![python-如何模拟BDD步骤文件](/upload/InfoBanner/zyjiaocheng/685/08dce52f413744819361998190cdc829.jpg)
我想模拟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
解决方法:
因此,要回答我自己的问题,您必须使用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)要容易得多.
内容总结
以上是互联网集市为您收集整理的python-如何模拟BDD步骤文件全部内容,希望文章能够帮你解决python-如何模拟BDD步骤文件所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。