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

75 lines
2.4 KiB
Python

import os
import pytest
from fastapi.testclient import TestClient
from app.main import app
client = TestClient(app)
def test_replace_text_operation():
filepath = os.path.abspath("../corpus/basic/hello_world.pdf")
if not os.path.exists(filepath):
filepath = os.path.abspath("gateway/../corpus/basic/hello_world.pdf")
with open(filepath, "rb") as f:
resp = client.post("/documents", files={"file": ("hello_world.pdf", f, "application/pdf")})
assert resp.status_code == 201
doc_id = resp.json()["id"]
resp = client.get(f"/documents/{doc_id}/pages/0/model")
assert resp.status_code == 200
model = resp.json()
target_run = None
for p in model["paragraphs"]:
for line in p["lines"]:
for run in line["runs"]:
if "hello" in run["text"].lower():
target_run = run
break
if target_run:
break
if target_run:
break
assert target_run is not None, "Could not find a text run with 'hello'"
assert "object_indices" in target_run
assert len(target_run["object_indices"]) > 0
for g in target_run["glyphs"]:
assert "page_object_index" in g
assert g["page_object_index"] >= 0
edits_payload = {
"version": "1.0",
"operations": [
{
"id": "replace_text_op_1",
"type": "replace_text",
"pageIndex": 0,
"data": {
"objectIndices": target_run["object_indices"],
"text": "Greeting, universe!",
"internalFontId": target_run["internal_font_id"],
"fontSize": target_run["font_size"]
}
}
]
}
resp = client.post(f"/documents/{doc_id}/edits", json=edits_payload)
assert resp.status_code == 200
res = resp.json()
assert res["success"] is True
new_doc_id = res["newDocumentId"]
resp = client.get(f"/documents/{new_doc_id}/pages/0/text")
assert resp.status_code == 200
text_data = resp.json()
assert "Greeting, universe!" in text_data["text"]
assert "hello" not in text_data["text"].lower()
resp = client.get(f"/documents/{new_doc_id}/pages/0/render")
assert resp.status_code == 200
assert resp.headers["content-type"] == "image/png"