This commit is contained in:
+22
-26
@@ -1,16 +1,13 @@
|
||||
import logging
|
||||
import logzero
|
||||
from logzero import setup_logger
|
||||
import pytest
|
||||
import tempfile
|
||||
import subprocess
|
||||
import os
|
||||
import sys
|
||||
import importlib
|
||||
import textwrap
|
||||
from logzero import logger as log
|
||||
from slic.utils.logcfg import add_log_Level, logcfg, setup_import_logging
|
||||
import slic.utils.logcfg as module
|
||||
|
||||
# Set for all the tests
|
||||
@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
|
||||
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):
|
||||
captured = []
|
||||
monkeypatch.setattr(module.log, "trace", lambda msg: captured.append(msg))
|
||||
def test_import_logging_once_per_module():
|
||||
code = textwrap.dedent("""
|
||||
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
|
||||
reset_imports()
|
||||
env = os.environ.copy()
|
||||
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
|
||||
import importlib
|
||||
for m in ("math", "io", "random"):
|
||||
importlib.import_module(m)
|
||||
result = subprocess.run([sys.executable, tmp_path], capture_output=True, text=True, env=env)
|
||||
os.remove(tmp_path)
|
||||
|
||||
# Verify logs
|
||||
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)
|
||||
assert result.returncode == 0, f"Script failed:\n{result.stderr}"
|
||||
|
||||
stderr = result.stderr
|
||||
print(stderr)
|
||||
lines = stderr.splitlines()
|
||||
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}"
|
||||
count = sum(1 for line in lines if f"importing: {mod}" in line)
|
||||
assert count == 1, f"Expected 1 import log for '{mod}', found {count}"
|
||||
|
||||
Reference in New Issue
Block a user