Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 27 additions & 6 deletions tests/lk_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
import socket
import subprocess
import time
import urllib.error
import urllib.request

import pytest

Expand All @@ -27,13 +29,32 @@ def _port_in_use(port: int) -> bool:
return s.connect_ex(("127.0.0.1", port)) == 0


def _wait_for_port(port: int, timeout: float = 15.0) -> None:
def _wait_for_ready(port: int, timeout: float = 15.0) -> None:
"""Wait until the LiveKit server is ready to accept connections.

Polls the HTTP endpoint on the same port as a readiness proxy. Any HTTP
response (including 4xx/5xx) confirms that the server's handler stack is
fully initialised — a stronger signal than TCP reachability alone, which
can return true before the WebSocket acceptor is ready, causing transient
ConnectError failures in tests that open multiple rapid connections.
"""
deadline = time.monotonic() + timeout
last_exc: Exception | None = None
req = urllib.request.Request(f"http://127.0.0.1:{port}", method="HEAD")
while time.monotonic() < deadline:
if _port_in_use(port):
return
time.sleep(0.3)
raise TimeoutError(f"LiveKit server did not start within {timeout}s (port {port})")
try:
with urllib.request.urlopen(req, timeout=0.5):
return # any HTTP response means the server is up
except urllib.error.HTTPError as exc:
exc.close() # HTTPError is a response object; close to avoid FD leak
return # a 4xx/5xx reply still means the server is ready
Comment thread
Lothnic marked this conversation as resolved.
Comment thread
Lothnic marked this conversation as resolved.
except (urllib.error.URLError, OSError) as exc:
last_exc = exc
time.sleep(0.3)
raise TimeoutError(
f"LiveKit server did not become ready within {timeout}s (port {port})"
+ (f": last error: {last_exc!r}" if last_exc else "")
)


@pytest.fixture(scope="session")
Expand Down Expand Up @@ -65,7 +86,7 @@ def livekit_server():
)

try:
_wait_for_port(_PORT)
_wait_for_ready(_PORT)
yield
finally:
proc.terminate()
Expand Down
Loading