我正在尝试对我正在构建的某些代码执行某些单元测试,但我看到这种奇怪的行为,即使我将函数调用的返回值设置为 False ,相关代码不执行,因此断言instance.fail_json.assert_called_with(msg='Not enough parameters specified.')
失败。
我还需要设置其他内容吗?
project.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.')
答案 0 :(得分:0)
重新阅读您的生产代码。在检查它是否为True之前,它在行上将return_val设置为True:
...
return_val = run_module(module)
return_val = True
if return_val is True:
...
无论return_val
返回什么, run_module
始终为真,因此无论您在测试中做什么,生产代码都将始终执行if-else检查的'true'分支。 / p>