use std::fmt;
use anyhow::Result;
use thirtyfour::prelude::*;
use tokio::time::{self, Duration, Instant};
pub const POLL_INTERVAL: Duration = Duration::from_millis(25);
pub(crate) const WAIT_TIMEOUT: Duration = Duration::from_secs(5);
pub(crate) const LOAD_TIMEOUT: Duration = Duration::from_secs(15);
tokio::task_local! {
static DEADLINE: Instant;
}
#[derive(Debug)]
pub(crate) struct OutOfTime(pub(crate) String);
impl fmt::Display for OutOfTime {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl std::error::Error for OutOfTime {}
pub(crate) fn bounded(timeout: Duration) -> Duration {
DEADLINE
.try_with(|deadline| timeout.min(deadline.saturating_duration_since(Instant::now())))
.unwrap_or(timeout)
}
pub(crate) async fn poll<T>(
timeout: Duration,
mut attempt: impl AsyncFnMut() -> Result<Option<T>>,
) -> Result<Option<T>> {
let own = Instant::now() + timeout;
let deadline = DEADLINE.try_with(|outer| own.min(*outer)).unwrap_or(own);
DEADLINE
.scope(deadline, async move {
loop {
match attempt().await {
Ok(Some(found)) => return Ok(Some(found)),
Ok(None) => {}
Err(error)
if error.downcast_ref::<OutOfTime>().is_some()
&& Instant::now() >= deadline => {}
Err(error) => return Err(error),
}
if Instant::now() >= deadline {
return Ok(None);
}
time::sleep(POLL_INTERVAL).await;
}
})
.await
}
macro_rules! common {
() => {
pub async fn wait_until(
&self,
what: impl std::fmt::Display,
condition: impl AsyncFnMut() -> Result<bool>,
) -> Result<()> {
self.wait_for(self.wait_timeout, what, condition).await
}
pub async fn wait_until_within(
&self,
timeout: Duration,
what: impl std::fmt::Display,
condition: impl AsyncFnMut() -> Result<bool>,
) -> Result<()> {
self.wait_for(timeout, what, condition).await
}
async fn wait_for(
&self,
timeout: Duration,
what: impl std::fmt::Display,
mut condition: impl AsyncFnMut() -> Result<bool>,
) -> Result<()> {
self.waiting.on(&what);
let held = crate::finding::poll(timeout, async || Ok(condition().await?.then_some(())))
.await?;
match held {
Some(()) => Ok(()),
None => Err(crate::finding::OutOfTime(format!(
"Timed out after {timeout:?} waiting for {what}"
))
.into()),
}
}
pub async fn wait_texts<const N: usize>(
&self,
by: impl IntoBy,
expected: [&str; N],
) -> Result<()> {
let by = by.into_by();
tracing::trace!(?by, ?expected, "Waiting for texts");
let seen = std::cell::RefCell::new(Vec::new());
let result = self
.wait_until(format_args!("{by} to read {expected:?}"), async || {
let texts = self.find_all_texts(by.clone()).await?;
let matched = texts == expected;
*seen.borrow_mut() = texts;
Ok(matched)
})
.await;
match result {
Ok(()) => Ok(()),
Err(error) => {
let seen = seen.into_inner();
Err(error.context(format!("last read {seen:?}")))
}
}
}
pub async fn wait_count(&self, by: impl IntoBy, expected: usize) -> Result<()> {
let by = by.into_by();
tracing::trace!(?by, expected, "Waiting for count");
self.wait_until(format_args!("{by} to match {expected} nodes"), async || {
Ok(self.find_all(by.clone()).await?.len() == expected)
})
.await
}
#[inline]
pub async fn count(&self, by: impl IntoBy) -> Result<usize> {
Ok(self.find_all(by.into_by()).await?.len())
}
pub async fn wait_count_from(
&self,
by: impl IntoBy,
before: usize,
expected: usize,
) -> Result<()> {
let by = by.into_by();
ensure!(
before != expected,
"Waiting for {by} to match {expected} nodes verifies nothing: \
{expected} is also the count read before the action, so the \
first poll agrees whether or not the action has landed. Assert \
the count this action is supposed to produce, or if it really \
is meant to leave the count alone, assert what it did change.",
);
tracing::trace!(?by, before, expected, "Waiting for count to change");
self.wait_until(
format_args!("{by} to go from {before} to {expected} nodes"),
async || Ok(self.find_all(by.clone()).await?.len() == expected),
)
.await
}
#[inline]
pub async fn find_all_texts(&self, by: impl IntoBy) -> Result<Vec<String>> {
let mut texts = Vec::new();
for item in self.find_all(by.into_by()).await? {
texts.push(item.text().await?);
}
Ok(texts)
}
#[inline]
pub async fn find_one_by_xpath(&self, xpath: &str) -> Result<TestElement> {
self.find_one_by(By::XPath(xpath)).await
}
pub async fn find_one_by(&self, by: impl IntoBy) -> Result<TestElement> {
let by = by.into_by();
tracing::trace!(?by, "Finding one element");
let found = crate::finding::poll(self.wait_timeout, async || {
let items = self.find_all(by.clone()).await?;
ensure!(
items.len() <= 1,
"Expected exactly one by {by}, but got {}: where several is \
what the page is, ask for one of them by index with \
find_nth, or for the first of them with find_first",
items.len()
);
Ok(items.into_iter().next())
})
.await?;
found.ok_or_else(|| {
crate::finding::OutOfTime(format!(
"Timed out after {:?} waiting for {by}",
self.wait_timeout
))
.into()
})
}
pub async fn find_nth(&self, by: impl IntoBy, index: usize) -> Result<TestElement> {
let by = by.into_by();
tracing::trace!(?by, index, "Finding one of several elements");
let found = crate::finding::poll(self.wait_timeout, async || {
Ok(self.find_all(by.clone()).await?.into_iter().nth(index))
})
.await?;
found.ok_or_else(|| {
crate::finding::OutOfTime(format!(
"Timed out after {:?} waiting for {by} at {index}",
self.wait_timeout
))
.into()
})
}
#[inline]
pub async fn find_first(&self, by: impl IntoBy) -> Result<TestElement> {
self.find_nth(by, 0).await
}
pub async fn find_all(&self, by: impl IntoBy) -> Result<Vec<TestElement>> {
self.find_all_within(self.wait_timeout, by).await
}
pub async fn find_all_within(
&self,
timeout: Duration,
by: impl IntoBy,
) -> Result<Vec<TestElement>> {
let by = by.into_by();
let timeout = crate::finding::bounded(timeout);
tracing::trace!(?by, "Finding all elements");
let task = self.inner.find_all(by.clone());
let sleep = time::sleep(timeout);
tokio::select! {
_ = sleep => {
Err(crate::finding::OutOfTime(format!(
"find_elements({by:?}) timed out after {timeout:?}"
))
.into())
}
result = task => {
Ok(result?.into_iter().map(|inner| TestElement { inner, wait_timeout: self.wait_timeout, waiting: self.waiting.clone(), holding: self.holding.clone() }).collect::<Vec<_>>())
}
}
}
}
}
pub(crate) use common;
pub trait IntoBy {
fn into_by(self) -> By;
}
impl IntoBy for &str {
#[inline]
fn into_by(self) -> By {
By::Css(self)
}
}
impl IntoBy for &String {
#[inline]
fn into_by(self) -> By {
By::Css(self.as_str())
}
}
impl IntoBy for By {
#[inline]
fn into_by(self) -> By {
self
}
}
#[cfg(test)]
mod tests {
use anyhow::{Result, anyhow, bail};
use tokio::time::{self, Duration, Instant};
use super::{OutOfTime, bounded, poll};
async fn slow_find(takes: Duration) -> Result<Option<()>> {
let bound = bounded(Duration::from_secs(5));
tokio::select! {
_ = time::sleep(bound) => Err(OutOfTime(format!("timed out after {bound:?}")).into()),
_ = time::sleep(takes) => Ok(None),
}
}
#[test]
fn outside_a_wait_a_bound_is_left_alone() {
assert_eq!(bounded(Duration::from_secs(5)), Duration::from_secs(5));
}
#[tokio::test(start_paused = true)]
async fn a_slow_lookup_does_not_carry_a_wait_past_its_deadline() -> Result<()> {
let start = Instant::now();
let found = poll(Duration::from_millis(300), async || {
slow_find(Duration::from_secs(3)).await
})
.await?;
assert!(found.is_none());
assert_eq!(start.elapsed(), Duration::from_millis(300));
Ok(())
}
#[tokio::test(start_paused = true)]
async fn a_poll_inside_a_wait_gives_up_with_it() -> Result<()> {
let start = Instant::now();
let found = poll(Duration::from_millis(300), async || {
match poll(Duration::from_secs(5), async || Ok(None::<()>)).await? {
Some(()) => Ok(Some(())),
None => Err(OutOfTime(String::from("the inner poll")).into()),
}
})
.await?;
assert!(found.is_none());
assert!(start.elapsed() < Duration::from_millis(400));
Ok(())
}
#[tokio::test(start_paused = true)]
async fn a_lookup_out_of_its_own_time_is_still_a_failure() -> Result<()> {
let result = poll(Duration::from_secs(60), async || {
slow_find(Duration::from_secs(10)).await
})
.await;
let Err(error) = result else {
bail!("a lookup that ran out of its own time passed");
};
assert_eq!(error.to_string(), "timed out after 5s");
Ok(())
}
#[tokio::test(start_paused = true)]
async fn an_attempt_that_fails_is_not_retried() -> Result<()> {
let mut attempts = 0;
let result = poll(Duration::from_secs(1), async || {
attempts += 1;
Err::<Option<()>, _>(anyhow!("broken"))
})
.await;
assert!(result.is_err());
assert_eq!(attempts, 1);
Ok(())
}
}