Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions tests/test_games_axe.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,8 @@ def scan(browser, served, path, width, theme, lang):
page.goto("%s/%s#lang=%s" % (served, path, lang))
page.wait_for_load_state("load")
quiet(page, 1200) # built: nothing changing, nothing animating (at most the 1.2 s this once waited)
if path != "index.html": # the shelf's middle is a game's tile at desktop width: a tap there leaves the page
page.mouse.click(width // 2, 420)
quiet(page, 500)
page.mouse.click(2, 2) # a gesture to wake the page, on no tile (the shelf's rows lie under the middle)
quiet(page, 500)
page.add_script_tag(content=AXE)
return page.evaluate(RUN)
finally:
Expand Down
211 changes: 201 additions & 10 deletions tests/test_games_bar_stable.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
"""The bar never shifts: Undo has its place from the first frame (disabled until a move), so Menu sits at the same x before
and after the first move, and a bar title localizes whenever it is the game's title, however the markup spells it.

Touch targets on a 390px phone: the shelf's controls give a finger 44 x 44, and a press on a grid of cells, a keyboard or a
fan of cards never lands in a gap between two of them (a dead gap is a second try).

Run: pytest tests/test_games_bar_stable.py -v
"""

Expand All @@ -14,6 +17,7 @@

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from games_wait import game_ready # noqa: E402
from hit_area import undersized # noqa: E402

pytest.importorskip("playwright")
from playwright.sync_api import sync_playwright # noqa: E402
Expand All @@ -32,21 +36,28 @@ def base():


@pytest.fixture(scope="module")
def browser():
def pw():
with sync_playwright() as p:
for kind in (p.webkit, p.chromium):
try:
b = kind.launch()
except Exception:
continue
yield b
b.close()
return
pytest.skip("no browser installed")
yield p


@pytest.fixture(scope="module")
def browser(pw):
for kind in (pw.webkit, pw.chromium):
try:
b = kind.launch()
except Exception:
continue
yield b
b.close()
return
pytest.skip("no browser installed")


def open_game(browser, base, name, width=390, **ctx):
c = browser.new_context(viewport={"width": width, "height": 844}, has_touch=True, is_mobile=True, **ctx)
# Five Letters opens its how-to-play sheet by itself on a first visit; these tests are past it.
c.add_init_script("localStorage.setItem('zimi.games.fiveletters.how', '{\"seen\":true}')")
page = c.new_page()
page.goto(base + "/" + name)
game_ready(page)
Expand Down Expand Up @@ -100,3 +111,183 @@ def straight(route):
fr = page.evaluate("ZimiText.T('game.holdem.title')")
assert page.locator(".ar-bar h1").inner_text() == fr
c.close()


# What cannot reach 44 on a phone is a physical grid (ten keys across, nine cells across): there the rule is no dead gap, the
# nearest cell takes the touch. Each game names the cell it is made of.
SEAM_GAMES = [
("sudoku.html", ".su-c"),
("go.html", ".go-pt"),
("fiveletters.html", ".fl-key"),
("minicrossword.html", ".cw-key"),
("mahjong.html", ".mj-t"),
("spider.html", ".zc-card, .zc-slot"),
("hearts.html", ".zc-card"),
]

_SEAMS = """(sel) => {
const cells = [...document.querySelectorAll(sel)].filter(e => e.offsetWidth && !e.closest('[hidden]'));
const box = (e) => e.getBoundingClientRect(), bad = [];
const hit = (x, y) => { const h = document.elementFromPoint(x, y); return !!h && !!h.closest(sel); };
// The middle of the gap between each cell and the next one on its row (and below it in its column).
for (const a of cells) {
const r = box(a);
for (const b of cells) {
if (a === b) continue;
const q = box(b), rows = Math.min(r.bottom, q.bottom) - Math.max(r.top, q.top), cols = Math.min(r.right, q.right) - Math.max(r.left, q.left);
if (rows > 4 && q.left >= r.right - 1 && q.left - r.right < 12) { const x = (r.right + q.left) / 2, y = (Math.max(r.top, q.top) + Math.min(r.bottom, q.bottom)) / 2; if (!hit(x, y)) bad.push([a.className, 'right', Math.round(x), Math.round(y)]); }
if (cols > 4 && q.top >= r.bottom - 1 && q.top - r.bottom < 12) { const y = (r.bottom + q.top) / 2, x = (Math.max(r.left, q.left) + Math.min(r.right, q.right)) / 2; if (!hit(x, y)) bad.push([a.className, 'below', Math.round(x), Math.round(y)]); }
}
}
return { n: cells.length, bad: bad.slice(0, 6) };
}"""


@pytest.mark.parametrize("game,cell", SEAM_GAMES)
def test_a_touch_between_two_cells_is_never_lost(browser, base, game, cell):
c, page = open_game(browser, base, game)
r = page.evaluate(_SEAMS, cell)
if "zc-" in cell:
# The card table takes a press in a gap for the pile nearest it: a press there lifts that pile's top card.
lost = []
for _name, _side, x, y in r["bad"]:
page.mouse.move(x, y)
page.mouse.down()
if not page.query_selector(".zc-drag"):
lost.append((x, y))
page.mouse.up()
r["bad"] = lost
c.close()
assert r["n"] > 4, r
assert not r["bad"], r


def test_the_shelf_gives_a_finger_44px(browser, base):
c = browser.new_context(viewport={"width": 390, "height": 844}, device_scale_factor=2, has_touch=True, is_mobile=True)
page = c.new_page()
page.goto(base + "/index.html")
page.wait_for_selector(".ar-shelf header", timeout=30000)
page.wait_for_timeout(1500)
short = undersized(page)
c.close()
assert not short, "\n".join(short)


# One game of each kind: its menu and the sheets the menu opens (Settings, How to play, History, Stats, About) give a finger 44.
SHEET_GAMES = ["chess.html", "solitaire.html", "sudoku.html", "snake.html", "flags.html", "yacht.html", "memory.html", "mahjong.html"]


@pytest.mark.parametrize("game", SHEET_GAMES)
def test_the_menu_and_its_sheets_give_a_finger_44px(browser, base, game):
c, page = open_game(browser, base, game)
short = []
page.evaluate("document.querySelector('.gs-menu-btn').click()")
page.wait_for_timeout(500)
short += undersized(page, noscroll=True)
sheet = ".ar-sheet button, .gs-sheet button, [role=dialog] button, [role=menu] button"
labels = page.evaluate("(s) => [...document.querySelectorAll(s)].map(e => (e.textContent || '').trim())", sheet)
for want in ("Settings", "How to play", "History", "Stats", "About this game"):
if want not in labels:
continue
page.evaluate(
"([s, w]) => [...document.querySelectorAll(s)].find(e => (e.textContent || '').trim() === w).click()", [sheet, want]
)
page.wait_for_timeout(500)
short += undersized(page, noscroll=True)
page.keyboard.press("Escape")
page.wait_for_timeout(300)
if not page.query_selector(sheet):
page.evaluate("document.querySelector('.gs-menu-btn').click()")
page.wait_for_timeout(400)
c.close()
assert not short, "\n".join(sorted(set(short)))


# Every board, card and tile game on the shelf, and minesweeper: the cells are what the page puts a press handler on, or
# the children of the box that has one (found through the browser's own list of listeners).
_CELLS = """(idx) => {
const all = Array.from(document.querySelectorAll('body, body *'));
const sig = (e) => { const c = ((e.className && e.className.baseVal !== undefined ? e.className.baseVal : e.className) + '').trim().split(/\\s+/).filter(Boolean)[0];
return c ? e.tagName.toLowerCase() + '.' + CSS.escape(c) : null; };
const out = new Set(['.zc-card', '.zc-slot']), plain = (e) => !/^(svg|g|path|rect|circle|use|text|line|polygon|polyline|ellipse|defs)$/.test(e.tagName) && !e.closest('svg');
for (const i of idx) {
const e = all[i], r = e.getBoundingClientRect();
if (e.closest('.ar-bar, .gs-bar, .ar-sheet, [role=dialog]')) continue;
if (r.width <= 200 && r.height <= 200) { if (plain(e) && sig(e)) out.add(sig(e)); continue; }
const n = {};
e.querySelectorAll('*').forEach((c) => { const q = c.getBoundingClientRect(); if (q.width > 6 && q.width < 120 && q.height > 6 && q.height < 140 && plain(c) && sig(c)) n[sig(c)] = (n[sig(c)] || 0) + 1; });
for (const [k, v] of Object.entries(n)) if (v >= 4) out.add(k);
}
return [...out].join(',');
}"""


@pytest.fixture(scope="module")
def chromium(pw):
"""The listeners behind a press are only asked of Chromium (the DevTools protocol)."""
try:
b = pw.chromium.launch()
except Exception:
pytest.skip("no chromium installed")
yield b
b.close()


def _cell_selector(page):
cdp = page.context.new_cdp_session(page)
arr = cdp.send("Runtime.evaluate", {"expression": "Array.from(document.querySelectorAll('body, body *'))"})
props = cdp.send("Runtime.getProperties", {"objectId": arr["result"]["objectId"], "ownProperties": True})
idx = []
for pr in props["result"]:
oid = pr["value"].get("objectId") if pr["name"].isdigit() else None
if oid and {l["type"] for l in cdp.send("DOMDebugger.getEventListeners", {"objectId": oid})["listeners"]} & {"click", "pointerdown", "pointerup", "mousedown", "touchstart"}:
idx.append(int(pr["name"]))
found = page.evaluate(_CELLS, idx).split(",")
if ".zc-card" in found and any("zc-" in f for f in found if f not in (".zc-card", ".zc-slot")):
return ".zc-card,.zc-slot" # the card table: the cards and their places, not what is drawn on them
return ",".join(f for f in found if f not in ("button.ar-btn", "button.ar-back", "span.ct-chip", ".zc-card", ".zc-slot")) or ".zc-card,.zc-slot"


def _shelf_games(*kinds):
import json

rows = json.load(open(os.path.join(GAMES, "games.json")))
return sorted({r["path"] for r in rows if r.get("kind") in kinds and r.get("path") and "/" not in r["path"]} | {"minesweeper.html"})


@pytest.mark.parametrize("game", _shelf_games("board", "cards", "tiles"))
def test_no_touch_is_lost_between_the_cells_of_any_board_or_card_game(chromium, base, game):
try:
c, page = open_game(chromium, base, game)
except Exception:
pytest.skip("a game that waits on a lobby or a canvas")
sel = _cell_selector(page)
r = page.evaluate(_SEAMS, sel)
if r["bad"] and "zc-" not in sel:
# A gap is not lost if a touch there reaches a cell anyway (the place kit sends it to the nearest within 14px).
page.evaluate(
"""(sel) => { window.__reached = 0; for (const t of ['click', 'pointerdown', 'pointerup'])
document.addEventListener(t, (e) => { if (e.target.closest && e.target.closest(sel)) window.__reached++; }, true); }""",
sel,
)
lost = []
for _n, _s, x, y in r["bad"]:
page.evaluate("window.__reached = 0")
page.mouse.click(x, y) # the mouse: no browser help in aiming a touch at the nearest control
page.wait_for_timeout(150)
if not page.evaluate("window.__reached"):
lost.append((x, y))
r["bad"] = lost
if "zc-" in sel and r["bad"]:
# The card table takes a press in a gap for the pile nearest it (cards.js nearestSlot, 14px): a gap with no pile that near is lost.
r["bad"] = [
(x, y)
for _n, _s, x, y in r["bad"]
if not page.evaluate(
"""([x, y]) => [...document.querySelectorAll('.zc-slot')].some(e => { const r = e.getBoundingClientRect();
return Math.hypot(Math.max(r.left - x, 0, x - r.right), Math.max(r.top - y, 0, y - r.bottom)) <= 14; })""",
[x, y],
)
]
c.close()
assert not r["bad"], (sel, r)
20 changes: 20 additions & 0 deletions tests/test_games_bar_stack_browser.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,3 +54,23 @@ def test_snake_keeps_its_name_whole_when_pause_turns_to_resume(browser, served):
assert not got["cut"], got
assert got["h"] == 56 and got["right"] <= 390 - 16 + 1, got
ctx.close()


def test_snake_title_keeps_its_size_while_playing(browser, served):
""""Snake" beside "Apples 12 · Best 34" at 390 px was stepped down to 14px to squeeze in, which read as a cut title: the stat
goes under the title first, and the title stays at the size every other game's has."""
ctx = browser.new_context(viewport={"width": 390, "height": 844}, has_touch=True, is_mobile=True)
page = ctx.new_page()
page.goto("%s/snake.html#lang=en&dir=ltr" % served)
page.wait_for_selector(".gs-sp-play")
page.click(".gs-sp-play")
for stat in ("Apples 0 · Best 0", "Apples 12 · Best 34", "Apples 100 · Best 100"):
page.evaluate("s => { document.getElementById('sn-stat').textContent = s; }", stat)
page.wait_for_timeout(250)
got = page.evaluate(
"() => { const h = document.querySelector('.ar-bar h1'); return { px: h.style.fontSize, "
"natural: parseFloat(getComputedStyle(h).fontSize), cut: h.scrollWidth > h.clientWidth + 0.5, "
"stack: document.querySelector('.ar-bar').classList.contains('gs-bar-stack') }; }"
)
assert got["px"] == "" and not got["cut"] and got["stack"], (stat, got)
ctx.close()
76 changes: 76 additions & 0 deletions tests/test_games_bar_title_browser.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
"""A game's name in Zimi's bar on a phone: the longest game name in each of the ten languages either shows whole, or ends in an
ellipsis with the full name as its tooltip; the bar's buttons stay on screen, 40px wide at least, and never overlap the name.
Polyominoes (the English name that was cut to "Polyomin...") shows whole.

Run: ZIMI_TORRENT=0 ZIMI_OFFLINE=1 pytest tests/test_games_bar_title_browser.py -v
"""

import json
import os
import sys

import pytest

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
from test_games_home_isolation import browser, zimi # noqa: E402,F401

TEXT = os.path.join(os.path.dirname(HERE), "zimi", "builtin", "games", "text")
LANGS = ["ar", "de", "en", "es", "fr", "he", "hi", "pt", "ru", "zh"]
WIDTHS = [360, 390]
PER_LANG = 3
WIDE_SCRIPT = 1.8 # a Chinese character is about this many Latin letters wide


def longest(lang):
with open(os.path.join(TEXT, lang + ".json"), encoding="utf-8") as f:
table = json.load(f)
names = {
v
for k, v in table.items()
if k.startswith("game.") and k.endswith(".title") and isinstance(v, str)
}
weight = WIDE_SCRIPT if lang == "zh" else 1
return sorted(names, key=lambda n: (-len(n) * weight, n))[:PER_LANG] # ties by name: every worker collects the same tests


NAMES = [(lang, n) for lang in LANGS for n in longest(lang)] + [("en", "Polyominoes")]

FIT = """([name, dir]) => {
document.documentElement.dir = dir;
document.body.classList.add('game-page');
const head = document.getElementById('game-head'), title = document.getElementById('game-title');
head.hidden = false;
for (const id of ['game-act-btn', 'game-menu-btn']) { const b = document.getElementById(id); b.hidden = false; }
document.getElementById('game-act-btn').innerHTML = _GAME_ACT_SVG.undo;
title.textContent = name;
_fitGameTitle(title);
const t = title.getBoundingClientRect(), bar = document.querySelector('.topbar').getBoundingClientRect();
const btns = [...head.querySelectorAll('.reader-btn')].map(b => b.getBoundingClientRect());
return { whole: !_titleOverflows(title), tip: title.title, ellipsis: getComputedStyle(title).textOverflow, barOver: document.querySelector('.topbar').scrollWidth > document.querySelector('.topbar').clientWidth,
btnW: Math.min(...btns.map(b => b.width)), btnsIn: btns.every(b => b.left >= bar.left - 0.5 && b.right <= bar.right + 0.5),
overlap: btns.some(b => b.left < t.right - 0.5 && b.right > t.left + 0.5), px: parseFloat(getComputedStyle(title).fontSize) };
}"""


@pytest.mark.parametrize("width", WIDTHS)
@pytest.mark.parametrize("lang,name", NAMES, ids=lambda v: str(v))
def test_the_name_fits_or_ends_in_an_ellipsis(zimi, browser, width, lang, name):
ctx = browser.new_context(
viewport={"width": width, "height": 844}, has_touch=True, is_mobile=True
)
page = ctx.new_page()
page.goto(zimi)
page.wait_for_function(
"() => typeof _fitGameTitle === 'function' && typeof _GAME_ACT_SVG === 'object'"
)
got = page.evaluate(FIT, [name, "rtl" if lang in ("ar", "he") else "ltr"])
assert not got["barOver"] and got["btnsIn"] and not got["overlap"], (name, got)
assert got["btnW"] >= 40, (name, got)
assert got["whole"] or (got["ellipsis"] == "ellipsis" and got["tip"] == name), (
name,
got,
)
if name == "Polyominoes":
assert got["whole"], got
ctx.close()
19 changes: 18 additions & 1 deletion tests/test_games_batch2_browser.py
Original file line number Diff line number Diff line change
Expand Up @@ -313,7 +313,11 @@ def test_puzzle_pages_say_their_rules_in_one_line(browser, served):
# 8. German: the games speak to the player as "du" (the shelf's "Sie" in a score pill read as "she/they"), and Hold'em's
# out and fold words differ.
THIRD_PERSON_SIE = {"game.goproblems.why", "game.koikoi.why", "help.fourinarow.turn", "help.inertia.turn", "help.liarsdice.tip", "help.scopa.turn",
"history.blast", "history.draughts", "history.golf", "history.pattern", "openings.notThis", "sky.fact.venus", "spider.why.rank"}
"history.blast", "history.draughts", "history.golf", "history.pattern", "openings.notThis", "sky.fact.venus", "spider.why.rank",
# the new games: Sie is she, it or they (a card, a pile, a shape), never the player
"accordion.why.match", "help.beleaguered.tip", "help.canfield.tip", "help.cheat.turn", "help.courtier.turn", "help.fortythieves.tip",
"help.polyominoes.turn", "help.shutthebox.tip", "history.acesup", "history.fortythieves", "history.polyominoes",
"poly.why.bounds", "poly.why.corner", "poly.why.edge"}


def test_german_games_text_is_informal():
Expand All @@ -327,3 +331,16 @@ def test_german_games_text_is_informal():
found = [k for k in found if k != "history.zimcity"] # "Ihr Code" is the city simulator's own code
assert not found, found
assert de["holdem.out"] != de["holdem.last.fold"] and "raus" not in de["holdem.out"]


def test_backgammon_point_numbers_are_readable_on_a_phone(browser, served):
"""The point numbers were 10px beside the triangle tips: they are 12px on the phone's board, upright, and none leaves the board."""
c, page = open_game(browser, served, "backgammon")
got = page.evaluate(
"""() => { const svg = document.querySelector('#wk-board svg'), b = svg.getBoundingClientRect();
return [...document.querySelectorAll('.bk-pn')].map(t => { const m = t.getScreenCTM(), r = t.getBoundingClientRect();
return { px: parseFloat(getComputedStyle(t).fontSize) * Math.hypot(m.a, m.b), upright: Math.abs(m.b) < 0.01 && m.a > 0, inside: r.left >= b.left && r.right <= b.right && r.top >= b.top && r.bottom <= b.bottom }; }); }"""
)
assert len(got) == 24, got
assert all(g["px"] >= 11.5 and g["upright"] and g["inside"] for g in got), got
c.close()
2 changes: 1 addition & 1 deletion tests/test_games_batch2_zimi_browser.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
import pytest

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from test_games_final_fixes import PHONE, browser, zimi # noqa: E402,F401
from test_games_final_fixes import PHONE, browser, playwright_driver, zimi # noqa: E402,F401

LOCALES = [
"en-US",
Expand Down
Loading