78 lines
2.3 KiB
Python
78 lines
2.3 KiB
Python
import json
|
|
import logging
|
|
|
|
from 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"]
|