| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
"""test anta.device.py.""" |
| 5 |
|
| 6 |
from __future__ import annotations |
| 7 |
|
| 8 |
from json import load as json_load |
| 9 |
from json import loads as json_loads |
| 10 |
from pathlib import Path |
| 11 |
from typing import TYPE_CHECKING, Any, Literal |
| 12 |
|
| 13 |
import pytest |
| 14 |
from pydantic import ValidationError |
| 15 |
from yaml import safe_load |
| 16 |
|
| 17 |
from anta.catalog import AntaCatalog, AntaCatalogFile, AntaTestDefinition |
| 18 |
from anta.models import AntaTest |
| 19 |
from anta.tests.interfaces import VerifyL3MTU |
| 20 |
from anta.tests.mlag import VerifyMlagStatus |
| 21 |
from anta.tests.software import VerifyEOSVersion |
| 22 |
from anta.tests.system import ( |
| 23 |
VerifyAgentLogs, |
| 24 |
VerifyCoredump, |
| 25 |
VerifyCPUUtilization, |
| 26 |
VerifyFileSystemUtilization, |
| 27 |
VerifyMemoryUtilization, |
| 28 |
VerifyNTP, |
| 29 |
VerifyReloadCause, |
| 30 |
VerifyUptime, |
| 31 |
) |
| 32 |
from tests.units.test_models import FakeTestWithInput |
| 33 |
|
| 34 |
if TYPE_CHECKING: |
| 35 |
from _pytest.mark.structures import ParameterSet |
| 36 |
|
| 37 |
DATA_DIR: Path = Path(__file__).parent.parent.resolve() / "data" |
| 38 |
|
| 39 |
INIT_CATALOG_PARAMS: list[ParameterSet] = [ |
| 40 |
pytest.param("test_catalog.yml", "yaml", [(VerifyEOSVersion, VerifyEOSVersion.Input(versions=["4.31.1F"]))], id="test_catalog_yaml"), |
| 41 |
pytest.param("test_catalog.json", "json", [(VerifyEOSVersion, VerifyEOSVersion.Input(versions=["4.31.1F"]))], id="test_catalog_json"), |
| 42 |
pytest.param( |
| 43 |
"test_catalog_with_tags.yml", |
| 44 |
"yaml", |
| 45 |
[ |
| 46 |
( |
| 47 |
VerifyUptime, |
| 48 |
VerifyUptime.Input( |
| 49 |
minimum=10, |
| 50 |
filters=VerifyUptime.Input.Filters(tags={"spine"}), |
| 51 |
), |
| 52 |
), |
| 53 |
( |
| 54 |
VerifyUptime, |
| 55 |
VerifyUptime.Input( |
| 56 |
minimum=9, |
| 57 |
filters=VerifyUptime.Input.Filters(tags={"leaf"}), |
| 58 |
), |
| 59 |
), |
| 60 |
(VerifyReloadCause, {"filters": {"tags": ["spine", "leaf"]}}), |
| 61 |
(VerifyCoredump, VerifyCoredump.Input()), |
| 62 |
(VerifyAgentLogs, AntaTest.Input()), |
| 63 |
(VerifyCPUUtilization, None), |
| 64 |
(VerifyMemoryUtilization, None), |
| 65 |
(VerifyFileSystemUtilization, None), |
| 66 |
(VerifyNTP, {}), |
| 67 |
(VerifyMlagStatus, {"filters": {"tags": ["leaf"]}}), |
| 68 |
(VerifyL3MTU, {"mtu": 1500, "filters": {"tags": ["spine"]}}), |
| 69 |
], |
| 70 |
id="test_catalog_with_tags", |
| 71 |
), |
| 72 |
pytest.param("test_empty_catalog.yml", "yaml", [], id="test_empty_catalog"), |
| 73 |
pytest.param("test_empty_dict_catalog.yml", "yaml", [], id="test_empty_dict_catalog"), |
| 74 |
] |
| 75 |
CATALOG_PARSE_FAIL_PARAMS: list[ParameterSet] = [ |
| 76 |
pytest.param( |
| 77 |
"test_catalog_wrong_format.toto", |
| 78 |
"toto", |
| 79 |
"'toto' is not a valid format for an AntaCatalog file. Only 'yaml' and 'json' are supported.", |
| 80 |
id="undefined_tests", |
| 81 |
), |
| 82 |
pytest.param("test_catalog_invalid_json.json", "json", "JSONDecodeError", id="invalid_json"), |
| 83 |
pytest.param("test_catalog_with_undefined_tests.yml", "yaml", "FakeTest is not defined in Python module anta.tests.software", id="undefined_tests"), |
| 84 |
pytest.param("test_catalog_with_undefined_module.yml", "yaml", "Module named anta.tests.undefined cannot be imported", id="undefined_module"), |
| 85 |
pytest.param( |
| 86 |
"test_catalog_with_syntax_error_module.yml", |
| 87 |
"yaml", |
| 88 |
"Value error, Module named tests.data.syntax_error cannot be imported. Verify that the module exists and there is no Python syntax issues.", |
| 89 |
id="syntax_error", |
| 90 |
), |
| 91 |
pytest.param( |
| 92 |
"test_catalog_with_undefined_module_nested.yml", |
| 93 |
"yaml", |
| 94 |
"Module named undefined from package anta.tests cannot be imported", |
| 95 |
id="undefined_module_nested", |
| 96 |
), |
| 97 |
pytest.param( |
| 98 |
"test_catalog_not_a_list.yml", |
| 99 |
"yaml", |
| 100 |
"Value error, Syntax error when parsing: True\nIt must be a list of ANTA tests. Check the test catalog.", |
| 101 |
id="not_a_list", |
| 102 |
), |
| 103 |
pytest.param( |
| 104 |
"test_catalog_test_definition_not_a_dict.yml", |
| 105 |
"yaml", |
| 106 |
"Value error, Syntax error when parsing: VerifyEOSVersion\nIt must be a dictionary. Check the test catalog.", |
| 107 |
id="test_definition_not_a_dict", |
| 108 |
), |
| 109 |
pytest.param( |
| 110 |
"test_catalog_test_definition_multiple_dicts.yml", |
| 111 |
"yaml", |
| 112 |
"Value error, Syntax error when parsing: {'VerifyEOSVersion': {'versions': ['4.25.4M', '4.26.1F']}, 'VerifyTerminAttrVersion': {'versions': ['4.25.4M']}}\n" |
| 113 |
"It must be a dictionary with a single entry. Check the indentation in the test catalog.", |
| 114 |
id="test_definition_multiple_dicts", |
| 115 |
), |
| 116 |
pytest.param("test_catalog_wrong_type.yml", "yaml", "must be a dict, got str", id="wrong_type_after_parsing"), |
| 117 |
] |
| 118 |
CATALOG_FROM_DICT_FAIL_PARAMS: list[ParameterSet] = [ |
| 119 |
pytest.param("test_catalog_with_undefined_tests.yml", "FakeTest is not defined in Python module anta.tests.software", id="undefined_tests"), |
| 120 |
pytest.param("test_catalog_wrong_type.yml", "Wrong input type for catalog data, must be a dict, got str", id="wrong_type"), |
| 121 |
] |
| 122 |
CATALOG_FROM_LIST_FAIL_PARAMS: list[ParameterSet] = [ |
| 123 |
pytest.param([(FakeTestWithInput, AntaTest.Input())], "Test input has type AntaTest.Input but expected type FakeTestWithInput.Input", id="wrong_inputs"), |
| 124 |
pytest.param([(None, None)], "Input should be a subclass of AntaTest", id="no_test"), |
| 125 |
pytest.param( |
| 126 |
[(FakeTestWithInput, None)], |
| 127 |
"FakeTestWithInput test inputs are not valid: 1 validation error for Input\n\tstring\n\t Field required", |
| 128 |
id="no_input_when_required", |
| 129 |
), |
| 130 |
pytest.param( |
| 131 |
[(FakeTestWithInput, {"string": True})], |
| 132 |
"FakeTestWithInput test inputs are not valid: 1 validation error for Input\n\tstring\n\t Input should be a valid string", |
| 133 |
id="wrong_input_type", |
| 134 |
), |
| 135 |
] |
| 136 |
TESTS_SETTER_FAIL_PARAMS: list[ParameterSet] = [ |
| 137 |
pytest.param("not_a_list", "The catalog must contain a list of tests", id="not_a_list"), |
| 138 |
pytest.param([42, 43], "A test in the catalog must be an AntaTestDefinition instance", id="not_a_list_of_test_definitions"), |
| 139 |
] |
| 140 |
|
| 141 |
|
| 142 |
class TestAntaCatalog: |
| 143 |
"""Tests for anta.catalog.AntaCatalog.""" |
| 144 |
|
| 145 |
@pytest.mark.parametrize(("filename", "file_format", "tests"), INIT_CATALOG_PARAMS) |
| 146 |
def test_parse(self, filename: str, file_format: Literal["yaml", "json"], tests: list[tuple[type[AntaTest], AntaTest.Input | dict[str, Any] | None]]) -> None: |
| 147 |
"""Instantiate AntaCatalog from a file.""" |
| 148 |
catalog: AntaCatalog = AntaCatalog.parse(DATA_DIR / filename, file_format=file_format) |
| 149 |
|
| 150 |
assert len(catalog.tests) == len(tests) |
| 151 |
for test_id, (test, inputs_data) in enumerate(tests): |
| 152 |
assert catalog.tests[test_id].test == test |
| 153 |
if inputs_data is not None: |
| 154 |
inputs = test.Input(**inputs_data) if isinstance(inputs_data, dict) else inputs_data |
| 155 |
assert inputs == catalog.tests[test_id].inputs |
| 156 |
|
| 157 |
@pytest.mark.parametrize(("filename", "file_format", "tests"), INIT_CATALOG_PARAMS) |
| 158 |
def test_from_list( |
| 159 |
self, filename: str, file_format: Literal["yaml", "json"], tests: list[tuple[type[AntaTest], AntaTest.Input | dict[str, Any] | None]] |
| 160 |
) -> None: |
| 161 |
"""Instantiate AntaCatalog from a list.""" |
| 162 |
catalog: AntaCatalog = AntaCatalog.from_list(tests) |
| 163 |
|
| 164 |
assert len(catalog.tests) == len(tests) |
| 165 |
for test_id, (test, inputs_data) in enumerate(tests): |
| 166 |
assert catalog.tests[test_id].test == test |
| 167 |
if inputs_data is not None: |
| 168 |
inputs = test.Input(**inputs_data) if isinstance(inputs_data, dict) else inputs_data |
| 169 |
assert inputs == catalog.tests[test_id].inputs |
| 170 |
|
| 171 |
@pytest.mark.parametrize(("filename", "file_format", "tests"), INIT_CATALOG_PARAMS) |
| 172 |
def test_from_dict( |
| 173 |
self, filename: str, file_format: Literal["yaml", "json"], tests: list[tuple[type[AntaTest], AntaTest.Input | dict[str, Any] | None]] |
| 174 |
) -> None: |
| 175 |
"""Instantiate AntaCatalog from a dict.""" |
| 176 |
file = DATA_DIR / filename |
| 177 |
with file.open(encoding="UTF-8") as f: |
| 178 |
data = safe_load(f) if file_format == "yaml" else json_load(f) |
| 179 |
catalog: AntaCatalog = AntaCatalog.from_dict(data) |
| 180 |
|
| 181 |
assert len(catalog.tests) == len(tests) |
| 182 |
for test_id, (test, inputs_data) in enumerate(tests): |
| 183 |
assert catalog.tests[test_id].test == test |
| 184 |
if inputs_data is not None: |
| 185 |
inputs = test.Input(**inputs_data) if isinstance(inputs_data, dict) else inputs_data |
| 186 |
assert inputs == catalog.tests[test_id].inputs |
| 187 |
|
| 188 |
@pytest.mark.parametrize(("filename", "file_format", "error"), CATALOG_PARSE_FAIL_PARAMS) |
| 189 |
def test_parse_fail(self, filename: str, file_format: Literal["yaml", "json"], error: str) -> None: |
| 190 |
"""Errors when instantiating AntaCatalog from a file.""" |
| 191 |
with pytest.raises((ValidationError, TypeError, ValueError, OSError)) as exec_info: |
| 192 |
AntaCatalog.parse(DATA_DIR / filename, file_format=file_format) |
| 193 |
if isinstance(exec_info.value, ValidationError): |
| 194 |
assert error in exec_info.value.errors()[0]["msg"] |
| 195 |
else: |
| 196 |
assert error in str(exec_info) |
| 197 |
|
| 198 |
def test_parse_fail_parsing(self, caplog: pytest.LogCaptureFixture) -> None: |
| 199 |
"""Errors when instantiating AntaCatalog from a file.""" |
| 200 |
with pytest.raises(FileNotFoundError) as exec_info: |
| 201 |
AntaCatalog.parse(DATA_DIR / "catalog_does_not_exist.yml") |
| 202 |
assert "No such file or directory" in str(exec_info) |
| 203 |
assert len(caplog.record_tuples) >= 1 |
| 204 |
_, _, message = caplog.record_tuples[0] |
| 205 |
assert "Unable to parse ANTA Test Catalog file" in message |
| 206 |
assert "FileNotFoundError: [Errno 2] No such file or directory" in message |
| 207 |
|
| 208 |
@pytest.mark.parametrize(("tests", "error"), CATALOG_FROM_LIST_FAIL_PARAMS) |
| 209 |
def test_from_list_fail(self, tests: list[tuple[type[AntaTest], AntaTest.Input | dict[str, Any] | None]], error: str) -> None: |
| 210 |
"""Errors when instantiating AntaCatalog from a list of tuples.""" |
| 211 |
with pytest.raises(ValidationError) as exec_info: |
| 212 |
AntaCatalog.from_list(tests) |
| 213 |
assert error in exec_info.value.errors()[0]["msg"] |
| 214 |
|
| 215 |
@pytest.mark.parametrize(("filename", "error"), CATALOG_FROM_DICT_FAIL_PARAMS) |
| 216 |
def test_from_dict_fail(self, filename: str, error: str) -> None: |
| 217 |
"""Errors when instantiating AntaCatalog from a list of tuples.""" |
| 218 |
file = DATA_DIR / filename |
| 219 |
with file.open(encoding="UTF-8") as f: |
| 220 |
data = safe_load(f) |
| 221 |
with pytest.raises((ValidationError, TypeError)) as exec_info: |
| 222 |
AntaCatalog.from_dict(data) |
| 223 |
if isinstance(exec_info.value, ValidationError): |
| 224 |
assert error in exec_info.value.errors()[0]["msg"] |
| 225 |
else: |
| 226 |
assert error in str(exec_info) |
| 227 |
|
| 228 |
def test_filename(self) -> None: |
| 229 |
"""Test filename.""" |
| 230 |
catalog = AntaCatalog(filename="test") |
| 231 |
assert catalog.filename == Path("test") |
| 232 |
catalog = AntaCatalog(filename=Path("test")) |
| 233 |
assert catalog.filename == Path("test") |
| 234 |
|
| 235 |
@pytest.mark.parametrize(("filename", "file_format", "tests"), INIT_CATALOG_PARAMS) |
| 236 |
def test__tests_setter_success( |
| 237 |
self, |
| 238 |
filename: str, |
| 239 |
file_format: Literal["yaml", "json"], |
| 240 |
tests: list[tuple[type[AntaTest], AntaTest.Input | dict[str, Any] | None]], |
| 241 |
) -> None: |
| 242 |
"""Success when setting AntaCatalog.tests from a list of tuples.""" |
| 243 |
catalog = AntaCatalog() |
| 244 |
catalog.tests = [AntaTestDefinition(test=test, inputs=inputs) for test, inputs in tests] |
| 245 |
assert len(catalog.tests) == len(tests) |
| 246 |
for test_id, (test, inputs_data) in enumerate(tests): |
| 247 |
assert catalog.tests[test_id].test == test |
| 248 |
if inputs_data is not None: |
| 249 |
inputs = test.Input(**inputs_data) if isinstance(inputs_data, dict) else inputs_data |
| 250 |
assert inputs == catalog.tests[test_id].inputs |
| 251 |
|
| 252 |
@pytest.mark.parametrize(("tests", "error"), TESTS_SETTER_FAIL_PARAMS) |
| 253 |
def test__tests_setter_fail(self, tests: list[Any], error: str) -> None: |
| 254 |
"""Errors when setting AntaCatalog.tests from a list of tuples.""" |
| 255 |
catalog = AntaCatalog() |
| 256 |
with pytest.raises(TypeError) as exec_info: |
| 257 |
catalog.tests = tests |
| 258 |
assert error in str(exec_info) |
| 259 |
|
| 260 |
def test_build_indexes_all(self) -> None: |
| 261 |
"""Test AntaCatalog.build_indexes().""" |
| 262 |
catalog: AntaCatalog = AntaCatalog.parse(DATA_DIR / "test_catalog_with_tags.yml") |
| 263 |
catalog.build_indexes() |
| 264 |
assert len(catalog.tag_to_tests[None]) == 6 |
| 265 |
assert "leaf" in catalog.tag_to_tests |
| 266 |
assert len(catalog.tag_to_tests["leaf"]) == 3 |
| 267 |
all_unique_tests = catalog.tag_to_tests[None] |
| 268 |
for tests in catalog.tag_to_tests.values(): |
| 269 |
all_unique_tests.update(tests) |
| 270 |
assert len(all_unique_tests) == 11 |
| 271 |
assert catalog.indexes_built is True |
| 272 |
|
| 273 |
def test_build_indexes_filtered(self) -> None: |
| 274 |
"""Test AntaCatalog.build_indexes().""" |
| 275 |
catalog: AntaCatalog = AntaCatalog.parse(DATA_DIR / "test_catalog_with_tags.yml") |
| 276 |
catalog.build_indexes({"VerifyUptime", "VerifyCoredump", "VerifyL3MTU"}) |
| 277 |
assert "leaf" in catalog.tag_to_tests |
| 278 |
assert len(catalog.tag_to_tests["leaf"]) == 1 |
| 279 |
assert len(catalog.tag_to_tests[None]) == 1 |
| 280 |
all_unique_tests = catalog.tag_to_tests[None] |
| 281 |
for tests in catalog.tag_to_tests.values(): |
| 282 |
all_unique_tests.update(tests) |
| 283 |
assert len(all_unique_tests) == 4 |
| 284 |
assert catalog.indexes_built is True |
| 285 |
|
| 286 |
def test_get_tests_by_tags(self) -> None: |
| 287 |
"""Test AntaCatalog.get_tests_by_tags().""" |
| 288 |
catalog: AntaCatalog = AntaCatalog.parse(DATA_DIR / "test_catalog_with_tags.yml") |
| 289 |
catalog.build_indexes() |
| 290 |
tests: set[AntaTestDefinition] = catalog.get_tests_by_tags(tags={"leaf"}) |
| 291 |
assert len(tests) == 3 |
| 292 |
tests = catalog.get_tests_by_tags(tags={"leaf", "spine"}, strict=True) |
| 293 |
assert len(tests) == 1 |
| 294 |
|
| 295 |
def test_merge_catalogs(self) -> None: |
| 296 |
"""Test the merge_catalogs function.""" |
| 297 |
|
| 298 |
small_catalog = AntaCatalog.parse(DATA_DIR / "test_catalog.yml") |
| 299 |
medium_catalog = AntaCatalog.parse(DATA_DIR / "test_catalog_medium.yml") |
| 300 |
tagged_catalog = AntaCatalog.parse(DATA_DIR / "test_catalog_with_tags.yml") |
| 301 |
|
| 302 |
|
| 303 |
final_catalog = AntaCatalog.merge_catalogs([small_catalog, medium_catalog, tagged_catalog]) |
| 304 |
assert len(final_catalog.tests) == len(small_catalog.tests) + len(medium_catalog.tests) + len(tagged_catalog.tests) |
| 305 |
|
| 306 |
def test_merge(self) -> None: |
| 307 |
"""Test AntaCatalog.merge().""" |
| 308 |
catalog1: AntaCatalog = AntaCatalog.parse(DATA_DIR / "test_catalog.yml") |
| 309 |
assert len(catalog1.tests) == 1 |
| 310 |
catalog2: AntaCatalog = AntaCatalog.parse(DATA_DIR / "test_catalog.yml") |
| 311 |
assert len(catalog2.tests) == 1 |
| 312 |
catalog3: AntaCatalog = AntaCatalog.parse(DATA_DIR / "test_catalog_medium.yml") |
| 313 |
assert len(catalog3.tests) == 228 |
| 314 |
|
| 315 |
with pytest.deprecated_call(): |
| 316 |
merged_catalog = catalog1.merge(catalog2) |
| 317 |
assert len(merged_catalog.tests) == 2 |
| 318 |
assert len(catalog1.tests) == 1 |
| 319 |
assert len(catalog2.tests) == 1 |
| 320 |
|
| 321 |
with pytest.deprecated_call(): |
| 322 |
merged_catalog = catalog2.merge(catalog3) |
| 323 |
assert len(merged_catalog.tests) == 229 |
| 324 |
assert len(catalog2.tests) == 1 |
| 325 |
assert len(catalog3.tests) == 228 |
| 326 |
|
| 327 |
def test_dump(self) -> None: |
| 328 |
"""Test AntaCatalog.dump().""" |
| 329 |
catalog: AntaCatalog = AntaCatalog.parse(DATA_DIR / "test_catalog.yml") |
| 330 |
assert len(catalog.tests) == 1 |
| 331 |
file: AntaCatalogFile = catalog.dump() |
| 332 |
assert sum(len(tests) for tests in file.root.values()) == 1 |
| 333 |
|
| 334 |
catalog = AntaCatalog.parse(DATA_DIR / "test_catalog_medium.yml") |
| 335 |
assert len(catalog.tests) == 228 |
| 336 |
file = catalog.dump() |
| 337 |
assert sum(len(tests) for tests in file.root.values()) == 228 |
| 338 |
|
| 339 |
|
| 340 |
class TestAntaCatalogFile: |
| 341 |
"""Test for anta.catalog.AntaCatalogFile.""" |
| 342 |
|
| 343 |
def test_yaml(self) -> None: |
| 344 |
"""Test AntaCatalogFile.yaml().""" |
| 345 |
file = DATA_DIR / "test_catalog_medium.yml" |
| 346 |
catalog = AntaCatalog.parse(file) |
| 347 |
assert len(catalog.tests) == 228 |
| 348 |
catalog_yaml_str = catalog.dump().yaml() |
| 349 |
with file.open(encoding="UTF-8") as f: |
| 350 |
assert catalog_yaml_str == f.read() |
| 351 |
|
| 352 |
def test_to_json(self) -> None: |
| 353 |
"""Load a YAML file, dump it to JSON and verify it works.""" |
| 354 |
file = DATA_DIR / "test_catalog_with_tags.yml" |
| 355 |
expected_json_path = DATA_DIR / "test_catalog_with_tags.json" |
| 356 |
catalog = AntaCatalog.parse(file) |
| 357 |
assert len(catalog.tests) == 11 |
| 358 |
with expected_json_path.open("r") as f: |
| 359 |
expected_data = json_load(f) |
| 360 |
|
| 361 |
assert json_loads(catalog.dump().to_json()) == expected_data |