Update tests/test_utils_logcfg.py
Run CI Tests / test (push) Successful in 2m32s

This commit is contained in:
2025-08-29 15:02:59 +02:00
parent 7d56d41477
commit e5dfe835d0
+22 -26
View File
@@ -1,16 +1,13 @@
import logging import logging
import logzero import logzero
from logzero import setup_logger
import pytest import pytest
import tempfile import tempfile
import subprocess import subprocess
import os import os
import sys import sys
import importlib
import textwrap import textwrap
from logzero import logger as log from logzero import logger as log
from slic.utils.logcfg import add_log_Level, logcfg, setup_import_logging from slic.utils.logcfg import add_log_Level, logcfg, setup_import_logging
import slic.utils.logcfg as module
# Set for all the tests # Set for all the tests
@pytest.fixture(scope="module", autouse=True) @pytest.fixture(scope="module", autouse=True)
@@ -51,32 +48,31 @@ def test_custom_log_outputs(levelname, logfunc, message, capsys):
# Test subprocess: top-level import logs only once # Test subprocess: top-level import logs only once
def reset_imports():
"""Reset sys.modules to a minimal safe state."""
keep = {"sys", "builtins", "importlib", "types", "warnings"}
for m in list(sys.modules.keys()):
if m not in keep:
sys.modules.pop(m, None)
def test_import_logging_once_per_module(monkeypatch): def test_import_logging_once_per_module():
captured = [] code = textwrap.dedent("""
monkeypatch.setattr(module.log, "trace", lambda msg: captured.append(msg)) from slic.utils.logcfg import *
import math
import io
import random
""")
with tempfile.NamedTemporaryFile("w", suffix=".py", delete=False) as tmp:
tmp.write(code)
tmp_path = tmp.name
# Reset all imports except core ones env = os.environ.copy()
reset_imports() root_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
env["PYTHONPATH"] = root_path + os.pathsep + env.get("PYTHONPATH", "")
# Now import fresh modules result = subprocess.run([sys.executable, tmp_path], capture_output=True, text=True, env=env)
import importlib os.remove(tmp_path)
for m in ("math", "io", "random"):
importlib.import_module(m)
# Verify logs assert result.returncode == 0, f"Script failed:\n{result.stderr}"
for mod in ("math", "io", "random"):
matches = [msg for msg in captured if f"importing: {mod}" in msg]
assert len(matches) == 1, f"Expected 1 log for {mod}, got {len(matches)}; captured={captured}"
importlib.import_module(m)
stderr = result.stderr
print(stderr)
lines = stderr.splitlines()
for mod in ["math", "io", "random"]: for mod in ["math", "io", "random"]:
matches = [msg for msg in captured if f"importing: {mod}" in msg] count = sum(1 for line in lines if f"importing: {mod}" in line)
assert len(matches) == 1, f"Expected 1 log for {mod}, got {len(matches)}; captured={captured}" assert count == 1, f"Expected 1 import log for '{mod}', found {count}"