Files
Cerbero-mcp/tests/unit/common/test_logging.py
T
AdrianoDev 993326136b test(V2): migrazione test common/
Copiati e aggiornati i test da services/common/tests/ a tests/unit/common/.
Import aggiornati da mcp_common a cerbero_mcp.common. Eliminati test di
funzionalità V1-only (app_factory, environment, auth/Principal, server_base).
Refactored test_audit.py (principal→actor str) e test_mcp_bridge.py
(TokenStore→valid_tokens set). 71/71 test passano.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-30 18:16:26 +02:00

78 lines
2.3 KiB
Python

import json
import logging
from cerbero_mcp.common.logging import (
SecretsFilter,
configure_root_logging,
get_json_logger,
)
def test_secrets_filter_masks_bearer():
f = SecretsFilter()
rec = logging.LogRecord(
name="t", level=logging.INFO, pathname="", lineno=0,
msg="Got Bearer abcdef123456 from client",
args=(), exc_info=None,
)
f.filter(rec)
assert "abcdef" not in rec.msg
assert "***" in rec.msg
def test_secrets_filter_masks_api_key_json():
f = SecretsFilter()
rec = logging.LogRecord(
name="t", level=logging.INFO, pathname="", lineno=0,
msg='{"api_key": "sk-live-abc123xyz"}',
args=(), exc_info=None,
)
f.filter(rec)
assert "sk-live-abc123xyz" not in rec.msg
def test_json_logger_outputs_json(capsys):
logger = get_json_logger("test")
logger.info("hello", extra={"user_id": 42})
captured = capsys.readouterr()
# output is on stderr by default for json logger
line = (captured.err or captured.out).strip().splitlines()[-1]
data = json.loads(line)
assert data["message"] == "hello"
assert data["user_id"] == 42
def test_configure_root_json_format(monkeypatch, capsys):
monkeypatch.setenv("LOG_FORMAT", "json")
monkeypatch.setenv("LOG_LEVEL", "INFO")
configure_root_logging()
logging.info("root json test")
line = capsys.readouterr().err.strip().splitlines()[-1]
data = json.loads(line)
assert data["message"] == "root json test"
assert data["levelname"] == "INFO"
def test_configure_root_text_format(monkeypatch, capsys):
monkeypatch.setenv("LOG_FORMAT", "text")
configure_root_logging()
logging.info("root text test")
line = capsys.readouterr().err.strip().splitlines()[-1]
# text format non è JSON parseable
try:
json.loads(line)
raise AssertionError("expected text format, got JSON")
except json.JSONDecodeError:
pass
assert "root text test" in line
def test_configure_root_applies_secrets_filter(monkeypatch, capsys):
monkeypatch.setenv("LOG_FORMAT", "json")
configure_root_logging()
logging.info("calling with Bearer sk-live-leak123456 token")
line = capsys.readouterr().err.strip().splitlines()[-1]
data = json.loads(line)
assert "sk-live-leak123456" not in data["message"]
assert "***" in data["message"]