From bb6300683364b62fb55405f9af3c3406a8a70dae Mon Sep 17 00:00:00 2001 From: Eric Pheterson <151483+epheterson@users.noreply.github.com> Date: Mon, 23 Nov 2026 01:49:17 -0800 Subject: [PATCH] Home, Library and Settings in the browser Co-Authored-By: Claude Fable 5.2 --- tests/hit_area.py | 189 +++ tests/hit_probe.js | 42 + tests/test_addons_row_browser.py | 171 ++ tests/test_books_page.cjs | 8 +- tests/test_card_foot_stack_browser.py | 51 + tests/test_catalog_community_card.py | 27 + .../test_catalog_community_corner_browser.py | 65 + tests/test_compact_tiles_live.py | 217 +++ tests/test_core_corners_browser.py | 318 ++++ tests/test_ctx_no_auto_update_item.py | 12 + tests/test_design_tokens.py | 156 ++ tests/test_did_you_mean_browser.py | 70 + tests/test_discover_card_width_browser.py | 33 + tests/test_first_run_setup_browser.py | 24 +- tests/test_folder_category_grouping.cjs | 3 + tests/test_hit_areas_browser.py | 142 ++ tests/test_home_apps_live.py | 69 +- tests/test_home_badge_browser.py | 156 ++ tests/test_home_boot_flash_live.py | 120 ++ tests/test_home_discover_live.py | 42 + tests/test_home_layout_live.py | 302 ++++ tests/test_home_more_menu.py | 297 ++++ tests/test_home_topbar_live.py | 46 + tests/test_i18n_split.py | 60 + tests/test_library_folders_ui.cjs | 2 +- tests/test_library_tidy.py | 416 +++++ tests/test_manage_files_sum.py | 17 + tests/test_manage_row_auto_update.cjs | 67 + tests/test_manage_split.py | 19 +- tests/test_mdwiki_flavor_editions.cjs | 1 + tests/test_open_zim_live_browser.py | 5 +- tests/test_phone_pass_1150.cjs | 13 +- tests/test_phone_polish_live.py | 26 +- tests/test_red_theme_browser.py | 12 + tests/test_scrollbars_hover_live.py | 101 ++ tests/test_search_chips_live.py | 12 +- tests/test_section_label_browser.py | 94 ++ tests/test_settings_overflow_live.py | 8 +- tests/test_settings_polish_live.py | 7 +- ...t_settings_rows_scroll_sideways_browser.py | 40 + tests/test_settings_tabs.cjs | 4 +- tests/test_topbar_tap_live.py | 10 +- tests/test_touch_areas_live.py | 126 ++ tests/test_tube_surface.cjs | 6 +- tests/test_wiki.py | 10 + tests/test_zim_info_endpoint.py | 21 + tests/test_zimi_home_line_browser.py | 251 --- tests/visual_validation.spec.mjs | 3 - zimi/static/app.css | 1486 +++++++++-------- zimi/static/apps.css | 90 +- zimi/static/manage.js | 805 ++++++++- zimi/templates/index.html | 57 +- 52 files changed, 5204 insertions(+), 1125 deletions(-) create mode 100644 tests/hit_area.py create mode 100644 tests/hit_probe.js create mode 100644 tests/test_addons_row_browser.py create mode 100644 tests/test_card_foot_stack_browser.py create mode 100644 tests/test_catalog_community_card.py create mode 100644 tests/test_catalog_community_corner_browser.py create mode 100644 tests/test_compact_tiles_live.py create mode 100644 tests/test_core_corners_browser.py create mode 100644 tests/test_ctx_no_auto_update_item.py create mode 100644 tests/test_design_tokens.py create mode 100644 tests/test_did_you_mean_browser.py create mode 100644 tests/test_discover_card_width_browser.py create mode 100644 tests/test_hit_areas_browser.py create mode 100644 tests/test_home_badge_browser.py create mode 100644 tests/test_home_boot_flash_live.py create mode 100644 tests/test_home_layout_live.py create mode 100644 tests/test_home_more_menu.py create mode 100644 tests/test_home_topbar_live.py create mode 100644 tests/test_i18n_split.py create mode 100644 tests/test_library_tidy.py create mode 100644 tests/test_manage_files_sum.py create mode 100644 tests/test_manage_row_auto_update.cjs create mode 100644 tests/test_scrollbars_hover_live.py create mode 100644 tests/test_section_label_browser.py create mode 100644 tests/test_settings_rows_scroll_sideways_browser.py create mode 100644 tests/test_touch_areas_live.py delete mode 100644 tests/test_zimi_home_line_browser.py diff --git a/tests/hit_area.py b/tests/hit_area.py new file mode 100644 index 000000000..2464d7661 --- /dev/null +++ b/tests/hit_area.py @@ -0,0 +1,189 @@ +"""How big a finger's target really is, measured the way a finger meets it. + +Every clickable thing on a touch screen must give a finger at least 44 x 44 CSS px. What counts is not the drawn box but +the box that `elementFromPoint` hands the finger: padding, a negative margin and a transparent ::after all count, and a +neighbour painted over the edge takes it away. So the page is sampled on a grid and each point is given to the clickable +thing under it; the extent of each thing's points is its hit area. + +`undersized(page)` returns one line for each kind of control under 44 on either axis; a test asserts the list is empty +(less the ones it names as waiting for a layout change). +""" + +import json + +MIN_PX = 44 +# A hit area a pixel or two short is the sampling's edge, not a short control. +SLACK_PX = 1 +COARSE_STEP_PX = 4 +REACH_PX = 8 + +CLICKABLE = ( + "a[href],button,input:not([type=hidden]),select,textarea,summary,label[for],label:has(input,select,textarea),[role=button],[role=tab]," + '[role=menuitem],[role=switch],[role=checkbox],[role=radio],[onclick],[tabindex]:not([tabindex="-1"]),[data-act],[data-action]' +) + +_JS = r""" +(o) => { + const SEL = o.sel, vw = innerWidth, vh = innerHeight, step = o.step, reach = o.reach; + const root = o.scroller ? document.querySelector(o.scroller) : document.scrollingElement; + const top = () => (o.scroller ? root.scrollTop : scrollY); + const goTo = (y) => { if (o.scroller) root.scrollTop = y; else scrollTo(0, y); }; + const memo = (fn) => { const m = new WeakMap(); return (e) => { let v = m.get(e); if (v === undefined) { v = fn(e); m.set(e, v); } return v; }; }; + const pointer = memo((e) => getComputedStyle(e).cursor === 'pointer'); + const fixedUp = memo((e) => { const p = getComputedStyle(e).position; return p === 'fixed' || p === 'sticky'; }); + const fixedish = (e) => { for (let n = e; n && n !== document.documentElement; n = n.parentElement) if (fixedUp(n)) return true; return false; }; + // The clickable thing a point belongs to: a control, one of the extra selectors (the outermost), or a pointer cursor's owner. + const owner = (h) => { + const t = h.closest(SEL); + if (t) return t; + if (o.extra) { + let x = h.closest(o.extra), y; + if (x) { while (x.parentElement && (y = x.parentElement.closest(o.extra))) x = y; return x; } + } + if (!pointer(h)) return null; + let e = h; + while (e.parentElement && pointer(e.parentElement)) e = e.parentElement; + return e; + }; + // Where the scroller's list shows from: under whatever sticks at its top (a pinned head). + const under = () => Math.max(root ? root.getBoundingClientRect().top : 0, ...Array.from(root ? root.children : []).filter((c) => getComputedStyle(c).position === 'sticky').map((c) => c.getBoundingClientRect().bottom)); + // Part of the control is out of sight above or below, behind the edge of what holds it (the screen, or a sheet that scrolls). + const EDGE = 12; // a box reaches up to 11px past a control: one this near an edge has its box cut by it + const heightCut = (t) => { + const r = t.getBoundingClientRect(); + if (r.top < EDGE || r.bottom > vh - EDGE) return true; + for (let a = t.parentElement; a && a !== document.documentElement; a = a.parentElement) { + if (getComputedStyle(a).overflowY === 'visible') continue; + const c = a.getBoundingClientRect(); + if (r.top < c.top + EDGE || r.bottom > c.bottom - EDGE) return true; + } + if (!o.scroller || !root.contains(t)) return false; + // A row partly under what sticks at the scroller's top, or under something laid over its foot, is seen whole at another scroll position. + const x = Math.min(Math.max((r.left + r.right) / 2, 0), vw - 1), at = (y) => { const h = document.elementFromPoint(x, Math.min(Math.max(y, 0), vh - 1)); return !!h && owner(h) === t; }; + return r.top < under() || !at(r.top + 2) || !at(r.bottom - 2); + }; + const found = new Map(); + const sample = () => { + const sx = scrollX, sy = top(), seen = new Map(); + for (let y = 1; y < vh; y += step) for (let x = 1; x < vw; x += step) { + const h = document.elementFromPoint(x, y), t = h && owner(h); + if (!t) continue; + const f = seen.get(t); + if (!f) seen.set(t, { l: x, r: x, t: y, b: y }); + else { f.l = Math.min(f.l, x); f.r = Math.max(f.r, x); f.t = Math.min(f.t, y); f.b = Math.max(f.b, y); } + } + for (const [t, f] of seen) { + if (heightCut(t)) continue; // straddling an edge it scrolls under: seen whole at another scroll position + const hit = (x, y) => { if (x < 0 || y < 0 || x >= vw || y >= vh) return false; const h = document.elementFromPoint(x, y); return !!h && owner(h) === t; }; + const row = (y, a, z) => { for (let x = a; x <= z; x++) if (hit(x, y)) return true; return false; }; + const col = (x, a, z) => { for (let y = a; y <= z; y++) if (hit(x, y)) return true; return false; }; + let { l, r, t: tp, b } = f; + for (let g = 0; g < reach && col(l - 1, tp, b); g++) l--; + for (let g = 0; g < reach && col(r + 1, tp, b); g++) r++; + for (let g = 0; g < reach && row(tp - 1, l, r); g++) tp--; + for (let g = 0; g < reach && row(b + 1, l, r); g++) b++; + let e = found.get(t); + if (fixedish(t)) { // a fixed bar keeps its place as the page scrolls: keep its biggest sighting + const w = r - l + 1, hh = b - tp + 1; + if (!e) found.set(t, { fixed: true, w, h: hh }); + else { e.w = Math.max(e.w, w); e.h = Math.max(e.h, hh); } + continue; + } + const inside = !o.scroller || root.contains(t); + const nb = { l: l + (inside ? sx : 0), r: r + (inside ? sx : 0), t: tp + (inside && o.scroller ? sy : o.scroller ? 0 : sy), b: b + (inside && o.scroller ? sy : o.scroller ? 0 : sy) }; + if (!e) found.set(t, nb); + else { e.l = Math.min(e.l, nb.l); e.r = Math.max(e.r, nb.r); e.t = Math.min(e.t, nb.t); e.b = Math.max(e.b, nb.b); } + } + }; + const view = o.scroller ? root.clientHeight : vh; + const maxY = o.noscroll ? 0 : Math.max(0, root.scrollHeight - view); + const lip = o.scroller ? under() - root.getBoundingClientRect().top : 0; // a pinned head covers the first of each page + for (let y = 0; ; y += view - 40 - lip) { goTo(Math.min(y, maxY)); sample(); if (y >= maxY) break; } + goTo(0); + const sig = (e) => { + const c = (typeof e.className === 'string' ? e.className : '').trim().split(/\s+/).filter(Boolean).slice(0, 3).join('.'); + return e.tagName.toLowerCase() + (e.id ? '#' + e.id : '') + (c ? '.' + c : ''); + }; + const out = []; + for (const [e, f] of found) { + // A canvas's targets are drawn (their reach is in the code); a radio or box inside its label is the label's. + if (e.tagName === 'CANVAS' || (e.tagName === 'INPUT' && e.closest('label')) || e.closest(o.skip || ':not(*)')) continue; + // A control the screen's edge cuts (the end of a row that scrolls sideways) is measured only where it shows: its width is not short. + const edge = e.getBoundingClientRect(), cut = edge.right > vw + 1 || edge.left < -1; + const w = cut ? 1e4 : f.fixed ? f.w : f.r - f.l + 1, h = f.fixed ? f.h : f.b - f.t + 1; + out.push({ sig: sig(e), label: (e.getAttribute('aria-label') || e.title || e.textContent || e.value || '').trim().replace(/\s+/g, ' ').slice(0, 24), w, h }); + } + return out; +}; +""" + + +def measure(page, scroller=None, extra=None, skip=None, noscroll=False): + """Every clickable thing the finger can reach, with the size of the box it gets: [{sig, label, w, h}].""" + return page.evaluate( + _JS.strip().rstrip(";"), + dict( + sel=CLICKABLE, + step=COARSE_STEP_PX, + reach=REACH_PX, + scroller=scroller, + extra=extra, + skip=skip, + noscroll=noscroll, + ), + ) + + +def undersized(page, ignore=(), **kw): + """One line per kind of control (its selector) whose hit area is under 44 on either axis, the smallest seen. + + `ignore` is a tuple of substrings of that selector: kinds that wait for a layout change and say so where they are listed. + """ + kinds = {} + for it in measure(page, **kw): + if it["w"] >= MIN_PX - SLACK_PX and it["h"] >= MIN_PX - SLACK_PX: + continue + if any(i in it["sig"] for i in ignore): + continue + k = kinds.setdefault(it["sig"], dict(it, n=0)) + k["n"] += 1 + k["w"], k["h"] = min(k["w"], it["w"]), min(k["h"], it["h"]) + return [ + "%s %dx%d (x%d) %r" % (k["sig"], k["w"], k["h"], k["n"], k["label"]) + for k in sorted(kinds.values(), key=lambda x: x["sig"]) + ] + + +__all__ = ["measure", "undersized", "MIN_PX", "json"] + + +TOP_BAND = 0.3 # the top of the 3D view, as a share of its height +_TOP_BOXES = """(band) => { + var view = document.getElementById('ae-view'), vr = view.getBoundingClientRect(), out = [], els = []; + var sel = '#ae-view button, #ae-view .ae-stand-text, #ae-view .as-cap, #ae-view .alm-ck-l, #ae-view .alm-spd, #ae-view .as-speed'; + Array.prototype.forEach.call(document.querySelectorAll(sel), function (e) { + var cs = getComputedStyle(e), r = e.getBoundingClientRect(); + if (cs.display === 'none' || cs.visibility === 'hidden' || +cs.opacity < 0.1 || r.width < 2 || r.height < 2) return; + for (var p = e.parentElement; p && p !== view; p = p.parentElement) { var ps = getComputedStyle(p); if (ps.display === 'none' || ps.visibility === 'hidden' || +ps.opacity < 0.1) return; } + if (r.top - vr.top > band * vr.height || r.bottom < vr.top) return; + var cl = r.left, ct = r.top, cr = r.right, cb = r.bottom; + for (var a = e.parentElement; a && a !== view; a = a.parentElement) { var as = getComputedStyle(a); if (as.overflowX !== 'visible' || as.overflowY !== 'visible') { var ar = a.getBoundingClientRect(); if (r.bottom <= ar.top || r.top >= ar.bottom || r.right <= ar.left || r.left >= ar.right) return; cl = Math.max(cl, ar.left); ct = Math.max(ct, ar.top); cr = Math.min(cr, ar.right); cb = Math.min(cb, ar.bottom); } } // clipped to its own scrolling box: what shows + out.push({ name: e.id || e.className || e.tagName, l: cl, t: ct, r: cr, b: cb }); + els.push(e); + }); + out.forEach(function (o, i) { o.in = []; els.forEach(function (p, j) { if (j !== i && p.contains(els[i])) o.in.push(j); }); }); // a part inside another is not a crossing + return out; +}""" + + +def top_overlaps(page, band=TOP_BAND, slack=1): + """Pairs of controls along the top of the 3D view whose boxes cross: one top for each mode, nothing drawn over anything.""" + boxes = page.evaluate(_TOP_BOXES, band) + bad = [] + for i, a in enumerate(boxes): + for j, b in enumerate(boxes[i + 1 :], i + 1): + if j in a["in"] or i in b["in"]: + continue + if min(a["r"], b["r"]) - max(a["l"], b["l"]) > slack and min(a["b"], b["b"]) - max(a["t"], b["t"]) > slack: + bad.append("%s x %s" % (a["name"], b["name"])) + return bad diff --git a/tests/hit_probe.js b/tests/hit_probe.js new file mode 100644 index 000000000..018f39ba3 --- /dev/null +++ b/tests/hit_probe.js @@ -0,0 +1,42 @@ +// Hit areas at a phone's width: for each control on the screen, the box where a tap lands on it (probed with +// elementFromPoint, so a ::after hit box counts) and how many are under 44x44 (the 3px sampling step is the tolerance). Used by tests/test_touch_areas_live.py. +() => { + const MIN = 44, STEP = 3, REACH = 26; + const sel = 'button, a[href], [role=button], [role=tab], [role=menuitem], [role=switch], input:not([type=hidden]), select, textarea, summary, [onclick], [tabindex]:not([tabindex="-1"])'; + const seen = new Set(), out = []; + const vis = el => { const cs = getComputedStyle(el); if (cs.visibility === 'hidden' || cs.display === 'none' || +cs.opacity === 0 || cs.pointerEvents === 'none') return false; const r = el.getBoundingClientRect(); return r.width > 0 && r.height > 0; }; + const describe = el => (el.tagName.toLowerCase() + (el.id ? '#' + el.id : '') + (typeof el.className === 'string' && el.className ? '.' + el.className.trim().split(/\s+/).slice(0, 2).join('.') : '') + + ((el.getAttribute('aria-label') || el.textContent || '').trim().slice(0, 18) ? ' "' + (el.getAttribute('aria-label') || el.textContent).trim().replace(/\s+/g, ' ').slice(0, 18) + '"' : '')); + const els = Array.from(document.querySelectorAll(sel)); + for (const el of els) { + if (seen.has(el) || !vis(el)) continue; + seen.add(el); + // Inline links inside running text are exempt (WCAG 2.5.8 inline exception). + if (el.tagName === 'A' && getComputedStyle(el).display === 'inline' && el.parentElement && /^(P|LI|SPAN|DIV|TD)$/.test(el.parentElement.tagName) && el.parentElement.textContent.trim().length > el.textContent.trim().length + 12) continue; + const r = el.getBoundingClientRect(); + if (r.bottom < 0 || r.top > innerHeight || r.right < 0 || r.left > innerWidth) continue; + let x0 = 1e9, y0 = 1e9, x1 = -1e9, y1 = -1e9, hits = 0; + const L = Math.max(0, r.left - REACH), R = Math.min(innerWidth - 1, r.right + REACH), T = Math.max(0, r.top - REACH), B = Math.min(innerHeight - 1, r.bottom + REACH); + for (let y = T; y <= B; y += STEP) for (let x = L; x <= R; x += STEP) { + const h = document.elementFromPoint(x, y); + if (h && (h === el || el.contains(h))) { hits++; if (x < x0) x0 = x; if (x > x1) x1 = x; if (y < y0) y0 = y; if (y > y1) y1 = y; } + } + if (!hits) continue; // covered by something else: not reachable here + let w = x1 - x0 + STEP, h = y1 - y0 + STEP; + // The screen's edge cuts the probe, not the control: the 3px sampling can stop short of the edge, so a control that itself runs past it counts too + // (a row that scrolls shows the last tab half; how much shows depends on the font's widths). + if (x0 <= 1 || x1 >= innerWidth - 3 || r.left < 0 || r.right > innerWidth - 1) w = Math.max(w, MIN); + if (y0 <= 1 || y1 >= innerHeight - 3) h = Math.max(h, MIN); + out.push({ d: describe(el), w: Math.round(w), h: Math.round(h), drawn: [Math.round(r.width), Math.round(r.height)], at: [Math.round(r.left), Math.round(r.top)], + small: w < MIN - 3 || h < MIN - 3, rect: [x0, y0, x1 + STEP, y1 + STEP], el }); + } + // Overlap: two small controls whose hit boxes intersect. + const smalls = out.filter(o => o.small); + const overlaps = []; + for (let i = 0; i < out.length; i++) for (let j = i + 1; j < out.length; j++) { + const a = out[i].rect, b = out[j].rect; + const ix = Math.min(a[2], b[2]) - Math.max(a[0], b[0]), iy = Math.min(a[3], b[3]) - Math.max(a[1], b[1]); + if (ix > 3 && iy > 3 && !out[i].el.contains(out[j].el) && !out[j].el.contains(out[i].el)) overlaps.push([out[i].d, out[j].d]); + } + return { total: out.length, small: smalls.length, list: smalls.map(o => o.d + ' ' + o.w + 'x' + o.h + ' @' + o.at.join(',')), overlaps: overlaps.length, ov: overlaps.slice(0, 6) }; +} diff --git a/tests/test_addons_row_browser.py b/tests/test_addons_row_browser.py new file mode 100644 index 000000000..f42259c88 --- /dev/null +++ b/tests/test_addons_row_browser.py @@ -0,0 +1,171 @@ +"""Settings > Server > Add-ons row: every state is one row shape, and a second press cannot start a second install. + +/manage/addons is answered by the test (no add-on is fetched). Run: pytest tests/test_addons_row_browser.py -v +""" + +import json +import os +import sys +import threading + +import pytest + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.dirname(HERE)) +sys.path.insert(0, HERE) + +import zimi.server as srv # noqa: E402 +from conftest_zim import build_fixture_zim # noqa: E402 +from zimi import http # noqa: E402 + +PHONE = {"width": 390, "height": 844} + + +@pytest.fixture +def base(tmp_path, monkeypatch): + from http.server import ThreadingHTTPServer + + import zimi.renderer as renderer + + if not renderer.browser_available(): + pytest.skip("playwright + chromium are not usable here") + monkeypatch.setenv("ZIMI_OFFLINE", "1") + monkeypatch.setenv("ZIMI_TORRENT", "0") + zdir = tmp_path / "zims" + zdir.mkdir() + build_fixture_zim(str(zdir / "wikipedia_en_all_2026-10.zim")) + monkeypatch.setattr(srv, "ZIM_DIR", str(zdir)) + monkeypatch.setattr(srv, "ZIMI_DATA_DIR", str(tmp_path / "data")) + os.makedirs(str(tmp_path / "data"), exist_ok=True) + srv.load_cache(force=True) + httpd = ThreadingHTTPServer(("127.0.0.1", 0), http.ZimHandler) + threading.Thread(target=httpd.serve_forever, daemon=True).start() + yield "http://127.0.0.1:%d" % httpd.server_address[1] + httpd.shutdown() + + +def _row(key, **kw): + r = {"key": key, "size": 50_000_000, "ready": False, "own": False, "requires": []} + r.update(kw) + return r + + +class Fake: + """The add-ons endpoint: the rows are set by the test, installs are counted.""" + + def __init__(self, rows): + self.rows = rows + self.posts = [] + self.busy = False + + def status(self): + return { + "supported": True, + "mode": "ask", + "locked": False, + "env": "ZIMI_ADDONS", + "choices": ["ask", "auto", "never"], + "addons": self.rows, + "delegated": [], + } + + def handle(self, route): + req = route.request + if req.method == "POST": + body = json.loads(req.post_data or "{}") + self.posts.append(body) + if body.get("install"): + if self.busy: + return route.fulfill( + status=409, + content_type="application/json", + body='{"error":"busy"}', + ) + self.busy = True + for r in self.rows: + if r["key"] == body["install"]: + r["progress"] = { + "done": 10, + "total": 100, + "step": "", + "active": True, + "error": None, + } + route.fulfill( + status=200, content_type="application/json", body=json.dumps(self.status()) + ) + + +def _open(pw, base, fake, scheme="dark", viewport=PHONE): + br = pw.chromium.launch() + pg = br.new_context( + viewport=viewport, color_scheme=scheme, service_workers="block" + ).new_page() + pg.route("**/manage/addons", fake.handle) + pg.goto(base + "/") + pg.wait_for_selector("#q") + pg.evaluate( + "() => { var o = document.getElementById('setup-overlay'); if (o) o.remove(); }" + ) + pg.evaluate("() => enterManage(null, 'library')") + pg.wait_for_selector("#ms-addons", state="attached", timeout=30000) + pg.evaluate("() => { document.querySelector('.offline-fold').open = true; }") + return br, pg + + +def _paint(pg, **opts): + pg.evaluate( + "(o) => { _addonsOpts = Object.assign({host: 'ms-addons'}, o); return _renderAddons(_addonsOpts); }", + opts, + ) + + +def test_a_second_press_does_not_start_a_second_install(base): + from playwright.sync_api import sync_playwright + + fake = Fake([_row("video", own=True, ready=True), _row("browser")]) + with sync_playwright() as pw: + br, pg = _open(pw, base, fake) + _paint(pg, setup=True) + pg.wait_for_selector("#ms-addons [data-addon=browser] button") + # Two presses in the same tick, the way a double tap lands. + pg.evaluate( + "() => { var b = document.querySelector('[data-addon=browser] button'); b.click(); b.click(); _addonInstall('browser'); }" + ) + pg.wait_for_selector("[data-addon=browser][data-state=downloading]") + assert [p for p in fake.posts if p.get("install")] == [{"install": "browser"}] + br.close() + + +@pytest.mark.parametrize("scheme", ["dark", "light"]) +def test_every_state_is_the_same_row_shape(base, scheme): + from playwright.sync_api import sync_playwright + + live = {"done": 40, "total": 100, "step": "", "active": True, "error": None} + cases = { + "idle": _row("browser"), + "downloading": _row("browser", progress=dict(live)), + "installing": _row("browser", progress=dict(live, step="build")), + "cancelling": _row("browser", progress=dict(live, cancelling=True)), + "ready": _row("browser", own=True, ready=True), + "failed": _row( + "browser", progress=dict(live, active=False, error="OSError: x") + ), + } + heights = {} + with sync_playwright() as pw: + for state, row in cases.items(): + fake = Fake([row]) + br, pg = _open(pw, base, fake, scheme) + _paint(pg, setup=state != "ready") + pg.wait_for_selector("#ms-addons [data-addon=browser]") + assert pg.get_attribute("[data-addon=browser]", "data-state") == state + assert "addon_" not in pg.inner_text("#ms-addons") + heights[state] = pg.evaluate( + "() => document.querySelector('[data-addon=browser]').getBoundingClientRect().height" + ) + assert pg.evaluate( + "() => document.documentElement.scrollWidth <= innerWidth" + ) + br.close() + assert max(heights.values()) - min(heights.values()) <= 1, heights diff --git a/tests/test_books_page.cjs b/tests/test_books_page.cjs index f8baf4508..68d67b03e 100644 --- a/tests/test_books_page.cjs +++ b/tests/test_books_page.cjs @@ -162,7 +162,7 @@ ok('a Gutenberg page is known by its own record, an EPUB\'s chapters by theirs', ok('an EPUB\'s address, or a book of pages\' (zimi/bookpages.py), is a book\'s before it loads', /if \(m && \(\/\\\.epub\\\/\$\/i\.test\(m\[2\]\) \|\| m\[2\]\.indexOf\(_BOOK_PAGES_PREFIX\) === 0\)\) return true;/.test(src) && /var _BOOK_PAGES_PREFIX = '_zimi_book_\/';/.test(src)); ok('a book has no
: Reader View reads its body', /if \(!main && _isBookDoc\(doc\)\) main = doc\.body;/.test(src) && /return !!main && \(main !== doc\.body \|\| _isBookDoc\(doc\)\);/.test(src)); ok('a book keeps its contents list in Reader View', /_isBookDoc\(doc\) \? 'script,style,link,noscript' : _READER_VIEW_STRIP/.test(src)); -ok('a book opens in Reader View, and the e-reader is set up before anything measures it', /var _wantReader = _readerViewOn \|\| _readerAuto\(\) \|\| _bookDoc;/.test(src) && /if \(_bookDoc && _readerViewOn\) \{\n\s*try \{ _bookOn = _bookAttach\(frame\);/.test(src)); +ok('a book opens in Reader View, and the e-reader is set up before anything measures it', /var _wantReader = _readerViewOn \|\| _readerAuto\(\) \|\| _bookDoc \|\| _readerViewFromAddress;/.test(src) && /if \(_bookDoc && _readerViewOn\) \{\n\s*try \{ _bookOn = _bookAttach\(frame\);/.test(src)); ok('Zimi\'s header is held away for a book, known from its address before it loads', /var _bookLoading = _bookUrl\(url\);\n\s*_bookChrome\(_bookLoading\);/.test(src) && /var held = _bookReading \|\| _pdfReading;[\s\S]{0,400}_chromeImmersive\(held\);/.test(src)); // So is it for a PDF, from the viewer's address, and given back on close. ok('Zimi\'s header is held away while a PDF is read in Zimi\'s PDF reader', /_pdfChrome\(url\.startsWith\('\/static\/pdfjs\/'\)\);/.test(src) && /_pdfChrome\(_isPdfPage\(\)\);/.test(src) && /_bookChrome\(false\);\n\s*_pdfChrome\(false\);/.test(src)); @@ -209,7 +209,7 @@ ok('places are capped per app, the oldest dropped first (a Zimipedia article nev // ── the shell ─────────────────────────────────────────────────────────── ok('the tile is one line in the apps row, like the others', /function _booksTileHtml\(\) \{\n\s*return _appTileHtml\('books', t\('books'\), _BOOKS_SVG, _installedBookZims\(\)/.test(src) && /_APP_TILES = \{[^}\n]*\bbooks: _booksTileHtml[,} ]/.test(src)); ok('an app like the others: switched per server and per account by its name', /var APP_NAMES = \[[^\]]*'books'[^\]]*\];/.test(src)); -ok('it is the page Zimi owns, in the reader, at /#books', /_openHashApp\('books', replaceState, function\(\) \{ _booksOpen = true; return _BOOKS_PAGE \+ '#' \+ _booksStrings\(\); \}\)/.test(src) && /if \(location\.hash === '#books'\) \{ enterHome\(false\); openBooks\(true\); return; \}/.test(src)); +ok('it is the page Zimi owns, in the reader, at /#books (or /?books= once a list or book is open, so a reload lands there)', /_openHashApp\('books', replaceState, function\(\) \{ _booksOpen = true; return _BOOKS_PAGE \+ '#' \+ _booksStrings\(view\); \}\)/.test(src) && /if \(location\.hash === '#books'\) \{ enterHome\(false\); openBooks\(true\); return; \}/.test(src) && /if \(params\.get\('books'\)\) \{ enterHome\(false\); openBooks\(true, params\.get\('books'\)\); return; \}/.test(src) && /view \? '\/\?books=' \+ encodeURIComponent\(view\) : '\/#books'/.test(src)); ok('the shell hands the page its strings and the shelves\' names', /_appStrings\('books', \['books_shelf'/.test(src) && /lcc\[c\] = t\('books_lcc_' \+ c\);/.test(src)); ok('typing and Enter in the box search inside the page', /\(_isWikiPage\(\) \? _wikiSearch : _booksSearch\)\(val\)/.test(src) && /if \(_isBooksPage\(\)\) \{ _booksSearch\(q\.value\.trim\(\)\); return; \}/.test(src) && /_appFrameCall\('booksSearch', val\)/.test(src)); ok('the box says what it is for', /if \(_isBooksPage\(\)\) return t\('books_search_placeholder'\);/.test(src)); @@ -223,7 +223,7 @@ const need = ['books', 'books_view_unavailable', 'books_search_placeholder', 'bo 'books_left_none', 'books_position', 'app_empty_books', 'apps_count_books_one', 'apps_count_books_other', 'bg_books', 'books_bce', 'books_bce_ce']; const pageKeys = (extract(src, /_appStrings\('books', \[[\s\S]*?\]/, 'keys').match(/'books_[a-z_]+'/g) || []).map(k => k.slice(1, -1)); const lcc = JSON.parse(extract(src, /var _BOOKS_LCC = \[[\s\S]*?\];/, 'lcc').replace(/^var _BOOKS_LCC = /, '').replace(/;$/, '').replace(/'/g, '"')); -for (const lang of fs.readdirSync(path.join(root, 'i18n'))) { +for (const lang of fs.readdirSync(path.join(root, 'i18n')).filter(f => f.endsWith('.json'))) { const d = JSON.parse(fs.readFileSync(path.join(root, 'i18n', lang), 'utf8')); const missing = need.concat(pageKeys).concat(lcc.map(c => 'books_lcc_' + c)).filter(k => !d[k]); if (missing.length) ok('every string in ' + lang, false, missing.join(', ')); @@ -231,7 +231,7 @@ for (const lang of fs.readdirSync(path.join(root, 'i18n'))) { if (!/\{from\}/.test(d.books_bce) || !/\{to\}/.test(d.books_bce) || !/\{from\}[\s\S]*\{to\}/.test(d.books_bce_ce) || !/\{name\}/.test(d.books_more_by)) ok('the placeholders survive in ' + lang, false); if (Object.keys(d).filter(k => /^books|_books/.test(k)).some(k => /\u2014/.test(d[k]))) ok('no em dash in ' + lang, false); } -ok('the strings are in all ten languages', fs.readdirSync(path.join(root, 'i18n')).length === 10); +ok('the strings are in all ten languages', fs.readdirSync(path.join(root, 'i18n')).filter(f => f.endsWith('.json')).length === 10); // A finger on the reader's sheet and slider, and on any app's pill. ok('the reading sheet\'s choices, its close and the book\'s slider reach 44px on a finger', /@media \(pointer:coarse\)\{\.zb-seg button\{min-height:44px\}\.zb-x\{width:44px;height:44px\}\}/.test(src) && /@media \(pointer:coarse\)\{\.zb-scrub\{height:44px;/.test(src)); diff --git a/tests/test_card_foot_stack_browser.py b/tests/test_card_foot_stack_browser.py new file mode 100644 index 000000000..db7c1bf18 --- /dev/null +++ b/tests/test_card_foot_stack_browser.py @@ -0,0 +1,51 @@ +"""A wide row's marks (favorite, kept on this phone, whatever comes next) stack up its right edge with the one control, the +three dots, at the bottom. Tiles keep their foot as it was. + +Run: pytest tests/test_card_foot_stack_browser.py -v +""" + +import os +import sys + +import pytest + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +import zimi.renderer as renderer # noqa: E402 + +STATIC = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "zimi", "static") + +CARD = ("
W
Wikipedia
" + "
An encyclopedia
2 entries
" + "*kx" + "
") + + +def _boxes(width, grid_class): + from playwright.sync_api import sync_playwright + + css = "".join(open(os.path.join(STATIC, n), encoding="utf-8").read() for n in ("tokens.css", "app.css")) + with sync_playwright() as p: + b = p.chromium.launch() + page = b.new_context(viewport={"width": width, "height": 844}, is_mobile=True).new_page() + page.set_content("" + "
%s
" % (css, grid_class, CARD)) + out = page.evaluate("""() => { + const r = e => { const b = e.getBoundingClientRect(); return [b.right, b.top, b.bottom]; }; + return {marks: [...document.querySelectorAll('.card-marks > *')].map(r), more: r(document.querySelector('.card-more'))}; + }""") + b.close() + return out + + +@pytest.mark.local_gate +def test_marks_stack_in_a_column_above_the_dots_on_a_wide_row(): + pytest.importorskip("playwright") + if not renderer.browser_available(): + pytest.skip("playwright + chromium are not usable here") + o = _boxes(390, "stats-grid pick-grid") + lefts = {round(m[0]) for m in o["marks"]} # their right edges: the marks are glyphs of different widths, so only the edge they stack on is one line + tops = [m[1] for m in o["marks"]] + assert len(lefts) == 1, o # one column + assert tops == sorted(tops) and len(set(tops)) == 3, o # one under the other + assert o["more"][1] > o["marks"][-1][1], o # the dots (a 44px touch box) sit below the last mark diff --git a/tests/test_catalog_community_card.py b/tests/test_catalog_community_card.py new file mode 100644 index 000000000..c66d7d16f --- /dev/null +++ b/tests/test_catalog_community_card.py @@ -0,0 +1,27 @@ +"""Community catalog entries: no source filter, solid mark in the actions row (the subtitle: test_community_copy.py).""" +import pathlib +import re + +STATIC = pathlib.Path(__file__).resolve().parent.parent / "zimi" / "static" + + +def _read(name): + return (STATIC / name).read_text(encoding="utf-8") + + +def test_no_catalog_source_filter(): + manage, app = _read("manage.js"), _read("app.js") + for gone in ("_catalogSourceHtml", "_bySource", "setCatalogSource", "CATALOG_SOURCE"): + assert gone not in manage and gone not in app, gone + for f in (STATIC / "i18n").glob("*.json"): + assert "catalog_source_" not in f.read_text(encoding="utf-8"), f.name + + +def test_badge_is_solid_and_sits_in_the_actions_row(): + manage = _read("manage.js") + assert "'
' + iconHtml + '
'" in manage + assert "'
' + communityBadge" in manage + body = re.search(r"function communityIcon\(size\) \{.*?\n\}", _read("app.js"), re.S).group(0) + assert 'fill="currentColor"' in body and 'fill="none"' not in body + css = _read("app.css") + assert "position: absolute" not in re.search(r"\.community-corner \{[^}]*\}", css).group(0) diff --git a/tests/test_catalog_community_corner_browser.py b/tests/test_catalog_community_corner_browser.py new file mode 100644 index 000000000..5dd01bdeb --- /dev/null +++ b/tests/test_catalog_community_corner_browser.py @@ -0,0 +1,65 @@ +"""A community catalog card carries its mark as a glyph in the icon's corner, not as words in the subtitle. + +Run: pytest tests/test_catalog_community_corner_browser.py -v +""" + +import os +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.dirname(HERE)) +sys.path.insert(0, HERE) +from test_almanac_corners_browser import base # noqa: E402,F401 + +SHOT = os.environ.get("CORNER_SHOTS", "") + +_DRAW = """(src) => { + const it = { name: 'x', title: 'Some Book', summary: 'Made by someone', article_count: 12, size_bytes: 5e6, + source: src, download_url: 'https://e.org/x.zim' }; + const host = document.createElement('div'); + host.id = 'corner-host'; host.style.cssText = 'position:fixed;inset:0 auto auto 0;width:100%;z-index:99999;background:var(--bg)'; + host.innerHTML = '
' + renderCatalogItem(it) + '
'; + document.body.appendChild(host); + const card = host.querySelector('.catalog-item'), mark = card.querySelector('.community-corner'); + const sub = card.querySelector('.ci-meta').textContent; + const c = card.getBoundingClientRect(), m = mark && mark.getBoundingClientRect(); + return { has: !!mark, sub: sub, label: mark && mark.getAttribute('aria-label'), + right: m && c.right - m.right, top: m && m.top - c.top, inside: m && m.left >= c.left && m.bottom <= c.bottom, + in_actions: !!mark && !!mark.closest('.ci-actions'), clear: !!m && document.elementFromPoint(m.left + m.width / 2, m.top + m.height / 2) !== null && mark.contains(document.elementFromPoint(m.left + m.width / 2, m.top + m.height / 2)) }; +}""" + + +def _page(pw, base, width, theme): + br = pw.chromium.launch() + pg = br.new_context(viewport={"width": width, "height": 700}, service_workers="block").new_page() + pg.goto(base + "/") + pg.wait_for_function("() => typeof communityIcon === 'function'", timeout=60000) + pg.add_script_tag(url=base + "/static/manage.js") + pg.wait_for_function("() => typeof renderCatalogItem === 'function'", timeout=60000) + pg.evaluate("t => document.documentElement.setAttribute('data-theme', t)", theme) + return br, pg + + +def test_the_mark_sits_in_the_card_corner_and_not_in_the_subtitle(base): + from playwright.sync_api import sync_playwright + + with sync_playwright() as pw: + for width, theme in ((390, "dark"), (390, "light"), (1280, "dark")): + br, pg = _page(pw, base, width, theme) + got = pg.evaluate(_DRAW, "community") + if SHOT: + pg.screenshot(path=os.path.join(SHOT, "corner-%d-%s.png" % (width, theme))) + br.close() + assert got["has"] and got["inside"], got + assert got["sub"].find(got["label"]) < 0, "the subtitle no longer names it: %r" % got + assert got["in_actions"] and got["clear"], got # the actions row since a84498c8f + + +def test_a_kiwix_card_has_no_mark(base): + from playwright.sync_api import sync_playwright + + with sync_playwright() as pw: + br, pg = _page(pw, base, 390, "dark") + got = pg.evaluate(_DRAW, "kiwix") + br.close() + assert not got["has"], got diff --git a/tests/test_compact_tiles_live.py b/tests/test_compact_tiles_live.py new file mode 100644 index 000000000..a56c568fc --- /dev/null +++ b/tests/test_compact_tiles_live.py @@ -0,0 +1,217 @@ +"""Compact (tiles) library view: no text ever escapes a tile ("lots of text flowing out of the +tiles... bigger or two rows or I dunno but it's baaaad"). + +Long titles, long language names and a Zimi-made kind badge, at a phone, 1280 and 1600 px wide. + +Run: pytest tests/test_compact_tiles_live.py -v +Set ZIMI_SHOTS= to also write a screenshot per width. +""" + +import os +import sys +import time + +import pytest + +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 zimi.renderer as renderer # noqa: E402 +import zimi.server as srv # noqa: E402 +from test_home_apps_live import HOME # noqa: E402 +from test_home_layout_live import WIDTHS # noqa: E402 + +SHOTS = os.environ.get("ZIMI_SHOTS") + +# Real-ish names: the long ones are what break a tile. +TITLES = [ + ("wikipedia_en_all_maxi_2026-01.zim", "wikipedia_en_all_maxi", "Wikipedia (English, all maxi)", "eng"), + ("math.stackexchange.com_en_all_2026-01.zim", "math.stackexchange.com_en_all", "Stack Exchange: Mathematics", "eng"), + ("wikisource_nds_nl_2026-01.zim", "wikisource_nds_nl", "Wikisource in Nedersaksisch (Low Saxon, Netherlands)", "nds"), + ("wiktionary_zh_classical_2026-01.zim", "wiktionary_zh_classical", "Wiktionary Literary Chinese", "lzh"), + ("devdocs_en_react_2026-01.zim", "devdocs_en_react", "Supercalifragilisticexpialidocious-DocumentationBundle", "eng"), + ("lowtech_2026-01.zim", "lowtech", "Low-tech Magazine", "eng"), + ("water.zim", "water", "Water", "eng"), + ("khan_academy_es_2026-01.zim", "khan_academy_es", "Khan Academy en Español (todos los cursos de matemáticas)", "spa"), +] + +# Every text-bearing descendant of a tile, and where it sits against the tile. +OVERFLOW = r"""() => { + const rows = []; + const tiles = Array.from(document.querySelectorAll('#output .stats-grid.tiles:not(.apps-grid) > .stat-card')); + for (const tile of tiles) { + const tb = tile.getBoundingClientRect(); + const kids = Array.from(tile.querySelectorAll('*')).filter(el => el.offsetParent !== null && el.childNodes.length && + Array.from(el.childNodes).some(n => n.nodeType === 3 && n.textContent.trim())); + for (const el of kids) { + const r = document.createRange(); r.selectNodeContents(el); + const ev = el.getBoundingClientRect(); + // Text an element clips (overflow hidden, an ellipsis) shows only inside the element's own box. + const clips = getComputedStyle(el).overflow !== 'visible'; + const b = clips ? ev : r.getBoundingClientRect(); + const bad = b.left < tb.left - 0.5 || b.right > tb.right + 0.5 || b.bottom > tb.bottom + 0.5 || b.top < tb.top - 0.5 || + ev.right > tb.right + 0.5 || ev.left < tb.left - 0.5 || ev.bottom > tb.bottom + 0.5; + if (bad) rows.push({ tile: tile.dataset.zim, el: el.className || el.tagName, text: el.textContent.trim().slice(0, 40), + t: [tb.left, tb.top, tb.right, tb.bottom].map(Math.round), b: [b.left, b.top, b.right, b.bottom].map(Math.round) }); + } + } + // Tiles of one row share a height. + const byTop = {}; + for (const tile of tiles) { const b = tile.getBoundingClientRect(); (byTop[Math.round(b.top)] = byTop[Math.round(b.top)] || []).push(Math.round(b.height)); } + const uneven = Object.values(byTop).filter(h => Math.max(...h) - Math.min(...h) > 1); + const sw = document.documentElement.scrollWidth, vw = document.documentElement.clientWidth; + return { n: tiles.length, rows, uneven, sw, vw, heights: tiles.map(t => Math.round(t.getBoundingClientRect().height)) }; +}""" + + +@pytest.fixture(scope="module") +def served(tmp_path_factory): + if not renderer.browser_available(): + pytest.skip("playwright + chromium are not usable here") + from http.server import ThreadingHTTPServer + + from conftest_zim import build_fixture_zim + + from zimi.http import ZimHandler + + tmp = tmp_path_factory.mktemp("compacttiles") + zdir, data = tmp / "zims", tmp / "data" + zdir.mkdir() + data.mkdir() + for filename, name, title, lang in TITLES: + build_fixture_zim( + str(zdir / filename), {"Name": name, "Title": title, "Language": lang, "Scraper": "mwoffliner 1.14"} + ) + mp = pytest.MonkeyPatch() + mp.setenv("ZIMI_APPS", ",".join(srv.APP_NAMES)) + mp.setattr(srv, "ZIM_DIR", str(zdir)) + mp.setattr(srv, "ZIMI_DATA_DIR", str(data)) + srv.load_cache(force=True) + for z in srv._zim_list_cache: + z["first_seen"] = time.time() - 60 * 86400 + z["updated_at"] = time.time() - 3600 if z["name"] == "lowtech" else None + # Wiktionary, Wikisource and Khan Academy read as several languages on their tile. + httpd = ThreadingHTTPServer(("127.0.0.1", 0), ZimHandler) + import threading + + threading.Thread(target=httpd.serve_forever, daemon=True).start() + yield "http://127.0.0.1:%d" % httpd.server_address[1] + httpd.shutdown() + mp.undo() + + +@pytest.mark.parametrize("width", [390, 1280, 1600]) +def test_no_text_escapes_a_compact_tile(served, width): + from playwright.sync_api import sync_playwright + + with sync_playwright() as pw: + br = pw.chromium.launch() + try: + ctx = br.new_context(color_scheme="dark", **WIDTHS[width][0]) + ctx.add_init_script("localStorage.setItem('zimi_library_view','tiles');") + pg = ctx.new_page() + pg.goto(served + "/") + pg.wait_for_function(HOME, timeout=30000) + pg.wait_for_selector("#output .stats-grid.tiles .stat-card", timeout=15000) + pg.wait_for_timeout(600) + m = pg.evaluate(OVERFLOW) + if SHOTS: + pg.screenshot(path=os.path.join(SHOTS, "tiles-%d.png" % width), full_page=True) + assert m["n"] >= len(TITLES), m + assert not m["rows"], m["rows"] + assert not m["uneven"], ("tiles in a row differ in height", m["uneven"]) + assert m["sw"] <= m["vw"], "nothing pushes the page sideways" + finally: + br.close() + + +# A tile's name: the first word (the distinctive one) fully visible and whole, not hyphenated or clipped. +FIRST_WORD = r"""() => { + const out = []; + for (const zt of document.querySelectorAll('#output .stats-grid.tiles:not(.apps-grid) > .stat-card .zt')) { + const node = zt.firstChild; if (!node || node.nodeType !== 3) continue; + const text = node.textContent, m = text.match(/^\s*(\S+)/); if (!m) continue; + const r = document.createRange(); r.setStart(node, text.indexOf(m[1])); r.setEnd(node, text.indexOf(m[1]) + m[1].length); + const rects = Array.from(r.getClientRects()), zb = zt.getBoundingClientRect(); + out.push({ word: m[1], lines: rects.length, inside: rects.every(b => b.bottom <= zb.bottom + 0.5 && b.right <= zb.right + 0.5 && b.left >= zb.left - 0.5), + zt: Math.round(zb.width), hyph: getComputedStyle(zt).hyphens }); + } + return out; +}""" + +_FULL_AND_TILE_WIDTH = r"""() => { + const el = document.querySelector('#output .stats-grid:not(.apps-grid) > .stat-card'); + return el ? el.getBoundingClientRect().width : 0; +}""" + + +def _first_card_width(pw, served, ctxargs, view): + br = pw.chromium.launch() + try: + ctx = br.new_context(color_scheme="dark", **ctxargs) + ctx.add_init_script("localStorage.setItem('zimi_library_view','%s');" % view) + pg = ctx.new_page() + pg.goto(served + "/") + pg.wait_for_function(HOME, timeout=30000) + pg.wait_for_selector("#output .stats-grid .stat-card", timeout=15000) + pg.wait_for_timeout(400) + return pg.evaluate(_FULL_AND_TILE_WIDTH), (pg.evaluate(FIRST_WORD) if view == "tiles" else None) + finally: + br.close() + + +@pytest.mark.parametrize("width", [390, 820, 1280, 1600]) +def test_three_compact_tiles_per_full_card(served, width): + """"Let's shoot for 3:1 sizing for the compact/full". A full card is within 2.8-3.2 of a compact tile's + width at every breakpoint, and each name's first word is whole and visible.""" + from playwright.sync_api import sync_playwright + + with sync_playwright() as pw: + full, _ = _first_card_width(pw, served, WIDTHS[width][0], "list") + tile, words = _first_card_width(pw, served, WIDTHS[width][0], "tiles") + assert tile > 0 and full > 0 + assert 2.8 <= full / tile <= 3.2, (width, full, tile, full / tile) + assert len(words) >= len(TITLES) + for w in words: + if w["word"] == TITLES[4][2]: # the one word wider than any tile: clipped, never past the tile (the overflow test) + continue + assert w["inside"], w + assert w["hyph"] != "auto", w + assert w["lines"] == 1, ("the first word is split across lines", w) + + +# Each tile given a kind chip the way _paintProvBadges adds one (last in its name row); then, per row, where each chip's foot is. +CHIP_FEET = r"""() => { + const tiles = Array.from(document.querySelectorAll('#output .stats-grid.tiles:not(.apps-grid) > .stat-card')); + for (const t of tiles) { const n = t.querySelector('.name'); if (n && !n.querySelector('.prov-badge')) n.insertAdjacentHTML('beforeend', 'Page'); } + const rows = {}; + for (const t of tiles) { + const b = t.querySelector('.prov-badge').getBoundingClientRect(), tb = t.getBoundingClientRect(); + (rows[Math.round(tb.top)] = rows[Math.round(tb.top)] || []).push({ foot: Math.round(b.bottom), gap: Math.round(tb.bottom - b.bottom) }); + } + return Object.values(rows); +}""" + + +@pytest.mark.parametrize("width", [390, 1280]) +def test_a_rows_kind_chips_share_one_line_at_the_tiles_foot(served, width): + """A one-line name and a three-line name in one row: their chips sit on the same line, at the foot of the tile.""" + from playwright.sync_api import sync_playwright + + with sync_playwright() as pw: + br = pw.chromium.launch() + try: + ctx = br.new_context(color_scheme="dark", **WIDTHS[width][0]) + ctx.add_init_script("localStorage.setItem('zimi_library_view','tiles');") + pg = ctx.new_page() + pg.goto(served + "/") + pg.wait_for_function(HOME, timeout=30000) + pg.wait_for_selector("#output .stats-grid.tiles .stat-card", timeout=15000) + rows = pg.evaluate(CHIP_FEET) + assert rows, "no tiles" + for row in rows: + feet = [c["foot"] for c in row] + assert max(feet) - min(feet) <= 1, ("chips in a row sit at different heights", row) + assert all(c["gap"] <= 12 for c in row), ("a chip floats above the tile's foot", row) + finally: + br.close() diff --git a/tests/test_core_corners_browser.py b/tests/test_core_corners_browser.py new file mode 100644 index 000000000..0c0f2f003 --- /dev/null +++ b/tests/test_core_corners_browser.py @@ -0,0 +1,318 @@ +"""Zimi's own corners on a phone (a design review of the 1.16 build, core list). + +- a search that finds nothing runs its suggestion and says so, in one quiet line, with the typed words a tap away +- the search tips are a full-width sheet whose rows put their syntax into the box (explanations are plain text) +- a PDF that will not open gets the missing-page card, not a grey line +- Settings > Server > Add-ons says it is offline instead of "Could not load this list" + +Run: pytest tests/test_core_corners_browser.py -v +""" + +import os +import sys +import threading + +import pytest + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.dirname(HERE)) +sys.path.insert(0, HERE) + +import zimi.server as srv # noqa: E402 +from conftest_zim import build_fixture_zim # noqa: E402 +from pdf_fixture import multipage_pdf # noqa: E402 +from zimi import http # noqa: E402 + +PHONE = {"width": 390, "height": 844} + + +def _skip_without_browser(): + import zimi.renderer as renderer + + if not renderer.browser_available(): + pytest.skip("playwright + chromium are not usable here") + + +@pytest.fixture +def base(tmp_path, monkeypatch): + from http.server import ThreadingHTTPServer + + monkeypatch.setenv("ZIMI_OFFLINE", "1") + zdir = tmp_path / "zims" + zdir.mkdir() + build_fixture_zim(str(zdir / "wikipedia_en_all_2026-10.zim")) + build_fixture_zim( + str(zdir / "zimgit-water.zim"), + {"Scraper": "nautiluszim 1.1.1", "Name": "zimgit-water"}, + files={"files/Here.pdf": multipage_pdf(2)}, + ) + monkeypatch.setattr(srv, "ZIM_DIR", str(zdir)) + monkeypatch.setattr(srv, "ZIMI_DATA_DIR", str(tmp_path / "data")) + os.makedirs(str(tmp_path / "data"), exist_ok=True) + srv.load_cache(force=True) + # A title index for the suggestion's vocabulary (words seen twice survive its prune), read before any search. + from test_did_you_mean import _make_title_index + from zimi import search + + _make_title_index( + str(tmp_path / "data" / "titles"), + "wikipedia", + [ + "Water purification", + "Water purification methods", + "Boil water", + "Fire", + "Fire safety", + ], + ) + search._reset_vocab() + search._ensure_vocab() + search._join_vocab_build() + httpd = ThreadingHTTPServer(("127.0.0.1", 0), http.ZimHandler) + threading.Thread(target=httpd.serve_forever, daemon=True).start() + yield "http://127.0.0.1:%d" % httpd.server_address[1] + httpd.shutdown() + srv.release_zim_handles(list(srv.get_zim_files())) + + +def _page(pw, scheme="dark"): + br = pw.chromium.launch() + ctx = br.new_context( + viewport=PHONE, + has_touch=True, + is_mobile=True, + color_scheme=scheme, + service_workers="block", + ) + return br, ctx.new_page() + + +def _search(pg, base, text): + pg.goto(base + "/") + # The box is in the page before the app's script has wired it: type once Home is drawn, or Enter can go nowhere. + pg.wait_for_function("() => typeof mode !== 'undefined' && mode === 'home'", timeout=60_000) + pg.fill("#q", text) + pg.press("#q", "Enter") + + +@pytest.mark.local_gate # the suggestion's second search outlasts a shared runner's wait; it passes on any desktop +def test_nothing_found_runs_the_suggestion(base): + _skip_without_browser() + from playwright.sync_api import sync_playwright + + with sync_playwright() as pw: + br, pg = _page(pw) + _search(pg, base, "watr purifcation") + pg.wait_for_selector(".dym-ran", timeout=30000) + line = pg.inner_text(".dym-ran") + assert "water purification" in line and "watr purifcation" in line + assert pg.locator("a.result").count() >= 1 + assert "No results found" not in pg.inner_text("#output") + # The typed words are a tap away; taking them keeps them (no second correction). + pg.click(".dym-ran a[data-typed]") + pg.wait_for_selector(".empty", timeout=30000) + assert pg.input_value("#q") == "watr purifcation" + assert pg.locator(".dym-ran").count() == 0 + br.close() + + +@pytest.mark.parametrize("scheme", ["dark", "light"]) +def test_empty_hint_uses_the_secondary_text_colour(base, scheme): + _skip_without_browser() + from playwright.sync_api import sync_playwright + + with sync_playwright() as pw: + br, pg = _page(pw, scheme) + _search(pg, base, "zzzqqq") + pg.wait_for_selector(".empty .hint", timeout=30000) + same = pg.evaluate( + "() => { const h = document.querySelector('.empty .hint'), p = document.querySelector('.empty p');" + " const hs = getComputedStyle(h), ps = getComputedStyle(p);" + " return [hs.opacity, hs.color === ps.color]; }" + ) + assert same == ["1", True] + br.close() + + +def test_search_tips_are_a_full_width_sheet_of_real_rows(base): + _skip_without_browser() + from playwright.sync_api import sync_playwright + + with sync_playwright() as pw: + br, pg = _page(pw) + pg.goto(base + "/") + pg.wait_for_selector("#search-help") + pg.click("#search-help") + pg.wait_for_selector(".search-tips") + box = pg.evaluate( + "() => { const r = document.querySelector('.suggest-dropdown').getBoundingClientRect();" + " return [r.left, r.width, r.bottom, innerWidth, innerHeight]; }" + ) + assert box[0] == 0 and box[1] == box[3], box + assert box[2] <= box[4], box # not clipped at the foot + # Explanations are text, not things that look pressable. + assert pg.locator(".search-tips .search-chip").count() == 0 + assert pg.locator(".search-example-note").count() >= 5 + # A row puts its syntax into the box and closes; nothing is searched. + row = pg.locator(".search-example").nth(1) + syntax = row.locator(".search-example-q").inner_text() + row.dispatch_event("mousedown") + assert pg.input_value("#q") == syntax + assert ( + pg.evaluate( + "() => getComputedStyle(document.querySelector('.suggest-dropdown')).display" + ) + == "none" + ) + assert pg.evaluate("() => !document.querySelector('.results')") + br.close() + + +def test_a_pdf_that_will_not_open_has_the_missing_page_card(base): + _skip_without_browser() + from playwright.sync_api import sync_playwright + + with sync_playwright() as pw: + br, pg = _page(pw) + pg.goto(base + "/?a=zimgit-water%2Ffiles%2FNope.pdf") + frame = None + for _ in range(100): + frame = next((f for f in pg.frames if "/static/pdfjs/" in f.url), None) + if frame and frame.query_selector(".zp-msg main"): + break + pg.wait_for_timeout(200) + assert frame is not None + card = frame.inner_text(".zp-msg main") + assert "files/Nope.pdf" in card + assert "missing or damaged" in card + assert frame.query_selector(".zp-msg-back") is not None + # The card is a surface of its own (it can be pressed), not a grey line over the page. + assert frame.evaluate( + "() => getComputedStyle(document.querySelector('.zp-msg')).pointerEvents !== 'none'" + ) + br.close() + + +def test_zimis_pieces_have_one_home_and_home_customizing_is_a_preference(base): + """Offline Readiness (with the add-ons inside it) closes the Files tab; Server has no second add-ons list; Customize + categories is in Preferences.""" + _skip_without_browser() + from playwright.sync_api import sync_playwright + + def present(pg, section, sel): + pg.evaluate("(s) => switchMs(s)", section) + pg.wait_for_selector("#ms-pane > *", state="attached") + return pg.evaluate("(q) => !!document.querySelector('#ms-pane ' + q)", sel) + + with sync_playwright() as pw: + br, pg = _page(pw) + pg.goto(base + "/") + pg.wait_for_selector("#q") + pg.evaluate("() => enterManage(null, 'library')") + pg.wait_for_selector(".offline-fold", state="attached", timeout=30000) + assert pg.evaluate( + "() => document.querySelector('#ms-pane').lastElementChild.classList.contains('offline-fold')" + ) + assert not present(pg, "library", "#ms-reorder") + assert present(pg, "preferences", "#ms-reorder") + assert not present(pg, "server", "#ms-addons") and not present( + pg, "server", ".offline-fold" + ) + br.close() + + +def test_zimis_own_zims_are_community_rows_that_add_the_packages_copy(base): + """No Zimi category: the community row of zimi_mul_games is the row, marked own so Add installs the release's copy + (zimi_games), never a community download; one the catalog lacks joins Community.""" + _skip_without_browser() + from playwright.sync_api import sync_playwright + + with sync_playwright() as pw: + br, pg = _page(pw) + pg.goto(base + "/") + pg.wait_for_selector("#q") + pg.evaluate("() => enterManage(null, 'library')") + pg.wait_for_selector(".offline-fold", state="attached", timeout=30000) + got = pg.evaluate("""() => { + const items = [{ name: 'zimi_mul_games', category: COMMUNITY_CAT, source: 'community' }, { name: 'wikipedia_en_all' }]; + _mergeOwnCatalogRows(items, [{ name: 'zimi_games', category: COMMUNITY_CAT }, { name: 'zimi_almanac', category: COMMUNITY_CAT }]); + return { items: items.map(i => [i.name, !!i.own, i.category || '']), keys: BROWSE_CATEGORIES.map(c => c.key), + add: _ownZimName('zimi_mul_games') }; + }""") + assert got["items"] == [ + ["zimi_mul_games", True, "community"], + ["wikipedia_en_all", False, ""], + ["zimi_almanac", False, "community"], + ] + assert "zimi" not in got["keys"] and got["add"] == "zimi_games" + br.close() + + +def test_the_community_mark_is_one_solid_drawing_everywhere(base): + _skip_without_browser() + from playwright.sync_api import sync_playwright + + with sync_playwright() as pw: + br, pg = _page(pw) + pg.goto(base + "/") + pg.wait_for_selector("#q") + got = pg.evaluate("""() => { + const tile = BROWSE_CATEGORIES.find(c => c.key === COMMUNITY_CAT).icon; + const card = communityIcon(16); + const paths = s => s.replace(/^]*>/, '').replace(/<\\/svg>$/, ''); + return { same: paths(tile) === paths(card), tile, card }; + }""") + assert got[ + "same" + ], "the category tile and the card's mark are different drawings" + for svg in (got["tile"], got["card"]): + assert 'fill="currentColor"' in svg and "stroke" not in svg + br.close() + + +def test_a_compact_library_tile_is_shorter_and_narrower_than_a_full_card(base): + """compact fit 5 to the full card's 4 and stood taller. At a wide window and on a phone it is + now shorter and narrower than the card, so more fit a row.""" + _skip_without_browser() + from playwright.sync_api import sync_playwright + + read = """() => { + const c = document.querySelector('#output .stats-grid:not(.pick-tiles) > .stat-card'); + const b = c.getBoundingClientRect(); + return { w: Math.round(b.width), h: Math.round(b.height) }; + }""" + with sync_playwright() as pw: + for size in ({"width": 1440, "height": 900}, PHONE): + br = pw.chromium.launch() + pg = br.new_context(viewport=size, service_workers="block").new_page() + pg.goto(base + "/") + pg.wait_for_selector( + "#output .stats-grid:not(.pick-tiles) > .stat-card", timeout=30000 + ) + pg.evaluate("() => _setLibraryView('list')") + pg.wait_for_selector( + "#output .stats-grid:not(.tiles):not(.pick-tiles) > .stat-card" + ) + card = pg.evaluate(read) + pg.evaluate("() => _setLibraryView('tiles')") + pg.wait_for_selector("#output .stats-grid.tiles > .stat-card") + tile = pg.evaluate(read) + assert tile["h"] < card["h"] and tile["w"] < card["w"], (size, tile, card) + br.close() + + +def test_addons_offline_says_so(base): + _skip_without_browser() + from playwright.sync_api import sync_playwright + + with sync_playwright() as pw: + br, pg = _page(pw) + pg.goto(base + "/") + pg.wait_for_selector("#q") + pg.evaluate("() => enterManage(null, 'library')") + pg.wait_for_selector(".offline-fold", state="attached", timeout=30000) + pg.evaluate("() => { document.querySelector('.offline-fold').open = true; }") + pg.wait_for_selector("#ms-addons .ms-hint", timeout=30000) + text = pg.inner_text("#ms-addons") + assert "ZIMI_OFFLINE" in text and "Could not load" not in text + br.close() diff --git a/tests/test_ctx_no_auto_update_item.py b/tests/test_ctx_no_auto_update_item.py new file mode 100644 index 000000000..4bf9a18b9 --- /dev/null +++ b/tests/test_ctx_no_auto_update_item.py @@ -0,0 +1,12 @@ +"""The card right-click menu carries no per-ZIM auto-update opt-out.""" +import pathlib + +STATIC = pathlib.Path(__file__).resolve().parent.parent / "zimi" / "static" + + +def test_card_menu_has_no_auto_update_item(): + js = (STATIC / "app.js").read_text(encoding="utf-8") + assert "au-skip" not in js + assert "au_skip_on" not in js + for f in (STATIC / "i18n").glob("*.json"): + assert "au_skip_on" not in f.read_text(encoding="utf-8"), f.name diff --git a/tests/test_design_tokens.py b/tests/test_design_tokens.py new file mode 100644 index 000000000..db76800ae --- /dev/null +++ b/tests/test_design_tokens.py @@ -0,0 +1,156 @@ +"""The design tokens (type, radius, spacing, touch, motion) are declared once, in tokens.css. The shell inlines them in +its head and each app page in front of apps.css, so every document that reads one finds it, and no stylesheet declares +its own. The shared stylesheets use them in place of the literals they replace. + +Run: pytest tests/test_design_tokens.py -v +""" + +import os +import re + +STATIC = os.path.join( + os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "zimi", "static" +) +SCALE = {"11", "13", "15", "17", "20", "26", "32"} + + +def _read(name): + with open(os.path.join(STATIC, name), encoding="utf-8") as f: + return f.read() + + +def _block(css): + return css + + +def test_the_type_scale_is_the_seven_sizes(): + block = _block(_read("tokens.css")) + assert set(re.findall(r"--fs-[a-z]+:\s*(\d+)px", block)) == SCALE + + +def test_the_tokens_exist(): + block = _block(_read("tokens.css")) + for name in ( + "--fw-regular", + "--fw-strong", + "--r-chip", + "--r-sheet", + "--r-full", + "--sp-1", + "--sp-5", + "--gutter", + "--target", + "--dur-press", + "--dur-settle", + "--dur-travel", + "--ease-press", + "--ease-settle", + "--ease-travel", + ): + assert re.search(re.escape(name) + r"\s*:", block), name + assert "--target: 44px" in block + assert ( + "--dur-press: 120ms" in block + and "--dur-settle: 200ms" in block + and "--dur-travel: 320ms" in block + ) + assert "cubic-bezier(.25, 1, .5, 1)" in block + + +def test_reduced_motion_zeroes_the_durations(): + block = _block(_read("tokens.css")) + m = re.search(r"prefers-reduced-motion: reduce\)\s*\{\s*:root\s*\{([^}]*)\}", block) + assert m + assert len(re.findall(r"--dur-\w+: 0\.001ms", m.group(1))) == 3 + + +def test_no_stylesheet_declares_the_tokens_again(): + for name in ("app.css", "apps.css"): + assert not re.search(r"--(?:fs-[a-z]+|sp-\d|dur-[a-z]+|ease-[a-z]+|target|r-chip|r-sheet|r-full)\s*:", _read(name)), name + + +def test_the_shell_and_the_app_pages_get_the_tokens_inlined(): + from zimi import http + + assert http._TOKENS_MARK not in http.SEARCH_UI_HTML + head = http.SEARCH_UI_HTML.split("", 1)[0] + assert "--dur-settle: 200ms" in head and head.index("--dur-settle") < head.index("/static/app.css") + with open(os.path.join(STATIC, "tube.html"), "rb") as f: + served = http._inline_apps_assets(f.read()) + assert served.count(b"--dur-settle: 200ms") == 1 + assert served.index(b"--dur-settle") < served.index(b"--amber:") + + +# What a stylesheet says in a token's place: the literal each token replaces. +SCALE_LITERALS = ( + r"font-size:\s*(?:11|13|15|17|20|26|32)px", + r"font-weight:\s*(?:400|600)\b", + r"min-height:\s*44px", + r"(?]*> typeof zimsCache !== 'undefined' && (zimsCache || []).length > 0", timeout=30000) + pg.fill("#q", query) + pg.keyboard.press("Enter") + pg.wait_for_function("() => document.querySelector('#output .result, #output .empty, #output .did-you-mean')", timeout=30000) + pg.wait_for_timeout(1500) + return pg.evaluate( + "() => ({ results: document.querySelectorAll('#output .result, #output a.result').length, dym: !!document.querySelector('#output .did-you-mean') })" + ) + + +def test_a_result_that_answers_the_search_leaves_no_suggestion_above_it(served): + from playwright.sync_api import sync_playwright + + with sync_playwright() as pw: + br = pw.chromium.launch() + try: + pg = br.new_context(viewport={"width": 390, "height": 844}, is_mobile=True, has_touch=True).new_page() + got = _search(pg, served, "wat") + assert got["results"] >= 1 and not got["dym"], got + finally: + br.close() diff --git a/tests/test_discover_card_width_browser.py b/tests/test_discover_card_width_browser.py new file mode 100644 index 000000000..155277fcb --- /dev/null +++ b/tests/test_discover_card_width_browser.py @@ -0,0 +1,33 @@ +"""A Discover card keeps its 260px on a phone, as in the shipping release (it had grown to the row's width at 390px). + +Run: pytest tests/test_discover_card_width_browser.py -v +""" + +import os +import sys + +import pytest + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +import zimi.renderer as renderer # noqa: E402 + +STATIC = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "zimi", "static") + + +@pytest.mark.parametrize("width", [360, 390, 480]) +def test_discover_cards_are_260_on_a_phone(width): + if not renderer.browser_available(): + pytest.skip("playwright + chromium are not usable here") + from playwright.sync_api import sync_playwright + + css = "".join(open(os.path.join(STATIC, n), encoding="utf-8").read() for n in ("tokens.css", "app.css")) + with sync_playwright() as p: + b = p.chromium.launch() + page = b.new_context(viewport={"width": width, "height": 844}, is_mobile=True).new_page() + page.set_content("" + "
%s
" + % (css, "x" * 4)) + widths = page.eval_on_selector_all(".discover-card", "els => els.map(e => Math.round(e.getBoundingClientRect().width))") + b.close() + assert widths == [260] * 4, widths diff --git a/tests/test_first_run_setup_browser.py b/tests/test_first_run_setup_browser.py index 0e4bd5d66..7c41f0e71 100644 --- a/tests/test_first_run_setup_browser.py +++ b/tests/test_first_run_setup_browser.py @@ -97,6 +97,22 @@ def _page(browser, base, headers): return page +def _past_the_offer_step(page): + """After who can manage, first run offers what can be downloaded now (4f09a1642: Almanac HD, voices, satellite data...); + its Done goes on to the library. With nothing to offer the overlay closes by itself.""" + page.wait_for_function( + "() => !document.getElementById('setup-overlay').classList.contains('open')" + " || !!document.querySelector('#setup-card #setup-addons')", + timeout=30000, + ) + if page.evaluate("() => document.getElementById('setup-overlay').classList.contains('open')"): + with page.expect_navigation(): + page.click("#setup-card .btn-row .btn-primary") + page.wait_for_function( + "() => !document.getElementById('setup-overlay').classList.contains('open')", timeout=30000 + ) + + def test_a_device_on_the_network_sets_it_up_with_the_key(served, browser): base, key = served page = _page(browser, base, LAN_VIA_PROXY) @@ -110,9 +126,7 @@ def test_a_device_on_the_network_sets_it_up_with_the_key(served, browser): page.fill("#setup-pw2", "hunter22") page.click("#setup-form button[type=submit]") page.wait_for_load_state("load") - page.wait_for_function( - "!document.getElementById('setup-overlay').classList.contains('open')" - ) + _past_the_offer_step(page) assert page.evaluate("fetch('/list').then(r => r.status)") == 200 assert ( page.evaluate( @@ -299,9 +313,7 @@ def test_a_first_run_without_a_password_is_a_choice_with_its_cost(served, browse assert "kept" not in cost, "there is no password to keep" assert page.is_hidden("#setup-fields") page.click("#setup-form button[type=submit]") - page.wait_for_function( - "!document.getElementById('setup-overlay').classList.contains('open')" - ) + _past_the_offer_step(page) assert ( page.evaluate("fetch('/manage/has-password').then(r => r.json()).then(j => j.access)") == "open" diff --git a/tests/test_folder_category_grouping.cjs b/tests/test_folder_category_grouping.cjs index 73f35cc45..21d0dbaec 100644 --- a/tests/test_folder_category_grouping.cjs +++ b/tests/test_folder_category_grouping.cjs @@ -45,7 +45,10 @@ vm.runInContext( // const at vm top level does not attach to the sandbox — rewrite to var. extract(/const OTHER_CAT = '__other__';/, 'OTHER_CAT').replace('const ', 'var ') + '\n' + extract(/var CREATED_CAT = '[^']*';/, 'CREATED_CAT') + '\n' + + extract(/const COMMUNITY_ICON_PATHS = .*;/, 'COMMUNITY_ICON_PATHS').replace('const ', 'var ') + '\n' + + extract(/const COMMUNITY_CAT = .*;/, 'COMMUNITY_CAT').replace('const ', 'var ') + '\n' + extract(/function _catIcon\(paths\) \{[\s\S]*?\n\}/, '_catIcon') + '\n' + + extract(/function communityIcon\(size\) \{[\s\S]*?\n\}/, 'communityIcon') + '\n' + extract(/const BROWSE_CATEGORIES = \[[\s\S]*?\n\];/, 'BROWSE_CATEGORIES').replace('const ', 'var ') + '\n' + extract(/const _CAT_TO_BROWSE_KEY = \{[\s\S]*?\n\};/, '_CAT_TO_BROWSE_KEY').replace('const ', 'var ') + '\n' + extract(/function _zimCat\(z\)\s*\{[\s\S]*?\n\}/, '_zimCat') + '\n' + diff --git a/tests/test_hit_areas_browser.py b/tests/test_hit_areas_browser.py new file mode 100644 index 000000000..ce6ed3c0c --- /dev/null +++ b/tests/test_hit_areas_browser.py @@ -0,0 +1,142 @@ +"""A control drawn under 44px still takes a 44px touch (an invisible box, nothing drawn or laid out moves). +Measured the way a finger finds it: elementFromPoint outward from the control until another element answers. + +Run: pytest tests/test_hit_areas_browser.py -v +""" + +import os +import sys + +import pytest + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +import zimi.renderer as renderer # noqa: E402 + +STATIC = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "zimi", "static") +TARGET = 44 +SLACK = 2 # a hairline border does not take a touch; a box edge on a fractional pixel (a narrower font) loses up to one at each end of a probe stepped in whole pixels + +REACH_JS = """(el) => { + const r = el.getBoundingClientRect(); + const hit = (x, y) => { const e = document.elementFromPoint(x, y); return !!e && (e === el || el.contains(e)); }; + const cx = r.left + r.width / 2, cy = r.top + r.height / 2; + const run = (fx, fy) => { let n = 0; while (n < 40 && hit(fx(n + 1), fy(n + 1))) n++; return n; }; + const l = run(n => r.left - n, () => cy), rt = run(n => r.right + n, () => cy); + const t = run(() => cx, n => r.top - n), b = run(() => cx, n => r.bottom + n); + return [Math.round(r.width + l + rt), Math.round(r.height + t + b), Math.round(r.width), Math.round(r.height)]; +}""" + + +def _read(name): + with open(os.path.join(STATIC, name), encoding="utf-8") as f: + return f.read() + + +@pytest.fixture(scope="module") +def phone(): + if not renderer.browser_available(): + pytest.skip("playwright + chromium are not usable here") + from playwright.sync_api import sync_playwright + + with sync_playwright() as p: + b = p.chromium.launch() + ctx = b.new_context(viewport={"width": 390, "height": 844}, has_touch=True, is_mobile=True) + yield ctx.new_page() + b.close() + + +def _shell(phone, body): + css = _read("tokens.css") + _read("app.css") + phone.set_content("%s" % (css, body)) + + +def _reach(phone, selector): + return phone.eval_on_selector(selector, REACH_JS) + + +def test_a_pill_in_the_scrolling_row_reaches_44_tall(phone): + _shell(phone, "
" + "

after

") + w, h, dw, dh = _reach(phone, ".pill") + assert dh == 28 and h >= TARGET - SLACK, (w, h) + + +def test_the_pill_row_does_not_move(phone): + html = "

after

" + _shell(phone, html) + after = phone.evaluate("[r.getBoundingClientRect().top, a.getBoundingClientRect().top, r.getBoundingClientRect().height]") + phone.set_content("%s" % (_read("tokens.css") + _read("app.css").replace( + ".pills-row { padding-block: 8px 10px; margin-block: -8px; }", ""), html)) + before = phone.evaluate("[r.getBoundingClientRect().top, a.getBoundingClientRect().top, r.getBoundingClientRect().height]") + assert after[1] == before[1], (before, after) + + +def test_hide_discover_reaches_44_tall(phone): + _shell(phone, "
" + "Discover
") + w, h, dw, dh = _reach(phone, ".dc-dismiss") + assert dh < 20 and h >= TARGET - SLACK and w >= TARGET - SLACK, (w, h) + + +def _app_page(phone, body): + css = _read("tokens.css") + _read("apps.css") + phone.set_content("%s" % (css, body)) + + +def test_an_app_chip_is_the_shells_pill_and_reaches_44(phone): + """Bookshelf and ZimiTube's chip: 28 tall and 12px like Home's pill, the chosen one filled amber, a 44px touch.""" + _app_page(phone, "
") + w, h, dw, dh = _reach(phone, ".chip.on") + assert dh == 28 and h >= TARGET - SLACK, (h, dh) + style = "e => { const c = getComputedStyle(e); return [c.fontSize, c.borderRadius, c.fontWeight, c.backgroundImage.slice(0, 15)]; }" + assert phone.eval_on_selector(".chip.on", style) == ["12px", "20px", "600", "linear-gradient"] + assert phone.eval_on_selector(".chip:not(.on)", style)[:3] == ["12px", "20px", "500"] + + +@pytest.fixture(scope="module") +def served(tmp_path_factory): + import threading + from http.server import ThreadingHTTPServer + + import zimi.server as srv + from zimi.http import ZimHandler + + tmp = tmp_path_factory.mktemp("hitareas") + (tmp / "zims").mkdir() + (tmp / "data").mkdir() + old = (srv.ZIM_DIR, srv.ZIMI_DATA_DIR) + srv.ZIM_DIR, srv.ZIMI_DATA_DIR = str(tmp / "zims"), str(tmp / "data") + srv.load_cache(force=True) + httpd = ThreadingHTTPServer(("127.0.0.1", 0), ZimHandler) + threading.Thread(target=httpd.serve_forever, daemon=True).start() + yield "http://127.0.0.1:%d" % httpd.server_address[1] + httpd.shutdown() + srv.ZIM_DIR, srv.ZIMI_DATA_DIR = old + + +@pytest.mark.parametrize("path, selectors", [ + ("/", ["#logo", "#search-help", "#library-btn", "#bm-panel-btn", ".topbar-more"]), + ("/?q=Paris", ["#logo", "#back-btn", "#search-clear", "#library-btn", "#bm-panel-btn", ".topbar-more"]), # tips wait while a query is typed +]) +def test_the_top_bar_reaches_44_where_it_can(phone, served, path, selectors): + """The bar's controls on a phone, as a finger finds them: every one 44 wide and tall. With a query typed the tips mark waits + (it is on the empty box), so the clear x has the end to itself.""" + phone.goto(served + path) + phone.wait_for_selector(".topbar .logo") + phone.wait_for_timeout(500) + for sel in selectors: + w, h, dw, dh = _reach(phone, sel) + assert h >= TARGET - SLACK and w >= TARGET - SLACK, (sel, w, h) + if path != "/": + assert phone.eval_on_selector("#search-help", "e => getComputedStyle(e).display") == "none" + + +def test_two_stacked_pill_rows_each_reach_44(phone): + """The source row over the language row (.suggest-filters): centres 44 apart, so neither row loses its touch to the other.""" + _shell(phone, "
" + "
" + "
") + for sel in (".pills-row .pill", ".lang-pills .pill"): + w, h, dw, dh = _reach(phone, sel) + assert h >= TARGET - SLACK, (sel, h) diff --git a/tests/test_home_apps_live.py b/tests/test_home_apps_live.py index 08e6cfd33..bde695478 100644 --- a/tests/test_home_apps_live.py +++ b/tests/test_home_apps_live.py @@ -233,20 +233,26 @@ def test_the_order_governs_the_apps_and_their_title_opens_their_page( assert at["heading"] == apps and at["clickable"] and at["aboveApps"], at # Help now is its own pill between the heading and the row of apps. assert at["helpFirst"], at - assert at["sort"] and at["view"] and at["controls"] == 1, at - ctl, text, grid = at["ctl"], at["text"], at["grid"] - assert ctl["b"] <= grid["t"], "the controls sit above the apps" + # The order and the size together, in one place, on the first heading, the Apps. + assert at["controls"] == 1, at + assert at["sort"] and at["view"], "the order and the view chooser sit together on the Apps heading" + box = pg.evaluate( + "() => { const c = document.querySelector('#output .lib-controls'), b = c.getBoundingClientRect()," + " r = document.createRange(); r.selectNodeContents(c.closest('.cat-heading').firstChild); const t = r.getBoundingClientRect();" + " return { l: b.left, r: b.right, tl: t.left, tr: t.right, vw: document.documentElement.clientWidth }; }" + ) assert ( - ctl["l"] >= 0 and ctl["r"] <= at["vw"] + box["l"] >= 0 and box["r"] <= box["vw"] ), "the controls are on the screen" - assert ctl["l"] >= text["r"] or ctl["r"] <= text["l"], "clear of the name" + assert box["l"] >= box["tr"] or box["r"] <= box["tl"], "clear of the name" assert at["scrollW"] <= at["vw"], "nothing pushes the page sideways" + text = at["text"] # Home shows only the apps with something inside; an empty one waits # on the Apps page (Eric, 2026-10-17: "hide apps that have no # backing zims"). borders = pg.evaluate( "() => Object.fromEntries(Array.from(document.querySelectorAll('#output .apps-grid .app-tile'))" - ".map(a => [a.dataset.app, getComputedStyle(a).borderTopStyle]))" + ".map(a => [a.dataset.app, getComputedStyle(a.closest('.pick-tiles') ? a.querySelector('.card-icon') : a).borderTopStyle]))" ) assert "reddot" not in borders and "maps" not in borders, borders assert borders["tube"] == borders["books"] == "solid", borders @@ -359,11 +365,15 @@ def test_opening_an_app_clears_its_dot(served, route): tile_dot = "() => !!document.querySelector(\"#output .apps-grid .app-tile[data-app='tube'] .rc-dot\")" with sync_playwright() as pw: br = pw.chromium.launch() - pg = br.new_context(viewport={"width": 390, "height": 844}, is_mobile=True, has_touch=True).new_page() + pg = br.new_context( + viewport={"width": 390, "height": 844}, is_mobile=True, has_touch=True + ).new_page() try: pg.goto(served + "/") pg.wait_for_function(HOME, timeout=30000) - assert pg.evaluate(tile_dot), "CrashCourse updated an hour ago: Tube wears the dot" + assert pg.evaluate( + tile_dot + ), "CrashCourse updated an hour ago: Tube wears the dot" if route == "tile": pg.locator("#output .apps-grid .app-tile[data-app='tube']").click() elif route == "search": @@ -382,20 +392,31 @@ def test_opening_an_app_clears_its_dot(served, route): @pytest.mark.parametrize("touch", [False, True], ids=["hover", "tap"]) def test_the_dot_says_what_lit_it(served, touch): """Eric, 2026-11-04: "maybe if I hover on a dot show the updates that lead to it". Hover the dot (a - mouse), or tap the dot itself (a phone): a small list says what changed, here CrashCourse's update an - hour ago, and the tap does not open the app.""" + mouse): a small list says what changed, here CrashCourse's update an hour ago. On a phone the dot is a mark only. + """ from playwright.sync_api import sync_playwright dot = "#output .apps-grid .app-tile[data-app='tube'] .rc-dot" with sync_playwright() as pw: br = pw.chromium.launch() - size = {"width": 390, "height": 844} if touch else {"width": 1280, "height": 900} + size = ( + {"width": 390, "height": 844} if touch else {"width": 1280, "height": 900} + ) pg = br.new_context(viewport=size, is_mobile=touch, has_touch=touch).new_page() try: pg.goto(served + "/") pg.wait_for_function(HOME, timeout=30000) if touch: - pg.locator(dot).tap() + # On a square tile the dot is 7px, too small a target: on touch it is a mark only, and a tap anywhere on + # the tile opens the app (the tile's long press opens its menu). + assert ( + pg.evaluate( + "(s) => getComputedStyle(document.querySelector(s)).pointerEvents", + dot, + ) + == "none" + ) + return else: # The pointer goes to the dot as a mouse does, with no scroll. Home redraws once more when its late data # lands (_renderHomeSoon); a locator.hover() that meets the redraw retries by scrolling the page, and a @@ -414,9 +435,16 @@ def test_the_dot_says_what_lit_it(served, touch): arg=["CrashCourse", pg.evaluate("t('upd_updated')")], timeout=10000, ).json_value() - assert not pg.evaluate("() => typeof _tubeOpen !== 'undefined' && _tubeOpen"), "the dot is not the tile" + assert not pg.evaluate( + "() => typeof _tubeOpen !== 'undefined' && _tubeOpen" + ), "the dot is not the tile" if os.environ.get("ZIMI_SHOTS"): - pg.screenshot(path=os.path.join(os.environ["ZIMI_SHOTS"], "dot-why-%s.png" % ("tap" if touch else "hover"))) + pg.screenshot( + path=os.path.join( + os.environ["ZIMI_SHOTS"], + "dot-why-%s.png" % ("tap" if touch else "hover"), + ) + ) finally: br.close() @@ -426,15 +454,22 @@ def test_about_says_when_it_last_changed_and_how(served): with sync_playwright() as pw: br = pw.chromium.launch() - pg = br.new_context(viewport={"width": 390, "height": 844}, is_mobile=True, has_touch=True).new_page() + pg = br.new_context( + viewport={"width": 390, "height": 844}, is_mobile=True, has_touch=True + ).new_page() try: pg.goto(served + "/") pg.wait_for_function(HOME, timeout=30000) pg.evaluate("_openZimAbout('crashcourse')") - pg.wait_for_function("() => !!document.querySelector('.zi-panel .zi-rows')", timeout=10000) + pg.wait_for_function( + "() => !!document.querySelector('.zi-panel .zi-rows')", timeout=10000 + ) text = pg.text_content(".zi-panel") assert pg.evaluate("t('zi_last_updated')") in text, text if os.environ.get("ZIMI_SHOTS"): - pg.screenshot(path=os.path.join(os.environ["ZIMI_SHOTS"], "about-updated.png"), full_page=True) + pg.screenshot( + path=os.path.join(os.environ["ZIMI_SHOTS"], "about-updated.png"), + full_page=True, + ) finally: br.close() diff --git a/tests/test_home_badge_browser.py b/tests/test_home_badge_browser.py new file mode 100644 index 000000000..b00bee392 --- /dev/null +++ b/tests/test_home_badge_browser.py @@ -0,0 +1,156 @@ +"""Discover's language badge says what the card's text is written in, on every card. + +A Word or Quote of the Day from an English wiki under a German, Russian or Arabic page carried no badge, +because only the standard card asked _cardLangBadge; the Game of the Day (its text translated by Zimi +itself, its ZIM's metadata saying English) carried one it should not. The quote card in Russian also +lost its last line at a phone's width. + +Run: pytest tests/test_home_badge_browser.py -v +""" + +import os +import sys +import threading + +import pytest + +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__))) + +READY = "() => typeof zimsCache !== 'undefined' && (zimsCache || []).length > 0" +RU_QUOTE = ( + "Воображение важнее знания. Знание ограничено, тогда как воображение охватывает целый мир," + " стимулирует прогресс и рождает эволюцию." +) + + +@pytest.fixture +def served(tmp_path_factory): + import zimi.renderer as renderer + + if not renderer.browser_available(): + pytest.skip("playwright + chromium are not usable here") + from http.server import ThreadingHTTPServer + + from app_saved_fixture import build_library + + import zimi.server as srv + from zimi.http import ZimHandler + + tmp = tmp_path_factory.mktemp("badge") + mp = pytest.MonkeyPatch() + build_library(tmp / "zims") + mp.setattr(srv, "ZIM_DIR", str(tmp / "zims")) + mp.setattr(srv, "ZIMI_DATA_DIR", str(tmp / "data")) + os.makedirs(str(tmp / "data"), exist_ok=True) + mp.setenv("ZIMI_OFFLINE", "1") + mp.setenv("ZIMI_TORRENT", "0") + srv.load_cache(force=True) + httpd = ThreadingHTTPServer(("127.0.0.1", 0), ZimHandler) + threading.Thread(target=httpd.serve_forever, daemon=True).start() + yield "http://127.0.0.1:%d" % httpd.server_address[1] + httpd.shutdown() + mp.undo() + + +@pytest.fixture +def pw(): + from playwright.sync_api import sync_playwright + + with sync_playwright() as p: + yield p + + +def _page(pw, served, lang, quote="Imagination is more important than knowledge."): + br = pw.chromium.launch() + pg = br.new_context(**pw.devices["iPhone 13"], service_workers="block").new_page() + pg.goto(served + "/") + pg.wait_for_function(READY, timeout=30000) + pg.wait_for_selector("#discover-row", state="attached") + pg.wait_for_function( + "() => document.querySelector('#discover-row .discover-card') && !document.querySelector('#discover-row .dc-loading')", + timeout=20000, + ) + pg.evaluate("l => setLanguage(l)", lang) + pg.wait_for_function("l => _currentLang === l", arg=lang) + pg.evaluate( + """() => { + [['wiktionary_en-simple_all_nopic', 'Wiktionary', 'eng'], + ['wikiquote_en_all_nopic', 'Wikiquote', 'eng'], + ['wikiquote_ru_all_nopic', 'Wikiquote', 'rus'], + ['zimi_games', 'Games', 'eng']].forEach(function(z) { + zimsCache.push({ name: z[0], title: z[1], language: z[2], main_path: 'index' }); + }); + _rebuildZimsMap(); + }""" + ) + pg.evaluate( + """q => _renderDiscover(document.getElementById('discover-row'), [ + { zim: 'wikiquote_en_all_nopic', path: 'Q', title: 'Albert Einstein', blurb: '\\u201c' + q + '\\u201d', attribution: 'Albert Einstein' }, + { zim: 'wiktionary_en-simple_all_nopic', path: 'institution', title: 'institution', blurb: 'a society or organization', part_of_speech: 'noun' }, + { zim: 'zimi_games', path: 'ineq', title: 'Inequality', type: 'random', blurb: 'A puzzle' }])""", + quote, + ) + return br, pg + + +@pytest.mark.parametrize("lang", ["de", "ru", "ar"]) +def test_every_card_badges_text_in_another_language_and_only_that(served, pw, lang): + br, pg = _page(pw, served, lang) + try: + got = pg.evaluate( + """() => ({ + quote: !!document.querySelector('.dc-quote-card:not(.dc-word-card) .dc-header .lang-badge'), + word: !!document.querySelector('.dc-word-card .dc-header .lang-badge'), + game: !!document.querySelector('.discover-card[data-zim="zimi_games"] .lang-badge'), + })""" + ) + assert got == {"quote": True, "word": True, "game": False}, got + finally: + br.close() + + +def test_a_card_in_the_pages_own_language_has_no_badge(served, pw): + br, pg = _page(pw, served, "en") + try: + assert pg.locator(".discover-card .lang-badge").count() == 0 + finally: + br.close() + + +def test_the_russian_quote_shows_its_last_line_at_phone_width(served, pw): + br, pg = _page(pw, served, "ru", RU_QUOTE) + try: + r = pg.evaluate( + """() => { const b = document.querySelector('.dc-quote-card:not(.dc-word-card) .dc-quote'); + const c = b.closest('.discover-card').getBoundingClientRect(); const q = b.getBoundingClientRect(); + return { scroll: b.scrollHeight, client: b.clientHeight, qb: q.bottom, cb: c.bottom, + lines: Math.round(b.scrollHeight / parseFloat(getComputedStyle(b).lineHeight)) }; }""" + ) + print(r) + assert r["scroll"] <= r["client"] + 1, r + finally: + br.close() + + +@pytest.mark.parametrize("scheme,dark", [("dark", True), ("light", False)]) +def test_first_paint_follows_the_os_when_no_theme_is_stored(served, pw, scheme, dark): + """No stored theme, no account: the page is stamped before its stylesheet, so the first frame is already the + OS's scheme and nothing flips later.""" + br = pw.chromium.launch() + try: + pg = br.new_context(**pw.devices["iPhone 13"], service_workers="block", color_scheme=scheme).new_page() + pg.add_init_script( + """window.__bg = []; document.addEventListener('readystatechange', function () { + if (document.body) __bg.push([document.documentElement.dataset.theme, getComputedStyle(document.body).backgroundColor]); }); + new MutationObserver(function () { if (document.body) __bg.push([document.documentElement.dataset.theme, getComputedStyle(document.body).backgroundColor]); }) + .observe(document.documentElement, { attributes: true });""" + ) + pg.goto(served + "/") + pg.wait_for_function(READY, timeout=30000) + seen = pg.evaluate("() => __bg") + want = "dark" if dark else "light" + assert seen and all(t == want for t, _ in seen), seen + assert len({c for _, c in seen}) == 1, seen + finally: + br.close() diff --git a/tests/test_home_boot_flash_live.py b/tests/test_home_boot_flash_live.py new file mode 100644 index 000000000..725adf599 --- /dev/null +++ b/tests/test_home_boot_flash_live.py @@ -0,0 +1,120 @@ +"""Opening Zimi's home does not flash ("Loading the main Zimi view has this weird flash during loading"). + +On a slow link the bar painted in one shape and, a moment later, the boot re-laid it out under the eye: the search box +shrank, the Saved button and the search tips popped in, the logo moved six pixels, the placeholder changed twice +("Search everything..." to "Search" to "Search everything…" to "Search"), and a "Loading library..." message blinked in +for a fraction of a second before the page replaced it. This samples every frame of a cold and a warm load of / on an +emulated iPhone and on a desktop, over a slow network, and fails on any of those. + +Run: pytest tests/test_home_boot_flash_live.py -v +""" + +import os +import sys +import threading + +import pytest + +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 zimi.renderer as renderer # noqa: E402 +import zimi.server as srv # noqa: E402 +from test_home_apps_live import HOME # noqa: E402 + +# One entry per frame in which anything the eye could catch changed. +RECORD = r""" +(() => { const T = window.__tl = []; const t0 = performance.now(); let last = '', loadAt = 0, loadSeen = 0; + function snap() { const d = document, tb = d.querySelector('.topbar'); if (!tb) return; + const box = id => { const e = d.getElementById(id), r = e && e.getBoundingClientRect(); return e && r.width > 0 ? [Math.round(r.left), Math.round(r.width)] : null; }; + const q = d.getElementById('q'), ld = d.querySelector('#output .loading'); + const now = performance.now() - t0; + if (ld && !loadAt) loadAt = now; + if (ld && !loadSeen && parseFloat(getComputedStyle(ld).opacity) > 0.05) loadSeen = now; + const o = { ph: q && q.placeholder, logo: box('logo'), q: box('q'), help: box('search-help'), saved: box('bm-panel-btn'), + bg: getComputedStyle(d.body).backgroundColor, loadAt: Math.round(loadAt), loadSeen: Math.round(loadSeen) }; + const k = JSON.stringify(o); if (k !== last) { last = k; T.push(o); } } + function loop() { snap(); requestAnimationFrame(loop); } + document.addEventListener('DOMContentLoaded', () => requestAnimationFrame(loop)); +})(); +""" + +CONTEXTS = { + "phone": dict(viewport={"width": 390, "height": 844}, is_mobile=True, has_touch=True, device_scale_factor=2), + "desktop": dict(viewport={"width": 1280, "height": 800}), +} + + +@pytest.fixture(scope="module") +def served(tmp_path_factory): + if not renderer.browser_available(): + pytest.skip("playwright + chromium are not usable here") + from http.server import ThreadingHTTPServer + + from conftest_zim import build_fixture_zim + + from zimi.http import ZimHandler + + tmp = tmp_path_factory.mktemp("bootflash") + zdir, data = tmp / "zims", tmp / "data" + zdir.mkdir() + data.mkdir() + for n in ("wikipedia_en_all_maxi", "devdocs_en_python", "lowtech"): + build_fixture_zim(str(zdir / (n + "_2026-01.zim")), {"Name": n, "Title": n.title(), "Language": "eng"}) + mp = pytest.MonkeyPatch() + mp.setenv("ZIMI_APPS", ",".join(srv.APP_NAMES)) + mp.setattr(srv, "ZIM_DIR", str(zdir)) + mp.setattr(srv, "ZIMI_DATA_DIR", str(data)) + srv.load_cache(force=True) + httpd = ThreadingHTTPServer(("127.0.0.1", 0), ZimHandler) + threading.Thread(target=httpd.serve_forever, daemon=True).start() + yield "http://127.0.0.1:%d/" % httpd.server_address[1] + httpd.shutdown() + mp.undo() + + +def _timeline(url, kind, warm): + from playwright.sync_api import sync_playwright + + with sync_playwright() as pw: + br = pw.chromium.launch() + try: + ctx = br.new_context(color_scheme="dark", **CONTEXTS[kind]) + if warm: + p = ctx.new_page() + p.goto(url) + p.wait_for_function(HOME, timeout=30000) + p.wait_for_timeout(1500) + p.close() + ctx.add_init_script(RECORD) + pg = ctx.new_page() + cdp = ctx.new_cdp_session(pg) + cdp.send("Network.enable") + cdp.send("Network.emulateNetworkConditions", {"offline": False, "latency": 150, "downloadThroughput": 400000, "uploadThroughput": 200000}) + cdp.send("Emulation.setCPUThrottlingRate", {"rate": 3}) + pg.goto(url, wait_until="commit") + pg.wait_for_function(HOME, timeout=60000) + pg.wait_for_timeout(1500) + return pg.evaluate("window.__tl") + finally: + br.close() + + +@pytest.mark.parametrize("warm", [False, True], ids=["cold", "warm"]) +@pytest.mark.parametrize("kind", ["phone", "desktop"]) +def test_home_boot_does_not_flash(served, kind, warm): + tl = _timeline(served, kind, warm) + assert tl, "no frames recorded" + # The bar is the one Home settles on from its first paint: nothing in it moves, pops in or changes its words. + # (The desktop's ⋯, an admin's Create, arrives when the server says who may; it is not part of this.) + if kind == "desktop": # the ⋯ moves the buttons sideways, so there it is whether they are there + tl = [dict(f, help=bool(f["help"]), saved=bool(f["saved"]), q=None) for f in tl] + keys = ("ph", "logo", "q", "help", "saved") + shapes = {tuple(repr(f[k]) for k in keys) for f in tl} + assert len(shapes) == 1, ("the bar changed after its first paint", [dict((k, f[k]) for k in keys) for f in tl]) + # Dark before and after: no light frame while the scheme is dark. + assert {f["bg"] for f in tl} == {"rgb(10, 10, 11)"}, {f["bg"] for f in tl} + # A "Loading library" message is for a slow start: never on screen within half a second of appearing. + last = tl[-1] + if last["loadSeen"]: + assert last["loadSeen"] - last["loadAt"] >= 450, ("the loading message blinked in", last) diff --git a/tests/test_home_discover_live.py b/tests/test_home_discover_live.py index 00f6facf6..460be23d3 100644 --- a/tests/test_home_discover_live.py +++ b/tests/test_home_discover_live.py @@ -257,3 +257,45 @@ def test_discover_drawn_before_the_library_fills_in_when_it_arrives(served): assert pg.evaluate("() => window.__asked") == 2 finally: br.close() + + +def test_say_reads_the_language_from_the_zim_not_only_its_name(served): + """"I can't believe we lost the speak button on the + word of the day." The NAS serves its Wiktionary as wiktionary_en-simple and + its Wikiquote as plain wikiquote; Say read the language from the name alone, + matched neither, and drew no button. The ZIM's Language says it.""" + from playwright.sync_api import sync_playwright + + with sync_playwright() as pw: + br, pg = _phone(pw) + try: + pg.goto(served + "/") + pg.wait_for_function(READY, timeout=30000) + pg.wait_for_selector("#discover-row", state="attached") + pg.wait_for_function( + "() => document.querySelector('#discover-row .discover-card') && !document.querySelector('#discover-row .dc-loading')", + timeout=20000, + ) + pg.wait_for_timeout(500) + got = pg.evaluate( + """() => { + zimsCache.push({ name: 'wiktionary_en-simple', title: 'Wiktionary', main_path: 'index', language: 'eng' }, + { name: 'wikiquote', title: 'Wikiquote', main_path: 'index', language: 'deu' }, + { name: 'wiktionary_fr_all_nopic_2026-01', title: 'Wiktionnaire', main_path: 'index' }); + _rebuildZimsMap(); + const row = document.getElementById('discover-row'); + _renderDiscover(row, [ + { zim: 'wiktionary_en-simple', path: 'paintbrush', title: 'paintbrush', blurb: 'A brush for paint.' }, + { zim: 'wikiquote', path: 'Goethe', title: 'Goethe', blurb: '\\u201cMehr Licht!\\u201d', attribution: 'Goethe' }, + { zim: 'wiktionary_fr_all_nopic_2026-01', path: 'pinceau', title: 'pinceau', blurb: 'Outil.' }]); + return [...row.querySelectorAll('.discover-card')].map(c => { + const s = c.querySelector('.dc-say'); return [c.dataset.zim, s ? s.dataset.lang : null]; }); + }""" + ) + assert got == [ + ["wiktionary_en-simple", "en"], + ["wikiquote", "de"], + ["wiktionary_fr_all_nopic_2026-01", "fr"], + ], got + finally: + br.close() diff --git a/tests/test_home_layout_live.py b/tests/test_home_layout_live.py new file mode 100644 index 000000000..ddc2fdd6a --- /dev/null +++ b/tests/test_home_layout_live.py @@ -0,0 +1,302 @@ +"""Home's layout at every width. + +Discover first, then Apps, then Favorites and the library. The library's card grids flow 1 / 2 / 3 / 4 columns at +about 600 / 1200 / 1600 px and never more, Home stopping at ~1600 px, centred. The apps are square launcher tiles, +the same size on a phone and a wide screen, packed from the start edge and never stretched to fill the row. Nothing +pushes a phone's page sideways. + +Run: pytest tests/test_home_layout_live.py -v +""" + +import json +import os +import sys +import threading +import time + +import pytest + +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 zimi.renderer as renderer # noqa: E402 +import zimi.server as srv # noqa: E402 +from test_home_apps_live import HOME, LIBRARY # noqa: E402 + +# More of one kind, so a category holds a full row at the widest width. +MORE = [ + ("devdocs_en_%s_2026-01.zim" % n, {"Name": "devdocs_en_%s" % n, "Title": n.title()}) + for n in ("python", "javascript", "rust", "go", "bash") +] +FAVORITES = ["devdocs_en_python", "devdocs_en_rust"] + +WIDTHS = { + 390: ( + dict( + viewport={"width": 390, "height": 844}, + is_mobile=True, + has_touch=True, + device_scale_factor=3, + ), + 1, + ), + 820: ( + dict(viewport={"width": 820, "height": 1180}, is_mobile=True, has_touch=True), + 2, + ), + 1280: (dict(viewport={"width": 1280, "height": 800}), 3), + 1600: (dict(viewport={"width": 1600, "height": 1000}), 4), + 1920: (dict(viewport={"width": 1920, "height": 1080}), 4), +} + +MEASURE = r"""() => { + const box = el => el.getBoundingClientRect(); + const out = document.getElementById('output'); + const disc = document.getElementById('discover-row'); + const appsGrid = out.querySelector('.apps-grid'); + const appsHead = appsGrid && appsGrid.previousElementSibling && appsGrid.previousElementSibling.classList.contains('apps-help') + ? appsGrid.previousElementSibling.previousElementSibling : appsGrid && appsGrid.previousElementSibling; + const libGrids = Array.from(out.querySelectorAll('.stats-grid:not(.apps-grid)')); + const tiles = Array.from(out.querySelectorAll('.apps-grid .app-tile')); + const g = appsGrid && box(appsGrid); + const c = box(document.querySelector('#main-view .container')); + return { + discoverFirst: !!disc && !!appsGrid && !!(disc.compareDocumentPosition(appsGrid) & Node.DOCUMENT_POSITION_FOLLOWING), + discoverAbove: !!disc && !!appsHead && box(disc).bottom <= box(appsHead).top, + favAfterApps: (() => { const f = libGrids[0]; return !!f && !!appsGrid && !!(appsGrid.compareDocumentPosition(f) & Node.DOCUMENT_POSITION_FOLLOWING) && box(f).top >= g.bottom; })(), + columns: libGrids.map(el => getComputedStyle(el).gridTemplateColumns.split(' ').filter(Boolean).length), + tiles: tiles.map(t => { const b = box(t); return [Math.round(b.width), Math.round(b.height)]; }), + tileIcons: tiles.map(t => { const b = box(t.querySelector('.card-icon')); return [Math.round(b.width), Math.round(b.height)]; }), + tilesRight: tiles.length ? Math.max.apply(null, tiles.map(t => box(t).right)) : 0, + tilesLeft: tiles.length ? Math.min.apply(null, tiles.map(t => box(t).left)) : 0, + grid: g ? { l: g.left, r: g.right } : null, + container: { l: c.left, r: c.right, w: c.width }, + vw: document.documentElement.clientWidth, sw: document.documentElement.scrollWidth, + }; +}""" + + +@pytest.fixture(scope="module") +def served(tmp_path_factory): + if not renderer.browser_available(): + pytest.skip("playwright + chromium are not usable here") + from http.server import ThreadingHTTPServer + + from conftest_zim import build_fixture_zim + + from zimi.http import ZimHandler + + tmp = tmp_path_factory.mktemp("homelayout") + zdir, data = tmp / "zims", tmp / "data" + zdir.mkdir() + data.mkdir() + for filename, meta, _ in LIBRARY: + build_fixture_zim(str(zdir / filename), meta) + for filename, meta in MORE: + build_fixture_zim(str(zdir / filename), meta) + (data / "collections.json").write_text( + json.dumps({"version": 1, "favorites": FAVORITES, "collections": {}}), + encoding="utf-8", + ) + mp = pytest.MonkeyPatch() + mp.setenv("ZIMI_APPS", ",".join(srv.APP_NAMES)) + mp.setattr(srv, "ZIM_DIR", str(zdir)) + mp.setattr(srv, "ZIMI_DATA_DIR", str(data)) + srv.load_cache(force=True) + # CrashCourse's new build landed an hour ago: ZimiTube wears the dot. + for z in srv._zim_list_cache: + z["first_seen"] = time.time() - 60 * 86400 + z["updated_at"] = time.time() - 3600 if z["name"] == "crashcourse" else None + httpd = ThreadingHTTPServer(("127.0.0.1", 0), ZimHandler) + threading.Thread(target=httpd.serve_forever, daemon=True).start() + yield "http://127.0.0.1:%d" % httpd.server_address[1] + httpd.shutdown() + mp.undo() + + +def _measure(pw, served, width, rtl=False): + br = pw.chromium.launch() + try: + opts, _ = WIDTHS[width] + ctx = br.new_context(color_scheme="dark", **opts) + if rtl: + ctx.add_init_script("localStorage.setItem('zimi_ui_lang','ar');") + pg = ctx.new_page() + errors = [] + pg.on("pageerror", lambda e: errors.append(str(e))) + pg.goto(served + "/") + pg.wait_for_function(HOME, timeout=30000) + pg.wait_for_function( + "() => !!document.querySelector('#discover-row .discover-card')", + timeout=15000, + ) + m = pg.evaluate(MEASURE) + assert not errors, errors + return m + finally: + br.close() + + +@pytest.mark.parametrize("width", sorted(WIDTHS)) +def test_home_flows_with_the_width(served, width): + from playwright.sync_api import sync_playwright + + with sync_playwright() as pw: + m = _measure(pw, served, width) + cols = WIDTHS[width][1] + # Discover, then Apps, then the library (Favorites first). + assert m["discoverFirst"] and m["discoverAbove"], m + assert m["favAfterApps"], m + # Every card grid has the columns this width gets, never more than four. + assert m["columns"] and set(m["columns"]) == {cols}, m["columns"] + # Home stops at about 1600 px and sits centred. + assert m["container"]["w"] <= 1600 + 2 * 16 + 1, m["container"] + assert abs(m["container"]["l"] - (m["vw"] - m["container"]["r"])) <= 1, m[ + "container" + ] + # Square tiles, one size, packed from the start edge: the row is not stretched to fill. + assert m["tiles"] and len(set(map(tuple, m["tiles"]))) == 1, m["tiles"] + assert ( + len(set(map(tuple, m["tileIcons"]))) == 1 + and m["tileIcons"][0][0] == m["tileIcons"][0][1] + ), m["tileIcons"] + assert m["tiles"][0][0] <= 96, "a launcher tile, not a card: %s" % m["tiles"] + assert abs(m["tilesLeft"] - m["grid"]["l"]) <= 1, m + if width >= 1280: + assert ( + m["grid"]["r"] - m["tilesRight"] > 200 + ), "the tiles keep their size and leave the rest of the row" + # Nothing pushes the page sideways. + assert m["sw"] <= m["vw"], m + + +def test_tiles_are_the_same_size_on_a_phone_and_a_wide_screen(served): + from playwright.sync_api import sync_playwright + + with sync_playwright() as pw: + phone = _measure(pw, served, 390) + wide = _measure(pw, served, 1920) + assert phone["tiles"][0] == wide["tiles"][0], (phone["tiles"], wide["tiles"]) + + +def test_right_to_left_packs_from_the_right(served): + from playwright.sync_api import sync_playwright + + with sync_playwright() as pw: + m = _measure(pw, served, 1920, rtl=True) + assert abs(m["tilesRight"] - m["grid"]["r"]) <= 1, m + assert m["sw"] <= m["vw"], m + + +# The tile's dot leads its name (as a phone marks a fresh app), on the name's line; a tile wears no ⋯, with a mouse or not. +TILE_MARKS = r"""() => { + const tile = document.querySelector("#output .pick-tiles .app-tile[data-app='tube']"); + const zt = tile.querySelector('.pick-name .zt').getBoundingClientRect(); + const dot = tile.querySelector('.pick-name .rc-dot i'); + const d = dot && dot.getBoundingClientRect(); + const rtl = document.documentElement.dir === 'rtl'; + const more = tile.querySelector('.card-more'), cs = more && getComputedStyle(more); + return { dot: !!dot, lead: d ? (rtl ? d.left - zt.right : zt.left - d.right) : null, dy: d ? (d.top + d.height / 2) - (zt.top + zt.height / 2) : null, + moreShown: !!more && !!more.offsetParent && +cs.opacity > 0, badgeShown: dot ? getComputedStyle(dot).visibility !== 'hidden' : null }; +}""" + + +@pytest.mark.parametrize("rtl", [False, True], ids=["ltr", "rtl"]) +@pytest.mark.parametrize("width", [390, 1920]) +def test_the_new_dot_leads_the_apps_name(served, width, rtl): + from playwright.sync_api import sync_playwright + + with sync_playwright() as pw: + br = pw.chromium.launch() + try: + ctx = br.new_context(color_scheme="dark", **WIDTHS[width][0]) + if rtl: + ctx.add_init_script("localStorage.setItem('zimi_ui_lang','ar');") + pg = ctx.new_page() + pg.goto(served + "/") + pg.wait_for_function(HOME, timeout=30000) + m = pg.evaluate(TILE_MARKS) + assert m["dot"] and 0 <= m["lead"] <= 8 and abs(m["dy"]) <= 2, m + assert not m["moreShown"] and m["badgeShown"], m + finally: + br.close() + + +def test_with_a_mouse_right_click_and_the_keyboard_open_a_tiles_menu(served): + from playwright.sync_api import sync_playwright + + tile = "#output .pick-tiles .app-tile[data-app='tube']" + with sync_playwright() as pw: + br = pw.chromium.launch() + try: + pg = br.new_context(color_scheme="dark", **WIDTHS[1920][0]).new_page() + pg.goto(served + "/") + pg.wait_for_function(HOME, timeout=30000) + pg.hover(tile + " .card-icon") + pg.wait_for_timeout(300) + m = pg.evaluate(TILE_MARKS) + assert not m["moreShown"] and m["badgeShown"], m + for how in ("right-click", "Shift+F10"): + pg.keyboard.press("Escape") + pg.wait_for_selector("#zim-ctx-menu.visible", state="hidden", timeout=3000) + if how == "right-click": + pg.click(tile + " .card-icon", button="right") + else: + pg.focus(tile) + pg.keyboard.press("Shift+F10") + pg.wait_for_selector("#zim-ctx-menu.visible [data-action=about-app]", timeout=3000) + finally: + br.close() + + +# How many compact tiles share a row, and how wide a Discover card is. +COMPACT = r"""() => ({ + cols: getComputedStyle(document.querySelector('#output .stats-grid.tiles')).gridTemplateColumns.split(' ').filter(Boolean).length, + tile: Math.round(document.querySelector('#output .stats-grid.tiles .stat-card').getBoundingClientRect().width), + disc: Array.from(document.querySelectorAll('#discover-row .discover-card')).map(c => Math.round(c.getBoundingClientRect().width)), +})""" + + +@pytest.mark.parametrize("width,cols", [(390, 3), (1280, 5), (1600, 6), (1920, 6)]) +def test_compact_stays_compact_and_discover_keeps_its_size(served, width, cols): + """"that should be like 6 of the compact and it's still only four", and the Discover cards + "were sized nicely before, just more of them visible now".""" + from playwright.sync_api import sync_playwright + + with sync_playwright() as pw: + br = pw.chromium.launch() + try: + ctx = br.new_context(color_scheme="dark", **WIDTHS.get(width, (dict(viewport={"width": width, "height": 900}),))[0]) + ctx.add_init_script("localStorage.setItem('zimi_library_view','tiles');") + pg = ctx.new_page() + pg.goto(served + "/") + pg.wait_for_function(HOME, timeout=30000) + pg.wait_for_function("() => !!document.querySelector('#discover-row .discover-card')", timeout=15000) + m = pg.evaluate(COMPACT) + assert m["cols"] >= cols and m["tile"] <= 160, m # 1.16: denser than 1.15, never sparser + assert set(m["disc"]) == {260}, m + finally: + br.close() + + + + +# Home is always wide: no width toggle, the container takes the room up to --pick-max. +def test_home_is_always_wide_with_no_width_toggle(served): + from playwright.sync_api import sync_playwright + + with sync_playwright() as pw: + br = pw.chromium.launch() + try: + ctx = br.new_context(color_scheme="dark", **WIDTHS[1600][0]) + ctx.add_init_script("localStorage.setItem('zimi_home_width','compact');") # an old choice is ignored + pg = ctx.new_page() + pg.goto(served + "/") + pg.wait_for_function(HOME, timeout=30000) + pg.wait_for_selector("#output .lib-view-toggle", state="attached") + m = pg.evaluate("""() => ({ toggle: !!document.querySelector('.home-width-toggle'), + compact: document.body.classList.contains('home-compact'), + w: Math.round(document.querySelector('#main-view .container').getBoundingClientRect().width) })""") + assert not m["toggle"] and not m["compact"] and m["w"] > 1500, m + finally: + br.close() diff --git a/tests/test_home_more_menu.py b/tests/test_home_more_menu.py new file mode 100644 index 000000000..9ecd3549f --- /dev/null +++ b/tests/test_home_more_menu.py @@ -0,0 +1,297 @@ +"""One ⋯ on everything Home draws, and on every app's top bar; the same About sheet behind each. + +"All the apps are supposed to have a ... menu with what's relevant including about that lists what's in it" and +"I want ... menu on every tile on homepage, every app". + +On a phone, in a real browser, over a small library: every tile and row on Home (each source, each app, in the list and +in the tiles) has a ⋯ with a hit area of at least 44x44, which opens the card's menu with an About; every app page has a +⋯ in the top bar whose About says what the app is and which sources it reads; the sheet closes on Escape and on Back and +hands focus back to the ⋯; the Discover cards carry the same ⋯. + +Run: pytest tests/test_home_more_menu.py -v +""" + +import os +import sys +import threading +import time + +import pytest + +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 zimi.renderer as renderer # noqa: E402 +import zimi.server as srv # noqa: E402 +from test_home_apps_live import HOME, LIBRARY # noqa: E402 + +pytestmark = pytest.mark.fieldguide_on +PHONE = { + "width": 390, + "height": 3000, +} # as wide as a phone, tall enough to hit-test the whole of Home at once +DAY = 86400 + + +@pytest.fixture(scope="module") +def served(tmp_path_factory): + if not renderer.browser_available(): + pytest.skip("playwright + chromium are not usable here") + from http.server import ThreadingHTTPServer + + from conftest_zim import build_fixture_zim + + from zimi.http import ZimHandler + + tmp = tmp_path_factory.mktemp("morehome") + zdir = tmp / "zims" + zdir.mkdir() + for filename, meta, _ in LIBRARY: + build_fixture_zim(str(zdir / filename), meta) + mp = pytest.MonkeyPatch() + mp.setenv("ZIMI_APPS", ",".join(srv.APP_NAMES)) + mp.setenv("ZIMI_OFFLINE", "1") + mp.setattr(srv, "ZIM_DIR", str(zdir)) + mp.setattr(srv, "ZIMI_DATA_DIR", str(tmp / "data")) + os.makedirs(str(tmp / "data"), exist_ok=True) + srv.load_cache(force=True) + now = time.time() + by_file = {srv._zim_short_name(f): when for f, _, when in LIBRARY} + for z in srv._zim_list_cache: + if z["name"] in by_file: + days, hours, entries = by_file[z["name"]] + z["first_seen"] = now - days * DAY + z["updated_at"] = now - hours * 3600 if hours else None + z["entries"] = entries + httpd = ThreadingHTTPServer(("127.0.0.1", 0), ZimHandler) + threading.Thread(target=httpd.serve_forever, daemon=True).start() + yield "http://127.0.0.1:%d" % httpd.server_address[1] + httpd.shutdown() + mp.undo() + + +def _page(pw, served, view="list", lang="en", theme="light"): + br = pw.chromium.launch() + ctx = br.new_context( + viewport=PHONE, + is_mobile=True, + has_touch=True, + color_scheme="dark" if theme == "dark" else "light", + locale="he-IL" if lang == "he" else "en-US", + ) + init = "localStorage.setItem('zimi_library_view','%s');" % view + if theme == "red": + init += "localStorage.setItem('zimi_app_theme','red');" + ctx.add_init_script(init) + pg = ctx.new_page() + pg.goto(served + "/") + pg.wait_for_function(HOME, timeout=30000) + pg.wait_for_timeout(500) + return br, pg + + +# Every tile and row on Home, with the ⋯ it wears and how big a tap on it is. A square app tile wears none: +# a right click or a long press opens its menu (nine ⋯ over nine icons were noise). +# A finger held 600 ms on a card's icon, then lifted. +PRESS = r"""async (i) => { + const c = document.querySelectorAll('#output .stat-card')[i], el = c.querySelector('.card-icon') || c; + const r = el.getBoundingClientRect(); + const t = new Touch({ identifier: 1, target: el, clientX: r.left + r.width / 2, clientY: r.top + r.height / 2 }); + el.dispatchEvent(new TouchEvent('touchstart', { touches: [t], targetTouches: [t], changedTouches: [t], bubbles: true, cancelable: true })); + await new Promise(res => setTimeout(res, 600)); + el.dispatchEvent(new TouchEvent('touchend', { touches: [], targetTouches: [], changedTouches: [t], bubbles: true, cancelable: true })); +}""" +TILES = r"""() => Array.from(document.querySelectorAll('#output .stat-card')).map(c => { + const square = !!c.closest('.pick-tiles'); + const m = square ? null : c.querySelector('.card-more'); + let w = 0, h = 0; + if (m) { + const r = m.getBoundingClientRect(), L = r.left - 30, T = r.top - 30; let x0 = 1e9, y0 = 1e9, x1 = -1e9, y1 = -1e9; + for (let y = T; y < r.bottom + 30; y += 2) for (let x = L; x < r.right + 30; x += 2) { + const e = document.elementFromPoint(x, y); + if (e && (e === m || m.contains(e))) { x0 = Math.min(x0, x); x1 = Math.max(x1, x); y0 = Math.min(y0, y); y1 = Math.max(y1, y); } + } + w = x1 - x0 + 2; h = y1 - y0 + 2; + } + const shown = !!c.querySelector('.card-more') && !!c.querySelector('.card-more').offsetParent; + return { zim: c.dataset.zim, app: c.dataset.app || '', square: square, more: !!m, shownMore: shown, w: w, h: h }; +})""" + + +@pytest.mark.parametrize("view", ["list", "tiles"]) +def test_every_tile_and_row_has_a_more_that_opens_an_about(served, view): + from playwright.sync_api import sync_playwright + + with sync_playwright() as pw: + br, pg = _page(pw, served, view) + try: + cards = pg.evaluate(TILES) + assert len(cards) >= 10, cards + assert any(c["app"] for c in cards) and any(c["zim"] for c in cards) + bare = [c for c in cards if not c["more"] and not c["square"]] + assert not bare, "tiles with no ⋯: %s" % bare + assert not [c for c in cards if c["square"] and c["shownMore"]], "no ⋯ on a square tile" + small = [c for c in cards if not c["square"] and (c["w"] < 43 or c["h"] < 43)] + assert not small, "a ⋯ with a tap area under 44x44: %s" % small + # Each opens a menu with an About, and About opens a sheet that says what it is. + for i in range(len(cards)): + pg.evaluate( + "(i) => document.querySelectorAll('#output .stat-card')[i].scrollIntoView({block: 'center'})", + i, + ) + if cards[i]["square"]: + pg.evaluate(PRESS, i) + else: + pg.evaluate( + "(i) => document.querySelectorAll('#output .stat-card')[i].querySelector('.card-more').click()", + i, + ) + pg.wait_for_selector( + "#zim-ctx-menu.visible [data-action^=about]", timeout=5000 + ) + kind = pg.evaluate( + "document.querySelector('#zim-ctx-menu [data-action^=about]').dataset.action" + ) + assert kind == ("about-app" if cards[i]["app"] else "about"), (i, kind) + pg.click("#zim-ctx-menu [data-action^=about]") + pg.wait_for_selector( + "#zim-about .zi-body .zi-title, #zim-about .zi-body .zi-none", + timeout=8000, + ) + body = pg.inner_text("#zim-about") + assert "zi_load_failed" not in body and len(body) > 20, body + if cards[i]["app"]: + assert pg.evaluate( + "(a) => document.querySelector('#zim-about').innerText.includes(t('app_about_' + a))", + cards[i]["app"], + ), body + pg.keyboard.press("Escape") + pg.wait_for_selector("#zim-about", state="detached", timeout=3000) + if not cards[i]["square"]: + assert pg.evaluate( + "(i) => document.activeElement === document.querySelectorAll('#output .stat-card')[i].querySelector('.card-more')", + i, + ), "focus goes back to the ⋯ that opened it" + finally: + br.close() + + +def test_the_discover_cards_carry_the_same_more(served): + from playwright.sync_api import sync_playwright + + with sync_playwright() as pw: + br, pg = _page(pw, served) + try: + pg.wait_for_selector( + "#output .discover-card:not(.dc-loading)", timeout=15000 + ) + cards = pg.evaluate( + "() => Array.from(document.querySelectorAll('.discover-card:not(.dc-loading)')).map(c => !!c.querySelector('.dc-more'))" + ) + assert cards and all(cards), cards + pg.evaluate("document.querySelector('.discover-card .dc-more').click()") + pg.wait_for_selector( + "#zim-ctx-menu.visible [data-action^=about]", timeout=5000 + ) + finally: + br.close() + + +# Left out: Zimipedia (it needs a wiki ZIM) and the Games (Zimi's own ZIM, which the test suite turns off): same code path. +APPS = { + "tube": "openTube()", + "exchange": "openExchange()", + "books": "openBooks()", + "dictionary": "openDictionary()", + "fieldguide": "openFieldguide()", + "almanac": "openAlmanac()", +} + + +@pytest.mark.parametrize("app", sorted(APPS)) +def test_every_app_has_a_more_in_its_top_bar_with_an_about(served, app): + from playwright.sync_api import sync_playwright + + with sync_playwright() as pw: + br, pg = _page(pw, served) + try: + pg.evaluate("() => " + APPS[app]) + pg.wait_for_function("(a) => _openAppId() === a", arg=app, timeout=15000) + pg.wait_for_function( + "() => { const b = document.querySelector('.topbar-more'); return b && b.getBoundingClientRect().width > 0; }" + ) + pg.click(".topbar-more") + pg.wait_for_selector("#topbar-menu.visible .topbar-menu-item", timeout=3000) + pg.click("#topbar-menu .topbar-menu-item >> nth=0") + pg.wait_for_selector("#zim-about .zi-desc", timeout=5000) + said = pg.evaluate( + "(a) => document.querySelector('#zim-about').innerText.includes(t('app_about_' + a))", + app, + ) + assert said, pg.inner_text("#zim-about") + if app in ("tube", "exchange", "books"): + assert pg.query_selector( + "#zim-about .zi-src" + ), "the sources it reads are listed" + # Escape closes it and focus returns to the ⋯. + pg.keyboard.press("Escape") + pg.wait_for_selector("#zim-about", state="detached", timeout=3000) + assert pg.evaluate( + "document.activeElement && document.activeElement.classList.contains('topbar-more')" + ) + # Back closes it too, and stays on the app. + pg.wait_for_timeout(400) # the step Escape took back has landed + pg.click(".topbar-more") + pg.click("#topbar-menu .topbar-menu-item >> nth=0") + pg.wait_for_selector("#zim-about", timeout=3000) + pg.go_back() + pg.wait_for_selector("#zim-about", state="detached", timeout=3000) + assert pg.evaluate("(a) => _openAppId() === a", app) + finally: + br.close() + + +def test_the_sheet_mirrors_in_hebrew_and_names_the_app_in_it(served): + from playwright.sync_api import sync_playwright + + with sync_playwright() as pw: + br, pg = _page(pw, served, lang="he") + try: + # A square tile's menu is its long press (the same one a ⋯ on a row opens). + pg.evaluate(PRESS, pg.evaluate("[...document.querySelectorAll('#output .stat-card')].findIndex(c => c.dataset.app === 'books')")) + pg.wait_for_selector("#zim-ctx-menu.visible [data-action=about-app]") + pg.click("#zim-ctx-menu [data-action=about-app]") + pg.wait_for_selector("#zim-about .zi-src", timeout=5000) + assert pg.evaluate("document.documentElement.dir") == "rtl" + text = pg.inner_text("#zim-about") + assert pg.evaluate("t('app_about_books')") in text + assert "app_about_books" not in text + finally: + br.close() + + +def test_a_long_press_and_a_right_click_on_an_app_tile_open_its_menu(served): + from playwright.sync_api import sync_playwright + + with sync_playwright() as pw: + br, pg = _page(pw, served) + try: + errors = [] + pg.on("pageerror", lambda e: errors.append(str(e))) + pg.evaluate( + "document.querySelector('.app-tile[data-app=books]:not(.app-empty)').scrollIntoView({block: 'center'})" + ) + box = pg.locator(".app-tile[data-app=books]:not(.app-empty) .card-info").bounding_box() + x, y = box["x"] + 20, box["y"] + box["height"] / 2 + cdp = pg.context.new_cdp_session(pg) + pt = [{"x": x, "y": y}] + cdp.send("Input.dispatchTouchEvent", {"type": "touchStart", "touchPoints": pt}) + pg.wait_for_selector("#zim-ctx-menu.visible [data-action=about-app]", timeout=4000) + cdp.send("Input.dispatchTouchEvent", {"type": "touchEnd", "touchPoints": []}) + assert pg.evaluate("_openAppId()") != "books", "a long press opens the menu, not the app" + pg.keyboard.press("Escape") + pg.mouse.click(x, y, button="right") + pg.wait_for_selector("#zim-ctx-menu.visible [data-action=about-app]", timeout=4000) + assert not errors, errors + finally: + br.close() diff --git a/tests/test_home_topbar_live.py b/tests/test_home_topbar_live.py new file mode 100644 index 000000000..1f44d833d --- /dev/null +++ b/tests/test_home_topbar_live.py @@ -0,0 +1,46 @@ +"""Wide Home's top bar: the background is full bleed, the contents sit on the library tiles' column edges +. + +Run: pytest tests/test_home_topbar_live.py -v +""" + +import os +import sys + +import pytest + +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__))) + +from test_home_apps_live import HOME # noqa: E402 +from test_home_layout_live import served # noqa: E402,F401 + +EDGES = r"""() => { + const bar = document.querySelector('.topbar'); + const logo = document.getElementById('logo').getBoundingClientRect(); + const kids = Array.from(bar.children).filter(e => e.offsetParent !== null && e.getBoundingClientRect().width); + const last = Math.max.apply(null, kids.map(e => e.getBoundingClientRect().right)); + const g = document.querySelector('#output .stats-grid:not(.apps-grid)').getBoundingClientRect(); + const b = bar.getBoundingClientRect(); + return { logoL: logo.left, lastR: last, gridL: g.left, gridR: g.right, barL: b.left, barR: b.right, + vw: document.documentElement.clientWidth }; +}""" + + +@pytest.mark.parametrize("width", [1280, 1920, 2560]) +def test_top_bar_contents_sit_on_the_tiles_edges(served, width): # noqa: F811 + from playwright.sync_api import sync_playwright + + with sync_playwright() as pw: + br = pw.chromium.launch() + try: + ctx = br.new_context(color_scheme="dark", viewport={"width": width, "height": 1000}) + pg = ctx.new_page() + pg.goto(served + "/") + pg.wait_for_function(HOME, timeout=30000) + m = pg.evaluate(EDGES) + assert m["barL"] == 0 and m["barR"] >= m["vw"] - 1, m + assert abs(m["logoL"] - m["gridL"]) <= 1, m + assert abs(m["lastR"] - m["gridR"]) <= 1, m + finally: + br.close() diff --git a/tests/test_i18n_split.py b/tests/test_i18n_split.py new file mode 100644 index 000000000..dbc44752f --- /dev/null +++ b/tests/test_i18n_split.py @@ -0,0 +1,60 @@ +"""Home does not download the Almanac's strings. + +i18n/.json is what the shell shows; the Almanac's own strings (alm_, tb_, ref_) are in i18n/almanac/.json and +come down with the Almanac's first file. A key the shell's code names (exact, or the front of a family such as +alm_shower_) stays in Home's file, so the teaser cards and the Manage panel never read a bare key. +""" + +import glob +import json +import os +import sys + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, os.path.join(ROOT, "scripts")) + +import i18n_split as split # noqa: E402 + + +def _load(path): + with open(path, encoding="utf-8") as f: + return json.load(f) + + +def test_home_holds_only_the_almanac_keys_the_shell_names(): + names = split.shell_names() + extra = {} + for path in sorted(glob.glob(os.path.join(split.I18N, "*.json"))): + stray = [ + k + for k in _load(path) + if split.is_almanac_key(k) and not split.home_needs(k, names) + ] + if stray: + extra[os.path.basename(path)] = sorted(stray)[:5] + assert not extra, ( + "Almanac strings in Home's file (run scripts/i18n_split.py): %s" % extra + ) + + +def test_the_almanacs_file_holds_nothing_the_shell_names(): + names = split.shell_names() + for path in sorted(glob.glob(os.path.join(split.ALMANAC_I18N, "*.json"))): + keys = _load(path) + assert not [k for k in keys if not split.is_almanac_key(k)], path + assert not [k for k in keys if split.home_needs(k, names)], path + + +def test_the_almanacs_files_share_one_key_set_across_languages(): + en = set(_load(os.path.join(split.ALMANAC_I18N, "en.json"))) + assert en + for lang in ("ar", "de", "es", "fr", "he", "hi", "pt", "ru", "zh"): + assert set(_load(os.path.join(split.ALMANAC_I18N, lang + ".json"))) == en, lang + + +def test_no_key_is_in_both_files(): + for path in sorted(glob.glob(os.path.join(split.I18N, "*.json"))): + both = set(_load(path)) & set( + _load(os.path.join(split.ALMANAC_I18N, os.path.basename(path))) + ) + assert not both, (path, sorted(both)[:5]) diff --git a/tests/test_library_folders_ui.cjs b/tests/test_library_folders_ui.cjs index 45b22268f..a8025d84d 100644 --- a/tests/test_library_folders_ui.cjs +++ b/tests/test_library_folders_ui.cjs @@ -29,7 +29,7 @@ ok('an owned ZIM with a newer edition offers Update', has({ _installedDate: '202 ok('the same date offers nothing', has({ _installedDate: '2026-03' }, newer) === false); ok('a ZIM in another program\'s folder never offers Update', has({ _installedDate: '2026-01', _installedExternal: 'Project NOMAD' }, newer) === false); ok('no download link offers nothing', has({ _installedDate: '2026-01' }, { date: '2026-03-01' }) === false); -ok('the catalog row asks the function', /const hasUpdate = _catalogHasUpdate\(instVariant, updVariant\);/.test(src)); +ok('the catalog row asks the function', /const hasUpdate = !item\.own && _catalogHasUpdate\(instVariant, updVariant\);/.test(src)); // The count sublines and the badge diff --git a/tests/test_library_tidy.py b/tests/test_library_tidy.py new file mode 100644 index 000000000..d4d606bab --- /dev/null +++ b/tests/test_library_tidy.py @@ -0,0 +1,416 @@ +"""One Almanac, one Games: the library lists a thing once. + +"There's too many copies of the zim when I go to library." Zimi's own content alone was listed as the +built-in Almanac and Games, an old Almanac HD core, an old maxi, the new maxi, four HD parts and two trial copies. + +- the same name with an older date is superseded: served by the newer file only, shown as an older copy kept +- a ZIM whose Name metadata is an own ZIM's is that ZIM: listed once, the package's file winning unless the copy is newer +- a ZIM that only looks alike is left alone +- data packs are not library rows; the Almanac HD row holds them and their sizes +- nothing is deleted or moved by any of this + +Run: pytest tests/test_library_tidy.py -v +""" + +import json +import os +import sys +import threading + +import pytest + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.dirname(HERE)) +sys.path.insert(0, HERE) + +import zimi.server as srv # noqa: E402 +from conftest_zim import build_fixture_zim, split_fixture_zim # noqa: E402 +from zimi import almanachd, ownzims # noqa: E402 + +ALMANAC_META = { + "Name": "zimi_eng_zimi_almanac", + "Title": "Almanac · Zimi", + "Publisher": "Zimi", + "Date": "2026-11-08", +} + + +@pytest.fixture +def lib(tmp_path, monkeypatch): + """A library folder and a package folder holding the built-in Almanac; returns the library's path.""" + zdir, pkg = tmp_path / "zims", tmp_path / "pkg" + zdir.mkdir() + pkg.mkdir() + (tmp_path / "data").mkdir() + build_fixture_zim(str(pkg / "zimi_almanac_2026-11b.zim"), ALMANAC_META) + monkeypatch.setenv("ZIMI_BUILTIN_ZIMS", "1") + monkeypatch.setattr(ownzims, "OUT_DIR", str(pkg)) + monkeypatch.setattr(srv, "ZIM_DIR", str(zdir)) + monkeypatch.setattr(srv, "ZIMI_DATA_DIR", str(tmp_path / "data")) + return zdir + + +def _scan(): + srv.load_cache(force=True) + return srv.get_zim_files() + + +def _own_path(name="zimi_almanac_2026-11b.zim"): + return os.path.join(ownzims.OUT_DIR, name) + + +def test_a_copy_of_an_own_zim_under_another_file_name_is_listed_once(lib): + copy = lib / "zimi_eng_zimi_almanac_2026-11.zim" + build_fixture_zim(str(copy), dict(ALMANAC_META, Date="2026-11")) + zims = _scan() + assert zims["zimi_almanac"] == _own_path() + assert "zimi_eng_zimi_almanac" not in zims + # It is shown as an older copy kept, and still on disk. + older = srv.older_copies() + assert [(o["file"], o["replaced_by"]) for o in older] == [ + ("zimi_eng_zimi_almanac_2026-11.zim", "zimi_almanac_2026-11b.zim") + ] + assert copy.exists() + + +def test_a_strictly_newer_copy_takes_the_name(lib): + copy = lib / "zimi_eng_zimi_almanac_2026-12.zim" + build_fixture_zim(str(copy), dict(ALMANAC_META, Date="2026-12-01")) + zims = _scan() + assert zims["zimi_almanac"] == str(copy) + assert "zimi_eng_zimi_almanac" not in zims + # The package's file is never offered for removal. + assert srv.older_copies() == [] + + +def test_the_same_day_is_not_newer(lib): + build_fixture_zim( + str(lib / "zimi_eng_zimi_almanac_2026-11.zim"), + dict(ALMANAC_META, Date="2026-11-08"), + ) + assert _scan()["zimi_almanac"] == _own_path() + + +def test_a_zim_that_only_looks_alike_is_left_alone(lib): + other = lib / "zimi_almanac_notes_2026-11.zim" + build_fixture_zim( + str(other), + { + "Name": "zimi_almanac_notes", + "Title": "My almanac notes", + "Date": "2026-11-09", + }, + ) + zims = _scan() + assert zims["zimi_almanac_notes"] == str(other) + assert zims["zimi_almanac"] == _own_path() + assert srv.older_copies() == [] + + +def test_a_file_name_alone_does_not_make_a_copy(lib): + # Called like the own ZIM, but another Name: not it. + other = lib / "zimi_eng_zimi_almanac_2026-11.zim" + build_fixture_zim( + str(other), {"Name": "somebody_elses", "Title": "Other", "Date": "2026-11"} + ) + zims = _scan() + assert zims["zimi_eng_zimi_almanac"] == str(other) + + +def test_a_renamed_copy_is_caught_by_its_metadata_not_its_file_name(lib): + copy = lib / "my_almanac_backup_2026-11.zim" + build_fixture_zim(str(copy), dict(ALMANAC_META, Date="2026-11")) + zims = _scan() + assert zims["zimi_almanac"] == _own_path() + assert "my_almanac_backup" not in zims + assert [o["file"] for o in srv.older_copies()] == ["my_almanac_backup_2026-11.zim"] + + +def test_the_name_comes_from_the_metadata_cache_once_it_is_there(lib, monkeypatch): + copy = lib / "my_almanac_backup_2026-11.zim" + build_fixture_zim(str(copy), dict(ALMANAC_META, Date="2026-11")) + _scan() # reads it, and the cache keeps its Name + ownzims._ident_cache.clear() + assert srv.cached_identity(str(copy)) == ( + "zimi_eng_zimi_almanac", + "2026-11", + ) + # A scan now opens no archive for it: the cache answers. + import libzim.reader + + def refuse(*_a, **_k): + raise AssertionError("opened an archive the cache already described") + + monkeypatch.setattr(libzim.reader, "Archive", refuse) + assert ownzims.identity(str(copy)) == ("zimi_eng_zimi_almanac", "2026-11") + # A changed file is not described by the old record. + os.utime(copy, (1, 1)) + assert srv.cached_identity(str(copy)) is None + + +def _cache_records(): + with open(srv._cache_file_path(), encoding="utf-8") as f: + return json.load(f)["files"] + + +def test_a_record_that_learns_its_name_is_written_down(lib): + book = lib / "plain_en_all_2026-11.zim" + build_fixture_zim(str(book), {"Name": "plain_en_all", "Date": "2026-11"}) + _scan() + records = _cache_records() + assert records[book.name]["mname"] == "plain_en_all" + # A cache from before the Name was kept: one start reads it, and writes it down. + del records[book.name]["mname"] + with open(srv._cache_file_path(), "w", encoding="utf-8") as f: + json.dump({"version": srv._CACHE_VERSION, "files": records}, f) + ownzims._ident_cache.clear() + srv.load_cache() + assert _cache_records()[book.name]["mname"] == "plain_en_all" + + +def test_a_split_book_is_described_by_the_metadata_cache(lib): + book = lib / "my_almanac_backup_2026-11.zim" + build_fixture_zim(str(book), dict(ALMANAC_META, Date="2026-11")) + first = split_fixture_zim(str(book), 4096)[0] + assert first.endswith(".zimaa") + _scan() + assert _cache_records()["my_almanac_backup_2026-11.zim"]["mname"] == "zimi_eng_zimi_almanac" + ownzims._ident_cache.clear() + assert srv.cached_identity(first) == ("zimi_eng_zimi_almanac", "2026-11") + + +def test_the_same_name_with_an_older_date_is_superseded_and_kept_on_disk(lib): + old, new = ( + lib / "zimi_almanac_maxi_2026-11.zim", + lib / "zimi_almanac_maxi_2026-11b.zim", + ) + build_fixture_zim(str(old), {"Name": "zimi_almanac_maxi", "Date": "2026-11"}) + build_fixture_zim(str(new), {"Name": "zimi_almanac_maxi", "Date": "2026-11"}) + zims = _scan() + assert zims["zimi_almanac_maxi"] == str(new) + assert str(old) not in zims.values() + assert [(o["file"], o["replaced_by"]) for o in srv.older_copies()] == [ + ("zimi_almanac_maxi_2026-11.zim", "zimi_almanac_maxi_2026-11b.zim") + ] + assert old.exists() and new.exists() + + +def test_data_packs_are_one_almanac_hd_row_with_their_parts(lib): + for fname, name in ( + ("zimi_almanac_maxi_2026-11b.zim", "zimi_almanac_maxi"), + ("zimi_almanac_hd_moon_2026-11b.zim", "zimi_almanac_hd_moon"), + ("zimi_almanac_hd_mars_2026-11b.zim", "zimi_almanac_hd_mars"), + ): + build_fixture_zim(str(lib / fname), {"Name": name}) + build_fixture_zim(str(lib / "wikipedia_en_all_2026-10.zim"), {"Name": "wikipedia"}) + _scan() + row = almanachd.library_row() + assert [p["name"] for p in row["packs"]] == [ + "zimi_almanac_maxi", + "zimi_almanac_hd_moon", + "zimi_almanac_hd_mars", + ] + assert row["size_bytes"] == sum(p["size_bytes"] for p in row["packs"]) and all( + p["size_bytes"] > 0 for p in row["packs"] + ) + assert [p["part"] for p in row["packs"]] == ["", "moon", "mars"] + # Not rows of the library: what search and the listing walk leaves them out. + assert set(srv.content_zims()) == {"wikipedia", "zimi_almanac"} + assert not (set(srv.DATA_PACKS) & set(srv.content_zims())) + + +def test_almanac_hd_carries_the_almanacs_name_and_is_still_served(lib): + # The real file: the HD flavour has the Almanac's own Name metadata (almanachd), and the 3D view reads its tiles. + build_fixture_zim( + str(lib / "zimi_almanac_maxi_2026-11b.zim"), dict(ALMANAC_META, Flavour="maxi") + ) + zims = _scan() + assert zims["zimi_almanac"] == _own_path() + assert ( + os.path.basename(zims["zimi_almanac_maxi"]) == "zimi_almanac_maxi_2026-11b.zim" + ) + assert srv.older_copies() == [] + assert almanachd.status()["installed"] is True + + +def test_the_counts_agree_with_what_is_listed(lib): + from zimi import http + + build_fixture_zim( + str(lib / "zimi_eng_zimi_almanac_2026-11.zim"), + dict(ALMANAC_META, Date="2026-11"), + ) + build_fixture_zim( + str(lib / "zimi_almanac_hd_moon_2026-11b.zim"), {"Name": "zimi_almanac_hd_moon"} + ) + build_fixture_zim(str(lib / "wikipedia_en_all_2026-10.zim"), {"Name": "wikipedia"}) + _scan() + listed = [z["name"] for z in srv.list_zims() if z["name"] not in srv.DATA_PACKS] + assert sorted(listed) == ["wikipedia", "zimi_almanac"] + assert sorted(srv.content_zims()) == sorted(listed) + assert http is not None + + +def test_nothing_on_disk_is_touched(lib): + files = [ + "zimi_eng_zimi_almanac_2026-11.zim", + "zimi_almanac_maxi_2026-11.zim", + "zimi_almanac_maxi_2026-11b.zim", + ] + for f in files: + build_fixture_zim( + str(lib / f), + ( + dict(ALMANAC_META, Date="2026-11") + if "eng" in f + else {"Name": "zimi_almanac_maxi"} + ), + ) + before = {f: (lib / f).stat() for f in files} + _scan() + srv.older_copies() + for f in files: + st = (lib / f).stat() + assert (st.st_size, st.st_mtime_ns) == ( + before[f].st_size, + before[f].st_mtime_ns, + ) + assert sorted(os.listdir(lib)) == sorted(files) + + +# ── the Library at 390 px ──────────────────────────────────────────────── + + +def _skip_without_browser(): + import zimi.renderer as renderer + + if not renderer.browser_available(): + pytest.skip("playwright + chromium are not usable here") + + +def test_the_library_at_390_lists_one_almanac_and_one_almanac_hd_row(lib): + _skip_without_browser() + from http.server import ThreadingHTTPServer + + from playwright.sync_api import sync_playwright + + from zimi.http import ZimHandler + + build_fixture_zim( + str(lib / "zimi_eng_zimi_almanac_2026-11.zim"), + dict(ALMANAC_META, Date="2026-11"), + ) + build_fixture_zim( + str(lib / "zimi_almanac_maxi_2026-11.zim"), + {"Name": "zimi_almanac_maxi", "Date": "2026-11"}, + ) + build_fixture_zim( + str(lib / "zimi_almanac_maxi_2026-11b.zim"), + {"Name": "zimi_almanac_maxi", "Date": "2026-11"}, + ) + build_fixture_zim( + str(lib / "zimi_almanac_hd_moon_2026-11b.zim"), {"Name": "zimi_almanac_hd_moon"} + ) + build_fixture_zim( + str(lib / "wikipedia_en_all_2026-10.zim"), + {"Name": "wikipedia", "Title": "Wikipedia"}, + ) + srv.load_cache(force=True) + httpd = ThreadingHTTPServer(("127.0.0.1", 0), ZimHandler) + threading.Thread(target=httpd.serve_forever, daemon=True).start() + base = "http://127.0.0.1:%d" % httpd.server_address[1] + try: + with sync_playwright() as pw: + br = pw.chromium.launch() + ctx = br.new_context( + viewport={"width": 390, "height": 844}, + has_touch=True, + is_mobile=True, + service_workers="block", + ) + pg = ctx.new_page() + pg.goto(base + "/") + pg.wait_for_selector("#q") + pg.evaluate("() => enterManage(null, 'library')") + pg.get_by_text("Library", exact=True).first.click() + pg.wait_for_selector(".ci-hd-group", timeout=30000) + titles = pg.evaluate( + "() => [...document.querySelectorAll('#manage-installed .ci-title')].map(e => e.innerText)" + ) + assert ( + len( + [t for t in titles if t.startswith("Almanac") and t != "Almanac HD"] + ) + == 1 + ), titles + assert titles.count("Almanac HD") == 1, titles + assert not [t for t in titles if "zimi_" in t], titles + # The HD row is the Almanac's: in its group, under its icon; every header counts the rows it shows. + groups = pg.evaluate( + """() => [...document.querySelectorAll('#manage-installed .manage-installed-group')].map(g => ({ + label: (g.querySelector('.ci-section-label') || {}).innerText || '', + rows: [...g.querySelectorAll('.catalog-item')].map(r => ({ title: r.querySelector('.ci-title').innerText, + icon: r.querySelector('.ci-icon').innerHTML })) }))""" + ) + home = [ + g for g in groups if "Almanac HD" in [r["title"] for r in g["rows"]] + ] + assert len(home) == 1, groups + titles_here = [r["title"] for r in home[0]["rows"]] + alm = [ + r + for r in home[0]["rows"] + if r["title"].startswith("Almanac") and r["title"] != "Almanac HD" + ] + assert ( + len(alm) == 1 + ), titles_here # beside the Almanac, not in a group of its own + hd = [r for r in home[0]["rows"] if r["title"] == "Almanac HD"][0] + assert hd["icon"] == alm[0]["icon"], (hd, alm) + for g in groups: + assert g["label"], g # no row outside a headed group + assert g["label"].split()[-1] == str(len(g["rows"])), g + # The files only once the row is opened. + assert pg.locator(".ci-hd-part").first.is_visible() is False + assert "zimi_almanac" not in pg.inner_text("#manage-installed") + parts = pg.evaluate( + "() => [...document.querySelectorAll('.ci-hd-part')].map(e => e.textContent)" + ) + assert len(parts) == 2 and any("moon" in p for p in parts), parts + pg.locator(".ci-hd-group summary, .ci-hd-files summary").first.click() + assert pg.locator(".ci-hd-part").first.is_visible() is True + assert pg.evaluate("document.documentElement.scrollWidth") <= 390 + # Older copies, with a remove, are in Settings > Server (Storage). + # Manage is open on Library: its Settings tab, Server section (Storage). + pg.evaluate("() => switchManageTab('settings')") + pg.wait_for_function("() => typeof switchMs === 'function' && document.querySelector('.ms-nav-item[data-ms=server]')", timeout=30000) + pg.evaluate("() => switchMs('server')") + # They fold to one line with a count (fee478a3): open it. + pg.locator("#ms-older summary").click(timeout=30000) + pg.wait_for_selector("#ms-older .catalog-item", timeout=30000) + older = pg.inner_text("#ms-older") + assert ( + "zimi_almanac_maxi_2026-11.zim" in older + and "zimi_eng_zimi_almanac_2026-11.zim" in older + ), older + assert pg.locator("#ms-older .ci-delete-btn").count() == 2 + br.close() + finally: + httpd.shutdown() + srv.release_zim_handles(list(srv.get_zim_files())) + + +def test_an_older_copy_in_another_programs_folder_does_not_break_the_scan(lib, tmp_path, monkeypatch): + """A copy of an own ZIM in a folder another program owns, not newer than the package's: the scan still answers, + the package's file keeps the name, and the copy is recorded as shadowed by it.""" + from zimi import libfolders + + other = tmp_path / "nomad" + other.mkdir() + copy = other / "zimi_eng_zimi_almanac_2026-11.zim" + build_fixture_zim(str(copy), dict(ALMANAC_META, Date="2026-11")) + monkeypatch.setenv(libfolders.ENV, str(other)) + zims = _scan() + assert zims["zimi_almanac"] == _own_path() + assert "zimi_eng_zimi_almanac" not in zims + assert libfolders._shadowed.get(os.path.normpath(str(copy))) == os.path.normpath(_own_path()) diff --git a/tests/test_manage_files_sum.py b/tests/test_manage_files_sum.py new file mode 100644 index 000000000..41ecb8fcb --- /dev/null +++ b/tests/test_manage_files_sum.py @@ -0,0 +1,17 @@ +"""The cache rows of Manage > Server say "N files, size" through the translated string, never in hard-coded English.""" + +import json +import os + +STATIC = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "zimi", "static") + + +def test_cache_rows_use_the_translated_files_sum(): + with open(os.path.join(STATIC, "manage.js"), encoding="utf-8") as f: + src = f.read() + assert "' files, '" not in src + for lang in ("en", "de", "fr", "es"): + path = os.path.join(STATIC, "i18n", lang + ".json") + if os.path.exists(path): + with open(path, encoding="utf-8") as f: + assert "{n}" in json.load(f)["older_copies_sum"], lang diff --git a/tests/test_manage_row_auto_update.cjs b/tests/test_manage_row_auto_update.cjs new file mode 100644 index 000000000..5c89a169a --- /dev/null +++ b/tests/test_manage_row_auto_update.cjs @@ -0,0 +1,67 @@ +// Manage > Installed: a ZIM's row carries the auto-updater's opt-out (the card +// menu no longer does). Shown only while auto-update is on and only for a ZIM +// the updater can reach; its state is the listing's `auto_update: false`. +// +// Run: node tests/test_manage_row_auto_update.cjs (exit 0 = pass) + +const fs = require('fs'); +const path = require('path'); +const vm = require('vm'); + +const root = path.join(__dirname, '..', 'zimi', 'static'); +const src = ['manage.js', 'app.js'].map((f) => fs.readFileSync(path.join(root, f), 'utf8')).join('\n'); +function extract(re, label) { + const m = src.match(re); + if (!m) throw new Error('could not extract ' + label); + return m[0]; +} +let failures = 0; +const ok = (label, cond, detail) => { + console.log((cond ? 'PASS ' : 'FAIL ') + label + (detail ? ' ' + detail : '')); + if (!cond) failures++; +}; + +const posts = []; +const zims = { a: { name: 'a', file: 'a_2026-01.zim' }, b: { name: 'b', file: 'b_2026-01.zim', auto_update: false } }; +const ctx = { + JSON, t: (k) => k, escAttr: (s) => String(s), + manageEnabled: true, _manageStatusData: { auto_update: { enabled: true } }, + _zimInfo: (n) => zims[n], + manageFetch: (url, o) => { posts.push([url, JSON.parse(o.body)]); return Promise.resolve({ ok: true }); }, + renderInstalled: () => { ctx.repainted = true; }, +}; +vm.createContext(ctx); +vm.runInContext(extract(/var _DATED_ZIM_FILE_RE = .*;/, 'dated'), ctx); +vm.runInContext(extract(/var _AU_GLYPH = .*;/, 'glyph'), ctx); +vm.runInContext(extract(/function _zimAutoUpdateBtn\(z\) \{[\s\S]*?\n\}/, '_zimAutoUpdateBtn'), ctx); +vm.runInContext(extract(/function _toggleZimAutoUpdate\(name\) \{[\s\S]*?\n\}/, '_toggleZimAutoUpdate'), ctx); + +const on = ctx._zimAutoUpdateBtn(zims.a), off = ctx._zimAutoUpdateBtn(zims.b); +ok('an updating ZIM shows a pressed button with a label', + /aria-pressed="true"/.test(on) && /aria-label="au_zim_toggle"/.test(on) && /title="au_zim_toggle"/.test(on)); +ok('a ZIM left alone shows it unpressed', /aria-pressed="false"/.test(off) && /ci-au-off/.test(off)); +ok('not for a local file the updater cannot reach', ctx._zimAutoUpdateBtn({ name: 'c', file: 'c.zim' }) === ''); +ok('not for a ZIM another program owns', ctx._zimAutoUpdateBtn({ name: 'd', file: 'd_2026-01.zim', external: 'NOMAD' }) === ''); +ctx._manageStatusData.auto_update.enabled = false; +ok('not while auto-update is off', ctx._zimAutoUpdateBtn(zims.a) === ''); +ctx._manageStatusData.auto_update.enabled = true; + +ctx._toggleZimAutoUpdate('a'); +ctx._toggleZimAutoUpdate('b'); +setTimeout(() => { + ok('pressing posts the opt-out, the other way for a ZIM already left alone', + JSON.stringify(posts) === JSON.stringify([ + ['/manage/auto-update-skip', { zim: 'a', skip: true }], + ['/manage/auto-update-skip', { zim: 'b', skip: false }]]), JSON.stringify(posts)); + ok('the listing entry follows and the list repaints', + zims.a.auto_update === false && !('auto_update' in zims.b) && ctx.repainted === true); + + const i18n = path.join(root, 'i18n'); + const files = fs.readdirSync(i18n).filter((f) => f.endsWith('.json')); + const orders = files.map((f) => { + const keys = Object.keys(JSON.parse(fs.readFileSync(path.join(i18n, f), 'utf8'))); + return keys.indexOf('au_zim_toggle') - keys.indexOf('zi_icon_full'); + }); + ok('the label exists in all ten languages, in the same place', files.length === 10 && orders.every((o) => o === 1), orders.join(',')); + process.exit(failures ? 1 : 0); +}, 20); diff --git a/tests/test_manage_split.py b/tests/test_manage_split.py index 7151dc596..898745074 100644 --- a/tests/test_manage_split.py +++ b/tests/test_manage_split.py @@ -12,6 +12,13 @@ STATIC = os.path.join(os.path.dirname(__file__), "..", "zimi", "static") DECL = re.compile(r"^(?:async\s+)?function\s+([\w$]+)|^(?:var|let|const)\s+([\w$]+)", re.M) STUB = re.compile(r"^function ([\w$]+)\(\) \{ return _manageThen\('\1', arguments\); \}$", re.M) +# A stub that does something itself until manage.js replaces it: drawing the top bar (every boot) must not load manage.js, +# and with no manage.js there is no selection bar to draw. Each is one line, declared by app.js and then by manage.js. +LOCAL_STUB = re.compile(r"^function (_renderSelectionBar)\(\) \{ var bar = document\.getElementById\('ci-selection-bar'\); if \(bar\) bar\.remove\(\); \}$", re.M) + + +def _stubs(app): + return set(STUB.findall(app)) | set(LOCAL_STUB.findall(app)) def _read(name): @@ -31,7 +38,7 @@ def _names(src): def test_every_stub_is_defined_by_manage_js(): - stubs = set(STUB.findall(_read("app.js"))) + stubs = _stubs(_read("app.js")) assert len(stubs) > 10 missing = stubs - _names(_read("manage.js")) assert not missing, f"stubs manage.js does not define: {sorted(missing)}" @@ -39,20 +46,20 @@ def test_every_stub_is_defined_by_manage_js(): def test_app_js_reaches_manage_js_only_through_stubs(): app = _read("app.js") - stubs = set(STUB.findall(app)) - without_stubs = STUB.sub("", app) + stubs = _stubs(app) + without_stubs = LOCAL_STUB.sub("", STUB.sub("", app)) crossed = (_names(_read("manage.js")) - stubs) & _code_words(without_stubs) assert not crossed, f"app.js uses names only manage.js declares: {sorted(crossed)}" def test_no_name_is_declared_in_both(): - stubs = set(STUB.findall(_read("app.js"))) + stubs = _stubs(_read("app.js")) both = (_names(_read("app.js")) & _names(_read("manage.js"))) - stubs assert not both, f"declared in app.js and manage.js: {sorted(both)}" def test_other_scripts_reach_manage_js_only_through_stubs(): - stubs = set(STUB.findall(_read("app.js"))) + stubs = _stubs(_read("app.js")) declared = _names(_read("manage.js")) - stubs for name in sorted(os.listdir(STATIC)): if not name.endswith(".js") or name in ("app.js", "manage.js", "sw.js"): @@ -66,7 +73,7 @@ def test_other_scripts_reach_manage_js_only_through_stubs(): def test_the_page_reaches_manage_js_only_through_stubs(): - stubs = set(STUB.findall(_read("app.js"))) + stubs = _stubs(_read("app.js")) with open(os.path.join(STATIC, "..", "templates", "index.html"), encoding="utf-8") as f: page = f.read() used = (_names(_read("manage.js")) - stubs) & set(re.findall(r"[A-Za-z_$][\w$]*", page)) diff --git a/tests/test_mdwiki_flavor_editions.cjs b/tests/test_mdwiki_flavor_editions.cjs index 5fb2f387b..973109c1e 100644 --- a/tests/test_mdwiki_flavor_editions.cjs +++ b/tests/test_mdwiki_flavor_editions.cjs @@ -54,6 +54,7 @@ const sandbox = { }; vm.createContext(sandbox); vm.runInContext( + extract(/const ZIMI_COMMUNITY_PREFIX = .*;/, 'ZIMI_COMMUNITY_PREFIX').replace('const ', 'var ') + '\n' + extract(/function _flavorToken\(url\)\s*\{[\s\S]*?\n\}/, '_flavorToken') + '\n' + extract(/function _newestPerFlavor\(list\)\s*\{[\s\S]*?\n\}/, '_newestPerFlavor') + '\n' + extract(/function variantLabel\(url, siblingUrls\)\s*\{[\s\S]*?\n\}/, 'variantLabel') + '\n' + diff --git a/tests/test_open_zim_live_browser.py b/tests/test_open_zim_live_browser.py index c14cb9cb7..ec5da6d8b 100644 --- a/tests/test_open_zim_live_browser.py +++ b/tests/test_open_zim_live_browser.py @@ -55,6 +55,8 @@ def served(tmp_path_factory): yield { "base": "http://127.0.0.1:%d" % httpd.server_address[1], "swap": lambda: (shutil.copy(tmp / "second.zim", target), srv.load_cache(force=True)), + # Back to the first edition: a rerun (CI retries a failed test) starts from where the test expects. + "reset": lambda: (shutil.copy(tmp / "first.zim", target), srv.load_cache(force=True)), } httpd.shutdown() srv.ZIM_DIR, srv.ZIMI_DATA_DIR = saved @@ -63,6 +65,7 @@ def served(tmp_path_factory): def test_a_replaced_zim_shows_new_at_the_same_place(served): from playwright.sync_api import sync_playwright + served["reset"]() with sync_playwright() as pw: br = pw.chromium.launch() pg = br.new_context(viewport={"width": 390, "height": 844}, service_workers="block").new_page() @@ -78,7 +81,7 @@ def test_a_replaced_zim_shows_new_at_the_same_place(served): seq0 = changes._seq served["swap"]() try: - pg.wait_for_function("() => { %s }" % ("const h = (%s)(); return h === 'second';" % heading), timeout=30000) + pg.wait_for_function("() => { %s }" % ("const h = (%s)(); return h === 'second';" % heading), timeout=90000) except Exception as e: # Where it stopped: did the server announce, did the window hear, did its list change? seen = pg.evaluate( diff --git a/tests/test_phone_pass_1150.cjs b/tests/test_phone_pass_1150.cjs index 1be7b68d2..222cf798b 100644 --- a/tests/test_phone_pass_1150.cjs +++ b/tests/test_phone_pass_1150.cjs @@ -52,7 +52,7 @@ ok('nothing calls the old offline key', !/catalog_offline_note/.test(src)); // 3. Capture, in every language, and no em dash in the strings added here. const dir = path.join(root, 'i18n'); const newKeys = ['ms_creator', 'catalog_stale_note', 'delete_games_confirm']; -for (const f of fs.readdirSync(dir)) { +for (const f of fs.readdirSync(dir).filter(f => f.endsWith('.json'))) { const d = JSON.parse(fs.readFileSync(path.join(dir, f), 'utf8')); ok(f + ': the Creator tab is renamed', f === 'en.json' ? d.ms_creator === 'Capture' : d.ms_creator !== 'Creator' && !!d.ms_creator); ok(f + ': new strings have no em dash', newKeys.every((k) => d[k] && !/—/.test(d[k]))); @@ -72,10 +72,15 @@ ok('Home\'s own-app tiles wear the line glyphs', !/_ownIconHtml\(_GAMES_ZIM, _GA ok('the count line carries no recency dots', !/_recencyDotsHtml/.test(src) && !/statsHtml = _recency/.test(src)); // 7. Zimi's category goes last, a monochrome mark. -const cats = vm.runInNewContext(extract(/function _catIcon\(paths\) \{[\s\S]*?\n\}/, '_catIcon') + '\n' + +const cats = vm.runInNewContext( + extract(/const COMMUNITY_ICON_PATHS = .*;/, 'COMMUNITY_ICON_PATHS').replace(/^const /, 'var ') + '\n' + + extract(/const COMMUNITY_CAT = .*;/, 'COMMUNITY_CAT').replace(/^const /, 'var ') + '\n' + + extract(/function communityIcon\(size\) \{[\s\S]*?\n\}/, 'communityIcon') + '\n' + + extract(/function _catIcon\(paths\) \{[\s\S]*?\n\}/, '_catIcon') + '\n' + extract(/const BROWSE_CATEGORIES = \[[\s\S]*?\n\];/, 'BROWSE_CATEGORIES').replace(/^const /, 'var ') + '\nBROWSE_CATEGORIES'); -ok('Zimi is the last category', cats[cats.length - 1].key === 'zimi', cats.map((c) => c.key).join(',')); -ok('its mark is a stroke in the category style', /stroke="currentColor"/.test(cats[cats.length - 1].icon) && !/ c.key === 'zimi'), cats.map((c) => c.key).join(',')); +ok('every category mark is drawn, not an image', cats.every((c) => !/= 0, f"the text box reaches {-gap:.0f}px under the ×" -def test_an_app_tile_has_a_menu_only_when_it_holds_more_than_open(page, zimi): +def test_every_app_tile_has_a_menu_with_an_about(page, zimi): _home(page, zimi) - # Signed out, an app with no ZIM of its own (Dictionary) has Open alone: no ⋯. The Almanac has its own ZIM. - feet = page.evaluate( - "() => { const was = _userSession; _userSession = null;" - " const r = [_appTileFootHtml('dictionary'), _appTileFootHtml('almanac')]; _userSession = was; return r; }" - ) - assert "card-more" not in feet[0], feet[0] - assert "card-more" in feet[1], feet[1] - # Every ⋯ on the page opens more than Open (read in one go: Home redraws its tiles as the library settles). - menus = page.evaluate("""() => [...document.querySelectorAll('.app-tile:not(.app-empty) .card-more')].map(btn => { - _cardMore(btn); - const n = [...document.querySelectorAll('#zim-ctx-menu > .ctx-item')].length; + # "I want ... menu on every tile on homepage, every app". A square tile wears no ⋯: its menu is + # the one a right click or a long press opens, with Open and an About (read in one go: Home redraws its tiles as the + # library settles). + menus = page.evaluate("""() => [...document.querySelectorAll('.app-tile:not(.app-empty)')].map(tile => { + const r = tile.getBoundingClientRect(); + tile.querySelector('.card-icon').dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: r.left + 20, clientY: r.top + 20 })); + const acts = [...document.querySelectorAll('#zim-ctx-menu > .ctx-item')].map(i => i.dataset.action); _closeMenu(); - return [btn.closest('.app-tile').dataset.app, n]; + return [tile.dataset.app, acts]; })""") assert menus, "no app tile has a menu" - one = [app for app, n in menus if n < 2] - assert not one, f"a menu of one item: {one}" + bad = [app for app, acts in menus if "app-open" not in acts or "about-app" not in acts] + assert not bad, f"a tile whose menu lacks Open or About: {bad}" def test_a_discover_card_whose_picture_fails_keeps_a_picture_of_its_source(page, zimi): diff --git a/tests/test_red_theme_browser.py b/tests/test_red_theme_browser.py index 506962f78..186e1554b 100644 --- a/tests/test_red_theme_browser.py +++ b/tests/test_red_theme_browser.py @@ -194,6 +194,18 @@ def test_red_holds_over_a_zims_own_page_in_the_reader_frame(base, phone): ) +def test_a_page_that_took_red_for_itself_gets_no_filter_over_it(base, phone): + """ZimiGames draws Red from its own tokens (night-red on its ): the reader frame must not dim it again.""" + phone.add_init_script("try{localStorage.setItem('%s','red')}catch(e){}" % THEME_KEY) + _open(phone, base, ARTICLE) + frame = _reader_frame(phone) + assert "night-filter" in (frame.get_attribute("class") or "") + phone.evaluate("document.getElementById('reader-frame').contentDocument.documentElement.classList.add('night-red')") + phone.evaluate("_syncFrameNight(null)") + assert "night-filter" not in (phone.query_selector("#reader-frame").get_attribute("class") or "") + assert phone.evaluate("_docBroughtRed(document.getElementById('reader-frame').contentDocument)") is True + + @pytest.mark.fieldguide_on def test_red_holds_in_an_app_page_the_reader_frame_shows(base, phone): phone.add_init_script("try{localStorage.setItem('%s','red')}catch(e){}" % THEME_KEY) diff --git a/tests/test_scrollbars_hover_live.py b/tests/test_scrollbars_hover_live.py new file mode 100644 index 000000000..451ac46e5 --- /dev/null +++ b/tests/test_scrollbars_hover_live.py @@ -0,0 +1,101 @@ +"""Sideways scrollers show their bar on hover to a mouse, and never to a finger ("on Macs, the scroll bar +usually shows up when you hover over a scrollable area. Make sure that's all working"). + +One rule draws it everywhere (tokens.css hscroll, and its twin in the games' games.css): at 1367px with a mouse, a Home +row and a games shelf row have a real bar that takes room (macOS's own bars are overlays, shown only while scrolling, so +the bar is one of our own, a classic one), clear until the pointer is over the row and coloured then, and the row does +not change height when it shows; at 390px on a phone there is no bar at all. Chromium runs with its bars drawn +(--hide-scrollbars off), so the test measures what a person sees; SHOTS=dir keeps a picture of each row on hover. + +Run: ZIMI_TORRENT=0 ZIMI_OFFLINE=1 pytest tests/test_scrollbars_hover_live.py -v +""" + +import functools +import http.server +import os +import sys +import threading + +import pytest + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from test_home_layout_live import HOME, served # noqa: E402,F401 + +GAMES = os.path.join( + os.path.dirname(os.path.dirname(os.path.abspath(__file__))), + "zimi", + "builtin", + "games", +) +DESK = dict(viewport={"width": 1367, "height": 900}) +PHONE = dict(viewport={"width": 390, "height": 844}, is_mobile=True, has_touch=True) +SHOTS = os.environ.get("SHOTS", "") +# The bar's room (the row's height less its inside), and the colour its thumb takes from the row (--hs-now: Chrome +# repaints a thumb whose colour comes from the row's own style, not one styled by row:hover::-webkit-scrollbar-thumb). +BAR = r"""(sel) => { const el = document.querySelector(sel); + return { room: el.offsetHeight - el.clientHeight, thumb: getComputedStyle(el).getPropertyValue('--hs-now').trim(), h: el.offsetHeight }; }""" + + +@pytest.fixture(scope="module") +def games_site(): + class Quiet(http.server.SimpleHTTPRequestHandler): + def log_message(self, *a): + pass + + httpd = http.server.ThreadingHTTPServer( + ("127.0.0.1", 0), functools.partial(Quiet, directory=GAMES) + ) + threading.Thread(target=httpd.serve_forever, daemon=True).start() + yield "http://127.0.0.1:%d" % httpd.server_address[1] + httpd.shutdown() + + +def _home(pg, served): + pg.goto(served + "/") + pg.wait_for_function(HOME, timeout=30000) + pg.wait_for_selector("#discover-row .discover-scroll .discover-card", timeout=15000) + pg.wait_for_timeout(600) # Home draws its rows again as its late data lands + # A small library's Discover row fits 1367px; more cards (copies of its own) make it scroll, as a real one does. + pg.evaluate( + "() => { const r = document.querySelector('#discover-row .discover-scroll'), c = r.querySelector('.discover-card');" + " for (let i = 0; i < 6; i++) r.appendChild(c.cloneNode(true)); }" + ) + return "#discover-row .discover-scroll" + + +def _games(pg, games_site): + pg.add_init_script("localStorage.setItem('zimi.games.view','lobby')") + pg.goto(games_site + "/index.html") + pg.wait_for_selector(".ar-world .ar-game") + return ".ar-world .ar-games" + + +@pytest.mark.parametrize("where", ["home", "games"]) +def test_a_mouse_sees_the_bar_on_hover_a_finger_never(served, games_site, where): + from playwright.sync_api import sync_playwright + + with sync_playwright() as pw: + br = pw.chromium.launch(ignore_default_args=["--hide-scrollbars"]) + try: + for opts, mouse in ((DESK, True), (PHONE, False)): + pg = br.new_context(color_scheme="dark", **opts).new_page() + row = _home(pg, served) if where == "home" else _games(pg, games_site) + pg.evaluate("(s) => document.querySelector(s).scrollIntoView({ block: 'center' })", row) + pg.mouse.move(2, 2) + pg.wait_for_timeout(100) + away = pg.evaluate(BAR, row) + if not mouse: + assert away["room"] == 0, (where, away) + continue + assert away["room"] > 0 and away["thumb"] == "transparent", (where, away) + box = pg.locator(row).bounding_box() + pg.mouse.move(box["x"] + box["width"] / 2, box["y"] + box["height"] / 2) + pg.wait_for_timeout(100) + over = pg.evaluate(BAR, row) + if SHOTS: + clip = {"x": box["x"], "y": box["y"] - 8, "width": 700, "height": box["height"] + 16} + pg.screenshot(path=os.path.join(SHOTS, "bar-%s-hover.png" % where), clip=clip) + assert over["room"] > 0 and over["thumb"] not in ("", "transparent"), (where, over) + assert over["h"] == away["h"], "the row keeps its height when the bar shows: %s %s" % (away, over) + finally: + br.close() diff --git a/tests/test_search_chips_live.py b/tests/test_search_chips_live.py index a1384b0a7..f0062cee4 100644 --- a/tests/test_search_chips_live.py +++ b/tests/test_search_chips_live.py @@ -127,10 +127,10 @@ def test_chips_and_help_fit_a_phone(served, lang): assert help_.is_visible() assert pg.evaluate(_FIT) == [] - # Typing: the "?" and the × side by side, neither on the words. + # Typing: the "?" steps aside so the × has the box's end to itself, and neither sits on the words. pg.locator("#q").tap() pg.locator("#q").fill(QUERY) - assert help_.is_visible() and pg.locator("#search-clear").is_visible() + assert not help_.is_visible() and pg.locator("#search-clear").is_visible() assert pg.evaluate(_FIT) == [] # The search: one chip per operator, all on the screen. @@ -173,11 +173,12 @@ def test_chips_and_help_fit_a_phone(served, lang): if lang == "he": assert "פאנל סולארי" in first assert pg.evaluate(_FIT) == [] - examples.nth(1).tap() # the exclusion - pg.wait_for_selector("#output .search-chips") + examples.nth(1).tap() # the exclusion: its syntax goes into the box, to be sent assert pg.evaluate("document.getElementById('q').value") == pg.evaluate( "t('search_example_without')" ) + pg.keyboard.press("Enter") + pg.wait_for_selector("#output .search-chips") assert pg.evaluate(_FIT) == [] # The catalog: the same chips under its count, the same "?". @@ -219,7 +220,8 @@ def test_chips_and_help_fit_a_phone(served, lang): assert pg.locator("#catalog-results .search-chip").count() == 2 pg.evaluate("document.activeElement.blur()") assert pg.evaluate(_FIT) == [] - pg.locator("#q").tap() + pg.locator("#q").fill("") # the "?" waits while something is typed + pg.evaluate("document.activeElement.blur()") help_.tap() assert pg.locator("#suggest-dropdown .search-example").count() == 3 assert pg.evaluate(_FIT) == [] diff --git a/tests/test_section_label_browser.py b/tests/test_section_label_browser.py new file mode 100644 index 000000000..b8dac218b --- /dev/null +++ b/tests/test_section_label_browser.py @@ -0,0 +1,94 @@ +"""One section label: the heading of a list on Home and in every app is drawn the same (13px, strong, caps, the quiet ink), +whatever file styles the page around it. + +Run: pytest tests/test_section_label_browser.py -v +""" + +import os +import re +import sys + +import pytest + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +import zimi.renderer as renderer # noqa: E402 + +STATIC = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "zimi", "static") +LABELS = ( + '
Maps
', + '
Discover
', + '

Subjects

', + '
Answers
', + '

Picture of the day

', + '

English

', + '

More

', +) +STYLE = ( + "e => { const c = getComputedStyle(e); " + "return [c.fontFamily === getComputedStyle(document.body).fontFamily, c.fontSize, c.fontWeight, c.textTransform, c.letterSpacing]; }" +) + + +def _read(name): + with open(os.path.join(STATIC, name), encoding="utf-8") as f: + return f.read() + + +@pytest.fixture(scope="module") +def page(): + if not renderer.browser_available(): + pytest.skip("playwright + chromium are not usable here") + from playwright.sync_api import sync_playwright + + with sync_playwright() as p: + b = p.chromium.launch() + yield b.new_page(viewport={"width": 390, "height": 844}) + b.close() + + +@pytest.mark.parametrize("sheet", ["app.css", "apps.css"]) +def test_every_section_label_is_drawn_the_same(page, sheet): + # A page's own styles are in its html; the shared sheet and the tokens are what must agree, and its serif class is + # the wiki's own (.serif sets a family). + css = _read("tokens.css") + _read(sheet) + ".serif { font-family: Georgia, serif; }" + page.set_content("%s" % (css, "".join(LABELS))) + seen = set() + for sel in (".cat-heading", ".discover-label", ".shelf-h h2", ".section-h", ".sec-h h2", ".lang-h h2", ".fg-h2"): + style = page.eval_on_selector(sel, STYLE) + # discover-label is the span's parent: its own text is the label. + seen.add(tuple(style)) + assert len(seen) == 1, seen + assert next(iter(seen))[1:4] == ("13px", "600", "uppercase") + + +def test_no_page_restyles_a_section_label(): + for name in ("wiki.html", "dictionary.html", "fieldguide.html", "books.html", "exchange.html", "reddot.html"): + src = _read(name) + for m in re.finditer(r"\.(?:sec-h h2|lang-h h2|shelf-h h2|fg-h2|section-h)\s*\{([^}]*)\}", src): + assert not re.search(r"font-size|font-weight|text-transform|letter-spacing|color", m.group(1)), (name, m.group(0)) + + +def _decl(css, selector, prop): + m = re.search(r"(?:^|\n)%s \{([^}]*)\}" % re.escape(selector), css) + assert m, selector + v = re.search(r"(?:^|[;\s])%s:\s*([^;]+);" % prop, m.group(1)) + return v.group(1).strip() if v else None + + +def test_the_almanac_and_the_games_use_the_same_label(): + """Their standalone ZIMs carry no tokens, so each writes the label's values out; they must stay Zimi's.""" + games = _read(os.path.join("..", "builtin", "games", "games.css")) + alm = _read("almanac.css") + want = {"font-size": "13px", "font-weight": "600", "letter-spacing": "0.06em", "text-transform": "uppercase"} + for css, selector in ((games, ".ar-section h2"), (alm, ".almanac-section-title"), (alm, ".alm-tiles-h")): + got = {p: _decl(css, selector, p) for p in want} + got["font-size"] = {"var(--fs-small)": "13px"}.get(got["font-size"], got["font-size"]) + assert got == want, (selector, got) + tokens = _read("tokens.css") + assert "font-size: var(--fs-small)" in tokens and "letter-spacing: 0.06em" in tokens and "text-transform: uppercase" in tokens + + +def test_the_games_all_chip_is_amber_when_chosen_like_the_others(): + games = _read(os.path.join("..", "builtin", "games", "games.css")) + assert "sh-chip-all[aria-pressed" not in games diff --git a/tests/test_settings_overflow_live.py b/tests/test_settings_overflow_live.py index 566ecbf17..631820b9d 100644 --- a/tests/test_settings_overflow_live.py +++ b/tests/test_settings_overflow_live.py @@ -142,7 +142,13 @@ def check(label, root=".manage-wrap"): for i in range(pg.locator("#create-modes .create-chip").count()): chip = pg.locator("#create-modes .create-chip").nth(i) if chip.is_enabled(): - chip.click() + try: + chip.click(timeout=5000) + except Exception: + # A chip that needs the internet is turned off a moment after the picker opens (what is offline is read from the server). + if chip.is_enabled(): + raise + continue check("create-%d" % i, "#create-picker") pg.close() br.close() diff --git a/tests/test_settings_polish_live.py b/tests/test_settings_polish_live.py index 258bf2636..f7bdf1e0a 100644 --- a/tests/test_settings_polish_live.py +++ b/tests/test_settings_polish_live.py @@ -214,13 +214,14 @@ def bt_off(route): pg.route("**/manage/mirror*", bt_off) pg.goto(served + "/?manage=server") pg.wait_for_selector("#ms-mirror-status input[onchange*=torrent]", state="attached", timeout=15000) - pg.wait_for_selector("#ms-dl-schedule .needs-bt", state="attached", timeout=15000) + pg.wait_for_selector("#ms-dl-schedule .ms-dl-speed", state="attached", timeout=15000) + # Restrict uploads rides the nightly window: with the window off it is not drawn at all. got = pg.evaluate( """() => ({ off: document.getElementById('ms-pane').classList.contains('ms-bt-off'), mirror: !!(document.querySelector('#ms-mirror-status input[onchange*=mirror]') || {}).offsetParent, - upload: !!document.querySelector('#ms-dl-schedule .needs-bt').offsetParent })""" + upload: document.querySelectorAll('#ms-dl-schedule .needs-bt').length })""" ) - assert got == {"off": True, "mirror": False, "upload": False}, got + assert got == {"off": True, "mirror": False, "upload": 0}, got def test_every_settings_on_off_is_a_switch(served, phone): diff --git a/tests/test_settings_rows_scroll_sideways_browser.py b/tests/test_settings_rows_scroll_sideways_browser.py new file mode 100644 index 000000000..e972b3d00 --- /dev/null +++ b/tests/test_settings_rows_scroll_sideways_browser.py @@ -0,0 +1,40 @@ +"""Settings' row of panes (Library, Display, Languages, Capture...) and the Manage tabs scroll sideways only: the 44px touch +boxes the pills reach for must not make the rows scrollable up and down too. + +Run: pytest tests/test_settings_rows_scroll_sideways_browser.py -v +""" + +import os +import sys + +import pytest + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +import zimi.renderer as renderer # noqa: E402 + +STATIC = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "zimi", "static") + + +@pytest.fixture(scope="module") +def phone(): + if not renderer.browser_available(): + pytest.skip("playwright + chromium are not usable here") + from playwright.sync_api import sync_playwright + + with sync_playwright() as p: + b = p.chromium.launch() + ctx = b.new_context(viewport={"width": 390, "height": 844}, has_touch=True, is_mobile=True) + yield ctx.new_page() + b.close() + + +def test_the_rows_have_no_vertical_scroll(phone): + css = "".join(open(os.path.join(STATIC, n), encoding="utf-8").read() for n in ("tokens.css", "app.css")) + items = "".join("" % (c, i) for c, i in (("ms-nav-item", n) for n in range(8))) + tabs = "".join("" % n for n in range(8)) + phone.set_content("" + "
%s
%s
" % (css, items, tabs)) + for sel in ("#n", "#t"): + info = phone.eval_on_selector(sel, "e => [getComputedStyle(e).overflowY, e.scrollWidth > e.clientWidth]") + assert info == ["hidden", True], (sel, info) diff --git a/tests/test_settings_tabs.cjs b/tests/test_settings_tabs.cjs index a65ce4995..21978192b 100644 --- a/tests/test_settings_tabs.cjs +++ b/tests/test_settings_tabs.cjs @@ -28,7 +28,7 @@ const msKeys = [...src.matchAll(/class="ms-nav-item[^"]*" data-ms="\w+"[^>]*>' \ ok('both rows of tabs are found', manageKeys.length >= 5 && msKeys.length >= 4, manageKeys + ' / ' + msKeys); const dir = path.join(root, 'static', 'i18n'); -for (const f of fs.readdirSync(dir)) { +for (const f of fs.readdirSync(dir).filter(f => f.endsWith('.json'))) { const d = JSON.parse(fs.readFileSync(path.join(dir, f), 'utf8')); const names = manageKeys.concat(msKeys).map((k) => (d[k] || '').trim().toLowerCase()); const twice = names.filter((n, i) => n && names.indexOf(n) !== i); @@ -41,7 +41,7 @@ ok('...and the Server pane keeps only the server\'s backup', /_serverBackupCardH // Cut: a keyboard key in the empty Saved panel (a phone has none), and the // Reader View switch's subtitle that only said its title again. -for (const f of fs.readdirSync(dir)) { +for (const f of fs.readdirSync(dir).filter(f => f.endsWith('.json'))) { const d = JSON.parse(fs.readFileSync(path.join(dir, f), 'utf8')); ok(f + ': the empty Saved panel names no key', !/\bB\b/.test(d.no_bookmarks || 'B')); ok(f + ': no "Open articles in Reader View" under "Always use Reader View"', !('reader_auto_hint' in d)); diff --git a/tests/test_topbar_tap_live.py b/tests/test_topbar_tap_live.py index 3b99c8834..b5cb9318f 100644 --- a/tests/test_topbar_tap_live.py +++ b/tests/test_topbar_tap_live.py @@ -155,7 +155,7 @@ def test_a_tap_on_the_bar_takes_the_almanac_to_its_top(served): try: pg.goto(base + "/#almanac") pg.wait_for_function( - "() => { const c = document.getElementById('almanac-content'); return !_almVeilIsUp() && c && c.scrollHeight > 3000; }", + "() => { const c = document.getElementById('almanac-content'); return (typeof _almShownAt !== 'undefined' && _almShownAt > 0 && !_almSkyHold()) && c && c.scrollHeight > 3000; }", timeout=30000, ) pg.evaluate( @@ -253,13 +253,13 @@ def test_a_tap_on_the_bar_takes_the_almanac_to_its_top(served): "dictionary": ("() => openDictionary()", APP, None, False), "almanac": ( "() => openAlmanac()", - "() => { const c = document.getElementById('almanac-content'); return !_almVeilIsUp() && c && c.scrollHeight > 3000; }", + "() => { const c = document.getElementById('almanac-content'); return (typeof _almShownAt !== 'undefined' && _almShownAt > 0 && !_almSkyHold()) && c && c.scrollHeight > 3000; }", None, False, ), "a-table-over-the-scrolled-almanac": ( "() => openAlmanac()", - "() => !_almVeilIsUp() && document.getElementById('alm-group-tables')", + "() => (typeof _almShownAt !== 'undefined' && _almShownAt > 0 && !_almSkyHold()) && document.getElementById('alm-group-tables')", "() => { document.getElementById('almanac-content').scrollTop = 1500; _almRefOpen('sunmoon'); }", False, ), @@ -357,9 +357,9 @@ def test_a_tap_on_the_bar_takes_every_view_to_its_top(library, view): k: v for k, v in pg.evaluate(SCROLLED).items() if behind.get(k) != v } assert moved, "the view scrolled" - # The header steps aside only while an article is read. + # The header stays while reading, scrolling or turning pages (7e7b7bb8d), an article included. away = pg.evaluate("() => document.body.classList.contains('chrome-away')") - assert away == reading, (view, away) + assert not away, (view, away) pg.evaluate("() => document.body.classList.remove('chrome-away')") pg.wait_for_timeout(400) spot = pg.evaluate(EMPTY_SPOT) diff --git a/tests/test_touch_areas_live.py b/tests/test_touch_areas_live.py new file mode 100644 index 000000000..271c7a844 --- /dev/null +++ b/tests/test_touch_areas_live.py @@ -0,0 +1,126 @@ +"""Every control on a phone's first screens has a hit area a finger can find, and the count of ones that do not only goes down. + +"enlarge the touch area only": the look and the layout stay, the box a tap lands on grows to 44x44 CSS px (an +invisible ::after, app.css's coarse-pointer block). tests/hit_probe.js walks the screen's buttons, links, inputs and +[onclick] elements at 390 px and finds where a tap really lands on each (elementFromPoint, so a hit box counts and one a +neighbour covers does not). A screen may keep at most FLOORS[screen] controls under 44x44: what is left is a control that +cannot grow without moving pixels (the search box is 40 tall, the three buttons at the bar's end are 6px apart, a menu's +rows are stacked, a date's parts are the Almanac's editor). + +Run: pytest tests/test_touch_areas_live.py -v +""" + +import os +import sys +import threading +import time + +import pytest + +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 zimi.renderer as renderer # noqa: E402 +import zimi.server as srv # noqa: E402 +from test_home_apps_live import HOME, LIBRARY # noqa: E402 + +pytestmark = pytest.mark.fieldguide_on +DAY = 86400 +PROBE = "\n".join( + line + for line in open( + os.path.join(os.path.dirname(os.path.abspath(__file__)), "hit_probe.js"), + encoding="utf-8", + ) + .read() + .splitlines() + if not line.startswith("//") +) +# screen: (library view, what to do first, most controls allowed under 44x44) +SCREENS = { + "home-list": ("list", "", 3), + "home-tiles": ("tiles", "", 2), + "reader": ("list", "openArticle('water', 'A/Water_purification', 'Water')", 1), + # 13: a Linux font is narrower, so the last settings tab (Access) starts on the screen and is counted; a Mac font pushes it off + "manage": ("list", "toggleManage()", 13), + "tube": ("list", "openTube()", 1), +} + + +@pytest.fixture(scope="module") +def served(tmp_path_factory): + if not renderer.browser_available(): + pytest.skip("playwright + chromium are not usable here") + from http.server import ThreadingHTTPServer + + from conftest_zim import build_fixture_zim + + from zimi.http import ZimHandler + + tmp = tmp_path_factory.mktemp("touch") + zdir = tmp / "zims" + zdir.mkdir() + for filename, meta, _ in LIBRARY: + build_fixture_zim(str(zdir / filename), meta) + mp = pytest.MonkeyPatch() + mp.setenv("ZIMI_APPS", ",".join(srv.APP_NAMES)) + mp.setenv("ZIMI_OFFLINE", "1") + mp.setattr(srv, "ZIM_DIR", str(zdir)) + mp.setattr(srv, "ZIMI_DATA_DIR", str(tmp / "data")) + os.makedirs(str(tmp / "data"), exist_ok=True) + srv.load_cache(force=True) + now = time.time() + by_file = {srv._zim_short_name(f): when for f, _, when in LIBRARY} + for z in srv._zim_list_cache: + if z["name"] in by_file: + days, hours, entries = by_file[z["name"]] + z["first_seen"] = now - days * DAY + z["updated_at"] = now - hours * 3600 if hours else None + z["entries"] = entries + httpd = ThreadingHTTPServer(("127.0.0.1", 0), ZimHandler) + threading.Thread(target=httpd.serve_forever, daemon=True).start() + yield "http://127.0.0.1:%d" % httpd.server_address[1] + httpd.shutdown() + mp.undo() + + +@pytest.mark.parametrize("screen", sorted(SCREENS)) +def test_a_finger_finds_every_control_it_can(served, screen): + from playwright.sync_api import sync_playwright + + view, act, floor = SCREENS[screen] + with sync_playwright() as pw: + br = pw.chromium.launch() + ctx = br.new_context( + viewport={ + "width": 390, + "height": 3000 if screen.startswith("home") else 844, + }, + is_mobile=True, + has_touch=True, + ) + ctx.add_init_script("localStorage.setItem('zimi_library_view','%s');" % view) + pg = ctx.new_page() + try: + pg.goto(served + "/") + pg.wait_for_function(HOME, timeout=30000) + pg.wait_for_timeout(600) + if act: + pg.evaluate("() => { %s; }" % act) + pg.wait_for_timeout(2500) + got = pg.evaluate(PROBE) + assert got["total"] >= 6, got # the screen opened (reading, the bar gives the source mark's room to the box: 28b22ba71) + assert ( + got["small"] <= floor + ), "%s: %d controls under 44x44 (floor %d): %s" % ( + screen, + got["small"], + floor, + got["list"], + ) + # The ⋯ on a Home tile is never one of them. + assert not [ + x for x in got["list"] if "card-more" in x or "dc-more" in x + ], got["list"] + finally: + br.close() diff --git a/tests/test_tube_surface.cjs b/tests/test_tube_surface.cjs index ef60a55c1..057ff7cd0 100644 --- a/tests/test_tube_surface.cjs +++ b/tests/test_tube_surface.cjs @@ -35,7 +35,7 @@ const ctx = { _userSession: null, document: { body: { dataset: {} } }, _zimInfo: name => ctx.zimsCache.find(z => z.name === name) || null, // Zimi's own tiles: the ZIM's icon, its new-dot and the pet's peek are not what this file judges. - _ownIconHtml: (zim, glyph) => glyph, _appTileFootHtml: () => '', OWN_TILE_ICON_PX: 42, _petPeekSchedule() {}, _petPeek: null, + _ownIconHtml: (zim, glyph) => glyph, _appTileFootHtml: () => '', _appTileDotHtml: () => '', OWN_TILE_ICON_PX: 42, _petPeekSchedule() {}, _petPeek: null, }; vm.createContext(ctx); vm.runInContext(require("./app_source.cjs").localeHelpers(src), ctx); @@ -81,7 +81,7 @@ require('./apps_order_parts.cjs')(src, ctx); // ── the apps row ───────────────────────────────────────────────────────── const row = ctx._appsRowHtml(); -ok('one row holds the apps, each a tile like a source', /class="stats-grid apps-grid">/.test(row) && /maps-tile/.test(row) && /tube-tile/.test(row)); +ok('one row holds the apps, each a tile like a source', /class="stats-grid apps-grid pick-tiles">/.test(row) && /maps-tile/.test(row) && /tube-tile/.test(row)); ok('the ZimiTube tile names the video ZIMs', /ZimiTube<\/span>/.test(row) && /TED Talks – Technology/.test(row) && /href="#tube"/.test(row)); ctx.zimsCache = ctx.zimsCache.filter(z => z.kind !== 'video'); ok('no video ZIM: home leaves ZimiTube out, its tile still the door to the Video category', !/tube-tile/.test(ctx._appsRowHtml()) && /No videos yet/.test(ctx._tubeTileHtml()) && /_openCategory\(_APP_CATEGORY\.tube\)/.test(ctx._tubeTileHtml())); @@ -170,7 +170,7 @@ ok('strings arrive in the hash, escaped on the way in', //.test ok('leaving the player with a video playing docks it, and a tap brings it back', /function closePlayer\(silent\)/.test(page) && /dock-stage'\)\.appendChild\(v\)/.test(page) && /function undock\(\)/.test(page) && /function stopDock\(\)/.test(page) && /id="dock" hidden onclick="undock\(\)"/.test(page)); ok('theater mode is remembered and picture in picture appears only where the browser has it', /zimitube_theater/.test(page) && /player\.theater/.test(page) && /function pipAvailable\(v\)/.test(page) && /webkitSetPresentationMode/.test(page) && /requestPictureInPicture/.test(page)); ok('the page takes the shared sheet, which holds both themes', //.test(page) && !/prefers-color-scheme/.test(page)); -for (const lang of fs.readdirSync(path.join(__dirname, '..', 'zimi', 'static', 'i18n'))) { +for (const lang of fs.readdirSync(path.join(__dirname, '..', 'zimi', 'static', 'i18n')).filter(f => f.endsWith('.json'))) { const d = JSON.parse(fs.readFileSync(path.join(__dirname, '..', 'zimi', 'static', 'i18n', lang), 'utf8')); for (const k of ['tube', 'tube_search_placeholder', 'tube_videos', 'tube_sources', 'tube_more', 'tube_none', 'tube_empty', 'tube_up_next', 'tube_autoplay', 'tube_theater', 'tube_pip', 'tube_open_page', 'tube_sort_top', 'tube_no_media']) if (!d[k]) ok(k + ' in ' + lang, false); if (d.tube !== 'ZimiTube') ok('it is called ZimiTube in ' + lang, false); diff --git a/tests/test_wiki.py b/tests/test_wiki.py index e6883df24..211a9e119 100644 --- a/tests/test_wiki.py +++ b/tests/test_wiki.py @@ -665,6 +665,16 @@ def test_random_with_a_day_answers_the_wiki_s_pick(served): assert card["path"] == otd[0]["path"] +def test_the_card_a_page_is_given_is_the_word_said_ahead(served, monkeypatch): + """The browser asks for its own day; the word it is given is the one the server says ahead.""" + got = [] + monkeypatch.setattr(wiki, "say_card_ahead", lambda card: got.append(card)) + homes = _get(served + "/wiki/home")[1]["wikis"] + wikt = next(w["name"] for w in homes if w["project"] == "wiktionary") + status, card = _get(served + "/random?zim=%s&day=20260925" % wikt) + assert status == 200 and [c["title"] for c in got] == [card["title"]] + + def test_today_answers_for_the_wikis_named_and_home_carries_what_is_known( today_lib, monkeypatch ): diff --git a/tests/test_zim_info_endpoint.py b/tests/test_zim_info_endpoint.py index 12d7e5588..5795444a9 100644 --- a/tests/test_zim_info_endpoint.py +++ b/tests/test_zim_info_endpoint.py @@ -88,6 +88,8 @@ "Publisher": "openZIM", "Scraper": "devdocs2zim v0.2.1", "Tags": "devdocs;lit", + "License": "CC-BY-SA 4.0", + "Relation": "devdocs_en_lit_all", } @@ -229,6 +231,25 @@ def test_foreign_zim_shows_its_publishers_fields_and_no_history(self): # No Source was ever written, so none is claimed. self.assertEqual(info["source"], "") + def test_license_and_relation_are_rows_of_their_own(self): + status, info = self._get("/zim-info?zim=found") + self.assertEqual(info["license"], "CC-BY-SA 4.0") + self.assertEqual(info["relation"], "devdocs_en_lit_all") + other = info.get("other") or {} + self.assertNotIn("License", other) + self.assertNotIn("Relation", other) + root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + with open(os.path.join(root, "zimi", "static", "app.js"), encoding="utf-8") as f: + app = f.read() + i18n = os.path.join(root, "zimi", "static", "i18n") + for key in ("zi_license", "zi_relation"): + self.assertIn("_ziRow('%s'" % key, app) + for fn in os.listdir(i18n): + if not fn.endswith(".json"): + continue # i18n/almanac/ holds the Almanac's own strings + with open(os.path.join(i18n, fn), encoding="utf-8") as f: + self.assertTrue(json.load(f).get(key), (fn, key)) + def test_kinds_lists_only_the_zims_zimi_made(self): status, body = self._get("/zim-info?kinds=1") self.assertEqual(status, 200) diff --git a/tests/test_zimi_home_line_browser.py b/tests/test_zimi_home_line_browser.py deleted file mode 100644 index efe6fd30b..000000000 --- a/tests/test_zimi_home_line_browser.py +++ /dev/null @@ -1,251 +0,0 @@ -"""The credit line ("© Zimi" after the mark, Zimi a link), drawn where the Games and the Almanac are read outside Zimi -(Kiwix, a browser tab) and never inside Zimi's reader: under the shelf's title, the foot of a game's Menu, the Almanac's foot. -The address is written once, in games/zimihome.js (the Almanac's ZIM carries a copy); the year is the build's, zimibuild.js, -which ownzims writes into each ZIM beside its Date. The mark sits on the digits, measured. - -Run: ZIMI_TORRENT=0 ZIMI_OFFLINE=1 pytest tests/test_zimi_home_line_browser.py -v -""" - -import os -import re -import sys -import tempfile - -import pytest - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from test_games_persist_browser import GAMES, VIEW, browser, served # noqa: E402,F401 - - -def home_url(): - with open(os.path.join(GAMES, "zimihome.js"), encoding="utf-8") as f: - return re.search(r"ZIMI_HOME = '([^']+)'", f.read()).group(1) - - -# The mark's centre against the centre of the digits' height (baseline up to the top of "0"), in px: the optical seat. -MARK_OFFSET = """sel => { const line = document.querySelector(sel), img = line.querySelector('img'), span = line.querySelector('span'); - const probe = document.createElement('i'); probe.style.cssText = 'display:inline-block;width:0;height:0;vertical-align:baseline'; - span.appendChild(probe); const base = probe.getBoundingClientRect().bottom; probe.remove(); - const c = document.createElement('canvas').getContext('2d'); const cs = getComputedStyle(span); c.font = cs.fontWeight + ' ' + cs.fontSize + ' ' + cs.fontFamily; - const digits = c.measureText('0').actualBoundingBoxAscent; const r = img.getBoundingClientRect(); - return (r.top + r.height / 2) - (base - digits / 2); }""" - - -def test_outside_zimi_the_shelf_and_the_menu_credit_zimi(browser, served): - url = home_url() - ctx = browser.new_context(viewport=VIEW) - page = ctx.new_page() - # The year is the build's (zimibuild.js, which ownzims writes into the ZIM), never the reader's clock: a year no clock says. - page.route( - "**/zimibuild.js", - lambda r: r.fulfill( - body="window.ZIMI_BUILT_YEAR = 2031;\n", content_type="text/javascript" - ), - ) - page.goto("%s/index.html" % served) - line = page.wait_for_selector(".ar-shelf > .gs-home") - assert ( - line.is_visible() and line.inner_text().strip() == "© 2031 Zimi" - ), line.inner_text() - link = line.query_selector("a") - assert link.inner_text() == "Zimi" and link.get_attribute("href") == url - # The shelf's very last line: under Credits, nothing of the page below it. - below = page.evaluate( - "() => { const b = document.querySelector('.ar-shelf > .gs-home').getBoundingClientRect().bottom;" - " return Array.from(document.querySelectorAll('body *')).filter(e => e.offsetWidth && e.getBoundingClientRect().top >= b - 0.5" - " && !e.closest('.gs-home') && (e.innerText || '').trim()).map(e => e.innerText.trim().slice(0, 30)); }" - ) - assert below == [], below - assert page.evaluate( - "document.querySelector('.ar-shelf').lastElementChild.classList.contains('gs-home')" - ) - # The shipped default (zimihome.js ZIMI_HOME_MARK = 'none'): no mark in the line, the words alone. - assert line.query_selector("img") is None - page.goto("%s/chess.html" % served) - page.click(".gs-menu-btn") - menu_line = page.wait_for_selector(".gs-card .gs-home") - assert ( - menu_line.is_visible() - and menu_line.query_selector("a").get_attribute("href") == url - ) - assert "2031" in menu_line.inner_text() - assert menu_line.query_selector("img") is None - ctx.close() - - -def test_a_page_read_from_its_folder_has_no_year(browser, served): - ctx = browser.new_context(viewport=VIEW) - page = ctx.new_page() - page.goto("%s/index.html" % served) # no zimibuild.js in the source folder - line = page.wait_for_selector(".ar-shelf > .gs-home") - assert line.inner_text().strip() == "© Zimi" - ctx.close() - - -def test_the_build_writes_its_year_beside_the_date(): - import datetime - - from zimi import ownzims - from libzim.reader import Archive - - for own in ownzims.OWN: - archive = Archive(ownzims.zim_path(own)) - year = archive.get_metadata("Date").decode()[:4] - body = bytes( - archive.get_entry_by_path(ownzims.BUILD_FILE).get_item().content - ).decode() - assert body == "window.ZIMI_BUILT_YEAR = %s;\n" % year, (own.name, body) - assert int(year) <= datetime.date.today().year - - -def test_inside_zimis_reader_nothing_is_drawn(browser, served): - ctx = browser.new_context(viewport=VIEW) - page = ctx.new_page() - # Zimi's reader, as shell.js recognises it: a same-origin parent whose #reader-frame holds the page. - page.route( - "%s/host.html" % served, - lambda r: r.fulfill( - body='', - content_type="text/html", - ), - ) - page.goto("%s/host.html" % served) - frame = page.frame_locator("#reader-frame") - frame.locator(".ar-game").first.wait_for() - assert frame.locator(".gs-home").count() == 0 - inner = next(f for f in page.frames if f.url.endswith("/index.html")) - assert inner.evaluate("!!(window.ZimiShell && ZimiShell.hosted)") - assert inner.evaluate("typeof window.ZIMI_HOME") == "undefined" # not even fetched - ctx.close() - - -def test_the_almanac_carries_the_same_address(): - from zimi import almanacstage - - with tempfile.TemporaryDirectory() as tmp: - almanacstage.stage(tmp) - with ( - open(os.path.join(tmp, "zimihome.js"), encoding="utf-8") as f, - open(os.path.join(GAMES, "zimihome.js"), encoding="utf-8") as g, - ): - assert f.read() == g.read() - assert os.path.exists(os.path.join(tmp, "mark.svg")) - with open(os.path.join(tmp, "index.html"), encoding="utf-8") as f: - page = f.read() - assert ( - '' in page - and '' in page - ) - # The line is drawn by local.js: an href written in index.html's own script is a dead link to zimcheck. - assert "href=" not in page.split(" + + + + @@ -109,7 +144,7 @@