diff --git a/tests/test_utils_logcfg.py b/tests/test_utils_logcfg.py index 92e6b6cc..1743d83b 100644 --- a/tests/test_utils_logcfg.py +++ b/tests/test_utils_logcfg.py @@ -51,16 +51,30 @@ 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 = [] - - # Replace the trace method with a capturing lambda monkeypatch.setattr(module.log, "trace", lambda msg: captured.append(msg)) - # Force re-import so the hook is triggered + # Reset all imports except core ones + reset_imports() + + # Now import fresh modules + import importlib for m in ("math", "io", "random"): - sys.modules.pop(m, None) + importlib.import_module(m) + + # 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) for mod in ["math", "io", "random"]: