Files
DbusSmsForward/tests/test_cli_web.py
T

79 lines
2.6 KiB
Python

import json
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
PROJECT_ROOT = Path("/Users/chick/.Hermes/workspace/DbusSmsForward")
CLI_ENV = {**(__import__("os").environ), "PYTHONPATH": str(PROJECT_ROOT / "src")}
class ServeWebCliTests(unittest.TestCase):
def test_serve_web_command_starts_http_server_and_serves_health(self):
with tempfile.TemporaryDirectory() as tmpdir:
root = Path(tmpdir)
config_path = root / "config.json"
config_path.write_text(
json.dumps(
{
"daemon": {"host": "127.0.0.1", "port": 0},
"notifications": {"console": {"enabled": True}},
},
ensure_ascii=False,
),
encoding="utf-8",
)
process = subprocess.Popen(
[
sys.executable,
"-u",
"-m",
"dbussmsforward.cli",
"serve-web",
"--config",
str(config_path),
"--port",
"18091",
],
cwd=str(PROJECT_ROOT),
env=CLI_ENV,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
)
try:
import time
import urllib.request
deadline = time.time() + 10
while time.time() < deadline:
try:
with urllib.request.urlopen("http://127.0.0.1:18091/api/health", timeout=1) as response:
body = json.loads(response.read().decode("utf-8"))
self.assertEqual(response.status, 200)
self.assertEqual(body["status"], "ok")
break
except Exception:
time.sleep(0.2)
else:
stderr = process.stderr.read()
self.fail(f"serve-web did not become ready: {stderr}")
finally:
process.terminate()
try:
process.wait(timeout=5)
except subprocess.TimeoutExpired:
process.kill()
process.wait(timeout=5)
if process.stdout:
process.stdout.close()
if process.stderr:
process.stderr.close()
if __name__ == "__main__":
unittest.main()