Skip to main content

yew_e2e/test_driver/
navigation.rs

1//! Where the browser is: its window, its clock, waiting for a page or window
2//! to show, and going to a page again or in a second tab or window.
3
4use anyhow::{Context, Result, bail};
5use thirtyfour::By;
6
7use crate::driver::with_cleanup;
8use crate::{TestDriver, WINDOW};
9
10impl TestDriver {
11    /// **`epoch_ms` on the browser's own clock**: its month (from one), day,
12    /// hour and minute, for a test reading a time the page shows in the
13    /// reader's zone.
14    pub async fn local_clock(&self, epoch_ms: u64) -> Result<[u32; 4]> {
15        let read = self
16            .inner
17            .execute(
18                "const d = new Date(arguments[0]); \
19                 return [d.getMonth() + 1, d.getDate(), d.getHours(), d.getMinutes()]",
20                vec![serde_json::json!(epoch_ms)],
21            )
22            .await?;
23        let parts = read.json().as_array().context("clock array")?;
24        let mut clock = [0; 4];
25
26        for (slot, part) in clock.iter_mut().zip(parts) {
27            *slot = u32::try_from(part.as_u64().context("clock part")?)?;
28        }
29
30        Ok(clock)
31    }
32
33    /// Resize the browser window.
34    pub async fn set_window_size(&self, width: u32, height: u32) -> Result<()> {
35        tracing::trace!(width, height, "Sizing the window");
36        self.inner.set_window_rect(0, 0, width, height).await?;
37        Ok(())
38    }
39
40    /// What a page that did not become what was asked for has to say for
41    /// itself, as a sentence to hang off a timeout: whether anything is
42    /// mounted, what `data-page` the body carries, what it threw, and how the
43    /// document and its bundle loaded.
44    pub async fn what_the_page_says(&self) -> Result<String> {
45        let script = "const b = document.body; \
46             if (!b) { return 'and the document has no body at all'; } \
47             const page = b.getAttribute('data-page'); \
48             const threw = b.getAttribute('data-threw'); \
49             const mounted = b.children.length; \
50             let out = page ? `; the page showing is '${page}'` \
51                 : '; nothing has claimed the page yet'; \
52             out += `, ${mounted} element(s) are mounted under the body`; \
53             if (threw) { out += `, and the page threw: ${threw}`; } \
54             out += `, the document is ${document.readyState}`; \
55             out += `, the bundle's exports are ${typeof window.wasmBindings}`; \
56             try { new WebAssembly.Module( \
57                 new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0])); \
58                 out += ', an empty module still compiles'; } \
59             catch (e) { out += ', and an empty module will not compile: ' + e; } \
60             out += ', history=' + history.length; \
61             const nav = performance.getEntriesByType('navigation')[0]; \
62             if (nav) { out += `, the document was answered after \
63                 ${Math.max(0, Math.round(nav.responseEnd))}ms`; } \
64             for (const got of performance.getEntriesByType('resource')) { \
65                 if (!/\\.(wasm|js)(\\?|$)/.test(got.name)) { continue; } \
66                 out += `, ${got.name.split('/').pop()} was fetched in \
67                     ${Math.round(got.duration)}ms`; } \
68             return out;";
69
70        let told = self.inner.execute(script, Vec::new()).await?;
71        Ok(told.json().as_str().unwrap_or_default().to_owned())
72    }
73
74    /// Wait for the body to carry `data-page` = `page`, then watch the page
75    /// for errors. Gives up after [`Self::load_timeout`] with
76    /// [`Self::what_the_page_says`].
77    pub async fn wait_page(&self, page: &str) -> Result<()> {
78        tracing::trace!(page, "Waiting for page");
79
80        let selector = By::Css(format!("body[data-page={}]", css_string(page)));
81
82        let arrived = self
83            .wait_until_within(
84                self.load_timeout(),
85                format_args!("page {page}"),
86                async || {
87                    Ok(!self
88                        .find_all_within(self.load_timeout(), selector.clone())
89                        .await?
90                        .is_empty())
91                },
92            )
93            .await;
94
95        if let Err(error) = arrived {
96            bail!(
97                "{error}{}",
98                self.what_the_page_says().await.unwrap_or_default()
99            );
100        }
101
102        self.watch_for_errors().await
103    }
104
105    /// Go to `url` and [wait for `page`](Self::wait_page), returning the
106    /// address the browser was at before.
107    pub async fn visit(&self, url: &str, page: &str) -> Result<String> {
108        let was = self.inner.current_url().await?;
109
110        tracing::trace!(url, %was, page, "Visiting");
111
112        self.inner.goto(url).await?;
113        self.wait_page(page).await?;
114        Ok(was.to_string())
115    }
116
117    /// Wait for a visible element whose `data-window` is `window`, then watch
118    /// the page for errors. Gives up after [`Self::load_timeout`] with
119    /// [`Self::what_the_page_says`].
120    pub async fn wait_window(&self, window: &str) -> Result<()> {
121        tracing::trace!(window, "Waiting for window");
122
123        let selector = By::Css(format!("[data-window={}]", css_string(window)));
124
125        let arrived = self
126            .wait_until_within(
127                self.load_timeout(),
128                format_args!("window {window}"),
129                async || {
130                    for element in self
131                        .find_all_within(self.load_timeout(), selector.clone())
132                        .await?
133                    {
134                        if element.visible().await.unwrap_or(false) {
135                            return Ok(true);
136                        }
137                    }
138
139                    Ok(false)
140                },
141            )
142            .await;
143
144        if let Err(error) = arrived {
145            bail!(
146                "{error}{}",
147                self.what_the_page_says().await.unwrap_or_default()
148            );
149        }
150
151        self.watch_for_errors().await
152    }
153
154    /// Reload the page, which is the only way to ask what the *server* holds.
155    /// A test watching for errors goes on watching the reloaded page.
156    pub async fn reload(&self) -> Result<()> {
157        tracing::trace!("Reloading the page");
158        self.inner.refresh().await?;
159        self.rewatch().await
160    }
161
162    /// Open the page again with `query` in the address. A test watching for
163    /// errors goes on watching the reopened page.
164    pub async fn reopen_with(&self, query: &str) -> Result<()> {
165        tracing::trace!(query, "Reopening the page");
166
167        let mut url = self.inner.current_url().await?;
168        url.set_query(Some(query));
169        self.inner.goto(url.as_str()).await?;
170        self.rewatch().await
171    }
172
173    /// Run `run` in a second tab showing the page this one shows, then close
174    /// it and come back. The tab is sized as every test's first one is, and
175    /// `run` is what waits for the page to come up. A test watching for errors
176    /// goes on watching in the second tab, and what the page there threw fails
177    /// it as it would the test; a test that never asked for the watch is left
178    /// unwatched there too.
179    pub async fn in_second_tab(&self, run: impl AsyncFnOnce() -> Result<()>) -> Result<()> {
180        self.in_second_context(true, run).await
181    }
182
183    /// The same in a second window.
184    pub async fn in_second_window(&self, run: impl AsyncFnOnce() -> Result<()>) -> Result<()> {
185        self.in_second_context(false, run).await
186    }
187
188    /// [`Self::in_second_tab`], [waiting for `window`](Self::wait_window)
189    /// there before `run`.
190    pub async fn in_new_tab(
191        &self,
192        window: &str,
193        run: impl AsyncFnOnce() -> Result<()>,
194    ) -> Result<()> {
195        self.in_second_tab(async move || {
196            self.wait_window(window).await?;
197            run().await
198        })
199        .await
200    }
201
202    /// [`Self::in_second_window`], [waiting for `window`](Self::wait_window)
203    /// there before `run`.
204    pub async fn in_new_window(
205        &self,
206        window: &str,
207        run: impl AsyncFnOnce() -> Result<()>,
208    ) -> Result<()> {
209        self.in_second_window(async move || {
210            self.wait_window(window).await?;
211            run().await
212        })
213        .await
214    }
215
216    async fn in_second_context(
217        &self,
218        tab: bool,
219        run: impl AsyncFnOnce() -> Result<()>,
220    ) -> Result<()> {
221        let original = self.inner.window().await?;
222        let url = self.inner.current_url().await?;
223        let opened = if tab {
224            self.inner.new_tab().await?
225        } else {
226            self.inner.new_window().await?
227        };
228
229        let result = async {
230            self.inner.switch_to_window(opened.clone()).await?;
231            self.set_window_size(WINDOW.0, WINDOW.1).await?;
232            self.inner.goto(url.as_str()).await?;
233            self.rewatch().await?;
234            run().await?;
235            match self.error_seen().await? {
236                Some(threw) => bail!("the page threw: {threw}"),
237                None => Ok(()),
238            }
239        }
240        .await;
241
242        let cleanup = async {
243            self.inner.switch_to_window(opened).await?;
244            self.inner.close_window().await?;
245            self.inner.switch_to_window(original).await?;
246            Ok(())
247        }
248        .await;
249
250        match result {
251            Ok(()) => cleanup,
252            Err(error) => Err(with_cleanup(error, cleanup)),
253        }
254    }
255}
256
257fn css_string(value: &str) -> String {
258    format!("'{}'", value.replace('\\', "\\\\").replace('\'', "\\'"))
259}