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: restore logger levels after silencing machine output (#2011)

Amane38d24344aa5
diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md
index 935254d03..b9ef71bb5 100644
--- a/.github/CONTRIBUTING.md
+++ b/.github/CONTRIBUTING.md
@@ -262,6 +262,7 @@ Adding a new language has a dedicated recipe, see
- Add tests for new features and bug fixes
- Place tests in `tests/unit/` or `tests/integration/`
- Run the full suite with `uv run pytest`
+- A test asserting on a `caplog` record needs `caplog.set_level(logging.INFO, logger="<the module's full logger name>")` (or the level you're asserting on) — setting the root logger's level is not enough when an ancestor logger (e.g. `repowise.core`, `repowise.server`) has its own level raised, since Python resolves the *effective* level from the nearest ancestor that has one set, not from root.
### Retrieval guard
diff --git a/packages/cli/src/repowise/cli/commands/_tool_adapters.py b/packages/cli/src/repowise/cli/commands/_tool_adapters.py
index c47fc8aee..7b4be1af9 100644
--- a/packages/cli/src/repowise/cli/commands/_tool_adapters.py
+++ b/packages/cli/src/repowise/cli/commands/_tool_adapters.py
@@ -139,8 +139,8 @@ def run(repo_path: Path, factory: Callable[[], Awaitable[dict]], tool_name: str)
from repowise.cli.helpers import silence_logs_for_machine_output
from repowise.cli.tool_bridge import call_tool
- silence_logs_for_machine_output()
- return call_tool(repo_path, factory, tool_name)
+ with silence_logs_for_machine_output():
+ return call_tool(repo_path, factory, tool_name)
#: MCP tool name -> the CLI command that now does the same thing.
diff --git a/packages/cli/src/repowise/cli/commands/dead_code_cmd.py b/packages/cli/src/repowise/cli/commands/dead_code_cmd.py
index 0822513d4..c2ac18109 100644
--- a/packages/cli/src/repowise/cli/commands/dead_code_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/dead_code_cmd.py
@@ -16,7 +16,7 @@ from repowise.cli.helpers import (
repo_index_session,
resolve_command_target,
run_async,
- silence_logs_for_machine_output,
+ silence_logs_for_machine_output_until_close,
)
from repowise.cli.output import notice_console
from repowise.core.analysis.dead_code.models import DeadCodeFindingData, DeadCodeReport
@@ -283,7 +283,7 @@ def dead_code_command(
detection is not yet supported — run once per repo for now.
"""
if fmt != "table":
- silence_logs_for_machine_output()
+ silence_logs_for_machine_output_until_close()
target = resolve_command_target(
path=path,
diff --git a/packages/cli/src/repowise/cli/commands/doc_drift_cmd.py b/packages/cli/src/repowise/cli/commands/doc_drift_cmd.py
index d182d95eb..610806438 100644
--- a/packages/cli/src/repowise/cli/commands/doc_drift_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/doc_drift_cmd.py
@@ -298,12 +298,12 @@ def _run_check(
write_baseline_path: Path | None,
since: str | None = None,
) -> None:
- from repowise.cli.helpers import silence_logs_for_machine_output
+ from repowise.cli.helpers import silence_logs_for_machine_output_until_close
from repowise.core.analysis.doc_drift.gate import evaluate_gate
from repowise.core.analysis.doc_drift.live import LiveTreeError
# The analyzer's debug line would land in the report a CI log shows.
- silence_logs_for_machine_output()
+ silence_logs_for_machine_output_until_close()
if min_confidence is not None and min_confidence > fail_on:
ci_notices(fmt).print(
f"[yellow]--min-confidence {min_confidence:.2f} is above --fail-on-confidence "
diff --git a/packages/cli/src/repowise/cli/commands/doctor_cmd/command.py b/packages/cli/src/repowise/cli/commands/doctor_cmd/command.py
index b2634a145..f1dd36669 100644
--- a/packages/cli/src/repowise/cli/commands/doctor_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/doctor_cmd/command.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import contextlib
import json
import click
@@ -61,96 +62,95 @@ def doctor_command(
"--repair is not supported with --format json (json mode is read-only)."
)
- if fmt != "table":
- silence_logs_for_machine_output()
+ silencer = silence_logs_for_machine_output() if fmt != "table" else contextlib.nullcontext()
+ with silencer:
+ status = err_console if fmt != "table" else console
- status = err_console if fmt != "table" else console
-
- target = resolve_command_target(
- path=path,
- workspace_flag=workspace,
- no_workspace_flag=no_workspace,
- )
- target.notice(status, command="doctor")
+ target = resolve_command_target(
+ path=path,
+ workspace_flag=workspace,
+ no_workspace_flag=no_workspace,
+ )
+ target.notice(status, command="doctor")
- if fmt == "table":
- # Advisory CLI update check, printed once above the repo check table(s).
- _print_cli_version_status()
+ if fmt == "table":
+ # Advisory CLI update check, printed once above the repo check table(s).
+ _print_cli_version_status()
+
+ if not target.is_workspace:
+ assert target.repo_path is not None
+ all_ok, checks = _run_repo_checks(target.repo_path, repair, fmt=fmt)
+ if fmt != "table":
+ payload = {"ok": all_ok, "checks": [c._asdict() for c in checks]}
+ click.echo(json.dumps(payload, indent=2))
+ if not all_ok:
+ raise SystemExit(1)
+ return
+
+ # Workspace mode — iterate over every entry, run workspace-level
+ # validation, and report a summary table at the end so the user knows
+ # which repos need attention.
+ assert target.ws_root is not None and target.ws_config is not None
+ ws_root = target.ws_root
+ ws_config = target.ws_config
+
+ ws_issues = _run_workspace_checks(ws_root, ws_config, repair=repair, fmt=fmt)
+
+ overall_ok = True
+ not_indexed: list[str] = []
+ all_checks: list[DoctorCheck] = []
+ for entry in ws_config.repos:
+ abs_path = (ws_root / entry.path).resolve()
+ if not abs_path.is_dir():
+ continue
+ if not (abs_path / ".repowise").is_dir():
+ not_indexed.append(entry.alias)
+ continue
+ if fmt == "table":
+ console.print()
+ console.print(
+ f"[bold]── {entry.alias}[/bold] "
+ f"[dim]({entry.path})[/dim]"
+ + (
+ " [bold cyan](primary)[/bold cyan]"
+ if entry.alias == ws_config.default_repo
+ else ""
+ )
+ )
+ ok, checks = _run_repo_checks(abs_path, repair, fmt=fmt)
+ overall_ok = overall_ok and ok
+ all_checks.extend(DoctorCheck(f"{entry.alias}: {c.name}", c.ok, c.detail) for c in checks)
- if not target.is_workspace:
- assert target.repo_path is not None
- all_ok, checks = _run_repo_checks(target.repo_path, repair, fmt=fmt)
if fmt != "table":
- payload = {"ok": all_ok, "checks": [c._asdict() for c in checks]}
+ all_ok = overall_ok and not ws_issues and not not_indexed
+ payload = {
+ "ok": all_ok,
+ "checks": [c._asdict() for c in all_checks],
+ "workspace": {
+ "checked": True,
+ "issues": list(ws_issues),
+ "not_indexed": not_indexed,
+ },
+ }
click.echo(json.dumps(payload, indent=2))
if not all_ok:
raise SystemExit(1)
- return
-
- # Workspace mode — iterate over every entry, run workspace-level
- # validation, and report a summary table at the end so the user knows
- # which repos need attention.
- assert target.ws_root is not None and target.ws_config is not None
- ws_root = target.ws_root
- ws_config = target.ws_config
-
- ws_issues = _run_workspace_checks(ws_root, ws_config, repair=repair, fmt=fmt)
-
- overall_ok = True
- not_indexed: list[str] = []
- all_checks: list[DoctorCheck] = []
- for entry in ws_config.repos:
- abs_path = (ws_root / entry.path).resolve()
- if not abs_path.is_dir():
- continue
- if not (abs_path / ".repowise").is_dir():
- not_indexed.append(entry.alias)
- continue
- if fmt == "table":
- console.print()
+ return
+
+ console.print()
+ if not_indexed:
+ console.print(f"[yellow]Not indexed:[/yellow] {', '.join(not_indexed)}")
+ console.print(" Run [bold]repowise update --workspace[/bold] to index them.")
+ if ws_issues and not repair:
console.print(
- f"[bold]── {entry.alias}[/bold] "
- f"[dim]({entry.path})[/dim]"
- + (
- " [bold cyan](primary)[/bold cyan]"
- if entry.alias == ws_config.default_repo
- else ""
- )
+ f"[yellow]{len(ws_issues)} workspace-level issue(s); "
+ f"rerun with [bold]--repair[/bold] to attempt fixes.[/yellow]"
)
- ok, checks = _run_repo_checks(abs_path, repair, fmt=fmt)
- overall_ok = overall_ok and ok
- all_checks.extend(DoctorCheck(f"{entry.alias}: {c.name}", c.ok, c.detail) for c in checks)
-
- if fmt != "table":
- all_ok = overall_ok and not ws_issues and not not_indexed
- payload = {
- "ok": all_ok,
- "checks": [c._asdict() for c in all_checks],
- "workspace": {
- "checked": True,
- "issues": list(ws_issues),
- "not_indexed": not_indexed,
- },
- }
- click.echo(json.dumps(payload, indent=2))
- if not all_ok:
- raise SystemExit(1)
- return
-
- console.print()
- if not_indexed:
- console.print(f"[yellow]Not indexed:[/yellow] {', '.join(not_indexed)}")
- console.print(" Run [bold]repowise update --workspace[/bold] to index them.")
- if ws_issues and not repair:
- console.print(
- f"[yellow]{len(ws_issues)} workspace-level issue(s); "
- f"rerun with [bold]--repair[/bold] to attempt fixes.[/yellow]"
- )
- workspace_clean = not ws_issues and overall_ok and not not_indexed
- if workspace_clean:
- console.print("[bold green]Workspace healthy.[/bold green]")
- elif overall_ok and not ws_issues:
- console.print("[bold yellow]All indexed repos healthy; some repos unindexed.[/bold yellow]")
- else:
- console.print("[bold yellow]Some checks failed across the workspace.[/bold yellow]")
+ workspace_clean = not ws_issues and overall_ok and not not_indexed
+ if workspace_clean:
+ console.print("[bold green]Workspace healthy.[/bold green]")
+ elif overall_ok and not ws_issues:
+ console.print("[bold yellow]All indexed repos healthy; some repos unindexed.[/bold yellow]")
+ else:
+ console.print("[bold yellow]Some checks failed across the workspace.[/bold yellow]")
diff --git a/packages/cli/src/repowise/cli/commands/health_cmd/command.py b/packages/cli/src/repowise/cli/commands/health_cmd/command.py
index 3599f590e..adeef7872 100644
--- a/packages/cli/src/repowise/cli/commands/health_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/health_cmd/command.py
@@ -21,7 +21,7 @@ from repowise.cli.helpers import (
load_state,
resolve_command_target,
run_async,
- silence_logs_for_machine_output,
+ silence_logs_for_machine_output_until_close,
)
from repowise.core.analysis.health.counts import (
COUNTS,
@@ -196,7 +196,7 @@ def health_command(
# machine-readable format so stdout is pure JSON/Markdown and safe to
# pipe into jq or other tools (e.g. `repowise health --format json | jq .kpis`).
if fmt != "table":
- silence_logs_for_machine_output()
+ silence_logs_for_machine_output_until_close()
# Status output goes to stderr when the user asked for a machine-readable
# format — otherwise rich's banner pollutes stdout and breaks
diff --git a/packages/cli/src/repowise/cli/commands/impacted_tests_cmd.py b/packages/cli/src/repowise/cli/commands/impacted_tests_cmd.py
index 7d6362fd5..1a0f3dfcc 100644
--- a/packages/cli/src/repowise/cli/commands/impacted_tests_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/impacted_tests_cmd.py
@@ -49,7 +49,7 @@ from repowise.cli.helpers import (
repo_index_session,
resolve_command_target,
run_async,
- silence_logs_for_machine_output,
+ silence_logs_for_machine_output_until_close,
)
from repowise.cli.output import emit_json
from repowise.core.analysis.test_selection import RUNNERS
@@ -111,7 +111,7 @@ def impacted_tests_command(
# json/list/args go to downstream tools; keep stdout clean of log noise.
if fmt != "table":
- silence_logs_for_machine_output()
+ silence_logs_for_machine_output_until_close()
repo_path = _resolve_repo_path(repo, fmt)
try:
diff --git a/packages/cli/src/repowise/cli/commands/security_cmd.py b/packages/cli/src/repowise/cli/commands/security_cmd.py
index 5d7dfad49..586562062 100644
--- a/packages/cli/src/repowise/cli/commands/security_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/security_cmd.py
@@ -37,7 +37,7 @@ from repowise.cli.helpers import (
get_db_url_for_repo,
resolve_command_target,
run_async,
- silence_logs_for_machine_output,
+ silence_logs_for_machine_output_until_close,
)
from repowise.cli.output import emit_json, format_option, notice_console
@@ -130,7 +130,7 @@ def security_scan(
return
if output_format == "json":
- silence_logs_for_machine_output()
+ silence_logs_for_machine_output_until_close()
from pathlib import Path
@@ -293,7 +293,7 @@ def security_check(
if staged and revspec:
raise click.UsageError("--staged checks the staged changes; drop REVSPEC.")
if fmt != "table":
- silence_logs_for_machine_output()
+ silence_logs_for_machine_output_until_close()
try:
_check(
_CheckOptions(revspec, fail_on, baseline_path, write_baseline_path, repo, staged, fmt)
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/command.py b/packages/cli/src/repowise/cli/commands/update_cmd/command.py
index 05eb71647..af92a3bb1 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/command.py
@@ -36,7 +36,7 @@ from repowise.cli.helpers import (
rotate_update_log_if_needed,
run_async,
save_state,
- silence_logs_for_machine_output,
+ silence_logs_for_machine_output_until_close,
try_acquire_update_lock,
write_update_pending,
)
@@ -660,7 +660,7 @@ def run_update(
# into whatever runs next in the same process.
emitter: JsonProgressEmitter | None = None
if progress == "json":
- silence_logs_for_machine_output()
+ silence_logs_for_machine_output_until_close()
console.file = sys.stderr
# Restore to None (rather than a captured file object) so `console`
# goes back to resolving sys.stdout dynamically on each print, its
diff --git a/packages/cli/src/repowise/cli/helpers.py b/packages/cli/src/repowise/cli/helpers.py
index 49093e615..06b8f6ef1 100644
--- a/packages/cli/src/repowise/cli/helpers.py
+++ b/packages/cli/src/repowise/cli/helpers.py
@@ -88,36 +88,86 @@ def _clean_flag(value: str | None) -> bool:
# Logging / structlog helpers
# ---------------------------------------------------------------------------
+MACHINE_OUTPUT_LOGGER_NAMES = ("httpx", "httpcore", "repowise.core", "repowise.server")
-def silence_logs_for_machine_output() -> None:
- """Suppress info/debug log output when stdout is machine-readable (JSON/md).
+def silence_logs_for_machine_output():
+ """Suppress info/debug log output while stdout is machine-readable (JSON/md).
Structlog and stdlib loggers write to stdout by default. When a command
emits JSON or Markdown, those lines corrupt the output for downstream
consumers (e.g. ``repowise health --format json | jq .kpis``).
- Call this at the top of any command that supports ``--format json`` or
- ``--format md`` before the ingestion pipeline starts.
+ Context manager, not a bare call: logger levels and the structlog
+ wrapper class are process-global with no other owner, so a caller that
+ forgot to restore them would permanently silence its own process — the
+ case that mattered in practice was a test session, where the mutation
+ outlived the test that made it and broke unrelated caplog assertions
+ later in the same run (see #1976).
+
+ Use as:
+
+ with silence_logs_for_machine_output():
+ emit_json_or_markdown(...)
"""
import logging
- logging.getLogger("httpx").setLevel(logging.ERROR)
- logging.getLogger("httpcore").setLevel(logging.ERROR)
- for _name in ("repowise.core", "repowise.server"):
- logging.getLogger(_name).setLevel(logging.ERROR)
+ loggers = [logging.getLogger(name) for name in MACHINE_OUTPUT_LOGGER_NAMES]
+ previous_levels = [logger.level for logger in loggers]
+
+ previous_structlog_config: dict[str, Any] | None = None
try:
import structlog
- # cache_logger_on_first_use=False is required: module-level
- # ``structlog.get_logger`` calls snapshot the logger before configure()
- # runs and would bypass this filter without it.
- structlog.configure(
- wrapper_class=structlog.make_filtering_bound_logger(logging.ERROR),
- cache_logger_on_first_use=False,
- )
+ previous_structlog_config = dict(structlog.get_config())
except ImportError:
pass
+ try:
+ for logger in loggers:
+ logger.setLevel(logging.ERROR)
+ if previous_structlog_config is not None:
+ import structlog
+
+ # cache_logger_on_first_use=False is required: module-level
+ # ``structlog.get_logger`` calls snapshot the logger before
+ # configure() runs and would bypass this filter without it.
+ structlog.configure(
+ wrapper_class=structlog.make_filtering_bound_logger(logging.ERROR),
+ cache_logger_on_first_use=False,
+ )
+ yield
+ finally:
+ for logger, level in zip(loggers, previous_levels, strict=True):
+ logger.setLevel(level)
+ if previous_structlog_config is not None:
+ import structlog
+
+ structlog.configure(**previous_structlog_config)
+
+def silence_logs_for_machine_output_until_close() -> None:
+ """Enter ``silence_logs_for_machine_output`` and restore it when the
+ current click command finishes.
+
+ ``silence_logs_for_machine_output`` is a context manager because it must
+ always restore what it mutates — but not every call site has a single
+ lexical block to wrap it around. An option callback (see the ``--format``
+ and ``--json`` callbacks in ``output.py``) returns before the command body
+ even starts running, so a ``with`` block there would restore the levels
+ before the command does any work. Re-indenting an entire command
+ function's body under one ``with`` is also a large, easy-to-get-wrong
+ diff at call sites deep inside long functions.
+
+ Solved the same way ``update_cmd`` already solves it for restoring
+ ``console.file``: register the undo against click's context instead of a
+ lexical scope, so it fires when the command finishes regardless of how
+ much code runs in between or where the call sits.
+ """
+ ctx = click.get_current_context()
+ cm = silence_logs_for_machine_output()
+ cm.__enter__()
+ ctx.call_on_close(lambda: cm.__exit__(None, None, None))
+
# ---------------------------------------------------------------------------
# Async bridge
diff --git a/packages/cli/src/repowise/cli/output.py b/packages/cli/src/repowise/cli/output.py
index 3d0e628c7..be357e199 100644
--- a/packages/cli/src/repowise/cli/output.py
+++ b/packages/cli/src/repowise/cli/output.py
@@ -85,9 +85,9 @@ def _silence_when_machine_readable(ctx: Any, param: Any, value: str) -> str:
a module that logs on import.
"""
if value != "table":
- from repowise.cli.helpers import silence_logs_for_machine_output
+ from repowise.cli.helpers import silence_logs_for_machine_output_until_close
- silence_logs_for_machine_output()
+ silence_logs_for_machine_output_until_close()
return value
@@ -121,9 +121,9 @@ def _silence_when_alias_selects_json(ctx: Any, param: Any, value: bool) -> bool:
the one a legacy caller asked for.
"""
if value:
- from repowise.cli.helpers import silence_logs_for_machine_output
+ from repowise.cli.helpers import silence_logs_for_machine_output_until_close
- silence_logs_for_machine_output()
+ silence_logs_for_machine_output_until_close()
return value
diff --git a/tests/conftest.py b/tests/conftest.py
index f4da7dff1..6516bcb8b 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -150,6 +150,40 @@ def _isolate_structlog_config():
finally:
structlog.configure(**saved)
[email protected](autouse=True)
+def _isolate_silenced_logger_levels():
+ """Restore stdlib logger levels mutated by silence_logs_for_machine_output.
+
+ That helper also calls ``logging.getLogger(name).setLevel(logging.ERROR)``
+ on ``httpx``, ``httpcore``, ``repowise.core``, and ``repowise.server`` —
+ process-global state that ``_isolate_structlog_config`` (above) does not
+ touch, since it only snapshots structlog's own configuration.
+
+ Without this, a test that exercises any ``--format json``/``--format md``
+ command leaves those loggers raised to ERROR for the rest of the session.
+ A later test asserting a ``caplog`` record from a module under
+ ``repowise.core`` or ``repowise.server`` then reads an empty list: the
+ module's own logger has no level set, so its *effective* level is
+ inherited from the ancestor now pinned at ERROR, and
+ ``logger.warning(...)`` is dropped before any handler — including
+ ``caplog``'s — ever runs. Same failure shape as the structlog case
+ above: passes when the file is run alone, fails only in a full run,
+ depending on whether a machine-output command executed first (#1976).
+
+ Snapshot and restore rather than reset to ``NOTSET``: a test that sets a
+ level on purpose keeps working, and the next test still starts clean.
+ """
+ import logging
+
+ from repowise.cli.helpers import MACHINE_OUTPUT_LOGGER_NAMES
+
+ loggers = [logging.getLogger(name) for name in MACHINE_OUTPUT_LOGGER_NAMES]
+ previous_levels = [logger.level for logger in loggers]
+ try:
+ yield
+ finally:
+ for logger, level in zip(loggers, previous_levels, strict=True):
+ logger.setLevel(level)
@pytest.fixture(scope="session")
def repo_root() -> Path:
diff --git a/tests/unit/cli/test_tool_adapter_commands.py b/tests/unit/cli/test_tool_adapter_commands.py
index b6a0dd475..b3297581c 100644
--- a/tests/unit/cli/test_tool_adapter_commands.py
+++ b/tests/unit/cli/test_tool_adapter_commands.py
@@ -18,6 +18,7 @@ Three things have to hold and each has tests below.
from __future__ import annotations
+import contextlib
import json
import pytest
@@ -778,9 +779,15 @@ def test_logs_are_silenced_at_every_format_not_only_the_machine_ones(
answer — and inside anything reading it through ``repowise distill``.
"""
silenced: list = []
+
+ @contextlib.contextmanager
+ def _fake_silence():
+ silenced.append(True)
+ yield
+
monkeypatch.setattr(
"repowise.cli.helpers.silence_logs_for_machine_output",
- lambda: silenced.append(True),
+ _fake_silence,
)
monkeypatch.setattr("repowise.cli.tool_bridge.call_tool", lambda p, f, t: {"_meta": {}})
result = CliRunner(mix_stderr=False).invoke(
diff --git a/tests/unit/cli/test_update_full_dry_run.py b/tests/unit/cli/test_update_full_dry_run.py
index dd019e712..60a6713b5 100644
--- a/tests/unit/cli/test_update_full_dry_run.py
+++ b/tests/unit/cli/test_update_full_dry_run.py
@@ -127,7 +127,7 @@ def test_full_dry_run_emits_dry_run_machine_outcome(
repo = tmp_path / "repo"
_prepare_repo(repo)
_patch_boundary(monkeypatch, repo)
- monkeypatch.setattr(update_cmd, "silence_logs_for_machine_output", lambda: None)
+ monkeypatch.setattr(update_cmd, "silence_logs_for_machine_output_until_close", lambda: None)
events: list[tuple[str, dict[str, Any]]] = []
diff --git a/tests/unit/test_structlog_isolation.py b/tests/unit/test_structlog_isolation.py
index 492fa634d..4d84bb17f 100644
--- a/tests/unit/test_structlog_isolation.py
+++ b/tests/unit/test_structlog_isolation.py
@@ -1,14 +1,4 @@
-"""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.
-"""
+"""Machine-output log silencing is limited to its command's lifetime."""
from __future__ import annotations
@@ -18,14 +8,15 @@ 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_machine_output_silences_logs_only_within_its_scope() -> None:
+ structlog.configure(cache_logger_on_first_use=True)
+ with 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:
+ assert structlog.get_config()["cache_logger_on_first_use"] is True
with capture_logs() as logs:
structlog.get_logger(__name__).warning("visible_again")
assert [entry["event"] for entry in logs] == ["visible_again"]