Debian Codegraph @

tests/units/test_runner.py

raw symbols SCIP
1 # Copyright (c) 2023-2026 Arista Networks, Inc.
2 # Use of this source code is governed by the Apache License 2.0
3 # that can be found in the LICENSE file.
4 """test anta.runner.py."""
5
6 from __future__ import annotations
7
8 import logging
9 import os
10 from pathlib import Path
11 from typing import TYPE_CHECKING
12 from unittest.mock import AsyncMock, patch
13
14 import pytest
15
16 from anta.catalog import AntaCatalog
17 from anta.result_manager import ResultManager
18 from anta.runner import main, prepare_tests
19
20 from .test_models import FakeTest
21
22 if TYPE_CHECKING:
23 from anta.inventory import AntaInventory
24
25 if os.name == "posix":
26 # The function is not defined on non-POSIX system
27 import resource
28
29 from anta.runner import adjust_rlimit_nofile
30
31 DATA_DIR: Path = Path(__file__).parent.parent.resolve() / "data"
32 FAKE_CATALOG: AntaCatalog = AntaCatalog.from_list([(FakeTest, None)])
33
34
35 # TODO: Remove this in ANTA v2.0.0
36 @pytest.mark.filterwarnings("ignore::DeprecationWarning")
37 @pytest.mark.skipif(os.name != "posix", reason="Cannot run this test on Windows")
38 def test_adjust_rlimit_nofile_valid_env(caplog: pytest.LogCaptureFixture) -> None:
39 """Test adjust_rlimit_nofile with valid environment variables."""
40 # pylint: disable=E0606
41 with (
42 caplog.at_level(logging.DEBUG),
43 patch.dict("os.environ", {"ANTA_NOFILE": "20480"}),
44 patch("anta.runner.resource.getrlimit") as getrlimit_mock,
45 patch("anta.runner.resource.setrlimit") as setrlimit_mock,
46 ):
47 # Simulate the default system limits
48 system_limits = (8192, 1048576)
49
50 # Setup getrlimit mock return value
51 getrlimit_mock.return_value = system_limits
52
53 # Simulate setrlimit behavior
54 def side_effect_setrlimit(resource_id: int, limits: tuple[int, int]) -> None:
55 _ = resource_id
56 getrlimit_mock.return_value = (limits[0], limits[1])
57
58 setrlimit_mock.side_effect = side_effect_setrlimit
59
60 result = adjust_rlimit_nofile()
61
62 # Assert the limits were updated as expected
63 assert result == (20480, 1048576)
64 assert "Initial limit numbers for open file descriptors for the current ANTA process: Soft Limit: 8192 | Hard Limit: 1048576" in caplog.text
65 assert "Setting soft limit for open file descriptors for the current ANTA process to 20480" in caplog.text
66
67 setrlimit_mock.assert_called_once_with(resource.RLIMIT_NOFILE, (20480, 1048576))
68
69
70 # TODO: Remove this in ANTA v2.0.0
71 @pytest.mark.filterwarnings("ignore::DeprecationWarning")
72 @pytest.mark.skipif(os.name != "posix", reason="Cannot run this test on Windows")
73 def test_adjust_rlimit_nofile_invalid_env(caplog: pytest.LogCaptureFixture) -> None:
74 """Test adjust_rlimit_nofile with invalid environment variables."""
75 with (
76 caplog.at_level(logging.DEBUG),
77 patch.dict("os.environ", {"ANTA_NOFILE": "invalid"}),
78 patch("anta.runner.resource.getrlimit") as getrlimit_mock,
79 patch("anta.runner.resource.setrlimit") as setrlimit_mock,
80 ):
81 # Simulate the default system limits
82 system_limits = (8192, 1048576)
83
84 # Setup getrlimit mock return value
85 getrlimit_mock.return_value = system_limits
86
87 # Simulate setrlimit behavior
88 def side_effect_setrlimit(resource_id: int, limits: tuple[int, int]) -> None:
89 _ = resource_id
90 getrlimit_mock.return_value = (limits[0], limits[1])
91
92 setrlimit_mock.side_effect = side_effect_setrlimit
93
94 result = adjust_rlimit_nofile()
95
96 # Assert the limits were updated as expected
97 assert result == (16384, 1048576)
98 assert "The ANTA_NOFILE environment variable value is invalid" in caplog.text
99 assert caplog.records[0].levelname == "WARNING"
100 assert "Initial limit numbers for open file descriptors for the current ANTA process: Soft Limit: 8192 | Hard Limit: 1048576" in caplog.text
101 assert "Setting soft limit for open file descriptors for the current ANTA process to 16384" in caplog.text
102
103 setrlimit_mock.assert_called_once_with(resource.RLIMIT_NOFILE, (16384, 1048576))
104
105
106 # TODO: Remove this in ANTA v2.0.0
107 @pytest.mark.skipif(os.name != "posix", reason="Cannot run this test on Windows")
108 def test_adjust_rlimit_nofile_value_error(caplog: pytest.LogCaptureFixture) -> None:
109 """Test adjust_rlimit_nofile with invalid environment variables."""
110 with (
111 caplog.at_level(logging.DEBUG),
112 patch.dict("os.environ", {"ANTA_NOFILE": "666"}),
113 patch("anta.runner.resource.getrlimit") as getrlimit_mock,
114 patch("anta.runner.resource.setrlimit") as setrlimit_mock,
115 ):
116 # Simulate the default system limits
117 system_limits = (8192, 1048576)
118
119 # Setup getrlimit mock return value
120 getrlimit_mock.return_value = system_limits
121
122 # Simulate setrlimit behavior raising ValueError
123 def side_effect_setrlimit(_resource_id: int, _limits: tuple[int, int]) -> None:
124 msg = "not allowed to raise maximum limit"
125 raise ValueError(msg)
126
127 setrlimit_mock.side_effect = side_effect_setrlimit
128
129 result = adjust_rlimit_nofile()
130
131 # Assert the limits were *NOT* updated as expected
132 assert result == system_limits
133 assert "Initial limit numbers for open file descriptors for the current ANTA process: Soft Limit: 8192 | Hard Limit: 1048576" in caplog.text
134 assert caplog.records[-1].levelname == "WARNING"
135 assert "Failed to set soft limit for open file descriptors for the current ANTA process" in caplog.records[-1].getMessage()
136
137 setrlimit_mock.assert_called_once_with(resource.RLIMIT_NOFILE, (666, 1048576))
138
139
140 # TODO: Remove this in ANTA v2.0.0
141 @pytest.mark.filterwarnings("ignore::DeprecationWarning")
142 @pytest.mark.parametrize(
143 ("inventory", "tags", "tests", "devices_count", "tests_count"),
144 [
145 pytest.param({"filename": "test_inventory_with_tags.yml"}, None, None, 3, 27, id="all-tests"),
146 pytest.param({"filename": "test_inventory_with_tags.yml"}, {"leaf"}, None, 2, 6, id="1-tag"),
147 pytest.param({"filename": "test_inventory_with_tags.yml"}, {"leaf", "spine"}, None, 3, 9, id="2-tags"),
148 pytest.param({"filename": "test_inventory_with_tags.yml"}, None, {"VerifyMlagStatus", "VerifyUptime"}, 3, 5, id="filtered-tests"),
149 pytest.param({"filename": "test_inventory_with_tags.yml"}, {"leaf"}, {"VerifyMlagStatus", "VerifyUptime"}, 2, 4, id="1-tag-filtered-tests"),
150 pytest.param({"filename": "test_inventory_with_tags.yml"}, {"invalid"}, None, 0, 0, id="invalid-tag"),
151 pytest.param({"filename": "test_inventory_with_tags.yml"}, {"dc1"}, None, 0, 0, id="device-tag-no-tests"),
152 ],
153 indirect=["inventory"],
154 )
155 async def test_prepare_tests(
156 caplog: pytest.LogCaptureFixture, inventory: AntaInventory, tags: set[str], tests: set[str], devices_count: int, tests_count: int
157 ) -> None:
158 """Test the runner prepare_tests function with specific tests."""
159 caplog.set_level(logging.WARNING)
160 catalog: AntaCatalog = AntaCatalog.parse(str(DATA_DIR / "test_catalog_with_tags.yml"))
161 selected_tests = prepare_tests(inventory=inventory, catalog=catalog, tags=tags, tests=tests)
162 if selected_tests is None:
163 msg = f"There are no tests matching the tags {tags} to run in the current test catalog and device inventory, please verify your inputs."
164 assert msg in caplog.messages
165 return
166 assert selected_tests is not None
167 assert len(selected_tests) == devices_count
168 assert sum(len(tests) for tests in selected_tests.values()) == tests_count
169
170
171 async def test_main_forwards_disconnect(inventory: AntaInventory) -> None:
172 """Test anta.runner.main forwards the disconnect flag to AntaRunner."""
173 manager = ResultManager()
174 catalog = AntaCatalog()
175
176 with patch("anta.runner.AntaRunner.run", new=AsyncMock()) as run_mock:
177 await main(
178 manager,
179 inventory,
180 catalog,
181 devices={"leaf1"},
182 tests={"VerifyEOSVersion"},
183 tags={"leaf"},
184 established_only=False,
185 dry_run=True,
186 disconnect=True,
187 )
188
189 run_mock.assert_awaited_once()
190 assert run_mock.await_args is not None
191 args = run_mock.await_args.args
192 kwargs = run_mock.await_args.kwargs
193 assert args[:3] == (inventory, catalog, manager)
194 filters = args[3]
195 assert filters.devices == {"leaf1"}
196 assert filters.tests == {"VerifyEOSVersion"}
197 assert filters.tags == {"leaf"}
198 assert filters.established_only is False
199 assert kwargs == {"dry_run": True, "disconnect": True}