about summary refs log tree commit diff
path: root/test/python/server_test_case.py
diff options
context:
space:
mode:
authorAlexander_Kabui <alexanderkabua@gmail.com>2026-10-04 09:40:07 +0300
committerAlexander_Kabui <alexanderkabua@gmail.com>2026-10-05 21:52:23 +0300
commitf063893efa75dd58a9ef125bbbc4e64f84721dd4 (patch)
treeab5047e288ede2a3855ebf6d6bb3d67422584541 /test/python/server_test_case.py
parent0892471500f877513f4f983e74858e8421dd87ef (diff)
downloadgenenetwork4-f063893efa75dd58a9ef125bbbc4e64f84721dd4.tar.gz
* test/python/server_test_case.py (ServerTestCase): probe SQL_URI
credentials, not just the port

Mirrors the Rust-side fix in 4a2cf5b on the Python suites: the old
skip check connected to 127.0.0.1:3306, so tests ran (and failed)
whenever a server was listening but rejected the credentials.
database_reachable() now performs the real
mysql_native_password handshake and skips only when the database is
genuinely unusable; the five DB-mapped test modules use it instead
of their local port probes.

* test/python/test_{groups,group_by_name,group_strains,species,species_by_name}.py
(database_reachable): use the shared probe; drop local copies.
Diffstat (limited to 'test/python/server_test_case.py')
-rw-r--r--test/python/server_test_case.py96
1 files changed, 96 insertions, 0 deletions
diff --git a/test/python/server_test_case.py b/test/python/server_test_case.py
index ec243a2..d4bb330 100644
--- a/test/python/server_test_case.py
+++ b/test/python/server_test_case.py
@@ -3,11 +3,14 @@ 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 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"
@@ -25,6 +28,99 @@ def wait_for_port(host, port, timeout=10):
     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 = 1  # 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("<H", handshake, pos)[0]
+    pos += 2
+    if len(handshake) <= pos:
+        return scramble  # pre-4.1 server; part 1 is all we get
+    pos += 1 + 2  # charset, status
+    capabilities |= struct.unpack_from("<H", handshake, pos)[0] << 16
+    pos += 2
+    if capabilities & 0x00080000:  # CLIENT_PLUGIN_AUTH
+        auth_len = handshake[pos]
+        pos += 1 + 10  # auth data length, reserved
+        part2_len = max(13, auth_len - 8)
+    else:
+        part2_len = 13
+    scramble += handshake[pos : pos + part2_len]
+    return scramble.rstrip(b"\0")[:20]
+
+
+def _login_packet(parsed, scramble):
+    """A minimal mysql_native_password login attempt."""
+    password = (parsed.password or "").encode()
+    stage1 = hashlib.sha1(password).digest()
+    token = bytes(
+        a ^ b
+        for a, b in zip(
+            stage1,
+            hashlib.sha1(scramble + hashlib.sha1(stage1).digest()).digest(),
+        )
+    )
+    user = (parsed.username or "").encode()
+    db = (parsed.path or "/").lstrip("/").encode()
+    payload = (
+        struct.pack("<IIB", 0x00008200, 0, 8)  # PROTOCOL_41 | SECURE_CONN
+        + b"\0" * 23
+        + user
+        + b"\0"
+        + bytes([len(token)])
+        + token
+        + db
+        + b"\0"
+    )
+    return struct.pack("<I", len(payload))[:3] + b"\x01" + payload
+
+
 class ServerTestCase(unittest.TestCase):
     """Spawns the genenetwork4 binary for the duration of the test class.