Skip to main content

yew_e2e/
finding.rs

1//! What every lookup and every wait shares: how often a wait looks again, how
2//! long it looks for, the methods [`TestDriver`] and [`TestElement`] both
3//! have, and [`IntoBy`], which names what they look for.
4//!
5//! [`TestDriver`]: crate::TestDriver
6//! [`TestElement`]: crate::TestElement
7
8use std::fmt;
9
10use anyhow::Result;
11use thirtyfour::prelude::*;
12use tokio::time::{self, Duration, Instant};
13
14/// How often a pending observation is repeated.
15pub const POLL_INTERVAL: Duration = Duration::from_millis(25);
16
17/// How long any one observation of a page that is already up may take to agree.
18pub(crate) const WAIT_TIMEOUT: Duration = Duration::from_secs(5);
19
20/// How long the first look at a page may take: the browser starting, the bundle
21/// being fetched, the wasm compiled and the application connected, none of
22/// which has happened when a test first asks for the page; see
23/// [`TestDriver::load_timeout`].
24pub(crate) const LOAD_TIMEOUT: Duration = Duration::from_secs(15);
25
26tokio::task_local! {
27    /// When the innermost wait under way gives up. Every lookup made while
28    /// one is under way is bounded by it, so that no one slow find can carry
29    /// a wait past its own deadline.
30    static DEADLINE: Instant;
31}
32
33/// **A wait or a lookup that ran out of time**, as opposed to one that
34/// failed. A wait whose attempt ran out of the wait's own time gives up with
35/// its own words rather than passing on the attempt's.
36#[derive(Debug)]
37pub(crate) struct OutOfTime(pub(crate) String);
38
39impl fmt::Display for OutOfTime {
40    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
41        f.write_str(&self.0)
42    }
43}
44
45impl std::error::Error for OutOfTime {}
46
47/// `timeout`, cut to what is left of the wait under way, if one is.
48pub(crate) fn bounded(timeout: Duration) -> Duration {
49    DEADLINE
50        .try_with(|deadline| timeout.min(deadline.saturating_duration_since(Instant::now())))
51        .unwrap_or(timeout)
52}
53
54/// **Repeat `attempt` until it answers, or `timeout` passes**, looking again
55/// every [`POLL_INTERVAL`]. `None` is running out of time, for the caller to
56/// say what it was waiting for.
57///
58/// A poll inside a wait gives up no later than that wait does, and every
59/// lookup an attempt makes is bounded by what is left of the poll's deadline;
60/// an attempt that failed by running out of that time ran out of time, and is
61/// not a failure of its own.
62pub(crate) async fn poll<T>(
63    timeout: Duration,
64    mut attempt: impl AsyncFnMut() -> Result<Option<T>>,
65) -> Result<Option<T>> {
66    let own = Instant::now() + timeout;
67    let deadline = DEADLINE.try_with(|outer| own.min(*outer)).unwrap_or(own);
68
69    DEADLINE
70        .scope(deadline, async move {
71            loop {
72                match attempt().await {
73                    Ok(Some(found)) => return Ok(Some(found)),
74                    Ok(None) => {}
75                    Err(error)
76                        if error.downcast_ref::<OutOfTime>().is_some()
77                            && Instant::now() >= deadline => {}
78                    Err(error) => return Err(error),
79                }
80
81                if Instant::now() >= deadline {
82                    return Ok(None);
83                }
84
85                time::sleep(POLL_INTERVAL).await;
86            }
87        })
88        .await
89}
90
91macro_rules! common {
92    () => {
93        /// Repeat `condition` until it holds, or the wait timeout passes.
94        pub async fn wait_until(
95            &self,
96            what: impl std::fmt::Display,
97            condition: impl AsyncFnMut() -> Result<bool>,
98        ) -> Result<()> {
99            self.wait_for(self.wait_timeout, what, condition).await
100        }
101
102        /// [`Self::wait_until`] where the default deadline is the wrong one,
103        /// because what is being waited for has a length of its own that is
104        /// known and is close to it. A wait that habitually lands just inside
105        /// its cap is not passing, it is winning a race.
106        ///
107        /// Every lookup `condition` makes is bounded by what is left of
108        /// `timeout`, so a slow one cannot carry the wait past it.
109        pub async fn wait_until_within(
110            &self,
111            timeout: Duration,
112            what: impl std::fmt::Display,
113            condition: impl AsyncFnMut() -> Result<bool>,
114        ) -> Result<()> {
115            self.wait_for(timeout, what, condition).await
116        }
117
118        /// [`Self::wait_until`] against a deadline of the caller's choosing.
119        async fn wait_for(
120            &self,
121            timeout: Duration,
122            what: impl std::fmt::Display,
123            mut condition: impl AsyncFnMut() -> Result<bool>,
124        ) -> Result<()> {
125            self.waiting.on(&what);
126
127            let held = crate::finding::poll(timeout, async || Ok(condition().await?.then_some(())))
128                .await?;
129
130            match held {
131                Some(()) => Ok(()),
132                None => Err(crate::finding::OutOfTime(format!(
133                    "Timed out after {timeout:?} waiting for {what}"
134                ))
135                .into()),
136            }
137        }
138
139        /// Wait until the text of every node matching `by` reads `expected`.
140        pub async fn wait_texts<const N: usize>(
141            &self,
142            by: impl IntoBy,
143            expected: [&str; N],
144        ) -> Result<()> {
145            let by = by.into_by();
146
147            tracing::trace!(?by, ?expected, "Waiting for texts");
148
149            let seen = std::cell::RefCell::new(Vec::new());
150
151            let result = self
152                .wait_until(format_args!("{by} to read {expected:?}"), async || {
153                    let texts = self.find_all_texts(by.clone()).await?;
154                    let matched = texts == expected;
155                    *seen.borrow_mut() = texts;
156                    Ok(matched)
157                })
158                .await;
159
160            match result {
161                Ok(()) => Ok(()),
162                Err(error) => {
163                    let seen = seen.into_inner();
164                    Err(error.context(format!("last read {seen:?}")))
165                }
166            }
167        }
168
169        /// Wait until exactly `expected` nodes match `by`.
170        ///
171        /// **Exact equality, polled, starting immediately -- which is a trap
172        /// directly after an action.** A call whose `expected` is the count that
173        /// was already on screen is answered by the very first poll, before the
174        /// action it is meant to be checking can have landed, so it asserts only
175        /// that the page has not caught up yet. It stays green for months and
176        /// then turns into a hard timeout the first time anything, however
177        /// unrelated, makes the page a few milliseconds slower to lay out --
178        /// and blames that change. Where the count is supposed to have *changed*,
179        /// read it before the action and say so with [`Self::wait_count_from`],
180        /// which refuses the degenerate case instead of passing it. Plain
181        /// `wait_count` belongs where a count is being established rather than
182        /// changed: a page just loaded, a selector first asserted.
183        pub async fn wait_count(&self, by: impl IntoBy, expected: usize) -> Result<()> {
184            let by = by.into_by();
185
186            tracing::trace!(?by, expected, "Waiting for count");
187
188            self.wait_until(format_args!("{by} to match {expected} nodes"), async || {
189                Ok(self.find_all(by.clone()).await?.len() == expected)
190            })
191            .await
192        }
193
194        /// How many nodes match `by` right now, without waiting for any
195        /// particular number of them. The before-read [`Self::wait_count_from`]
196        /// asks for.
197        #[inline]
198        pub async fn count(&self, by: impl IntoBy) -> Result<usize> {
199            Ok(self.find_all(by.into_by()).await?.len())
200        }
201
202        /// Wait until exactly `expected` nodes match `by`, having been told the
203        /// `before` count that the action in between was supposed to change.
204        ///
205        /// **The before-read is the whole point.** [`Self::wait_count`] cannot
206        /// tell "the action landed" apart from "the action has not started",
207        /// because both of those look exactly like the number it was given; this
208        /// can, because it knows which number meant "not yet". When `before`
209        /// already equals `expected` it refuses outright rather than passing on
210        /// the first poll, so the assertion that verifies nothing fails loudly
211        /// the day it is written instead of years later on somebody else's
212        /// change. Take `before` with [`Self::count`] immediately before the
213        /// action -- at the top of the test it is a different question, and
214        /// anything landing in between makes it a lie.
215        pub async fn wait_count_from(
216            &self,
217            by: impl IntoBy,
218            before: usize,
219            expected: usize,
220        ) -> Result<()> {
221            let by = by.into_by();
222
223            ensure!(
224                before != expected,
225                "Waiting for {by} to match {expected} nodes verifies nothing: \
226                 {expected} is also the count read before the action, so the \
227                 first poll agrees whether or not the action has landed. Assert \
228                 the count this action is supposed to produce, or if it really \
229                 is meant to leave the count alone, assert what it did change.",
230            );
231
232            tracing::trace!(?by, before, expected, "Waiting for count to change");
233
234            self.wait_until(
235                format_args!("{by} to go from {before} to {expected} nodes"),
236                async || Ok(self.find_all(by.clone()).await?.len() == expected),
237            )
238            .await
239        }
240
241        /// Find the text contents of all nodes match the given [`By`].
242        #[inline]
243        pub async fn find_all_texts(&self, by: impl IntoBy) -> Result<Vec<String>> {
244            let mut texts = Vec::new();
245
246            for item in self.find_all(by.into_by()).await? {
247                texts.push(item.text().await?);
248            }
249
250            Ok(texts)
251        }
252
253        /// Find an element by xpath.
254        #[inline]
255        pub async fn find_one_by_xpath(&self, xpath: &str) -> Result<TestElement> {
256            self.find_one_by(By::XPath(xpath)).await
257        }
258
259        /// Find the one element matching `by`, waiting for it to appear.
260        ///
261        /// **Refusing a second match is the point.** A selector that was meant
262        /// to name one thing and now names three is the way a guard goes quiet,
263        /// so this says so instead of picking. Where several *is* what the page
264        /// is, the question was never "the one": see [`Self::find_nth`].
265        pub async fn find_one_by(&self, by: impl IntoBy) -> Result<TestElement> {
266            let by = by.into_by();
267
268            tracing::trace!(?by, "Finding one element");
269
270            let found = crate::finding::poll(self.wait_timeout, async || {
271                let items = self.find_all(by.clone()).await?;
272
273                ensure!(
274                    items.len() <= 1,
275                    "Expected exactly one by {by}, but got {}: where several is \
276                     what the page is, ask for one of them by index with \
277                     find_nth, or for the first of them with find_first",
278                    items.len()
279                );
280
281                Ok(items.into_iter().next())
282            })
283            .await?;
284
285            found.ok_or_else(|| {
286                crate::finding::OutOfTime(format!(
287                    "Timed out after {:?} waiting for {by}",
288                    self.wait_timeout
289                ))
290                .into()
291            })
292        }
293
294        /// Find the `index`th element matching `by`, waiting for that many to
295        /// appear.
296        ///
297        /// **What a test asks when several is the answer**, and the reading twin
298        /// of [`TestDriver::press_nth`](crate::TestDriver::press_nth): the row a test appended is the one at
299        /// the end, three related buttons are three whatever is measured, and
300        /// neither is a broken selector for [`Self::find_one_by`] to refuse.
301        /// Asked here rather than by reaching for [`Self::find_all`] and
302        /// indexing the answer, which drops the wait along with the sentence
303        /// saying which one was wanted.
304        ///
305        /// A wait polling for an element to *arrive* still wants
306        /// [`Self::find_all`]: nothing there is an answer to that question, and
307        /// this has a deadline of its own to spend before it says so.
308        pub async fn find_nth(&self, by: impl IntoBy, index: usize) -> Result<TestElement> {
309            let by = by.into_by();
310
311            tracing::trace!(?by, index, "Finding one of several elements");
312
313            let found = crate::finding::poll(self.wait_timeout, async || {
314                Ok(self.find_all(by.clone()).await?.into_iter().nth(index))
315            })
316            .await?;
317
318            found.ok_or_else(|| {
319                crate::finding::OutOfTime(format!(
320                    "Timed out after {:?} waiting for {by} at {index}",
321                    self.wait_timeout
322                ))
323                .into()
324            })
325        }
326
327        /// The first element matching `by`, however many there turn out to be.
328        /// [`Self::find_nth`] says when that is the question.
329        #[inline]
330        pub async fn find_first(&self, by: impl IntoBy) -> Result<TestElement> {
331            self.find_nth(by, 0).await
332        }
333
334        /// Find all elements matching `by`.
335        pub async fn find_all(&self, by: impl IntoBy) -> Result<Vec<TestElement>> {
336            self.find_all_within(self.wait_timeout, by).await
337        }
338
339        /// [`Self::find_all`] with a bound of the caller's choosing on the call
340        /// itself, for putting the question to a browser which is still
341        /// starting. Inside a wait, the bound is never longer than what is left
342        /// of that wait. See
343        /// [`TestDriver::load_timeout`](crate::TestDriver::load_timeout).
344        pub async fn find_all_within(
345            &self,
346            timeout: Duration,
347            by: impl IntoBy,
348        ) -> Result<Vec<TestElement>> {
349            let by = by.into_by();
350            let timeout = crate::finding::bounded(timeout);
351            tracing::trace!(?by, "Finding all elements");
352
353            let task = self.inner.find_all(by.clone());
354            let sleep = time::sleep(timeout);
355
356            tokio::select! {
357                _ = sleep => {
358                    Err(crate::finding::OutOfTime(format!(
359                        "find_elements({by:?}) timed out after {timeout:?}"
360                    ))
361                    .into())
362                }
363                result = task => {
364                    Ok(result?.into_iter().map(|inner| TestElement { inner, wait_timeout: self.wait_timeout, waiting: self.waiting.clone(), holding: self.holding.clone() }).collect::<Vec<_>>())
365                }
366            }
367        }
368    }
369}
370
371pub(crate) use common;
372
373/// **Anything that names elements to find**, taken by every lookup on
374/// [`TestDriver`](crate::TestDriver) that says `by`.
375///
376/// A string (`&str` or `&String`) is a CSS selector; any other way of finding
377/// elements is written out as a [`By`].
378///
379/// # Examples
380///
381/// ```no_run
382/// use yew_e2e::prelude::*;
383///
384/// async fn lookups(driver: &TestDriver) -> Result<()> {
385///     // A CSS selector.
386///     driver.wait_count("li.item", 3).await?;
387///
388///     // One that was built rather than written out.
389///     let id = 7;
390///     driver.find_one_by(&format!("[data-test=row-{id}]")).await?;
391///
392///     // Any other `By`.
393///     driver.find_first(By::XPath("//button[text()='Save']")).await?;
394///     Ok(())
395/// }
396/// ```
397pub trait IntoBy {
398    /// The [`By`] this names.
399    fn into_by(self) -> By;
400}
401
402impl IntoBy for &str {
403    #[inline]
404    fn into_by(self) -> By {
405        By::Css(self)
406    }
407}
408
409/// A selector that was built rather than written out, such as one naming a
410/// control whose `data-test` carries an identifier in it.
411impl IntoBy for &String {
412    #[inline]
413    fn into_by(self) -> By {
414        By::Css(self.as_str())
415    }
416}
417
418impl IntoBy for By {
419    #[inline]
420    fn into_by(self) -> By {
421        self
422    }
423}
424
425#[cfg(test)]
426mod tests {
427    use anyhow::{Result, anyhow, bail};
428    use tokio::time::{self, Duration, Instant};
429
430    use super::{OutOfTime, bounded, poll};
431
432    /// A lookup that takes `takes` to answer, bounded as `find_all_within`
433    /// bounds one.
434    async fn slow_find(takes: Duration) -> Result<Option<()>> {
435        let bound = bounded(Duration::from_secs(5));
436
437        tokio::select! {
438            _ = time::sleep(bound) => Err(OutOfTime(format!("timed out after {bound:?}")).into()),
439            _ = time::sleep(takes) => Ok(None),
440        }
441    }
442
443    #[test]
444    fn outside_a_wait_a_bound_is_left_alone() {
445        assert_eq!(bounded(Duration::from_secs(5)), Duration::from_secs(5));
446    }
447
448    #[tokio::test(start_paused = true)]
449    async fn a_slow_lookup_does_not_carry_a_wait_past_its_deadline() -> Result<()> {
450        let start = Instant::now();
451
452        let found = poll(Duration::from_millis(300), async || {
453            slow_find(Duration::from_secs(3)).await
454        })
455        .await?;
456
457        assert!(found.is_none());
458        assert_eq!(start.elapsed(), Duration::from_millis(300));
459        Ok(())
460    }
461
462    #[tokio::test(start_paused = true)]
463    async fn a_poll_inside_a_wait_gives_up_with_it() -> Result<()> {
464        let start = Instant::now();
465
466        let found = poll(Duration::from_millis(300), async || {
467            match poll(Duration::from_secs(5), async || Ok(None::<()>)).await? {
468                Some(()) => Ok(Some(())),
469                None => Err(OutOfTime(String::from("the inner poll")).into()),
470            }
471        })
472        .await?;
473
474        assert!(found.is_none());
475        assert!(start.elapsed() < Duration::from_millis(400));
476        Ok(())
477    }
478
479    #[tokio::test(start_paused = true)]
480    async fn a_lookup_out_of_its_own_time_is_still_a_failure() -> Result<()> {
481        let result = poll(Duration::from_secs(60), async || {
482            slow_find(Duration::from_secs(10)).await
483        })
484        .await;
485
486        let Err(error) = result else {
487            bail!("a lookup that ran out of its own time passed");
488        };
489
490        assert_eq!(error.to_string(), "timed out after 5s");
491        Ok(())
492    }
493
494    #[tokio::test(start_paused = true)]
495    async fn an_attempt_that_fails_is_not_retried() -> Result<()> {
496        let mut attempts = 0;
497
498        let result = poll(Duration::from_secs(1), async || {
499            attempts += 1;
500            Err::<Option<()>, _>(anyhow!("broken"))
501        })
502        .await;
503
504        assert!(result.is_err());
505        assert_eq!(attempts, 1);
506        Ok(())
507    }
508}