Skip to content

Commit 5746040

Browse files
tests/om1_utils/healthcheck/test_healthcheck.py (#99)
Co-authored-by: openminddev <147775420+openminddev@users.noreply.github.com>
1 parent 3fd3513 commit 5746040

1 file changed

Lines changed: 79 additions & 0 deletions

File tree

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
import socket
2+
import time
3+
from contextlib import closing
4+
5+
import pytest
6+
import requests
7+
8+
from om1_utils.healthcheck import HealthCheckServer
9+
10+
11+
def find_free_port() -> int:
12+
"""Find a free port on localhost."""
13+
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
14+
sock.bind(("", 0))
15+
sock.listen(1)
16+
return sock.getsockname()[1]
17+
18+
19+
@pytest.fixture
20+
def server():
21+
"""Create and manage a HealthCheckServer for testing."""
22+
port = find_free_port()
23+
srv = HealthCheckServer(port=port)
24+
srv.start()
25+
time.sleep(0.3)
26+
yield srv, port
27+
srv.stop()
28+
time.sleep(0.3)
29+
30+
31+
class TestHealthCheckServer:
32+
"""Tests for the HealthCheckServer class."""
33+
34+
def test_default_port(self):
35+
"""Test that default port is 9999."""
36+
srv = HealthCheckServer()
37+
assert srv.port == 9999
38+
39+
def test_custom_port(self):
40+
"""Test initialization with a custom port."""
41+
srv = HealthCheckServer(port=8080)
42+
assert srv.port == 8080
43+
44+
def test_initial_state(self):
45+
"""Test that server starts in non-running state."""
46+
srv = HealthCheckServer()
47+
assert srv.is_running() is False
48+
assert srv.server is None
49+
assert srv.server_thread is None
50+
51+
def test_start_sets_running(self, server):
52+
"""Test that start sets running to True."""
53+
srv, _ = server
54+
assert srv.is_running() is True
55+
56+
def test_stop_sets_not_running(self, server):
57+
"""Test that stop sets running to False."""
58+
srv, _ = server
59+
srv.stop()
60+
assert srv.is_running() is False
61+
62+
def test_double_start_does_not_crash(self, server):
63+
"""Test that calling start twice does not raise an error."""
64+
srv, _ = server
65+
srv.start()
66+
assert srv.is_running() is True
67+
68+
def test_get_returns_200(self, server):
69+
"""Test that GET request returns 200 OK."""
70+
_, port = server
71+
response = requests.get(f"http://127.0.0.1:{port}", timeout=5)
72+
assert response.status_code == 200
73+
assert response.text == "OK"
74+
75+
def test_stop_without_start(self):
76+
"""Test that stop on a never-started server does not crash."""
77+
srv = HealthCheckServer()
78+
srv.stop()
79+
assert srv.is_running() is False

0 commit comments

Comments
 (0)