about summary refs log tree commit diff
path: root/test/python/server_test_case.py
blob: 0025c4b410db19ec6f4f0a5bc05531a8c019c1ce (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
"""Shared helper for tests that exercise a running genenetwork4 server over
real HTTP (Python can only reach the server this way, unlike the Rust
integration tests under tests/, which call the router in-process).
"""

import os
import socket
import subprocess
import time
import unittest

BINARY = os.environ.get("GENENETWORK4_BINARY", "genenetwork4")
HOST = "127.0.0.1"
PORT = os.environ.get("GENENETWORK4_PORT", "3000")


def wait_for_port(host, port, timeout=10):
    deadline = time.time() + timeout
    while time.time() < deadline:
        try:
            with socket.create_connection((host, int(port)), timeout=0.5):
                return True
        except OSError:
            time.sleep(0.1)
    return False


class ServerTestCase(unittest.TestCase):
    """Spawns the genenetwork4 binary for the duration of the test class."""

    @classmethod
    def setUpClass(cls):
        env = dict(os.environ, GENENETWORK4_PORT=PORT)
        cls.proc = subprocess.Popen([BINARY], env=env)
        if not wait_for_port(HOST, PORT):
            cls.proc.terminate()
            raise RuntimeError(f"server did not start listening on {HOST}:{PORT}")

    @classmethod
    def tearDownClass(cls):
        cls.proc.terminate()
        cls.proc.wait(timeout=5)