| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
"""ANTA Inventory unit tests.""" |
| 5 |
|
| 6 |
from __future__ import annotations |
| 7 |
|
| 8 |
import logging |
| 9 |
from typing import TYPE_CHECKING |
| 10 |
from unittest.mock import AsyncMock, patch |
| 11 |
|
| 12 |
import pytest |
| 13 |
from pydantic import ValidationError |
| 14 |
|
| 15 |
from anta.device import AntaDeviceCapabilities, AsyncEOSDevice |
| 16 |
from anta.inventory import AntaInventory |
| 17 |
from anta.inventory.exceptions import InventoryIncorrectSchemaError, InventoryRootKeyError |
| 18 |
|
| 19 |
if TYPE_CHECKING: |
| 20 |
from pathlib import Path |
| 21 |
|
| 22 |
from _pytest.mark.structures import ParameterSet |
| 23 |
|
| 24 |
from anta.device import AntaDevice |
| 25 |
|
| 26 |
|
| 27 |
INIT_VALID_PARAMS: list[ParameterSet] = [ |
| 28 |
pytest.param( |
| 29 |
{"anta_inventory": {"hosts": [{"host": "192.168.0.17"}, {"host": "192.168.0.2"}, {"host": "my.awesome.host.com"}]}}, |
| 30 |
id="Inventory_with_host_only", |
| 31 |
), |
| 32 |
pytest.param({"anta_inventory": {"networks": [{"network": "192.168.0.0/24"}]}}, id="ValidInventory_with_networks_only"), |
| 33 |
pytest.param( |
| 34 |
{"anta_inventory": {"ranges": [{"start": "10.0.0.1", "end": "10.0.0.11"}, {"start": "10.0.0.101", "end": "10.0.0.111"}]}}, |
| 35 |
id="Inventory_with_ranges_only", |
| 36 |
), |
| 37 |
pytest.param( |
| 38 |
{"anta_inventory": {"hosts": [{"host": "192.168.0.17", "port": 443}, {"host": "192.168.0.2", "port": 80}]}}, |
| 39 |
id="Inventory_with_host_port", |
| 40 |
), |
| 41 |
pytest.param( |
| 42 |
{"anta_inventory": {"hosts": [{"host": "192.168.0.17", "tags": ["leaf"]}, {"host": "192.168.0.2", "tags": ["spine"]}]}}, |
| 43 |
id="Inventory_with_host_tags", |
| 44 |
), |
| 45 |
pytest.param({"anta_inventory": {"networks": [{"network": "192.168.0.0/24", "tags": ["leaf"]}]}}, id="ValidInventory_with_networks_tags"), |
| 46 |
pytest.param( |
| 47 |
{ |
| 48 |
"anta_inventory": { |
| 49 |
"ranges": [{"start": "10.0.0.1", "end": "10.0.0.11", "tags": ["leaf"]}, {"start": "10.0.0.101", "end": "10.0.0.111", "tags": ["spine"]}] |
| 50 |
} |
| 51 |
}, |
| 52 |
id="Inventory_with_ranges_tags", |
| 53 |
), |
| 54 |
pytest.param( |
| 55 |
{ |
| 56 |
"anta_inventory": { |
| 57 |
"hosts": [{"host": "192.168.0.17", "use_session_auth": True}, {"host": "192.168.0.2", "use_session_auth": True}, {"host": "my.awesome.host.com"}], |
| 58 |
"networks": [{"network": "192.168.0.0/24", "use_session_auth": True}], |
| 59 |
"ranges": [{"start": "10.0.0.1", "end": "10.0.0.11", "use_session_auth": True}, {"start": "10.0.0.101", "end": "10.0.0.111"}], |
| 60 |
} |
| 61 |
}, |
| 62 |
id="Inventory_with_use_session_auth", |
| 63 |
), |
| 64 |
] |
| 65 |
|
| 66 |
|
| 67 |
INIT_INVALID_PARAMS = [ |
| 68 |
pytest.param({"anta_inventory": {"hosts": [{"host": "192.168.0.17/32"}, {"host": "192.168.0.2"}]}}, id="Inventory_with_host_only"), |
| 69 |
pytest.param({"anta_inventory": {"networks": [{"network": "192.168.42.0/8"}]}}, id="Inventory_wrong_network_bits"), |
| 70 |
pytest.param({"anta_inventory": {"networks": [{"network": "toto"}]}}, id="Inventory_wrong_network"), |
| 71 |
pytest.param({"anta_inventory": {"ranges": [{"start": "toto", "end": "192.168.42.42"}]}}, id="Inventory_wrong_range"), |
| 72 |
pytest.param({"anta_inventory": {"ranges": [{"start": "fe80::cafe", "end": "192.168.42.42"}]}}, id="Inventory_wrong_range_type_mismatch"), |
| 73 |
pytest.param( |
| 74 |
{"inventory": {"ranges": [{"start": "10.0.0.1", "end": "10.0.0.11"}, {"start": "10.0.0.100", "end": "10.0.0.111"}]}}, |
| 75 |
id="Invalid_Root_Key", |
| 76 |
), |
| 77 |
] |
| 78 |
|
| 79 |
|
| 80 |
class TestAntaInventory: |
| 81 |
"""Tests for anta.inventory.AntaInventory.""" |
| 82 |
|
| 83 |
@pytest.mark.parametrize("yaml_file", INIT_VALID_PARAMS, indirect=["yaml_file"]) |
| 84 |
def test_parse_valid(self, yaml_file: Path) -> None: |
| 85 |
"""Parse valid YAML file to create ANTA inventory.""" |
| 86 |
AntaInventory.parse(filename=yaml_file, username="arista", password="arista123") |
| 87 |
|
| 88 |
@pytest.mark.parametrize("yaml_file", INIT_INVALID_PARAMS, indirect=["yaml_file"]) |
| 89 |
def test_parse_invalid(self, yaml_file: Path) -> None: |
| 90 |
"""Parse invalid YAML file to create ANTA inventory.""" |
| 91 |
with pytest.raises((InventoryIncorrectSchemaError, InventoryRootKeyError, ValidationError)): |
| 92 |
AntaInventory.parse(filename=yaml_file, username="arista", password="arista123") |
| 93 |
|
| 94 |
def test_parse_wrong_format(self) -> None: |
| 95 |
"""Use wrong file format to parse the ANTA inventory.""" |
| 96 |
with pytest.raises(ValueError, match=r" is not a valid format for an AntaInventory file. Only 'yaml' and 'json' are supported."): |
| 97 |
AntaInventory.parse(filename="dummy.yml", username="arista", password="arista123", file_format="wrong") |
| 98 |
|
| 99 |
def test_parse_os_error(self, caplog: pytest.LogCaptureFixture) -> None: |
| 100 |
"""Use wrong file name to parse the ANTA inventory.""" |
| 101 |
caplog.set_level(logging.INFO) |
| 102 |
with pytest.raises(OSError, match=r"No such file or directory"): |
| 103 |
_ = AntaInventory.parse(filename="dummy.yml", username="arista", password="arista123") |
| 104 |
assert "Unable to parse ANTA Device Inventory file" in caplog.records[0].message |
| 105 |
|
| 106 |
@pytest.mark.parametrize(("inventory"), [{"count": 3}], indirect=True) |
| 107 |
def test_max_potential_connections(self, inventory: AntaInventory) -> None: |
| 108 |
"""Test max_potential_connections property with regular AsyncEOSDevice objects in the inventory.""" |
| 109 |
|
| 110 |
assert inventory.max_potential_connections == 300 |
| 111 |
|
| 112 |
@pytest.mark.parametrize(("device"), [{"name": "anta_device"}], indirect=True) |
| 113 |
def test_get_potential_connections_custom_anta_device(self, caplog: pytest.LogCaptureFixture, async_device: AsyncEOSDevice, device: AntaDevice) -> None: |
| 114 |
"""Test max_potential_connections property with an AntaDevice with no max_connections in the inventory.""" |
| 115 |
caplog.set_level(logging.DEBUG) |
| 116 |
|
| 117 |
inventory = AntaInventory() |
| 118 |
inventory.add_device(async_device) |
| 119 |
inventory.add_device(device) |
| 120 |
|
| 121 |
assert len(inventory) == 2 |
| 122 |
assert inventory.max_potential_connections is None |
| 123 |
assert "Device anta_device 'max_connections' is not available" in caplog.messages |
| 124 |
|
| 125 |
@pytest.mark.parametrize( |
| 126 |
"yaml_file", |
| 127 |
[ |
| 128 |
{ |
| 129 |
"anta_inventory": { |
| 130 |
"hosts": [ |
| 131 |
{"host": "192.168.0.1", "use_session_auth": True}, |
| 132 |
{"host": "192.168.0.2"}, |
| 133 |
] |
| 134 |
} |
| 135 |
} |
| 136 |
], |
| 137 |
indirect=["yaml_file"], |
| 138 |
) |
| 139 |
def test_use_session_auth_propagates_to_asynceapi_device(self, yaml_file: Path) -> None: |
| 140 |
"""Verify use_session_auth=True in an inventory entry reaches the underlying asynceapi.Device.""" |
| 141 |
inventory = AntaInventory.parse(filename=yaml_file, username="arista", password="arista123") |
| 142 |
devices_by_host = {device._client.host: device for device in inventory.values() if isinstance(device, AsyncEOSDevice)} |
| 143 |
|
| 144 |
assert devices_by_host["192.168.0.1"]._client._use_session_auth is True |
| 145 |
assert devices_by_host["192.168.0.2"]._client._use_session_auth is False |
| 146 |
|
| 147 |
@pytest.mark.parametrize( |
| 148 |
("cli", "inventory", "expected"), |
| 149 |
[ |
| 150 |
|
| 151 |
pytest.param(None, False, False, id="cli_unset_inventory_false__default"), |
| 152 |
pytest.param(None, True, True, id="cli_unset_inventory_true__inventory"), |
| 153 |
|
| 154 |
pytest.param(True, False, True, id="cli_enable_inventory_false__cli"), |
| 155 |
pytest.param(True, True, True, id="cli_enable_inventory_true__cli"), |
| 156 |
|
| 157 |
pytest.param(False, False, False, id="cli_disable_inventory_false__cli"), |
| 158 |
pytest.param(False, True, False, id="cli_disable_inventory_true__cli_override"), |
| 159 |
], |
| 160 |
) |
| 161 |
def test_resolve_session_auth(self, cli: bool | None, inventory: bool, expected: bool) -> None: |
| 162 |
"""Verify _resolve_session_auth truth table with a supporting device.""" |
| 163 |
result = AntaInventory._resolve_session_auth("test-device", AsyncEOSDevice.capabilities, use_session_auth_override=cli, inventory_use_session_auth=inventory) |
| 164 |
assert result is expected |
| 165 |
|
| 166 |
def test_resolve_session_auth_unsupported_device_inventory_raises(self) -> None: |
| 167 |
"""Verify ValueError when inventory requests session auth on an unsupported device.""" |
| 168 |
caps = AntaDeviceCapabilities(supports_session_auth=False) |
| 169 |
with pytest.raises(ValueError, match="does not support session authentication"): |
| 170 |
AntaInventory._resolve_session_auth("unsupported-device", caps, use_session_auth_override=None, inventory_use_session_auth=True) |
| 171 |
|
| 172 |
def test_resolve_session_auth_unsupported_device_cli_warns(self, caplog: pytest.LogCaptureFixture) -> None: |
| 173 |
"""Verify warning (not error) when CLI requests session auth on an unsupported device.""" |
| 174 |
caps = AntaDeviceCapabilities(supports_session_auth=False) |
| 175 |
caplog.set_level(logging.WARNING) |
| 176 |
result = AntaInventory._resolve_session_auth("unsupported-device", caps, use_session_auth_override=True, inventory_use_session_auth=False) |
| 177 |
assert result is False |
| 178 |
assert "does not support session authentication" in caplog.text |
| 179 |
|
| 180 |
@pytest.mark.parametrize( |
| 181 |
"yaml_file", |
| 182 |
[ |
| 183 |
{ |
| 184 |
"anta_inventory": { |
| 185 |
"hosts": [ |
| 186 |
{"host": "192.168.0.1", "use_session_auth": False}, |
| 187 |
{"host": "192.168.0.2", "use_session_auth": False}, |
| 188 |
] |
| 189 |
} |
| 190 |
} |
| 191 |
], |
| 192 |
indirect=["yaml_file"], |
| 193 |
) |
| 194 |
def test_use_session_auth_cli_overrides_inventory(self, yaml_file: Path) -> None: |
| 195 |
"""Verify that use_session_auth=True passed to parse() overrides per-device inventory values of False.""" |
| 196 |
inventory = AntaInventory.parse(filename=yaml_file, username="arista", password="arista123", use_session_auth=True) |
| 197 |
devices_by_host = {device._client.host: device for device in inventory.values() if isinstance(device, AsyncEOSDevice)} |
| 198 |
|
| 199 |
assert devices_by_host["192.168.0.1"]._client._use_session_auth is True |
| 200 |
assert devices_by_host["192.168.0.2"]._client._use_session_auth is True |
| 201 |
|
| 202 |
@pytest.mark.parametrize( |
| 203 |
"yaml_file", |
| 204 |
[ |
| 205 |
{ |
| 206 |
"anta_inventory": { |
| 207 |
"hosts": [ |
| 208 |
{"host": "192.168.0.1", "use_session_auth": True}, |
| 209 |
{"host": "192.168.0.2", "use_session_auth": True}, |
| 210 |
] |
| 211 |
} |
| 212 |
} |
| 213 |
], |
| 214 |
indirect=["yaml_file"], |
| 215 |
) |
| 216 |
def test_no_session_auth_cli_overrides_inventory(self, yaml_file: Path) -> None: |
| 217 |
"""Verify that use_session_auth=False (--no-session-auth) disables session auth even when inventory enables it.""" |
| 218 |
inventory = AntaInventory.parse(filename=yaml_file, username="arista", password="arista123", use_session_auth=False) |
| 219 |
devices_by_host = {device._client.host: device for device in inventory.values() if isinstance(device, AsyncEOSDevice)} |
| 220 |
|
| 221 |
assert devices_by_host["192.168.0.1"]._client._use_session_auth is False |
| 222 |
assert devices_by_host["192.168.0.2"]._client._use_session_auth is False |
| 223 |
|
| 224 |
@pytest.mark.parametrize( |
| 225 |
"yaml_file", |
| 226 |
[ |
| 227 |
{ |
| 228 |
"anta_inventory": { |
| 229 |
"hosts": [ |
| 230 |
{"host": "192.168.0.1", "use_session_auth": True}, |
| 231 |
{"host": "192.168.0.2", "use_session_auth": False}, |
| 232 |
] |
| 233 |
} |
| 234 |
} |
| 235 |
], |
| 236 |
indirect=["yaml_file"], |
| 237 |
) |
| 238 |
def test_dump_preserves_use_session_auth(self, yaml_file: Path) -> None: |
| 239 |
"""Verify that dump() preserves the use_session_auth value for each device.""" |
| 240 |
inventory = AntaInventory.parse(filename=yaml_file, username="arista", password="arista123") |
| 241 |
dumped = inventory.dump() |
| 242 |
hosts_by_name = {str(host.host): host for host in dumped.hosts or []} |
| 243 |
|
| 244 |
assert hosts_by_name["192.168.0.1"].use_session_auth is True |
| 245 |
assert hosts_by_name["192.168.0.2"].use_session_auth is False |
| 246 |
|
| 247 |
@pytest.mark.parametrize( |
| 248 |
"yaml_file", |
| 249 |
[ |
| 250 |
{ |
| 251 |
"anta_inventory": { |
| 252 |
"networks": [ |
| 253 |
{"network": "192.168.0.0/31", "use_session_auth": True}, |
| 254 |
{"network": "192.168.1.0/31", "use_session_auth": False}, |
| 255 |
] |
| 256 |
} |
| 257 |
} |
| 258 |
], |
| 259 |
indirect=["yaml_file"], |
| 260 |
) |
| 261 |
def test_use_session_auth_propagates_from_networks(self, yaml_file: Path) -> None: |
| 262 |
"""Verify use_session_auth propagates from network entries to all generated devices.""" |
| 263 |
inventory = AntaInventory.parse(filename=yaml_file, username="arista", password="arista123") |
| 264 |
devices_by_host = {device._client.host: device for device in inventory.values() if isinstance(device, AsyncEOSDevice)} |
| 265 |
|
| 266 |
assert devices_by_host["192.168.0.0"]._client._use_session_auth is True |
| 267 |
assert devices_by_host["192.168.0.1"]._client._use_session_auth is True |
| 268 |
assert devices_by_host["192.168.1.0"]._client._use_session_auth is False |
| 269 |
assert devices_by_host["192.168.1.1"]._client._use_session_auth is False |
| 270 |
|
| 271 |
@pytest.mark.parametrize( |
| 272 |
"yaml_file", |
| 273 |
[ |
| 274 |
{ |
| 275 |
"anta_inventory": { |
| 276 |
"ranges": [ |
| 277 |
{"start": "10.0.0.1", "end": "10.0.0.2", "use_session_auth": True}, |
| 278 |
{"start": "10.0.1.1", "end": "10.0.1.2", "use_session_auth": False}, |
| 279 |
] |
| 280 |
} |
| 281 |
} |
| 282 |
], |
| 283 |
indirect=["yaml_file"], |
| 284 |
) |
| 285 |
def test_use_session_auth_propagates_from_ranges(self, yaml_file: Path) -> None: |
| 286 |
"""Verify use_session_auth propagates from range entries to all generated devices.""" |
| 287 |
inventory = AntaInventory.parse(filename=yaml_file, username="arista", password="arista123") |
| 288 |
devices_by_host = {device._client.host: device for device in inventory.values() if isinstance(device, AsyncEOSDevice)} |
| 289 |
|
| 290 |
assert devices_by_host["10.0.0.1"]._client._use_session_auth is True |
| 291 |
assert devices_by_host["10.0.0.2"]._client._use_session_auth is True |
| 292 |
assert devices_by_host["10.0.1.1"]._client._use_session_auth is False |
| 293 |
assert devices_by_host["10.0.1.2"]._client._use_session_auth is False |
| 294 |
|
| 295 |
@pytest.mark.parametrize(("device"), [{"name": "base_device"}], indirect=True) |
| 296 |
async def test_disconnect_inventory_logs_exceptions(self, caplog: pytest.LogCaptureFixture, async_device: AsyncEOSDevice, device: AntaDevice) -> None: |
| 297 |
"""Test disconnect_inventory attempts every device and logs individual disconnect errors.""" |
| 298 |
caplog.set_level(logging.WARNING) |
| 299 |
inventory = AntaInventory() |
| 300 |
inventory.add_device(async_device) |
| 301 |
inventory.add_device(device) |
| 302 |
|
| 303 |
with ( |
| 304 |
patch.object(async_device, "disconnect", new=AsyncMock()) as async_device_disconnect, |
| 305 |
patch.object(device, "disconnect", new=AsyncMock(side_effect=RuntimeError("boom"))) as device_disconnect, |
| 306 |
): |
| 307 |
await inventory.disconnect_inventory() |
| 308 |
|
| 309 |
async_device_disconnect.assert_awaited_once() |
| 310 |
device_disconnect.assert_awaited_once() |
| 311 |
assert "Error when disconnecting inventory" in caplog.text |
| 312 |
assert "RuntimeError: boom" in caplog.text |
| 313 |
assert all(record.levelno == logging.WARNING for record in caplog.records) |