Spaces:
Running
Running
Download tests/conftest.py from mertkayacs/postkitty-api: direct link, hf CLI and curl.
- Browser
- Download file 5.1 kB
-
https://huggingface.co/spaces/mertkayacs/postkitty-api/resolve/main/tests/conftest.py
- Command line
-
hf download hf://spaces/mertkayacs/postkitty-api/tests/conftest.py
-
curl -L -o conftest.py https://huggingface.co/spaces/mertkayacs/postkitty-api/resolve/main/tests/conftest.py
5.1 kB
| """Test setup: an engine checkout on the import path, and no face model. | |
| Set POSTKITTY_SRC to a checkout of https://github.com/mertkayacs/postkitty. Jobs run in a child process, | |
| so the detector is swapped through the engine's own POSTKITTY_DETECTIONS switch (it replays recorded | |
| detections) and the child inherits it. A monkeypatch in this process would not reach the child. | |
| """ | |
| from __future__ import annotations | |
| import inspect | |
| import json | |
| import os | |
| import subprocess | |
| import sys | |
| import time | |
| from pathlib import Path | |
| import pytest | |
| API_ROOT = Path(__file__).resolve().parent.parent | |
| ENGINE_LINK = API_ROOT / ".engine" | |
| if not os.environ.get("POSTKITTY_SRC"): | |
| raise pytest.UsageError("set POSTKITTY_SRC to a checkout of the postkitty engine") | |
| # The engine's folder is itself the package, so it is linked under the name `postkitty`. | |
| ENGINE_LINK.mkdir(exist_ok=True) | |
| (ENGINE_LINK / "postkitty").unlink(missing_ok=True) | |
| (ENGINE_LINK / "postkitty").symlink_to(Path(os.environ["POSTKITTY_SRC"]).resolve(), target_is_directory=True) | |
| sys.path[:0] = [str(ENGINE_LINK), str(API_ROOT)] | |
| os.environ["PYTHONPATH"] = os.pathsep.join([str(ENGINE_LINK), str(API_ROOT)]) | |
| # Keep bytecode out of the engine checkout, which belongs to someone else. | |
| sys.dont_write_bytecode = True | |
| os.environ["PYTHONDONTWRITEBYTECODE"] = "1" | |
| # One face, replayed for every frame. The box lies inside both the test photo and the test clip. | |
| FACE = {"x": 260, "y": 90, "w": 110, "h": 140, "score": 0.99} | |
| def recorded_detections(tmp_path_factory): | |
| from postkitty.engine.detect import faces | |
| if "POSTKITTY_DETECTIONS" not in inspect.getsource(faces.get_detector): | |
| pytest.exit("the engine no longer reads POSTKITTY_DETECTIONS, so the real face model would load; not running") | |
| path = tmp_path_factory.mktemp("detections") / "faces.json" | |
| path.write_text(json.dumps({"schema": "postkitty.faces/1", "detector": "test-replay", | |
| "frames": [{"t": 0.0, "faces": [FACE]}]}), encoding="utf-8") | |
| os.environ["POSTKITTY_DETECTIONS"] = str(path) | |
| def media(tmp_path_factory) -> dict[str, Path]: | |
| """Small real files of every accepted kind, plus the ones that must be refused.""" | |
| from PIL import Image, ImageDraw | |
| root = tmp_path_factory.mktemp("media") | |
| photo = Image.new("RGB", (1200, 800), (214, 196, 168)) | |
| draw = ImageDraw.Draw(photo) | |
| draw.rectangle((0, 620, 1200, 800), fill=(52, 72, 104)) | |
| draw.ellipse((260, 90, 370, 230), fill=(128, 96, 72)) | |
| photo.save(root / "team.jpg", quality=90) | |
| photo.save(root / "team.png") | |
| photo.save(root / "team.webp") | |
| photo.save(root / "still.gif") | |
| photo.save(root / "moving.gif", save_all=True, append_images=[photo.rotate(8)], duration=120, loop=0) | |
| whole = (root / "team.jpg").read_bytes() | |
| (root / "cut.jpg").write_bytes(whole[: len(whole) // 2]) | |
| subprocess.run( | |
| ["nice", "-n", "10", "ffmpeg", "-hide_banner", "-loglevel", "error", "-nostdin", "-y", | |
| "-f", "lavfi", "-i", "testsrc2=size=640x360:rate=24:duration=3", | |
| "-f", "lavfi", "-i", "sine=frequency=330:duration=3", | |
| "-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p", "-c:a", "aac", "-shortest", | |
| str(root / "clip.mp4")], | |
| check=True, | |
| ) | |
| return {path.name: path for path in root.iterdir()} | |
| def make_client(tmp_path): | |
| """Build a client for an app with its own data folder and, when given, other limits.""" | |
| from fastapi.testclient import TestClient | |
| from app.config import Limits | |
| from app.main import create_app | |
| opened = [] | |
| def build(**limits): | |
| client = TestClient(create_app(tmp_path / "data", Limits(**limits))) | |
| client.__enter__() | |
| opened.append(client) | |
| return client | |
| yield build | |
| for client in opened: | |
| client.__exit__(None, None, None) | |
| def client(make_client): | |
| return make_client() | |
| def upload(media: dict[str, Path], *names: str) -> list[tuple]: | |
| """Multipart ``files`` parts for the named media files.""" | |
| return [("files", (name, media[name].read_bytes())) for name in names] | |
| def finish(client, job_id: str, seconds: float = 180.0) -> dict: | |
| """Poll a job until it is done or failed and return its last status.""" | |
| deadline = time.monotonic() + seconds | |
| while True: | |
| status = client.get(f"/v1/jobs/{job_id}").json() | |
| if status["status"] in ("done", "failed"): | |
| return status | |
| assert time.monotonic() < deadline, f"job still {status['status']}: {status['progress']}" | |
| time.sleep(0.2) | |
| def error_of(response, status: int, code: str) -> dict: | |
| """Assert the one error shape and return its inner object.""" | |
| assert response.status_code == status, response.text | |
| body = response.json() | |
| assert set(body) == {"error"} and set(body["error"]) == {"code", "message", "hint"}, body | |
| assert body["error"]["code"] == code, body | |
| assert body["error"]["message"] and body["error"]["hint"] | |
| return body["error"] | |