"""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 hashlib import json import os import socket import struct import subprocess import time import unittest from urllib.parse import urlparse BINARY = os.environ.get("GENENETWORK4_BINARY", "genenetwork4") HOST = "127.0.0.1" PORT = os.environ.get("GENENETWORK4_PORT", "3000") def envelope_data(body): """The `data` of a success response body, after checking that the body is the standard envelope: `meta` (state, took_ms, request_id), `notes` and `next` next to `data`.""" envelope = json.loads(body) assert isinstance(envelope["meta"]["state"], str), envelope assert isinstance(envelope["meta"]["took_ms"], int), envelope assert isinstance(envelope["notes"], list), envelope assert isinstance(envelope["next"], list), envelope return envelope["data"] 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 def database_reachable(): """True only when the configured MariaDB accepts the SQL_URI credentials. A server may be listening on the port yet still reject the login (the common local case), which a bare port check cannot see — so this performs the real mysql_native_password handshake. Any protocol surprise is treated as "not reachable" (skip), which is the safe direction: these tests must not fail where there is simply no usable database (e.g. the Guix build sandbox).""" uri = os.environ.get( "SQL_URI", "mysql://webqtlout:webqtlout@127.0.0.1/db_webqtl" ) try: parsed = urlparse(uri) sock = socket.create_connection( (parsed.hostname or "127.0.0.1", parsed.port or 3306), timeout=1 ) with sock: scramble = _read_scramble(_read_packet(sock)) if scramble is None: return False sock.sendall(_login_packet(parsed, scramble)) # OK starts with 0x00, ERR with 0xff (access denied etc.). return _read_packet(sock)[4] == 0 except (OSError, struct.error, IndexError): return False def _read_packet(sock): header = _read_exact(sock, 4) length = header[0] | (header[1] << 8) | (header[2] << 16) return header + _read_exact(sock, length) def _read_exact(sock, count): data = b"" while len(data) < count: chunk = sock.recv(count - len(data)) if not chunk: raise ConnectionError("connection closed mid-packet") data += chunk return data def _read_scramble(handshake): """Extract the 20-byte auth plugin data from the server handshake.""" pos = 5 # 4-byte packet header, then protocol version pos = handshake.index(b"\0", pos) + 1 # server version string pos += 4 # connection id scramble = handshake[pos : pos + 8] pos += 8 + 1 # auth data part 1, filler capabilities = struct.unpack_from("