conftest.py raw

   1  """Shared fixtures for morly's integration suite.
   2  
   3  The unit layer runs through the compiler's own harness (`make test-unit`); this
   4  is the layer that drives a real relay process: the ORLY_* env contract, the
   5  WebSocket round-trip, and the policy limits. It replaces the browser with a
   6  socket, so it needs no selenium and no app build.
   7  
   8  Test regime uses 127.0.0.1 on a non-standard port so a dev relay on the
   9  production port (3334) is not disturbed:
  10    127.0.0.1:23335  — test relay (WebSocket + static files, when one is given)
  11  """
  12  
  13  import os
  14  import re
  15  import shutil
  16  import signal
  17  import subprocess
  18  import time
  19  
  20  import pytest
  21  
  22  PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  23  # MORLY_RELAY_BIN forces a specific binary, which is how `make test-integration`
  24  # points the suite at the one it just built. The fallbacks cover a hand-run
  25  # `make build` and the instrumented build (`make build-test-relay`).
  26  _bins = ["morly", "morly-test"]
  27  RELAY_BIN = os.environ.get("MORLY_RELAY_BIN") or next(
  28      (os.path.join(PROJECT_ROOT, b) for b in _bins
  29       if os.path.exists(os.path.join(PROJECT_ROOT, b))), "")
  30  # Optional: the relay serves this tree. Unset means the static-file checks are
  31  # not in play; nothing in the relay layer requires a frontend build.
  32  STATIC_DIR = os.environ.get("ORLY_STATIC_DIR") or ""
  33  DATA_DIR = "/tmp/morly-test-data"
  34  
  35  RELAY_HOST = "127.0.0.1"
  36  RELAY_PORT = 23335
  37  RELAY_URL = f"http://{RELAY_HOST}:{RELAY_PORT}"
  38  WS_URL = f"ws://{RELAY_HOST}:{RELAY_PORT}"
  39  
  40  
  41  def relay_tree_pids():
  42      """PIDs running this checkout's relay binary, from any earlier run.
  43  
  44      The relay is started as an absolute path, and every domain spawn()ed from
  45      it forks a child that keeps the same argv, so anchoring the pattern on the
  46      path finds the whole tree and nothing else.
  47      """
  48      if not RELAY_BIN:
  49          return []
  50      try:
  51          out = subprocess.run(
  52              ["pgrep", "-f", "^" + re.escape(RELAY_BIN)],
  53              capture_output=True, text=True, timeout=5,
  54          ).stdout
  55      except Exception:
  56          return []
  57      return sorted({int(p) for p in out.split() if p.isdigit()})
  58  
  59  
  60  def kill_stale_relays():
  61      """Kill any relay left behind by a previous (crashed or killed) run.
  62  
  63      A leftover relay keeps listening on the test port, so a new fixture would
  64      talk to it instead of the one it started: its store is the old one and its
  65      process group outlives ours. A quit run cleans up after itself; this is the
  66      guard for the runs that do not get to.
  67      """
  68      pids = relay_tree_pids()
  69      if not pids:
  70          return
  71      print(f"\nrelay fixture: killing {len(pids)} leftover relay process(es) {pids}")
  72      for pid in pids:
  73          try:
  74              os.killpg(os.getpgid(pid), signal.SIGKILL)
  75          except Exception:
  76              try:
  77                  os.kill(pid, signal.SIGKILL)
  78              except Exception:
  79                  pass
  80      for _ in range(50):
  81          if not relay_tree_pids():
  82              return
  83          time.sleep(0.1)
  84  
  85  
  86  def port_pids(port):
  87      """PIDs listening on a TCP port, via ss. Empty if ss cannot say."""
  88      try:
  89          out = subprocess.run(
  90              ["ss", "-ltnpH", f"sport = :{port}"],
  91              capture_output=True, text=True, timeout=5,
  92          ).stdout
  93      except Exception:
  94          return []
  95      return sorted({int(m.group(1)) for m in re.finditer(r"pid=(\d+)", out)})
  96  
  97  
  98  def stop_relay(proc):
  99      """Terminate the relay's whole process group, then reap it.
 100  
 101      The relay forks a child per spawn()ed domain; signalling only the parent
 102      leaves those children holding resources (and their copy of the store), so
 103      the group gets the signal.
 104      """
 105      if proc.poll() is not None:
 106          return
 107      try:
 108          pgid = os.getpgid(proc.pid)
 109      except Exception:
 110          pgid = None
 111      for sig in (signal.SIGTERM, signal.SIGKILL):
 112          try:
 113              if pgid is not None:
 114                  os.killpg(pgid, sig)
 115              else:
 116                  proc.send_signal(sig)
 117          except Exception:
 118              pass
 119          try:
 120              proc.wait(timeout=5 if sig == signal.SIGTERM else 2)
 121              break
 122          except subprocess.TimeoutExpired:
 123              continue
 124  
 125  
 126  @pytest.fixture(scope="session")
 127  def relay():
 128      """Start the relay for the test session."""
 129      if not RELAY_BIN or not os.path.exists(RELAY_BIN):
 130          pytest.skip("relay binary not found — run: make build")
 131  
 132      os.makedirs(DATA_DIR, exist_ok=True)
 133      # Start from an empty store. The data dir survives across sessions, and the
 134      # relay replays the whole WAL at open: after a few runs the accumulated
 135      # events made startup take longer than the readiness wait below and every
 136      # test in the session errored on "relay failed to start". Tests also
 137      # expect a known store, not whatever earlier runs left behind.
 138      shutil.rmtree(os.path.join(DATA_DIR, "db"), ignore_errors=True)
 139      env = os.environ.copy()
 140      env["ORLY_DATA_DIR"] = DATA_DIR
 141      env["ORLY_LISTEN"] = RELAY_HOST
 142      env["ORLY_PORT"] = str(RELAY_PORT)
 143      env["ORLY_HTTP_GUARD_ENABLED"] = "false"
 144      if STATIC_DIR:
 145          env["ORLY_STATIC_DIR"] = STATIC_DIR
 146  
 147      # Nothing may be listening before we bind: a stale relay would answer the
 148      # readiness probe below and every request in this session.
 149      kill_stale_relays()
 150      holders = port_pids(RELAY_PORT)
 151      if holders:
 152          pytest.fail(
 153              f"port {RELAY_PORT} is already held by pid(s) {holders}; "
 154              f"stop them before running the suite"
 155          )
 156  
 157      # Log to a file, not a pipe: the relay logs every store and request event,
 158      # and a pipe nobody drains fills up and stalls the relay mid-suite.
 159      relay_log_path = "/tmp/morly-test-relay.log"
 160      relay_log = open(relay_log_path, "wb")
 161      # own session/process group: the relay forks a child per spawned domain,
 162      # and only a group signal reaches all of them at teardown.
 163      proc = subprocess.Popen(
 164          [RELAY_BIN],
 165          env=env,
 166          stdout=relay_log,
 167          stderr=subprocess.STDOUT,
 168          start_new_session=True,
 169      )
 170  
 171      import urllib.error
 172      import urllib.request
 173      # Probe /health, not /. This suite does not require a frontend build, and
 174      # without ORLY_STATIC_DIR a request for / is a 404 - which urlopen raises
 175      # on, so a probe against / would never report a relay that is serving
 176      # perfectly well. Any HTTP status here means the listener is up.
 177      ready = False
 178      for _ in range(300):
 179          if proc.poll() is not None:
 180              break
 181          try:
 182              urllib.request.urlopen(RELAY_URL + "/health", timeout=1)
 183              ready = True
 184              break
 185          except urllib.error.HTTPError:
 186              ready = True
 187              break
 188          except Exception:
 189              time.sleep(0.2)
 190      if not ready:
 191          # Read the exit state before stop_relay reaps it: after the SIGTERM the
 192          # return code is ours, and reporting that as "exited during startup"
 193          # sends the reader looking for a crash that never happened.
 194          exited = proc.poll()
 195          stop_relay(proc)
 196          relay_log.flush()
 197          relay_log.close()
 198          with open(relay_log_path, errors="replace") as f:
 199              print(f"\n=== RELAY LOG ===\n{f.read()[-4000:]}\n=== END ===\n")
 200          pytest.fail(
 201              "Relay failed to start within 60 seconds"
 202              if exited is None
 203              else f"Relay exited with {exited} during startup"
 204          )
 205  
 206      # The readiness probe only proves *something* served that port.
 207      holders = port_pids(RELAY_PORT)
 208      if holders and proc.pid not in holders:
 209          stop_relay(proc)
 210          pytest.fail(
 211              f"port {RELAY_PORT} answered from pid(s) {holders}, "
 212              f"not the relay this fixture started (pid {proc.pid})"
 213          )
 214  
 215      info = {
 216          "proc": proc,
 217          "url": RELAY_URL,
 218          "ws": WS_URL,
 219          "host": RELAY_HOST,
 220          "port": RELAY_PORT,
 221      }
 222      yield info
 223  
 224      if proc.poll() is not None:
 225          relay_log.flush()
 226          with open(relay_log_path, errors="replace") as f:
 227              out = f.read()
 228          if out:
 229              print(f"\n=== RELAY LOG ===\n{out[-4000:]}\n=== END ===\n")
 230  
 231      stop_relay(proc)
 232      relay_log.close()
 233      kill_stale_relays()
 234      leftovers = port_pids(RELAY_PORT)
 235      if leftovers:
 236          print(f"\nrelay fixture: port {RELAY_PORT} still held by {leftovers} after teardown")
 237