hermes-trace/tests/test_env_int.py

103 lines
3.3 KiB
Python

"""Tests for validated integer environment variable parsing."""
from __future__ import annotations
import importlib.util
import os
import sys
import unittest
from unittest.mock import patch
_plugin_root = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
_plugin_init = os.path.join(_plugin_root, "__init__.py")
_module_name = "hermes_trace_env_plugin"
_original_module = sys.modules.get(_module_name)
_spec = importlib.util.spec_from_file_location(
_module_name,
_plugin_init,
submodule_search_locations=[_plugin_root],
)
_plugin = importlib.util.module_from_spec(_spec)
sys.modules[_module_name] = _plugin
_spec.loader.exec_module(_plugin)
def tearDownModule() -> None:
"""Restore the module registry entry changed during test import."""
if _original_module is None:
sys.modules.pop(_module_name, None)
else:
sys.modules[_module_name] = _original_module
_env_int = _plugin._env_int
class TestEnvInt(unittest.TestCase):
"""Unit tests for the ``_env_int`` helper."""
def test_unset_uses_default(self) -> None:
"""An unset variable returns the configured default."""
with patch.dict(os.environ, {}, clear=True):
self.assertEqual(_env_int("TEST_INT", 42, 1), 42)
def test_valid_value_is_parsed(self) -> None:
"""A valid integer within the bounds is returned."""
with patch.dict(os.environ, {"TEST_INT": "65535"}, clear=True):
self.assertEqual(_env_int("TEST_INT", 42, 1, 65535), 65535)
def test_non_integer_uses_default(self) -> None:
"""A non-integer value logs a warning and returns the default."""
with (
patch.dict(os.environ, {"TEST_INT": "invalid"}, clear=True),
self.assertLogs(_module_name, level="WARNING") as logs,
):
self.assertEqual(_env_int("TEST_INT", 42, 1), 42)
self.assertEqual(
logs.output,
[
(
"WARNING:hermes_trace_env_plugin._state:Invalid TEST_INT='invalid', "
"falling back to 42"
)
],
)
def test_value_below_minimum_uses_default(self) -> None:
"""A value below the lower bound returns the default."""
with (
patch.dict(os.environ, {"TEST_INT": "0"}, clear=True),
self.assertLogs(_module_name, level="WARNING") as logs,
):
self.assertEqual(_env_int("TEST_INT", 42, 1), 42)
self.assertEqual(
logs.output,
[
(
"WARNING:hermes_trace_env_plugin._state:TEST_INT=0 out of range "
"[1, ∞], falling back to 42"
)
],
)
def test_value_above_maximum_uses_default(self) -> None:
"""A value above the upper bound returns the default."""
with (
patch.dict(os.environ, {"TEST_INT": "65536"}, clear=True),
self.assertLogs(_module_name, level="WARNING") as logs,
):
self.assertEqual(_env_int("TEST_INT", 42, 1, 65535), 42)
self.assertEqual(
logs.output,
[
(
"WARNING:hermes_trace_env_plugin._state:TEST_INT=65536 out of range "
"[1, 65535], falling back to 42"
)
],
)
if __name__ == "__main__":
unittest.main()