Files
pdf/gateway/tests/test_glyph_metrics.py
2026-06-22 15:18:47 +05:30

85 lines
2.8 KiB
Python

import os
import pytest
from fastapi.testclient import TestClient
from app.main import app
client = TestClient(app)
def get_doc_id(filename: str) -> str:
"""Upload a PDF from corpus/fonts and return its document ID."""
filepath = os.path.abspath(f"gateway/../corpus/fonts/{filename}")
if not os.path.exists(filepath):
filepath = os.path.abspath(f"../corpus/fonts/{filename}")
with open(filepath, "rb") as f:
resp = client.post("/documents", files={"file": (filename, f, "application/pdf")})
assert resp.status_code == 201, f"Failed to load {filename}: {resp.json()}"
return resp.json()["id"]
def test_glyph_width_proportionality():
"""Verify that wide characters return larger glyph widths than narrow characters."""
doc_id = get_doc_id("utf-8.pdf")
resp = client.get(f"/documents/{doc_id}/pages/0/fonts")
assert resp.status_code == 200
fonts = resp.json()
assert len(fonts) > 0, "No fonts extracted from utf-8.pdf"
font_name = fonts[0]["fontName"]
w_resp = client.get(
f"/documents/{doc_id}/pages/0/fonts/glyph-width",
params={"font_name": font_name, "charcode": 87, "font_size": 12.0},
)
assert w_resp.status_code == 200
w_width = w_resp.json()["width"]
assert w_width > 0.0
i_resp = client.get(
f"/documents/{doc_id}/pages/0/fonts/glyph-width",
params={"font_name": font_name, "charcode": 105, "font_size": 12.0},
)
assert i_resp.status_code == 200
i_width = i_resp.json()["width"]
assert i_width > 0.0
assert w_width > i_width, f"Expected width('W') > width('i'), got {w_width} vs {i_width}"
def test_glyph_width_font_size_scaling():
"""Verify that glyph width scales proportionally with font size."""
doc_id = get_doc_id("utf-8.pdf")
resp = client.get(f"/documents/{doc_id}/pages/0/fonts")
fonts = resp.json()
font_name = fonts[0]["fontName"]
resp_12 = client.get(
f"/documents/{doc_id}/pages/0/fonts/glyph-width",
params={"font_name": font_name, "charcode": 65, "font_size": 12.0},
)
assert resp_12.status_code == 200
width_12 = resp_12.json()["width"]
resp_24 = client.get(
f"/documents/{doc_id}/pages/0/fonts/glyph-width",
params={"font_name": font_name, "charcode": 65, "font_size": 24.0},
)
assert resp_24.status_code == 200
width_24 = resp_24.json()["width"]
assert pytest.approx(width_24) == 2.0 * width_12
def test_glyph_width_invalid_font():
"""Verify that querying an invalid font returns a bad request error."""
doc_id = get_doc_id("utf-8.pdf")
resp = client.get(
f"/documents/{doc_id}/pages/0/fonts/glyph-width",
params={"font_name": "NonExistentFontName123", "charcode": 65, "font_size": 12.0},
)
assert resp.status_code == 400
assert "detail" in resp.json()