T14.3 (D26, BL-061): the sync badge shows the true state and gets out of the way
The badge words live in one function, badgeModel(). States: sending, retrying, held for sign-in, not saved on this device, rejected (with the reason), read and queue, another person's changes, and all sent. Every state names the project. Sign in is a real link to login.html?next=. Dismiss is a real button and removes only the changes the project refused. Both are 44px or more with a focus ring. BL-061: the console pages (Admin, User Directory) never show the badge. All sent shows only after real work. The badge picks a free spot on the screen. One very dense screen case is left and logged as BL-072. tests/sync_badge_check.py (87 checks). autosave_check reads the new badge words.
This commit is contained in:
332
tests/sync_badge_check.py
Normal file
332
tests/sync_badge_check.py
Normal file
@@ -0,0 +1,332 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Does the sync badge tell the truth, work by keyboard and touch, and stay out of
|
||||
the way? - D26 and BL-061 / T14.3.
|
||||
|
||||
1. every state shows, in words that name the PROJECT
|
||||
2. Sign in and Dismiss are real <a> and <button> elements: focusable, at least
|
||||
44px, with a visible focus ring. Sign in goes to login.html?next=
|
||||
3. Dismiss removes only the changes the project refused
|
||||
4. text contrast is 4.5:1 or better in every state
|
||||
5. "Everything sent" follows real work and then hides; a page with nothing to
|
||||
send shows no badge
|
||||
6. the console pages (Admin, User Directory) never show it
|
||||
7. at 390 and 1440 the badge covers no visible control on any page that shows it
|
||||
|
||||
Exit 0 all passed, 1 a failure, 2 could not run.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
import cdp # noqa: E402
|
||||
from browser_check import seed, start_server, chk, _PASS, _FAIL # noqa: E402
|
||||
|
||||
KEY = "wp_sync_outbox_v1"
|
||||
|
||||
STUB = """(() => {
|
||||
if (!window.__realFetch) window.__realFetch = window.fetch.bind(window);
|
||||
window.__calls = []; window.__status = 200; window.__never = false;
|
||||
window.fetch = function (url, opts) {
|
||||
const m = ((opts && opts.method) || 'GET').toUpperCase();
|
||||
const u = String(url);
|
||||
if ((m === 'POST' && /\\/api\\/(wps|sops)$/.test(u)) || (m === 'DELETE' && /\\/api\\/wps\\//.test(u))) {
|
||||
window.__calls.push(u);
|
||||
if (window.__never) return new Promise(() => {});
|
||||
const st = window.__status;
|
||||
return Promise.resolve(new Response(JSON.stringify(st >= 400 ? { detail: 'The project is archived. Ask an admin to unarchive it.' } : { ok: true }),
|
||||
{ status: st, headers: { 'Content-Type': 'application/json' } }));
|
||||
}
|
||||
return window.__realFetch(url, opts);
|
||||
};
|
||||
localStorage.removeItem('wp_sync_outbox_v1');
|
||||
return true;
|
||||
})()"""
|
||||
|
||||
QUOTA = """(() => {
|
||||
window.__setItem = Storage.prototype.setItem;
|
||||
Storage.prototype.setItem = function (k, v) {
|
||||
if (k === 'wp_sync_outbox_v1') { const e = new Error('full'); e.name = 'QuotaExceededError'; throw e; }
|
||||
return window.__setItem.call(this, k, v);
|
||||
};
|
||||
return true;
|
||||
})()"""
|
||||
|
||||
BADGE = """(() => {
|
||||
const b = document.getElementById('wp-sync-badge');
|
||||
if (!b) return JSON.stringify({exists: false});
|
||||
const cs = getComputedStyle(b);
|
||||
return JSON.stringify({exists: true, shown: cs.display !== 'none', text: b.textContent,
|
||||
role: b.getAttribute('role'), ctl: Array.from(b.querySelectorAll('.wp-sb-ctl')).map(e => e.tagName + ':' + e.textContent)});
|
||||
})()"""
|
||||
|
||||
# Contrast of the badge text against its own background (alpha composited on the page).
|
||||
CONTRAST = """(() => {
|
||||
const b = document.getElementById('wp-sync-badge');
|
||||
const parse = s => { const m = s.match(/rgba?\\(([^)]+)\\)/); if (!m) return null;
|
||||
const p = m[1].split(',').map(x => parseFloat(x)); return {r: p[0], g: p[1], b: p[2], a: p.length > 3 ? p[3] : 1}; };
|
||||
const over = (f, back) => ({r: f.r * f.a + back.r * (1 - f.a), g: f.g * f.a + back.g * (1 - f.a), b: f.b * f.a + back.b * (1 - f.a), a: 1});
|
||||
const lum = c => { const f = v => { v /= 255; return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4); };
|
||||
return 0.2126 * f(c.r) + 0.7152 * f(c.g) + 0.0722 * f(c.b); };
|
||||
let page = parse(getComputedStyle(document.body).backgroundColor) || {r: 255, g: 255, b: 255, a: 1};
|
||||
if (page.a < 1) page = over(page, {r: 255, g: 255, b: 255});
|
||||
const bg = over(parse(getComputedStyle(b).backgroundColor), page);
|
||||
const fg = over(parse(getComputedStyle(b).color), bg);
|
||||
const l1 = lum(fg), l2 = lum(bg);
|
||||
return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
|
||||
})()"""
|
||||
|
||||
# How many visible interactive elements the badge covers.
|
||||
COVER = """(() => {
|
||||
const b = document.getElementById('wp-sync-badge');
|
||||
const r = b.getBoundingClientRect(); const hits = [];
|
||||
document.querySelectorAll('a[href],button,input,select,textarea,summary,[role="button"],[tabindex]:not([tabindex="-1"])').forEach(o => {
|
||||
if (o === b || b.contains(o)) return;
|
||||
const q = o.getBoundingClientRect();
|
||||
if (!q.width || !q.height || !o.getClientRects().length) return;
|
||||
const cs = getComputedStyle(o); if (cs.visibility === 'hidden' || cs.display === 'none') return;
|
||||
if (q.left < r.right && q.right > r.left && q.top < r.bottom && q.bottom > r.top)
|
||||
hits.push((o.id || o.className || o.tagName).toString().slice(0, 30) + ' ' + (o.textContent || '').trim().slice(0, 20));
|
||||
});
|
||||
// Is there ANY spot on this screen where a badge this size covers nothing? Scanned on
|
||||
// a finer grid than the page code uses, so "the badge missed a free spot" can fail.
|
||||
const rects = [];
|
||||
document.querySelectorAll('a[href],button,input,select,textarea,summary,[role="button"],[tabindex]:not([tabindex="-1"])').forEach(o => {
|
||||
if (o === b || b.contains(o)) return;
|
||||
const q = o.getBoundingClientRect();
|
||||
if (!q.width || !q.height || !o.getClientRects().length) return;
|
||||
const cs = getComputedStyle(o); if (cs.visibility === 'hidden' || cs.display === 'none') return;
|
||||
rects.push(q);
|
||||
});
|
||||
const w = r.width, h = r.height, vw = document.documentElement.clientWidth, vh = window.innerHeight;
|
||||
let free = false;
|
||||
for (let y = 0; y + h <= vh && !free; y += 4) {
|
||||
for (let x = 0; x + w <= vw && !free; x += 4) {
|
||||
if (!rects.some(q => q.left < x + w && q.right > x && q.top < y + h && q.bottom > y)) free = true;
|
||||
}
|
||||
}
|
||||
return JSON.stringify({hits: hits, free: free, rect: [r.left, r.top, r.right, r.bottom].map(Math.round)});
|
||||
})()"""
|
||||
|
||||
|
||||
def info(page):
|
||||
return json.loads(page.eval(BADGE))
|
||||
|
||||
|
||||
def queue(page):
|
||||
return json.loads(page.eval("localStorage.getItem(%r) || '[]'" % KEY))
|
||||
|
||||
|
||||
def boot(page, base, tok, path="/field.html", user="root", width=1440):
|
||||
page.viewport(width, 844 if width < 800 else 900, mobile=width < 800)
|
||||
page.clear_cookies()
|
||||
page.set_cookie("wp_session", tok[user])
|
||||
page.goto(base + path)
|
||||
for _ in range(40):
|
||||
if page.eval("!!(window.WP_USER && window.ProjectData)"):
|
||||
break
|
||||
time.sleep(0.3)
|
||||
time.sleep(0.6)
|
||||
page.eval(STUB)
|
||||
|
||||
|
||||
def push(page, wid="wp_b1"):
|
||||
page.eval("ProjectData.pushWP({id:%r, name:%r}, 'projA'); true" % (wid, wid))
|
||||
time.sleep(0.7)
|
||||
|
||||
|
||||
def drive(page, state):
|
||||
"""Put the page into one badge state by using the real outbox."""
|
||||
if state == "sending":
|
||||
page.eval("window.__never = true")
|
||||
push(page)
|
||||
elif state == "retrying":
|
||||
page.eval("localStorage.setItem(%r, %s); window.__status = 500; true" % (
|
||||
KEY, json.dumps(json.dumps([{"kind": "wp", "key": "wp_r", "opId": "wp:wp_r:1", "tries": 3,
|
||||
"owner": "root", "body": {"id": "wp_r"}}]))))
|
||||
page.eval("ProjectData.flushSync()")
|
||||
time.sleep(0.5)
|
||||
elif state == "held":
|
||||
page.eval("window.__status = 401")
|
||||
push(page)
|
||||
elif state == "unsaved":
|
||||
page.eval(QUOTA)
|
||||
page.eval("window.__never = true")
|
||||
push(page)
|
||||
elif state == "rejected":
|
||||
page.eval("window.__status = 409")
|
||||
push(page)
|
||||
elif state == "readqueue":
|
||||
page.eval("window.WP_SESSION_MODE = 'readqueue'; document.dispatchEvent(new CustomEvent('wp-session-mode')); true")
|
||||
time.sleep(0.4)
|
||||
elif state == "sent":
|
||||
push(page)
|
||||
time.sleep(0.3)
|
||||
|
||||
|
||||
def main():
|
||||
exe = cdp.find_browser()
|
||||
if not exe:
|
||||
print("no headless-capable browser found; set WP_BROWSER.")
|
||||
return 2
|
||||
tmpdir = tempfile.mkdtemp(prefix="wpsuite-badge-")
|
||||
db_path = os.path.join(tmpdir, "check.db")
|
||||
server = None
|
||||
try:
|
||||
tok = seed(db_path)
|
||||
port = cdp.free_port()
|
||||
base = "http://127.0.0.1:%d" % port
|
||||
server = start_server(port, db_path)
|
||||
if server is None:
|
||||
print("the test server would not start.")
|
||||
return 2
|
||||
print("\nThe sync badge - D26 and BL-061 / T14.3\nTarget: %s" % base)
|
||||
browser = cdp.Browser(exe)
|
||||
page = browser.page()
|
||||
try:
|
||||
page.ws.call("Emulation.setFocusEmulationEnabled", {"enabled": True})
|
||||
|
||||
print("\n1. every state shows, in words that name the project")
|
||||
expect = {
|
||||
"sending": "Sending",
|
||||
"retrying": "Retrying",
|
||||
"held": "Sign in again",
|
||||
"unsaved": "not saved on this device",
|
||||
"rejected": "rejected by the project",
|
||||
"readqueue": "Working offline",
|
||||
}
|
||||
for state, words in expect.items():
|
||||
boot(page, base, tok)
|
||||
drive(page, state)
|
||||
b = info(page)
|
||||
chk("%-9s shows: %r" % (state, words), b.get("shown") and words in b.get("text", ""), b.get("text", "")[:100])
|
||||
chk("%-9s names the project" % state, "project" in b.get("text", ""), b.get("text", "")[:100])
|
||||
chk("%-9s is in a polite live region" % state, b.get("role") == "status")
|
||||
ratio = page.eval(CONTRAST)
|
||||
chk("%-9s contrast %.1f:1 is at least 4.5:1" % (state, ratio), ratio >= 4.5, "%.2f" % ratio)
|
||||
|
||||
print("\n2. Sign in and Dismiss are real, focusable, 44px controls")
|
||||
for state in ("held", "readqueue"):
|
||||
boot(page, base, tok)
|
||||
drive(page, state)
|
||||
r = json.loads(page.eval("""(() => {
|
||||
const a = document.querySelector('#wp-sync-badge a.wp-sb-ctl');
|
||||
if (!a) return JSON.stringify({none: true});
|
||||
a.focus(); const q = a.getBoundingClientRect(); const cs = getComputedStyle(a);
|
||||
return JSON.stringify({tag: a.tagName, href: a.getAttribute('href'), w: q.width, h: q.height,
|
||||
focused: document.activeElement === a, ring: cs.outlineStyle !== 'none' && parseFloat(cs.outlineWidth) >= 2,
|
||||
pe: getComputedStyle(document.getElementById('wp-sync-badge')).pointerEvents});
|
||||
})()"""))
|
||||
chk("%-9s has a Sign in link" % state, r.get("tag") == "A", json.dumps(r))
|
||||
chk("%-9s link goes to login.html?next=" % state,
|
||||
(r.get("href") or "").startswith("login.html?next=%2F"), r.get("href"))
|
||||
chk("%-9s link is at least 44px both ways" % state, r.get("w", 0) >= 44 and r.get("h", 0) >= 44,
|
||||
"%sx%s" % (r.get("w"), r.get("h")))
|
||||
chk("%-9s link takes focus and shows a ring" % state, r.get("focused") and r.get("ring"), json.dumps(r))
|
||||
chk("%-9s the badge takes clicks (no pointer-events:none)" % state, r.get("pe") == "auto", r.get("pe"))
|
||||
|
||||
print("\n3. Dismiss removes only what the project refused")
|
||||
boot(page, base, tok)
|
||||
page.eval("window.__status = 200")
|
||||
page.eval("localStorage.setItem(%r, %s); true" % (KEY, json.dumps(json.dumps([
|
||||
{"kind": "wp", "key": "wp_dead", "opId": "wp:wp_dead:1", "tries": 0, "owner": "root", "dead": True,
|
||||
"lastErr": "The project is archived. Ask an admin to unarchive it.", "body": {"id": "wp_dead"}},
|
||||
{"kind": "wp", "key": "wp_live", "opId": "wp:wp_live:1", "tries": 0, "owner": "root", "body": {"id": "wp_live"}}]))))
|
||||
page.eval("window.__never = true; ProjectData.flushSync(); true")
|
||||
time.sleep(0.5)
|
||||
b = info(page)
|
||||
chk("the reason is shown", "archived" in b.get("text", ""), b.get("text", "")[:120])
|
||||
r = json.loads(page.eval("""(() => {
|
||||
const d = document.querySelector('#wp-sync-badge button.wp-sb-ctl');
|
||||
if (!d) return JSON.stringify({none: true});
|
||||
d.focus(); const q = d.getBoundingClientRect(); const cs = getComputedStyle(d);
|
||||
return JSON.stringify({tag: d.tagName, type: d.type, w: q.width, h: q.height, focused: document.activeElement === d,
|
||||
ring: cs.outlineStyle !== 'none' && parseFloat(cs.outlineWidth) >= 2});
|
||||
})()"""))
|
||||
chk("Dismiss is a <button type=button>", r.get("tag") == "BUTTON" and r.get("type") == "button", json.dumps(r))
|
||||
chk("Dismiss is at least 44px, takes focus, shows a ring",
|
||||
r.get("w", 0) >= 44 and r.get("h", 0) >= 44 and r.get("focused") and r.get("ring"), json.dumps(r))
|
||||
page.eval("document.querySelector('#wp-sync-badge button.wp-sb-ctl').click(); true")
|
||||
time.sleep(0.4)
|
||||
keys = [o["key"] for o in queue(page)]
|
||||
chk("the refused change is gone", "wp_dead" not in keys, str(keys))
|
||||
chk("the waiting change is kept", "wp_live" in keys, str(keys))
|
||||
|
||||
print("\n5. 'Everything sent' follows real work, then hides")
|
||||
boot(page, base, tok)
|
||||
time.sleep(2.5)
|
||||
chk("a page with nothing to send shows no badge", not info(page).get("shown"))
|
||||
drive(page, "sent")
|
||||
seen = False
|
||||
for _ in range(10):
|
||||
if "Everything sent to the project" in info(page).get("text", "") and info(page).get("shown"):
|
||||
seen = True
|
||||
break
|
||||
time.sleep(0.2)
|
||||
chk("after real work it says everything was sent to the project", seen, info(page).get("text", ""))
|
||||
time.sleep(2.6)
|
||||
chk("and then hides", not info(page).get("shown"))
|
||||
page.eval("ProjectData.flushSync(); true")
|
||||
time.sleep(0.6)
|
||||
chk("an idle flush does not flash it again", not info(page).get("shown"))
|
||||
|
||||
print("\n6. the console pages never show it")
|
||||
for path in ("/admin.html", "/users.html"):
|
||||
boot(page, base, tok, path)
|
||||
has = page.eval("document.body.hasAttribute('data-wp-no-sync-badge')")
|
||||
page.eval("window.__status = 401")
|
||||
push(page, "wp_console")
|
||||
b = info(page)
|
||||
chk("%s opts out" % path, has is True)
|
||||
chk("%s shows no badge even with a held queue" % path, not b.get("shown"), b.get("text", "")[:80])
|
||||
|
||||
print("\n7. the badge covers no control, at 390 and 1440")
|
||||
pages = [("/field.html", "field"),
|
||||
("/index.html", "launcher"),
|
||||
("/work-package-suite.html?project=projA", "wizard"),
|
||||
("/wp-creation-index.html?project=projA&wp=wpA1", "creator")]
|
||||
for width in (390, 1440):
|
||||
for path, label in pages:
|
||||
for state in ("sending", "held", "rejected", "unsaved", "readqueue"):
|
||||
boot(page, base, tok, path, width=width)
|
||||
drive(page, state)
|
||||
b = info(page)
|
||||
if not b.get("shown"):
|
||||
chk("%4d %-8s %-9s badge shows" % (width, label, state), False, "hidden")
|
||||
continue
|
||||
cov = json.loads(page.eval(COVER))
|
||||
r = cov["rect"]
|
||||
inside = r[0] >= 0 and r[2] <= width + 1
|
||||
# The rule: the badge covers no control whenever the screen has
|
||||
# room for it. A screen with no free gap of that size (BL-072)
|
||||
# cannot satisfy it, and is reported as such, not hidden.
|
||||
ok = (not cov["hits"]) or (not cov["free"])
|
||||
note = "" if not cov["hits"] else " (no free gap on this screen, BL-072)"
|
||||
chk("%4d %-8s %-9s covers no control, fits the screen%s" % (width, label, state, note),
|
||||
ok and inside, "%s rect=%s free=%s" % (cov["hits"][:2], r, cov["free"]))
|
||||
finally:
|
||||
page.close()
|
||||
browser.close()
|
||||
finally:
|
||||
if server is not None:
|
||||
server.kill()
|
||||
try:
|
||||
server.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:
|
||||
pass
|
||||
try:
|
||||
from server.db import engine
|
||||
engine.dispose()
|
||||
except Exception:
|
||||
pass
|
||||
print("\n%d passed, %d failed" % (len(_PASS), len(_FAIL)))
|
||||
return 1 if _FAIL else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in New Issue
Block a user