|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import datetime |
| 4 | +import logging |
| 5 | +import random |
| 6 | +import socket |
| 7 | +import subprocess |
| 8 | +import sys |
| 9 | +import threading |
| 10 | +from pathlib import PurePath |
| 11 | +from time import sleep |
| 12 | +from types import TracebackType |
| 13 | +from typing import IO, Callable, Generator, List, Optional, TextIO, Type, Union |
| 14 | + |
| 15 | +import pytest |
| 16 | + |
| 17 | +__all__ = ( |
| 18 | + "ShinyAppProc", |
| 19 | + "create_app_fixture", |
| 20 | + "create_doc_example_fixture", |
| 21 | + "create_example_fixture", |
| 22 | + "local_app", |
| 23 | + "run_shiny_app", |
| 24 | +) |
| 25 | + |
| 26 | +here = PurePath(__file__).parent |
| 27 | + |
| 28 | + |
| 29 | +def random_port(): |
| 30 | + while True: |
| 31 | + port = random.randint(1024, 49151) |
| 32 | + with socket.socket() as s: |
| 33 | + try: |
| 34 | + s.bind(("127.0.0.1", port)) |
| 35 | + return port |
| 36 | + except Exception: |
| 37 | + # Let's just assume that port was in use; try again |
| 38 | + continue |
| 39 | + |
| 40 | + |
| 41 | +class OutputStream: |
| 42 | + """Designed to wrap an IO[str] and accumulate the output using a bg thread |
| 43 | +
|
| 44 | + Also allows for blocking waits for particular lines.""" |
| 45 | + |
| 46 | + def __init__(self, io: IO[str], desc: Optional[str] = None): |
| 47 | + self._io = io |
| 48 | + self._closed = False |
| 49 | + self._lines: List[str] = [] |
| 50 | + self._cond = threading.Condition() |
| 51 | + self._thread = threading.Thread( |
| 52 | + group=None, target=self._run, daemon=True, name=desc |
| 53 | + ) |
| 54 | + |
| 55 | + self._thread.start() |
| 56 | + |
| 57 | + def _run(self): |
| 58 | + """Pump lines into self._lines in a tight loop.""" |
| 59 | + |
| 60 | + try: |
| 61 | + while not self._io.closed: |
| 62 | + try: |
| 63 | + line = self._io.readline() |
| 64 | + except ValueError: |
| 65 | + # This is raised when the stream is closed |
| 66 | + break |
| 67 | + if line is None: |
| 68 | + break |
| 69 | + if line != "": |
| 70 | + with self._cond: |
| 71 | + self._lines.append(line) |
| 72 | + self._cond.notify_all() |
| 73 | + finally: |
| 74 | + # If we got here, we're finished reading self._io and need to signal any |
| 75 | + # waiters that we're done and they'll never hear from us again. |
| 76 | + with self._cond: |
| 77 | + self._closed = True |
| 78 | + self._cond.notify_all() |
| 79 | + |
| 80 | + def wait_for(self, predicate: Callable[[str], bool], timeoutSecs: float) -> bool: |
| 81 | + timeoutAt = datetime.datetime.now() + datetime.timedelta(seconds=timeoutSecs) |
| 82 | + pos = 0 |
| 83 | + with self._cond: |
| 84 | + while True: |
| 85 | + while pos < len(self._lines): |
| 86 | + if predicate(self._lines[pos]): |
| 87 | + return True |
| 88 | + pos += 1 |
| 89 | + if self._closed: |
| 90 | + return False |
| 91 | + else: |
| 92 | + remaining = (timeoutAt - datetime.datetime.now()).total_seconds() |
| 93 | + if remaining < 0 or not self._cond.wait(timeout=remaining): |
| 94 | + # Timed out |
| 95 | + raise TimeoutError( |
| 96 | + "Timeout while waiting for Shiny app to become ready" |
| 97 | + ) |
| 98 | + |
| 99 | + def __str__(self): |
| 100 | + with self._cond: |
| 101 | + return "".join(self._lines) |
| 102 | + |
| 103 | + |
| 104 | +def dummyio() -> TextIO: |
| 105 | + io = TextIO() |
| 106 | + io.close() |
| 107 | + return io |
| 108 | + |
| 109 | + |
| 110 | +class ShinyAppProc: |
| 111 | + def __init__(self, proc: subprocess.Popen[str], port: int): |
| 112 | + self.proc = proc |
| 113 | + self.port = port |
| 114 | + self.url = f"http://127.0.0.1:{port}/" |
| 115 | + self.stdout = OutputStream(proc.stdout or dummyio()) |
| 116 | + self.stderr = OutputStream(proc.stderr or dummyio()) |
| 117 | + threading.Thread(group=None, target=self._run, daemon=True).start() |
| 118 | + |
| 119 | + def _run(self) -> None: |
| 120 | + self.proc.wait() |
| 121 | + if self.proc.stdout is not None: |
| 122 | + self.proc.stdout.close() |
| 123 | + if self.proc.stderr is not None: |
| 124 | + self.proc.stderr.close() |
| 125 | + |
| 126 | + def close(self) -> None: |
| 127 | + sleep(0.5) |
| 128 | + self.proc.terminate() |
| 129 | + |
| 130 | + def __enter__(self) -> ShinyAppProc: |
| 131 | + return self |
| 132 | + |
| 133 | + def __exit__( |
| 134 | + self, |
| 135 | + exc_type: Optional[Type[BaseException]], |
| 136 | + exc_value: Optional[BaseException], |
| 137 | + traceback: Optional[TracebackType], |
| 138 | + ): |
| 139 | + self.close() |
| 140 | + |
| 141 | + def wait_until_ready(self, timeoutSecs: float) -> None: |
| 142 | + if self.stderr.wait_for( |
| 143 | + lambda line: "Uvicorn running on" in line, timeoutSecs=timeoutSecs |
| 144 | + ): |
| 145 | + return |
| 146 | + else: |
| 147 | + raise RuntimeError("Shiny app exited without ever becoming ready") |
| 148 | + |
| 149 | + |
| 150 | +def run_shiny_app( |
| 151 | + app_file: Union[str, PurePath], |
| 152 | + *, |
| 153 | + port: int = 0, |
| 154 | + cwd: Optional[str] = None, |
| 155 | + wait_for_start: bool = True, |
| 156 | + timeout_secs: float = 10, |
| 157 | + bufsize: int = 64 * 1024, |
| 158 | +) -> ShinyAppProc: |
| 159 | + if port == 0: |
| 160 | + port = random_port() |
| 161 | + |
| 162 | + child = subprocess.Popen( |
| 163 | + [sys.executable, "-m", "shiny", "run", "--port", str(port), str(app_file)], |
| 164 | + bufsize=bufsize, |
| 165 | + executable=sys.executable, |
| 166 | + stdout=subprocess.PIPE, |
| 167 | + stderr=subprocess.PIPE, |
| 168 | + cwd=cwd, |
| 169 | + encoding="utf-8", |
| 170 | + ) |
| 171 | + |
| 172 | + # TODO: Detect early exit |
| 173 | + |
| 174 | + sa = ShinyAppProc(child, port) |
| 175 | + if wait_for_start: |
| 176 | + sa.wait_until_ready(timeout_secs) |
| 177 | + return sa |
| 178 | + |
| 179 | + |
| 180 | +def create_app_fixture(app: Union[PurePath, str], scope: str = "module"): |
| 181 | + def fixture_func(): |
| 182 | + sa = run_shiny_app(app, wait_for_start=False) |
| 183 | + try: |
| 184 | + with sa: |
| 185 | + sa.wait_until_ready(30) |
| 186 | + yield sa |
| 187 | + finally: |
| 188 | + logging.warning("Application output:\n" + str(sa.stderr)) |
| 189 | + |
| 190 | + return pytest.fixture( |
| 191 | + scope=scope, # type: ignore |
| 192 | + )(fixture_func) |
| 193 | + |
| 194 | + |
| 195 | +def create_example_fixture(example_name: str, scope: str = "module"): |
| 196 | + """Used to create app fixtures from apps in py-shiny/examples""" |
| 197 | + return create_app_fixture(here / "../examples" / example_name / "app.py", scope) |
| 198 | + |
| 199 | + |
| 200 | +def create_doc_example_fixture(example_name: str, scope: str = "module"): |
| 201 | + """Used to create app fixtures from apps in py-shiny/shiny/examples""" |
| 202 | + return create_app_fixture( |
| 203 | + here / "../shiny/examples" / example_name / "app.py", scope |
| 204 | + ) |
| 205 | + |
| 206 | + |
| 207 | +@pytest.fixture(scope="module") |
| 208 | +def local_app(request: pytest.FixtureRequest) -> Generator[ShinyAppProc, None, None]: |
| 209 | + sa = run_shiny_app(PurePath(request.path).parent / "app.py", wait_for_start=False) |
| 210 | + try: |
| 211 | + with sa: |
| 212 | + sa.wait_until_ready(30) |
| 213 | + yield sa |
| 214 | + finally: |
| 215 | + logging.warning("Application output:\n" + str(sa.stderr)) |
0 commit comments