Debian Codegraph @

tests/units/test_settings.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 """Unit tests for the anta.settings module."""
5
6 from __future__ import annotations
7
8 import logging
9 import os
10 import sys
11 from unittest.mock import patch
12
13 import pytest
14 from pydantic import ValidationError
15
16 from anta.device import AsyncEOSDevice
17 from anta.settings import DEFAULT_HTTPX_TRUST_ENV, DEFAULT_MAX_CONCURRENCY, DEFAULT_NOFILE, AntaHttpxSettings, AntaRunnerSettings, get_httpx_settings
18
19 if os.name == "posix":
20 # The function is not defined on non-POSIX system
21 import resource
22
23
24 # Some type ignores for https://github.com/pydantic/pydantic-settings/issues/201
25
26
27 class TestAntaRunnerSettings:
28 """Tests for the AntaRunnerSettings class."""
29
30 def test_defaults(self, setenvvar: pytest.MonkeyPatch) -> None:
31 """Test defaults for ANTA runner settings."""
32 settings = AntaRunnerSettings()
33 assert settings.nofile == DEFAULT_NOFILE
34 assert settings.max_concurrency == DEFAULT_MAX_CONCURRENCY
35
36 def test_env_var(self, setenvvar: pytest.MonkeyPatch) -> None:
37 """Test setting different ANTA runner settings."""
38 setenvvar.setenv("ANTA_NOFILE", "20480")
39 settings = AntaRunnerSettings()
40 assert settings.nofile == 20480
41 assert settings.max_concurrency == DEFAULT_MAX_CONCURRENCY
42
43 def test_validation(self, setenvvar: pytest.MonkeyPatch) -> None:
44 """Test validation of ANTA runner settings."""
45 setenvvar.setenv("ANTA_NOFILE", "-1")
46 with pytest.raises(ValidationError):
47 AntaRunnerSettings()
48
49 setenvvar.setenv("ANTA_MAX_CONCURRENCY", "0")
50 with pytest.raises(ValidationError):
51 AntaRunnerSettings()
52
53 @pytest.mark.skipif(os.name == "posix", reason="Run this test on Windows only")
54 def test_file_descriptor_limit_windows(self, caplog: pytest.LogCaptureFixture) -> None:
55 """Test file_descriptor_limit on Windows."""
56 caplog.set_level(logging.INFO)
57 settings = AntaRunnerSettings()
58 assert settings.file_descriptor_limit == sys.maxsize
59 assert "Running on a non-POSIX system, cannot adjust the maximum number of file descriptors." in caplog.text
60
61 @pytest.mark.skipif(os.name != "posix", reason="Fake non-posix for coverage")
62 async def test_file_descriptor_limit_fake_windows(self, caplog: pytest.LogCaptureFixture) -> None:
63 """Test file_descriptor_limit on fake Windows."""
64 caplog.set_level(logging.INFO)
65 with patch("os.name", new="win32"):
66 settings = AntaRunnerSettings()
67 assert settings.file_descriptor_limit == sys.maxsize
68 assert "Running on a non-POSIX system, cannot adjust the maximum number of file descriptors." in caplog.records[0].message
69
70 @pytest.mark.skipif(os.name != "posix", reason="Cannot run this test on Windows")
71 def test_file_descriptor_limit_posix(self, caplog: pytest.LogCaptureFixture) -> None:
72 """Test file_descriptor_limit on POSIX systems."""
73 with (
74 caplog.at_level(logging.DEBUG),
75 patch.dict("os.environ", {"ANTA_NOFILE": "20480"}),
76 patch("resource.getrlimit") as getrlimit_mock,
77 patch("resource.setrlimit") as setrlimit_mock,
78 ):
79 # Simulate the default system limits
80 system_limits = (8192, 1048576)
81
82 # Setup getrlimit mock return value
83 getrlimit_mock.return_value = system_limits
84
85 # Simulate setrlimit behavior
86 def side_effect_setrlimit(_resource_id: int, limits: tuple[int, int]) -> None:
87 getrlimit_mock.return_value = (limits[0], limits[1])
88
89 setrlimit_mock.side_effect = side_effect_setrlimit
90
91 settings = AntaRunnerSettings()
92
93 # Assert the limits were updated as expected
94 assert settings.file_descriptor_limit == 20480
95 assert "Initial file descriptor limits for the current ANTA process: Soft Limit: 8192 | Hard Limit: 1048576" in caplog.text
96 assert "Setting file descriptor soft limit to 20480" in caplog.text
97
98 setrlimit_mock.assert_called_once_with(resource.RLIMIT_NOFILE, (20480, 1048576)) # pylint: disable=possibly-used-before-assignment # pyright: ignore[reportPossiblyUnboundVariable]
99
100 @pytest.mark.skipif(os.name != "posix", reason="Cannot run this test on Windows")
101 def test_file_descriptor_limit_value_error(self, caplog: pytest.LogCaptureFixture) -> None:
102 """Test file_descriptor_limit with invalid environment variables."""
103 with (
104 caplog.at_level(logging.DEBUG),
105 patch.dict("os.environ", {"ANTA_NOFILE": "666"}),
106 patch("resource.getrlimit") as getrlimit_mock,
107 patch("resource.setrlimit") as setrlimit_mock,
108 ):
109 # Simulate the default system limits
110 system_limits = (32768, 131072)
111
112 # Setup getrlimit mock return value
113 getrlimit_mock.return_value = system_limits
114
115 # Simulate setrlimit behavior raising ValueError
116 def side_effect_setrlimit(_resource_id: int, _limits: tuple[int, int]) -> None:
117 msg = "not allowed to raise maximum limit"
118 raise ValueError(msg)
119
120 setrlimit_mock.side_effect = side_effect_setrlimit
121
122 _ = AntaRunnerSettings()
123
124 # Assert the limits were *NOT* updated as expected
125 assert caplog.records[-1].levelname == "WARNING"
126 assert "Failed to set file descriptor soft limit for the current ANTA process" in caplog.records[-1].getMessage()
127
128 setrlimit_mock.assert_called_once_with(resource.RLIMIT_NOFILE, (666, 131072)) # pyright: ignore[reportPossiblyUnboundVariable]
129
130
131 class TestAntaHttpxSettings:
132 """Tests for the AntaHttpxSettings class."""
133
134 def test_defaults(self, setenvvar: pytest.MonkeyPatch) -> None:
135 """Test that AntaHttpxSettings uses default values when no environment variables are set."""
136 httpx_settings = AntaHttpxSettings()
137 assert httpx_settings.trust_env == DEFAULT_HTTPX_TRUST_ENV
138
139 def test_env_var(self, setenvvar: pytest.MonkeyPatch) -> None:
140 """Test that the ANTA_HTTPX_TRUST_ENV environment variable overrides the default trust_env value."""
141 setenvvar.setenv("ANTA_HTTPX_TRUST_ENV", "False")
142 httpx_settings = AntaHttpxSettings()
143 assert httpx_settings.trust_env is False
144
145 @pytest.mark.skipif(os.name != "posix", reason="Cannot run this test on Windows")
146 def test_env_var_attached_to_session(self, setenvvar: pytest.MonkeyPatch) -> None:
147 """Test that the trust_env value from ANTA_HTTPX_SETTINGS singleton is passed to the asynceapi.Device session."""
148 get_httpx_settings.cache_clear()
149 setenvvar.setenv("ANTA_HTTPX_TRUST_ENV", "False")
150 device = AsyncEOSDevice(host="test", username="test", password="test", port=80)
151 assert device._client.trust_env is False
152 get_httpx_settings.cache_clear()
153
154 def test_validation_error(self, setenvvar: pytest.MonkeyPatch) -> None:
155 """Test that get_httpx_settings raises ValueError when an env var is invalid."""
156 get_httpx_settings.cache_clear()
157 setenvvar.setenv("ANTA_HTTPX_TRUST_ENV", "not_a_valid_bool")
158 with pytest.raises(ValueError, match=r"Failed to load ANTA HTTPX settings\. Check ANTA_HTTPX_\* environment variables:"):
159 get_httpx_settings()
160 get_httpx_settings.cache_clear()