alef-e2e 0.15.10

Fixture-driven e2e test generator for alef
Documentation
{{ header }}"""Pytest configuration for e2e tests."""
{% if has_http_fixtures %}from __future__ import annotations

import os
import subprocess
import threading
from pathlib import Path
from typing import Generator

import pytest

# Ensure the package is importable.
# The {{ module }} package is expected to be installed in the current environment.

_HERE = Path(__file__).parent
_E2E_DIR = _HERE.parent
_MOCK_SERVER_BIN = _E2E_DIR / "rust" / "target" / "release" / "mock-server"
_FIXTURES_DIR = _E2E_DIR.parent / "fixtures"


@pytest.fixture(scope="session", autouse=True)
def mock_server() -> Generator[str, None, None]:
    """Spawn the mock HTTP server binary and set MOCK_SERVER_URL."""
    proc = subprocess.Popen(  # noqa: S603
        [str(_MOCK_SERVER_BIN), str(_FIXTURES_DIR)],
        stdout=subprocess.PIPE,
        stderr=None,
        stdin=subprocess.PIPE,
    )
    url = ""
    assert proc.stdout is not None
    for raw_line in proc.stdout:
        line = raw_line.decode().strip()
        if line.startswith("MOCK_SERVER_URL="):
            url = line.split("=", 1)[1]
            break
    os.environ["MOCK_SERVER_URL"] = url
    # Drain stdout in background so the server never blocks.
    threading.Thread(target=proc.stdout.read, daemon=True).start()
    yield url
    if proc.stdin:
        proc.stdin.close()
    proc.terminate()
    proc.wait()


def _make_request(method: str, path: str, **kwargs: object) -> object:
    """Make an HTTP request to the mock server."""
    import urllib.request  # noqa: PLC0415

    base_url = os.environ.get("MOCK_SERVER_URL", "http://localhost:8080")
    url = f"{base_url}{path}"
    data = kwargs.pop("json", None)
    if data is not None:
        import json  # noqa: PLC0415

        body = json.dumps(data).encode()
        headers = dict(kwargs.pop("headers", {}))
        headers.setdefault("Content-Type", "application/json")
        req = urllib.request.Request(url, data=body, headers=headers, method=method.upper())
    else:
        headers = dict(kwargs.pop("headers", {}))
        req = urllib.request.Request(url, headers=headers, method=method.upper())
    try:
        with urllib.request.urlopen(req) as resp:  # noqa: S310
            return resp
    except urllib.error.HTTPError as exc:
        return exc


@pytest.fixture(scope="session")
def app(mock_server: str) -> object:  # noqa: ARG001
    """Return a simple HTTP helper bound to the mock server URL."""

    class _App:
        def request(self, path: str, **kwargs: object) -> object:
            method = str(kwargs.pop("method", "GET"))
            return _make_request(method, path, **kwargs)

    return _App()
{% elif has_file_fixtures %}import os
from pathlib import Path

# Ensure the package is importable.
# The {{ module }} package is expected to be installed in the current environment.

# Change to the test_documents directory so that fixture file paths like
# "pdf/fake_memo.pdf" resolve correctly when running pytest from e2e/python/.
_TEST_DOCUMENTS = Path(__file__).parent.parent.parent / "test_documents"
if _TEST_DOCUMENTS.is_dir():
    os.chdir(_TEST_DOCUMENTS)

# On macOS, Pdfium is a separate dylib not on the default library path in dev builds.
# Search common locations (Cargo build output, staged target/release) and extend
# DYLD_LIBRARY_PATH / LD_LIBRARY_PATH so the extension can load the library.
_REPO_ROOT = Path(__file__).parent.parent.parent


def _find_pdfium_dir() -> str | None:
    """Find the directory containing libpdfium, searching Cargo build outputs."""
    for _candidate in sorted(_REPO_ROOT.glob("target/*/release/build/*/out/libpdfium*")):
        return str(_candidate.parent)
    for _candidate in sorted(_REPO_ROOT.glob("target/release/build/*/out/libpdfium*")):
        return str(_candidate.parent)
    return None


_pdfium_dir = _find_pdfium_dir()
if _pdfium_dir is not None:
    for _var in ("DYLD_LIBRARY_PATH", "LD_LIBRARY_PATH"):
        _existing = os.environ.get(_var, "")
        if _pdfium_dir not in _existing:
            os.environ[_var] = f"{_pdfium_dir}:{_existing}" if _existing else _pdfium_dir
{% else %}# Ensure the package is importable.
# The {{ module }} package is expected to be installed in the current environment.
{% endif %}