"""Pages in a real browser, asserting layout and never pixels."""
import re
import shutil
import pytest
import harness
from playwright.sync_api import Error, sync_playwright
PAGE = "/forge.invalid/acct/r/long.go"
# A bar's bottom and the line's top may differ by the scroll's rounding.
ROUNDING = 1
@pytest.fixture(scope="module")
def browser():
"""Playwright's Chromium where installed, else the machine's Brave."""
kept = shutil.which("brave-browser")
tries = [{}, {"executable_path": kept}] if kept else [{}]
with sync_playwright() as p:
for options in tries:
try:
# basic: Brave otherwise asks the desktop's wallet for a password.
b = p.chromium.launch(args=["--password-store=basic", "--use-mock-keychain"], **options)
except Error as err:
failure = str(err).splitlines()[0]
continue
yield b
b.close()
return
pytest.skip(f"no browser starts: {failure}")
@pytest.fixture
def origin(servers):
"""Where the code page answers, past any reading page a first request gets."""
server = servers("public")
server.get(PAGE)
return server.origin
@pytest.fixture
def page(browser):
page = browser.new_page(viewport={"width": 1280, "height": 800})
yield page
page.close()
def assert_below_bars(page, line):
got = page.evaluate(
"""(line) => ({
line: document.getElementById(line).getBoundingClientRect().top,
search: document.querySelector("div.search").getBoundingClientRect().bottom,
view: document.querySelector("div.view").getBoundingClientRect().bottom,
y: scrollY,
})""",
line,
)
assert got["y"] > 0, got
assert got["line"] >= max(got["search"], got["view"]) - ROUNDING, got
assert got["line"] < max(got["search"], got["view"]) + 40, got
# Code lines anchor as #L42. A marked line lands below the search row and
# the view links.
@pytest.mark.parametrize("query", ["", "?scopes"])
@pytest.mark.parametrize("fragment", ["#L100", "#L100-L110"])
def test_load_marks_a_line_below_the_bars(origin, page, query, fragment):
page.goto(origin + PAGE + query + fragment, wait_until="load")
assert_below_bars(page, "L100")
def test_click_marks_a_line_below_the_bars(origin, page):
page.goto(origin + PAGE, wait_until="load")
page.evaluate("""scrollTo(0, document.getElementById("L200").getBoundingClientRect().top + scrollY - 300)""")
# The number is the link's ::before, so the link itself has no size to click.
page.locator("#L200 > a").first.dispatch_event("click")
page.wait_for_function("""location.hash === "#L200" """)
assert_below_bars(page, "L200")
# The details view leads each row with size and age. Sizes of different
# widths, here 4 and 3.0K, still leave the names in one column.
def test_details_names_line_up(origin, page):
page.goto(origin + "/forge.invalid/acct/r/?details", wait_until="load")
lefts = page.evaluate(
"""[...document.querySelectorAll("ul.listing li:not(.cmds) > a")]
.map((a) => a.getBoundingClientRect().left)"""
)
assert len(lefts) == 2, lefts
assert max(lefts) - min(lefts) < ROUNDING, lefts
# The history keeps to the right end of a listing's first row. A public
# server offers no history for a seeded repo, since its forge does not
# resolve, so this reads a repo in the default server's tree.
def test_history_ends_the_first_row(servers, page):
server = servers("default")
repo = server.home / "tree" / "hist"
repo.mkdir()
harness.git(repo, "init", "-q")
(repo / "a.md").write_text("a\n")
harness.git(repo, "add", ".")
harness.git(repo, "commit", "-q", "-m", "first")
page.goto(server.origin.replace(".2:", ".1:") + "/tree/hist/", wait_until="load")
got = page.evaluate(
"""({
history: document.querySelector("ul.listing li.cmds > a.history").getBoundingClientRect().right,
row: document.querySelector("ul.listing li.cmds").getBoundingClientRect().right,
})"""
)
assert abs(got["history"] - got["row"]) < ROUNDING, got
def overflow(page, selector):
"""How far each scroll box's content runs past its width, in px."""
return page.evaluate(
"""(selector) => [...document.querySelectorAll(selector)].map((e) => e.scrollWidth - e.clientWidth)""",
selector,
)
# A code block in a document holds 99 columns in the measure: a line of 99
# does not scroll and a line of 100 does.
def test_a_document_s_code_fits_99_columns(servers, page):
server = servers("public")
server.get("/forge.invalid/acct/cols/cols.md")
page.goto(server.origin + "/forge.invalid/acct/cols/cols.md", wait_until="load")
page.evaluate("document.fonts.ready")
fits, over = overflow(page, "main pre")
assert fits == 0, (fits, over)
assert over > 0, (fits, over)
# Code in a document keeps the text colour; a code page mutes its
# comments. Named after "Code in docs carries no syntax colour".
def test_code_in_docs_carries_no_syntax_colour(servers, page):
server = servers("public")
colours = """(() => [getComputedStyle(document.querySelector("code span.co")).color,
getComputedStyle(document.body).color])()"""
server.get("/forge.invalid/acct/cols/code.md")
page.goto(server.origin + "/forge.invalid/acct/cols/code.md", wait_until="load")
comment, text = page.evaluate(colours)
assert comment == text, (comment, text)
page.goto(server.origin + PAGE, wait_until="load")
comment, text = page.evaluate(colours)
assert comment != text, (comment, text)
# Code has no italics, since Firefox drew the installed Iosevka's italic
# with letters missing. Named after "Fonts never come from the network",
# whose commentary holds the evidence.
def test_code_has_no_italics(origin, page):
page.goto(origin + PAGE, wait_until="load")
styles = page.evaluate("""[...new Set([...document.querySelectorAll("code span[class]")].map((s) => getComputedStyle(s).fontStyle))]""")
assert styles == ["normal"], styles
# A code page colours strings and mutes comments; keywords are bold in the
# text colour, and so is everything else. Named after "Code pages colour
# strings and comments".
def test_code_pages_colour_strings_and_comments(servers, page):
server = servers("public")
server.get("/forge.invalid/acct/cols/str.go")
page.goto(server.origin + "/forge.invalid/acct/cols/str.go", wait_until="load")
got = page.evaluate(
"""(() => {
const c = (sel) => getComputedStyle(document.querySelector(sel)).color;
const k = document.querySelector("code span.kw");
return { text: getComputedStyle(document.body).color, kw: c("code span.kw"), bold: getComputedStyle(k).fontWeight,
fu: c("code span.fu"), st: c("code span.st"), co: c("code span.co") };
})()"""
)
assert got["kw"] == got["text"] and got["fu"] == got["text"], got
assert int(got["bold"]) >= 700, got
assert got["st"] != got["text"] and got["co"] != got["text"] and got["st"] != got["co"], got
# The lines below a 404 read at a listing's size. Named after "Error text
# reads at listing size".
def test_error_text_reads_at_listing_size(servers, page):
server = servers("public")
server.get("/forge.invalid/acct/r/")
page.goto(server.origin + "/forge.invalid/acct/r/", wait_until="load")
listing = page.evaluate("""getComputedStyle(document.querySelector("ul.listing")).fontSize""")
page.goto(server.origin + "/forge.invalid/acct/r/nope.md", wait_until="load")
gone = page.evaluate("""getComputedStyle(document.querySelector("table.gone")).fontSize""")
assert gone == listing, (gone, listing)
# A code page holds 104 columns: 99 of code after a gutter of five cells,
# which a four-digit line number and a space fill.
def test_a_code_page_fits_99_columns_and_four_digits(servers, page):
server = servers("public")
server.get("/forge.invalid/acct/cols/fits.go")
page.goto(server.origin + "/forge.invalid/acct/cols/fits.go", wait_until="load")
page.evaluate("document.fonts.ready")
assert overflow(page, "div.code > div.sourceCode") == [0]
got = page.evaluate(
"""(() => {
const line = document.getElementById("L1000");
const text = document.createRange();
text.selectNodeContents(line);
const box = text.getBoundingClientRect();
return {
gutter: box.left - document.querySelector("div.code > div.sourceCode").getBoundingClientRect().left,
cell: box.width / line.textContent.length,
columns: line.textContent.length,
};
})()"""
)
assert got["columns"] == 99, got
assert abs(got["gutter"] - 5 * got["cell"]) < ROUNDING, got
page.goto(server.origin + "/forge.invalid/acct/cols/over.go", wait_until="load")
page.evaluate("document.fonts.ready")
assert overflow(page, "div.code > div.sourceCode")[0] > 0
# A diff holds 99 columns, its sign included: an added line of 98 does not
# scroll and one of 99 does. A commit page gives each file its own diff.
def test_a_diff_fits_99_columns(servers, page):
server = servers("default")
repo = server.home / "tree" / "diffcols"
repo.mkdir()
harness.git(repo, "init", "-q")
(repo / "a-fits.txt").write_text("x" * 98 + "\n")
(repo / "b-over.txt").write_text("x" * 99 + "\n")
harness.git(repo, "add", ".")
harness.git(repo, "commit", "-q", "-m", "first")
head = harness.git(repo, "rev-parse", "HEAD")
page.goto(server.origin.replace(".2:", ".1:") + "/tree/diffcols/?commit=" + head, wait_until="load")
page.evaluate("document.fonts.ready")
fits, over = overflow(page, "pre.diff")
assert fits == 0, (fits, over)
assert over > 0, (fits, over)
# The colour mode's line names the mode in force, and each mode in its
# menu wears its own colours: light, dark and green their own, system
# the system's. The system here is dark.
def test_colour_modes_wear_their_colours(origin, browser):
page = browser.new_page(viewport={"width": 1280, "height": 800}, color_scheme="dark")
try:
page.goto(origin + PAGE, wait_until="load")
shown = """document.querySelector("details.theme > summary").innerText"""
assert page.evaluate(shown) == "system"
page.click("details.theme > summary")
got = page.evaluate(
"""Object.fromEntries([...document.querySelectorAll("details.theme button")]
.map((b) => [b.dataset.theme, getComputedStyle(b).backgroundColor]))"""
)
assert got == {
"light": "rgb(246, 246, 246)",
"system": "rgb(28, 28, 28)",
"dark": "rgb(28, 28, 28)",
"green": "rgb(11, 15, 11)",
}, got
page.click("details.theme button[data-theme=light]")
assert page.evaluate(shown) == "light"
assert page.evaluate("""document.querySelector("details.theme").open""") is False
assert page.evaluate("""getComputedStyle(document.body).backgroundColor""") == "rgb(246, 246, 246)"
# green is a palette of its own, and the other buttons keep theirs
# while it is in force.
page.click("details.theme > summary")
page.click("details.theme button[data-theme=green]")
assert page.evaluate(shown) == "green"
assert page.evaluate("""getComputedStyle(document.body).backgroundColor""") == "rgb(11, 15, 11)"
page.click("details.theme > summary")
got = page.evaluate(
"""Object.fromEntries([...document.querySelectorAll("details.theme button")]
.map((b) => [b.dataset.theme, getComputedStyle(b).backgroundColor]))"""
)
assert got["light"] == "rgb(246, 246, 246)" and got["dark"] == "rgb(28, 28, 28)", got
finally:
page.close()
def palette(page):
"""The palette's rows as [name, what], and the highlighted row's name."""
return page.evaluate(
"""({
rows: [...document.querySelectorAll("ul.palette li:not(.none)")]
.map((li) => [li.querySelector(".name").textContent, li.querySelector(".what").textContent]),
sel: (document.querySelector("ul.palette li.sel .name") || {}).textContent,
})"""
)
def hist_repo(server, name):
"""A repo in the default server's tree, and its listing's URL."""
repo = server.home / "tree" / name
repo.mkdir()
harness.git(repo, "init", "-q")
(repo / "a.md").write_text("a\n")
harness.git(repo, "add", ".")
harness.git(repo, "commit", "-q", "-m", "first")
return server.origin.replace(".2:", ".1:") + "/tree/" + name + "/"
# A colon in the box lists the page's commands, its own first, and the
# first row is highlighted. What follows the colon filters, and Enter
# runs the highlighted command.
def test_a_colon_lists_the_page_s_commands(origin, page):
page.goto(origin + PAGE, wait_until="load")
page.click("input.search")
page.keyboard.type(":")
got = palette(page)
names = [n for n, _ in got["rows"]]
for want in ["scopes", "tree", "raw", "up", "light", "system", "dark", "green", "copy", "share"]:
assert want in names, got
assert names.index("raw") < names.index("up") < names.index("light"), names
assert got["sel"] == names[0], got
assert "?q=" not in page.url
page.keyboard.type("tre")
assert palette(page)["sel"] == "tree"
with page.expect_navigation():
page.keyboard.press("Enter")
assert page.url.endswith(PAGE + "?tree"), page.url
# Escape clears the box and the palette with it.
def test_escape_closes_the_palette(origin, page):
page.goto(origin + PAGE, wait_until="load")
page.click("input.search")
page.keyboard.type(":ra")
assert palette(page)["sel"] == "raw"
page.keyboard.press("Escape")
assert page.evaluate("""[!!document.querySelector("ul.palette"), document.querySelector("input.search").value]""") == [False, ""]
# The names view offers the details view's sorts, and a command's letters
# in order find it: -t finds ls -lt.
def test_the_palette_sorts_from_the_names_view(servers, page):
url = hist_repo(servers("default"), "sorts")
page.goto(url, wait_until="load")
page.click("input.search")
page.keyboard.type(":-t")
assert palette(page)["sel"] == "ls -lt", palette(page)
with page.expect_navigation():
page.keyboard.press("Enter")
assert page.url == url + "?details=t", page.url
# A colour mode runs in place, and a command that stops something asks
# for a second Enter first.
def test_the_palette_sets_colours_and_asks_before_stopping(servers, page):
url = hist_repo(servers("default"), "colours")
page.goto(url, wait_until="load")
page.click("input.search")
page.keyboard.type(":dark")
page.keyboard.press("Enter")
assert page.evaluate("""[document.documentElement.dataset.theme, document.querySelector("input.search").value]""") == ["dark", ""]
page.keyboard.type(":delete")
assert palette(page)["sel"] == "delete lock", palette(page)
page.keyboard.press("Enter")
got = page.evaluate("""[location.href, document.querySelector("ul.palette li.armed .what").textContent]""")
assert got == [url, "Enter again to stop serving this tree"], got
# versions opens the menu of versions, which then takes the arrows.
def test_the_palette_opens_the_versions(servers, page):
url = hist_repo(servers("default"), "versions")
page.goto(url + "a.md", wait_until="load")
page.click("input.search")
page.keyboard.type(":ver")
assert palette(page)["sel"] == "versions", palette(page)
page.keyboard.press("Enter")
# A selector, not a function: the page's CSP refuses eval.
page.wait_for_selector("details.latest[open] ol.versions")
assert page.evaluate("""[document.querySelector("details.latest").open, !!document.querySelector("ul.palette")]""") == [True, False]
# The menu of versions drops over a code page's view links: each row is
# what a click on it reaches, the second included, which the sticky row
# of links once covered.
def test_the_versions_drop_over_the_view_links(servers, page):
server = servers("default")
url = hist_repo(server, "over")
repo = server.home / "tree" / "over"
for n in range(3):
(repo / "a.go").write_text("package a\n" + f"// {n}\n" * 40)
harness.git(repo, "add", ".")
harness.git(repo, "commit", "-q", "-m", f"change {n}")
page.goto(url + "a.go", wait_until="load")
page.click("details.latest > summary")
page.wait_for_selector("ol.versions > li:nth-child(4)")
got = page.evaluate(
"""[...document.querySelectorAll("ol.versions > li")].map((li) => {
const r = li.getBoundingClientRect();
const at = document.elementFromPoint(r.left + r.width / 2, r.top + r.height / 2);
return !!at && !!at.closest("ol.versions");
})"""
)
assert got == [True, True, True, True], got
TREE = "/forge.invalid/acct/cols/tree.go?tree"
TREE_STATE = """(() => {
const t = document.querySelector("div.syntax");
const fns = [...t.querySelectorAll("details")].filter((d) => d.querySelector(":scope > summary b").textContent === "function_declaration");
return { lazy: "sum" in t.dataset, empty: t.querySelectorAll("details[data-fold]").length,
deep: t.textContent.includes("deepName"), open: fns.map((d) => d.open),
note: [...document.querySelectorAll("p.unfound")].map((p) => p.textContent) };
})()"""
# A tree page arrives with its closed folds empty, then fills them in
# place once it has loaded, so the browser's own find reaches every row.
# A fold the reader opened stays open through a search and its end.
def test_tree_fills_its_folds(servers, page):
server = servers("public")
server.get(TREE)
page.goto(server.origin + TREE, wait_until="load")
page.wait_for_selector("div.syntax:not([data-sum])", state="attached")
got = page.evaluate(TREE_STATE)
assert got["empty"] == 0 and got["deep"], got
assert got["open"] == [False, False], got
page.click("div.syntax details:has(> summary > b:text-is('function_declaration')) > summary > b")
page.click("input.search")
page.keyboard.type("deepName")
page.wait_for_selector("div.syntax [hidden]", state="attached")
page.keyboard.press("Escape")
got = page.evaluate(TREE_STATE)
assert got["open"] == [True, False], got
# When the whole tree cannot be had, a search covers the rows the page
# has and says so, rather than show the tree as if all of it matched.
def test_tree_search_without_its_folds(servers, page):
server = servers("public")
server.get(TREE)
page.route(re.compile(r"fold=all"), lambda route: route.abort())
page.goto(server.origin + TREE, wait_until="load")
page.click("input.search")
page.keyboard.type("other")
page.wait_for_selector("p.unfound:has-text('could not')")
got = page.evaluate(TREE_STATE)
# A page closed with a route still in place hangs Playwright.
page.unroute_all(behavior="ignoreErrors")
assert got["lazy"] and got["note"] == ["the folds not yet opened could not be fetched, so the search skips them"], got