Spaces:
Running
Running
File size: 6,013 Bytes
9f3fb22 d8cd787 9f3fb22 d8cd787 | 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 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 | """Regression checks for binary verification and invalid docking grids."""
import hashlib
from pathlib import Path
import pytest
from app.tools import docking
@pytest.fixture
def verified_binary(tmp_path, monkeypatch):
binary = tmp_path / "vina"
binary.write_bytes(b"verified release bytes")
monkeypatch.setattr(docking, "_VINA_SHA256", hashlib.sha256(binary.read_bytes()).hexdigest())
monkeypatch.setattr(docking, "_VINA_BINARY", str(binary))
return binary
def test_cached_binary_is_checked_on_every_use(verified_binary):
assert docking._ensure_vina() == str(verified_binary)
verified_binary.write_bytes(b"tampered")
with pytest.raises(RuntimeError, match="checksum mismatch"):
docking._ensure_vina()
@pytest.mark.parametrize("digest", ["", "bad", "a" * 63])
def test_missing_or_invalid_checksum_fails_closed(verified_binary, monkeypatch, digest):
monkeypatch.setattr(docking, "_VINA_SHA256", digest)
with pytest.raises(RuntimeError, match="checksum is missing or invalid"):
docking._ensure_vina()
def test_existing_download_cache_cannot_bypass_verification(tmp_path, monkeypatch):
cache = tmp_path / "vina_bin"
cache.mkdir()
(cache / docking._EXE_NAME).write_bytes(b"unverified old cached binary")
monkeypatch.setattr(docking, "_VINA_BINARY", None)
monkeypatch.setattr(docking.tempfile, "gettempdir", lambda: str(tmp_path))
monkeypatch.setattr(docking.os.path, "isfile", lambda p: False)
with pytest.raises(RuntimeError, match="checksum mismatch"):
docking._ensure_vina()
def test_bad_download_never_published(tmp_path, monkeypatch):
monkeypatch.setattr(docking, "_VINA_BINARY", None)
monkeypatch.setattr(docking.tempfile, "gettempdir", lambda: str(tmp_path))
monkeypatch.setattr(docking.os.path, "isfile", lambda p: False)
monkeypatch.setattr(docking.urllib.request, "urlretrieve", lambda url, p: Path(p).write_bytes(b"bad download"))
with pytest.raises(RuntimeError, match="checksum mismatch"):
docking._ensure_vina()
assert not list((tmp_path / "vina_bin").iterdir())
def test_rcsb_fetch_retries_transient_proxy_and_rejects_nonstructure(monkeypatch):
import httpx
attempts = []
delays = []
request = httpx.Request("GET", "https://files.rcsb.org/download/1STP.pdb")
def fetch(url, **kwargs):
attempts.append((url, kwargs))
if len(attempts) == 1:
return httpx.Response(403, text="proxy transient", request=request)
if len(attempts) == 2:
return httpx.Response(200, text="temporarily unavailable", request=request)
return httpx.Response(200, text="ATOM 1 CA ALA A 1 1.000 2.000 3.000\n", request=request)
monkeypatch.setattr(docking.httpx, "get", fetch)
monkeypatch.setattr(docking.time, "sleep", delays.append)
data = docking.fetch_pdb_from_rcsb("1stp")
assert data.startswith("ATOM")
assert len(attempts) == 3
assert delays == [1, 2]
assert all(url == "https://files.rcsb.org/download/1STP.pdb" for url, _ in attempts)
assert all(kwargs["follow_redirects"] is True for _, kwargs in attempts)
def test_rcsb_fetch_bad_identifier_fails_before_network(monkeypatch):
monkeypatch.setattr(docking.httpx, "get", lambda *a, **k: pytest.fail("network not expected"))
with pytest.raises(ValueError, match="Invalid PDB ID"):
docking.fetch_pdb_from_rcsb("../admin")
@pytest.mark.parametrize("pdb", ["", "HEADER no atoms\nEND", "ATOM invalid columns",
"HETATM 1 C LIG A 1 1.000 2.000 3.000"])
def test_grid_without_receptor_coordinates_fails(pdb):
with pytest.raises(ValueError, match="no valid finite ATOM coordinates"):
docking.compute_grid_center(pdb)
with pytest.raises(ValueError, match="no valid finite ATOM coordinates"):
docking.compute_pocket_grid(pdb)
def test_nonfinite_receptor_coordinates_rejected():
pdb = "ATOM 1 CA ALA A 1 " + f"{float('nan'):8.3f}{2:8.3f}{3:8.3f}"
with pytest.raises(ValueError, match="no valid finite ATOM coordinates"):
docking.compute_grid_center(pdb)
@pytest.mark.parametrize("center,size", [(None, [20]*3), ([1, 2], [20]*3),
([float('nan'), 0, 0], [20]*3), ([0]*3, [20, 0, 20]),
([0]*3, [20, float('inf'), 20]), ([0]*3, None)])
def test_invalid_grid_rejected_before_binary_lookup(center, size, monkeypatch):
def forbidden():
pytest.fail("Binary lookup must not precede grid validation")
monkeypatch.setattr(docking, "_ensure_vina", forbidden)
with pytest.raises(ValueError):
docking.run_vina("", "", center, size)
def test_explicit_origin_is_a_valid_center():
assert docking._validate_grid_vector([0, 0, 0], "grid_center") == [0.0]*3
@pytest.mark.parametrize("budget", [0, -1, float("nan"), float("inf"), 1801])
def test_native_execution_budget_rejected_before_binary_execution(monkeypatch, budget):
monkeypatch.setattr(docking, "_ensure_vina", lambda: pytest.fail("Invalid budget reached native binary"))
with pytest.raises(ValueError, match="timeout_seconds"):
docking.run_vina("", "", [1, 2, 3], [20, 20, 20], timeout_seconds=budget)
def test_native_execution_honors_explicit_budget(verified_binary, monkeypatch):
from types import SimpleNamespace
artifacts = Path(__file__).resolve().parents[3] / "benchmark/results/docking/redock/artifacts/20261012T080418163266Z/1STP"
def execute(command, **kwargs):
assert kwargs["timeout"] == 900
Path(command[command.index("--out") + 1]).write_text((artifacts / "vina_output.pdbqt").read_text())
return SimpleNamespace(returncode=0, stdout=(artifacts / "vina.log").read_text(), stderr="")
monkeypatch.setattr(docking.subprocess, "run", execute)
monkeypatch.setattr(docking, "pdbqt_to_sdf", lambda *args: "")
result = docking.run_vina("receptor", "ligand", [1, 2, 3], [20, 20, 20], timeout_seconds=900)
assert result["num_poses"] > 0
|