Ansible: How to unit test module without using `pytest`
by yaobin.wen
Ansible uses pytest for unit testing. Usually, one cannot test the run_module() function directly because it requires two things:
stdinasAnsibleModulereads its input arguments from the standard input.exit_json()andfail_json()callsys.exit()which will cause the test program to exit.
Therefore, usually one can only test the functions that the Ansible module calls. But the patch_ansible_module() function makes it possible to test the Ansible module directly.
However, sometimes the project may not use pytest as the unit testing tool. Instead, the project may use Python’s built-in unittest module. In this case, we wouldn’t be able to use the function patch_ansible_module().
But I implemented this demo to show how to unit test an AnsibleModule in real mode and check mode using Python’s unittest module. Basically,
- Implement
class MyAnsibleModule(AnsibleModuleBasic.AnsibleModule)in order to change the behaviors ofexit_json()andfail_json()so, when called, they don’t actually quit the test program. - Use
mockto replace the realAnsibleModulewithMyAnsibleModule. - Set
_ansible_check_modeinansible.module_utils.basic._ANSIBLE_ARGSin order to use the check mode.
Go take a look at the code.
Tags: Tech