|
| 1 | +# Extra fixtures used for wasm testing. |
| 2 | +from functools import partial |
| 3 | +from pathlib import Path |
| 4 | +from playwright.sync_api import Page |
| 5 | +import pytest |
| 6 | +import subprocess |
| 7 | +import time |
| 8 | + |
| 9 | +@pytest.fixture(scope="session", autouse=True) |
| 10 | +def run_web_server(): |
| 11 | + with open('serve.log', 'w') as f: |
| 12 | + cwd = Path(__file__).parent.parent / 'wasm/test' |
| 13 | + proc = subprocess.Popen( |
| 14 | + ['npm', 'run', 'serve'], stdout=f, stderr=f, cwd=cwd |
| 15 | + ) |
| 16 | + # Wait a bit until server ready to receive connections. |
| 17 | + time.sleep(0.3) |
| 18 | + yield |
| 19 | + proc.terminate() |
| 20 | + |
| 21 | +@pytest.fixture(scope="function", autouse=True) |
| 22 | +def load_page(page: Page): |
| 23 | + # Load web page at start of every test. |
| 24 | + page.goto("http://localhost:8000") |
| 25 | + page.locator("#loaded").wait_for() |
| 26 | + |
| 27 | +def subprocess_run( |
| 28 | + page: Page, |
| 29 | + cmd: list[str], |
| 30 | + *, |
| 31 | + capture_output: bool = False, |
| 32 | + cwd: str | None = None, |
| 33 | + text: bool | None = None |
| 34 | +) -> subprocess.CompletedProcess: |
| 35 | + if cwd is not None: |
| 36 | + raise RuntimeError('cwd is not yet supported') |
| 37 | + |
| 38 | + proc = page.evaluate("async cmd => window.cockle.shellRun(cmd)", cmd) |
| 39 | + # TypeScript object is auto converted to Python dict. |
| 40 | + # Want to return subprocess.CompletedProcess, consider namedtuple if this fails in future. |
| 41 | + stdout = proc['stdout'] if capture_output else '' |
| 42 | + stderr = proc['stderr'] if capture_output else '' |
| 43 | + if not text: |
| 44 | + stdout = stdout.encode("utf-8") |
| 45 | + stderr = stderr.encode("utf-8") |
| 46 | + return subprocess.CompletedProcess( |
| 47 | + args=cmd, |
| 48 | + returncode=proc['returncode'], |
| 49 | + stdout=stdout, |
| 50 | + stderr=stderr |
| 51 | + ) |
| 52 | + |
| 53 | +@pytest.fixture(scope="function", autouse=True) |
| 54 | +def mock_subprocess_run(page: Page, monkeypatch): |
| 55 | + monkeypatch.setattr(subprocess, "run", partial(subprocess_run, page)) |
0 commit comments