1#![warn(missing_docs)]
168#![deny(rustdoc::broken_intra_doc_links)]
169
170use std::fmt::Write;
171use std::future::Future;
172use std::panic::AssertUnwindSafe;
173use std::path::{Path, PathBuf};
174use std::pin::pin;
175use std::sync::{Arc, Mutex};
176
177use anyhow::{Context, Result, anyhow, bail, ensure};
178use futures_util::FutureExt;
179use thirtyfour::common::types::ElementRect;
180use thirtyfour::prelude::*;
181use tokio::time::{self, Duration};
182
183mod dist;
184mod driver;
185mod fetch;
186pub mod harness;
187#[cfg(test)]
188mod lib_tests;
189mod run_lock;
190mod sandbox;
191mod sessions;
192
193pub use self::dist::{dist, target_dir, workspace_root};
194pub use self::driver::Engine;
195
196use self::driver::{Driver, QUIT_TIMEOUT, STARTUP_TIMEOUT, with_cleanup};
197
198pub mod prelude {
209 pub use anyhow::{Context, Result, anyhow, bail, ensure};
210 pub use thirtyfour::prelude::*;
211
212 pub use crate::{TestDriver, TestElement};
215}
216
217pub trait Fixture: Sized + 'static {
224 type Setup: Default;
228
229 fn config() -> Config {
231 Config::default()
232 }
233
234 fn init_tracing() {
237 _ = tracing_subscriber::fmt()
238 .with_max_level(tracing::Level::INFO)
239 .try_init();
240 }
241
242 fn enter_sandbox(root: &Path) -> Result<()> {
247 _ = root;
248 Ok(())
249 }
250
251 fn check() -> Result<()> {
254 Ok(())
255 }
256
257 fn start(setup: Self::Setup) -> impl Future<Output = Result<Self>>;
259
260 fn url(&self) -> String;
262
263 fn quit(self) -> impl Future<Output = Result<()>>;
265}
266
267#[derive(Debug, Clone)]
269pub struct Config {
270 pub(crate) about: String,
271 pub(crate) frontend: Frontend,
272 pub(crate) lock: String,
273 pub(crate) sessions: String,
274}
275
276impl Default for Config {
277 fn default() -> Self {
278 Self {
279 about: String::from("A browser suite."),
280 frontend: Frontend::Trunk(PathBuf::new()),
281 lock: String::from("yew-e2e.lock"),
282 sessions: String::from("e2e-sessions"),
283 }
284 }
285}
286
287impl Config {
288 pub fn about(mut self, about: impl Into<String>) -> Self {
290 self.about = about.into();
291 self
292 }
293
294 pub fn frontend(mut self, frontend: Frontend) -> Self {
296 self.frontend = frontend;
297 self
298 }
299
300 pub fn lock_name(mut self, name: impl Into<String>) -> Self {
302 self.lock = name.into();
303 self
304 }
305
306 pub fn sessions_dir(mut self, name: impl Into<String>) -> Self {
310 self.sessions = name.into();
311 self
312 }
313}
314
315#[derive(Debug, Clone)]
318pub enum Frontend {
319 None,
321 Trunk(PathBuf),
325}
326
327#[derive(Clone, Default)]
336pub(crate) struct Waiting(Arc<Mutex<Option<String>>>);
337
338impl Waiting {
339 fn on(&self, what: impl std::fmt::Display) {
341 *self.held() = Some(what.to_string());
342 }
343
344 fn clear(&self) {
346 *self.held() = None;
347 }
348
349 pub(crate) fn clause(&self) -> String {
352 match &*self.held() {
353 Some(what) => format!(", last waiting for {what}"),
354 None => String::new(),
355 }
356 }
357
358 fn held(&self) -> std::sync::MutexGuard<'_, Option<String>> {
361 self.0.lock().unwrap_or_else(|held| held.into_inner())
362 }
363}
364
365pub(crate) struct Browser {
367 webdriver: Driver,
368 driver: TestDriver,
369}
370
371impl Browser {
372 pub(crate) async fn open() -> Result<Self> {
374 let engine = crate::harness::engine();
375 let deadline = time::Instant::now() + STARTUP_TIMEOUT;
376 let caps = engine.capabilities(crate::harness::headed())?;
377 let webdriver = Driver::new(engine, deadline).await?;
378 Self::connect(webdriver, caps, deadline).await
379 }
380
381 async fn connect(
382 mut webdriver: Driver,
383 mut caps: Capabilities,
384 deadline: time::Instant,
385 ) -> Result<Self> {
386 let downloads = tempfile::tempdir().context("creating browser download directory")?;
387 let directory = downloads.path().to_string_lossy().into_owned();
388 let key = match webdriver.engine() {
389 Engine::Firefox => "moz:firefoxOptions",
390 Engine::Chrome => "goog:chromeOptions",
391 };
392 if !caps.contains_key(key) {
393 caps.set(key, serde_json::json!({}))?;
394 }
395 match webdriver.engine() {
396 Engine::Firefox => {
397 let options = caps
398 .get_mut("moz:firefoxOptions")
399 .context("Firefox capabilities have no options")?;
400 let prefs = options
401 .as_object_mut()
402 .context("Firefox options")?
403 .entry("prefs")
404 .or_insert_with(|| serde_json::json!({}));
405 let prefs = prefs.as_object_mut().context("Firefox preferences")?;
406 prefs.insert("browser.download.folderList".into(), 2.into());
407 prefs.insert("browser.download.dir".into(), directory.into());
408 prefs.insert("browser.download.useDownloadDir".into(), true.into());
409 prefs.insert(
410 "browser.helperApps.neverAsk.saveToDisk".into(),
411 "audio/wav,application/zip,application/json".into(),
412 );
413 }
414 Engine::Chrome => {
415 let options = caps
416 .get_mut("goog:chromeOptions")
417 .context("Chrome capabilities have no options")?;
418 options["prefs"] = serde_json::json!({
419 "download.default_directory": directory,
420 "download.prompt_for_download": false,
421 });
422 }
423 }
424 tracing::info!(
425 "{} address: {:?}",
426 webdriver.engine().driver(),
427 webdriver.address
428 );
429
430 let url = format!("http://{}", webdriver.address);
431 let connected = webdriver
432 .during(deadline, "startup", async {
433 Ok(WebDriver::new(&url, caps).await?)
434 })
435 .await;
436 let driver = match connected {
437 Ok(driver) => driver,
438 Err(error) => return Err(with_cleanup(error, webdriver.terminate().await)),
439 };
440
441 Ok(Self {
442 webdriver,
443 driver: TestDriver {
444 inner: driver,
445 wait_timeout: WAIT_TIMEOUT,
446 load_timeout: LOAD_TIMEOUT,
447 waiting: Waiting::default(),
448 downloads,
449 },
450 })
451 }
452
453 async fn reset(&mut self, url: &str) -> Result<()> {
459 self.driver.waiting.clear();
460 for file in std::fs::read_dir(self.driver.downloads.path())? {
461 std::fs::remove_file(file?.path())?;
462 }
463 let old = self.driver.inner.window().await?;
464 let fresh = self.driver.inner.new_tab().await?;
465 self.driver.inner.switch_to_window(fresh.clone()).await?;
466 self.driver.inner.switch_to_window(old).await?;
467 self.driver.inner.close_window().await?;
468 self.driver.inner.switch_to_window(fresh).await?;
469 self.driver.set_window_size(WINDOW.0, WINDOW.1).await?;
470 self.driver.inner.goto(url).await?;
471 Ok(())
472 }
473
474 pub(crate) async fn close(mut self) -> Result<Option<anyhow::Error>> {
480 let driver = self.driver.inner.clone();
484 let quit = self
485 .webdriver
486 .during(time::Instant::now() + QUIT_TIMEOUT, "quit", async {
487 Ok(driver.quit().await?)
488 })
489 .await;
490 let reaped = self.webdriver.terminate().await;
491 match (quit, reaped) {
492 (Ok(()), reaped) => reaped.map(|()| None),
493 (Err(error), Ok(())) if error.downcast_ref::<driver::TimedOut>().is_some() => {
494 Ok(Some(error))
495 }
496 (Err(error), reaped) => Err(with_cleanup(error, reaped)),
497 }
498 }
499}
500
501impl Drop for Browser {
502 fn drop(&mut self) {
503 let _ = self.driver.inner.clone().leak();
506 }
507}
508
509#[cfg(test)]
510mod browser_tests {
511 use anyhow::{Context, Result, ensure};
512
513 use super::Browser;
514
515 #[tokio::test]
521 #[ignore = "requires a real WebDriver"]
522 async fn a_reset_discards_the_preceding_document() -> Result<()> {
523 let mut browser = Browser::open().await?;
524
525 let result = async {
526 browser.reset("data:text/html,first").await?;
527 let first = browser.driver.inner.window().await?;
528
529 browser.reset("data:text/html,second").await?;
530 let second = browser.driver.inner.window().await?;
531 let windows = browser.driver.inner.windows().await?;
532 let history = browser
533 .driver
534 .inner
535 .execute("return history.length", Vec::new())
536 .await?
537 .json()
538 .as_u64()
539 .context("browser history length")?;
540
541 ensure!(first != second, "the second reset kept the first tab");
542 ensure!(windows == [second], "reset left tabs behind: {windows:?}");
543 ensure!(history <= 2, "the fresh tab has {history} history entries");
544 Ok(())
545 }
546 .await;
547
548 match (result, browser.close().await) {
549 (Ok(()), Ok(_)) => Ok(()),
550 (Err(error), Ok(_)) | (Ok(()), Err(error)) => Err(error),
551 (Err(error), Err(cleanup)) => Err(super::driver::with_cleanup(error, Err(cleanup))),
552 }
553 }
554}
555
556const WINDOW: (u32, u32) = (1600, 1000);
558
559const SESSION_DEATH: &[&str] = &[
570 "invalid session id",
571 "session id is invalid",
572 "session deleted because of page crash",
573 "session terminated",
574 "the webdriver server's output ended",
575 "error sending request",
576];
577
578pub(crate) fn browser_death(error: &anyhow::Error) -> Option<&'static str> {
581 let mut source: Option<&dyn std::error::Error> = Some(error.as_ref());
582
583 while let Some(error) = source {
584 let said = error.to_string().to_lowercase();
585
586 if let Some(mark) = SESSION_DEATH.iter().find(|mark| said.contains(**mark)) {
587 return Some(mark);
588 }
589
590 source = error.source();
591 }
592
593 None
594}
595
596fn went_away(browser: &Browser, mark: &str) -> anyhow::Error {
602 let name = browser.webdriver.engine().driver();
603
604 anyhow!(
605 "the browser went away ({mark}); {name} last said: {}",
606 driver_said(browser)
607 )
608}
609
610fn driver_said(browser: &Browser) -> String {
613 let said = browser.webdriver.diagnostics();
614
615 said.lines()
616 .rev()
617 .take(3)
618 .collect::<Vec<_>>()
619 .into_iter()
620 .rev()
621 .collect::<Vec<_>>()
622 .join(" | ")
623}
624
625pub(crate) async fn run_one<F: Fixture>(
627 browser: &mut Browser,
628 start: crate::harness::Start<F>,
629 setup: F::Setup,
630 limit: Option<Duration>,
631) -> Result<()> {
632 let mut fixture = F::start(setup).await?;
633
634 let mut errors = String::new();
635
636 let result = match browser.reset(&fixture.url()).await {
637 Ok(()) => drive_one(browser, &mut fixture, start, limit).await,
638 Err(error) => Err(error),
639 };
640
641 let fixture_result = fixture.quit().await;
642
643 if let Err(error) = result.as_ref() {
644 if let Some(mark) = browser_death(error) {
645 let mut error = went_away(browser, mark);
646
647 if let Err(quit) = fixture_result {
648 error = error.context(format!("the fixture also failed to quit: {quit}"));
649 }
650
651 return Err(error);
652 }
653
654 writeln!(errors, "Test error: {error}")?;
655
656 let mut source = error.source();
657
658 while let Some(e) = source.take() {
659 writeln!(errors, " Caused by: {e}")?;
660 source = e.source();
661 }
662 }
663
664 if let Err(error) = fixture_result {
665 writeln!(errors, "Fixture error: {error}")?;
666
667 let mut source = error.source();
668
669 while let Some(e) = source.take() {
670 writeln!(errors, " Caused by: {e}")?;
671 source = e.source();
672 }
673 }
674
675 if let Err(error) = F::check() {
676 writeln!(errors, "Check error: {error}")?;
677 }
678
679 if !errors.is_empty() {
680 return Err(anyhow!("{errors}"));
681 }
682
683 Ok(())
684}
685
686async fn drive_one<F: Fixture>(
696 browser: &mut Browser,
697 fixture: &mut F,
698 start: crate::harness::Start<F>,
699 limit: Option<Duration>,
700) -> Result<()> {
701 let mut timeout = pin!(async move {
702 match limit {
703 Some(limit) => time::sleep(limit).await,
704 None => std::future::pending::<()>().await,
705 }
706 });
707
708 let Browser { webdriver, driver } = browser;
709
710 let waiting = driver.waiting.clone();
711
712 let outcome = {
713 let task = AssertUnwindSafe(start(driver, fixture)).catch_unwind();
714 let mut task = pin!(task);
715
716 loop {
717 tokio::select! {
718 _ = timeout.as_mut() => {
719 break Err(overran(limit, &waiting));
720 }
721 result = task.as_mut() => {
722 break Ok(result);
723 }
724 result = webdriver.io() => {
725 if !result? {
726 break Err("the WebDriver server's output ended".to_string());
727 }
728 }
729 }
730 }
731 };
732
733 match outcome {
734 Ok(Ok(Ok(()))) => match driver.error_seen().await? {
735 Some(threw) => bail!("the page threw: {threw}"),
736 None => Ok(()),
737 },
738 Ok(Ok(result)) => result,
739 Ok(Err(panicked)) => bail!("the test panicked: {}", panic_message(&panicked)),
740 Err(error) => bail!(error),
741 }
742}
743
744pub(crate) fn overran(limit: Option<Duration>, waiting: &Waiting) -> String {
747 let seconds = limit.map_or(0, |limit| limit.as_secs());
748
749 format!(
750 "the test was still running after {seconds}s, which is --timeout{}",
751 waiting.clause()
752 )
753}
754
755fn panic_message(payload: &Box<dyn std::any::Any + Send>) -> &str {
757 if let Some(message) = payload.downcast_ref::<&'static str>() {
758 return message;
759 }
760
761 if let Some(message) = payload.downcast_ref::<String>() {
762 return message;
763 }
764
765 "a payload that is neither a string nor a &str"
766}
767
768fn drag_nudge(offset: i64) -> i64 {
771 offset.clamp(-8, 8)
772}
773
774pub const POLL_INTERVAL: Duration = Duration::from_millis(25);
776
777const WAIT_TIMEOUT: Duration = Duration::from_secs(5);
779
780const LOAD_TIMEOUT: Duration = Duration::from_secs(15);
785
786macro_rules! common {
787 () => {
788 pub async fn wait_until(
790 &self,
791 what: impl std::fmt::Display,
792 condition: impl AsyncFnMut() -> Result<bool>,
793 ) -> Result<()> {
794 self.wait_for(self.wait_timeout, what, condition).await
795 }
796
797 pub async fn wait_until_within(
802 &self,
803 timeout: Duration,
804 what: impl std::fmt::Display,
805 condition: impl AsyncFnMut() -> Result<bool>,
806 ) -> Result<()> {
807 self.wait_for(timeout, what, condition).await
808 }
809
810 async fn wait_for(
812 &self,
813 timeout: Duration,
814 what: impl std::fmt::Display,
815 mut condition: impl AsyncFnMut() -> Result<bool>,
816 ) -> Result<()> {
817 let deadline = time::Instant::now() + timeout;
818
819 self.waiting.on(&what);
820
821 loop {
822 if condition().await? {
823 return Ok(());
824 }
825
826 if time::Instant::now() >= deadline {
827 bail!("Timed out after {timeout:?} waiting for {what}");
828 }
829
830 time::sleep(POLL_INTERVAL).await;
831 }
832 }
833
834 pub async fn wait_texts<const N: usize>(
836 &self,
837 by: impl IntoBy,
838 expected: [&str; N],
839 ) -> Result<()> {
840 let by = by.into_by();
841
842 tracing::trace!(?by, ?expected, "Waiting for texts");
843
844 let seen = std::cell::RefCell::new(Vec::new());
845
846 let result = self
847 .wait_until(format_args!("{by} to read {expected:?}"), async || {
848 let texts = self.find_all_texts(by.clone()).await?;
849 let matched = texts == expected;
850 *seen.borrow_mut() = texts;
851 Ok(matched)
852 })
853 .await;
854
855 match result {
856 Ok(()) => Ok(()),
857 Err(error) => {
858 let seen = seen.into_inner();
859 Err(error.context(format!("last read {seen:?}")))
860 }
861 }
862 }
863
864 pub async fn wait_count(&self, by: impl IntoBy, expected: usize) -> Result<()> {
879 let by = by.into_by();
880
881 tracing::trace!(?by, expected, "Waiting for count");
882
883 self.wait_until(format_args!("{by} to match {expected} nodes"), async || {
884 Ok(self.find_all(by.clone()).await?.len() == expected)
885 })
886 .await
887 }
888
889 #[inline]
893 pub async fn count(&self, by: impl IntoBy) -> Result<usize> {
894 Ok(self.find_all(by.into_by()).await?.len())
895 }
896
897 pub async fn wait_count_from(
911 &self,
912 by: impl IntoBy,
913 before: usize,
914 expected: usize,
915 ) -> Result<()> {
916 let by = by.into_by();
917
918 ensure!(
919 before != expected,
920 "Waiting for {by} to match {expected} nodes verifies nothing: \
921 {expected} is also the count read before the action, so the \
922 first poll agrees whether or not the action has landed. Assert \
923 the count this action is supposed to produce, or if it really \
924 is meant to leave the count alone, assert what it did change.",
925 );
926
927 tracing::trace!(?by, before, expected, "Waiting for count to change");
928
929 self.wait_until(
930 format_args!("{by} to go from {before} to {expected} nodes"),
931 async || Ok(self.find_all(by.clone()).await?.len() == expected),
932 )
933 .await
934 }
935
936 #[inline]
938 pub async fn find_all_texts(&self, by: impl IntoBy) -> Result<Vec<String>> {
939 let mut texts = Vec::new();
940
941 for item in self.find_all(by.into_by()).await? {
942 texts.push(item.text().await?);
943 }
944
945 Ok(texts)
946 }
947
948 #[inline]
950 pub async fn find_one_by_xpath(&self, xpath: &str) -> Result<TestElement> {
951 self.find_one_by(By::XPath(xpath)).await
952 }
953
954 pub async fn find_one_by(&self, by: impl IntoBy) -> Result<TestElement> {
961 let by = by.into_by();
962
963 tracing::trace!(?by, "Finding one element");
964
965 let deadline = time::Instant::now() + self.wait_timeout;
966
967 loop {
968 let items = self.find_all(by.clone()).await?;
969
970 ensure!(
971 items.len() <= 1,
972 "Expected exactly one by {by}, but got {}: where several is \
973 what the page is, ask for one of them by index with \
974 find_nth, or for the first of them with find_first",
975 items.len()
976 );
977
978 if let Some(item) = items.into_iter().next() {
979 return Ok(item);
980 }
981
982 if time::Instant::now() >= deadline {
983 bail!(
984 "Timed out after {:?} waiting for {by}",
985 self.wait_timeout
986 );
987 }
988
989 time::sleep(POLL_INTERVAL).await;
990 }
991 }
992
993 pub async fn find_nth(&self, by: impl IntoBy, index: usize) -> Result<TestElement> {
1008 let by = by.into_by();
1009
1010 tracing::trace!(?by, index, "Finding one of several elements");
1011
1012 let deadline = time::Instant::now() + self.wait_timeout;
1013
1014 loop {
1015 if let Some(item) = self.find_all(by.clone()).await?.into_iter().nth(index) {
1016 return Ok(item);
1017 }
1018
1019 if time::Instant::now() >= deadline {
1020 bail!(
1021 "Timed out after {:?} waiting for {by} at {index}",
1022 self.wait_timeout
1023 );
1024 }
1025
1026 time::sleep(POLL_INTERVAL).await;
1027 }
1028 }
1029
1030 #[inline]
1033 pub async fn find_first(&self, by: impl IntoBy) -> Result<TestElement> {
1034 self.find_nth(by, 0).await
1035 }
1036
1037 pub async fn find_all(&self, by: impl Into<By>) -> Result<Vec<TestElement>> {
1039 self.find_all_within(self.wait_timeout, by).await
1040 }
1041
1042 pub async fn find_all_within(
1046 &self,
1047 timeout: Duration,
1048 by: impl Into<By>,
1049 ) -> Result<Vec<TestElement>> {
1050 let by = by.into();
1051 tracing::trace!(?by, "Finding all elements");
1052
1053 let task = self.inner.find_all(by.clone());
1054 let sleep = time::sleep(timeout);
1055
1056 tokio::select! {
1057 _ = sleep => {
1058 Err(anyhow!("find_elements({by:?}) timed out after {timeout:?}"))
1059 }
1060 result = task => {
1061 Ok(result?.into_iter().map(|inner| TestElement { inner, wait_timeout: self.wait_timeout, waiting: self.waiting.clone() }).collect::<Vec<_>>())
1062 }
1063 }
1064 }
1065 }
1066}
1067
1068#[derive(Debug, Clone, Copy)]
1070pub struct CanvasSize {
1071 pub device_width: f64,
1073 pub device_height: f64,
1075 pub css_width: f64,
1077 pub css_height: f64,
1079 pub device_pixel_ratio: f64,
1081}
1082
1083pub struct TestElement {
1085 inner: WebElement,
1086 wait_timeout: Duration,
1087 waiting: Waiting,
1088}
1089
1090impl TestElement {
1091 pub fn element(&self) -> &WebElement {
1094 &self.inner
1095 }
1096
1097 pub async fn click(&self) -> Result<()> {
1099 tracing::trace!("Clicking element");
1100 self.inner.click().await?;
1101 Ok(())
1102 }
1103
1104 pub async fn extend_click(&self) -> Result<()> {
1107 tracing::trace!("Extend-clicking element");
1108
1109 self.inner.scroll_into_view().await?;
1110
1111 self.inner
1112 .handle()
1113 .action_chain()
1114 .key_down(thirtyfour::Key::Control)
1115 .click_element(&self.inner)
1116 .key_up(thirtyfour::Key::Control)
1117 .perform()
1118 .await?;
1119
1120 Ok(())
1121 }
1122
1123 pub async fn shift_click(&self) -> Result<()> {
1126 tracing::trace!("Shift-clicking element");
1127
1128 self.inner.scroll_into_view().await?;
1129
1130 self.inner
1131 .handle()
1132 .action_chain()
1133 .key_down(thirtyfour::Key::Shift)
1134 .click_element(&self.inner)
1135 .key_up(thirtyfour::Key::Shift)
1136 .perform()
1137 .await?;
1138
1139 Ok(())
1140 }
1141
1142 pub async fn hover(&self) -> Result<()> {
1144 tracing::trace!("Hovering element");
1145
1146 self.inner.scroll_into_view().await?;
1147
1148 self.inner
1149 .handle()
1150 .action_chain()
1151 .move_to_element_center(&self.inner)
1152 .perform()
1153 .await?;
1154
1155 Ok(())
1156 }
1157
1158 pub async fn double_click(&self) -> Result<()> {
1160 tracing::trace!("Double-clicking element");
1161
1162 self.inner.scroll_into_view().await?;
1163
1164 self.inner
1165 .handle()
1166 .action_chain()
1167 .double_click_element(&self.inner)
1168 .perform()
1169 .await?;
1170
1171 Ok(())
1172 }
1173
1174 pub async fn double_click_by(&self, dx: i64, dy: i64) -> Result<()> {
1178 tracing::trace!(dx, dy, "Double-clicking element off centre");
1179
1180 self.inner.scroll_into_view().await?;
1181
1182 self.inner
1183 .handle()
1184 .action_chain()
1185 .move_to_element_center(&self.inner)
1186 .move_by_offset(dx, dy)
1187 .double_click()
1188 .perform()
1189 .await?;
1190
1191 Ok(())
1192 }
1193
1194 pub async fn click_by(&self, dx: i64, dy: i64) -> Result<()> {
1198 tracing::trace!(dx, dy, "Clicking element off centre");
1199
1200 self.inner.scroll_into_view().await?;
1201
1202 self.inner
1203 .handle()
1204 .action_chain()
1205 .move_to_element_center(&self.inner)
1206 .move_by_offset(dx, dy)
1207 .click()
1208 .perform()
1209 .await?;
1210
1211 Ok(())
1212 }
1213
1214 pub async fn context_click(&self) -> Result<()> {
1216 tracing::trace!("Context-clicking element");
1217
1218 self.inner.scroll_into_view().await?;
1219
1220 self.inner
1221 .handle()
1222 .action_chain()
1223 .context_click_element(&self.inner)
1224 .perform()
1225 .await?;
1226
1227 Ok(())
1228 }
1229
1230 pub async fn drag_by(&self, dx: i64, dy: i64) -> Result<()> {
1237 tracing::trace!(dx, dy, "Dragging element");
1238
1239 let (nx, ny) = (drag_nudge(dx), drag_nudge(dy));
1240
1241 self.inner.scroll_into_view().await?;
1242
1243 self.inner
1244 .handle()
1245 .action_chain()
1246 .move_to_element_center(&self.inner)
1247 .click_and_hold()
1248 .move_by_offset(nx, ny)
1249 .move_by_offset(dx - nx, dy - ny)
1250 .perform()
1251 .await?;
1252
1253 Ok(())
1254 }
1255
1256 pub async fn drag_from_by(&self, at_x: i64, at_y: i64, dx: i64, dy: i64) -> Result<()> {
1262 tracing::trace!(at_x, at_y, dx, dy, "Dragging from a point in an element");
1263
1264 let (nx, ny) = (drag_nudge(dx), drag_nudge(dy));
1265
1266 self.inner.scroll_into_view().await?;
1267
1268 self.inner
1269 .handle()
1270 .action_chain()
1271 .move_to_element_center(&self.inner)
1272 .move_by_offset(at_x, at_y)
1273 .click_and_hold()
1274 .move_by_offset(nx, ny)
1275 .move_by_offset(dx - nx, dy - ny)
1276 .perform()
1277 .await?;
1278
1279 Ok(())
1280 }
1281
1282 pub async fn alt_drag_by(&self, dx: i64, dy: i64) -> Result<()> {
1284 tracing::trace!(dx, dy, "Dragging element with alt held");
1285
1286 let (nx, ny) = (drag_nudge(dx), drag_nudge(dy));
1287
1288 self.inner.scroll_into_view().await?;
1289
1290 self.inner
1291 .handle()
1292 .action_chain()
1293 .key_down(thirtyfour::Key::Alt)
1294 .move_to_element_center(&self.inner)
1295 .click_and_hold()
1296 .move_by_offset(nx, ny)
1297 .move_by_offset(dx - nx, dy - ny)
1298 .perform()
1299 .await?;
1300
1301 Ok(())
1302 }
1303
1304 pub async fn text(&self) -> Result<String> {
1306 tracing::trace!("Getting element text");
1307 Ok(self.inner.text().await?)
1308 }
1309
1310 pub async fn prop(&self, name: &str) -> Result<String> {
1312 tracing::trace!(name, "Getting element property");
1313 Ok(self.inner.prop(name).await?.unwrap_or_default())
1314 }
1315
1316 pub async fn attr(&self, name: &str) -> Result<String> {
1319 tracing::trace!(name, "Getting element attribute");
1320 Ok(self.inner.attr(name).await?.unwrap_or_default())
1321 }
1322
1323 pub async fn scroll_into_view(&self) -> Result<()> {
1325 tracing::trace!("Scrolling element into view");
1326 self.inner.scroll_into_view().await?;
1327 Ok(())
1328 }
1329
1330 pub async fn focus(&self) -> Result<()> {
1332 tracing::trace!("Focusing element");
1333 self.inner.focus().await?;
1334 Ok(())
1335 }
1336
1337 pub async fn visible(&self) -> Result<bool> {
1343 Ok(self.inner.is_displayed().await?)
1344 }
1345
1346 pub async fn rect(&self) -> Result<ElementRect> {
1348 tracing::trace!("Measuring element");
1349 Ok(self.inner.rect().await?)
1350 }
1351
1352 pub async fn css(&self, name: &str) -> Result<String> {
1354 tracing::trace!(name, "Getting element style");
1355 Ok(self.inner.css_value(name).await?)
1356 }
1357
1358 pub async fn value(&self) -> Result<String> {
1360 tracing::trace!("Getting element value");
1361 Ok(self.inner.prop("value").await?.unwrap_or_default())
1362 }
1363
1364 pub async fn clear(&self) -> Result<()> {
1366 tracing::trace!("Clearing element text");
1367 self.inner.clear().await?;
1368 Ok(())
1369 }
1370
1371 pub async fn send_keys(&self, keys: &str) -> Result<()> {
1373 tracing::trace!(?keys, "Sending keys to element");
1374 self.inner.send_keys(keys).await?;
1375 Ok(())
1376 }
1377
1378 pub async fn pressed(&self) -> Result<bool> {
1380 Ok(self.prop("ariaPressed").await? == "true")
1381 }
1382
1383 pub async fn enabled(&self) -> Result<bool> {
1385 Ok(self.inner.is_enabled().await?)
1386 }
1387
1388 pub async fn disabled(&self) -> Result<bool> {
1393 Ok(self.prop("ariaDisabled").await? == "true")
1394 }
1395
1396 common!();
1397}
1398
1399pub struct TestDriver {
1401 inner: WebDriver,
1402 downloads: tempfile::TempDir,
1403 wait_timeout: Duration,
1404 load_timeout: Duration,
1405 waiting: Waiting,
1406}
1407
1408impl TestDriver {
1409 pub async fn local_clock(&self, epoch_ms: u64) -> Result<[u32; 4]> {
1413 let read = self
1414 .inner
1415 .execute(
1416 "const d = new Date(arguments[0]); \
1417 return [d.getMonth() + 1, d.getDate(), d.getHours(), d.getMinutes()]",
1418 vec![serde_json::json!(epoch_ms)],
1419 )
1420 .await?;
1421 let parts = read.json().as_array().context("clock array")?;
1422 let mut clock = [0; 4];
1423
1424 for (slot, part) in clock.iter_mut().zip(parts) {
1425 *slot = u32::try_from(part.as_u64().context("clock part")?)?;
1426 }
1427
1428 Ok(clock)
1429 }
1430
1431 pub async fn rendered_texts(&self, selector: &str) -> Result<Vec<String>> {
1438 let read = self
1439 .inner
1440 .execute(
1441 "return Array.from(document.querySelectorAll(arguments[0])) \
1442 .map(n => n.innerText)",
1443 vec![serde_json::json!(selector)],
1444 )
1445 .await?;
1446 let rows = read.json().as_array().context("rendered text array")?;
1447
1448 rows.iter()
1449 .map(|row| row.as_str().context("rendered text").map(str::to_owned))
1450 .collect()
1451 }
1452
1453 pub fn downloads(&self) -> &std::path::Path {
1455 self.downloads.path()
1456 }
1457
1458 pub(crate) fn waiting(&self) -> Waiting {
1461 self.waiting.clone()
1462 }
1463
1464 pub fn webdriver(&self) -> &WebDriver {
1467 &self.inner
1468 }
1469
1470 pub fn wait_timeout(&self) -> Duration {
1473 self.wait_timeout
1474 }
1475
1476 pub fn load_timeout(&self) -> Duration {
1480 self.load_timeout
1481 }
1482
1483 pub async fn set_window_size(&self, width: u32, height: u32) -> Result<()> {
1485 tracing::trace!(width, height, "Sizing the window");
1486 self.inner.set_window_rect(0, 0, width, height).await?;
1487 Ok(())
1488 }
1489
1490 pub async fn set_style(
1494 &self,
1495 element: &TestElement,
1496 property: &str,
1497 value: &str,
1498 ) -> Result<()> {
1499 tracing::trace!(property, value, "Setting an inline style property");
1500
1501 let script = format!("arguments[0].style.setProperty({property:?}, {value:?});");
1502
1503 self.inner
1504 .execute(script, vec![element.inner.to_json()?])
1505 .await?;
1506
1507 Ok(())
1508 }
1509
1510 pub async fn set_class(&self, element: &TestElement, class: &str, on: bool) -> Result<()> {
1514 tracing::trace!(class, on, "Forcing a class");
1515
1516 let script = format!("arguments[0].classList.toggle({class:?}, {on});");
1517
1518 self.inner
1519 .execute(script, vec![element.inner.to_json()?])
1520 .await?;
1521
1522 Ok(())
1523 }
1524
1525 pub async fn set_value(&self, element: &TestElement, value: &str, event: &str) -> Result<()> {
1529 tracing::trace!(value, event, "Setting a field's value");
1530
1531 self.inner
1532 .execute(
1533 "arguments[0].value = arguments[1]; \
1534 arguments[0].dispatchEvent(new Event(arguments[2], {bubbles: true}));",
1535 vec![
1536 element.inner.to_json()?,
1537 serde_json::json!(value),
1538 serde_json::json!(event),
1539 ],
1540 )
1541 .await?;
1542
1543 Ok(())
1544 }
1545
1546 pub async fn set_text(&self, element: &TestElement, text: &str) -> Result<()> {
1550 tracing::trace!(text, "Replacing an element's text");
1551
1552 let script = format!(
1553 "const node = arguments[0].firstChild; \
1554 if (!node || node.nodeType !== Node.TEXT_NODE) throw new Error('no text node'); \
1555 node.data = {text:?};"
1556 );
1557
1558 self.inner
1559 .execute(script, vec![element.inner.to_json()?])
1560 .await?;
1561
1562 Ok(())
1563 }
1564
1565 pub async fn overflowing(&self, element: &TestElement) -> Result<Vec<String>> {
1571 tracing::trace!("Finding what overflows inside an element");
1572
1573 let script = "const out = []; \
1574 for (const el of [arguments[0], ...arguments[0].querySelectorAll('*')]) { \
1575 if (el.clientHeight <= 1 || el.clientWidth <= 1) continue; \
1576 const cs = getComputedStyle(el); \
1577 const y = el.scrollHeight - el.clientHeight; \
1578 const x = el.scrollWidth - el.clientWidth; \
1579 const shows = v => v === 'auto' || v === 'scroll' || v === 'hidden' || v === 'clip'; \
1580 if ((y > 1 && shows(cs.overflowY)) || (x > 1 && shows(cs.overflowX))) { \
1581 const test = el.getAttribute('data-test'); \
1582 out.push(el.localName + (el.className ? '.' + String(el.className).trim().split(/\\s+/).join('.') : '') \
1583 + (test ? `[data-test=${test}]` : '') \
1584 + ` ${cs.overflowX}/${cs.overflowY} over by ${x}x${y}`); \
1585 } \
1586 } \
1587 return out;";
1588
1589 let found = self
1590 .inner
1591 .execute(script, vec![element.inner.to_json()?])
1592 .await?;
1593
1594 Ok(found
1595 .json()
1596 .as_array()
1597 .into_iter()
1598 .flatten()
1599 .filter_map(|line| line.as_str().map(str::to_owned))
1600 .collect())
1601 }
1602
1603 pub async fn small_text(
1608 &self,
1609 element: &TestElement,
1610 floor: f64,
1611 marks: &str,
1612 ) -> Result<Vec<String>> {
1613 tracing::trace!(floor, marks, "Finding text set below a size");
1614
1615 let script = format!(
1616 "const out = []; \
1617 for (const el of [arguments[0], ...arguments[0].querySelectorAll('*')]) {{ \
1618 if (el.closest({marks:?})) continue; \
1619 const words = Array.from(el.childNodes) \
1620 .filter(n => n.nodeType === Node.TEXT_NODE) \
1621 .map(n => n.textContent.trim()).join(' ').trim(); \
1622 if (!words) continue; \
1623 const rect = el.getBoundingClientRect(); \
1624 if (rect.width <= 1 || rect.height <= 1) continue; \
1625 const cs = getComputedStyle(el); \
1626 if (cs.visibility !== 'visible') continue; \
1627 const size = parseFloat(cs.fontSize); \
1628 if (size < {floor}) {{ \
1629 const test = el.getAttribute('data-test'); \
1630 out.push(el.localName + (el.className ? '.' + String(el.className).trim().split(/\\s+/).join('.') : '') \
1631 + (test ? `[data-test=${{test}}]` : '') \
1632 + ` at ${{cs.fontSize}}: ${{JSON.stringify(words.slice(0, 32))}}`); \
1633 }} \
1634 }} \
1635 return out;"
1636 );
1637
1638 let found = self
1639 .inner
1640 .execute(script, vec![element.inner.to_json()?])
1641 .await?;
1642
1643 Ok(found
1644 .json()
1645 .as_array()
1646 .into_iter()
1647 .flatten()
1648 .filter_map(|line| line.as_str().map(str::to_owned))
1649 .collect())
1650 }
1651
1652 pub async fn wheel_consumed(&self, element: &TestElement, delta: f64) -> Result<bool> {
1657 tracing::trace!(delta, "Turning the wheel and asking who took it");
1658
1659 let script = format!(
1660 "return !arguments[0].dispatchEvent(new WheelEvent('wheel', \
1661 {{ deltaY: {delta}, bubbles: true, cancelable: true }}))"
1662 );
1663
1664 let taken = self
1665 .inner
1666 .execute(script, vec![element.inner.to_json()?])
1667 .await?;
1668
1669 Ok(taken.json().as_bool().unwrap_or(false))
1670 }
1671
1672 pub async fn wheel(&self, element: &TestElement, delta: f64) -> Result<()> {
1680 tracing::trace!(delta, "Turning the wheel over an element");
1681
1682 let script = format!(
1683 "arguments[0].dispatchEvent(new WheelEvent('wheel', \
1684 {{ deltaY: {delta}, bubbles: true, cancelable: true }}))"
1685 );
1686
1687 self.inner
1688 .execute(script, vec![element.inner.to_json()?])
1689 .await?;
1690
1691 Ok(())
1692 }
1693
1694 pub async fn wheel_alt(&self, element: &TestElement, delta: f64, shift: bool) -> Result<()> {
1701 tracing::trace!(delta, shift, "Turning the wheel with alt held");
1702
1703 let script = format!(
1704 "const box = arguments[0].getBoundingClientRect(); \
1705 arguments[0].dispatchEvent(new WheelEvent('wheel', \
1706 {{ deltaY: {delta}, altKey: true, shiftKey: {shift}, \
1707 clientX: box.left + box.width / 2, \
1708 clientY: box.top + box.height / 2, \
1709 bubbles: true, cancelable: true }}))"
1710 );
1711
1712 self.inner
1713 .execute(script, vec![element.inner.to_json()?])
1714 .await?;
1715
1716 Ok(())
1717 }
1718
1719 pub async fn wheel_over(
1730 &self,
1731 element: &TestElement,
1732 across: f64,
1733 down: f64,
1734 ctrl: bool,
1735 ) -> Result<bool> {
1736 tracing::trace!(across, down, ctrl, "Turning the wheel over both axes");
1737
1738 let script = format!(
1739 "const box = arguments[0].getBoundingClientRect(); \
1740 return !arguments[0].dispatchEvent(new WheelEvent('wheel', \
1741 {{ deltaX: {across}, deltaY: {down}, ctrlKey: {ctrl}, \
1742 clientX: box.left + box.width / 2, \
1743 clientY: box.top + box.height / 2, \
1744 bubbles: true, cancelable: true }}))"
1745 );
1746
1747 let taken = self
1748 .inner
1749 .execute(script, vec![element.inner.to_json()?])
1750 .await?;
1751
1752 Ok(taken.json().as_bool().unwrap_or(false))
1753 }
1754
1755 pub async fn wheel_across(&self, element: &TestElement, delta: f64) -> Result<()> {
1758 tracing::trace!(delta, "Turning the wheel sideways over an element");
1759
1760 let script = format!(
1761 "arguments[0].dispatchEvent(new WheelEvent('wheel', \
1762 {{ deltaX: {delta}, bubbles: true, cancelable: true }}))"
1763 );
1764
1765 self.inner
1766 .execute(script, vec![element.inner.to_json()?])
1767 .await?;
1768
1769 Ok(())
1770 }
1771
1772 pub async fn capture_clipboard(&self) -> Result<()> {
1778 self.inner
1779 .execute(
1780 "const inject = document.createElement('script'); \
1781 inject.textContent = `navigator.clipboard.writeText = async text => { \
1782 document.body.setAttribute('data-copied', text); \
1783 };`; \
1784 document.documentElement.appendChild(inject); inject.remove();",
1785 Vec::new(),
1786 )
1787 .await?;
1788 Ok(())
1789 }
1790
1791 pub async fn delay_websocket_sends(&self, millis: u64) -> Result<()> {
1809 self.inner.execute(format!(
1810 "const inject = document.createElement('script'); \
1811 inject.textContent = `(() => {{ \
1812 WebSocket.__e2eOriginalSend = WebSocket.__e2eOriginalSend \
1813 || WebSocket.prototype.send; \
1814 const send = WebSocket.__e2eOriginalSend; \
1815 WebSocket.prototype.send = function(data) {{ \
1816 const copy = data && typeof data.slice === 'function' \
1817 ? data.slice() : data; \
1818 setTimeout(() => {{ if (this.readyState === 1) send.call(this, copy); }}, {millis}); \
1819 }}; \
1820 }})();`; \
1821 document.documentElement.appendChild(inject); inject.remove();"
1822 ), Vec::new()).await?;
1823 Ok(())
1824 }
1825
1826 pub async fn stop_delaying_websocket_sends(&self) -> Result<()> {
1833 self.inner
1834 .execute(
1835 "const inject = document.createElement('script'); \
1836 inject.textContent = `(() => { \
1837 if (WebSocket.__e2eOriginalSend) { \
1838 WebSocket.prototype.send = WebSocket.__e2eOriginalSend; \
1839 delete WebSocket.__e2eOriginalSend; \
1840 } \
1841 })();`; \
1842 document.documentElement.appendChild(inject); inject.remove();"
1843 .to_owned(),
1844 Vec::new(),
1845 )
1846 .await?;
1847 Ok(())
1848 }
1849
1850 pub async fn wait_copied(&self, text: &str) -> Result<()> {
1853 self.wait_until("the full text to be copied", async || {
1854 Ok(self.find_one_by("body").await?.attr("data-copied").await? == text)
1855 })
1856 .await
1857 }
1858
1859 pub async fn watch_for_errors(&self) -> Result<()> {
1870 tracing::trace!("Listening for uncaught errors in the page");
1871
1872 let script = "if (!document.body.hasAttribute('data-watching')) { \
1873 const inject = document.createElement('script'); \
1874 inject.textContent = `(() => { \
1875 const say = what => document.body.setAttribute( \
1876 'data-threw', String(what).slice(0, 6000)); \
1877 const told = (thrown, otherwise) => { \
1878 if (!(thrown instanceof Error)) { return otherwise; } \
1879 const head = String(thrown); \
1880 const stack = thrown.stack || ''; \
1881 return stack.startsWith(head) ? stack : head + '\\\\n' + stack; \
1882 }; \
1883 window.addEventListener('error', e => say(told(e.error, e.message))); \
1884 window.addEventListener('unhandledrejection', \
1885 e => say(told(e.reason, e.reason))); \
1886 const was = console.error; \
1887 console.error = (...a) => { say(a.join(' ')); was(...a); }; \
1888 document.body.setAttribute('data-watching', ''); \
1889 })();`; \
1890 document.documentElement.appendChild(inject); \
1891 inject.remove(); \
1892 } \
1893 return document.body.hasAttribute('data-watching');";
1894
1895 let watching = self.inner.execute(script, Vec::new()).await?;
1896
1897 ensure!(
1898 watching.json().as_bool() == Some(true),
1899 "the script that watches the page for errors did not run"
1900 );
1901 Ok(())
1902 }
1903
1904 pub async fn what_the_page_says(&self) -> Result<String> {
1909 let script = "const b = document.body; \
1910 if (!b) { return 'and the document has no body at all'; } \
1911 const page = b.getAttribute('data-page'); \
1912 const threw = b.getAttribute('data-threw'); \
1913 const mounted = b.children.length; \
1914 let out = page ? `; the page showing is '${page}'` \
1915 : '; nothing has claimed the page yet'; \
1916 out += `, ${mounted} element(s) are mounted under the body`; \
1917 if (threw) { out += `, and the page threw: ${threw}`; } \
1918 out += `, the document is ${document.readyState}`; \
1919 out += `, the bundle's exports are ${typeof window.wasmBindings}`; \
1920 try { new WebAssembly.Module( \
1921 new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0])); \
1922 out += ', an empty module still compiles'; } \
1923 catch (e) { out += ', and an empty module will not compile: ' + e; } \
1924 out += ', history=' + history.length; \
1925 const nav = performance.getEntriesByType('navigation')[0]; \
1926 if (nav) { out += `, the document was answered after \
1927 ${Math.max(0, Math.round(nav.responseEnd))}ms`; } \
1928 for (const got of performance.getEntriesByType('resource')) { \
1929 if (!/\\.(wasm|js)(\\?|$)/.test(got.name)) { continue; } \
1930 out += `, ${got.name.split('/').pop()} was fetched in \
1931 ${Math.round(got.duration)}ms`; } \
1932 return out;";
1933
1934 let told = self.inner.execute(script, Vec::new()).await?;
1935 Ok(told.json().as_str().unwrap_or_default().to_owned())
1936 }
1937
1938 pub async fn error_seen(&self) -> Result<Option<String>> {
1940 let body = self.find_one_by("body").await?;
1941 let seen = body.attr("data-threw").await?;
1942
1943 Ok((!seen.is_empty()).then_some(seen))
1944 }
1945
1946 pub async fn pointer_drag_onto(&self, from: &TestElement, to: &TestElement) -> Result<()> {
1948 from.inner.scroll_into_view().await?;
1949 self.inner
1950 .action_chain()
1951 .move_to_element_center(&from.inner)
1952 .click_and_hold()
1953 .move_by_offset(8, 0)
1954 .release_on_element(&to.inner)
1955 .perform()
1956 .await?;
1957 Ok(())
1958 }
1959
1960 pub async fn native_drag_over(&self, from: &TestElement, to: &TestElement) -> Result<()> {
1967 tracing::trace!("Carrying one element over another with the pointer");
1968
1969 from.inner.scroll_into_view().await?;
1970
1971 self.inner
1972 .action_chain()
1973 .move_to_element_center(&from.inner)
1974 .click_and_hold()
1975 .move_by_offset(4, 0)
1976 .move_by_offset(8, 2)
1977 .move_by_offset(16, 4)
1978 .move_to_element_center(&to.inner)
1979 .move_by_offset(2, 0)
1980 .perform()
1981 .await?;
1982
1983 Ok(())
1984 }
1985
1986 pub async fn release_all_input(&self) -> Result<()> {
1990 self.inner.action_chain().reset_actions().await?;
1991 Ok(())
1992 }
1993
1994 pub async fn native_release(&self) -> Result<()> {
1996 self.inner
1997 .action_chain()
1998 .move_by_offset(1, 0)
1999 .release()
2000 .perform()
2001 .await?;
2002 Ok(())
2003 }
2004
2005 pub async fn watch_mutations(&self, element: &TestElement) -> Result<()> {
2011 self.inner
2012 .execute(
2013 "if (window.__e2eMutations) { \
2014 window.__e2eMutations.observer.disconnect(); \
2015 window.__e2eMutations.outer.disconnect(); \
2016 } \
2017 const watch = { count: 0, kinds: [] }; \
2018 watch.observer = new MutationObserver(records => { \
2019 watch.count += records.length; \
2020 for (const r of records) watch.kinds.push(r.type + ':' + (r.attributeName || '') + ':' + (r.target.className || r.target.nodeName)); \
2021 }); \
2022 watch.observer.observe(arguments[0], \
2023 { subtree: true, childList: true, attributes: true, characterData: true }); \
2024 const node = arguments[0]; \
2025 watch.outer = new MutationObserver(records => { \
2026 for (const r of records) for (const n of r.removedNodes) \
2027 if (n === node || n.contains(node)) { watch.count += 1; watch.kinds.push('removed'); } \
2028 }); \
2029 watch.outer.observe(document.body, { subtree: true, childList: true }); \
2030 if (!window.__e2eClearRect) { \
2031 window.__e2eClearRect = CanvasRenderingContext2D.prototype.clearRect; \
2032 CanvasRenderingContext2D.prototype.clearRect = function (...args) { \
2033 const watch = window.__e2eMutations; \
2034 if (watch && watch.node.contains(this.canvas)) { watch.count += 1; watch.kinds.push('redrawn'); } \
2035 return window.__e2eClearRect.apply(this, args); \
2036 }; \
2037 } \
2038 watch.node = node; \
2039 window.__e2eMutations = watch;",
2040 vec![element.inner.to_json()?],
2041 )
2042 .await?;
2043 Ok(())
2044 }
2045
2046 pub async fn mutations(&self) -> Result<(u64, Vec<String>)> {
2049 let value = self
2050 .inner
2051 .execute(
2052 "const watch = window.__e2eMutations; \
2053 return watch ? [watch.count, watch.kinds] : [0, []];",
2054 Vec::new(),
2055 )
2056 .await?;
2057 Ok(serde_json::from_value(value.json().clone())?)
2058 }
2059
2060 pub async fn external_files(&self, paths: &str) -> Result<TestElement> {
2062 self.inner.execute("const input = document.createElement('input'); input.type = 'file'; input.multiple = true; input.hidden = true; input.dataset.test = 'external-files'; document.body.appendChild(input);", Vec::new()).await?;
2063 let input = self.find_one_by("[data-test='external-files']").await?;
2064 input.send_keys(paths).await?;
2065 Ok(input)
2066 }
2067
2068 pub async fn drag_external_files(
2070 &self,
2071 files: &TestElement,
2072 to: &TestElement,
2073 kind: &str,
2074 ) -> Result<bool> {
2075 let result = self.inner.execute("const data = new DataTransfer(); for (const file of arguments[0].files) data.items.add(file); const event = new DragEvent(arguments[2], {dataTransfer: data, bubbles: true, cancelable: true}); arguments[1].dispatchEvent(event); return event.defaultPrevented;", vec![files.inner.to_json()?, to.inner.to_json()?, kind.into()]).await?;
2076 Ok(serde_json::from_value(result.json().clone())?)
2077 }
2078
2079 pub async fn drag_onto(&self, from: &TestElement, to: &TestElement) -> Result<()> {
2081 tracing::trace!("Carrying one element onto another");
2082
2083 let script = "const data = new DataTransfer(); \
2084 const fire = (node, kind) => node.dispatchEvent( \
2085 new DragEvent(kind, \
2086 { dataTransfer: data, bubbles: true, cancelable: true })); \
2087 fire(arguments[0], 'dragstart'); \
2088 fire(arguments[1], 'dragover'); \
2089 fire(arguments[1], 'drop'); \
2090 fire(arguments[0], 'dragend');";
2091
2092 self.inner
2093 .execute(script, vec![from.inner.to_json()?, to.inner.to_json()?])
2094 .await?;
2095
2096 Ok(())
2097 }
2098
2099 pub async fn drag_over(&self, from: &TestElement, to: &TestElement) -> Result<()> {
2102 tracing::trace!("Carrying one element over another");
2103
2104 let script = "const data = new DataTransfer(); \
2105 const fire = (node, kind) => node.dispatchEvent( \
2106 new DragEvent(kind, \
2107 { dataTransfer: data, bubbles: true, cancelable: true })); \
2108 fire(arguments[0], 'dragstart'); \
2109 fire(arguments[1], 'dragover');";
2110
2111 self.inner
2112 .execute(script, vec![from.inner.to_json()?, to.inner.to_json()?])
2113 .await?;
2114
2115 Ok(())
2116 }
2117
2118 pub async fn drag_off(&self, left: &TestElement) -> Result<()> {
2123 tracing::trace!("Carrying a drag back off an element");
2124
2125 let script = "const data = new DataTransfer(); \
2126 arguments[0].dispatchEvent( \
2127 new DragEvent('dragleave', \
2128 { dataTransfer: data, bubbles: true, cancelable: true }));";
2129
2130 self.inner
2131 .execute(script, vec![left.inner.to_json()?])
2132 .await?;
2133
2134 Ok(())
2135 }
2136
2137 pub async fn scroll_top(&self, element: &TestElement, top: i32) -> Result<()> {
2139 self.inner
2140 .execute(
2141 "arguments[0].scrollTop = arguments[1];",
2142 vec![element.inner.to_json()?, serde_json::json!(top)],
2143 )
2144 .await?;
2145 Ok(())
2146 }
2147
2148 pub async fn scroll_to_far_end(&self, element: &TestElement) -> Result<()> {
2150 tracing::trace!("Scrolling an element's box to the end of its travel");
2151
2152 let script = "let node = arguments[0].parentElement; \
2153 while (node) { \
2154 const how = getComputedStyle(node).overflowX; \
2155 if ((how === 'auto' || how === 'scroll') \
2156 && node.scrollWidth > node.clientWidth) { \
2157 break; \
2158 } \
2159 node = node.parentElement; \
2160 } \
2161 if (node) { node.scrollLeft = node.scrollWidth; }";
2162
2163 self.inner
2164 .execute(script, vec![element.inner.to_json()?])
2165 .await?;
2166
2167 Ok(())
2168 }
2169
2170 pub async fn computed(
2172 &self,
2173 element: &TestElement,
2174 pseudo: &str,
2175 property: &str,
2176 ) -> Result<String> {
2177 tracing::trace!(pseudo, property, "Asking what a property computed to");
2178
2179 let script = "return getComputedStyle(arguments[0], arguments[1] || null) \
2180 .getPropertyValue(arguments[2]);";
2181
2182 let value = self
2183 .inner
2184 .execute(
2185 script,
2186 vec![
2187 element.inner.to_json()?,
2188 serde_json::json!(pseudo),
2189 serde_json::json!(property),
2190 ],
2191 )
2192 .await?;
2193
2194 Ok(value.json().as_str().unwrap_or_default().trim().to_string())
2195 }
2196
2197 pub async fn reduced_motion(&self) -> Result<bool> {
2204 let value = self
2205 .inner
2206 .execute(
2207 "return matchMedia('(prefers-reduced-motion: reduce)').matches;",
2208 Vec::new(),
2209 )
2210 .await?;
2211 let reduced = value
2212 .json()
2213 .as_bool()
2214 .context("reduced-motion media query")?;
2215 if let Ok(requested) = std::env::var("E2E_MOTION") {
2216 anyhow::ensure!(
2217 reduced == (requested == "reduce"),
2218 "browser did not honor E2E_MOTION={requested}"
2219 );
2220 }
2221 Ok(reduced)
2222 }
2223
2224 pub async fn animation_time(
2227 &self,
2228 element: &TestElement,
2229 name: &str,
2230 millis: f64,
2231 ) -> Result<()> {
2232 self.inner.execute(
2233 "const animation = arguments[0].getAnimations().find(a => a.animationName === arguments[1]); \
2234 if (!animation) throw new Error('Missing animation: ' + arguments[1]); \
2235 animation.pause(); animation.currentTime = arguments[2];",
2236 vec![element.inner.to_json()?, serde_json::json!(name), serde_json::json!(millis)],
2237 ).await?;
2238 Ok(())
2239 }
2240
2241 pub async fn color_alpha(&self, element: &TestElement, property: &str) -> Result<f64> {
2244 let value = self.inner.execute(
2245 "const canvas = document.createElement('canvas'); canvas.width = canvas.height = 1; \
2246 const context = canvas.getContext('2d'); context.fillStyle = 'transparent'; \
2247 context.fillStyle = getComputedStyle(arguments[0]).getPropertyValue(arguments[1]); \
2248 context.fillRect(0, 0, 1, 1); return context.getImageData(0, 0, 1, 1).data[3] / 255;",
2249 vec![element.inner.to_json()?, serde_json::json!(property)],
2250 ).await?;
2251 value.json().as_f64().context("computed color alpha")
2252 }
2253
2254 pub async fn color_shift(&self, element: &TestElement, property: &str) -> Result<f64> {
2260 let [red, green, blue] = self.painted(element, property).await?;
2261 Ok((red + green + blue) / 3.0 - 128.0)
2262 }
2263
2264 pub async fn painted(&self, element: &TestElement, property: &str) -> Result<[f64; 3]> {
2271 let value = self.inner.execute(
2272 "const canvas = document.createElement('canvas'); canvas.width = canvas.height = 1; \
2273 const context = canvas.getContext('2d'); \
2274 context.fillStyle = '#808080'; context.fillRect(0, 0, 1, 1); \
2275 context.fillStyle = 'transparent'; \
2276 context.fillStyle = getComputedStyle(arguments[0]).getPropertyValue(arguments[1]); \
2277 context.fillRect(0, 0, 1, 1); \
2278 const painted = context.getImageData(0, 0, 1, 1).data; \
2279 return [painted[0], painted[1], painted[2]];",
2280 vec![element.inner.to_json()?, serde_json::json!(property)],
2281 ).await?;
2282
2283 let read = value.json();
2284 let read = read.as_array().context("what a computed colour paints")?;
2285
2286 let mut rgb = [0.0; 3];
2287
2288 for (channel, value) in rgb.iter_mut().zip(read) {
2289 *channel = value.as_f64().context("a painted channel")?;
2290 }
2291
2292 Ok(rgb)
2293 }
2294
2295 pub async fn canvas_columns(
2304 &self,
2305 canvas: &TestElement,
2306 columns: usize,
2307 ) -> Result<Vec<(f64, f64, f64)>> {
2308 let script = "const canvas = arguments[0]; \
2309 const columns = Math.max(1, arguments[1]); \
2310 const w = canvas.width, h = canvas.height; \
2311 if (w === 0 || h === 0) return []; \
2312 const ctx = canvas.getContext('2d'); \
2313 const data = ctx.getImageData(0, 0, w, h).data; \
2314 const step = Math.max(1, Math.floor(w / columns)); \
2315 const out = []; \
2316 for (let x = 0; x < w; x += step) { \
2317 let top = -1, bottom = -1; \
2318 for (let y = 0; y < h; y++) { \
2319 if (data[(y * w + x) * 4 + 3] > 0) { \
2320 if (top === -1) top = y; \
2321 bottom = y; \
2322 } \
2323 } \
2324 out.push([x / w, top === -1 ? -1 : top / h, bottom === -1 ? -1 : bottom / h]); \
2325 } \
2326 return out;";
2327
2328 let value = self
2329 .inner
2330 .execute(
2331 script,
2332 vec![canvas.inner.to_json()?, serde_json::json!(columns)],
2333 )
2334 .await?;
2335
2336 let read = value.json();
2337 let read = read.as_array().context("canvas column scan")?;
2338 let mut out = Vec::with_capacity(read.len());
2339
2340 for row in read {
2341 let row = row.as_array().context("a canvas column")?;
2342 let field = |at: usize, name: &str| {
2343 row.get(at)
2344 .and_then(serde_json::Value::as_f64)
2345 .with_context(|| format!("a canvas column's {name}"))
2346 };
2347 out.push((field(0, "x")?, field(1, "top")?, field(2, "bottom")?));
2348 }
2349
2350 Ok(out)
2351 }
2352
2353 pub async fn canvas_size(&self, canvas: &TestElement) -> Result<CanvasSize> {
2358 let script = "const c = arguments[0]; const r = c.getBoundingClientRect(); \
2359 return [c.width, c.height, r.width, r.height, window.devicePixelRatio];";
2360
2361 let value = self
2362 .inner
2363 .execute(script, vec![canvas.inner.to_json()?])
2364 .await?;
2365 let read = value.json();
2366 let read = read.as_array().context("canvas size read")?;
2367 let field = |at: usize, name: &str| {
2368 read.get(at)
2369 .and_then(serde_json::Value::as_f64)
2370 .with_context(|| format!("canvas size's {name}"))
2371 };
2372
2373 Ok(CanvasSize {
2374 device_width: field(0, "device_width")?,
2375 device_height: field(1, "device_height")?,
2376 css_width: field(2, "css_width")?,
2377 css_height: field(3, "css_height")?,
2378 device_pixel_ratio: field(4, "device_pixel_ratio")?,
2379 })
2380 }
2381
2382 pub async fn middle_click(&self, element: &TestElement) -> Result<()> {
2384 tracing::trace!("Middle-clicking an element");
2385
2386 let script = "for (const type of ['mousedown', 'mouseup', 'auxclick']) {\
2387 arguments[0].dispatchEvent(new MouseEvent(type, \
2388 { button: 1, buttons: 4, bubbles: true, cancelable: true })); \
2389 }";
2390
2391 self.inner
2392 .execute(script, vec![element.inner.to_json()?])
2393 .await?;
2394
2395 Ok(())
2396 }
2397
2398 pub async fn middle_drag_by(&self, element: &TestElement, dx: i64) -> Result<()> {
2400 use thirtyfour::common::command::Command;
2401
2402 let actions = serde_json::json!([{
2403 "type": "pointer", "id": "pointer", "parameters": {"pointerType": "mouse"},
2404 "actions": [
2405 {"type": "pointerMove", "duration": 0, "origin": element.inner.to_json()?, "x": 0, "y": 0},
2406 {"type": "pointerDown", "button": 1},
2407 {"type": "pointerMove", "duration": 150, "origin": "pointer", "x": dx, "y": 0},
2408 {"type": "pointerUp", "button": 1}
2409 ]
2410 }]);
2411 self.inner
2412 .cmd(Command::PerformActions(actions.into()))
2413 .await?;
2414 Ok(())
2415 }
2416
2417 pub async fn move_held(&self, dx: i64, dy: i64) -> Result<()> {
2419 tracing::trace!(dx, dy, "Carrying a held drag");
2420
2421 self.inner
2422 .action_chain()
2423 .move_by_offset(dx, dy)
2424 .perform()
2425 .await?;
2426
2427 Ok(())
2428 }
2429
2430 pub async fn drop_held(&self) -> Result<()> {
2432 tracing::trace!("Releasing a held drag");
2433 self.inner.action_chain().release().perform().await?;
2434 Ok(())
2435 }
2436
2437 pub async fn cancel_pointer(&self, element: &TestElement) -> Result<()> {
2440 self.inner
2441 .execute(
2442 "arguments[0].dispatchEvent(new PointerEvent('pointercancel', { bubbles: true }));",
2443 vec![element.inner.to_json()?],
2444 )
2445 .await?;
2446 Ok(())
2447 }
2448
2449 pub async fn drop_held_alt(&self) -> Result<()> {
2452 tracing::trace!("Releasing a held drag and the alt key with it");
2453
2454 self.inner
2455 .action_chain()
2456 .release()
2457 .key_up(thirtyfour::Key::Alt)
2458 .perform()
2459 .await?;
2460
2461 Ok(())
2462 }
2463
2464 pub async fn drawn_inside(&self, selector: &str, x: f64, y: f64) -> Result<bool> {
2479 tracing::trace!(selector, x, y, "Asking what is drawn at a point");
2480
2481 let script = "const [selector, x, y] = arguments; \
2482 const host = document.querySelector(selector); \
2483 const found = document.elementFromPoint(x, y); \
2484 if (!host || !found || !host.contains(found)) return false; \
2485 for (const over of document.body.children) { \
2486 if (over.contains(host) || host.contains(over)) continue; \
2487 const box = over.getBoundingClientRect(); \
2488 if (x >= box.left && x <= box.right && y >= box.top && y <= box.bottom) \
2489 return false; \
2490 } \
2491 return true;";
2492
2493 let value = self
2494 .inner
2495 .execute(
2496 script,
2497 vec![
2498 serde_json::json!(selector),
2499 serde_json::json!(x),
2500 serde_json::json!(y),
2501 ],
2502 )
2503 .await?;
2504
2505 Ok(value.json().as_bool().unwrap_or_default())
2506 }
2507
2508 pub async fn screenshot_png(&self) -> Result<Vec<u8>> {
2513 tracing::trace!("Taking a screenshot");
2514 Ok(self.inner.screenshot_as_png().await?)
2515 }
2516
2517 pub async fn screenshot(&self, path: impl AsRef<std::path::Path>) -> Result<()> {
2519 std::fs::write(path, self.screenshot_png().await?)?;
2520 Ok(())
2521 }
2522
2523 pub async fn snapshot(&self, name: &str) -> Result<()> {
2539 let Some(dir) = std::env::var_os("E2E_SHOTS") else {
2540 return Ok(());
2541 };
2542
2543 let dir = std::path::PathBuf::from(dir);
2544
2545 let dir = match dir.is_absolute() {
2546 true => dir,
2547 false => crate::dist::target_dir()?.join("e2e-shots").join(dir),
2548 };
2549
2550 std::fs::create_dir_all(&dir)?;
2551
2552 let path = dir.join(format!("{name}.png"));
2553 tracing::info!(path = %path.display(), "Writing snapshot");
2554 self.screenshot(&path).await
2555 }
2556
2557 pub async fn press_nth(&self, by: impl IntoBy, index: usize) -> Result<()> {
2560 let by = by.into_by();
2561
2562 tracing::trace!(?by, index, "Pressing element");
2563
2564 let deadline = time::Instant::now() + self.wait_timeout;
2565
2566 loop {
2567 let found = self.find_all(by.clone()).await?;
2568
2569 if let Some(item) = found.get(index)
2570 && item.click().await.is_ok()
2571 {
2572 return Ok(());
2573 }
2574
2575 if time::Instant::now() >= deadline {
2576 bail!(
2577 "Timed out after {:?} pressing {by} at {index}",
2578 self.wait_timeout
2579 );
2580 }
2581
2582 time::sleep(POLL_INTERVAL).await;
2583 }
2584 }
2585
2586 pub async fn context_press_nth(&self, by: impl IntoBy, index: usize) -> Result<()> {
2590 let by = by.into_by();
2591
2592 tracing::trace!(?by, index, "Right-clicking element");
2593
2594 let deadline = time::Instant::now() + self.wait_timeout;
2595
2596 loop {
2597 let found = self.find_all(by.clone()).await?;
2598
2599 if let Some(item) = found.get(index)
2600 && item.context_click().await.is_ok()
2601 {
2602 return Ok(());
2603 }
2604
2605 if time::Instant::now() >= deadline {
2606 bail!(
2607 "Timed out after {:?} right-clicking {by} at {index}",
2608 self.wait_timeout
2609 );
2610 }
2611
2612 time::sleep(POLL_INTERVAL).await;
2613 }
2614 }
2615
2616 pub async fn local_storage(&self, key: &str) -> Result<Option<String>> {
2618 let value = self
2619 .inner
2620 .execute(
2621 "return localStorage.getItem(arguments[0]);",
2622 vec![serde_json::json!(key)],
2623 )
2624 .await?;
2625 Ok(value.json().as_str().map(str::to_owned))
2626 }
2627
2628 pub async fn set_local_storage(&self, key: &str, value: &str) -> Result<()> {
2630 self.inner
2631 .execute(
2632 "localStorage.setItem(arguments[0], arguments[1]);",
2633 vec![serde_json::json!(key), serde_json::json!(value)],
2634 )
2635 .await?;
2636 Ok(())
2637 }
2638
2639 pub async fn block_local_storage(&self) -> Result<()> {
2641 self.inner.execute(
2642 "const script = document.createElement('script'); \
2643 script.textContent = `Object.defineProperty(window, 'localStorage', {configurable: true, get() { throw new DOMException('Storage blocked by test', 'SecurityError'); }});`; \
2644 document.documentElement.appendChild(script); script.remove();",
2645 vec![],
2646 ).await?;
2647 Ok(())
2648 }
2649
2650 pub async fn reload(&self) -> Result<()> {
2652 tracing::trace!("Reloading the page");
2653 self.inner.refresh().await?;
2654
2655 let _ = self.watch_for_errors().await;
2656 Ok(())
2657 }
2658
2659 pub async fn reopen_with(&self, query: &str) -> Result<()> {
2661 tracing::trace!(query, "Reopening the page");
2662
2663 let mut url = self.inner.current_url().await?;
2664 url.set_query(Some(query));
2665 self.inner.goto(url.as_str()).await?;
2666 Ok(())
2667 }
2668
2669 pub async fn in_second_tab(&self, run: impl AsyncFnOnce() -> Result<()>) -> Result<()> {
2674 self.in_second_context(true, run).await
2675 }
2676
2677 pub async fn in_second_window(&self, run: impl AsyncFnOnce() -> Result<()>) -> Result<()> {
2679 self.in_second_context(false, run).await
2680 }
2681
2682 async fn in_second_context(
2683 &self,
2684 tab: bool,
2685 run: impl AsyncFnOnce() -> Result<()>,
2686 ) -> Result<()> {
2687 let original = self.inner.window().await?;
2688 let url = self.inner.current_url().await?;
2689 let opened = if tab {
2690 self.inner.new_tab().await?
2691 } else {
2692 self.inner.new_window().await?
2693 };
2694
2695 let result = async {
2696 self.inner.switch_to_window(opened.clone()).await?;
2697 self.set_window_size(WINDOW.0, WINDOW.1).await?;
2698 self.inner.goto(url.as_str()).await?;
2699 run().await?;
2700 match self.error_seen().await? {
2701 Some(threw) => bail!("the page threw: {threw}"),
2702 None => Ok(()),
2703 }
2704 }
2705 .await;
2706
2707 let cleanup = async {
2708 self.inner.switch_to_window(opened).await?;
2709 self.inner.close_window().await?;
2710 self.inner.switch_to_window(original).await?;
2711 Ok(())
2712 }
2713 .await;
2714
2715 match result {
2716 Ok(()) => cleanup,
2717 Err(error) => Err(with_cleanup(error, cleanup)),
2718 }
2719 }
2720
2721 pub async fn press_key(&self, key: Key) -> Result<()> {
2724 tracing::trace!(?key, "Pressing a key");
2725 self.inner.action_chain().send_keys(key).perform().await?;
2726 Ok(())
2727 }
2728
2729 pub async fn hold_key(&self, key: char) -> Result<()> {
2732 self.inner.action_chain().key_down(key).perform().await?;
2733 Ok(())
2734 }
2735
2736 pub async fn release_key(&self, key: char) -> Result<()> {
2738 self.inner.action_chain().key_up(key).perform().await?;
2739 Ok(())
2740 }
2741
2742 pub async fn find_all_attrs(&self, selector: &str, attr: &str) -> Result<Vec<String>> {
2747 let script = format!(
2748 "return Array.from(document.querySelectorAll({})) \
2749 .map(n => n.getAttribute({}) ?? '')",
2750 serde_json::to_string(selector)?,
2751 serde_json::to_string(attr)?,
2752 );
2753
2754 let read = self.inner.execute(script, Vec::new()).await?;
2755
2756 Ok(read
2757 .json()
2758 .as_array()
2759 .map(|rows| {
2760 rows.iter()
2761 .map(|row| row.as_str().unwrap_or_default().to_owned())
2762 .collect()
2763 })
2764 .unwrap_or_default())
2765 }
2766
2767 pub async fn bands(&self, selector: &str, attr: &str) -> Result<Vec<(String, f64, f64)>> {
2776 let script = format!(
2777 "return Array.from(document.querySelectorAll({})) \
2778 .filter(n => n.getClientRects().length > 0) \
2779 .map(n => [n.getAttribute({}) ?? '', \
2780 n.getBoundingClientRect().top, n.getBoundingClientRect().height])",
2781 serde_json::to_string(selector)?,
2782 serde_json::to_string(attr)?,
2783 );
2784
2785 let read = self.inner.execute(script, Vec::new()).await?;
2786 let read = read.json();
2787
2788 let rows = read.as_array().context("a list of bands")?;
2789 let mut bands = Vec::with_capacity(rows.len());
2790
2791 for row in rows {
2792 let row = row.as_array().context("a band")?;
2793
2794 bands.push((
2795 row.first()
2796 .and_then(|name| name.as_str())
2797 .unwrap_or_default()
2798 .to_owned(),
2799 row.get(1).and_then(|top| top.as_f64()).context("a top")?,
2800 row.get(2)
2801 .and_then(|height| height.as_f64())
2802 .context("a height")?,
2803 ));
2804 }
2805
2806 Ok(bands)
2807 }
2808
2809 pub async fn press_key_on(&self, selector: &str, key: &str) -> Result<()> {
2811 let script = format!(
2812 "const at = document.querySelector({}); \
2813 if (!at) throw new Error('No element for keyboard press'); \
2814 at.focus(); at.dispatchEvent(new KeyboardEvent('keydown', \
2815 {{ key: {}, bubbles: true, cancelable: true }}));",
2816 serde_json::to_string(selector)?,
2817 serde_json::to_string(key)?,
2818 );
2819 self.inner.execute(script, Vec::new()).await?;
2820 Ok(())
2821 }
2822
2823 pub async fn press_key_with_ctrl(&self, selector: &str, key: &str) -> Result<()> {
2831 tracing::trace!(selector, key, "Pressing a key with control held");
2832
2833 let code = match key.chars().collect::<Vec<_>>().as_slice() {
2834 [c] if c.is_ascii_alphabetic() => format!("Key{}", c.to_ascii_uppercase()),
2835 _ => key.to_owned(),
2836 };
2837
2838 let script = format!(
2839 "const at = document.querySelector({}); \
2840 if (at) {{ at.focus(); at.dispatchEvent(new KeyboardEvent('keydown', \
2841 {{ key: {}, code: {}, ctrlKey: true, bubbles: true, cancelable: true }})); }}",
2842 serde_json::to_string(selector)?,
2843 serde_json::to_string(key)?,
2844 serde_json::to_string(&code)?,
2845 );
2846
2847 self.inner.execute(script, Vec::new()).await?;
2848 Ok(())
2849 }
2850
2851 pub async fn press_key_with_shift(&self, selector: &str, key: &str) -> Result<()> {
2854 tracing::trace!(selector, key, "Pressing a key with shift held");
2855
2856 let script = format!(
2857 "const at = document.querySelector({}); \
2858 if (at) {{ at.focus(); at.dispatchEvent(new KeyboardEvent('keydown', \
2859 {{ key: {}, shiftKey: true, bubbles: true, cancelable: true }})); }}",
2860 serde_json::to_string(selector)?,
2861 serde_json::to_string(key)?,
2862 );
2863
2864 self.inner.execute(script, Vec::new()).await?;
2865 Ok(())
2866 }
2867
2868 pub async fn blur(&self) -> Result<()> {
2871 tracing::trace!("Blurring the focused element");
2872
2873 self.inner
2874 .execute(
2875 "document.activeElement && document.activeElement.blur();",
2876 Vec::new(),
2877 )
2878 .await?;
2879
2880 Ok(())
2881 }
2882
2883 pub async fn focused_attr(&self, name: &str) -> Result<Option<String>> {
2889 let found = self
2890 .inner
2891 .execute(
2892 "return document.activeElement \
2893 && document.activeElement.getAttribute(arguments[0])",
2894 vec![serde_json::json!(name)],
2895 )
2896 .await?;
2897
2898 Ok(found.json().as_str().map(str::to_owned))
2899 }
2900
2901 common!();
2902}
2903
2904pub trait IntoBy {
2929 fn into_by(self) -> By;
2931}
2932
2933impl IntoBy for &str {
2934 #[inline]
2935 fn into_by(self) -> By {
2936 By::Css(self)
2937 }
2938}
2939
2940impl IntoBy for &String {
2943 #[inline]
2944 fn into_by(self) -> By {
2945 By::Css(self.as_str())
2946 }
2947}
2948
2949impl IntoBy for By {
2950 #[inline]
2951 fn into_by(self) -> By {
2952 self
2953 }
2954}