Files
smeta-web/tests/ui_smoke_harness.py
T
anor 04cb1a5c74 feat(ui/core): срез 6.2 — правка сметы → пересчёт ДВИЖКОМ (не JS)
Объёмы в панели редактируемы (input); «Пересчитать движком» → POST /api/recalc →
estimate_contract.calc_estimate в threadpool (не блокирует сервер) → новая панель с
детерминир. пересчётом. JS не считает — только движок. Браузер-verified (100→250 → итог
пересчитан). APP_VERSION 2026-07-17r.
2026-07-17 23:57:23 +10:00

125 lines
7.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""UI-smoke харнесс (срез UI 0.1): гоняем РЕАЛЬНЫЙ static/chat.html в браузере
без поднятия полного бэкенда (нет .env/venv локально — см. memory
feedback_chat_html_local_smoke).
Идея: берём настоящий static/chat.html и инъектим в <head> стаб, который
подменяет window.fetch поддельными /api-эндпоинтами и кладёт токен в localStorage.
Так браузер исполняет НАСТОЯЩИЕ функции (sendMessage/runChat/openFeedbackForm/…),
а не их копию — регрессии ловятся на живом коде.
Использование:
python3 tests/ui_smoke_harness.py # печатает путь к сгенерированному stub
python3 tests/ui_smoke_harness.py /tmp/x.html # свой путь вывода
Дальше stub раздаётся любым статик-сервером (`python3 -m http.server`) и
драйвится Playwright (file:// заблокирован в MCP-Playwright — только http).
SSE-стаб /api/chat уважает opts.signal — поэтому корректно тестируется abort
(кнопка «Стоп», newChat/switchChat мид-стрим).
"""
import sys
from pathlib import Path
CHAT_HTML = Path(__file__).resolve().parent.parent / "static" / "chat.html"
# Стаб: авторизация + поддельные /api. SSE /api/chat отдаёт tool→text→text→done
# с задержками, уважает signal (abort роняет поток AbortError'ом).
STUB = r"""<script>
localStorage.setItem('token','stub-token'); localStorage.setItem('tabId','stub-tab');
const _enc = new TextEncoder();
window._fb = 0; // счётчик POST /api/feedback (для теста дублей)
function _sse(events, signal){
return new ReadableStream({start(controller){
let i = 0;
const abort = () => { try { controller.error(new DOMException('Aborted','AbortError')); } catch(e){} };
if (signal) { if (signal.aborted) { abort(); return; } signal.addEventListener('abort', abort); }
const tick = () => {
if (signal && signal.aborted) return;
if (i >= events.length) { controller.close(); return; }
controller.enqueue(_enc.encode(events[i])); i++; setTimeout(tick, 300);
};
setTimeout(tick, 120);
}});
}
// Stateful сессии — для тестов панели чатов (rename/delete/поиск)
window._sessions = [
{tab_id:'t-dom', last_ts: 1752700000, msg_count: 4, last_question:'Смета по дому', title: null},
{tab_id:'t-garaj', last_ts: 1752600000, msg_count: 2, last_question:'Смета по гаражу', title: null},
];
window._calls = {del: [], title: []};
function _json(o, status=200){ return new Response(JSON.stringify(o),{status,headers:{'Content-Type':'application/json'}}); }
window.fetch = async (url, opts={}) => {
url = String(url); opts = opts || {};
if (url.includes('/api/chat')) {
const msg = (()=>{ try { return JSON.parse(opts.body||'{}').message||''; } catch(e){ return ''; } })();
const evs = [
'event: tool\ndata: {"tool":"mcp__smeta__verify_estimate_file"}\n\n',
'event: text\ndata: {"text":"Считаю смету"}\n\n',
'event: text\ndata: {"text":" — готово."}\n\n',
];
if (/смет|estimate/i.test(msg)) {
const est = {title:'Смета №1', ok:false,
positions:[
{code:'01-01-001-01', name:'Разработка грунта', unit:'м3', qty:100, unit_cost:150.5, total:15050},
{code:'06-01-001-02', name:'Бетон', unit:'м3', qty:20, unit_cost:5000, total:100000, unresolved:true}],
totals:{grand_pz:115050, grand_nr:10000, grand_sp:5000, grand_total:130050, vat:28611, total_with_vat:158661},
warnings:['Проверьте объёмы по ведомости'],
missing:[{code:'06-01-001-02', reason:'цена материала не найдена'}]};
evs.push('event: estimate\ndata: ' + JSON.stringify(est) + '\n\n');
}
if (/конъюнктур|\bКА\b|конъюктур/i.test(msg)) {
const ka = {query:'щебень', found:true, offer_count:3,
resource:{name:'Щебень фракция 20-40', unit:'м3', region:'г Тула', year:'2024', quarter:'4', code_tc:'ТЦ_‹КСР›_г-Тула_‹ИНН›_4кв2024_‹кодпер›'},
rows:[
{1:1,5:1500,6:1250,7:100,8:30,9:1380,12:'2024',13:'4',14:'Поставщик 1',18:'г Тула',20:3,is_winner:true},
{1:2,5:1550,6:1290,7:'‹нет в источнике›',8:32,9:1420,12:'2024',13:'4',14:'Поставщик 2',18:'г Калуга',20:3,is_winner:false},
{1:3,5:1600,6:1330,7:110,8:35,9:1470,12:'2024',13:'4',14:'Поставщик 3',18:'г Москва',20:3,is_winner:false}],
accepted:{winner:1380,min:1380,median:1420,max:1470},
warnings:['Сверьте ресурс: форма собрана по «Щебень фракция 20-40».']};
evs.push('event: ka_form\ndata: ' + JSON.stringify(ka) + '\n\n');
}
evs.push('event: done\ndata: {"result":"ok"}\n\n');
return new Response(_sse(evs, opts.signal), {status:200, headers:{'Content-Type':'text/event-stream'}});
}
if (url.includes('/api/recalc')) {
const b = JSON.parse(opts.body || '{}'); const pos = b.positions || [];
// «движок»: total позиции = qty*1000; итог = сумма
const positions = pos.map(p => ({code: p.code, name: 'Позиция ' + p.code, unit: p.unit || 'ед',
qty: p.qty, total: p.qty * 1000}));
const gt = positions.reduce((s, p) => s + p.total, 0);
window._recalc = (window._recalc || 0) + 1;
return _json({title: 'Смета (пересчёт)', positions, totals: {grand_total: gt}, ok: true, missing: []});
}
if (url.includes('/api/feedback')) { window._fb++; return _json({}); }
if (url.includes('/api/history')) return _json([]);
// /api/sessions/{tab}/title (POST)
let m = url.match(/\/api\/sessions\/([^/]+)\/title/);
if (m) { const tab = decodeURIComponent(m[1]); const b = JSON.parse(opts.body||'{}');
window._calls.title.push({tab, title:b.title});
const s = window._sessions.find(x=>x.tab_id===tab); if (s) s.title = b.title;
return _json({ok:true, title:b.title}); }
// /api/sessions/{tab} (DELETE)
m = url.match(/\/api\/sessions\/([^/]+)$/);
if (m && (opts.method||'GET').toUpperCase()==='DELETE') {
const tab = decodeURIComponent(m[1]); window._calls.del.push(tab);
window._sessions = window._sessions.filter(x=>x.tab_id!==tab);
return _json({ok:true, removed:1}); }
if (url.includes('/api/sessions')) return _json(window._sessions);
return _json({});
};
</script>
"""
def build_stub(out_path: Path) -> Path:
html = CHAT_HTML.read_text(encoding="utf-8")
if "</head>" not in html:
raise SystemExit("chat.html: нет </head> — некуда инъектить стаб")
out_path.write_text(html.replace("</head>", STUB + "</head>", 1), encoding="utf-8")
return out_path
if __name__ == "__main__":
out = Path(sys.argv[1]) if len(sys.argv) > 1 else CHAT_HTML.parent.parent / "tests" / ".ui_smoke_stub.html"
print(build_stub(out))