diff --git a/tests/test_utils_logcfg.py b/tests/test_utils_logcfg.py index 452d1d2a7..c9adbb6a4 100644 --- a/tests/test_utils_logcfg.py +++ b/tests/test_utils_logcfg.py @@ -5,6 +5,9 @@ import pytest import sys import os import importlib +import subprocess +import textwrap +import tempfile sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) from slic.utils.logcfg import * @@ -43,18 +46,40 @@ def test_custom_levels_are_logged(levelname, logfunc, message, ansi_color, capsy # Test: setup_import_logging() -def test_import_logging_multiple_modules(capfd): - add_log_Level(log, "TRACE", logging.DEBUG - 1, func_name="trace") - logcfg("TRACE") - setup_import_logging() +def test_import_logging_once_per_module(): + # Script to run in isolated subprocess + code = textwrap.dedent(""" + import sys + from slic.utils.logcfg import setup_import_logging, add_log_Level, logcfg + from logzero import logger as log + import logging - modules_to_test = ["json", "math", "io", "random"] - for name in modules_to_test: - importlib.reload(__import__(name)) + add_log_Level(log, "TRACE", logging.DEBUG - 1, func_name="trace") + logcfg("TRACE") + setup_import_logging() - out, err = capfd.readouterr() + import json + import math + import io + import random + import json + import math + import random + """) - for mod in modules_to_test: - assert f"importing: {mod}" in err, f"Missing import log for {mod}" - assert err.count(f"importing: {mod}") == 1 + # Write the script to a temp file and run it + with tempfile.NamedTemporaryFile("w", suffix=".py", delete=False) as tmp: + tmp.write(code) + tmp_path = tmp.name + + result = subprocess.run([sys.executable, tmp_path], capture_output=True, text=True) + + stderr = result.stderr + + # Clean up temp file + os.remove(tmp_path) + + # Assert that each module is logged only once + for mod in ["json", "math", "io", "random"]: + assert stderr.count(f"importing: {mod}") == 1, f"Module '{mod}' logged multiple times"