编程语言
首页 > 编程语言> > python-如何模拟BDD步骤文件

python-如何模拟BDD步骤文件

作者:互联网

我想模拟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)要容易得多.

标签:mocking,bdd,python-behave,python
来源: https://codeday.me/bug/20191026/1934179.html