|
| 1 | +"""Tests for the structured logging module.""" |
| 2 | + |
| 3 | +import json |
| 4 | +import logging |
| 5 | +from unittest.mock import patch |
| 6 | + |
| 7 | +import pytest |
| 8 | + |
| 9 | +from agentcore_rl_toolkit.logging import CorrelatedFormatter, configure_logging |
| 10 | + |
| 11 | + |
| 12 | +@pytest.fixture(autouse=True) |
| 13 | +def reset_root_logger(): |
| 14 | + """Reset root logger state before each test.""" |
| 15 | + root = logging.getLogger() |
| 16 | + original_handlers = root.handlers[:] |
| 17 | + original_level = root.level |
| 18 | + if hasattr(root, "_art_logging_configured"): |
| 19 | + delattr(root, "_art_logging_configured") |
| 20 | + yield |
| 21 | + root.handlers = original_handlers |
| 22 | + root.setLevel(original_level) |
| 23 | + if hasattr(root, "_art_logging_configured"): |
| 24 | + delattr(root, "_art_logging_configured") |
| 25 | + |
| 26 | + |
| 27 | +class TestCorrelatedFormatter: |
| 28 | + def test_outputs_valid_json(self): |
| 29 | + formatter = CorrelatedFormatter() |
| 30 | + record = logging.LogRecord( |
| 31 | + name="test.logger", |
| 32 | + level=logging.INFO, |
| 33 | + pathname="test.py", |
| 34 | + lineno=1, |
| 35 | + msg="hello %s", |
| 36 | + args=("world",), |
| 37 | + exc_info=None, |
| 38 | + ) |
| 39 | + |
| 40 | + output = formatter.format(record) |
| 41 | + parsed = json.loads(output) |
| 42 | + |
| 43 | + assert parsed["level"] == "INFO" |
| 44 | + assert parsed["message"] == "hello world" |
| 45 | + assert parsed["logger"] == "test.logger" |
| 46 | + assert "timestamp" in parsed |
| 47 | + |
| 48 | + @patch("bedrock_agentcore.runtime.BedrockAgentCoreContext.get_session_id", return_value="sess-123") |
| 49 | + @patch("bedrock_agentcore.runtime.BedrockAgentCoreContext.get_request_id", return_value="req-456") |
| 50 | + def test_includes_session_and_request_id(self, mock_req, mock_sess): |
| 51 | + formatter = CorrelatedFormatter() |
| 52 | + record = logging.LogRecord( |
| 53 | + name="test", level=logging.INFO, pathname="", lineno=0, msg="msg", args=(), exc_info=None |
| 54 | + ) |
| 55 | + |
| 56 | + parsed = json.loads(formatter.format(record)) |
| 57 | + |
| 58 | + assert parsed["sessionId"] == "sess-123" |
| 59 | + assert parsed["requestId"] == "req-456" |
| 60 | + |
| 61 | + @patch("bedrock_agentcore.runtime.BedrockAgentCoreContext.get_session_id", return_value=None) |
| 62 | + @patch("bedrock_agentcore.runtime.BedrockAgentCoreContext.get_request_id", return_value=None) |
| 63 | + def test_omits_ids_when_no_context(self, mock_req, mock_sess): |
| 64 | + formatter = CorrelatedFormatter() |
| 65 | + record = logging.LogRecord( |
| 66 | + name="test", level=logging.INFO, pathname="", lineno=0, msg="msg", args=(), exc_info=None |
| 67 | + ) |
| 68 | + |
| 69 | + parsed = json.loads(formatter.format(record)) |
| 70 | + |
| 71 | + assert "sessionId" not in parsed |
| 72 | + assert "requestId" not in parsed |
| 73 | + |
| 74 | + def test_includes_exception_info(self): |
| 75 | + formatter = CorrelatedFormatter() |
| 76 | + |
| 77 | + try: |
| 78 | + raise ValueError("test error") |
| 79 | + except ValueError: |
| 80 | + import sys |
| 81 | + |
| 82 | + exc_info = sys.exc_info() |
| 83 | + |
| 84 | + record = logging.LogRecord( |
| 85 | + name="test", level=logging.ERROR, pathname="", lineno=0, msg="failed", args=(), exc_info=exc_info |
| 86 | + ) |
| 87 | + |
| 88 | + parsed = json.loads(formatter.format(record)) |
| 89 | + |
| 90 | + assert parsed["errorType"] == "ValueError" |
| 91 | + assert parsed["errorMessage"] == "test error" |
| 92 | + assert isinstance(parsed["stackTrace"], list) |
| 93 | + assert len(parsed["stackTrace"]) > 0 |
| 94 | + |
| 95 | + |
| 96 | +class TestConfigureLogging: |
| 97 | + def test_attaches_handler_to_root(self): |
| 98 | + configure_logging() |
| 99 | + |
| 100 | + root = logging.getLogger() |
| 101 | + assert len(root.handlers) == 1 |
| 102 | + assert isinstance(root.handlers[0].formatter, CorrelatedFormatter) |
| 103 | + |
| 104 | + def test_sets_root_level(self): |
| 105 | + configure_logging(level=logging.DEBUG) |
| 106 | + |
| 107 | + assert logging.getLogger().level == logging.DEBUG |
| 108 | + |
| 109 | + def test_idempotent(self): |
| 110 | + configure_logging() |
| 111 | + configure_logging() |
| 112 | + configure_logging() |
| 113 | + |
| 114 | + assert len(logging.getLogger().handlers) == 1 |
| 115 | + |
| 116 | + def test_clears_existing_handlers(self): |
| 117 | + logging.basicConfig(level=logging.INFO) |
| 118 | + assert len(logging.getLogger().handlers) >= 1 |
| 119 | + |
| 120 | + configure_logging() |
| 121 | + |
| 122 | + root = logging.getLogger() |
| 123 | + assert len(root.handlers) == 1 |
| 124 | + assert isinstance(root.handlers[0].formatter, CorrelatedFormatter) |
| 125 | + |
| 126 | + def test_suppresses_sdk_logger_propagation(self): |
| 127 | + configure_logging() |
| 128 | + |
| 129 | + sdk_logger = logging.getLogger("bedrock_agentcore.app") |
| 130 | + assert sdk_logger.propagate is False |
0 commit comments