some
This commit is contained in:
@@ -0,0 +1,232 @@
|
||||
"""Wire fixture and independent conversion assets."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import gzip
|
||||
import io
|
||||
import json
|
||||
import shutil
|
||||
import subprocess
|
||||
import threading
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import dataclass
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Final, override
|
||||
from urllib.parse import parse_qs, urlsplit
|
||||
|
||||
import pytest
|
||||
from PIL import Image, ImageDraw
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Iterator
|
||||
|
||||
from pydantic import JsonValue
|
||||
|
||||
TOKEN: Final = "123456:FixtureCredential_Only_0123456789"
|
||||
ROOT: Final = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Reply:
|
||||
"""Immutable wire response for one fixture route."""
|
||||
|
||||
body: bytes
|
||||
status: int = 200
|
||||
location: str = ""
|
||||
|
||||
|
||||
def encoded(value: JsonValue) -> bytes:
|
||||
"""Serialize independent fixture JSON into a wire response."""
|
||||
return json.dumps(value).encode()
|
||||
|
||||
|
||||
@contextmanager
|
||||
def api_server(
|
||||
routes: dict[str, Reply], received: list[str] | None = None
|
||||
) -> Iterator[str]:
|
||||
"""Serve fixture routes on loopback without logging request credentials."""
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def do_GET(self) -> None:
|
||||
if received is not None:
|
||||
received.append(self.path)
|
||||
parsed = urlsplit(self.path)
|
||||
key = parsed.path.rsplit("/", 1)[-1]
|
||||
if key == "getFile":
|
||||
key = parse_qs(parsed.query)["file_id"][0]
|
||||
reply = routes.get(key, Reply(b"", 404))
|
||||
self.send_response(reply.status)
|
||||
if reply.location:
|
||||
self.send_header("Location", reply.location)
|
||||
self.send_header("Content-Length", str(len(reply.body)))
|
||||
self.end_headers()
|
||||
try:
|
||||
_ = self.wfile.write(reply.body)
|
||||
except (BrokenPipeError, ConnectionResetError):
|
||||
return # Expected when bounded client rejects oversized fixture.
|
||||
|
||||
@override
|
||||
def log_message(self, format: str, *args: str | int) -> None:
|
||||
return # Never log credential-bearing fixture paths.
|
||||
|
||||
with ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server:
|
||||
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
try:
|
||||
yield f"http://127.0.0.1:{server.server_port}"
|
||||
finally:
|
||||
server.shutdown()
|
||||
thread.join()
|
||||
|
||||
|
||||
def routes_for(assets: dict[str, bytes]) -> dict[str, Reply]:
|
||||
"""Describe source files using Bot API envelopes and download routes."""
|
||||
stickers: list[JsonValue] = []
|
||||
routes: dict[str, Reply] = {}
|
||||
for index, (filename, data) in enumerate(assets.items()):
|
||||
file_id = f"file{index}"
|
||||
stickers.append(
|
||||
{
|
||||
"file_id": file_id,
|
||||
"width": 512,
|
||||
"height": 512,
|
||||
"is_animated": filename.endswith(".tgs"),
|
||||
"is_video": filename.endswith(".webm"),
|
||||
"emoji": "😀",
|
||||
"file_size": len(data),
|
||||
}
|
||||
)
|
||||
routes[file_id] = Reply(
|
||||
encoded(
|
||||
{
|
||||
"ok": True,
|
||||
"result": {
|
||||
"file_path": "stickers/" + filename,
|
||||
"file_size": len(data),
|
||||
},
|
||||
}
|
||||
)
|
||||
)
|
||||
routes[filename] = Reply(data)
|
||||
routes["getStickerSet"] = Reply(
|
||||
encoded(
|
||||
{
|
||||
"ok": True,
|
||||
"result": {
|
||||
"name": "FixturePack",
|
||||
"title": "Fixture pack",
|
||||
"stickers": stickers,
|
||||
},
|
||||
}
|
||||
)
|
||||
)
|
||||
return routes
|
||||
|
||||
|
||||
def vector_data() -> JsonValue:
|
||||
"""Describe a moving solid layer independently of the converter."""
|
||||
return {
|
||||
"v": "5.5.2",
|
||||
"w": 512,
|
||||
"h": 512,
|
||||
"fr": 30,
|
||||
"ip": 0,
|
||||
"op": 30,
|
||||
"layers": [
|
||||
{
|
||||
"ty": 1,
|
||||
"ind": 1,
|
||||
"ip": 0,
|
||||
"op": 30,
|
||||
"st": 0,
|
||||
"sw": 128,
|
||||
"sh": 128,
|
||||
"sc": "#00ff00",
|
||||
"ks": {
|
||||
"o": {"a": 0, "k": 100},
|
||||
"r": {"a": 0, "k": 0},
|
||||
"p": {
|
||||
"a": 1,
|
||||
"k": [
|
||||
{
|
||||
"t": 0,
|
||||
"s": [64, 192],
|
||||
"e": [320, 192],
|
||||
"i": {"x": 1, "y": 1},
|
||||
"o": {"x": 0, "y": 0},
|
||||
},
|
||||
{"t": 30, "s": [320, 192]},
|
||||
],
|
||||
},
|
||||
"a": {"a": 0, "k": [0, 0]},
|
||||
"s": {"a": 0, "k": [100, 100]},
|
||||
},
|
||||
}
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def make_conversion_assets() -> dict[str, bytes]:
|
||||
"""Generate source media shared by CLI tests and the isolated game API fixture."""
|
||||
image = Image.new("RGBA", (256, 128))
|
||||
ImageDraw.Draw(image).rectangle((64, 32, 191, 95), fill=(255, 0, 0, 255))
|
||||
with io.BytesIO() as buffer:
|
||||
image.save(buffer, format="WEBP", lossless=True)
|
||||
webp = buffer.getvalue()
|
||||
frames: list[bytes] = []
|
||||
for index in range(80):
|
||||
image = Image.new("RGBA", (128, 128))
|
||||
ImageDraw.Draw(image).rectangle(
|
||||
(index % 64, 32, index % 64 + 31, 63), fill=(0, 0, 255, 255)
|
||||
)
|
||||
frames.append(image.tobytes())
|
||||
ffmpeg = shutil.which("ffmpeg")
|
||||
if ffmpeg is None:
|
||||
pytest.fail("ffmpeg is required to generate independent video fixtures")
|
||||
video = subprocess.run(
|
||||
[
|
||||
ffmpeg,
|
||||
"-v",
|
||||
"error",
|
||||
"-nostdin",
|
||||
"-threads",
|
||||
"1",
|
||||
"-f",
|
||||
"rawvideo",
|
||||
"-pixel_format",
|
||||
"rgba",
|
||||
"-video_size",
|
||||
"128x128",
|
||||
"-framerate",
|
||||
"20",
|
||||
"-i",
|
||||
"pipe:0",
|
||||
"-c:v",
|
||||
"libvpx-vp9",
|
||||
"-threads",
|
||||
"1",
|
||||
"-pix_fmt",
|
||||
"yuva420p",
|
||||
"-auto-alt-ref",
|
||||
"0",
|
||||
"-f",
|
||||
"webm",
|
||||
"pipe:1",
|
||||
],
|
||||
input=b"".join(frames),
|
||||
capture_output=True,
|
||||
check=True,
|
||||
timeout=30,
|
||||
).stdout
|
||||
return {
|
||||
"static.webp": webp,
|
||||
"vector.tgs": gzip.compress(encoded(vector_data())),
|
||||
"video.webm": video,
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def conversion_assets() -> dict[str, bytes]:
|
||||
"""Provide the same independent source media to parametrized import checks."""
|
||||
return make_conversion_assets()
|
||||
Reference in New Issue
Block a user