【问题标题】:Assertion not executing in Python Mock断言未在 Python Mock 中执行
【发布时间】:2017-09-17 03:37:33
【问题描述】:

我正在尝试对我正在构建的一些代码进行一些单元测试,但我看到了这种奇怪的行为,即使我将函数调用的返回值设置为 False,相关代码不执行,因此断言instance.fail_json.assert_called_with(msg='Not enough parameters specified.')fails。

我还有什么需要设置的吗?

项目.py:

def main():
   # define the available arguments/parameters that a user can pass
   # to the module
   module_args = dict(
      name=dict(type='str', required=True),
      ticktype=dict(type='str'),
      path=dict(type='str'),
      dbrp=dict(type='str'),
      state=dict(type='str', required=True, choices=["present", "absent"]),
      enable=dict(type='str', default="no", choices=["yes","no","da","net"])
   )

   required_if=[
      [ "state", "present", ["name", "type", "path", "dbrp", "enabled"] ],
      [ "state", "absent", ["name"]]
   ]

   # seed the result dict in the object
   # we primarily care about changed and state
   # change is if this module effectively modified the target
   # state will include any data that you want your module to pass back
   # for consumption, for exampole, in a subsequent task
   result = dict(
      changed=False,
      original_message='',
      message=''
   )

   # the AnsibleModule object will be our abstraction working with Ansible
   # this includes instantiation, a couple of common attr would be the
   # args/params passed to the execution, as well as if the module
   # supports check mode
   module = AnsibleModule(
      argument_spec=module_args,
      supports_check_mode=False
   )

   # if the user is working with this module in only check mode we do not
   # want to make any changes to the environment, just return the current
   # state with no modifications
   if module.check_mode:
      return result

   return_val = run_module(module)
   return_val = True
   if return_val is True:
      module.exit_json(changed=True, msg="Project updated.")
   else:
      module.fail_json(changed=True, msg="Not enough parameters found.")

test_project.py:

@patch('library.project.run_module')
@patch('library.project.AnsibleModule')
def test_main_exit_functionality_failure(mock_module, mock_run_module):
   """
   project - test_main_exit_functionality - failure
   """
   instance = mock_module.return_value

   # What happens when the run_module returns false
   # that is run_module fails
   mock_run_module.return_value = False

   project.main()

   # AnsibleModule.exit_json should not activated
   assert_equals(instance.fail_json.call_count, 0)

   #AnsibleModule.fail_json should be called
   instance.fail_json.assert_called_with(msg='Not enough parameters 
   specified.')

【问题讨论】:

  • 这不是真正的minimal, complete, and verifiable example - 没有上下文很难阅读代码。您应该非常仔细地阅读您的测试代码,以确保它说出了您认为的内容。我认为主要问题可能是最后一行。您必须将所有预期参数传递给assert_called_with。它应该是instance.fail_json.assert_called_with(changed=True, msg='Not enough parameters specified.')
  • 我会回去更新代码以反映上述标准。但是,如果我将 mock_run_module 的返回值设置为 'False':mock_run_module.return_value=False 将导致 main 中的 if-else 分支执行 false 并因此随后运行 module.fail_json(changed=True, msg="Not enough parameters specified 。”)?为什么它不运行是我的主要断开连接。 if return_value is True: module.exit_json(changed=True, msg=""Project updated.") else: module.fail_json(changed=True, msg="Not enough parameters found."

标签: python python-2.7 unit-testing python-mock


【解决方案1】:

重新阅读您的生产代码。在检查它是否为真之前,它会将 return_val 设置为 True:

...

return_val = run_module(module)

return_val = True

if return_val is True:
    ...

无论run_module 返回什么,return_val 始终为真,因此无论您在测试中做什么,生产代码将始终执行 if-else 检查的“真”分支。

【讨论】:

    猜你喜欢
    • 2014-12-08
    • 1970-01-01
    • 1970-01-01
    • 2014-12-04
    • 1970-01-01
    • 1970-01-01
    • 2012-08-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多