Files
RustProxy/tools/dev/backend_overview_smoke.py
T
2026-11-25 12:24:26 +01:00

135 lines
7.5 KiB
Python
Executable File

#!/usr/bin/env python3
"""Browser regression for Backends table layout, using source assets and a mock preference API.
Optional development dependencies: pip install playwright; playwright install chromium
(or a system chromium binary). This does not test the compiled RustProxy server.
"""
from pathlib import Path
import json
import re
import shutil
from playwright.sync_api import sync_playwright
ROOT = Path(__file__).resolve().parents[2]
WEB = ROOT / "src/admin/web"
def main():
html = (WEB / "index.html").read_text(encoding="utf-8")
article = re.search(r'<article class="card pool-card backend-overview-card".*?</article>', html, re.S).group()
manifest = json.loads((WEB / "css/manifest.json").read_text(encoding="utf-8"))
styles = "\n".join((WEB / "css" / name).read_text(encoding="utf-8") for name in manifest["files"])
source = (WEB / "vhosts/render.js").read_text(encoding="utf-8")
# Isolate the actual table renderer from the unrelated Vhost editor.
renderer = "const poolColumns =" + source.split("const poolColumns =", 1)[1].split("async function toggleVhostEnabled", 1)[0]
translations = json.loads((ROOT / "langs/en_US.json").read_text(encoding="utf-8"))["translations"]
stubs = "const translations = " + json.dumps(translations) + ";\n" + """
const $ = id => document.getElementById(id);
const el = (tag, text, cls) => { const node = document.createElement(tag); if (text !== undefined) node.textContent = text; if (cls) node.className = cls; return node; };
const t = key => translations[key] || key;
const rateBytes = value => value.toFixed(1) + ' KiB', bytes = rateBytes;
const compareText = (a,b) => String(a).localeCompare(String(b));
const authenticated = true, render = () => {}, toast = message => { throw Error(message); };
window.saved = {};
window.rustProxyPreferences = { update: async patch => {
await new Promise(resolve => setTimeout(resolve, 30));
Object.assign(window.saved, patch);
applyPreferences(window.saved);
return {...window.saved};
}};
"""
fixture = """
initPoolTableTools();
const testColumns = ['vhost','status','active','requests','statuses','latency','traffic','causes','lastFailure'];
const extra = {text:{causes:'5xx 5'},classes:[0,95,0,0,5],classTotal:100,causes:[{label:'5xx',value:5}]};
boItems = Array.from({length:3}, (_,i) => ({
key:String(i),group:'up',tone:'up',vhost:'example-'+i,backend:'origin',label:'UP',title:'healthy',activeText:'17/∞',requests:156901,errors:5,latency:48.8,traffic:15,trafficIn:5,trafficOut:10,sort:{},search:'example',
extra:i===1?{...extra,causes:[],text:{causes:'-'}}:extra,
series:{latency:[45,21,34,48.8],requests:[2,1,5,8,3],inRate:[0,2,4,5],outRate:[5,1,3,10]}
}));
applyPreferences({backend_table_columns:testColumns});
window.measure = () => ({
available:document.querySelector('.table-scroll').clientWidth,
table:document.querySelector('.bo-table').offsetWidth,
charts:Object.fromEntries(['bars','latency','traffic'].map(type => {
const svg = document.querySelector('.bo-spark-'+type);
return [type,svg?{width:svg.getBoundingClientRect().width,height:svg.getBoundingClientRect().height,aspect:svg.getAttribute('preserveAspectRatio')}:null];
})),
causes:[...document.querySelectorAll('td.bo-causes')].map(td => ({
display:getComputedStyle(td).display,top:td.getBoundingClientRect().top,rowTop:td.parentElement.getBoundingClientRect().top,height:td.getBoundingClientRect().height,rowHeight:td.parentElement.getBoundingClientRect().height,text:td.textContent
}))
});
"""
with sync_playwright() as playwright:
browser = playwright.chromium.launch(executable_path=shutil.which("chromium"), headless=True)
page = browser.new_page(viewport={"width":1800,"height":800})
errors = []
page.on("pageerror", lambda error: errors.append(str(error)))
page.set_content('<html data-theme="dark" data-table-density="normal"><head><style>' + styles + '</style></head><body><div id="panel-overview">' + article + '</div></body></html>')
page.add_script_tag(content=stubs + renderer + "\n" + fixture)
measure = lambda: page.evaluate("measure()")
def widths():
return [chart["width"] for chart in measure()["charts"].values()]
def settled():
page.wait_for_function("!poolPreferenceSaveRunning && !poolPreferenceSaveQueued")
def cause_layout():
causes = measure()["causes"]
assert len(causes) == 3 and causes[1]["text"] == "-"
for cell in causes:
assert cell["display"] == "table-cell"
assert abs(cell["top"] - cell["rowTop"]) < 0.1
assert abs(cell["height"] - cell["rowHeight"]) < 0.1
switch = page.locator("#bo-responsive-charts")
page.locator(".backend-column-picker summary").click()
assert not switch.is_checked() and widths() == [84,120,96]
cause_layout()
switch.check()
settled()
assert page.evaluate("saved.backend_table_responsive_charts") is True
assert all(chart["aspect"] == "none" for chart in measure()["charts"].values())
wide = widths()
assert all(a > b for a,b in zip(wide,[84,120,96]))
cause_layout()
# Resize with no rerender; the native table and CSS flex layout do the work.
page.set_viewport_size({"width":2400,"height":800})
assert all(a > b for a,b in zip(widths(),wide))
page.set_viewport_size({"width":600,"height":800})
narrow = measure()
assert narrow["table"] > narrow["available"]
assert all(chart["width"] >= 44 for chart in narrow["charts"].values())
page.set_viewport_size({"width":1800,"height":800})
# Hidden columns free space for each remaining chart.
page.locator('[data-pool-column-toggle="statuses"]').uncheck()
settled()
assert all(a > b for a,b in zip(widths(),wide))
for density,height in [("normal",22),("compact",18),("ultra",14)]:
page.evaluate("density=>document.documentElement.dataset.tableDensity=density",density)
assert all(chart["height"] == height for chart in measure()["charts"].values())
cause_layout()
before_scale = widths()
page.evaluate("document.documentElement.style.setProperty('--ui-scale','.7')")
assert all(a > b for a,b in zip(widths(),before_scale))
page.evaluate("document.documentElement.style.removeProperty('--ui-scale')")
page.evaluate("document.documentElement.dataset.tableDensity='normal'")
# Simulate two changes before the first save has returned.
page.evaluate("""() => { const input = $('bo-responsive-charts'); for (const checked of [false,true,false]) { input.checked = checked; input.dispatchEvent(new Event('change')); } }""")
settled()
assert page.evaluate("saved.backend_table_responsive_charts") is False
assert not switch.is_checked() and widths() == [84,120,96]
assert all(chart["aspect"] is None for chart in measure()["charts"].values())
# Loading account preferences restores the selected mode and absent legacy fields default off.
page.evaluate("applyPreferences({...saved,backend_table_responsive_charts:true})")
assert switch.is_checked()
page.evaluate("applyPreferences({backend_table_columns:testColumns})")
assert not switch.is_checked() and widths() == [84,120,96]
cause_layout()
assert not errors, errors
browser.close()
print("Backends browser regression passed (mock preference API, real source assets).")
if __name__ == "__main__":
main()