use anyhow::{Context, Result, bail};
use thirtyfour::By;
use crate::driver::with_cleanup;
use crate::{TestDriver, WINDOW};
impl TestDriver {
pub async fn local_clock(&self, epoch_ms: u64) -> Result<[u32; 4]> {
let read = self
.inner
.execute(
"const d = new Date(arguments[0]); \
return [d.getMonth() + 1, d.getDate(), d.getHours(), d.getMinutes()]",
vec![serde_json::json!(epoch_ms)],
)
.await?;
let parts = read.json().as_array().context("clock array")?;
let mut clock = [0; 4];
for (slot, part) in clock.iter_mut().zip(parts) {
*slot = u32::try_from(part.as_u64().context("clock part")?)?;
}
Ok(clock)
}
pub async fn set_window_size(&self, width: u32, height: u32) -> Result<()> {
tracing::trace!(width, height, "Sizing the window");
self.inner.set_window_rect(0, 0, width, height).await?;
Ok(())
}
pub async fn what_the_page_says(&self) -> Result<String> {
let script = "const b = document.body; \
if (!b) { return 'and the document has no body at all'; } \
const page = b.getAttribute('data-page'); \
const threw = b.getAttribute('data-threw'); \
const mounted = b.children.length; \
let out = page ? `; the page showing is '${page}'` \
: '; nothing has claimed the page yet'; \
out += `, ${mounted} element(s) are mounted under the body`; \
if (threw) { out += `, and the page threw: ${threw}`; } \
out += `, the document is ${document.readyState}`; \
out += `, the bundle's exports are ${typeof window.wasmBindings}`; \
try { new WebAssembly.Module( \
new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0])); \
out += ', an empty module still compiles'; } \
catch (e) { out += ', and an empty module will not compile: ' + e; } \
out += ', history=' + history.length; \
const nav = performance.getEntriesByType('navigation')[0]; \
if (nav) { out += `, the document was answered after \
${Math.max(0, Math.round(nav.responseEnd))}ms`; } \
for (const got of performance.getEntriesByType('resource')) { \
if (!/\\.(wasm|js)(\\?|$)/.test(got.name)) { continue; } \
out += `, ${got.name.split('/').pop()} was fetched in \
${Math.round(got.duration)}ms`; } \
return out;";
let told = self.inner.execute(script, Vec::new()).await?;
Ok(told.json().as_str().unwrap_or_default().to_owned())
}
pub async fn wait_page(&self, page: &str) -> Result<()> {
tracing::trace!(page, "Waiting for page");
let selector = By::Css(format!("body[data-page={}]", css_string(page)));
let arrived = self
.wait_until_within(
self.load_timeout(),
format_args!("page {page}"),
async || {
Ok(!self
.find_all_within(self.load_timeout(), selector.clone())
.await?
.is_empty())
},
)
.await;
if let Err(error) = arrived {
bail!(
"{error}{}",
self.what_the_page_says().await.unwrap_or_default()
);
}
self.watch_for_errors().await
}
pub async fn visit(&self, url: &str, page: &str) -> Result<String> {
let was = self.inner.current_url().await?;
tracing::trace!(url, %was, page, "Visiting");
self.inner.goto(url).await?;
self.wait_page(page).await?;
Ok(was.to_string())
}
pub async fn wait_window(&self, window: &str) -> Result<()> {
tracing::trace!(window, "Waiting for window");
let selector = By::Css(format!("[data-window={}]", css_string(window)));
let arrived = self
.wait_until_within(
self.load_timeout(),
format_args!("window {window}"),
async || {
for element in self
.find_all_within(self.load_timeout(), selector.clone())
.await?
{
if element.visible().await.unwrap_or(false) {
return Ok(true);
}
}
Ok(false)
},
)
.await;
if let Err(error) = arrived {
bail!(
"{error}{}",
self.what_the_page_says().await.unwrap_or_default()
);
}
self.watch_for_errors().await
}
pub async fn reload(&self) -> Result<()> {
tracing::trace!("Reloading the page");
self.inner.refresh().await?;
self.rewatch().await
}
pub async fn reopen_with(&self, query: &str) -> Result<()> {
tracing::trace!(query, "Reopening the page");
let mut url = self.inner.current_url().await?;
url.set_query(Some(query));
self.inner.goto(url.as_str()).await?;
self.rewatch().await
}
pub async fn in_second_tab(&self, run: impl AsyncFnOnce() -> Result<()>) -> Result<()> {
self.in_second_context(true, run).await
}
pub async fn in_second_window(&self, run: impl AsyncFnOnce() -> Result<()>) -> Result<()> {
self.in_second_context(false, run).await
}
pub async fn in_new_tab(
&self,
window: &str,
run: impl AsyncFnOnce() -> Result<()>,
) -> Result<()> {
self.in_second_tab(async move || {
self.wait_window(window).await?;
run().await
})
.await
}
pub async fn in_new_window(
&self,
window: &str,
run: impl AsyncFnOnce() -> Result<()>,
) -> Result<()> {
self.in_second_window(async move || {
self.wait_window(window).await?;
run().await
})
.await
}
async fn in_second_context(
&self,
tab: bool,
run: impl AsyncFnOnce() -> Result<()>,
) -> Result<()> {
let original = self.inner.window().await?;
let url = self.inner.current_url().await?;
let opened = if tab {
self.inner.new_tab().await?
} else {
self.inner.new_window().await?
};
let result = async {
self.inner.switch_to_window(opened.clone()).await?;
self.set_window_size(WINDOW.0, WINDOW.1).await?;
self.inner.goto(url.as_str()).await?;
self.rewatch().await?;
run().await?;
match self.error_seen().await? {
Some(threw) => bail!("the page threw: {threw}"),
None => Ok(()),
}
}
.await;
let cleanup = async {
self.inner.switch_to_window(opened).await?;
self.inner.close_window().await?;
self.inner.switch_to_window(original).await?;
Ok(())
}
.await;
match result {
Ok(()) => cleanup,
Err(error) => Err(with_cleanup(error, cleanup)),
}
}
}
fn css_string(value: &str) -> String {
format!("'{}'", value.replace('\\', "\\\\").replace('\'', "\\'"))
}