-1
我想對我正在構建的一些代碼實現一些單元測試,但我看到這種奇怪的行爲,即使我將函數調用的返回值設置爲False,相關代碼不會執行,因此斷言instance.fail_json.assert_called_with(msg='Not enough parameters specified.')
失敗。聲明不在Python中執行模擬
有沒有別的東西,我需要被設置?
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.')
這實際上並不是一個[最小,完整和可驗證的示例](https://stackoverflow.com/help/mcve) - 讀取沒有上下文的代碼非常困難。你應該仔細閱讀你的測試代碼,以確保它說明了你的想法。 我認爲主要問題可能是最後一行。你必須將期望的參數傳遞給'assert_called_with'。它應該讀取'instance.fail_json.assert_called_with(changed = True,msg ='沒有足夠的參數 指定。')' – ryanh119
我會返回並更新代碼以反映上述標準。但是,如果我將mock_run_module的返回值設置爲'False': '''mock_run_module.return_value = False''' 將會導致main中的if-else分支執行false並因此隨後運行module.fail_json( changed = True,msg =「沒有足夠的參數指定。」)?爲什麼沒有運行是我的主要脫節。 '''如果return_value爲True: module.exit_json(changed = True,msg =「」Project updated。「) else: module.fail_json(changed = True,msg =」找不到足夠的參數。 '' – 1up