Skip to content

Commit 4619040

Browse files
committed
test: fix DummyLokiHandler emit to avoid NotImplementedError (refs #6)
1 parent e29c9de commit 4619040

1 file changed

Lines changed: 60 additions & 0 deletions

File tree

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
import importlib
2+
import logging
3+
from types import ModuleType
4+
5+
import pytest
6+
from fastapi import FastAPI
7+
8+
from app.core import config as cfg
9+
10+
11+
@pytest.mark.parametrize("loki_enabled", [True, False])
12+
def test_logging_handler_selection(tmp_path, monkeypatch, loki_enabled):
13+
"""When Loki enabled and lib present we attach LokiHandler, else RotatingFileHandler."""
14+
15+
# Temp log dir
16+
monkeypatch.chdir(tmp_path)
17+
18+
# Patch settings at runtime
19+
monkeypatch.setattr(cfg.settings, "LOKI_ENABLED", loki_enabled, raising=False)
20+
monkeypatch.setattr(
21+
cfg.settings, "LOKI_ENDPOINT", "http://dummy:3100", raising=False
22+
)
23+
24+
# Reset root handlers to avoid cross-param contamination
25+
logging.getLogger().handlers.clear()
26+
27+
# Re-import observability to reset flags
28+
obs = importlib.reload(importlib.import_module("app.utils.observability"))
29+
30+
# Monkeypatch logging_loki availability based on scenario
31+
if loki_enabled:
32+
33+
class DummyLokiHandler(logging.Handler):
34+
def __init__(self, *args, **kwargs): # accept arbitrary Loki kwargs
35+
super().__init__()
36+
37+
def emit(self, record): # noqa: D401
38+
# Simply drop log records in tests
39+
return
40+
41+
dummy_module = ModuleType("logging_loki")
42+
dummy_module.LokiHandler = DummyLokiHandler # type: ignore[attr-defined]
43+
monkeypatch.setitem(importlib.sys.modules, "logging_loki", dummy_module)
44+
obs._LOKI_READY = True # type: ignore[attr-defined]
45+
else:
46+
# Ensure module import fails
47+
if "logging_loki" in importlib.sys.modules:
48+
del importlib.sys.modules["logging_loki"]
49+
obs._LOKI_READY = False # type: ignore[attr-defined]
50+
51+
# Run configurator
52+
app = FastAPI()
53+
obs.configure_observability(app)
54+
55+
handler_types = {type(h).__name__ for h in logging.getLogger().handlers}
56+
57+
if loki_enabled:
58+
assert "DummyLokiHandler" in handler_types
59+
else:
60+
assert "RotatingFileHandler" in handler_types

0 commit comments

Comments
 (0)