|
| 1 | +"""Unit tests for Splunk HEC client.""" |
| 2 | + |
| 3 | +from pathlib import Path |
| 4 | +from typing import Any |
| 5 | +from unittest.mock import AsyncMock, MagicMock, patch |
| 6 | + |
| 7 | +import aiohttp |
| 8 | +import pytest |
| 9 | + |
| 10 | +from observability.splunk import send_splunk_event, _read_token_from_file |
| 11 | + |
| 12 | + |
| 13 | +@pytest.fixture(name="mock_splunk_config") |
| 14 | +def mock_splunk_config_fixture(tmp_path: Path) -> MagicMock: |
| 15 | + """Create a mock SplunkConfiguration.""" |
| 16 | + token_file = tmp_path / "token" |
| 17 | + token_file.write_text("test-hec-token") |
| 18 | + |
| 19 | + config = MagicMock() |
| 20 | + config.enabled = True |
| 21 | + config.url = "https://splunk.example.com:8088/services/collector" |
| 22 | + config.token_path = token_file |
| 23 | + config.index = "test_index" |
| 24 | + config.source = "test-source" |
| 25 | + config.timeout = 5 |
| 26 | + config.verify_ssl = True |
| 27 | + return config |
| 28 | + |
| 29 | + |
| 30 | +@pytest.fixture(name="mock_session") |
| 31 | +def mock_session_fixture() -> AsyncMock: |
| 32 | + """Create a mock aiohttp session with successful response.""" |
| 33 | + mock_response = AsyncMock() |
| 34 | + mock_response.status = 200 |
| 35 | + session = AsyncMock(spec=aiohttp.ClientSession) |
| 36 | + session.post.return_value.__aenter__.return_value = mock_response |
| 37 | + return session |
| 38 | + |
| 39 | + |
| 40 | +@pytest.mark.parametrize( |
| 41 | + ("token_content", "expected"), |
| 42 | + [ |
| 43 | + (" my-secret-token \n", "my-secret-token"), |
| 44 | + ("token-no-whitespace", "token-no-whitespace"), |
| 45 | + ], |
| 46 | + ids=["strips_whitespace", "no_whitespace"], |
| 47 | +) |
| 48 | +def test_read_token_from_file( |
| 49 | + tmp_path: Path, token_content: str, expected: str |
| 50 | +) -> None: |
| 51 | + """Test reading and stripping token from file.""" |
| 52 | + token_file = tmp_path / "token" |
| 53 | + token_file.write_text(token_content) |
| 54 | + assert _read_token_from_file(str(token_file)) == expected |
| 55 | + |
| 56 | + |
| 57 | +def test_read_token_returns_none_for_missing_file(tmp_path: Path) -> None: |
| 58 | + """Test returns None when file doesn't exist.""" |
| 59 | + assert _read_token_from_file(str(tmp_path / "nonexistent")) is None |
| 60 | + |
| 61 | + |
| 62 | +def _make_config( |
| 63 | + enabled: bool = True, |
| 64 | + url: str | None = "https://splunk:8088", |
| 65 | + token_path: Path | None = None, |
| 66 | + index: str | None = "idx", |
| 67 | +) -> MagicMock: |
| 68 | + """Helper to create mock config with specific fields.""" |
| 69 | + config = MagicMock() |
| 70 | + config.enabled = enabled |
| 71 | + config.url = url |
| 72 | + config.token_path = token_path |
| 73 | + config.index = index |
| 74 | + return config |
| 75 | + |
| 76 | + |
| 77 | +@pytest.mark.asyncio |
| 78 | +@pytest.mark.parametrize( |
| 79 | + ("splunk_config",), |
| 80 | + [ |
| 81 | + (None,), |
| 82 | + (_make_config(enabled=False),), |
| 83 | + (_make_config(url=None, index=None),), |
| 84 | + ], |
| 85 | + ids=["config_none", "disabled", "incomplete"], |
| 86 | +) |
| 87 | +async def test_skips_event_when_not_configured(splunk_config: Any) -> None: |
| 88 | + """Test event is skipped when Splunk is not properly configured.""" |
| 89 | + with patch("observability.splunk.configuration") as mock_config: |
| 90 | + mock_config.splunk = splunk_config |
| 91 | + # Should not raise, just skip silently |
| 92 | + await send_splunk_event({"test": "event"}, "test_sourcetype") |
| 93 | + |
| 94 | + |
| 95 | +@pytest.mark.asyncio |
| 96 | +async def test_sends_event_successfully( |
| 97 | + mock_splunk_config: MagicMock, mock_session: AsyncMock |
| 98 | +) -> None: |
| 99 | + """Test event is sent successfully to Splunk HEC.""" |
| 100 | + with ( |
| 101 | + patch("observability.splunk.configuration") as mock_config, |
| 102 | + patch("observability.splunk.aiohttp.ClientSession") as mock_client, |
| 103 | + ): |
| 104 | + mock_config.splunk = mock_splunk_config |
| 105 | + mock_client.return_value.__aenter__.return_value = mock_session |
| 106 | + |
| 107 | + await send_splunk_event({"question": "test"}, "infer_with_llm") |
| 108 | + |
| 109 | + mock_session.post.assert_called_once() |
| 110 | + call_args = mock_session.post.call_args |
| 111 | + assert call_args[0][0] == mock_splunk_config.url |
| 112 | + assert "Authorization" in call_args[1]["headers"] |
| 113 | + assert call_args[1]["json"]["sourcetype"] == "infer_with_llm" |
| 114 | + assert call_args[1]["json"]["event"] == {"question": "test"} |
| 115 | + |
| 116 | + |
| 117 | +@pytest.mark.asyncio |
| 118 | +@pytest.mark.parametrize( |
| 119 | + ("error_setup",), |
| 120 | + [ |
| 121 | + ( |
| 122 | + lambda s: setattr( |
| 123 | + s.post.return_value.__aenter__.return_value, "status", 503 |
| 124 | + ), |
| 125 | + ), |
| 126 | + ( |
| 127 | + lambda s: setattr( |
| 128 | + s.return_value.__aenter__, "side_effect", aiohttp.ClientError() |
| 129 | + ), |
| 130 | + ), |
| 131 | + ], |
| 132 | + ids=["http_error", "client_error"], |
| 133 | +) |
| 134 | +async def test_logs_warning_on_error( |
| 135 | + mock_splunk_config: MagicMock, error_setup: Any |
| 136 | +) -> None: |
| 137 | + """Test warning is logged on HTTP or client errors.""" |
| 138 | + mock_session = AsyncMock(spec=aiohttp.ClientSession) |
| 139 | + mock_response = AsyncMock() |
| 140 | + mock_response.status = 503 |
| 141 | + mock_response.text.return_value = "error" |
| 142 | + mock_session.post.return_value.__aenter__.return_value = mock_response |
| 143 | + |
| 144 | + with ( |
| 145 | + patch("observability.splunk.configuration") as mock_config, |
| 146 | + patch("observability.splunk.aiohttp.ClientSession") as mock_client, |
| 147 | + patch("observability.splunk.logger") as mock_logger, |
| 148 | + ): |
| 149 | + mock_config.splunk = mock_splunk_config |
| 150 | + error_setup(mock_client) |
| 151 | + mock_client.return_value.__aenter__.return_value = mock_session |
| 152 | + |
| 153 | + await send_splunk_event({"test": "event"}, "test_sourcetype") |
| 154 | + |
| 155 | + mock_logger.warning.assert_called() |
0 commit comments