Debian Codegraph @

tests/units/result_manager/test__init__.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.result_manager.__init__.py."""
5
6 from __future__ import annotations
7
8 import json
9 import logging
10 import re
11 from contextlib import AbstractContextManager, nullcontext
12 from typing import TYPE_CHECKING
13
14 import pytest
15
16 from anta.result_manager import ResultManager, models
17 from anta.result_manager.models import AntaTestStatus
18
19 if TYPE_CHECKING:
20 from collections.abc import Callable
21
22 from anta.result_manager.models import TestResult
23
24
25 # pylint: disable=too-many-public-methods
26 class TestResultManager:
27 """Test ResultManager class."""
28
29 # TODO: test __init__() and reset()
30
31 def test__len__(self, result_manager_factory: Callable[[int], ResultManager]) -> None:
32 """Test __len__."""
33 for i in range(3):
34 result_manager = result_manager_factory(i)
35 assert len(result_manager) == i
36
37 def test_results_getter(self, result_manager_factory: Callable[[int], ResultManager]) -> None:
38 """Test ResultManager.results property getter."""
39 result_manager = result_manager_factory(3)
40 res = result_manager.results
41 assert len(res) == 3
42 assert isinstance(res, list)
43 for e in res:
44 assert isinstance(e, models.TestResult)
45
46 def test_results_setter(self, test_result_factory: Callable[..., TestResult], result_manager_factory: Callable[[int], ResultManager]) -> None:
47 """Test ResultManager.results property setter."""
48 result_manager = result_manager_factory(3)
49 assert len(result_manager) == 3
50 tests = [test_result_factory(i) for i in range(5)]
51 result_manager.results = tests
52 assert len(result_manager) == 5
53
54 def test_json(self, test_result_factory: Callable[..., TestResult]) -> None:
55 """Test ResultManager.json property."""
56 result_manager = ResultManager()
57
58 success_list = [test_result_factory(i) for i in range(3)]
59 for test in success_list:
60 test.result = AntaTestStatus.SUCCESS
61 result_manager.results = success_list
62
63 json_res = result_manager.json
64 assert isinstance(json_res, str)
65
66 # Verifies it can be deserialized back to a list of dict with the correct values types
67 res = json.loads(json_res)
68 for test in res:
69 assert isinstance(test, dict)
70 assert isinstance(test.get("test"), str)
71 assert isinstance(test.get("categories"), list)
72 assert isinstance(test.get("description"), str)
73 # @gmuloc: Adding this as part of #1364 to make sure we don't remove custom_field again
74 # TODO: modify this if we add back exclude_none=True
75 assert "custom_field" in test
76 assert test.get("custom_field") is None
77 assert test.get("result") == "success"
78
79 def test_sorted_category_stats(self, test_result_factory: Callable[..., TestResult]) -> None:
80 """Test ResultManager.sorted_category_stats."""
81 result_manager = ResultManager()
82 results = [test_result_factory(i) for i in range(4)]
83
84 # Modify the categories to have a mix of different acronym categories
85 results[0].categories = ["ospf"]
86 results[1].categories = ["bgp"]
87 results[2].categories = ["vxlan"]
88 results[3].categories = ["system"]
89
90 result_manager.results = results
91
92 # Check that category_stats returns sorted order by default
93 expected_order = ["bgp", "ospf", "system", "vxlan"]
94 assert list(result_manager.category_stats.keys()) == expected_order
95
96 @pytest.mark.parametrize(
97 ("starting_status", "test_status", "expected_status", "expected_raise"),
98 [
99 pytest.param("unset", "unset", "unset", nullcontext(), id="unset->unset"),
100 pytest.param("unset", "success", "success", nullcontext(), id="unset->success"),
101 pytest.param("unset", "error", "unset", nullcontext(), id="set error"),
102 pytest.param("skipped", "skipped", "skipped", nullcontext(), id="skipped->skipped"),
103 pytest.param("skipped", "unset", "skipped", nullcontext(), id="skipped, add unset"),
104 pytest.param(
105 "skipped",
106 "success",
107 "success",
108 nullcontext(),
109 id="skipped, add success",
110 ),
111 pytest.param(
112 "skipped",
113 "failure",
114 "failure",
115 nullcontext(),
116 id="skipped, add failure",
117 ),
118 pytest.param("success", "unset", "success", nullcontext(), id="success, add unset"),
119 pytest.param(
120 "success",
121 "skipped",
122 "success",
123 nullcontext(),
124 id="success, add skipped",
125 ),
126 pytest.param("success", "success", "success", nullcontext(), id="success->success"),
127 pytest.param("success", "failure", "failure", nullcontext(), id="success->failure"),
128 pytest.param("failure", "unset", "failure", nullcontext(), id="failure->failure"),
129 pytest.param("failure", "skipped", "failure", nullcontext(), id="failure, add unset"),
130 pytest.param(
131 "failure",
132 "success",
133 "failure",
134 nullcontext(),
135 id="failure, add skipped",
136 ),
137 pytest.param(
138 "failure",
139 "failure",
140 "failure",
141 nullcontext(),
142 id="failure, add success",
143 ),
144 pytest.param("unset", "unknown", None, pytest.raises(ValueError, match="'unknown' is not a valid AntaTestStatus"), id="wrong status"),
145 ],
146 )
147 def test_add(
148 self,
149 test_result_factory: Callable[..., TestResult],
150 starting_status: str,
151 test_status: str,
152 expected_status: str,
153 expected_raise: AbstractContextManager[Exception],
154 ) -> None:
155 """Test ResultManager_update_status."""
156 result_manager = ResultManager()
157 result_manager.status = AntaTestStatus(starting_status)
158 assert result_manager.error_status is False
159 assert len(result_manager) == 0
160
161 test = test_result_factory()
162 with expected_raise:
163 test.result = AntaTestStatus(test_status)
164 result_manager.add(test)
165 if test_status == "error":
166 assert result_manager.error_status is True
167 else:
168 assert result_manager.status == expected_status
169 assert len(result_manager) == 1
170
171 def test_add_clear_cache(self, result_manager: ResultManager, test_result_factory: Callable[..., TestResult]) -> None:
172 """Test ResultManager.add and make sure the cache is reset after adding a new test."""
173 # Check the cache is empty
174 assert "results_by_status" not in result_manager.__dict__
175
176 # Access the cache
177 assert result_manager.get_total_results() == 181
178
179 # Check the cache is filled with the correct results count
180 assert "results_by_status" in result_manager.__dict__
181 assert sum(len(v) for v in result_manager.__dict__["results_by_status"].values()) == 181
182
183 # Add a new test
184 result_manager.add(result=test_result_factory())
185
186 # Check the cache has been reset
187 assert "results_by_status" not in result_manager.__dict__
188
189 # Access the cache again
190 assert result_manager.get_total_results() == 182
191
192 # Check the cache is filled again with the correct results count
193 assert "results_by_status" in result_manager.__dict__
194 assert sum(len(v) for v in result_manager.__dict__["results_by_status"].values()) == 182
195
196 def test_get_results(self, result_manager: ResultManager) -> None:
197 """Test ResultManager.get_results."""
198 # Check for single status
199 success_results = result_manager.get_results(status={AntaTestStatus.SUCCESS})
200 assert len(success_results) == 43
201 assert all(r.result == "success" for r in success_results)
202
203 # Check for multiple statuses
204 failure_results = result_manager.get_results(status={AntaTestStatus.FAILURE, AntaTestStatus.ERROR})
205 assert len(failure_results) == 104
206 assert all(r.result in {"failure", "error"} for r in failure_results)
207
208 # Check all results
209 all_results = result_manager.get_results()
210 assert len(all_results) == 181
211
212 def test_get_results_sort_by(self, result_manager: ResultManager) -> None:
213 """Test ResultManager.get_results with sort_by."""
214 # Check all results with sort_by result
215 all_results = result_manager.get_results(sort_by=["result"])
216 assert len(all_results) == 181
217 assert [r.result for r in all_results] == ["error"] * 1 + ["failure"] * 103 + ["skipped"] * 34 + ["success"] * 43
218
219 # Check all results with sort_by device (name)
220 all_results = result_manager.get_results(sort_by=["name"])
221 assert len(all_results) == 181
222 assert all_results[0].name == "s1-spine1"
223
224 # Check multiple statuses with sort_by categories
225 success_skipped_results = result_manager.get_results(status={AntaTestStatus.SUCCESS, AntaTestStatus.SKIPPED}, sort_by=["categories"])
226 assert len(success_skipped_results) == 77
227 assert success_skipped_results[0].categories == ["avt"]
228 assert success_skipped_results[-1].categories == ["vxlan"]
229
230 # Check multiple statuses with sort_by custom_field
231 success_skipped_results = result_manager.get_results(status={AntaTestStatus.SUCCESS, AntaTestStatus.SKIPPED}, sort_by=["custom_field"])
232 assert len(success_skipped_results) == 77
233 assert success_skipped_results[-1].test == "VerifyReloadCause"
234
235 # Check all results with bad sort_by
236 with pytest.raises(
237 ValueError,
238 match=re.escape("Invalid sort_by fields: ['bad_field']."),
239 ):
240 all_results = result_manager.get_results(sort_by=["bad_field"])
241
242 def test_get_total_results(self, result_manager: ResultManager) -> None:
243 """Test ResultManager.get_total_results."""
244 # Test all results
245 assert result_manager.get_total_results() == 181
246
247 # Test single status
248 assert result_manager.get_total_results(status={AntaTestStatus.SUCCESS}) == 43
249 assert result_manager.get_total_results(status={AntaTestStatus.FAILURE}) == 103
250 assert result_manager.get_total_results(status={AntaTestStatus.ERROR}) == 1
251 assert result_manager.get_total_results(status={AntaTestStatus.SKIPPED}) == 34
252
253 # Test multiple statuses
254 assert result_manager.get_total_results(status={AntaTestStatus.SUCCESS, AntaTestStatus.FAILURE}) == 146
255 assert result_manager.get_total_results(status={AntaTestStatus.SUCCESS, AntaTestStatus.FAILURE, AntaTestStatus.ERROR}) == 147
256 assert result_manager.get_total_results(status={AntaTestStatus.SUCCESS, AntaTestStatus.FAILURE, AntaTestStatus.ERROR, AntaTestStatus.SKIPPED}) == 181
257
258 @pytest.mark.parametrize(
259 ("status", "error_status", "ignore_error", "expected_status"),
260 [
261 pytest.param("success", False, True, "success", id="no error"),
262 pytest.param("success", True, True, "success", id="error, ignore error"),
263 pytest.param("success", True, False, "error", id="error, do not ignore error"),
264 ],
265 )
266 def test_get_status(
267 self,
268 status: AntaTestStatus,
269 error_status: bool,
270 ignore_error: bool,
271 expected_status: str,
272 ) -> None:
273 """Test ResultManager.get_status."""
274 result_manager = ResultManager()
275 result_manager.status = status
276 result_manager.error_status = error_status
277
278 assert result_manager.get_status(ignore_error=ignore_error) == expected_status
279
280 def test_filter(self, test_result_factory: Callable[..., TestResult]) -> None:
281 """Test ResultManager.filter."""
282 result_manager = ResultManager()
283
284 success_list = [test_result_factory(i) for i in range(3)]
285 for test in success_list:
286 test.result = AntaTestStatus.SUCCESS
287 result_manager.results = success_list
288
289 test = test_result_factory()
290 test.result = AntaTestStatus.FAILURE
291 result_manager.add(test)
292
293 test = test_result_factory()
294 test.result = AntaTestStatus.ERROR
295 result_manager.add(test)
296
297 test = test_result_factory()
298 test.result = AntaTestStatus.SKIPPED
299 result_manager.add(test)
300
301 assert len(result_manager) == 6
302 assert len(result_manager.filter({AntaTestStatus.FAILURE})) == 5
303 assert len(result_manager.filter({AntaTestStatus.ERROR})) == 5
304 assert len(result_manager.filter({AntaTestStatus.SKIPPED})) == 5
305 assert len(result_manager.filter({AntaTestStatus.FAILURE, AntaTestStatus.ERROR})) == 4
306 assert len(result_manager.filter({AntaTestStatus.FAILURE, AntaTestStatus.ERROR, AntaTestStatus.SKIPPED})) == 3
307 assert len(result_manager.filter({AntaTestStatus.SUCCESS, AntaTestStatus.FAILURE, AntaTestStatus.ERROR, AntaTestStatus.SKIPPED})) == 0
308
309 def test_get_by_tests(self, test_result_factory: Callable[..., TestResult], result_manager_factory: Callable[[int], ResultManager]) -> None:
310 """Test ResultManager.get_by_tests."""
311 result_manager = result_manager_factory(3)
312
313 test = test_result_factory()
314 test.test = "Test1"
315 result_manager.add(test)
316
317 test = test_result_factory()
318 test.test = "Test2"
319 result_manager.add(test)
320
321 test = test_result_factory()
322 test.test = "Test2"
323 result_manager.add(test)
324
325 assert len(result_manager) == 6
326 assert len(result_manager.filter_by_tests({"Test1"})) == 1
327 rm = result_manager.filter_by_tests({"Test1", "Test2"})
328 assert len(rm) == 3
329 assert len(rm.filter_by_tests({"Test1"})) == 1
330
331 def test_get_by_devices(self, test_result_factory: Callable[..., TestResult], result_manager_factory: Callable[[int], ResultManager]) -> None:
332 """Test ResultManager.get_by_devices."""
333 result_manager = result_manager_factory(3)
334
335 test = test_result_factory()
336 test.name = "Device1"
337 result_manager.add(test)
338
339 test = test_result_factory()
340 test.name = "Device2"
341 result_manager.add(test)
342
343 test = test_result_factory()
344 test.name = "Device2"
345 result_manager.add(test)
346
347 assert len(result_manager) == 6
348 assert len(result_manager.filter_by_devices({"Device1"})) == 1
349 rm = result_manager.filter_by_devices({"Device1", "Device2"})
350 assert len(rm) == 3
351 assert len(rm.filter_by_devices({"Device1"})) == 1
352
353 def test_get_tests(self, test_result_factory: Callable[..., TestResult]) -> None:
354 """Test ResultManager.get_tests."""
355 result_manager = ResultManager()
356
357 tests = [test_result_factory(i) for i in range(3)]
358 for test in tests:
359 test.test = "Test1"
360 result_manager.results = tests
361
362 test = test_result_factory()
363 test.test = "Test2"
364 result_manager.add(test)
365
366 assert len(result_manager.get_tests()) == 2
367 assert all(t in result_manager.get_tests() for t in ["Test1", "Test2"])
368
369 def test_get_devices(self, test_result_factory: Callable[..., TestResult]) -> None:
370 """Test ResultManager.get_tests."""
371 result_manager = ResultManager()
372
373 tests = [test_result_factory(i) for i in range(3)]
374 for test in tests:
375 test.name = "Device1"
376 result_manager.results = tests
377
378 test = test_result_factory()
379 test.name = "Device2"
380 result_manager.add(test)
381
382 assert len(result_manager.get_devices()) == 2
383 assert all(t in result_manager.get_devices() for t in ["Device1", "Device2"])
384
385 def test_stats_computation_methods(self, test_result_factory: Callable[..., TestResult], caplog: pytest.LogCaptureFixture) -> None:
386 """Test ResultManager internal stats computation methods."""
387 result_manager = ResultManager()
388
389 # Initially stats should be unsynced
390 assert result_manager._stats_in_sync is False
391
392 # Test _reset_stats
393 result_manager._reset_stats()
394 assert result_manager._stats_in_sync is False
395 assert len(result_manager._device_stats) == 0
396 assert len(result_manager._category_stats) == 0
397 assert len(result_manager._test_stats) == 0
398
399 # Add some test results
400 test1 = test_result_factory()
401 test1.name = "device1"
402 test1.result = AntaTestStatus.SUCCESS
403 test1.categories = ["system"]
404 test1.test = "test1"
405
406 test2 = test_result_factory()
407 test2.name = "device2"
408 test2.result = AntaTestStatus.FAILURE
409 test2.categories = ["interfaces"]
410 test2.test = "test2"
411
412 result_manager.add(test1)
413 result_manager.add(test2)
414
415 # Stats should still be unsynced after adding results
416 assert result_manager._stats_in_sync is False
417
418 # Test _compute_stats directly
419 with caplog.at_level(logging.INFO):
420 result_manager._compute_stats()
421 assert "Computing statistics for all results" in caplog.text
422 assert result_manager._stats_in_sync is True
423
424 # Verify stats content
425 assert len(result_manager._device_stats) == 2
426 assert len(result_manager._category_stats) == 2
427 assert len(result_manager._test_stats) == 2
428 assert result_manager._device_stats["device1"].tests_success_count == 1
429 assert result_manager._device_stats["device2"].tests_failure_count == 1
430 assert result_manager._category_stats["system"].tests_success_count == 1
431 assert result_manager._category_stats["interfaces"].tests_failure_count == 1
432 assert result_manager._test_stats["test1"].devices_success_count == 1
433 assert result_manager._test_stats["test2"].devices_failure_count == 1
434
435 def test_stats_property_computation(self, test_result_factory: Callable[..., TestResult], caplog: pytest.LogCaptureFixture) -> None:
436 """Test that stats are computed only once when accessed via properties."""
437 result_manager = ResultManager()
438
439 # Add some test results
440 test1 = test_result_factory()
441 test1.name = "device1"
442 test1.result = AntaTestStatus.SUCCESS
443 test1.categories = ["system"]
444 result_manager.add(test1)
445
446 test2 = test_result_factory()
447 test2.name = "device2"
448 test2.result = AntaTestStatus.FAILURE
449 test2.categories = ["interfaces"]
450 result_manager.add(test2)
451
452 # Stats should be unsynced after adding results
453 assert result_manager._stats_in_sync is False
454 assert "Computing statistics" not in caplog.text
455
456 # Access device_stats property - should trigger computation
457 with caplog.at_level(logging.INFO):
458 _ = result_manager.device_stats
459 assert "Computing statistics for all results" in caplog.text
460 assert result_manager._stats_in_sync is True
461
462 # Clear the log
463 caplog.clear()
464
465 # Access other stats properties - should not trigger computation again
466 with caplog.at_level(logging.INFO):
467 _ = result_manager.category_stats
468 _ = result_manager.test_stats
469 assert "Computing statistics" not in caplog.text
470
471 # Add another result - should mark stats as unsynced
472 test3 = test_result_factory()
473 test3.name = "device3"
474 test3.result = AntaTestStatus.ERROR
475 result_manager.add(test3)
476 assert result_manager._stats_in_sync is False
477
478 # Access stats again - should trigger recomputation
479 with caplog.at_level(logging.INFO):
480 _ = result_manager.device_stats
481 assert "Computing statistics for all results" in caplog.text
482 assert result_manager._stats_in_sync is True
483
484 def test_sort_by_result(self, test_result_factory: Callable[[], TestResult]) -> None:
485 """Test sorting by result."""
486 result_manager = ResultManager()
487 test1 = test_result_factory()
488 test1.result = AntaTestStatus.SUCCESS
489 test2 = test_result_factory()
490 test2.result = AntaTestStatus.FAILURE
491 test3 = test_result_factory()
492 test3.result = AntaTestStatus.ERROR
493
494 result_manager.results = [test1, test2, test3]
495 sorted_manager = result_manager.sort(["result"])
496 assert [r.result for r in sorted_manager.results] == ["error", "failure", "success"]
497
498 def test_sort_by_name(self, test_result_factory: Callable[[], TestResult]) -> None:
499 """Test sorting by name."""
500 result_manager = ResultManager()
501 test1 = test_result_factory()
502 test1.name = "Device3"
503 test2 = test_result_factory()
504 test2.name = "Device1"
505 test3 = test_result_factory()
506 test3.name = "Device2"
507
508 result_manager.results = [test1, test2, test3]
509 sorted_manager = result_manager.sort(["name"])
510 assert [r.name for r in sorted_manager.results] == ["Device1", "Device2", "Device3"]
511
512 def test_sort_by_categories(self, test_result_factory: Callable[[], TestResult]) -> None:
513 """Test sorting by categories."""
514 result_manager = ResultManager()
515 test1 = test_result_factory()
516 test1.categories = ["VXLAN", "networking"]
517 test2 = test_result_factory()
518 test2.categories = ["BGP", "routing"]
519 test3 = test_result_factory()
520 test3.categories = ["system", "hardware"]
521
522 result_manager.results = [test1, test2, test3]
523 sorted_manager = result_manager.sort(["categories"])
524 results = sorted_manager.results
525
526 assert results[0].categories == ["BGP", "routing"]
527 assert results[1].categories == ["VXLAN", "networking"]
528 assert results[2].categories == ["system", "hardware"]
529
530 def test_sort_multiple_fields(self, test_result_factory: Callable[[], TestResult]) -> None:
531 """Test sorting by multiple fields."""
532 result_manager = ResultManager()
533 test1 = test_result_factory()
534 test1.result = AntaTestStatus.ERROR
535 test1.test = "Test3"
536 test2 = test_result_factory()
537 test2.result = AntaTestStatus.ERROR
538 test2.test = "Test1"
539 test3 = test_result_factory()
540 test3.result = AntaTestStatus.FAILURE
541 test3.test = "Test2"
542
543 result_manager.results = [test1, test2, test3]
544 sorted_manager = result_manager.sort(["result", "test"])
545 results = sorted_manager.results
546
547 assert results[0].result == "error"
548 assert results[0].test == "Test1"
549 assert results[1].result == "error"
550 assert results[1].test == "Test3"
551 assert results[2].result == "failure"
552 assert results[2].test == "Test2"
553
554 def test_sort_fields_as_none(self, test_result_factory: Callable[[], TestResult]) -> None:
555 """Test sorting by multiple fields."""
556 result_manager = ResultManager()
557 test1 = test_result_factory()
558 test1.result = AntaTestStatus.ERROR
559 test1.test = "Test3"
560 test1.custom_field = "custom"
561 test2 = test_result_factory()
562 test2.result = AntaTestStatus.ERROR
563 test2.test = "Test1"
564 test3 = test_result_factory()
565 test3.result = AntaTestStatus.FAILURE
566 test3.test = "Test2"
567
568 result_manager.results = [test1, test2, test3]
569 sorted_manager = result_manager.sort(["custom_field"])
570 results = sorted_manager.results
571
572 assert results[0].result == "error"
573 assert results[0].test == "Test1"
574 assert results[1].result == "failure"
575 assert results[1].test == "Test2"
576 assert results[2].result == "error"
577 assert results[2].test == "Test3"
578 assert results[2].custom_field == "custom"
579
580 def test_sort_invalid_field(self) -> None:
581 """Test that sort method raises ValueError for invalid sort_by fields."""
582 result_manager = ResultManager()
583 expected_match = (
584 r"Invalid sort_by fields: ['bad_field']. Accepted fields are: "
585 r"['name', 'test', 'categories', 'description', 'result', 'messages', 'atomic_results', 'custom_field']"
586 )
587 with pytest.raises(ValueError, match=re.escape(expected_match)):
588 _ = result_manager.sort(["bad_field"])
589
590 def test_sort_is_chainable(self) -> None:
591 """Test that the sort method is chainable."""
592 result_manager = ResultManager()
593 assert isinstance(result_manager.sort(["name"]), ResultManager)
594
595 def test_merge_result_manager(self) -> None:
596 """Test the merge_results function."""
597 result = ResultManager()
598 final_merged_results = ResultManager.merge_results([result])
599 assert isinstance(final_merged_results, ResultManager)
600
601 def test_merge_two_result_managers(self, test_result_factory: Callable[[], TestResult]) -> None:
602 """Test merging two non-empty ResultManager instances."""
603 rm1 = ResultManager()
604 test1_rm1 = test_result_factory()
605 test1_rm1.name = "device1"
606 rm1.add(test1_rm1)
607 test2_rm1 = test_result_factory()
608 test2_rm1.name = "device2"
609 rm1.add(test2_rm1)
610
611 rm2 = ResultManager()
612 test1_rm2 = test_result_factory()
613 test1_rm2.name = "device3"
614 rm2.add(test1_rm2)
615
616 merged_rm = ResultManager.merge_results([rm1, rm2])
617 assert len(merged_rm) == 3
618 assert {r.name for r in merged_rm.results} == {"device1", "device2", "device3"}
619
620 def test_merge_empty_list(self) -> None:
621 """Test merging an empty list of ResultManager instances."""
622 merged_rm = ResultManager.merge_results([])
623 assert isinstance(merged_rm, ResultManager)
624 assert len(merged_rm) == 0