dict add button: POST /api/dict/add with anti-injection, provenance lines, forms grid, typo guard (lev<=2); UI buttons; dict_promote; local *.txt layer survives update
This commit is contained in:
1 parent
68be624fb2
commit
7791d3422f
6 files changed
+1387
-14
No files matched your search
@@ -0,0 +1,140 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Кнопка «В словарь» (POST /api/dict/add): валидации, локальный слой, формы."""
|
||||
import os
|
||||
import time
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
import app
|
||||
|
||||
TXT = "Дежурный сообщил что выезд состоялся вовремя и без задержек.\n"
|
||||
|
||||
|
||||
def _run(client, content=TXT, name="doc.txt"):
|
||||
r = client.post("/api/check", files={"file": (name, content, "text/plain")},
|
||||
data={"use_llm": "false"})
|
||||
job = r.json()["job_id"]
|
||||
for _ in range(300):
|
||||
st = client.get(f"/api/job/{job}").json()
|
||||
if st.get("status") in ("done", "error"):
|
||||
break
|
||||
time.sleep(0.05)
|
||||
assert st.get("status") == "done", st
|
||||
return job, client.get(f"/api/report/{job}").json()
|
||||
|
||||
|
||||
def _client(monkeypatch, lt_mock, tmp_path):
|
||||
monkeypatch.setattr(app, "LT_URL", lt_mock["url"])
|
||||
d = {"exceptions.local.txt": str(tmp_path / "exceptions.local.txt"),
|
||||
"toponyms.local.txt": str(tmp_path / "toponyms.local.txt")}
|
||||
monkeypatch.setattr(app, "local_dict_path",
|
||||
lambda target: d.get(target + ".local.txt", str(tmp_path / "junk.local.txt")))
|
||||
client = TestClient(app.app)
|
||||
return client, d
|
||||
|
||||
|
||||
def test_dict_add_happy_and_loader_inline(monkeypatch, lt_mock, tmp_path):
|
||||
client, d = _client(monkeypatch, lt_mock, tmp_path)
|
||||
job, rep = _run(client)
|
||||
frag = rep["findings"][0]["fragment"]
|
||||
r = client.post("/api/dict/add", json={"job_id": job, "fragment": frag,
|
||||
"target": "exceptions", "forms": False})
|
||||
assert r.status_code == 200
|
||||
j = r.json()
|
||||
assert j["added"] == 1 and j["already"] is False
|
||||
content = open(d["exceptions.local.txt"], encoding="utf-8").read()
|
||||
assert content.endswith("\n")
|
||||
first_line = content.splitlines()[0]
|
||||
assert first_line.startswith(frag) and " # " in first_line
|
||||
# журнал ведётся
|
||||
assert (tmp_path / "dict_added.log").exists()
|
||||
|
||||
# загрузчик: провенанс отсекается, слово входит в словарь
|
||||
monkeypatch.setattr(app, "EXCEPTIONS_FILES", [d["exceptions.local.txt"]])
|
||||
words = app.load_exceptions()
|
||||
assert frag.lower() in words
|
||||
assert not any("#" in w for w in words)
|
||||
|
||||
# повтор — already, дублей в файле нет
|
||||
r2 = client.post("/api/dict/add", json={"job_id": job, "fragment": frag,
|
||||
"target": "exceptions", "forms": False})
|
||||
assert r2.status_code == 200 and r2.json()["already"] is True
|
||||
assert len(open(d["exceptions.local.txt"], encoding="utf-8").read().splitlines()) == 1
|
||||
|
||||
# словарь перечитывается при каждой проверке: повторный прогон находку не покажет
|
||||
_, rep2 = _run(client)
|
||||
assert rep2["findings"] == [] and rep2["exceptions_dropped"] >= 1
|
||||
|
||||
|
||||
def test_dict_add_requires_job_findings(monkeypatch, lt_mock, tmp_path):
|
||||
client, _ = _client(monkeypatch, lt_mock, tmp_path)
|
||||
job, _ = _run(client)
|
||||
r = client.post("/api/dict/add", json={"job_id": job, "fragment": "нет такого слова",
|
||||
"target": "exceptions", "forms": False})
|
||||
assert r.status_code == 400
|
||||
r = client.post("/api/dict/add", json={"job_id": "deadbeef", "fragment": "слово",
|
||||
"target": "exceptions"})
|
||||
assert r.status_code == 404
|
||||
r = client.post("/api/dict/add", json={"job_id": job, "fragment": "слово", "target": "дичь"})
|
||||
assert r.status_code == 400
|
||||
|
||||
|
||||
def test_dict_add_validation(monkeypatch, lt_mock, tmp_path):
|
||||
client, _ = _client(monkeypatch, lt_mock, tmp_path)
|
||||
job, rep = _run(client)
|
||||
frag = rep["findings"][0]["fragment"]
|
||||
for bad in [frag + "\nвторая", frag + ";rm", "сл0во", "x" * 65, ""]:
|
||||
r = client.post("/api/dict/add", json={"job_id": job, "fragment": bad,
|
||||
"target": "exceptions"})
|
||||
assert r.status_code == 400, bad
|
||||
assert (tmp_path / "exceptions.local.txt").exists() is False
|
||||
|
||||
|
||||
def test_dict_add_forms_network(monkeypatch, lt_mock, tmp_path):
|
||||
"""«со всеми формами»: прилагательное — слово + 10 склоняемых форм."""
|
||||
lt_mock["keyword"] = "Могилёвский"
|
||||
monkeypatch.setattr(app, "EXCEPTIONS_FILES", []) # «могилёвский» есть в toponyms.txt — отключаем словарь
|
||||
client, d = _client(monkeypatch, lt_mock, tmp_path)
|
||||
job, rep = _run(client, "Могилёвский гарнизон выехал ночью на подмогу.\n")
|
||||
frag = rep["findings"][0]["fragment"]
|
||||
r = client.post("/api/dict/add", json={"job_id": job, "fragment": frag,
|
||||
"target": "toponyms", "forms": True})
|
||||
assert r.status_code == 200
|
||||
j = r.json()
|
||||
assert j["added"] == 11 and j["forms"][0] == frag
|
||||
assert any(f.endswith("ского") for f in j["forms"])
|
||||
lines = open(d["toponyms.local.txt"], encoding="utf-8").read().splitlines()
|
||||
assert len(lines) == 11
|
||||
# стем для dict_promote
|
||||
import sys
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "scripts"))
|
||||
import dict_promote
|
||||
stems, plain = dict_promote.top_stems(dict_promote.parse_local(d["toponyms.local.txt"]))
|
||||
assert ["Могилёв"] == stems and not plain # стем сохраняет регистр формы
|
||||
|
||||
|
||||
def test_dict_add_typo_guard(monkeypatch, lt_mock, tmp_path):
|
||||
"""LT предлагает правку того же корня (lev ≤ 2) → 409 need_confirm → confirm."""
|
||||
lt_mock["keyword"] = "исправлено"
|
||||
lt_mock["replacement"] = "исправлена"
|
||||
client, d = _client(monkeypatch, lt_mock, tmp_path)
|
||||
job, rep = _run(client, "Заявка исправлено по факту проверки.\n")
|
||||
frag = rep["findings"][0]["fragment"]
|
||||
r = client.post("/api/dict/add", json={"job_id": job, "fragment": frag, "target": "exceptions"})
|
||||
assert r.status_code == 409
|
||||
det = r.json()["detail"]
|
||||
assert det["need_confirm"] is True and det["suggestion"] == "исправлена"
|
||||
assert (tmp_path / "exceptions.local.txt").exists() is False # ничего не записано
|
||||
r = client.post("/api/dict/add", json={"job_id": job, "fragment": frag,
|
||||
"target": "exceptions", "confirm": True})
|
||||
assert r.status_code == 200 and r.json()["added"] == 1
|
||||
|
||||
|
||||
def app_dir_python():
|
||||
import os
|
||||
return os.environ.get("PY", "python3")
|
||||
|
||||
|
||||
def root_path():
|
||||
import os
|
||||
return os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
Reference in new issue
Block a user