55 lines
2.0 KiB
Python
55 lines
2.0 KiB
Python
"""Every API response identifies the live replica process."""
|
|
|
|
import json
|
|
import socket
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
import unittest
|
|
import urllib.error
|
|
import urllib.request
|
|
|
|
|
|
class InstanceHeaderTests(unittest.TestCase):
|
|
def test_process_alias_on_success_and_error(self):
|
|
with socket.socket() as sock:
|
|
sock.bind(("127.0.0.1", 0))
|
|
port = sock.getsockname()[1]
|
|
server = subprocess.Popen(
|
|
[sys.executable, "-m", "uvicorn", "src.main:app", "--host", "127.0.0.1", "--port", str(port)],
|
|
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
|
)
|
|
try:
|
|
for _ in range(100):
|
|
try:
|
|
with urllib.request.urlopen(f"http://127.0.0.1:{port}/health/live", timeout=1) as response:
|
|
live_id = response.headers.get("X-Instance-Id")
|
|
self.assertEqual(json.load(response), {"status": "ok"})
|
|
break
|
|
except urllib.error.URLError:
|
|
if server.poll() is not None:
|
|
self.fail("API exited before readiness")
|
|
time.sleep(0.05)
|
|
else:
|
|
self.fail("API did not start")
|
|
self.assertTrue(live_id)
|
|
for path in ("/health/live", "/no-such-route"):
|
|
try:
|
|
response = urllib.request.urlopen(f"http://127.0.0.1:{port}{path}", timeout=1)
|
|
except urllib.error.HTTPError as error:
|
|
response = error
|
|
with response:
|
|
self.assertEqual(response.headers.get("X-Instance-Id"), live_id)
|
|
self.assertTrue(response.headers.get("X-Request-Id"))
|
|
finally:
|
|
server.terminate()
|
|
try:
|
|
server.wait(timeout=5)
|
|
except subprocess.TimeoutExpired:
|
|
server.kill()
|
|
server.wait(timeout=5)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|