Debian Codegraph @

tests/units/test_tools.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 """Tests for `anta.tools`."""
5
6 from __future__ import annotations
7
8 from contextlib import AbstractContextManager
9 from contextlib import nullcontext as does_not_raise
10 from datetime import datetime, timedelta, timezone
11 from typing import TYPE_CHECKING, Any
12 from unittest.mock import AsyncMock, patch
13
14 import pytest
15
16 from anta.tools import (
17 convert_categories,
18 cprofile,
19 custom_division,
20 format_data,
21 get_dict_superset,
22 get_failed_logs,
23 get_item,
24 get_value,
25 is_interface_ignored,
26 time_ago,
27 )
28
29 if TYPE_CHECKING:
30 from pathlib import Path
31
32
33 TEST_GET_FAILED_LOGS_DATA = [
34 {"id": 1, "name": "Alice", "age": 30, "email": "[email protected]"},
35 {"id": 2, "name": "Bob", "age": 35, "email": "[email protected]"},
36 {"id": 3, "name": "Charlie", "age": 40, "email": "[email protected]"},
37 {"id": 4, "name": "Jon", "age": 25, "email": "[email protected]"},
38 {"id": 4, "name": "Rob", "age": 25, "email": "[email protected]"},
39 ]
40 TEST_GET_DICT_SUPERSET_DATA = [
41 ("id", 0),
42 {
43 "id": 1,
44 "name": "Alice",
45 "age": 30,
46 "email": "[email protected]",
47 },
48 {
49 "id": 2,
50 "name": "Bob",
51 "age": 35,
52 "email": "[email protected]",
53 },
54 {
55 "id": 3,
56 "name": "Charlie",
57 "age": 40,
58 "email": "[email protected]",
59 },
60 ]
61 TEST_GET_VALUE_DATA = {"test_value": 42, "nested_test": {"nested_value": 43}}
62 TEST_GET_ITEM_DATA = [
63 ("id", 0),
64 {
65 "id": 1,
66 "name": "Alice",
67 "age": 30,
68 "email": "[email protected]",
69 },
70 {
71 "id": 2,
72 "name": "Bob",
73 "age": 35,
74 "email": "[email protected]",
75 },
76 {
77 "id": 3,
78 "name": "Charlie",
79 "age": 40,
80 "email": "[email protected]",
81 },
82 ]
83
84
85 @pytest.mark.parametrize(
86 ("expected_output", "actual_output", "expected_result"),
87 [
88 pytest.param(
89 TEST_GET_FAILED_LOGS_DATA[0],
90 TEST_GET_FAILED_LOGS_DATA[0],
91 "",
92 id="no difference",
93 ),
94 pytest.param(
95 TEST_GET_FAILED_LOGS_DATA[0],
96 TEST_GET_FAILED_LOGS_DATA[1],
97 "\nExpected `1` as the id, but found `2` instead.\nExpected `Alice` as the name, but found `Bob` instead.\n"
98 "Expected `30` as the age, but found `35` instead.\nExpected `[email protected]` as the email, but found `[email protected]` instead.",
99 id="different data",
100 ),
101 pytest.param(
102 TEST_GET_FAILED_LOGS_DATA[0],
103 {},
104 "\nExpected `1` as the id, but it was not found in the actual output.\nExpected `Alice` as the name, but it was not found in the actual output.\n"
105 "Expected `30` as the age, but it was not found in the actual output.\nExpected `[email protected]` as the email, but it was not found in "
106 "the actual output.",
107 id="empty actual output",
108 ),
109 pytest.param(
110 TEST_GET_FAILED_LOGS_DATA[3],
111 TEST_GET_FAILED_LOGS_DATA[4],
112 "\nExpected `Jon` as the name, but found `Rob` instead.",
113 id="different name",
114 ),
115 ],
116 )
117 def test_get_failed_logs(
118 expected_output: dict[Any, Any],
119 actual_output: dict[Any, Any],
120 expected_result: str,
121 ) -> None:
122 """Test get_failed_logs."""
123 assert get_failed_logs(expected_output, actual_output) == expected_result
124
125
126 @pytest.mark.parametrize(
127 (
128 "list_of_dicts",
129 "input_dict",
130 "default",
131 "required",
132 "var_name",
133 "custom_error_msg",
134 "expected_result",
135 "expected_raise",
136 ),
137 [
138 pytest.param(
139 [],
140 {"id": 1, "name": "Alice"},
141 None,
142 False,
143 None,
144 None,
145 None,
146 does_not_raise(),
147 id="empty list",
148 ),
149 pytest.param(
150 [],
151 {"id": 1, "name": "Alice"},
152 None,
153 True,
154 None,
155 None,
156 None,
157 pytest.raises(ValueError, match=r"not found in the provided list."),
158 id="empty list and required",
159 ),
160 pytest.param(
161 TEST_GET_DICT_SUPERSET_DATA,
162 {"id": 10, "name": "Jack"},
163 None,
164 False,
165 None,
166 None,
167 None,
168 does_not_raise(),
169 id="missing item",
170 ),
171 pytest.param(
172 TEST_GET_DICT_SUPERSET_DATA,
173 {"id": 1, "name": "Alice"},
174 None,
175 False,
176 None,
177 None,
178 TEST_GET_DICT_SUPERSET_DATA[1],
179 does_not_raise(),
180 id="found item",
181 ),
182 pytest.param(
183 TEST_GET_DICT_SUPERSET_DATA,
184 {"id": 10, "name": "Jack"},
185 "default_value",
186 False,
187 None,
188 None,
189 "default_value",
190 does_not_raise(),
191 id="default value",
192 ),
193 pytest.param(
194 TEST_GET_DICT_SUPERSET_DATA,
195 {"id": 10, "name": "Jack"},
196 None,
197 True,
198 None,
199 None,
200 None,
201 pytest.raises(ValueError, match=r"not found in the provided list."),
202 id="required",
203 ),
204 pytest.param(
205 TEST_GET_DICT_SUPERSET_DATA,
206 {"id": 10, "name": "Jack"},
207 None,
208 True,
209 "custom_var_name",
210 None,
211 None,
212 pytest.raises(ValueError, match=r"custom_var_name not found in the provided list."),
213 id="custom var_name",
214 ),
215 pytest.param(
216 TEST_GET_DICT_SUPERSET_DATA,
217 {"id": 1, "name": "Alice"},
218 None,
219 True,
220 "custom_var_name",
221 "Custom error message",
222 TEST_GET_DICT_SUPERSET_DATA[1],
223 does_not_raise(),
224 id="custom error message",
225 ),
226 pytest.param(
227 TEST_GET_DICT_SUPERSET_DATA,
228 {"id": 10, "name": "Jack"},
229 None,
230 True,
231 "custom_var_name",
232 "Custom error message",
233 None,
234 pytest.raises(ValueError, match=r"Custom error message"),
235 id="custom error message and required",
236 ),
237 pytest.param(
238 TEST_GET_DICT_SUPERSET_DATA,
239 {"id": 1, "name": "Jack"},
240 None,
241 False,
242 None,
243 None,
244 None,
245 does_not_raise(),
246 id="id ok but name not ok",
247 ),
248 pytest.param(
249 "not a list",
250 {"id": 1, "name": "Alice"},
251 None,
252 True,
253 None,
254 None,
255 None,
256 pytest.raises(ValueError, match=r"not found in the provided list."),
257 id="non-list input for list_of_dicts",
258 ),
259 pytest.param(
260 TEST_GET_DICT_SUPERSET_DATA,
261 "not a dict",
262 None,
263 True,
264 None,
265 None,
266 None,
267 pytest.raises(ValueError, match=r"not found in the provided list."),
268 id="non-dictionary input",
269 ),
270 pytest.param(
271 TEST_GET_DICT_SUPERSET_DATA,
272 {},
273 None,
274 False,
275 None,
276 None,
277 None,
278 does_not_raise(),
279 id="empty dictionary input",
280 ),
281 pytest.param(
282 TEST_GET_DICT_SUPERSET_DATA,
283 {"id": 1, "name": "Alice", "extra_key": "extra_value"},
284 None,
285 True,
286 None,
287 None,
288 None,
289 pytest.raises(ValueError, match=r"not found in the provided list."),
290 id="input dictionary with extra keys",
291 ),
292 pytest.param(
293 TEST_GET_DICT_SUPERSET_DATA,
294 {"id": 1},
295 None,
296 False,
297 None,
298 None,
299 TEST_GET_DICT_SUPERSET_DATA[1],
300 does_not_raise(),
301 id="input dictionary is a subset of more than one dictionary in list_of_dicts",
302 ),
303 pytest.param(
304 TEST_GET_DICT_SUPERSET_DATA,
305 {
306 "id": 1,
307 "name": "Alice",
308 "age": 30,
309 "email": "[email protected]",
310 "extra_key": "extra_value",
311 },
312 None,
313 True,
314 None,
315 None,
316 None,
317 pytest.raises(ValueError, match=r"not found in the provided list."),
318 id="input dictionary is a superset of a dictionary in list_of_dicts",
319 ),
320 ],
321 )
322 def test_get_dict_superset(
323 list_of_dicts: list[dict[Any, Any]],
324 input_dict: dict[Any, Any],
325 default: str | None,
326 required: bool,
327 var_name: str | None,
328 custom_error_msg: str | None,
329 expected_result: str,
330 expected_raise: AbstractContextManager[Exception],
331 ) -> None:
332 """Test get_dict_superset."""
333 with expected_raise:
334 assert get_dict_superset(list_of_dicts, input_dict, default, var_name, custom_error_msg, required=required) == expected_result
335
336
337 @pytest.mark.parametrize(
338 (
339 "input_dict",
340 "key",
341 "default",
342 "required",
343 "org_key",
344 "separator",
345 "expected_result",
346 "expected_raise",
347 ),
348 [
349 pytest.param({}, "test", None, False, None, None, None, does_not_raise(), id="empty dict"),
350 pytest.param(
351 TEST_GET_VALUE_DATA,
352 "test_value",
353 None,
354 False,
355 None,
356 None,
357 42,
358 does_not_raise(),
359 id="simple key",
360 ),
361 pytest.param(
362 TEST_GET_VALUE_DATA,
363 "nested_test.nested_value",
364 None,
365 False,
366 None,
367 None,
368 43,
369 does_not_raise(),
370 id="nested_key",
371 ),
372 pytest.param(
373 TEST_GET_VALUE_DATA,
374 "missing_value",
375 None,
376 False,
377 None,
378 None,
379 None,
380 does_not_raise(),
381 id="missing_value",
382 ),
383 pytest.param(
384 TEST_GET_VALUE_DATA,
385 "missing_value_with_default",
386 "default_value",
387 False,
388 None,
389 None,
390 "default_value",
391 does_not_raise(),
392 id="default",
393 ),
394 pytest.param(
395 TEST_GET_VALUE_DATA,
396 "missing_required",
397 None,
398 True,
399 None,
400 None,
401 None,
402 pytest.raises(ValueError, match=r"missing_required"),
403 id="required",
404 ),
405 pytest.param(
406 TEST_GET_VALUE_DATA,
407 "missing_required",
408 None,
409 True,
410 "custom_org_key",
411 None,
412 None,
413 pytest.raises(ValueError, match=r"custom_org_key"),
414 id="custom org_key",
415 ),
416 pytest.param(
417 TEST_GET_VALUE_DATA,
418 "nested_test||nested_value",
419 None,
420 None,
421 None,
422 "||",
423 43,
424 does_not_raise(),
425 id="custom separator",
426 ),
427 ],
428 )
429 def test_get_value(
430 input_dict: dict[Any, Any],
431 key: str,
432 default: str | None,
433 required: bool,
434 org_key: str | None,
435 separator: str | None,
436 expected_result: int | str | None,
437 expected_raise: AbstractContextManager[Exception],
438 ) -> None:
439 """Test get_value."""
440 kwargs = {
441 "default": default,
442 "required": required,
443 "org_key": org_key,
444 "separator": separator,
445 }
446 kwargs = {k: v for k, v in kwargs.items() if v is not None}
447 with expected_raise:
448 assert get_value(input_dict, key, **kwargs) == expected_result # type: ignore[arg-type]
449
450
451 @pytest.mark.parametrize(
452 ("list_of_dicts", "key", "value", "default", "required", "case_sensitive", "var_name", "custom_error_msg", "expected_result", "expected_raise"),
453 [
454 pytest.param([], "name", "Bob", None, False, False, None, None, None, does_not_raise(), id="empty list"),
455 pytest.param([], "name", "Bob", None, True, False, None, None, None, pytest.raises(ValueError, match=r"name"), id="empty list and required"),
456 pytest.param(TEST_GET_ITEM_DATA, "name", "Jack", None, False, False, None, None, None, does_not_raise(), id="missing item"),
457 pytest.param(TEST_GET_ITEM_DATA, "name", "Alice", None, False, False, None, None, TEST_GET_ITEM_DATA[1], does_not_raise(), id="found item"),
458 pytest.param(TEST_GET_ITEM_DATA, "name", "Jack", "default_value", False, False, None, None, "default_value", does_not_raise(), id="default value"),
459 pytest.param(TEST_GET_ITEM_DATA, "name", "Jack", None, True, False, None, None, None, pytest.raises(ValueError, match=r"name"), id="required"),
460 pytest.param(TEST_GET_ITEM_DATA, "name", "Bob", None, False, True, None, None, TEST_GET_ITEM_DATA[2], does_not_raise(), id="case sensitive"),
461 pytest.param(TEST_GET_ITEM_DATA, "name", "charlie", None, False, False, None, None, TEST_GET_ITEM_DATA[3], does_not_raise(), id="case insensitive"),
462 pytest.param(
463 TEST_GET_ITEM_DATA,
464 "name",
465 "Jack",
466 None,
467 True,
468 False,
469 "custom_var_name",
470 None,
471 None,
472 pytest.raises(ValueError, match=r"custom_var_name"),
473 id="custom var_name",
474 ),
475 pytest.param(
476 TEST_GET_ITEM_DATA,
477 "name",
478 "Jack",
479 None,
480 True,
481 False,
482 None,
483 "custom_error_msg",
484 None,
485 pytest.raises(ValueError, match=r"custom_error_msg"),
486 id="custom error msg",
487 ),
488 ],
489 )
490 def test_get_item(
491 list_of_dicts: list[dict[Any, Any]],
492 key: str,
493 value: str | None,
494 default: str | None,
495 required: bool,
496 case_sensitive: bool,
497 var_name: str | None,
498 custom_error_msg: str | None,
499 expected_result: str,
500 expected_raise: AbstractContextManager[Exception],
501 ) -> None:
502 """Test get_item."""
503 with expected_raise:
504 assert get_item(list_of_dicts, key, value, default, var_name, custom_error_msg, required=required, case_sensitive=case_sensitive) == expected_result
505
506
507 @pytest.mark.parametrize(
508 ("numerator", "denominator", "expected_result"),
509 [
510 pytest.param(4.0, 2.0, 2, id="int return for float input"),
511 pytest.param(4, 2, 2, id="int return for int input"),
512 pytest.param(5.0, 2.0, 2.5, id="float return for float input"),
513 pytest.param(5, 2, 2.5, id="float return for int input"),
514 ],
515 )
516 def test_custom_division(numerator: float, denominator: float, expected_result: str) -> None:
517 """Test custom_division."""
518 assert custom_division(numerator, denominator) == expected_result
519
520
521 @pytest.mark.parametrize(
522 ("test_input", "expected_raise", "expected_result"),
523 [
524 pytest.param([], does_not_raise(), [], id="empty list"),
525 pytest.param(["bgp", "system", "vlan", "configuration"], does_not_raise(), ["BGP", "System", "VLAN", "Configuration"], id="list with acronyms and titles"),
526 pytest.param(42, pytest.raises(TypeError, match=r"Wrong input type"), None, id="wrong input type"),
527 ],
528 )
529 def test_convert_categories(test_input: list[str], expected_raise: AbstractContextManager[Exception], expected_result: list[str]) -> None:
530 """Test convert_categories."""
531 with expected_raise:
532 assert convert_categories(test_input) == expected_result
533
534
535 @pytest.mark.parametrize(
536 ("input_data", "expected_output"),
537 [
538 pytest.param({"advertised": True, "received": True, "enabled": True}, "Advertised: True, Received: True, Enabled: True", id="multiple entry, all True"),
539 pytest.param({"advertised": False, "received": False}, "Advertised: False, Received: False", id="multiple entry, all False"),
540 pytest.param({}, "", id="empty dict"),
541 pytest.param({"test": True}, "Test: True", id="single entry"),
542 ],
543 )
544 def test_format_data(input_data: dict[str, bool], expected_output: str) -> None:
545 """Test format_data."""
546 assert format_data(input_data) == expected_output
547
548
549 CANONICAL_TYPES = {
550 "ethernet": "Ethernet",
551 "portchannel": "Port-Channel",
552 "vlan": "Vlan",
553 "loopback": "Loopback",
554 "management": "Management",
555 "tunnel": "Tunnel",
556 "fabric": "Fabric",
557 "vxlan": "Vxlan",
558 "dps": "Dps",
559 "recircchannel": "Recirc-Channel",
560 }
561
562
563 @pytest.mark.parametrize(
564 ("input_params", "expected_output"),
565 [
566 # Docstring Examples
567 pytest.param({"interface": "Ethernet1", "ignored_interfaces": [CANONICAL_TYPES["ethernet"], "Port-Channel1"]}, True, id="doc_ex1_prefix_match_type"),
568 pytest.param({"interface": "Ethernet2", "ignored_interfaces": ["Ethernet1", CANONICAL_TYPES["portchannel"]]}, False, id="doc_ex2_no_match"),
569 pytest.param(
570 {"interface": "Port-Channel1", "ignored_interfaces": ["Ethernet1", CANONICAL_TYPES["portchannel"]]}, True, id="doc_ex3_prefix_match_type_portchannel"
571 ),
572 pytest.param({"interface": "Ethernet1/1", "ignored_interfaces": ["Ethernet1/1", CANONICAL_TYPES["portchannel"]]}, True, id="doc_ex4_exact_match_subif"),
573 pytest.param(
574 {"interface": "Ethernet1/1", "ignored_interfaces": ["Ethernet1", CANONICAL_TYPES["portchannel"]]}, False, id="doc_ex5_no_match_specific_ignored_name"
575 ),
576 pytest.param(
577 {"interface": "Ethernet1.100", "ignored_interfaces": ["Ethernet1.100", CANONICAL_TYPES["portchannel"]]}, True, id="doc_ex6_exact_match_dot_subif"
578 ),
579 # Cases for None or Empty ignored_interfaces (function returns None)
580 pytest.param({"interface": "Loopback0", "ignored_interfaces": None}, None, id="none_ignored_list"),
581 pytest.param({"interface": "Management1", "ignored_interfaces": []}, None, id="empty_ignored_list"),
582 # Exact Match Cases (full interface names in ignored_interfaces list)
583 pytest.param({"interface": "Vlan20", "ignored_interfaces": ["Vlan20", CANONICAL_TYPES["ethernet"]]}, True, id="exact_match_Vlan20"),
584 pytest.param(
585 {"interface": "Port-Channel200", "ignored_interfaces": ["port-channel200", CANONICAL_TYPES["ethernet"]]}, False, id="exact_match_case_sensitive_fail"
586 ),
587 pytest.param(
588 {"interface": "Port-Channel200", "ignored_interfaces": ["Port-Channel200", CANONICAL_TYPES["ethernet"]]}, True, id="exact_match_case_sensitive_pass"
589 ),
590 pytest.param({"interface": "Ethernet1/1/1", "ignored_interfaces": ["ethernet1/1/1"]}, False, id="exact_match_subif_case_fail"),
591 pytest.param({"interface": "Ethernet1/1/1", "ignored_interfaces": ["Ethernet1/1/1"]}, True, id="exact_match_subif_case_pass"),
592 # Prefix Match Cases (interface types in ignored_interfaces list)
593 pytest.param(
594 {"interface": "Ethernet10/1", "ignored_interfaces": [CANONICAL_TYPES["ethernet"], CANONICAL_TYPES["loopback"]]}, True, id="prefix_match_Ethernet_type"
595 ),
596 pytest.param(
597 {"interface": "Port-Channel123", "ignored_interfaces": [CANONICAL_TYPES["portchannel"], CANONICAL_TYPES["vlan"]]},
598 True,
599 id="prefix_match_PortChannel_type",
600 ),
601 pytest.param({"interface": "Tunnel5", "ignored_interfaces": [CANONICAL_TYPES["tunnel"], CANONICAL_TYPES["vxlan"]]}, True, id="prefix_match_Tunnel_type"),
602 pytest.param({"interface": "Fabric1/2", "ignored_interfaces": [CANONICAL_TYPES["fabric"]]}, True, id="prefix_match_Fabric_type"),
603 pytest.param({"interface": "Dps1", "ignored_interfaces": [CANONICAL_TYPES["dps"]]}, True, id="prefix_match_Dps_type"),
604 pytest.param({"interface": "Recirc-Channel2/1", "ignored_interfaces": [CANONICAL_TYPES["recircchannel"]]}, True, id="prefix_match_RecircChannel_type"),
605 # Prefix Match: Case sensitivity of items in ignored_interfaces
606 pytest.param(
607 {"interface": "Ethernet20/1", "ignored_interfaces": ["ethernet", CANONICAL_TYPES["loopback"]]}, False, id="prefix_match_vs_lowercase_type_in_list_fail"
608 ),
609 pytest.param({"interface": "Vlan30.10", "ignored_interfaces": ["vlan"]}, False, id="prefix_match_vs_lowercase_vlan_in_list_fail"), # "Vlan" vs "vlan"
610 # Mixed: Exact name vs. Type in ignored_interfaces
611 pytest.param({"interface": "Ethernet1", "ignored_interfaces": ["Ethernet1"]}, True, id="mixed_exact_name_match_Ethernet1"),
612 pytest.param({"interface": "Ethernet1", "ignored_interfaces": [CANONICAL_TYPES["ethernet"]]}, True, id="mixed_type_match_Ethernet"),
613 pytest.param({"interface": "Ethernet1/1", "ignored_interfaces": [CANONICAL_TYPES["ethernet"]]}, True, id="mixed_type_match_subif_Ethernet"),
614 pytest.param({"interface": "Management1", "ignored_interfaces": ["Management1", CANONICAL_TYPES["management"]]}, True, id="mixed_exact_and_type_present"),
615 # No Match Cases
616 pytest.param(
617 {"interface": "Management1/1", "ignored_interfaces": [CANONICAL_TYPES["ethernet"], "Vlan10"]}, False, id="no_match_completely_different_types_and_names"
618 ),
619 pytest.param(
620 {"interface": "Loopback0", "ignored_interfaces": ["Loopback1", CANONICAL_TYPES["vxlan"]]}, False, id="no_match_specific_names_different_number"
621 ),
622 pytest.param({"interface": "Ethernet1", "ignored_interfaces": ["Eth", CANONICAL_TYPES["loopback"]]}, False, id="no_match_partial_prefix_in_list"),
623 pytest.param({"interface": "Vxlan1", "ignored_interfaces": [CANONICAL_TYPES["vlan"]]}, False, id="no_match_vxlan_vs_vlan_type"),
624 ],
625 )
626 def test_is_interface_ignored(input_params: dict[str, Any], expected_output: bool | None) -> None:
627 """Tests the is_interface_ignored function with various inputs, assuming Pydantic has validated and canonicalized interface names."""
628 interface_value = input_params["interface"]
629 ignored_interfaces_value = input_params["ignored_interfaces"]
630 assert is_interface_ignored(interface_value, ignored_interfaces_value) == expected_output
631
632
633 @pytest.mark.parametrize(
634 ("time_delta", "expected_output"),
635 [
636 pytest.param(timedelta(seconds=30), "less than a minute", id="less_than_a_minute"),
637 pytest.param(timedelta(minutes=1), "1 minute", id="one_minute"),
638 pytest.param(timedelta(minutes=1, seconds=10), "1 minute", id="one_minute_plus_seconds"),
639 pytest.param(timedelta(minutes=15), "15 minutes", id="multiple_minutes"),
640 pytest.param(timedelta(hours=1), "1 hour", id="one_hour"),
641 pytest.param(timedelta(hours=1, minutes=10), "1 hour and 10 minutes", id="one_hour_and_minutes"),
642 pytest.param(timedelta(hours=3), "3 hours", id="multiple_hours"),
643 pytest.param(timedelta(hours=2, minutes=45), "2 hours and 45 minutes", id="multiple_hours_and_minutes"),
644 pytest.param(timedelta(days=1), "1 day", id="one_day"),
645 pytest.param(timedelta(days=1, hours=5), "1 day", id="one_day_plus_hours"),
646 pytest.param(timedelta(days=5), "5 days", id="multiple_days"),
647 pytest.param(timedelta(seconds=0), "less than a minute", id="exactly_now"),
648 ],
649 )
650 def test_time_ago(time_delta: timedelta, expected_output: str) -> None:
651 """Tests the time_ago function with various time deltas."""
652 now = datetime.now(timezone.utc)
653 test_timestamp = (now - time_delta).timestamp()
654
655 assert time_ago(test_timestamp) == expected_output
656
657
658 async def test_cprofile_enabled(setenvvar: pytest.MonkeyPatch, tmp_path: Path) -> None:
659 """Verify the cprofile decorator when ANTA_CPROFILE is set."""
660 setenvvar.setenv("ANTA_CPROFILE", str(tmp_path / "run.profile"))
661 async_mock = AsyncMock()
662
663 await cprofile()(async_mock)()
664
665 assert (tmp_path / "run.profile").exists()
666 async_mock.assert_called_once()
667
668
669 async def test_cprofile_disabled(setenvvar: pytest.MonkeyPatch) -> None:
670 """Verify the cprofile decorator when ANTA_CPROFILE is not set."""
671 setenvvar.delenv("ANTA_CPROFILE", raising=False)
672 async_mock = AsyncMock()
673
674 with patch("cProfile.Profile.enable") as profiler_enabled, patch("cProfile.Profile.disable") as profiler_disabled:
675 await cprofile()(async_mock)()
676
677 async_mock.assert_called_once()
678 profiler_enabled.assert_not_called()
679 profiler_disabled.assert_not_called()