| 1 |
.. |
| 2 |
Copyright (c) Ansible Project |
| 3 |
GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 4 |
SPDX-License-Identifier: GPL-3.0-or-later |
| 5 |
|
| 6 |
.. _ansible_collections.community.general.docsite.guide_uthelper: |
| 7 |
|
| 8 |
UTHelper Guide |
| 9 |
============== |
| 10 |
|
| 11 |
Introduction |
| 12 |
^^^^^^^^^^^^ |
| 13 |
|
| 14 |
``UTHelper`` was written to reduce the boilerplate code used in unit tests for modules. |
| 15 |
It was originally written to handle tests of modules that run external commands using ``AnsibleModule.run_command()``. |
| 16 |
At the time of writing (Feb 2025) that remains the only type of tests you can use |
| 17 |
``UTHelper`` for, but it aims to provide support for other types of interactions. |
| 18 |
|
| 19 |
Until now, there are many different ways to implement unit tests that validate a module based on the execution of external commands. See some examples: |
| 20 |
|
| 21 |
* `test_apk.py <https://github.com/ansible-collections/community.general/blob/10.3.0/tests/unit/plugins/modules/test_apk.py>`_ - A very simple one |
| 22 |
* `test_bootc_manage.py <https://github.com/ansible-collections/community.general/blob/10.3.0/tests/unit/plugins/modules/test_bootc_manage.py>`_ - |
| 23 |
This one has more test cases, but do notice how the code is repeated amongst them. |
| 24 |
* `test_modprobe.py <https://github.com/ansible-collections/community.general/blob/10.3.0/tests/unit/plugins/modules/test_modprobe.py>`_ - |
| 25 |
This one has 15 tests in it, but to achieve that it declares 8 classes repeating quite a lot of code. |
| 26 |
|
| 27 |
As you can notice, there is no consistency in the way these tests are executed - |
| 28 |
they all do the same thing eventually, but each one is written in a very distinct way. |
| 29 |
|
| 30 |
``UTHelper`` aims to: |
| 31 |
|
| 32 |
* provide a consistent idiom to define unit tests |
| 33 |
* reduce the code to a bare minimal, and |
| 34 |
* define tests as data instead |
| 35 |
* allow the test cases definition to be expressed not only as a Python data structure but also as YAML content |
| 36 |
|
| 37 |
Quickstart |
| 38 |
"""""""""" |
| 39 |
|
| 40 |
To use UTHelper, your test module will need only a bare minimal of code: |
| 41 |
|
| 42 |
.. code-block:: python |
| 43 |
|
| 44 |
# tests/unit/plugin/modules/test_ansible_module.py |
| 45 |
from ansible_collections.community.general.plugins.modules import ansible_module |
| 46 |
from .uthelper import UTHelper, RunCommandMock |
| 47 |
|
| 48 |
|
| 49 |
UTHelper.from_module(ansible_module, __name__, mocks=[RunCommandMock]) |
| 50 |
|
| 51 |
Then, in the test specification file, you have: |
| 52 |
|
| 53 |
.. code-block:: yaml |
| 54 |
|
| 55 |
# tests/unit/plugin/modules/test_ansible_module.yaml |
| 56 |
test_cases: |
| 57 |
- id: test_ansible_module |
| 58 |
flags: |
| 59 |
diff: true |
| 60 |
input: |
| 61 |
state: present |
| 62 |
name: Roger the Shrubber |
| 63 |
output: |
| 64 |
shrubbery: |
| 65 |
looks: nice |
| 66 |
price: not too expensive |
| 67 |
changed: true |
| 68 |
diff: |
| 69 |
before: |
| 70 |
shrubbery: null |
| 71 |
after: |
| 72 |
shrubbery: |
| 73 |
looks: nice |
| 74 |
price: not too expensive |
| 75 |
mocks: |
| 76 |
run_command: |
| 77 |
- command: [/testbin/shrubber, --version] |
| 78 |
rc: 0 |
| 79 |
out: "2.80.0\n" |
| 80 |
err: '' |
| 81 |
- command: [/testbin/shrubber, --make-shrubbery] |
| 82 |
rc: 0 |
| 83 |
out: 'Shrubbery created' |
| 84 |
err: '' |
| 85 |
|
| 86 |
.. note:: |
| 87 |
|
| 88 |
If you prefer to pick a different YAML file for the test cases, or if you prefer to define them in plain Python, |
| 89 |
you can use the convenience methods ``UTHelper.from_file()`` and ``UTHelper.from_spec()``, respectively. |
| 90 |
See more details below. |
| 91 |
|
| 92 |
|
| 93 |
Using ``UTHelper`` |
| 94 |
^^^^^^^^^^^^^^^^^^ |
| 95 |
|
| 96 |
Test Module |
| 97 |
""""""""""" |
| 98 |
|
| 99 |
``UTHelper`` is **strictly for unit tests**. To use it, you import the ``.uthelper.UTHelper`` class. |
| 100 |
As mentioned in different parts of this guide, there are three different mechanisms to load the test cases. |
| 101 |
|
| 102 |
.. seealso:: |
| 103 |
|
| 104 |
See the UTHelper class reference below for API details on the three different mechanisms. |
| 105 |
|
| 106 |
|
| 107 |
The easies and most recommended way of using ``UTHelper`` is literally the example shown. |
| 108 |
See a real world example at |
| 109 |
`test_gconftool2.py <https://github.com/ansible-collections/community.general/blob/10.3.0/tests/unit/plugins/modules/test_gconftool2.py>`_. |
| 110 |
|
| 111 |
The ``from_module()`` method will pick the filename of the test module up (in the example above, ``tests/unit/plugins/modules/test_gconftool2.py``) |
| 112 |
and it will search for ``tests/unit/plugins/modules/test_gconftool2.yaml`` (or ``.yml`` if that is not found). |
| 113 |
In that file it will expect to find the test specification expressed in YAML format, conforming to the structure described below LINK LINK LINK. |
| 114 |
|
| 115 |
If you prefer to read the test specifications a different file path, use ``from_file()`` passing the file handle for the YAML file. |
| 116 |
|
| 117 |
And, if for any reason you prefer or need to pass the data structure rather than dealing with YAML files, use the ``from_spec()`` method. |
| 118 |
A real world example for that can be found at |
| 119 |
`test_snap.py <https://github.com/ansible-collections/community.general/blob/main/tests/unit/plugins/modules/test_snap.py>`_. |
| 120 |
|
| 121 |
|
| 122 |
Test Specification |
| 123 |
"""""""""""""""""" |
| 124 |
|
| 125 |
The structure of the test specification data is described below. |
| 126 |
|
| 127 |
Top level |
| 128 |
--------- |
| 129 |
|
| 130 |
At the top level there are two accepted keys: |
| 131 |
|
| 132 |
- ``anchors: dict`` |
| 133 |
Optional. Placeholder for you to define YAML anchors that can be repeated in the test cases. |
| 134 |
Its contents are never accessed directly by test Helper. |
| 135 |
- ``test_cases: list`` |
| 136 |
Mandatory. List of test cases, see below for definition. |
| 137 |
|
| 138 |
Test cases |
| 139 |
---------- |
| 140 |
|
| 141 |
You write the test cases with five elements: |
| 142 |
|
| 143 |
- ``id: str`` |
| 144 |
Mandatory. Used to identify the test case. |
| 145 |
|
| 146 |
- ``flags: dict`` |
| 147 |
Optional. Flags controling the behavior of the test case. All flags are optional. Accepted flags: |
| 148 |
|
| 149 |
* ``check: bool``: set to ``true`` if the module is to be executed in **check mode**. |
| 150 |
* ``diff: bool``: set to ``true`` if the module is to be executed in **diff mode**. |
| 151 |
* ``skip: str``: set the test case to be skipped, providing the message for ``pytest.skip()``. |
| 152 |
* ``xfail: str``: set the test case to expect failure, providing the message for ``pytest.xfail()``. |
| 153 |
|
| 154 |
- ``input: dict`` |
| 155 |
Optional. Parameters for the Ansible module, it can be empty. |
| 156 |
|
| 157 |
- ``output: dict`` |
| 158 |
Optional. Expected return values from the Ansible module. |
| 159 |
All RV names are used here are expected to be found in the module output, but not all RVs in the output must be here. |
| 160 |
It can include special RVs such as ``changed`` and ``diff``. |
| 161 |
It can be empty. |
| 162 |
|
| 163 |
- ``mocks: dict`` |
| 164 |
Optional. Mocked interactions, ``run_command`` being the only one supported for now. |
| 165 |
Each key in this dictionary refers to one subclass of ``TestCaseMock`` and its |
| 166 |
structure is dictated by the ``TestCaseMock`` subclass implementation. |
| 167 |
All keys are expected to be named using snake case, as in ``run_command``. |
| 168 |
The ``TestCaseMock`` subclass is responsible for defining the name used in the test specification. |
| 169 |
The structure for that specification is dependent on the implementing class. |
| 170 |
See more details below for the implementation of ``RunCommandMock`` |
| 171 |
|
| 172 |
Example using YAML |
| 173 |
------------------ |
| 174 |
|
| 175 |
We recommend you use ``UTHelper`` reading the test specifications from a YAML file. |
| 176 |
See an example below of how one actually looks like (excerpt from ``test_opkg.yaml``): |
| 177 |
|
| 178 |
.. code-block:: yaml |
| 179 |
|
| 180 |
--- |
| 181 |
anchors: |
| 182 |
environ: &env-def {environ_update: {LANGUAGE: C, LC_ALL: C}, check_rc: false} |
| 183 |
test_cases: |
| 184 |
- id: install_zlibdev |
| 185 |
input: |
| 186 |
name: zlib-dev |
| 187 |
state: present |
| 188 |
output: |
| 189 |
msg: installed 1 package(s) |
| 190 |
mocks: |
| 191 |
run_command: |
| 192 |
- command: [/testbin/opkg, --version] |
| 193 |
environ: *env-def |
| 194 |
rc: 0 |
| 195 |
out: '' |
| 196 |
err: '' |
| 197 |
- command: [/testbin/opkg, list-installed, zlib-dev] |
| 198 |
environ: *env-def |
| 199 |
rc: 0 |
| 200 |
out: '' |
| 201 |
err: '' |
| 202 |
- command: [/testbin/opkg, install, zlib-dev] |
| 203 |
environ: *env-def |
| 204 |
rc: 0 |
| 205 |
out: | |
| 206 |
Installing zlib-dev (1.2.11-6) to root... |
| 207 |
Downloading https://downloads.openwrt.org/releases/22.03.0/packages/mips_24kc/base/zlib-dev_1.2.11-6_mips_24kc.ipk |
| 208 |
Installing zlib (1.2.11-6) to root... |
| 209 |
Downloading https://downloads.openwrt.org/releases/22.03.0/packages/mips_24kc/base/zlib_1.2.11-6_mips_24kc.ipk |
| 210 |
Configuring zlib. |
| 211 |
Configuring zlib-dev. |
| 212 |
err: '' |
| 213 |
- command: [/testbin/opkg, list-installed, zlib-dev] |
| 214 |
environ: *env-def |
| 215 |
rc: 0 |
| 216 |
out: | |
| 217 |
zlib-dev - 1.2.11-6 |
| 218 |
err: '' |
| 219 |
- id: install_zlibdev_present |
| 220 |
input: |
| 221 |
name: zlib-dev |
| 222 |
state: present |
| 223 |
output: |
| 224 |
msg: package(s) already present |
| 225 |
mocks: |
| 226 |
run_command: |
| 227 |
- command: [/testbin/opkg, --version] |
| 228 |
environ: *env-def |
| 229 |
rc: 0 |
| 230 |
out: '' |
| 231 |
err: '' |
| 232 |
- command: [/testbin/opkg, list-installed, zlib-dev] |
| 233 |
environ: *env-def |
| 234 |
rc: 0 |
| 235 |
out: | |
| 236 |
zlib-dev - 1.2.11-6 |
| 237 |
err: '' |
| 238 |
|
| 239 |
TestCaseMocks Specifications |
| 240 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 241 |
|
| 242 |
The ``TestCaseMock`` subclass is free to define the expected data structure. |
| 243 |
|
| 244 |
RunCommandMock Specification |
| 245 |
"""""""""""""""""""""""""""" |
| 246 |
|
| 247 |
``RunCommandMock`` mocks can be specified with the key ``run_command`` and it expects a ``list`` in which elements follow the structure: |
| 248 |
|
| 249 |
- ``command: Union[list, str]`` |
| 250 |
Mandatory. The command that is expected to be executed by the module. It corresponds to the parameter ``args`` of the ``AnsibleModule.run_command()`` call. |
| 251 |
It can be either a list or a string, though the list form is generally recommended. |
| 252 |
- ``environ: dict`` |
| 253 |
Mandatory. All other parameters passed to the ``AnsibleModule.run_command()`` call. |
| 254 |
Most commonly used are ``environ_update`` and ``check_rc``. |
| 255 |
Must include all parameters the Ansible module uses in the ``AnsibleModule.run_command()`` call, otherwise the test will fail. |
| 256 |
- ``rc: int`` |
| 257 |
Mandatory. The return code for the command execution. |
| 258 |
As per usual in bash scripting, a value of ``0`` means success, whereas any other number is an error code. |
| 259 |
- ``out: str`` |
| 260 |
Mandatory. The *stdout* result of the command execution, as one single string containing zero or more lines. |
| 261 |
- ``err: str`` |
| 262 |
Mandatory. The *stderr* result of the command execution, as one single string containing zero or more lines. |
| 263 |
|
| 264 |
|
| 265 |
``UTHelper`` Reference |
| 266 |
^^^^^^^^^^^^^^^^^^^^^^ |
| 267 |
|
| 268 |
.. py:module:: .uthelper |
| 269 |
|
| 270 |
.. py:class:: UTHelper |
| 271 |
|
| 272 |
A class to encapsulate unit tests. |
| 273 |
|
| 274 |
.. py:staticmethod:: from_spec(ansible_module, test_module, test_spec, mocks=None) |
| 275 |
|
| 276 |
Creates an ``UTHelper`` instance from a given test specification. |
| 277 |
|
| 278 |
:param ansible_module: The Ansible module to be tested. |
| 279 |
:type ansible_module: :py:class:`types.ModuleType` |
| 280 |
:param test_module: The test module. |
| 281 |
:type test_module: :py:class:`types.ModuleType` |
| 282 |
:param test_spec: The test specification. |
| 283 |
:type test_spec: dict |
| 284 |
:param mocks: List of ``TestCaseMocks`` to be used during testing. Currently only ``RunCommandMock`` exists. |
| 285 |
:type mocks: list or None |
| 286 |
:return: An ``UTHelper`` instance. |
| 287 |
:rtype: UTHelper |
| 288 |
|
| 289 |
Example usage of ``from_spec()``: |
| 290 |
|
| 291 |
.. code-block:: python |
| 292 |
|
| 293 |
import sys |
| 294 |
|
| 295 |
from ansible_collections.community.general.plugins.modules import ansible_module |
| 296 |
from .uthelper import UTHelper, RunCommandMock |
| 297 |
|
| 298 |
TEST_SPEC = dict( |
| 299 |
test_cases=[ |
| 300 |
... |
| 301 |
] |
| 302 |
) |
| 303 |
|
| 304 |
helper = UTHelper.from_spec(ansible_module, sys.modules[__name__], TEST_SPEC, mocks=[RunCommandMock]) |
| 305 |
|
| 306 |
.. py:staticmethod:: from_file(ansible_module, test_module, test_spec_filehandle, mocks=None) |
| 307 |
|
| 308 |
Creates an ``UTHelper`` instance from a test specification file. |
| 309 |
|
| 310 |
:param ansible_module: The Ansible module to be tested. |
| 311 |
:type ansible_module: :py:class:`types.ModuleType` |
| 312 |
:param test_module: The test module. |
| 313 |
:type test_module: :py:class:`types.ModuleType` |
| 314 |
:param test_spec_filehandle: A file handle to an file stream handle providing the test specification in YAML format. |
| 315 |
:type test_spec_filehandle: ``file-like object`` |
| 316 |
:param mocks: List of ``TestCaseMocks`` to be used during testing. Currently only ``RunCommandMock`` exists. |
| 317 |
:type mocks: list or None |
| 318 |
:return: An ``UTHelper`` instance. |
| 319 |
:rtype: UTHelper |
| 320 |
|
| 321 |
Example usage of ``from_file()``: |
| 322 |
|
| 323 |
.. code-block:: python |
| 324 |
|
| 325 |
import sys |
| 326 |
|
| 327 |
from ansible_collections.community.general.plugins.modules import ansible_module |
| 328 |
from .uthelper import UTHelper, RunCommandMock |
| 329 |
|
| 330 |
with open("test_spec.yaml", "r") as test_spec_filehandle: |
| 331 |
helper = UTHelper.from_file(ansible_module, sys.modules[__name__], test_spec_filehandle, mocks=[RunCommandMock]) |
| 332 |
|
| 333 |
.. py:staticmethod:: from_module(ansible_module, test_module_name, mocks=None) |
| 334 |
|
| 335 |
Creates an ``UTHelper`` instance from a given Ansible module and test module. |
| 336 |
|
| 337 |
:param ansible_module: The Ansible module to be tested. |
| 338 |
:type ansible_module: :py:class:`types.ModuleType` |
| 339 |
:param test_module_name: The name of the test module. It works if passed ``__name__``. |
| 340 |
:type test_module_name: str |
| 341 |
:param mocks: List of ``TestCaseMocks`` to be used during testing. Currently only ``RunCommandMock`` exists. |
| 342 |
:type mocks: list or None |
| 343 |
:return: An ``UTHelper`` instance. |
| 344 |
:rtype: UTHelper |
| 345 |
|
| 346 |
Example usage of ``from_module()``: |
| 347 |
|
| 348 |
.. code-block:: python |
| 349 |
|
| 350 |
from ansible_collections.community.general.plugins.modules import ansible_module |
| 351 |
from .uthelper import UTHelper, RunCommandMock |
| 352 |
|
| 353 |
# Example usage |
| 354 |
helper = UTHelper.from_module(ansible_module, __name__, mocks=[RunCommandMock]) |
| 355 |
|
| 356 |
|
| 357 |
Creating TestCaseMocks |
| 358 |
^^^^^^^^^^^^^^^^^^^^^^ |
| 359 |
|
| 360 |
To create a new ``TestCaseMock`` you must extend that class and implement the relevant parts: |
| 361 |
|
| 362 |
.. code-block:: python |
| 363 |
|
| 364 |
class ShrubberyMock(TestCaseMock): |
| 365 |
# this name is mandatory, it is the name used in the test specification |
| 366 |
name = "shrubbery" |
| 367 |
|
| 368 |
def setup(self, mocker): |
| 369 |
# perform setup, commonly using mocker to patch some other piece of code |
| 370 |
... |
| 371 |
|
| 372 |
def check(self, test_case, results): |
| 373 |
# verify the tst execution met the expectations of the test case |
| 374 |
# for example the function was called as many times as it should |
| 375 |
... |
| 376 |
|
| 377 |
def fixtures(self): |
| 378 |
# returns a dict mapping names to pytest fixtures that should be used for the test case |
| 379 |
# for example, in RunCommandMock it creates a fixture that patches AnsibleModule.get_bin_path |
| 380 |
... |
| 381 |
|
| 382 |
Caveats |
| 383 |
^^^^^^^ |
| 384 |
|
| 385 |
Known issues/opportunities for improvement: |
| 386 |
|
| 387 |
* Only one ``UTHelper`` per test module: UTHelper injects a test function with a fixed name into the module's namespace, |
| 388 |
so placing a second ``UTHelper`` instance is going to overwrite the function created by the first one. |
| 389 |
* Order of elements in module's namespace is not consistent across executions in Python 3.5, so if adding more tests to the test module |
| 390 |
might make Test Helper add its function before or after the other test functions. |
| 391 |
In the community.general collection the CI processes uses ``pytest-xdist`` to paralellize and distribute the tests, |
| 392 |
and it requires the order of the tests to be consistent. |
| 393 |
|
| 394 |
.. versionadded:: 7.5.0 |