Lines
96.23 %
Functions
95 %
Branches
100 %
//! What every page must satisfy: no console error, no failed request, the
//! stylesheets applied and the form rows laid out as one clean grid, at
//! desktop and phone width. Each check also leaves a screenshot of both.
use anyhow::{Result, bail};
use serde_json::{Value, json};
use super::harness::Harness;
use super::page::{DESKTOP, PHONE};
/// Layout problems of the forms on the page, as text; `wide` adds the
/// one-line-per-row rules that only hold at desktop width.
const LAYOUT: &str = r#"
const wide = arguments[0];
const problems = [];
const shown = e => e.offsetParent !== null || getComputedStyle(e).position === 'fixed';
const near = (a, b) => Math.abs(a - b) <= 2;
const root = document.documentElement;
if (root.scrollWidth > root.clientWidth + 1) {
problems.push(`page overflows: ${root.scrollWidth} > ${root.clientWidth}`);
}
for (const form of document.querySelectorAll('form.nomi-form')) {
const field = [...form.querySelectorAll('.field')].find(shown);
if (field && getComputedStyle(field).display !== 'flex') {
problems.push(`${form.id}: form.css not applied`);
const columns = new Map();
for (const row of form.querySelectorAll('.form-row')) {
if (!shown(row)) continue;
const kind = row.dataset.row;
if (getComputedStyle(row).display !== 'grid') problems.push(`${kind} row is not a grid`);
const controls = [...row.querySelectorAll(':scope > label input:not([type=hidden]), \
:scope > label select, :scope > label textarea')].filter(shown);
const button = row.querySelector(':scope > button[data-action="remove-row"]');
const rowBox = row.getBoundingClientRect();
for (const control of controls) {
const box = control.getBoundingClientRect();
if (box.right > rowBox.right + 1 || box.left < rowBox.left - 1) {
problems.push(`${kind}: a control leaves its row`);
if (!wide || controls.length === 0) continue;
const first = controls[0].getBoundingClientRect();
if (!near(box.top, first.top) || !near(box.bottom, first.bottom)) {
problems.push(`${kind}: ${control.name} is off the row line (${box.top} vs ${first.top})`);
if (button) {
const box = button.getBoundingClientRect();
problems.push(`${kind}: remove button ${box.top}-${box.bottom} vs inputs ${first.top}-${first.bottom}`);
const cells = [...row.querySelectorAll(':scope > label')].filter(shown)
.map(l => [l.dataset.cell || (l.querySelector('[name]') || {name: '?'}).name.split('.').pop(),
l.getBoundingClientRect().left]);
if (button) cells.push(['remove', button.getBoundingClientRect().left]);
for (const [cell, left] of cells) {
const key = `${kind}/${cell}`;
if (!columns.has(key)) columns.set(key, left);
else if (!near(columns.get(key), left)) {
problems.push(`${key} column moves: ${columns.get(key)} vs ${left}`);
if (!wide) continue;
const aligned = [['splits/from', ['split-tags/name', 'tags/name']],
['splits/to', ['split-tags/value', 'tags/value']],
['splits/from-commodity', ['split-tags/description', 'tags/description']],
['splits/to-commodity', ['split-tags/side']],
['splits/remove', ['split-tags/remove', 'tags/remove']]];
for (const [anchor, followers] of aligned) {
if (!columns.has(anchor)) continue;
for (const follower of followers) {
if (columns.has(follower) && !near(columns.get(anchor), columns.get(follower))) {
problems.push(`${follower} is not under ${anchor}: ${columns.get(follower)} vs ${columns.get(anchor)}`);
return problems;
"#;
/// Requests of this page that answered 4xx or 5xx.
const FAILED: &str = r#"
return performance.getEntries()
.filter(e => (e.responseStatus || 0) >= 400)
.map(e => `${e.responseStatus} ${e.name}`);
fn strings(value: &Value) -> Vec<String> {
value
.as_array()
.map(|list| {
list.iter()
.map(|item| item.as_str().unwrap_or_default().to_string())
.collect()
})
.unwrap_or_default()
/// The console errors since the last check, apart from those naming one of
/// `expected` (a status a scenario provokes on purpose).
async fn console_errors(h: &Harness, expected: &[u16]) -> Result<Vec<String>> {
let entries = h.driver.log().await?;
Ok(entries
.iter()
.filter(|entry| entry["level"] == json!("SEVERE"))
.map(|entry| entry["message"].as_str().unwrap_or_default().to_string())
.filter(|message| {
!expected.iter().any(|status| {
message.contains(&format!("status of {status}"))
|| message.contains(&format!("Error Code {status} "))
.collect())
async fn failed_requests(h: &Harness, expected: &[u16]) -> Result<Vec<String>> {
let failed = strings(&h.driver.run(FAILED, vec![]).await?);
Ok(failed
.into_iter()
.filter(|line| !expected.iter().any(|s| line.starts_with(&format!("{s} "))))
async fn layout(h: &Harness, wide: bool) -> Result<Vec<String>> {
Ok(strings(&h.driver.run(LAYOUT, vec![json!(wide)]).await?))
async fn shoot(h: &Harness, name: &str) -> Result<()> {
let png = h.driver.screenshot().await?;
std::fs::write(h.shots.join(format!("{name}.png")), png)?;
Ok(())
/// Checks the page now shown and saves `<name>-desktop.png` and
/// `<name>-phone.png`; `expected` statuses are provoked by the scenario.
pub async fn check_page(h: &Harness, name: &str, expected: &[u16]) -> Result<()> {
let mut problems = Vec::new();
problems.extend(console_errors(h, expected).await?);
problems.extend(failed_requests(h, expected).await?);
problems.extend(layout(h, true).await?);
shoot(h, &format!("{name}-desktop")).await?;
h.driver.set_size(PHONE.0, PHONE.1).await?;
problems.extend(
layout(h, false)
.await?
.map(|p| format!("phone: {p}")),
);
shoot(h, &format!("{name}-phone")).await?;
h.driver.set_size(DESKTOP.0, DESKTOP.1).await?;
match problems.is_empty() {
true => Ok(()),
false => bail!("{name}: {}", problems.join("\n ")),