Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

fix(tests): restore structlog's global config after every test (#1239)

Raghav Chamadiya168385f13dc0
diff --git a/tests/conftest.py b/tests/conftest.py
index 52a2ea6c6..0359cf134 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -34,6 +34,33 @@ def _no_telemetry_network():
mp.undo()
[email protected](autouse=True)
+def _isolate_structlog_config():
+ """Restore structlog's global configuration after every test.
+
+ ``configure_cli_logging`` / ``silence_logs_for_machine_output`` install a
+ filtering bound logger at ERROR process-wide and never undo it, so the
+ first test to exercise a CLI command silences every ``info`` and
+ ``warning`` for the rest of the session.
+
+ That is invisible until a test asserts on a log record.
+ ``structlog.testing.capture_logs`` swaps the *processor chain*, not the
+ *wrapper class*, so a filtering logger drops the event before ``LogCapture``
+ ever runs and the test reads an empty list. Tests collected after
+ ``tests/unit/cli`` therefore pass alone and fail in a full run.
+
+ Snapshot and restore rather than reset to defaults: a test that configures
+ structlog on purpose keeps working, and the next test still starts clean.
+ """
+ import structlog
+
+ saved = structlog.get_config()
+ try:
+ yield
+ finally:
+ structlog.configure(**saved)
+
+
@pytest.fixture(scope="session")
def repo_root() -> Path:
"""Absolute path to the repository root."""
diff --git a/tests/unit/test_structlog_isolation.py b/tests/unit/test_structlog_isolation.py
new file mode 100644
index 000000000..492fa634d
--- /dev/null
+++ b/tests/unit/test_structlog_isolation.py
@@ -0,0 +1,31 @@
+"""The global structlog config does not leak from one test into the next.
+
+``silence_logs_for_machine_output`` and ``configure_cli_logging`` install a
+filtering bound logger at ERROR for the whole process. Without the autouse
+fixture in ``tests/conftest.py`` that setting outlives the test that made it,
+and every later ``capture_logs`` assertion on an ``info`` or ``warning`` reads
+an empty list. Such a test passes in isolation and fails in a full run.
+
+The two tests below must stay in this order: the first one does the damage,
+the second one proves it was undone.
+"""
+
+from __future__ import annotations
+
+import structlog
+from structlog.testing import capture_logs
+
+from repowise.cli.helpers import silence_logs_for_machine_output
+
+
+def test_a_cli_command_silences_logs_process_wide() -> None:
+ silence_logs_for_machine_output()
+ with capture_logs() as logs:
+ structlog.get_logger(__name__).warning("silenced_here")
+ assert logs == []
+
+
+def test_b_the_next_test_can_still_capture_a_warning() -> None:
+ with capture_logs() as logs:
+ structlog.get_logger(__name__).warning("visible_again")
+ assert [entry["event"] for entry in logs] == ["visible_again"]