You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/tests/manual/admin_sidebar_fixture.py

354 lines
16 KiB
Python

#!/usr/bin/env python3
"""Serve the real administrator sidebar CSS and script without PHP or a database.
Run: python3 web/tests/manual/admin_sidebar_fixture.py [--port 8766]
Open http://127.0.0.1:8766/a with a viewport narrower than 992 CSS pixels.
Use "Run scroll and coverage checks", "Test 204 recovery", and the real menu
button. Page B responds after 800 ms. Open the menu, follow "Slow page B", then
use browser Back to exercise actual BFCache. The report explicitly says SKIP
when the browser does not restore from BFCache; a separate historyReturn check
still verifies the saved scroll after a new-document history return. The
fixture stores only its expected value in its own sessionStorage key.
Resize while the menu is open
and press "Snapshot" to inspect coverage. The visible report and
window.sidebarFixture.snapshot() expose geometry for browser automation.
This desktop fixture verifies layout and interactions, not iOS toolbar or
rubber-band behavior. Those need a real device. This server only binds loopback.
"""
import argparse
import html
import re
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import urlsplit
WEB_ROOT = Path(__file__).resolve().parents[2]
ASSETS = {
"/theme/venix/css/app.min.css": WEB_ROOT / "public/theme/venix/css/app.min.css",
"/theme/venix/css/admin-home.css": WEB_ROOT / "public/theme/venix/css/admin-home.css",
}
FOOTER = WEB_ROOT / "resources/views/venix/admin/static_footer.tpl"
def sidebar_script():
scripts = re.findall(r"<script>(.*?)</script>", FOOTER.read_text(), re.DOTALL)
matches = [script for script in scripts if "button-toggle-menu" in script]
if len(matches) != 1:
raise RuntimeError("Expected exactly one real administrator sidebar script")
return matches[0]
def page(path):
label = "A" if path == "/a" else "B"
menu_rows = "".join(
f'<li><a href="{path}#anchor">Menu item {index:02d}</a></li>'
for index in range(1, 27)
)
cards = "".join(
f'<section class="fixture-card"><h2>Page {label}: section {index}</h2>'
'<p>Visible page content must remain visible while navigating.</p></section>'
for index in range(1, 16)
)
document = r"""<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Administrator sidebar fixture — __LABEL__</title>
<link rel="stylesheet" href="/theme/venix/css/app.min.css">
<link rel="stylesheet" href="/theme/venix/css/admin-home.css">
<style>
.fixture-card { padding: 24px; margin: 20px 0; min-height: 220px; background: white; border: 1px solid #ccd5df; }
.fixture-controls { display: flex; flex-wrap: wrap; gap: 8px; margin: 16px 0; }
.fixture-controls button { padding: 8px; }
#fixture-report-panel { position: fixed; z-index: 4000; top: 78px; right: 8px; width: min(290px, 70vw); max-height: 65vh; overflow: auto; background: #fff; border: 1px solid #6b7788; padding: 8px; font: 12px/1.4 monospace; }
#fixture-report-panel summary { cursor: pointer; }
#fixture-report { margin: 8px 0; white-space: pre-wrap; overflow-wrap: anywhere; }
#fixture-report-panel button { padding: 4px; }
#side-navbar .fixture-menu-actions { color: #fff; }
</style>
</head>
<body data-menu-color="dark" data-sidebar="default" class="admin-template-body">
<div id="app-layout" class="admin-template">
<div class="topbar-custom">
<div class="container-fluid d-flex align-items-center gap-3">
<button class="button-toggle-menu" type="button" aria-label="Toggle administrator navigation" aria-expanded="false" aria-controls="fixture-sidebar">Menu</button>
<strong>Fixture page __LABEL__</strong>
</div>
</div>
<div class="app-sidebar-menu" id="fixture-sidebar">
<div class="h-100"><div id="sidebar-menu">
<div class="logo-box">Administrator fixture</div>
<ul id="side-navbar">
<li><a class="fixture-menu-actions" href="/a">Page A</a></li>
<li><a class="fixture-menu-actions" href="/b" id="fixture-slow-link">Slow page B (800 ms)</a></li>
<li><a class="fixture-menu-actions" href="/no-content" id="fixture-204-link">No-content response (204)</a></li>
<li><a href="__PATH__">Same page</a></li>
__MENU_ROWS__
<li><a href="/b" id="fixture-last-link">Last menu link — page B</a></li>
</ul>
</div></div>
</div>
<button class="admin-sidebar-backdrop" type="button" aria-label="Close administrator navigation"></button>
<div class="content-page"><div class="content"><div class="container-fluid">
<h1 id="fixture-marker">Page __LABEL__: real sidebar regression fixture</h1>
<p>Use a mobile viewport. Real CSS and navigation script are read live from this checkout.</p>
<div class="fixture-controls">
<button id="fixture-run" type="button">Run scroll and coverage checks</button>
<button id="fixture-204" type="button">Test 204 recovery</button>
<button id="fixture-scrolled-open" type="button">Open menu at page scroll 600</button>
</div>
<p id="anchor">Same-page hash destination</p>
__CARDS__
</div></div><footer class="footer">End of fixture page __LABEL__</footer></div>
</div>
<details id="fixture-report-panel">
<summary>Regression results</summary>
<button id="fixture-snapshot" type="button">Snapshot</button>
<button id="fixture-bottom" type="button">Scroll menu to bottom</button>
<pre id="fixture-report" aria-live="polite"></pre>
</details>
<script>__REAL_SCRIPT__</script>
<script>
(function () {
'use strict';
var results = [];
var running = false;
var expectedReturnScroll = null;
var expectedScrollKey = 'virt-cloud:sidebar-fixture:return:' + window.location.href;
var bfcache = { status: 'SKIP', detail: 'No real BFCache restoration observed yet.' };
var historyReturn = { status: 'SKIP', detail: 'No browser history return observed yet.' };
var sidebar = document.querySelector('.app-sidebar-menu');
var backdrop = document.querySelector('.admin-sidebar-backdrop');
var toggle = document.querySelector('.button-toggle-menu');
var content = document.querySelector('.content-page');
var marker = document.getElementById('fixture-marker');
var report = document.getElementById('fixture-report');
function wait(ms) { return new Promise(function (resolve) { setTimeout(resolve, ms); }); }
function record(name, pass, detail) {
results.push({ name: name, status: pass ? 'PASS' : 'FAIL', detail: detail || '' });
snapshot();
}
function rect(element) {
var value = element.getBoundingClientRect();
return { top: value.top, bottom: value.bottom, left: value.left, right: value.right, height: value.height };
}
function snapshot() {
var viewport = window.visualViewport;
var sidebarRect = rect(sidebar);
var backdropRect = rect(backdrop);
var backdropStyle = getComputedStyle(backdrop);
var visible = backdropStyle.display !== 'none' && backdropStyle.visibility !== 'hidden';
var expectedBottom = Math.max(window.innerHeight, document.documentElement.clientHeight,
viewport ? viewport.offsetTop + viewport.height : 0);
var state = {
page: window.location.pathname,
viewport: { width: window.innerWidth, height: window.innerHeight, documentHeight: document.documentElement.clientHeight,
visualHeight: viewport ? viewport.height : null, visualOffsetTop: viewport ? viewport.offsetTop : null },
pageScroll: { x: window.scrollX, y: window.scrollY },
menuVisible: visible && sidebarRect.right > 1,
contentVisible: getComputedStyle(content).visibility === 'visible' && getComputedStyle(content).display !== 'none',
sidebar: sidebarRect,
backdrop: backdropRect,
sidebarScroll: { top: sidebar.scrollTop, maximum: sidebar.scrollHeight - sidebar.clientHeight },
coversVisibleBottom: visible ? sidebarRect.bottom >= expectedBottom - 1 && backdropRect.bottom >= expectedBottom - 1 : null,
bfcache: bfcache,
historyReturn: historyReturn,
checks: results
};
report.textContent = JSON.stringify(state, null, 2);
var failed = bfcache.status === 'FAIL' || historyReturn.status === 'FAIL' || results.some(function (item) { return item.status === 'FAIL'; });
var checked = results.length > 0 || historyReturn.status === 'PASS';
report.dataset.status = failed ? 'FAIL' : checked ? 'PASS' : 'READY';
return state;
}
async function openAtScroll() {
if (snapshot().menuVisible) {
backdrop.click();
await wait(260);
}
window.scrollTo({ left: 0, top: 600, behavior: 'instant' });
await wait(100);
var saved = { y: window.scrollY, markerTop: marker.getBoundingClientRect().top };
expectedReturnScroll = saved.y;
try { sessionStorage.setItem(expectedScrollKey, String(saved.y)); } catch (error) {}
toggle.click();
await wait(280);
return saved;
}
async function runChecks() {
if (running) return;
if (window.innerWidth >= 992) {
record('Mobile viewport', false, 'Resize the viewport below 992 CSS pixels first.');
return;
}
running = true;
results = [];
try {
var saved = await openAtScroll();
var state = snapshot();
record('Open from page scroll 600 without visual jump', Math.abs(saved.y - 600) <= 1 && Math.abs(marker.getBoundingClientRect().top - saved.markerTop) <= 1);
record('Sidebar and backdrop cover visible bottom', state.coversVisibleBottom === true);
record('Underlying content is still rendered', state.contentVisible);
window.scrollBy({ left: 0, top: 180, behavior: 'instant' });
await wait(100);
record('Background stays stationary while menu is open', Math.abs(marker.getBoundingClientRect().top - saved.markerTop) <= 1);
sidebar.scrollTop = sidebar.scrollHeight;
await wait(100);
var last = rect(document.getElementById('fixture-last-link'));
record('Last menu link is reachable', last.top >= -1 && last.bottom <= window.innerHeight + 1);
backdrop.click();
await wait(280);
state = snapshot();
record('Closing restores page scroll', Math.abs(window.scrollY - saved.y) <= 1, 'expected=' + saved.y + ', actual=' + window.scrollY);
record('Closing leaves visible content and no backdrop', state.contentVisible && !state.menuVisible);
window.scrollBy({ left: 0, top: 80, behavior: 'instant' });
await wait(100);
record('Page scroll works again after close', window.scrollY > saved.y + 60);
} catch (error) {
record('Fixture execution', false, String(error));
} finally {
running = false;
snapshot();
}
}
async function testNoContent() {
if (running || window.innerWidth >= 992) return;
running = true;
try {
var saved = await openAtScroll();
var originalUrl = window.location.href;
document.getElementById('fixture-204-link').click();
await wait(1200);
record('204 response retains rendered page', window.location.href === originalUrl && snapshot().contentVisible);
backdrop.click();
await wait(280);
var state = snapshot();
record('Navigation without a new document remains recoverable', !state.menuVisible && state.contentVisible && Math.abs(window.scrollY - saved.y) <= 1);
} catch (error) {
record('204 recovery fixture', false, String(error));
} finally {
running = false;
snapshot();
}
}
document.getElementById('fixture-run').addEventListener('click', runChecks);
document.getElementById('fixture-204').addEventListener('click', testNoContent);
document.getElementById('fixture-scrolled-open').addEventListener('click', openAtScroll);
document.getElementById('fixture-snapshot').addEventListener('click', snapshot);
document.getElementById('fixture-bottom').addEventListener('click', function () {
sidebar.scrollTop = sidebar.scrollHeight;
setTimeout(snapshot, 100);
});
window.addEventListener('resize', function () { setTimeout(snapshot, 300); });
window.addEventListener('pageshow', function (event) {
var navigation = performance.getEntriesByType('navigation')[0];
if (!event.persisted && (!navigation || navigation.type !== 'back_forward')) {
snapshot();
return;
}
if (!event.persisted) {
bfcache = { status: 'SKIP', detail: 'Browser history returned via a new document, not BFCache.' };
}
window.requestAnimationFrame(function () {
setTimeout(function () {
if (expectedReturnScroll === null) {
try {
var stored = sessionStorage.getItem(expectedScrollKey);
if (stored !== null && Number.isFinite(Number(stored)) && Number(stored) >= 0) {
expectedReturnScroll = Number(stored);
}
} catch (error) {}
}
var state = snapshot();
var visible = !state.menuVisible && state.contentVisible;
var restored = expectedReturnScroll !== null && Math.abs(window.scrollY - expectedReturnScroll) <= 1;
historyReturn = {
status: !visible ? 'FAIL' : expectedReturnScroll === null ? 'SKIP' : restored ? 'PASS' : 'FAIL',
detail: expectedReturnScroll === null ? 'Use Open menu at page scroll 600 before leaving to record the expected position.' : 'Real browser history return: page visible, menu closed, saved scroll restored.',
mechanism: event.persisted ? 'BFCache' : 'new-document',
expectedScrollY: expectedReturnScroll,
actualScrollY: window.scrollY
};
if (event.persisted) {
bfcache = {
status: historyReturn.status,
detail: 'Real pageshow.persisted=true restoration; see historyReturn for the scroll check.'
};
}
snapshot();
}, 100);
});
});
window.sidebarFixture = { snapshot: snapshot, runChecks: runChecks, testNoContent: testNoContent, openAtScroll: openAtScroll };
snapshot();
})();
</script>
</body></html>"""
return (
document.replace("__LABEL__", label)
.replace("__PATH__", html.escape(path, quote=True))
.replace("__MENU_ROWS__", menu_rows)
.replace("__CARDS__", cards)
.replace("__REAL_SCRIPT__", sidebar_script())
.encode("utf-8")
)
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
path = urlsplit(self.path).path
if path == "/no-content":
self.send_response(204)
self.end_headers()
return
if path == "/":
self.send_response(302)
self.send_header("Location", "/a")
self.end_headers()
return
if path in ASSETS:
content = ASSETS[path].read_bytes()
content_type = "text/css; charset=utf-8"
elif path in ("/a", "/b"):
if path == "/b":
time.sleep(0.8)
content = page(path)
content_type = "text/html; charset=utf-8"
else:
self.send_error(404)
return
self.send_response(200)
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(content)))
self.send_header("Cache-Control", "no-cache")
self.end_headers()
try:
self.wfile.write(content)
except (BrokenPipeError, ConnectionResetError):
pass
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--port", type=int, default=8766)
args = parser.parse_args()
server = ThreadingHTTPServer(("127.0.0.1", args.port), Handler)
print(f"Sidebar fixture: http://127.0.0.1:{args.port}/a", flush=True)
try:
server.serve_forever()
except KeyboardInterrupt:
pass
finally:
server.server_close()
if __name__ == "__main__":
main()