Skip to main content

appium_client/
wait.rs

1//! Wait API for waiting for elements to appear on screen
2//!
3//! It's basically like [crate::find], but does not return results immediately.
4//! If the element is not on screen, then it tries to locate it again in intervals until it appears.
5//!
6//! Wait has two parameters: interval and timeout.
7//!
8//! **Interval** is how often to check if it appeared on screen.
9//! **Timeout** is how much time do you want to wait (max).
10//!
11//! If Appium finds the element before the timeout is exceeded, then it is returned immediately.
12//! If not, then the client will query Appium again after a given interval.
13//!
14//! ## Basic usage
15//! ```no_run
16//! use appium_client::capabilities::android::AndroidCapabilities;
17//!# use appium_client::capabilities::{AppCapable, UdidCapable, UiAutomator2AppCompatible};
18//! use appium_client::ClientBuilder;
19//! use appium_client::find::{AppiumFind, By};
20//!
21//!# #[tokio::main]
22//!# async fn main() -> Result<(), Box<dyn std::error::Error>> {
23//!# // create capabilities
24//!# use appium_client::wait::AppiumWait;
25//! let mut capabilities = AndroidCapabilities::new_uiautomator();
26//!# capabilities.udid("emulator-5554");
27//!# capabilities.app("/apps/sample.apk");
28//!# capabilities.app_wait_activity("com.example.AppActivity");
29//!#
30//! // create the client
31//! let client = ClientBuilder::native(capabilities)
32//!     .connect("http://localhost:4723/wd/hub/")
33//!     .await?;
34//!
35//! // wait until element appears
36//! let element = client
37//!     .appium_wait()
38//!     .for_element(By::accessibility_id("Wait for me"))
39//!     .await?;
40//!
41//! # Ok(())
42//! # }
43//! ```
44//!
45//! ## Tweaking the interval and timeout
46//! To change those parameters, use [Wait::check_every] (for changing the interval) and [Wait::at_most] (the timeout).
47//! See the documentation of those functions for more info.
48//!
49//! ```no_run
50//! use appium_client::capabilities::android::AndroidCapabilities;
51//!# use appium_client::capabilities::{AppCapable, UdidCapable, UiAutomator2AppCompatible};
52//! use appium_client::ClientBuilder;
53//! use appium_client::find::{AppiumFind, By};
54//!
55//!# #[tokio::main]
56//!# async fn main() -> Result<(), Box<dyn std::error::Error>> {
57//!# use std::time::Duration;
58//! // create capabilities
59//!# use appium_client::wait::AppiumWait;
60//! let mut capabilities = AndroidCapabilities::new_uiautomator();
61//!# capabilities.udid("emulator-5554");
62//!# capabilities.app("/apps/sample.apk");
63//!# capabilities.app_wait_activity("com.example.AppActivity");
64//!#
65//! // create the client
66//! let client = ClientBuilder::native(capabilities)
67//!     .connect("http://localhost:4723/wd/hub/")
68//!     .await?;
69//!
70//! // wait 1 s until element appears (and check every 250ms if it's appeared)
71//! let element = client
72//!     .appium_wait()
73//!     .check_every(Duration::from_millis(250))
74//!     .at_most(Duration::from_secs(1))
75//!     .for_element(By::accessibility_id("Wait for me"))
76//!     .await?;
77//!
78//! # Ok(())
79//! # }
80//! ```
81//!
82//! Waiting for a list of elements
83//! Instead of [Wait::for_element], there is [Wait::for_elements] (notice the **s** at the end).
84//! The second method returns a Vec of elements instead of one elements.
85//!
86//! When you use the second function, the wait works the same.
87//! It still waits in the same way, and waits for the element to appear.
88//!
89//! The only difference is that after AT LEAST ONE matching elements has appeared, the wait is over.
90//! You get the result, and the result is a Vec of all matching elements.
91//!
92//! That means - if all elements appeared simultaneously, then you will get all elements.
93//! This method will not wait for all possible elements to appear.
94//! So if some elements appear with a delay - then they might not be there.
95//! This method returns immediately after at least one match.
96//!
97use std::time::Duration;
98use fantoccini::Client;
99use fantoccini::elements::Element;
100use fantoccini::error::CmdError;
101use tokio::time::{Instant, interval};
102use crate::find::{AppiumFind, By};
103use async_trait::async_trait;
104
105pub trait AppiumWait {
106    fn appium_wait(&self) -> Wait<'_>;
107}
108
109impl AppiumWait for Client {
110    fn appium_wait(&self) -> Wait<'_> {
111        Wait {
112            client: self,
113            timeout: Duration::from_secs(30),
114            check_delay: Duration::from_millis(250),
115        }
116    }
117}
118
119/// Wait parameters
120#[derive(Debug)]
121pub struct Wait<'c> {
122    client: &'c Client,
123    timeout: Duration,
124    check_delay: Duration,
125}
126
127impl Wait<'_> {
128    /// Set the timeout for maximum wait.
129    ///
130    /// Checks are performed in a loop, with an interval.
131    /// To prevent infinite wait, the loop will exit after this timeout and the wait will result in an error indicating timeout.
132    ///
133    /// It is not guaranteed that the loop exits at the exact duration, as the check interval may hold it off.
134    /// It works like this:
135    /// 1. is the timeout exceeded?
136    /// 2. try to locate
137    /// 3. wait for interval
138    /// 4. repeat
139    pub fn at_most(mut self, timeout: Duration) -> Self {
140        self.timeout = timeout;
141        self
142    }
143
144    /// Sets the period to delay checks.
145    ///
146    /// Checks are performed in a loop, with an interval defined by this method.
147    /// For example, if you set it to 250 ms,
148    /// then the loop will check if element is present, wait 250 ms and repeat.
149    pub fn check_every(mut self, interval: Duration) -> Self {
150        self.check_delay = interval;
151        self
152    }
153
154    /// Waits for element using Appium locator.
155    ///
156    /// Tries to locate element in loop, with interval defined by "check delay".
157    /// If the timeout is exceeded, then it returns an error.
158    pub async fn for_element(self, search: By) -> Result<Element, CmdError> {
159        WaitOnSingle(WaitSelector::new(self, search))
160            .wait()
161            .await
162    }
163
164    /// Waits for a list of elements using Appium locator.
165    ///
166    /// Tries to locate list of elements in loop, with interval defined by "check delay".
167    /// If the timeout is exceeded, then it returns an error.
168    pub async fn for_elements(self, search: By) -> Result<Vec<Element>, CmdError> {
169        WaitOnMultiple(WaitSelector::new(self, search))
170            .wait()
171            .await
172    }
173}
174
175#[async_trait]
176trait AppiumWaitOnSelector<T> where Self: Sized {
177    /// Checks if target can be located, then returns the result.
178    /// If not found, waits for given delay and retries.
179    /// Loops until a timeout is exceeded.
180    async fn wait(self) -> Result<T, CmdError> {
181        let wait = self.get_wait();
182        let mut interval = interval(wait.check_delay);
183        let timeout = wait.timeout;
184
185        let start = Instant::now();
186        loop {
187            if start.elapsed() > timeout {
188                return Err(CmdError::WaitTimeout);
189            }
190
191            {
192                let find_element = self.locate();
193                if let Some(result) = find_element.await? {
194                    return Ok(result);
195                }
196            }
197
198            interval.tick().await;
199        }
200    }
201
202    /// Returns wait parameters
203    fn get_wait(&self) -> &Wait<'_>;
204
205    /// Logic for locating the target.
206    async fn locate(&self) -> Result<Option<T>, CmdError>;
207}
208
209
210struct WaitSelector<'a> {
211    wait: Wait<'a>,
212    selector: By,
213}
214
215impl<'a> WaitSelector<'a> {
216    pub fn new(wait: Wait, selector: By) -> WaitSelector {
217        WaitSelector {
218            wait,
219            selector,
220        }
221    }
222}
223
224struct WaitOnSingle<'a>(WaitSelector<'a>);
225
226struct WaitOnMultiple<'a>(WaitSelector<'a>);
227
228#[async_trait]
229impl<'a> AppiumWaitOnSelector<Element> for WaitOnSingle<'a> {
230    fn get_wait(&self) -> &Wait<'_> {
231        &self.0.wait
232    }
233
234    async fn locate(&self) -> Result<Option<Element>, CmdError> {
235        find_element(&self.0.wait, self.0.selector.clone()).await
236    }
237}
238
239#[async_trait]
240impl<'a> AppiumWaitOnSelector<Vec<Element>> for WaitOnMultiple<'a> {
241    fn get_wait(&self) -> &Wait<'_> {
242        &self.0.wait
243    }
244
245    async fn locate(&self) -> Result<Option<Vec<Element>>, CmdError> {
246        find_all_elements(&self.0.wait, self.0.selector.clone()).await
247    }
248}
249
250async fn find_element(wait: &Wait<'_>, selector: By) -> Result<Option<Element>, CmdError> {
251    match wait.client.find_by(selector).await {
252        Ok(element) => Ok(Some(element)),
253        Err(err) if err.is_no_such_element() => Ok(None),
254        Err(err) => Err(err),
255    }
256}
257
258async fn find_all_elements(wait: &Wait<'_>, selector: By) -> Result<Option<Vec<Element>>, CmdError> {
259    match wait.client.find_all_by(selector).await {
260        Ok(result) => Ok(Some(result)),
261        Err(err) if err.is_no_such_element() => Ok(None),
262        Err(err) => Err(err),
263    }
264}