Skip to main content

thirtyfour/extensions/query/
element_waiter.rs

1use super::conditions::{collect_arg_slice, handle_errors};
2use super::{ElementPollerWithTimeout, IntoElementPoller, conditions};
3use crate::IntoArcStr;
4use crate::error::WebDriverError;
5use crate::prelude::WebDriverResult;
6use crate::{DynElementPredicate, ElementPredicate, WebElement};
7use std::ops::Deref;
8use std::sync::Arc;
9use std::time::Duration;
10use stringmatch::Needle;
11
12/// High-level interface for performing explicit waits using the builder pattern.
13///
14/// # Example:
15/// ```no_run
16/// # use thirtyfour::prelude::*;
17/// # use thirtyfour::support::block_on;
18/// #
19/// # fn main() -> WebDriverResult<()> {
20/// #     block_on(async {
21/// #         let caps = DesiredCapabilities::chrome();
22/// #         let mut driver = WebDriver::new("http://localhost:4444", caps).await?;
23/// let elem = driver.query(By::Id("button1")).first().await?;
24/// // Wait until the element is displayed.
25/// elem.wait_until().displayed().await?;
26/// #         driver.quit().await?;
27/// #         Ok(())
28/// #     })
29/// # }
30/// ```
31#[derive(Debug)]
32pub struct ElementWaiter {
33    element: WebElement,
34    poller: Arc<dyn IntoElementPoller + Send + Sync>,
35    message: String,
36    ignore_errors: bool,
37}
38
39impl ElementWaiter {
40    /// Create a new `ElementWaiter`.
41    ///
42    /// See `Element::wait_until()` rather than creating this directly.
43    pub fn new(element: WebElement, poller: Arc<dyn IntoElementPoller + Send + Sync>) -> Self {
44        Self {
45            element,
46            poller,
47            message: String::new(),
48            ignore_errors: true,
49        }
50    }
51
52    /// Use the specified ElementPoller for this ElementWaiter.
53    /// This will not affect the default ElementPoller used for other waits.
54    pub fn with_poller(mut self, poller: Arc<dyn IntoElementPoller + Send + Sync>) -> Self {
55        self.poller = poller;
56        self
57    }
58
59    /// Provide a human-readable error message to be returned in the case of timeout.
60    pub fn error(mut self, message: &str) -> Self {
61        self.message = message.to_string();
62        self
63    }
64
65    /// By default, a waiter will ignore any errors that occur while polling for the desired
66    /// condition(s). However, this behaviour can be modified so that the waiter will return
67    /// early if an error is returned from thirtyfour.
68    pub fn ignore_errors(mut self, ignore: bool) -> Self {
69        self.ignore_errors = ignore;
70        self
71    }
72
73    /// Force this ElementWaiter to wait for the specified timeout, polling once
74    /// after each interval. This will override the poller for this
75    /// ElementWaiter only.
76    pub fn wait(self, timeout: Duration, interval: Duration) -> Self {
77        self.with_poller(Arc::new(ElementPollerWithTimeout::new(timeout, interval)))
78    }
79
80    async fn run_poller<'a, F, I, P>(&self, conditions: F) -> WebDriverResult<bool>
81    where
82        F: Fn() -> I,
83        I: IntoIterator<Item = &'a P>,
84        P: ElementPredicate + ?Sized + 'a,
85    {
86        let mut poller = self.poller.start();
87        loop {
88            let mut conditions_met = true;
89            for f in conditions() {
90                if !f.call(self.element.clone()).await? {
91                    conditions_met = false;
92                    break;
93                }
94            }
95
96            if conditions_met {
97                return Ok(true);
98            }
99
100            if !poller.tick().await {
101                return Ok(false);
102            }
103        }
104    }
105
106    fn timeout(self) -> WebDriverResult<()> {
107        Err(WebDriverError::Timeout(format!("element condition timed out: {}", self.message)))
108    }
109
110    /// Wait for the specified condition to be true.
111    pub async fn condition(self, f: impl ElementPredicate) -> WebDriverResult<()> {
112        match self.run_poller(|| [&f].into_iter()).await? {
113            true => Ok(()),
114            false => self.timeout(),
115        }
116    }
117
118    /// Wait for the specified conditions to be true.
119    pub async fn conditions(
120        self,
121        conditions: Vec<Box<DynElementPredicate>>,
122    ) -> WebDriverResult<()> {
123        match self.run_poller(|| conditions.iter().map(Box::deref)).await? {
124            true => Ok(()),
125            false => self.timeout(),
126        }
127    }
128
129    /// Wait for the element to become stale.
130    pub async fn stale(self) -> WebDriverResult<()> {
131        let ignore_errors = self.ignore_errors;
132        self.condition(move |elem: WebElement| async move {
133            handle_errors(elem.is_present().await.map(|x| !x), ignore_errors)
134        })
135        .await
136    }
137
138    /// Wait for the element to be displayed.
139    pub async fn displayed(self) -> WebDriverResult<()> {
140        let ignore_errors = self.ignore_errors;
141        self.condition(conditions::element_is_displayed(ignore_errors)).await
142    }
143
144    /// Wait for the element to not be displayed.
145    pub async fn not_displayed(self) -> WebDriverResult<()> {
146        let ignore_errors = self.ignore_errors;
147        self.condition(conditions::element_is_not_displayed(ignore_errors)).await
148    }
149
150    /// Wait for the element to be selected.
151    pub async fn selected(self) -> WebDriverResult<()> {
152        let ignore_errors = self.ignore_errors;
153        self.condition(conditions::element_is_selected(ignore_errors)).await
154    }
155
156    /// Wait for the element to not be selected.
157    pub async fn not_selected(self) -> WebDriverResult<()> {
158        let ignore_errors = self.ignore_errors;
159        self.condition(conditions::element_is_not_selected(ignore_errors)).await
160    }
161
162    /// Wait for the element to be enabled.
163    pub async fn enabled(self) -> WebDriverResult<()> {
164        let ignore_errors = self.ignore_errors;
165        self.condition(conditions::element_is_enabled(ignore_errors)).await
166    }
167
168    /// Wait for the element to not be enabled.
169    pub async fn not_enabled(self) -> WebDriverResult<()> {
170        let ignore_errors = self.ignore_errors;
171        self.condition(conditions::element_is_not_enabled(ignore_errors)).await
172    }
173
174    /// Wait for the element to be clickable.
175    pub async fn clickable(self) -> WebDriverResult<()> {
176        let ignore_errors = self.ignore_errors;
177        self.condition(conditions::element_is_clickable(ignore_errors)).await
178    }
179
180    /// Wait for the element to not be clickable.
181    pub async fn not_clickable(self) -> WebDriverResult<()> {
182        let ignore_errors = self.ignore_errors;
183        self.condition(conditions::element_is_not_clickable(ignore_errors)).await
184    }
185
186    /// Wait until the element has the specified class.
187    pub async fn has_class<N>(self, class_name: N) -> WebDriverResult<()>
188    where
189        N: Needle + Clone + Send + Sync + 'static,
190    {
191        let ignore_errors = self.ignore_errors;
192        self.condition(conditions::element_has_class(class_name, ignore_errors)).await
193    }
194
195    /// Wait until the element lacks the specified class.
196    pub async fn lacks_class<N>(self, class_name: N) -> WebDriverResult<()>
197    where
198        N: Needle + Clone + Send + Sync + 'static,
199    {
200        let ignore_errors = self.ignore_errors;
201        self.condition(conditions::element_lacks_class(class_name, ignore_errors)).await
202    }
203
204    /// Wait until the element has the specified text.
205    pub async fn has_text<N>(self, text: N) -> WebDriverResult<()>
206    where
207        N: Needle + Clone + Send + Sync + 'static,
208    {
209        let ignore_errors = self.ignore_errors;
210        self.condition(conditions::element_has_text(text, ignore_errors)).await
211    }
212
213    /// Wait until the element lacks the specified text.
214    pub async fn lacks_text<N>(self, text: N) -> WebDriverResult<()>
215    where
216        N: Needle + Clone + Send + Sync + 'static,
217    {
218        let ignore_errors = self.ignore_errors;
219        self.condition(conditions::element_lacks_text(text, ignore_errors)).await
220    }
221
222    /// Wait until the element has the specified value.
223    pub async fn has_value<N>(self, value: N) -> WebDriverResult<()>
224    where
225        N: Needle + Clone + Send + Sync + 'static,
226    {
227        let ignore_errors = self.ignore_errors;
228        self.condition(conditions::element_has_value(value, ignore_errors)).await
229    }
230
231    /// Wait until the element lacks the specified value.
232    pub async fn lacks_value<N>(self, value: N) -> WebDriverResult<()>
233    where
234        N: Needle + Clone + Send + Sync + 'static,
235    {
236        let ignore_errors = self.ignore_errors;
237        self.condition(conditions::element_lacks_value(value, ignore_errors)).await
238    }
239
240    /// Wait until the element has the specified attribute.
241    pub async fn has_attribute<S, N>(self, attribute_name: S, value: N) -> WebDriverResult<()>
242    where
243        S: IntoArcStr,
244        N: Needle + Clone + Send + Sync + 'static,
245    {
246        let ignore_errors = self.ignore_errors;
247        self.condition(conditions::element_has_attribute(
248            attribute_name.into(),
249            value,
250            ignore_errors,
251        ))
252        .await
253    }
254
255    /// Wait until the element lacks the specified attribute.
256    pub async fn lacks_attribute<S, N>(self, attribute_name: S, value: N) -> WebDriverResult<()>
257    where
258        S: IntoArcStr,
259        N: Needle + Clone + Send + Sync + 'static,
260    {
261        let ignore_errors = self.ignore_errors;
262        self.condition(conditions::element_lacks_attribute(
263            attribute_name.into(),
264            value,
265            ignore_errors,
266        ))
267        .await
268    }
269
270    /// Wait until the element has all the specified attributes.
271    pub async fn has_attributes<S, N>(
272        self,
273        desired_attributes: impl IntoIterator<Item = (S, N)>,
274    ) -> WebDriverResult<()>
275    where
276        S: IntoArcStr,
277        N: Needle + Send + Sync + 'static,
278    {
279        let ignore_errors = self.ignore_errors;
280        self.condition(conditions::element_has_attributes(
281            collect_arg_slice(desired_attributes),
282            ignore_errors,
283        ))
284        .await
285    }
286
287    /// Wait until the element lacks all the specified attributes.
288    pub async fn lacks_attributes<S, N>(
289        self,
290        desired_attributes: impl IntoIterator<Item = (S, N)>,
291    ) -> WebDriverResult<()>
292    where
293        S: IntoArcStr,
294        N: Needle + Send + Sync + 'static,
295    {
296        let ignore_errors = self.ignore_errors;
297        self.condition(conditions::element_lacks_attributes(
298            collect_arg_slice(desired_attributes),
299            ignore_errors,
300        ))
301        .await
302    }
303
304    /// Wait until the element has the specified property.
305    pub async fn has_property<S, N>(self, property_name: S, value: N) -> WebDriverResult<()>
306    where
307        S: IntoArcStr,
308        N: Needle + Clone + Send + Sync + 'static,
309    {
310        let ignore_errors = self.ignore_errors;
311        self.condition(conditions::element_has_property(property_name.into(), value, ignore_errors))
312            .await
313    }
314
315    /// Wait until the element lacks the specified property.
316    pub async fn lacks_property<S, N>(self, property_name: S, value: N) -> WebDriverResult<()>
317    where
318        S: IntoArcStr,
319        N: Needle + Clone + Send + Sync + 'static,
320    {
321        let ignore_errors = self.ignore_errors;
322        self.condition(conditions::element_lacks_property(
323            property_name.into(),
324            value,
325            ignore_errors,
326        ))
327        .await
328    }
329
330    /// Wait until the element has all the specified properties.
331    pub async fn has_properties<S, N>(
332        self,
333        desired_properties: impl IntoIterator<Item = (S, N)>,
334    ) -> WebDriverResult<()>
335    where
336        S: IntoArcStr,
337        N: Needle + Send + Sync + 'static,
338    {
339        let desired_properties: Arc<[(Arc<str>, N)]> =
340            desired_properties.into_iter().map(|(a, b)| (a.into(), b)).collect();
341        let ignore_errors = self.ignore_errors;
342        self.condition(conditions::element_has_properties(desired_properties, ignore_errors)).await
343    }
344
345    /// Wait until the element lacks all the specified properties.
346    pub async fn lacks_properties<S, N>(
347        self,
348        desired_properties: impl IntoIterator<Item = (S, N)>,
349    ) -> WebDriverResult<()>
350    where
351        S: IntoArcStr,
352        N: Needle + Send + Sync + 'static,
353    {
354        let ignore_errors = self.ignore_errors;
355        self.condition(conditions::element_lacks_properties(
356            collect_arg_slice(desired_properties),
357            ignore_errors,
358        ))
359        .await
360    }
361
362    /// Wait until the element has the specified CSS property.
363    pub async fn has_css_property<S, N>(self, css_property_name: S, value: N) -> WebDriverResult<()>
364    where
365        S: IntoArcStr,
366        N: Needle + Clone + Send + Sync + 'static,
367    {
368        let ignore_errors = self.ignore_errors;
369        self.condition(conditions::element_has_css_property(
370            css_property_name.into(),
371            value,
372            ignore_errors,
373        ))
374        .await
375    }
376
377    /// Wait until the element lacks the specified CSS property.
378    pub async fn lacks_css_property<S, N>(
379        self,
380        css_property_name: S,
381        value: N,
382    ) -> WebDriverResult<()>
383    where
384        S: IntoArcStr,
385        N: Needle + Clone + Send + Sync + 'static,
386    {
387        let ignore_errors = self.ignore_errors;
388        self.condition(conditions::element_lacks_css_property(
389            css_property_name.into(),
390            value,
391            ignore_errors,
392        ))
393        .await
394    }
395
396    /// Wait until the element has all the specified CSS properties.
397    pub async fn has_css_properties<S, N>(
398        self,
399        desired_css_properties: impl IntoIterator<Item = (S, N)>,
400    ) -> WebDriverResult<()>
401    where
402        S: IntoArcStr,
403        N: Needle + Send + Sync + 'static,
404    {
405        let ignore_errors = self.ignore_errors;
406        self.condition(conditions::element_has_css_properties(
407            collect_arg_slice(desired_css_properties),
408            ignore_errors,
409        ))
410        .await
411    }
412
413    /// Wait until the element lacks all the specified CSS properties.
414    pub async fn lacks_css_properties<S, N>(
415        self,
416        desired_css_properties: impl IntoIterator<Item = (S, N)>,
417    ) -> WebDriverResult<()>
418    where
419        S: IntoArcStr,
420        N: Needle + Send + Sync + 'static,
421    {
422        let ignore_errors = self.ignore_errors;
423        self.condition(conditions::element_lacks_css_properties(
424            collect_arg_slice(desired_css_properties),
425            ignore_errors,
426        ))
427        .await
428    }
429}
430
431/// Trait for enabling the ElementWaiter interface.
432pub trait ElementWaitable {
433    /// Wait until the element meets one or more conditions.
434    fn wait_until(&self) -> ElementWaiter;
435}
436
437impl ElementWaitable for WebElement {
438    /// Return an ElementWaiter instance for more executing powerful explicit waits.
439    ///
440    /// This uses the builder pattern to construct explicit waits using one of the
441    /// provided predicates. Or you can provide your own custom predicate if desired.
442    ///
443    /// See [`ElementWaiter`] for more documentation.
444    fn wait_until(&self) -> ElementWaiter {
445        ElementWaiter::new(self.clone(), self.handle.config().poller.clone())
446    }
447}
448
449#[cfg(test)]
450/// This function checks if the public async methods implement Send. It is not intended to be executed.
451async fn _test_is_send() -> WebDriverResult<()> {
452    use crate::prelude::*;
453
454    // Helper methods
455    fn is_send<T: Send>() {}
456    fn is_send_val<T: Send>(_val: &T) {}
457
458    // Pre values
459    let caps = DesiredCapabilities::chrome();
460    let driver = WebDriver::new("http://localhost:4444", caps).await?;
461    let elem = driver.find(By::Css(r#"div"#)).await?;
462
463    // ElementWaitCondition
464    is_send_val(&elem.wait_until().stale());
465    is_send_val(&elem.wait_until().displayed());
466    is_send_val(&elem.wait_until().selected());
467    is_send_val(&elem.wait_until().enabled());
468    is_send_val(
469        &elem.wait_until().condition(move |elem: WebElement| async move {
470            elem.is_enabled().await.or(Ok(false))
471        }),
472    );
473
474    Ok(())
475}