| 1 |
# Copyright (c) Ansible project |
| 2 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 3 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 4 |
|
| 5 |
|
| 6 |
from __future__ import annotations |
| 7 |
|
| 8 |
import json |
| 9 |
import os |
| 10 |
import sys |
| 11 |
|
| 12 |
import pytest |
| 13 |
import yaml |
| 14 |
|
| 15 |
|
| 16 |
class UTHelper: |
| 17 |
TEST_SPEC_VALID_SECTIONS = ["anchors", "test_cases"] |
| 18 |
|
| 19 |
@staticmethod |
| 20 |
def from_spec(ansible_module, test_module, test_spec, mocks=None): |
| 21 |
helper = UTHelper(ansible_module, test_module, test_spec=test_spec, mocks=mocks) |
| 22 |
return helper |
| 23 |
|
| 24 |
@staticmethod |
| 25 |
def from_file(ansible_module, test_module, test_spec_filehandle, mocks=None): |
| 26 |
test_spec = yaml.safe_load(test_spec_filehandle) |
| 27 |
return UTHelper.from_spec(ansible_module, test_module, test_spec, mocks) |
| 28 |
|
| 29 |
# @TODO: calculate the test_module_name automatically, remove one more parameter |
| 30 |
@staticmethod |
| 31 |
def from_module(ansible_module, test_module_name, mocks=None): |
| 32 |
test_module = sys.modules[test_module_name] |
| 33 |
extensions = [".yaml", ".yml"] |
| 34 |
for ext in extensions: |
| 35 |
test_spec_filename = test_module.__file__.replace(".py", ext) |
| 36 |
if os.path.exists(test_spec_filename): |
| 37 |
with open(test_spec_filename) as test_spec_filehandle: |
| 38 |
return UTHelper.from_file(ansible_module, test_module, test_spec_filehandle, mocks=mocks) |
| 39 |
|
| 40 |
raise Exception( |
| 41 |
f"Cannot find test case file for {test_module.__file__} with one of the extensions: {extensions}" |
| 42 |
) |
| 43 |
|
| 44 |
def add_func_to_test_module(self, name, func): |
| 45 |
setattr(self.test_module, name, func) |
| 46 |
|
| 47 |
def __init__(self, ansible_module, test_module, test_spec, mocks=None): |
| 48 |
self.ansible_module = ansible_module |
| 49 |
self.test_module = test_module |
| 50 |
self.test_cases = [] |
| 51 |
self.fixtures = {} |
| 52 |
|
| 53 |
spec_diff = set(test_spec.keys()) - set(self.TEST_SPEC_VALID_SECTIONS) |
| 54 |
if spec_diff: |
| 55 |
raise ValueError(f"Test specification contain unknown keys: {', '.join(spec_diff)}") |
| 56 |
|
| 57 |
self.mocks_map = {m.name: m for m in mocks} if mocks else {} |
| 58 |
|
| 59 |
for spec_test_case in test_spec["test_cases"]: |
| 60 |
tc = ModuleTestCase.make_test_case(spec_test_case, test_module, self.mocks_map) |
| 61 |
self.test_cases.append(tc) |
| 62 |
self.fixtures.update(tc.fixtures) |
| 63 |
self.set_test_func() |
| 64 |
self.set_fixtures(self.fixtures) |
| 65 |
|
| 66 |
@property |
| 67 |
def runner(self): |
| 68 |
return Runner(self.ansible_module.main) |
| 69 |
|
| 70 |
def set_test_func(self): |
| 71 |
def make_test_func(tc): |
| 72 |
@pytest.mark.usefixtures(*self.fixtures) |
| 73 |
def _test_func(mocker, capfd, patch_ansible_module_uthelper): |
| 74 |
args = {} |
| 75 |
args.update(tc.input) |
| 76 |
if tc.flags.get("check"): |
| 77 |
args["_ansible_check_mode"] = tc.flags.get("check") |
| 78 |
if tc.flags.get("diff"): |
| 79 |
args["_ansible_diff"] = tc.flags.get("diff") |
| 80 |
with patch_ansible_module_uthelper(args): |
| 81 |
self.runner.run(mocker, capfd, tc) |
| 82 |
|
| 83 |
return _test_func |
| 84 |
|
| 85 |
for test_case in self.test_cases: |
| 86 |
func_name = test_case.id if test_case.id.startswith("test_") else f"test_{test_case.id}" |
| 87 |
if hasattr(self.test_module, func_name): |
| 88 |
raise ValueError(f"Name conflict: '{func_name}' already exists in module '{self.test_module.__name__}'") |
| 89 |
self.add_func_to_test_module(func_name, make_test_func(test_case)) |
| 90 |
|
| 91 |
def set_fixtures(self, fixtures): |
| 92 |
for name, fixture in fixtures.items(): |
| 93 |
self.add_func_to_test_module(name, fixture) |
| 94 |
|
| 95 |
|
| 96 |
class Runner: |
| 97 |
def __init__(self, module_main): |
| 98 |
self.module_main = module_main |
| 99 |
self.results = None |
| 100 |
|
| 101 |
def run(self, mocker, capfd, test_case): |
| 102 |
test_case.setup(mocker) |
| 103 |
self.pytest_module(capfd, test_case.flags) |
| 104 |
test_case.check(self.results) |
| 105 |
|
| 106 |
def pytest_module(self, capfd, flags): |
| 107 |
if flags.get("skip"): |
| 108 |
pytest.skip(flags.get("skip")) |
| 109 |
if flags.get("xfail"): |
| 110 |
pytest.xfail(flags.get("xfail")) |
| 111 |
|
| 112 |
with pytest.raises(SystemExit): |
| 113 |
(self.module_main)() |
| 114 |
|
| 115 |
out, err = capfd.readouterr() |
| 116 |
self.results = json.loads(out) |
| 117 |
|
| 118 |
|
| 119 |
class ModuleTestCase: |
| 120 |
def __init__(self, id, input, output, mocks, flags): |
| 121 |
self.id = id |
| 122 |
self.input = input |
| 123 |
self.output = output |
| 124 |
self.mock_specs = mocks |
| 125 |
self.mocks = {} |
| 126 |
self.flags = flags |
| 127 |
|
| 128 |
self._fixtures = {} |
| 129 |
|
| 130 |
def __str__(self): |
| 131 |
return ( |
| 132 |
f"<ModuleTestCase: id={self.id} {'input ' if self.input else ''}{'output ' if self.output else ''}" |
| 133 |
f"mocks=({', '.join(self.mocks.keys())}) flags={self.flags}>" |
| 134 |
) |
| 135 |
|
| 136 |
def __repr__(self): |
| 137 |
return f"ModuleTestCase(id={self.id}, input={self.input}, output={self.output}, mocks={self.mocks!r}, flags={self.flags})" |
| 138 |
|
| 139 |
@staticmethod |
| 140 |
def make_test_case(test_case_spec, test_module, mocks_map): |
| 141 |
tc = ModuleTestCase( |
| 142 |
id=test_case_spec["id"], |
| 143 |
input=test_case_spec.get("input", {}), |
| 144 |
output=test_case_spec.get("output", {}), |
| 145 |
mocks=test_case_spec.get("mocks", {}), |
| 146 |
flags=test_case_spec.get("flags", {}), |
| 147 |
) |
| 148 |
tc.build_mocks(mocks_map) |
| 149 |
return tc |
| 150 |
|
| 151 |
def build_mocks(self, mocks_map): |
| 152 |
for mock_name, mock_spec in self.mock_specs.items(): |
| 153 |
try: |
| 154 |
mock_class = mocks_map[mock_name] |
| 155 |
except KeyError as e: |
| 156 |
raise Exception(f"Cannot find TestCaseMock class for: {mock_name}") from e |
| 157 |
self.mocks[mock_name] = mock_class.build_mock(mock_spec) |
| 158 |
|
| 159 |
self._fixtures.update(self.mocks[mock_name].fixtures()) |
| 160 |
|
| 161 |
@property |
| 162 |
def fixtures(self): |
| 163 |
return dict(self._fixtures) |
| 164 |
|
| 165 |
def setup(self, mocker): |
| 166 |
self.setup_testcase(mocker) |
| 167 |
self.setup_mocks(mocker) |
| 168 |
|
| 169 |
def check(self, results): |
| 170 |
self.check_testcase(results) |
| 171 |
self.check_mocks(self, results) |
| 172 |
|
| 173 |
def setup_testcase(self, mocker): |
| 174 |
pass |
| 175 |
|
| 176 |
def setup_mocks(self, mocker): |
| 177 |
for mock in self.mocks.values(): |
| 178 |
mock.setup(mocker) |
| 179 |
|
| 180 |
def check_testcase(self, results): |
| 181 |
print(f"testcase =\n{self!r}") |
| 182 |
print(f"results =\n{results}") |
| 183 |
if "exception" in results: |
| 184 |
print(f"exception = \n{results['exception']}") |
| 185 |
|
| 186 |
for test_result in self.output: |
| 187 |
assert results[test_result] == self.output[test_result], ( |
| 188 |
f"'{test_result}': '{results[test_result]}' != '{self.output[test_result]}'" |
| 189 |
) |
| 190 |
|
| 191 |
def check_mocks(self, test_case, results): |
| 192 |
for mock in self.mocks.values(): |
| 193 |
mock.check(test_case, results) |
| 194 |
|
| 195 |
|
| 196 |
class TestCaseMock: |
| 197 |
@classmethod |
| 198 |
def build_mock(cls, mock_specs): |
| 199 |
return cls(mock_specs) |
| 200 |
|
| 201 |
def __str__(self): |
| 202 |
return f"<{self.__class__.__name__} specs={self.mock_specs}>" |
| 203 |
|
| 204 |
def __repr__(self): |
| 205 |
return f"{self.__class__.__name__}({self.mock_specs})" |
| 206 |
|
| 207 |
def __init__(self, mock_specs): |
| 208 |
self.mock_specs = mock_specs |
| 209 |
|
| 210 |
def fixtures(self): |
| 211 |
return {} |
| 212 |
|
| 213 |
def setup(self, mocker): |
| 214 |
pass |
| 215 |
|
| 216 |
def check(self, test_case, results): |
| 217 |
raise NotImplementedError() |
| 218 |
|
| 219 |
|
| 220 |
class RunCommandMock(TestCaseMock): |
| 221 |
name = "run_command" |
| 222 |
|
| 223 |
def fixtures(self): |
| 224 |
@pytest.fixture |
| 225 |
def patch_bin(mocker): |
| 226 |
def mockie(self_, path, *args, **kwargs): |
| 227 |
return f"/testbin/{path}" |
| 228 |
|
| 229 |
mocker.patch("ansible.module_utils.basic.AnsibleModule.get_bin_path", mockie) |
| 230 |
|
| 231 |
return {"patch_bin": patch_bin} |
| 232 |
|
| 233 |
def setup(self, mocker): |
| 234 |
def _results(): |
| 235 |
yield from [(x["rc"], x["out"], x["err"]) for x in self.mock_specs] |
| 236 |
raise Exception("testcase has not enough run_command calls") |
| 237 |
|
| 238 |
results = _results() |
| 239 |
|
| 240 |
def side_effect(self_, **kwargs): |
| 241 |
result = next(results) |
| 242 |
if kwargs.get("check_rc", False) and result[0] != 0: |
| 243 |
raise Exception(f"rc = {result[0]}") |
| 244 |
return result |
| 245 |
|
| 246 |
self.mock_run_cmd = mocker.patch( |
| 247 |
"ansible.module_utils.basic.AnsibleModule.run_command", side_effect=side_effect |
| 248 |
) |
| 249 |
|
| 250 |
def check(self, test_case, results): |
| 251 |
call_args_list = [(item[0][0], item[1]) for item in self.mock_run_cmd.call_args_list] |
| 252 |
expected_call_args_list = [(item["command"], item.get("environ", {})) for item in self.mock_specs] |
| 253 |
print(f"call args list =\n{call_args_list}") |
| 254 |
print(f"expected args list =\n{expected_call_args_list}") |
| 255 |
|
| 256 |
assert self.mock_run_cmd.call_count == len(self.mock_specs), ( |
| 257 |
f"{self.mock_run_cmd.call_count} != {len(self.mock_specs)}" |
| 258 |
) |
| 259 |
if self.mock_run_cmd.call_count: |
| 260 |
assert call_args_list == expected_call_args_list |