Lines
91.43 %
Functions
96.04 %
Branches
100 %
//! What a person does on the pages, and what every page must satisfy.
use std::time::{Duration, Instant};
use anyhow::{Context, Result, anyhow, bail};
use serde_json::{Value, json};
use uuid::Uuid;
use super::driver::{ARROW_DOWN, BACKSPACE, Driver, ENTER, Element};
use super::harness::{Harness, READY_DEADLINE};
pub const DESKTOP: (u32, u32) = (1280, 900);
pub const PHONE: (u32, u32) = (390, 844);
#[derive(Clone, Copy)]
pub enum Pick {
Mouse,
Keyboard,
}
/// Polls `script` (a function body returning a truthy value) until it holds.
pub async fn wait_for(
driver: &Driver,
script: &str,
args: Vec<Value>,
what: &str,
) -> Result<Value> {
let deadline = Instant::now() + READY_DEADLINE;
loop {
let value = driver.run(script, args.clone()).await?;
if !value.is_null() && value != json!(false) {
return Ok(value);
if Instant::now() > deadline {
bail!("timed out waiting for {what}");
tokio::time::sleep(Duration::from_millis(100)).await;
pub async fn login(h: &Harness) -> Result<()> {
h.driver.goto(&h.url("/login")).await?;
let email = h.driver.find("input[name=\"email\"]").await?;
h.driver.type_into(&email, &h.tenant.email).await?;
let password = h.driver.find("input[name=\"password\"]").await?;
h.driver.type_into(&password, h.tenant.password).await?;
let send = h.driver.find("#loginform button[type=\"submit\"]").await?;
h.driver.click(&send).await?;
wait_for(
&h.driver,
"return !location.pathname.startsWith('/login') && document.readyState === 'complete';",
vec![],
"the login to leave the login page",
)
.await
.map(drop)
/// Opens `path` and waits until the page and its form widgets are ready.
pub async fn open(h: &Harness, path: &str) -> Result<()> {
h.driver.goto(&h.url(path)).await?;
"return document.readyState === 'complete' && \
[...document.querySelectorAll('form.nomi-form')]\
.every(f => f.hasAttribute('data-suggest-ready'));",
&format!("{path} to be ready"),
/// The visible control of the select cell at `address`, whichever way the
/// page names it.
pub async fn visible(h: &Harness, address: &str) -> Result<Element> {
h.driver
.find(&format!(
"input[data-source][name=\"{address}\"], input[data-source][name=\"label:{address}\"]"
))
/// What the select cell at `address` shows and the id it carries (empty
/// when the page has no hidden reference input).
pub async fn reference(h: &Harness, address: &str) -> Result<(String, String)> {
let found = h
.driver
.run(
"const a = arguments[0];\
const shown = document.querySelector(\
`input[data-source][name=\"${a}\"], input[data-source][name=\"label:${a}\"]`);\
const hidden = document.querySelector(`input[type=hidden][name=\"${a}\"]`);\
return [shown ? shown.value : null, hidden ? hidden.value : '',\
document.body.innerText.slice(0, 400)];",
vec![json!(address)],
.await?;
let shown = found[0].as_str().ok_or_else(|| {
anyhow!(
"no select control at {address}; the page reads {}",
found[2]
})?;
Ok((
shown.to_string(),
found[1].as_str().unwrap_or_default().to_string(),
/// The labels of the open suggestion list, without their secondary text.
async fn suggestions(h: &Harness) -> Result<Vec<String>> {
let labels = h
"return [...document.querySelectorAll('.autocomplete-results .autocomplete-item')]\
.map(i => i.firstChild ? i.firstChild.textContent.trim() : '');",
Ok(labels
.as_array()
.map(|list| {
list.iter()
.map(|label| label.as_str().unwrap_or_default().to_string())
.collect()
})
.unwrap_or_default())
/// Clicks suggestion `position`. The list re-renders when its options
/// arrive, which can make a just-found item stale; it is found again.
pub async fn click_suggestion(h: &Harness, position: usize) -> Result<()> {
let mut attempts = 0;
let items = h
.find_all(".autocomplete-results .autocomplete-item")
let item = items
.get(position)
.ok_or_else(|| anyhow!("suggestion {position} vanished"))?;
match h.driver.click(item).await {
Err(error) if attempts < 5 && error.to_string().contains("stale element") => {
attempts += 1;
clicked => return clicked,
/// Clicks the suggestion labelled `label`. The list re-renders as options
/// arrive, so the item is looked up by its label again on every attempt,
/// never by an index read earlier.
async fn click_labelled(h: &Harness, label: &str) -> Result<()> {
let position = suggestions(h).await?.iter().position(|l| l == label);
if let Some(item) = position.and_then(|at| items.get(at)) {
Err(error) if error.to_string().contains("stale element") => {}
bail!("suggestion {label:?} was not clickable");
/// Types `query` into the select cell at `address`, then picks the `nth`
/// suggestion `matches` accepts; returns the picked label.
pub async fn pick(
h: &Harness,
address: &str,
query: &str,
matches: impl Fn(&str) -> bool,
nth: usize,
how: Pick,
) -> Result<String> {
let input = visible(h, address).await?;
h.driver.click(&input).await?;
h.driver.clear(&input).await?;
h.driver.type_into(&input, query).await?;
let (position, label) = loop {
let labels = suggestions(h).await?;
let found = labels
.iter()
.enumerate()
.filter(|(_, label)| matches(label))
.nth(nth);
if let Some((position, label)) = found {
break (position, label.clone());
bail!("no suggestion #{nth} for {query:?} at {address}: {labels:?}");
};
match how {
Pick::Mouse => click_labelled(h, &label).await?,
Pick::Keyboard => {
let keys = ARROW_DOWN.repeat(position) + ENTER;
h.driver.type_into(&input, &keys).await?;
Ok(label)
/// Replaces the text of the plain input or textarea named `name`.
pub async fn set_text(h: &Harness, name: &str, text: &str) -> Result<()> {
let input = h.driver.find(&format!("[name=\"{name}\"]")).await?;
h.driver.type_into(&input, text).await
/// Deletes the text of the select cell at `address` key by key, as a person does.
pub async fn erase(h: &Harness, address: &str) -> Result<()> {
h.driver.type_into(&input, &BACKSPACE.repeat(16)).await
/// Chooses `value` in the select named `name`.
pub async fn choose(h: &Harness, name: &str, value: &str) -> Result<()> {
let option = h
"select[name=\"{name}\"] option[value=\"{value}\"]"
h.driver.click(&option).await
pub async fn add_split(h: &Harness) -> Result<()> {
let add = h
.find("fieldset[data-rows=\"splits\"] > button[data-rows-for$=\"-splits\"]")
h.driver.click(&add).await
/// Adds a split tag to the split row `row` (0-based, in page order).
pub async fn add_split_tag(h: &Harness, row: usize) -> Result<()> {
let groups = h
.find_all("fieldset[data-rows=\"splits\"] > .row-group")
let group = groups
.get(row)
.ok_or_else(|| anyhow!("no split row {row}"))?;
.find_in(group, ".nested-rows > button[data-action=\"add-row\"]")
/// Submits the page's form and returns the result box text once the reply
/// is shown, or the re-rendered form's errors if it came back invalid. The
/// form is marked first, so errors of an earlier reply never count.
pub async fn submit(h: &Harness) -> Result<String> {
"const form = document.querySelector('form.nomi-form');\
form.setAttribute('data-e2e-pending', '');\
const box = form.querySelector('.result-box'); if (box) box.textContent = '';",
let button = h
.find("form.nomi-form button[type=\"submit\"]")
h.driver.click(&button).await?;
let shown = wait_for(
const box = form.querySelector('.result-box');\
const text = box ? box.textContent.trim() : '';\
if (form.hasAttribute('data-e2e-pending')) return text || null;\
const errors = [...form.querySelectorAll('.field-error, .row-error, .form-banner')]\
.map(e => e.textContent.trim()).filter(Boolean);\
return 'INVALID: ' + errors.join(' | ');",
"the submit reply",
Ok(shown.as_str().unwrap_or_default().to_string())
/// The id a "created with ID" or "updated with ID" reply names.
pub fn reply_id(reply: &str) -> Result<Uuid> {
let id = reply.rsplit(' ').next().unwrap_or_default();
Uuid::parse_str(id.trim()).with_context(|| format!("no id in reply {reply:?}"))
/// The exact texts of the buttons of the page's forms, in page order.
pub async fn button_texts(h: &Harness) -> Result<Vec<String>> {
let texts = h
"return [...document.querySelectorAll('form.nomi-form button')]\
.filter(b => b.offsetParent !== null).map(b => b.textContent.trim());",
Ok(texts
.map(|text| text.as_str().unwrap_or_default().to_string())