chore: закоммичены все рабочие файлы smeta-web

Предотвращение потери данных при деплое:
batch_v3, search_engine, xlsx_utils, тесты, скрипты деплоя,
архитектура, security page, admin page.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
anor
2026-03-30 04:48:52 +10:00
co-authored by Claude Opus 4.6
parent 223112c085
commit 56ba1bd5aa
15 changed files with 2456 additions and 61 deletions
+254
View File
@@ -0,0 +1,254 @@
#!/usr/bin/env python3
"""
Chat quality test suite — sends 100 questions, checks for expected markers.
Usage:
python tests/test_chat_quality.py # full test (100 questions)
python tests/test_chat_quality.py --category НР # only НР questions
python tests/test_chat_quality.py --quick # first 20 questions
python tests/test_chat_quality.py --id 42 # single question by id
python tests/test_chat_quality.py --report # last run report
Requires: running smeta-web instance (localhost:8101 or SMETA_URL env var)
"""
import json
import os
import sys
import time
from datetime import datetime
from pathlib import Path
# Config
SMETA_URL = os.environ.get("SMETA_URL", "http://localhost:8101")
TESTS_DIR = Path(__file__).parent
QUESTIONS_FILE = TESTS_DIR / "test_questions.json"
RESULTS_FILE = TESTS_DIR / "test_results.json"
TIMEOUT = 120 # seconds per question
def get_token() -> str:
"""Generate a fresh JWT token."""
sys.path.insert(0, str(Path(__file__).parent.parent))
from auth import _make_token
return _make_token("test@test.ru", "admin")
def ask_question(question: str, token: str, tab_id: str) -> str:
"""Send question to chat API, return response text."""
import httpx
try:
with httpx.Client(timeout=TIMEOUT) as client:
resp = client.post(
f"{SMETA_URL}/api/chat",
json={"message": question},
headers={
"Authorization": f"Bearer {token}",
"X-Tab-Id": tab_id,
},
)
# Parse SSE response — collect all text events
texts = []
for line in resp.text.split("\n"):
if line.startswith("data: "):
try:
data = json.loads(line[6:])
t = data.get("text") or data.get("result") or ""
if t:
texts.append(t)
except json.JSONDecodeError:
pass
# Concatenate all text events (done event may duplicate, but markers check is OR)
return "\n".join(texts) if texts else ""
except Exception as e:
return f"ERROR: {e}"
def check_markers(response: str, markers: list[str]) -> tuple[bool, list[str]]:
"""Check if all markers are present in response (case-insensitive, comma/dot normalized)."""
# Normalize: comma→dot, various dashes→hyphen, collapse spaces
import re as _re
def _norm(s):
s = s.lower()
s = s.replace("**", "").replace("*", "") # strip markdown bold/italic
s = s.replace(",", ".").replace("–", "-").replace("—", "-")
s = _re.sub(r'\s+', ' ', s)
s = _re.sub(r'\s*\.\s*', '.', s)
s = _re.sub(r'\s*-\s*', '-', s)
return s
resp_norm = _norm(response)
missing = []
for m in markers:
m_norm = _norm(m)
if m_norm not in resp_norm:
missing.append(m)
return len(missing) == 0, missing
def run_tests(
questions: list[dict],
token: str,
verbose: bool = True,
) -> dict:
"""Run all tests, return results dict."""
results = {
"timestamp": datetime.now().isoformat(),
"total": len(questions),
"passed": 0,
"failed": 0,
"errors": 0,
"details": [],
"by_category": {},
}
for i, q in enumerate(questions):
qid = q["id"]
category = q["category"]
question = q["question"]
markers = q["markers"]
tab_id = f"test_{qid}_{int(time.time())}"
t0 = time.time()
response = ask_question(question, token, tab_id)
elapsed = time.time() - t0
if response.startswith("ERROR:"):
status = "error"
missing = markers
results["errors"] += 1
else:
passed, missing = check_markers(response, markers)
if passed:
status = "pass"
results["passed"] += 1
else:
status = "fail"
results["failed"] += 1
detail = {
"id": qid,
"category": category,
"question": question,
"status": status,
"missing_markers": missing,
"response_length": len(response),
"elapsed_s": round(elapsed, 1),
}
if status != "pass":
detail["response_preview"] = response[:300]
results["details"].append(detail)
# Track by category
if category not in results["by_category"]:
results["by_category"][category] = {"pass": 0, "fail": 0, "error": 0}
results["by_category"][category][status] = (
results["by_category"][category].get(status, 0) + 1
)
# Progress
icon = {"pass": "✅", "fail": "❌", "error": "💥"}[status]
if verbose:
extra = f" (missing: {missing})" if missing else ""
print(f" {icon} Q{qid:3d} [{category:20s}] {elapsed:.1f}s{extra}")
return results
def print_summary(results: dict):
"""Print formatted summary."""
total = results["total"]
passed = results["passed"]
failed = results["failed"]
errors = results["errors"]
print(f"\n{'='*60}")
print(f" CHAT QUALITY TEST RESULTS — {results['timestamp'][:19]}")
print(f"{'='*60}")
print(f" Total: {total}")
print(f" Passed: {passed} ({100*passed//total}%)")
print(f" Failed: {failed}")
print(f" Errors: {errors}")
if results["by_category"]:
print(f"\n By category:")
for cat, stats in sorted(results["by_category"].items()):
p = stats.get("pass", 0)
f = stats.get("fail", 0)
e = stats.get("error", 0)
t = p + f + e
icon = "✅" if f == 0 and e == 0 else "❌"
print(f" {icon} {cat:25s} {p}/{t}")
if failed > 0 or errors > 0:
print(f"\n Failed questions:")
for d in results["details"]:
if d["status"] != "pass":
print(f" Q{d['id']}: {d['question'][:60]}")
print(f" Missing: {d['missing_markers']}")
if "response_preview" in d:
print(f" Response: {d['response_preview'][:100]}...")
print(f"{'='*60}")
if passed == total:
print(f" ✅ ALL {total} TESTS PASSED")
else:
print(f" ⚠ {failed + errors} TESTS NEED ATTENTION")
print(f"{'='*60}")
def main():
args = sys.argv[1:]
# Load questions
questions = json.loads(QUESTIONS_FILE.read_text(encoding="utf-8"))
# Filter
if "--report" in args:
if RESULTS_FILE.exists():
results = json.loads(RESULTS_FILE.read_text(encoding="utf-8"))
print_summary(results)
else:
print("No previous results found")
return
if "--quick" in args:
questions = questions[:20]
elif "--category" in args:
idx = args.index("--category")
cat = args[idx + 1] if idx + 1 < len(args) else ""
questions = [q for q in questions if cat.lower() in q["category"].lower()]
elif "--id" in args:
idx = args.index("--id")
qid = int(args[idx + 1]) if idx + 1 < len(args) else 1
questions = [q for q in questions if q["id"] == qid]
if not questions:
print("No matching questions found")
return
print(f"Running {len(questions)} tests against {SMETA_URL}...")
# Get token
try:
token = get_token()
except Exception:
# Fallback: generate via env
print("Could not generate token locally, trying env SESSION_SECRET...")
os.environ.setdefault("SESSION_SECRET", "test")
token = get_token()
# Run
results = run_tests(questions, token, verbose=True)
# Save
RESULTS_FILE.write_text(
json.dumps(results, ensure_ascii=False, indent=2), encoding="utf-8"
)
# Summary
print_summary(results)
if __name__ == "__main__":
main()