| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
"""Tests for anta.cli.get.utils.""" |
| 5 |
|
| 6 |
from __future__ import annotations |
| 7 |
|
| 8 |
from contextlib import AbstractContextManager, nullcontext |
| 9 |
from pathlib import Path |
| 10 |
from typing import Any, ClassVar |
| 11 |
from unittest.mock import MagicMock, patch |
| 12 |
|
| 13 |
import pytest |
| 14 |
import requests |
| 15 |
|
| 16 |
from anta.cli.get.utils import create_inventory_from_ansible, create_inventory_from_cvp, extract_examples, find_tests_in_module, get_cv_token, print_test |
| 17 |
from anta.inventory import AntaInventory |
| 18 |
from anta.models import AntaCommand, AntaTemplate, AntaTest |
| 19 |
|
| 20 |
DATA_DIR: Path = Path(__file__).parents[3].resolve() / "data" |
| 21 |
|
| 22 |
|
| 23 |
@pytest.mark.parametrize( |
| 24 |
"verify_cert", |
| 25 |
[ |
| 26 |
pytest.param(True, id="Verify cert enabled"), |
| 27 |
pytest.param(False, id="Verify cert disabled"), |
| 28 |
], |
| 29 |
) |
| 30 |
def test_get_cv_token(verify_cert: bool) -> None: |
| 31 |
"""Test anta.get.utils.get_cv_token.""" |
| 32 |
ip_addr = "42.42.42.42" |
| 33 |
username = "ant" |
| 34 |
password = "formica" |
| 35 |
|
| 36 |
with patch("anta.cli.get.utils.requests.request") as patched_request: |
| 37 |
mocked_ret = MagicMock(autospec=requests.Response) |
| 38 |
mocked_ret.json.return_value = {"sessionId": "simple"} |
| 39 |
patched_request.return_value = mocked_ret |
| 40 |
res = get_cv_token(ip_addr, username, password, verify_cert=verify_cert) |
| 41 |
patched_request.assert_called_once_with( |
| 42 |
"POST", |
| 43 |
"https://42.42.42.42/cvpservice/login/authenticate.do", |
| 44 |
headers={"Content-Type": "application/json", "Accept": "application/json"}, |
| 45 |
data='{"userId": "ant", "password": "formica"}', |
| 46 |
verify=verify_cert, |
| 47 |
timeout=10, |
| 48 |
) |
| 49 |
assert res == "simple" |
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
CVP_INVENTORY = [ |
| 54 |
{ |
| 55 |
"hostname": "device1", |
| 56 |
"containerName": "DC1", |
| 57 |
"ipAddress": "10.20.20.97", |
| 58 |
}, |
| 59 |
{ |
| 60 |
"hostname": "device2", |
| 61 |
"containerName": "DC2", |
| 62 |
"ipAddress": "10.20.20.98", |
| 63 |
}, |
| 64 |
{ |
| 65 |
"hostname": "device3", |
| 66 |
"containerName": "", |
| 67 |
"ipAddress": "10.20.20.99", |
| 68 |
}, |
| 69 |
] |
| 70 |
|
| 71 |
|
| 72 |
@pytest.mark.parametrize( |
| 73 |
"inventory", |
| 74 |
[ |
| 75 |
pytest.param(CVP_INVENTORY, id="some container"), |
| 76 |
pytest.param([], id="empty_inventory"), |
| 77 |
], |
| 78 |
) |
| 79 |
def test_create_inventory_from_cvp(tmp_path: Path, inventory: list[dict[str, Any]]) -> None: |
| 80 |
"""Test anta.get.utils.create_inventory_from_cvp.""" |
| 81 |
output = tmp_path / "output.yml" |
| 82 |
|
| 83 |
create_inventory_from_cvp(inventory, output) |
| 84 |
|
| 85 |
assert output.exists() |
| 86 |
|
| 87 |
inv = AntaInventory.parse(str(output), "user", "pass") |
| 88 |
assert len(inv) == len(inventory) |
| 89 |
|
| 90 |
|
| 91 |
@pytest.mark.parametrize( |
| 92 |
("inventory_filename", "ansible_group", "expected_raise", "expected_log", "expected_inv_length"), |
| 93 |
[ |
| 94 |
pytest.param("ansible_inventory.yml", None, nullcontext(), None, 7, id="no group"), |
| 95 |
pytest.param("ansible_inventory.yml", "ATD_LEAFS", nullcontext(), None, 4, id="group found"), |
| 96 |
pytest.param( |
| 97 |
"ansible_inventory.yml", |
| 98 |
"DUMMY", |
| 99 |
pytest.raises(ValueError, match=r"Group DUMMY not found in Ansible inventory"), |
| 100 |
None, |
| 101 |
0, |
| 102 |
id="group not found", |
| 103 |
), |
| 104 |
pytest.param( |
| 105 |
"empty_ansible_inventory.yml", |
| 106 |
None, |
| 107 |
pytest.raises(ValueError, match=r"Ansible inventory .* is empty"), |
| 108 |
None, |
| 109 |
0, |
| 110 |
id="empty inventory", |
| 111 |
), |
| 112 |
pytest.param( |
| 113 |
"wrong_ansible_inventory.yml", |
| 114 |
None, |
| 115 |
pytest.raises(ValueError, match=r"Could not parse"), |
| 116 |
None, |
| 117 |
0, |
| 118 |
id="os error inventory", |
| 119 |
), |
| 120 |
pytest.param( |
| 121 |
"ansible_inventory_with_vault.yml", |
| 122 |
None, |
| 123 |
pytest.raises(ValueError, match=r"Could not parse"), |
| 124 |
"`anta get from-ansible` does not support inline vaulted variables", |
| 125 |
0, |
| 126 |
id="Vault variable in inventory", |
| 127 |
), |
| 128 |
pytest.param( |
| 129 |
"ansible_inventory_unknown_yaml_tag.yml", |
| 130 |
None, |
| 131 |
pytest.raises(ValueError, match=r"Could not parse"), |
| 132 |
None, |
| 133 |
0, |
| 134 |
id="Unknown YAML tag in inventory", |
| 135 |
), |
| 136 |
], |
| 137 |
) |
| 138 |
def test_create_inventory_from_ansible( |
| 139 |
caplog: pytest.LogCaptureFixture, |
| 140 |
tmp_path: Path, |
| 141 |
inventory_filename: Path, |
| 142 |
ansible_group: str | None, |
| 143 |
expected_raise: AbstractContextManager[Exception], |
| 144 |
expected_log: str | None, |
| 145 |
expected_inv_length: int, |
| 146 |
) -> None: |
| 147 |
"""Test anta.get.utils.create_inventory_from_ansible.""" |
| 148 |
target_file = tmp_path / "inventory.yml" |
| 149 |
inventory_file_path = DATA_DIR / inventory_filename |
| 150 |
|
| 151 |
with expected_raise: |
| 152 |
if ansible_group: |
| 153 |
create_inventory_from_ansible(inventory_file_path, target_file, ansible_group) |
| 154 |
else: |
| 155 |
create_inventory_from_ansible(inventory_file_path, target_file) |
| 156 |
|
| 157 |
assert target_file.exists() |
| 158 |
inv = AntaInventory().parse(str(target_file), "user", "pass") |
| 159 |
assert len(inv) == expected_inv_length |
| 160 |
if not isinstance(expected_raise, nullcontext): |
| 161 |
assert not target_file.exists() |
| 162 |
if expected_log: |
| 163 |
assert expected_log in caplog.text |
| 164 |
|
| 165 |
|
| 166 |
class MissingExampleTest(AntaTest): |
| 167 |
"""ANTA test that always succeed but has no Examples section.""" |
| 168 |
|
| 169 |
categories: ClassVar[list[str]] = [] |
| 170 |
commands: ClassVar[list[AntaCommand | AntaTemplate]] = [] |
| 171 |
|
| 172 |
@AntaTest.anta_test |
| 173 |
def test(self) -> None: |
| 174 |
"""Test function.""" |
| 175 |
self.result.is_success() |
| 176 |
|
| 177 |
|
| 178 |
class EmptyExampleTest(AntaTest): |
| 179 |
"""ANTA test that always succeed but has an empty Examples section. |
| 180 |
|
| 181 |
Examples |
| 182 |
-------- |
| 183 |
""" |
| 184 |
|
| 185 |
|
| 186 |
|
| 187 |
|
| 188 |
categories: ClassVar[list[str]] = [] |
| 189 |
commands: ClassVar[list[AntaCommand | AntaTemplate]] = [] |
| 190 |
|
| 191 |
@AntaTest.anta_test |
| 192 |
def test(self) -> None: |
| 193 |
"""Test function.""" |
| 194 |
self.result.is_success() |
| 195 |
|
| 196 |
|
| 197 |
class TypoExampleTest(AntaTest): |
| 198 |
"""ANTA test that always succeed but has a Typo in the test name in the example. |
| 199 |
|
| 200 |
Notice capital P in TyPo below. |
| 201 |
|
| 202 |
Examples |
| 203 |
-------- |
| 204 |
```yaml |
| 205 |
tests.units.cli.get.test_utils: |
| 206 |
- TyPoExampleTest: |
| 207 |
``` |
| 208 |
""" |
| 209 |
|
| 210 |
|
| 211 |
|
| 212 |
|
| 213 |
categories: ClassVar[list[str]] = [] |
| 214 |
commands: ClassVar[list[AntaCommand | AntaTemplate]] = [] |
| 215 |
|
| 216 |
@AntaTest.anta_test |
| 217 |
def test(self) -> None: |
| 218 |
"""Test function.""" |
| 219 |
self.result.is_success() |
| 220 |
|
| 221 |
|
| 222 |
def test_find_tests_in_module() -> None: |
| 223 |
"""Test find_tests_examples. |
| 224 |
|
| 225 |
Only testing the failure scenarii not tested through test_commands. |
| 226 |
TODO: expand |
| 227 |
""" |
| 228 |
with pytest.raises(ValueError, match=r"Error when importing"): |
| 229 |
find_tests_in_module("blah", "UnusedTestName") |
| 230 |
|
| 231 |
|
| 232 |
def test_print_test() -> None: |
| 233 |
"""Test print_test.""" |
| 234 |
with pytest.raises(ValueError, match=r"Could not find the name of the test"): |
| 235 |
print_test(TypoExampleTest) |
| 236 |
with pytest.raises(LookupError, match=r"is missing an Example"): |
| 237 |
print_test(MissingExampleTest) |
| 238 |
with pytest.raises(LookupError, match=r"is missing an Example"): |
| 239 |
print_test(EmptyExampleTest) |
| 240 |
|
| 241 |
|
| 242 |
def test_extract_examples() -> None: |
| 243 |
"""Test extract_examples. |
| 244 |
|
| 245 |
Only testing the case where the 'Examples' is missing as everything else |
| 246 |
is covered already in test_commands.py. |
| 247 |
""" |
| 248 |
assert MissingExampleTest.__doc__ is not None |
| 249 |
assert EmptyExampleTest.__doc__ is not None |
| 250 |
assert extract_examples(MissingExampleTest.__doc__) is None |
| 251 |
assert extract_examples(EmptyExampleTest.__doc__) is None |