Files
smeta-web/tests/test_inline_estimate_ui.py
T

125 lines
6.2 KiB
Python

"""The price selector edits the current answer bubble in a real browser."""
import functools
import http.server
import os
import socketserver
import sys
import threading
from pathlib import Path
import pytest
sys.path.insert(0, str(Path(__file__).resolve().parent))
pytest.importorskip("playwright.sync_api")
import ui_smoke_harness # noqa: E402
from test_password_reset_ui import browser # noqa: E402,F401
@pytest.fixture(scope="module")
def site(tmp_path_factory):
directory = tmp_path_factory.mktemp("inline-estimate")
ui_smoke_harness.build_stub(directory / "index.html", logged_in=True)
handler = functools.partial(http.server.SimpleHTTPRequestHandler, directory=str(directory))
class Quiet(socketserver.ThreadingTCPServer):
allow_reuse_address = True
daemon_threads = True
server = Quiet(("127.0.0.1", 0), handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
yield f"http://127.0.0.1:{server.server_address[1]}/index.html"
server.shutdown()
def test_choice_replaces_current_answer_without_new_bubble(browser, site):
page = browser.new_page(viewport={"width": 390, "height": 844})
page.goto(site)
page.wait_for_timeout(500)
page.evaluate("""() => {
const oldFetch = window.fetch;
window._basisPosts = [];
const old = {title:'Смета', _message_id:31, _assistant_id:30, _revision:0, ok:true,
positions:[{code:'ГЭСН 01-01-001-01',name:'Работа',unit:'м3',qty:2,total:100}],
totals:{grand_total:100}, applied:{subject:'Тестовый край',subject_id:1,
zone:'Тестовый край (1 зона)',zone_id:11,period:'3 квартал 2026',period_id:403}};
window.fetch = async (url, opts={}) => {
if (String(url).includes('/api/estimates/31/basis')) {
if (opts.method === 'POST') {
window._basisPosts.push(JSON.parse(opts.body));
return new Response(JSON.stringify({answer:'Итого: 240 ₽ · 4 квартал 2026',
estimate:{...old,_revision:1,
positions:[{...old.positions[0],total:240}],totals:{grand_total:240},
applied:{...old.applied,zone:'Тестовый край (2 зона)',zone_id:12,
period:'4 квартал 2026',period_id:404}}}),
{status:200,headers:{'Content-Type':'application/json'}});
}
return new Response(JSON.stringify({revision:0,zones:[
{zone_id:11,name:'Тестовый край (1 зона)',periods:[{period_id:403,name:'3 квартал 2026'}]},
{zone_id:12,name:'Тестовый край (2 зона)',periods:[
{period_id:402,name:'2 квартал 2026'},
{period_id:404,name:'4 квартал 2026'}]}]}),
{status:200,headers:{'Content-Type':'application/json'}});
}
return oldFetch(url,opts);
};
const answer = addMsg('ai','Исходный ответ: 100 ₽');
addEstimatePanel(old,null,answer);
window._answer = answer;
}""")
page.locator(".est-basis-picker button").click()
page.locator('select[aria-label="Ценовая зона"]').select_option("12")
page.wait_for_function("window._basisPosts.length === 1 && window._answer.innerText.includes('240')")
state = page.evaluate("""() => ({
bubbles: document.querySelectorAll('#messages .msg-ai').length,
within: !!window._answer.querySelector('.est-panel'),
text: window._answer.innerText,
posts: window._basisPosts,
cssWidth: window.innerWidth,
headDisplay: getComputedStyle(window._answer.querySelector('.est-header-row')).display,
hostClass: window._answer.className,
horizontalOverflow: document.documentElement.scrollWidth > window.innerWidth
})""")
screenshot_dir = os.environ.get("INLINE_ESTIMATE_SCREENSHOTS")
if screenshot_dir:
page.evaluate("document.querySelector('#messages').scrollTop = 0")
page.screenshot(path=str(Path(screenshot_dir) / "inline-estimate-mobile.png"))
page.evaluate("document.querySelector('#messages').scrollTop = document.querySelector('#messages').scrollHeight")
page.screenshot(path=str(Path(screenshot_dir) / "inline-estimate-mobile-bottom.png"))
page.set_viewport_size({"width": 1280, "height": 800})
page.screenshot(path=str(Path(screenshot_dir) / "inline-estimate-desktop.png"))
page.close()
assert state["bubbles"] == 1 and state["within"]
assert "Исходный ответ: 100" not in state["text"]
assert "240" in state["text"] and "4 квартал 2026" in state["text"]
assert state["posts"][0]["zone_id"] == 12
assert state["posts"][0]["period_id"] == 404
assert state["headDisplay"] == "none", state
assert not state["horizontalOverflow"]
def test_saved_revision_reopens_inside_same_bubble(browser, site):
page = browser.new_page(viewport={"width": 390, "height": 844})
page.goto(site)
page.wait_for_timeout(500)
state = page.evaluate("""async () => {
const oldFetch = window.fetch;
window.fetch = async (url, opts={}) => {
if (String(url).includes('/api/history')) return new Response(JSON.stringify([
{id:30,role:'assistant',content:'Итого по локальной смете: 240 ₽',timestamp:1},
{id:31,role:'estimate',timestamp:2,content:JSON.stringify({
_assistant_id:30,_revision:1,title:'Смета',ok:true,
positions:[{code:'ГЭСН 01-01-001-01',name:'Работа',unit:'м3',qty:2,total:240}],
totals:{grand_total:240},applied:{subject:'Тестовый край',subject_id:1,
zone:'Тестовый край (2 зона)',zone_id:12,period:'4 квартал 2026',period_id:404}})}
]),{status:200,headers:{'Content-Type':'application/json'}});
return oldFetch(url,opts);
};
await loadHistory();
return {bubbles:document.querySelectorAll('#messages .msg-ai').length,
inside:!!document.querySelector('#messages .msg-ai .est-panel'),
text:document.querySelector('#messages .msg-ai')?.innerText || ''};
}""")
page.close()
assert state["bubbles"] == 1 and state["inside"]
assert "240" in state["text"] and "4 квартал 2026" in state["text"]