Skip to content

Commit d4e7e16

Browse files
committed
Added unit test for the HTTPS log handler
1 parent 8c2351c commit d4e7e16

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

tests/util/test_logging.py

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
import time
2+
from unittest import mock
3+
from unittest.mock import MagicMock
4+
5+
import pytest
6+
from fastapi import Response
7+
from pytest_mock import MockerFixture
8+
9+
from murfey.util.logging import HTTPSHandler
10+
11+
https_handler_test_matrix = (
12+
# Num messages | Status code
13+
(10, 200),
14+
(10, 404),
15+
)
16+
17+
18+
@pytest.mark.parametrize("test_params", https_handler_test_matrix)
19+
def test_https_handler(
20+
mocker: MockerFixture,
21+
mock_client_configuration,
22+
test_params: tuple[int, int],
23+
):
24+
# Unpack test params
25+
num_messages, status_code = test_params
26+
27+
# Mock the imported 'requests' module and the HTTPX response
28+
mock_response = MagicMock(spec=Response)
29+
mock_response.status_code = status_code
30+
mock_requests = mocker.patch("murfey.util.logging.requests")
31+
mock_requests.post.return_value = mock_response
32+
33+
# Import logger and set up a logger object
34+
from logging import getLogger
35+
36+
# Initialise the logger with URL from mock client config
37+
client_config = dict(mock_client_configuration["Murfey"])
38+
server_url = client_config["server"]
39+
https_handler = HTTPSHandler(
40+
endpoint_url=server_url,
41+
min_batch=5,
42+
max_batch=10,
43+
min_interval=0.5,
44+
max_interval=1.0,
45+
max_retry=1,
46+
)
47+
48+
logger = getLogger("tests.util.test_logging")
49+
logger.setLevel(10)
50+
logger.addHandler(https_handler)
51+
for i in range(num_messages):
52+
# Test all the logging levels
53+
if i % 4 == 0:
54+
logger.debug("This is a debug log")
55+
if i % 4 == 1:
56+
logger.info("This is an info log")
57+
if i % 4 == 2:
58+
logger.warning("This is a warning log")
59+
if i % 4 == 3:
60+
logger.error("This is an error log")
61+
62+
# Let it run in the background before checking for the expected calls
63+
time.sleep(1)
64+
mock_requests.post.assert_called_with(
65+
server_url,
66+
json=mock.ANY,
67+
timeout=5,
68+
)
69+
70+
assert https_handler.close() is None

0 commit comments

Comments
 (0)