|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import importlib |
| 4 | +import json |
| 5 | +import logging |
| 6 | +import os |
| 7 | +from collections.abc import Iterator |
| 8 | +from types import ModuleType |
| 9 | + |
| 10 | +import pytest |
| 11 | + |
| 12 | +_LOG_ENV_VARS = ("LOG_FORMAT", "LOG_LEVEL") |
| 13 | + |
| 14 | + |
| 15 | +@pytest.fixture(autouse=True) |
| 16 | +def _restore_logging() -> Iterator[None]: |
| 17 | + """Snapshot and restore global state mutated by these tests. |
| 18 | +
|
| 19 | + Each test reloads app.app_configs / app.logging_config under custom env and |
| 20 | + calls setup_logging(), which mutates both module-level globals and the |
| 21 | + process-wide logging configuration. We restore the logging handlers, the |
| 22 | + LOG_* env vars, and — critically — reload both modules back to their |
| 23 | + baseline so leftover module attributes (e.g. JSON_LOGGING=True) cannot leak |
| 24 | + into the rest of the pytest session, which shares this process. |
| 25 | + """ |
| 26 | + root = logging.getLogger() |
| 27 | + saved_root_handlers = root.handlers[:] |
| 28 | + saved_root_level = root.level |
| 29 | + saved: dict[str, tuple[list[logging.Handler], int, bool]] = {} |
| 30 | + for name in ("uvicorn", "uvicorn.error", "uvicorn.access"): |
| 31 | + lg = logging.getLogger(name) |
| 32 | + saved[name] = (lg.handlers[:], lg.level, lg.propagate) |
| 33 | + saved_env = {var: os.environ.get(var) for var in _LOG_ENV_VARS} |
| 34 | + try: |
| 35 | + yield |
| 36 | + finally: |
| 37 | + root.handlers = saved_root_handlers |
| 38 | + root.setLevel(saved_root_level) |
| 39 | + for name, (handlers, level, propagate) in saved.items(): |
| 40 | + lg = logging.getLogger(name) |
| 41 | + lg.handlers = handlers |
| 42 | + lg.setLevel(level) |
| 43 | + lg.propagate = propagate |
| 44 | + # Restore the env first, then reload so module globals reflect baseline. |
| 45 | + for var, value in saved_env.items(): |
| 46 | + if value is None: |
| 47 | + os.environ.pop(var, None) |
| 48 | + else: |
| 49 | + os.environ[var] = value |
| 50 | + import app.app_configs as app_configs |
| 51 | + import app.logging_config as logging_config |
| 52 | + |
| 53 | + importlib.reload(app_configs) |
| 54 | + importlib.reload(logging_config) |
| 55 | + |
| 56 | + |
| 57 | +def _reload_logging_config( |
| 58 | + monkeypatch: pytest.MonkeyPatch, log_format: str, level: str = "INFO" |
| 59 | +) -> ModuleType: |
| 60 | + """Reload app.app_configs and app.logging_config under the given env.""" |
| 61 | + monkeypatch.setenv("LOG_FORMAT", log_format) |
| 62 | + monkeypatch.setenv("LOG_LEVEL", level) |
| 63 | + import app.app_configs as app_configs |
| 64 | + import app.logging_config as logging_config |
| 65 | + |
| 66 | + importlib.reload(app_configs) |
| 67 | + return importlib.reload(logging_config) |
| 68 | + |
| 69 | + |
| 70 | +def test_plain_format_is_default(monkeypatch: pytest.MonkeyPatch) -> None: |
| 71 | + monkeypatch.delenv("LOG_FORMAT", raising=False) |
| 72 | + import app.app_configs as app_configs |
| 73 | + |
| 74 | + importlib.reload(app_configs) |
| 75 | + assert app_configs.JSON_LOGGING is False |
| 76 | + |
| 77 | + |
| 78 | +def test_plain_logging_output( |
| 79 | + monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] |
| 80 | +) -> None: |
| 81 | + logging_config = _reload_logging_config(monkeypatch, "plain") |
| 82 | + logging_config.setup_logging() |
| 83 | + |
| 84 | + logging.getLogger("app.test").info("hello plain") |
| 85 | + |
| 86 | + err = capsys.readouterr().err |
| 87 | + assert "hello plain" in err |
| 88 | + assert "app.test" in err |
| 89 | + # Plain output is not JSON. |
| 90 | + with pytest.raises(json.JSONDecodeError): |
| 91 | + json.loads(err.strip().splitlines()[-1]) |
| 92 | + |
| 93 | + |
| 94 | +def test_json_logging_output_and_extra_fields( |
| 95 | + monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] |
| 96 | +) -> None: |
| 97 | + logging_config = _reload_logging_config(monkeypatch, "json") |
| 98 | + logging_config.setup_logging() |
| 99 | + |
| 100 | + logging.getLogger("app.test").info("hello json", extra={"session_id": "abc123"}) |
| 101 | + |
| 102 | + line = capsys.readouterr().err.strip().splitlines()[-1] |
| 103 | + payload = json.loads(line) |
| 104 | + |
| 105 | + assert payload["message"] == "hello json" |
| 106 | + assert payload["level"] == "INFO" |
| 107 | + assert payload["logger"] == "app.test" |
| 108 | + # extra fields are promoted to discrete top-level keys. |
| 109 | + assert payload["session_id"] == "abc123" |
| 110 | + # renamed standard fields are present. |
| 111 | + assert "timestamp" in payload |
| 112 | + |
| 113 | + |
| 114 | +def test_json_logging_strips_color_message( |
| 115 | + monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] |
| 116 | +) -> None: |
| 117 | + """Uvicorn's ANSI-coded color_message must not leak into JSON output.""" |
| 118 | + logging_config = _reload_logging_config(monkeypatch, "json") |
| 119 | + logging_config.setup_logging() |
| 120 | + |
| 121 | + logging.getLogger("uvicorn.error").info( |
| 122 | + "Started server", extra={"color_message": "\x1b[36mStarted server\x1b[0m"} |
| 123 | + ) |
| 124 | + |
| 125 | + line = capsys.readouterr().err.strip().splitlines()[-1] |
| 126 | + payload = json.loads(line) |
| 127 | + |
| 128 | + assert payload["message"] == "Started server" |
| 129 | + assert "color_message" not in payload |
| 130 | + |
| 131 | + |
| 132 | +def test_invalid_log_level_falls_back_to_info(monkeypatch: pytest.MonkeyPatch) -> None: |
| 133 | + """A typo'd LOG_LEVEL must not crash startup; it falls back to INFO.""" |
| 134 | + logging_config = _reload_logging_config(monkeypatch, "plain", level="INFOO") |
| 135 | + logging_config.setup_logging() # must not raise |
| 136 | + |
| 137 | + assert logging.getLogger().level == logging.INFO |
| 138 | + |
| 139 | + |
| 140 | +def test_setup_logging_is_idempotent(monkeypatch: pytest.MonkeyPatch) -> None: |
| 141 | + """Repeated calls must not stack duplicate handlers on the root logger.""" |
| 142 | + logging_config = _reload_logging_config(monkeypatch, "plain") |
| 143 | + logging_config.setup_logging() |
| 144 | + logging_config.setup_logging() |
| 145 | + logging_config.setup_logging() |
| 146 | + |
| 147 | + assert len(logging.getLogger().handlers) == 1 |
| 148 | + |
| 149 | + |
| 150 | +def test_uvicorn_loggers_propagate_to_root(monkeypatch: pytest.MonkeyPatch) -> None: |
| 151 | + """Uvicorn loggers should propagate to root and own no handlers of their own.""" |
| 152 | + logging_config = _reload_logging_config(monkeypatch, "json") |
| 153 | + logging_config.setup_logging() |
| 154 | + |
| 155 | + for name in ("uvicorn", "uvicorn.error", "uvicorn.access"): |
| 156 | + lg = logging.getLogger(name) |
| 157 | + assert lg.handlers == [] |
| 158 | + assert lg.propagate is True |
0 commit comments