"""Verify the running FastAPI server with a real HTTP enhancement request.""" from __future__ import annotations import argparse import json import sys import time from io import BytesIO from pathlib import Path import httpx from PIL import Image BACKEND_ROOT = Path(__file__).resolve().parents[1] DEFAULT_INPUT = BACKEND_ROOT / "tests" / "fixtures" / "0014.jpg" DEFAULT_OUTPUT = BACKEND_ROOT / "outputs" / "api-0014-enhanced-4x.png" def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--base-url", default="http://127.0.0.1:8000") parser.add_argument("--input", type=Path, default=DEFAULT_INPUT) parser.add_argument("--output", type=Path, default=DEFAULT_OUTPUT) arguments = parser.parse_args() base_url = arguments.base_url.rstrip("/") input_bytes = arguments.input.read_bytes() with Image.open(BytesIO(input_bytes)) as source: source.load() source_width, source_height = source.size timeout = httpx.Timeout(connect=10, read=180, write=30, pool=10) with httpx.Client(timeout=timeout) as client: health = client.get(f"{base_url}/health") health.raise_for_status() if health.json().get("ready") is not True: raise RuntimeError("The API health endpoint did not report ready.") docs = client.get(f"{base_url}/docs") docs.raise_for_status() if "swagger-ui" not in docs.text: raise RuntimeError("Swagger UI was not served at /docs.") schema_response = client.get(f"{base_url}/openapi.json") schema_response.raise_for_status() schema = schema_response.json() operation = schema["paths"]["/api/enhance"]["post"] form_schema = operation["requestBody"]["content"]["multipart/form-data"][ "schema" ] component = form_schema.get("$ref", "").rsplit("/", maxsplit=1)[-1] fields = sorted(schema["components"]["schemas"][component]["properties"]) if fields != ["file", "output_format", "scale"]: raise RuntimeError(f"Unexpected multipart fields in OpenAPI: {fields}") started = time.perf_counter() response = client.post( f"{base_url}/api/enhance", files={"file": (arguments.input.name, input_bytes, "image/jpeg")}, data={"scale": "4", "output_format": "png"}, ) elapsed = time.perf_counter() - started response.raise_for_status() expected_size = (source_width * 4, source_height * 4) required_headers = { "x-original-width": str(source_width), "x-original-height": str(source_height), "x-enhanced-width": str(expected_size[0]), "x-enhanced-height": str(expected_size[1]), "x-upscale-factor": "4", "x-model": "RealESRGAN_x4plus", } for name, value in required_headers.items(): if response.headers.get(name) != value: raise RuntimeError(f"Unexpected {name} response header.") if ( response.headers.get("content-type", "").split(";", maxsplit=1)[0] != "image/png" ): raise RuntimeError("The API did not return a PNG image.") if not response.headers.get("content-disposition", "").startswith("attachment;"): raise RuntimeError("The response did not include a download disposition.") if response.content == input_bytes: raise RuntimeError("The API response unexpectedly matches the input bytes.") with Image.open(BytesIO(response.content)) as output: output.load() if output.format != "PNG" or output.size != expected_size: raise RuntimeError( f"Unexpected decoded output: {output.format} {output.size}, " f"expected PNG {expected_size}." ) arguments.output.parent.mkdir(parents=True, exist_ok=True) arguments.output.write_bytes(response.content) print( json.dumps( { "health_status": health.status_code, "docs_status": docs.status_code, "openapi_status": schema_response.status_code, "openapi_multipart_fields": fields, "enhance_status": response.status_code, "content_type": response.headers["content-type"], "response_headers": { **required_headers, "content-disposition": response.headers["content-disposition"], }, "input_dimensions": [source_width, source_height], "output_dimensions": list(expected_size), "output_bytes": len(response.content), "output_path": str(arguments.output.resolve()), "elapsed_seconds": round(elapsed, 3), "response_differs_from_input": response.content != input_bytes, }, indent=2, ) ) return 0 if __name__ == "__main__": try: raise SystemExit(main()) except Exception as error: print(f"HTTP API smoke test failed: {error}", file=sys.stderr) raise SystemExit(1) from error