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::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 sessions;
191
192pub use self::dist::{dist, target_dir, workspace_root};
193pub use self::driver::Engine;
194
195use self::driver::{Driver, QUIT_TIMEOUT, STARTUP_TIMEOUT, with_cleanup};
196
197pub mod prelude {
208 pub use anyhow::{Context, Result, anyhow, bail, ensure};
209 pub use thirtyfour::prelude::*;
210
211 pub use crate::{TestDriver, TestElement};
214}
215
216pub trait Fixture: Sized + 'static {
223 type Setup: Default;
227
228 fn config() -> Config {
230 Config::default()
231 }
232
233 fn init_tracing() {
236 _ = tracing_subscriber::fmt()
237 .with_max_level(tracing::Level::INFO)
238 .try_init();
239 }
240
241 fn start(setup: Self::Setup) -> impl Future<Output = Result<Self>>;
243
244 fn url(&self) -> String;
246
247 fn quit(self) -> impl Future<Output = Result<()>>;
249}
250
251#[derive(Debug, Clone)]
253pub struct Config {
254 pub(crate) about: String,
255 pub(crate) frontend: Frontend,
256 pub(crate) lock: String,
257 pub(crate) sessions: String,
258}
259
260impl Default for Config {
261 fn default() -> Self {
262 Self {
263 about: String::from("A browser suite."),
264 frontend: Frontend::Trunk(PathBuf::new()),
265 lock: String::from("yew-e2e.lock"),
266 sessions: String::from("e2e-sessions"),
267 }
268 }
269}
270
271impl Config {
272 pub fn about(mut self, about: impl Into<String>) -> Self {
274 self.about = about.into();
275 self
276 }
277
278 pub fn frontend(mut self, frontend: Frontend) -> Self {
280 self.frontend = frontend;
281 self
282 }
283
284 pub fn lock_name(mut self, name: impl Into<String>) -> Self {
286 self.lock = name.into();
287 self
288 }
289
290 pub fn sessions_dir(mut self, name: impl Into<String>) -> Self {
294 self.sessions = name.into();
295 self
296 }
297}
298
299#[derive(Debug, Clone)]
302pub enum Frontend {
303 None,
305 Trunk(PathBuf),
309}
310
311#[derive(Clone, Default)]
320pub(crate) struct Waiting(Arc<Mutex<Option<String>>>);
321
322impl Waiting {
323 fn on(&self, what: impl std::fmt::Display) {
325 *self.held() = Some(what.to_string());
326 }
327
328 fn clear(&self) {
330 *self.held() = None;
331 }
332
333 pub(crate) fn clause(&self) -> String {
336 match &*self.held() {
337 Some(what) => format!(", last waiting for {what}"),
338 None => String::new(),
339 }
340 }
341
342 fn held(&self) -> std::sync::MutexGuard<'_, Option<String>> {
345 self.0.lock().unwrap_or_else(|held| held.into_inner())
346 }
347}
348
349pub(crate) struct Browser {
351 webdriver: Driver,
352 driver: TestDriver,
353}
354
355impl Browser {
356 pub(crate) async fn open() -> Result<Self> {
358 let engine = crate::harness::engine();
359 let deadline = time::Instant::now() + STARTUP_TIMEOUT;
360 let caps = engine.capabilities(crate::harness::headed())?;
361 let webdriver = Driver::new(engine, deadline).await?;
362 Self::connect(webdriver, caps, deadline).await
363 }
364
365 async fn connect(
366 mut webdriver: Driver,
367 mut caps: Capabilities,
368 deadline: time::Instant,
369 ) -> Result<Self> {
370 let downloads = tempfile::tempdir().context("creating browser download directory")?;
371 let directory = downloads.path().to_string_lossy().into_owned();
372 let key = match webdriver.engine() {
373 Engine::Firefox => "moz:firefoxOptions",
374 Engine::Chrome => "goog:chromeOptions",
375 };
376 if !caps.contains_key(key) {
377 caps.set(key, serde_json::json!({}))?;
378 }
379 match webdriver.engine() {
380 Engine::Firefox => {
381 let options = caps
382 .get_mut("moz:firefoxOptions")
383 .context("Firefox capabilities have no options")?;
384 let prefs = options
385 .as_object_mut()
386 .context("Firefox options")?
387 .entry("prefs")
388 .or_insert_with(|| serde_json::json!({}));
389 let prefs = prefs.as_object_mut().context("Firefox preferences")?;
390 prefs.insert("browser.download.folderList".into(), 2.into());
391 prefs.insert("browser.download.dir".into(), directory.into());
392 prefs.insert("browser.download.useDownloadDir".into(), true.into());
393 prefs.insert(
394 "browser.helperApps.neverAsk.saveToDisk".into(),
395 "audio/wav,application/zip,application/json".into(),
396 );
397 }
398 Engine::Chrome => {
399 let options = caps
400 .get_mut("goog:chromeOptions")
401 .context("Chrome capabilities have no options")?;
402 options["prefs"] = serde_json::json!({
403 "download.default_directory": directory,
404 "download.prompt_for_download": false,
405 });
406 }
407 }
408 tracing::info!(
409 "{} address: {:?}",
410 webdriver.engine().driver(),
411 webdriver.address
412 );
413
414 let url = format!("http://{}", webdriver.address);
415 let connected = webdriver
416 .during(deadline, "startup", async {
417 Ok(WebDriver::new(&url, caps).await?)
418 })
419 .await;
420 let driver = match connected {
421 Ok(driver) => driver,
422 Err(error) => return Err(with_cleanup(error, webdriver.terminate().await)),
423 };
424
425 Ok(Self {
426 webdriver,
427 driver: TestDriver {
428 inner: driver,
429 wait_timeout: WAIT_TIMEOUT,
430 load_timeout: LOAD_TIMEOUT,
431 waiting: Waiting::default(),
432 downloads,
433 },
434 })
435 }
436
437 async fn reset(&mut self, url: &str) -> Result<()> {
443 self.driver.waiting.clear();
444 for file in std::fs::read_dir(self.driver.downloads.path())? {
445 std::fs::remove_file(file?.path())?;
446 }
447 let old = self.driver.inner.window().await?;
448 let fresh = self.driver.inner.new_tab().await?;
449 self.driver.inner.switch_to_window(fresh.clone()).await?;
450 self.driver.inner.switch_to_window(old).await?;
451 self.driver.inner.close_window().await?;
452 self.driver.inner.switch_to_window(fresh).await?;
453 self.driver.set_window_size(WINDOW.0, WINDOW.1).await?;
454 self.driver.inner.goto(url).await?;
455 Ok(())
456 }
457
458 pub(crate) async fn close(mut self) -> Result<Option<anyhow::Error>> {
464 let driver = self.driver.inner.clone();
468 let quit = self
469 .webdriver
470 .during(time::Instant::now() + QUIT_TIMEOUT, "quit", async {
471 Ok(driver.quit().await?)
472 })
473 .await;
474 let reaped = self.webdriver.terminate().await;
475 match (quit, reaped) {
476 (Ok(()), reaped) => reaped.map(|()| None),
477 (Err(error), Ok(())) if error.downcast_ref::<driver::TimedOut>().is_some() => {
478 Ok(Some(error))
479 }
480 (Err(error), reaped) => Err(with_cleanup(error, reaped)),
481 }
482 }
483}
484
485impl Drop for Browser {
486 fn drop(&mut self) {
487 let _ = self.driver.inner.clone().leak();
490 }
491}
492
493#[cfg(test)]
494mod browser_tests {
495 use anyhow::{Context, Result, ensure};
496
497 use super::Browser;
498
499 #[tokio::test]
505 #[ignore = "requires a real WebDriver"]
506 async fn a_reset_discards_the_preceding_document() -> Result<()> {
507 let mut browser = Browser::open().await?;
508
509 let result = async {
510 browser.reset("data:text/html,first").await?;
511 let first = browser.driver.inner.window().await?;
512
513 browser.reset("data:text/html,second").await?;
514 let second = browser.driver.inner.window().await?;
515 let windows = browser.driver.inner.windows().await?;
516 let history = browser
517 .driver
518 .inner
519 .execute("return history.length", Vec::new())
520 .await?
521 .json()
522 .as_u64()
523 .context("browser history length")?;
524
525 ensure!(first != second, "the second reset kept the first tab");
526 ensure!(windows == [second], "reset left tabs behind: {windows:?}");
527 ensure!(history <= 2, "the fresh tab has {history} history entries");
528 Ok(())
529 }
530 .await;
531
532 match (result, browser.close().await) {
533 (Ok(()), Ok(_)) => Ok(()),
534 (Err(error), Ok(_)) | (Ok(()), Err(error)) => Err(error),
535 (Err(error), Err(cleanup)) => Err(super::driver::with_cleanup(error, Err(cleanup))),
536 }
537 }
538}
539
540const WINDOW: (u32, u32) = (1600, 1000);
542
543const SESSION_DEATH: &[&str] = &[
554 "invalid session id",
555 "session id is invalid",
556 "session deleted because of page crash",
557 "session terminated",
558 "the webdriver server's output ended",
559 "error sending request",
560];
561
562pub(crate) fn browser_death(error: &anyhow::Error) -> Option<&'static str> {
565 let mut source: Option<&dyn std::error::Error> = Some(error.as_ref());
566
567 while let Some(error) = source {
568 let said = error.to_string().to_lowercase();
569
570 if let Some(mark) = SESSION_DEATH.iter().find(|mark| said.contains(**mark)) {
571 return Some(mark);
572 }
573
574 source = error.source();
575 }
576
577 None
578}
579
580fn went_away(browser: &Browser, mark: &str) -> anyhow::Error {
586 let name = browser.webdriver.engine().driver();
587
588 anyhow!(
589 "the browser went away ({mark}); {name} last said: {}",
590 driver_said(browser)
591 )
592}
593
594fn driver_said(browser: &Browser) -> String {
597 let said = browser.webdriver.diagnostics();
598
599 said.lines()
600 .rev()
601 .take(3)
602 .collect::<Vec<_>>()
603 .into_iter()
604 .rev()
605 .collect::<Vec<_>>()
606 .join(" | ")
607}
608
609pub(crate) async fn run_one<F: Fixture>(
611 browser: &mut Browser,
612 start: crate::harness::Start<F>,
613 setup: F::Setup,
614 limit: Option<Duration>,
615) -> Result<()> {
616 let mut fixture = F::start(setup).await?;
617
618 let mut errors = String::new();
619
620 let result = match browser.reset(&fixture.url()).await {
621 Ok(()) => drive_one(browser, &mut fixture, start, limit).await,
622 Err(error) => Err(error),
623 };
624
625 let fixture_result = fixture.quit().await;
626
627 if let Err(error) = result.as_ref() {
628 if let Some(mark) = browser_death(error) {
629 let mut error = went_away(browser, mark);
630
631 if let Err(quit) = fixture_result {
632 error = error.context(format!("the fixture also failed to quit: {quit}"));
633 }
634
635 return Err(error);
636 }
637
638 writeln!(errors, "Test error: {error}")?;
639
640 let mut source = error.source();
641
642 while let Some(e) = source.take() {
643 writeln!(errors, " Caused by: {e}")?;
644 source = e.source();
645 }
646 }
647
648 if let Err(error) = fixture_result {
649 writeln!(errors, "Fixture error: {error}")?;
650
651 let mut source = error.source();
652
653 while let Some(e) = source.take() {
654 writeln!(errors, " Caused by: {e}")?;
655 source = e.source();
656 }
657 }
658
659 if !errors.is_empty() {
660 return Err(anyhow!("{errors}"));
661 }
662
663 Ok(())
664}
665
666async fn drive_one<F: Fixture>(
676 browser: &mut Browser,
677 fixture: &mut F,
678 start: crate::harness::Start<F>,
679 limit: Option<Duration>,
680) -> Result<()> {
681 let mut timeout = pin!(async move {
682 match limit {
683 Some(limit) => time::sleep(limit).await,
684 None => std::future::pending::<()>().await,
685 }
686 });
687
688 let Browser { webdriver, driver } = browser;
689
690 let waiting = driver.waiting.clone();
691
692 let outcome = {
693 let task = AssertUnwindSafe(start(driver, fixture)).catch_unwind();
694 let mut task = pin!(task);
695
696 loop {
697 tokio::select! {
698 _ = timeout.as_mut() => {
699 break Err(overran(limit, &waiting));
700 }
701 result = task.as_mut() => {
702 break Ok(result);
703 }
704 result = webdriver.io() => {
705 if !result? {
706 break Err("the WebDriver server's output ended".to_string());
707 }
708 }
709 }
710 }
711 };
712
713 match outcome {
714 Ok(Ok(Ok(()))) => match driver.error_seen().await? {
715 Some(threw) => bail!("the page threw: {threw}"),
716 None => Ok(()),
717 },
718 Ok(Ok(result)) => result,
719 Ok(Err(panicked)) => bail!("the test panicked: {}", panic_message(&panicked)),
720 Err(error) => bail!(error),
721 }
722}
723
724pub(crate) fn overran(limit: Option<Duration>, waiting: &Waiting) -> String {
727 let seconds = limit.map_or(0, |limit| limit.as_secs());
728
729 format!(
730 "the test was still running after {seconds}s, which is --timeout{}",
731 waiting.clause()
732 )
733}
734
735fn panic_message(payload: &Box<dyn std::any::Any + Send>) -> &str {
737 if let Some(message) = payload.downcast_ref::<&'static str>() {
738 return message;
739 }
740
741 if let Some(message) = payload.downcast_ref::<String>() {
742 return message;
743 }
744
745 "a payload that is neither a string nor a &str"
746}
747
748fn drag_nudge(offset: i64) -> i64 {
751 offset.clamp(-8, 8)
752}
753
754pub const POLL_INTERVAL: Duration = Duration::from_millis(25);
756
757const WAIT_TIMEOUT: Duration = Duration::from_secs(5);
759
760const LOAD_TIMEOUT: Duration = Duration::from_secs(15);
765
766macro_rules! common {
767 () => {
768 pub async fn wait_until(
770 &self,
771 what: impl std::fmt::Display,
772 condition: impl AsyncFnMut() -> Result<bool>,
773 ) -> Result<()> {
774 self.wait_for(self.wait_timeout, what, condition).await
775 }
776
777 pub async fn wait_until_within(
782 &self,
783 timeout: Duration,
784 what: impl std::fmt::Display,
785 condition: impl AsyncFnMut() -> Result<bool>,
786 ) -> Result<()> {
787 self.wait_for(timeout, what, condition).await
788 }
789
790 async fn wait_for(
792 &self,
793 timeout: Duration,
794 what: impl std::fmt::Display,
795 mut condition: impl AsyncFnMut() -> Result<bool>,
796 ) -> Result<()> {
797 let deadline = time::Instant::now() + timeout;
798
799 self.waiting.on(&what);
800
801 loop {
802 if condition().await? {
803 return Ok(());
804 }
805
806 if time::Instant::now() >= deadline {
807 bail!("Timed out after {timeout:?} waiting for {what}");
808 }
809
810 time::sleep(POLL_INTERVAL).await;
811 }
812 }
813
814 pub async fn wait_texts<const N: usize>(
816 &self,
817 by: impl IntoBy,
818 expected: [&str; N],
819 ) -> Result<()> {
820 let by = by.into_by();
821
822 tracing::trace!(?by, ?expected, "Waiting for texts");
823
824 let seen = std::cell::RefCell::new(Vec::new());
825
826 let result = self
827 .wait_until(format_args!("{by} to read {expected:?}"), async || {
828 let texts = self.find_all_texts(by.clone()).await?;
829 let matched = texts == expected;
830 *seen.borrow_mut() = texts;
831 Ok(matched)
832 })
833 .await;
834
835 match result {
836 Ok(()) => Ok(()),
837 Err(error) => {
838 let seen = seen.into_inner();
839 Err(error.context(format!("last read {seen:?}")))
840 }
841 }
842 }
843
844 pub async fn wait_count(&self, by: impl IntoBy, expected: usize) -> Result<()> {
859 let by = by.into_by();
860
861 tracing::trace!(?by, expected, "Waiting for count");
862
863 self.wait_until(format_args!("{by} to match {expected} nodes"), async || {
864 Ok(self.find_all(by.clone()).await?.len() == expected)
865 })
866 .await
867 }
868
869 #[inline]
873 pub async fn count(&self, by: impl IntoBy) -> Result<usize> {
874 Ok(self.find_all(by.into_by()).await?.len())
875 }
876
877 pub async fn wait_count_from(
891 &self,
892 by: impl IntoBy,
893 before: usize,
894 expected: usize,
895 ) -> Result<()> {
896 let by = by.into_by();
897
898 ensure!(
899 before != expected,
900 "Waiting for {by} to match {expected} nodes verifies nothing: \
901 {expected} is also the count read before the action, so the \
902 first poll agrees whether or not the action has landed. Assert \
903 the count this action is supposed to produce, or if it really \
904 is meant to leave the count alone, assert what it did change.",
905 );
906
907 tracing::trace!(?by, before, expected, "Waiting for count to change");
908
909 self.wait_until(
910 format_args!("{by} to go from {before} to {expected} nodes"),
911 async || Ok(self.find_all(by.clone()).await?.len() == expected),
912 )
913 .await
914 }
915
916 #[inline]
918 pub async fn find_all_texts(&self, by: impl IntoBy) -> Result<Vec<String>> {
919 let mut texts = Vec::new();
920
921 for item in self.find_all(by.into_by()).await? {
922 texts.push(item.text().await?);
923 }
924
925 Ok(texts)
926 }
927
928 #[inline]
930 pub async fn find_one_by_xpath(&self, xpath: &str) -> Result<TestElement> {
931 self.find_one_by(By::XPath(xpath)).await
932 }
933
934 pub async fn find_one_by(&self, by: impl IntoBy) -> Result<TestElement> {
941 let by = by.into_by();
942
943 tracing::trace!(?by, "Finding one element");
944
945 let deadline = time::Instant::now() + self.wait_timeout;
946
947 loop {
948 let items = self.find_all(by.clone()).await?;
949
950 ensure!(
951 items.len() <= 1,
952 "Expected exactly one by {by}, but got {}: where several is \
953 what the page is, ask for one of them by index with \
954 find_nth, or for the first of them with find_first",
955 items.len()
956 );
957
958 if let Some(item) = items.into_iter().next() {
959 return Ok(item);
960 }
961
962 if time::Instant::now() >= deadline {
963 bail!(
964 "Timed out after {:?} waiting for {by}",
965 self.wait_timeout
966 );
967 }
968
969 time::sleep(POLL_INTERVAL).await;
970 }
971 }
972
973 pub async fn find_nth(&self, by: impl IntoBy, index: usize) -> Result<TestElement> {
988 let by = by.into_by();
989
990 tracing::trace!(?by, index, "Finding one of several elements");
991
992 let deadline = time::Instant::now() + self.wait_timeout;
993
994 loop {
995 if let Some(item) = self.find_all(by.clone()).await?.into_iter().nth(index) {
996 return Ok(item);
997 }
998
999 if time::Instant::now() >= deadline {
1000 bail!(
1001 "Timed out after {:?} waiting for {by} at {index}",
1002 self.wait_timeout
1003 );
1004 }
1005
1006 time::sleep(POLL_INTERVAL).await;
1007 }
1008 }
1009
1010 #[inline]
1013 pub async fn find_first(&self, by: impl IntoBy) -> Result<TestElement> {
1014 self.find_nth(by, 0).await
1015 }
1016
1017 pub async fn find_all(&self, by: impl Into<By>) -> Result<Vec<TestElement>> {
1019 self.find_all_within(self.wait_timeout, by).await
1020 }
1021
1022 pub async fn find_all_within(
1026 &self,
1027 timeout: Duration,
1028 by: impl Into<By>,
1029 ) -> Result<Vec<TestElement>> {
1030 let by = by.into();
1031 tracing::trace!(?by, "Finding all elements");
1032
1033 let task = self.inner.find_all(by.clone());
1034 let sleep = time::sleep(timeout);
1035
1036 tokio::select! {
1037 _ = sleep => {
1038 Err(anyhow!("find_elements({by:?}) timed out after {timeout:?}"))
1039 }
1040 result = task => {
1041 Ok(result?.into_iter().map(|inner| TestElement { inner, wait_timeout: self.wait_timeout, waiting: self.waiting.clone() }).collect::<Vec<_>>())
1042 }
1043 }
1044 }
1045 }
1046}
1047
1048#[derive(Debug, Clone, Copy)]
1050pub struct CanvasSize {
1051 pub device_width: f64,
1053 pub device_height: f64,
1055 pub css_width: f64,
1057 pub css_height: f64,
1059 pub device_pixel_ratio: f64,
1061}
1062
1063pub struct TestElement {
1065 inner: WebElement,
1066 wait_timeout: Duration,
1067 waiting: Waiting,
1068}
1069
1070impl TestElement {
1071 pub fn element(&self) -> &WebElement {
1074 &self.inner
1075 }
1076
1077 pub async fn click(&self) -> Result<()> {
1079 tracing::trace!("Clicking element");
1080 self.inner.click().await?;
1081 Ok(())
1082 }
1083
1084 pub async fn extend_click(&self) -> Result<()> {
1087 tracing::trace!("Extend-clicking element");
1088
1089 self.inner.scroll_into_view().await?;
1090
1091 self.inner
1092 .handle()
1093 .action_chain()
1094 .key_down(thirtyfour::Key::Control)
1095 .click_element(&self.inner)
1096 .key_up(thirtyfour::Key::Control)
1097 .perform()
1098 .await?;
1099
1100 Ok(())
1101 }
1102
1103 pub async fn shift_click(&self) -> Result<()> {
1106 tracing::trace!("Shift-clicking element");
1107
1108 self.inner.scroll_into_view().await?;
1109
1110 self.inner
1111 .handle()
1112 .action_chain()
1113 .key_down(thirtyfour::Key::Shift)
1114 .click_element(&self.inner)
1115 .key_up(thirtyfour::Key::Shift)
1116 .perform()
1117 .await?;
1118
1119 Ok(())
1120 }
1121
1122 pub async fn hover(&self) -> Result<()> {
1124 tracing::trace!("Hovering element");
1125
1126 self.inner.scroll_into_view().await?;
1127
1128 self.inner
1129 .handle()
1130 .action_chain()
1131 .move_to_element_center(&self.inner)
1132 .perform()
1133 .await?;
1134
1135 Ok(())
1136 }
1137
1138 pub async fn double_click(&self) -> Result<()> {
1140 tracing::trace!("Double-clicking element");
1141
1142 self.inner.scroll_into_view().await?;
1143
1144 self.inner
1145 .handle()
1146 .action_chain()
1147 .double_click_element(&self.inner)
1148 .perform()
1149 .await?;
1150
1151 Ok(())
1152 }
1153
1154 pub async fn double_click_by(&self, dx: i64, dy: i64) -> Result<()> {
1158 tracing::trace!(dx, dy, "Double-clicking element off centre");
1159
1160 self.inner.scroll_into_view().await?;
1161
1162 self.inner
1163 .handle()
1164 .action_chain()
1165 .move_to_element_center(&self.inner)
1166 .move_by_offset(dx, dy)
1167 .double_click()
1168 .perform()
1169 .await?;
1170
1171 Ok(())
1172 }
1173
1174 pub async fn click_by(&self, dx: i64, dy: i64) -> Result<()> {
1178 tracing::trace!(dx, dy, "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 .click()
1188 .perform()
1189 .await?;
1190
1191 Ok(())
1192 }
1193
1194 pub async fn context_click(&self) -> Result<()> {
1196 tracing::trace!("Context-clicking element");
1197
1198 self.inner.scroll_into_view().await?;
1199
1200 self.inner
1201 .handle()
1202 .action_chain()
1203 .context_click_element(&self.inner)
1204 .perform()
1205 .await?;
1206
1207 Ok(())
1208 }
1209
1210 pub async fn drag_by(&self, dx: i64, dy: i64) -> Result<()> {
1217 tracing::trace!(dx, dy, "Dragging element");
1218
1219 let (nx, ny) = (drag_nudge(dx), drag_nudge(dy));
1220
1221 self.inner.scroll_into_view().await?;
1222
1223 self.inner
1224 .handle()
1225 .action_chain()
1226 .move_to_element_center(&self.inner)
1227 .click_and_hold()
1228 .move_by_offset(nx, ny)
1229 .move_by_offset(dx - nx, dy - ny)
1230 .perform()
1231 .await?;
1232
1233 Ok(())
1234 }
1235
1236 pub async fn drag_from_by(&self, at_x: i64, at_y: i64, dx: i64, dy: i64) -> Result<()> {
1242 tracing::trace!(at_x, at_y, dx, dy, "Dragging from a point in an element");
1243
1244 let (nx, ny) = (drag_nudge(dx), drag_nudge(dy));
1245
1246 self.inner.scroll_into_view().await?;
1247
1248 self.inner
1249 .handle()
1250 .action_chain()
1251 .move_to_element_center(&self.inner)
1252 .move_by_offset(at_x, at_y)
1253 .click_and_hold()
1254 .move_by_offset(nx, ny)
1255 .move_by_offset(dx - nx, dy - ny)
1256 .perform()
1257 .await?;
1258
1259 Ok(())
1260 }
1261
1262 pub async fn alt_drag_by(&self, dx: i64, dy: i64) -> Result<()> {
1264 tracing::trace!(dx, dy, "Dragging element with alt held");
1265
1266 let (nx, ny) = (drag_nudge(dx), drag_nudge(dy));
1267
1268 self.inner.scroll_into_view().await?;
1269
1270 self.inner
1271 .handle()
1272 .action_chain()
1273 .key_down(thirtyfour::Key::Alt)
1274 .move_to_element_center(&self.inner)
1275 .click_and_hold()
1276 .move_by_offset(nx, ny)
1277 .move_by_offset(dx - nx, dy - ny)
1278 .perform()
1279 .await?;
1280
1281 Ok(())
1282 }
1283
1284 pub async fn text(&self) -> Result<String> {
1286 tracing::trace!("Getting element text");
1287 Ok(self.inner.text().await?)
1288 }
1289
1290 pub async fn prop(&self, name: &str) -> Result<String> {
1292 tracing::trace!(name, "Getting element property");
1293 Ok(self.inner.prop(name).await?.unwrap_or_default())
1294 }
1295
1296 pub async fn attr(&self, name: &str) -> Result<String> {
1299 tracing::trace!(name, "Getting element attribute");
1300 Ok(self.inner.attr(name).await?.unwrap_or_default())
1301 }
1302
1303 pub async fn scroll_into_view(&self) -> Result<()> {
1305 tracing::trace!("Scrolling element into view");
1306 self.inner.scroll_into_view().await?;
1307 Ok(())
1308 }
1309
1310 pub async fn focus(&self) -> Result<()> {
1312 tracing::trace!("Focusing element");
1313 self.inner.focus().await?;
1314 Ok(())
1315 }
1316
1317 pub async fn visible(&self) -> Result<bool> {
1323 Ok(self.inner.is_displayed().await?)
1324 }
1325
1326 pub async fn rect(&self) -> Result<ElementRect> {
1328 tracing::trace!("Measuring element");
1329 Ok(self.inner.rect().await?)
1330 }
1331
1332 pub async fn css(&self, name: &str) -> Result<String> {
1334 tracing::trace!(name, "Getting element style");
1335 Ok(self.inner.css_value(name).await?)
1336 }
1337
1338 pub async fn value(&self) -> Result<String> {
1340 tracing::trace!("Getting element value");
1341 Ok(self.inner.prop("value").await?.unwrap_or_default())
1342 }
1343
1344 pub async fn clear(&self) -> Result<()> {
1346 tracing::trace!("Clearing element text");
1347 self.inner.clear().await?;
1348 Ok(())
1349 }
1350
1351 pub async fn send_keys(&self, keys: &str) -> Result<()> {
1353 tracing::trace!(?keys, "Sending keys to element");
1354 self.inner.send_keys(keys).await?;
1355 Ok(())
1356 }
1357
1358 pub async fn pressed(&self) -> Result<bool> {
1360 Ok(self.prop("ariaPressed").await? == "true")
1361 }
1362
1363 pub async fn enabled(&self) -> Result<bool> {
1365 Ok(self.inner.is_enabled().await?)
1366 }
1367
1368 pub async fn disabled(&self) -> Result<bool> {
1373 Ok(self.prop("ariaDisabled").await? == "true")
1374 }
1375
1376 common!();
1377}
1378
1379pub struct TestDriver {
1381 inner: WebDriver,
1382 downloads: tempfile::TempDir,
1383 wait_timeout: Duration,
1384 load_timeout: Duration,
1385 waiting: Waiting,
1386}
1387
1388impl TestDriver {
1389 pub async fn local_clock(&self, epoch_ms: u64) -> Result<[u32; 4]> {
1393 let read = self
1394 .inner
1395 .execute(
1396 "const d = new Date(arguments[0]); \
1397 return [d.getMonth() + 1, d.getDate(), d.getHours(), d.getMinutes()]",
1398 vec![serde_json::json!(epoch_ms)],
1399 )
1400 .await?;
1401 let parts = read.json().as_array().context("clock array")?;
1402 let mut clock = [0; 4];
1403
1404 for (slot, part) in clock.iter_mut().zip(parts) {
1405 *slot = u32::try_from(part.as_u64().context("clock part")?)?;
1406 }
1407
1408 Ok(clock)
1409 }
1410
1411 pub async fn rendered_texts(&self, selector: &str) -> Result<Vec<String>> {
1418 let read = self
1419 .inner
1420 .execute(
1421 "return Array.from(document.querySelectorAll(arguments[0])) \
1422 .map(n => n.innerText)",
1423 vec![serde_json::json!(selector)],
1424 )
1425 .await?;
1426 let rows = read.json().as_array().context("rendered text array")?;
1427
1428 rows.iter()
1429 .map(|row| row.as_str().context("rendered text").map(str::to_owned))
1430 .collect()
1431 }
1432
1433 pub fn downloads(&self) -> &std::path::Path {
1435 self.downloads.path()
1436 }
1437
1438 pub(crate) fn waiting(&self) -> Waiting {
1441 self.waiting.clone()
1442 }
1443
1444 pub fn webdriver(&self) -> &WebDriver {
1447 &self.inner
1448 }
1449
1450 pub fn wait_timeout(&self) -> Duration {
1453 self.wait_timeout
1454 }
1455
1456 pub fn load_timeout(&self) -> Duration {
1460 self.load_timeout
1461 }
1462
1463 pub async fn set_window_size(&self, width: u32, height: u32) -> Result<()> {
1465 tracing::trace!(width, height, "Sizing the window");
1466 self.inner.set_window_rect(0, 0, width, height).await?;
1467 Ok(())
1468 }
1469
1470 pub async fn set_style(
1474 &self,
1475 element: &TestElement,
1476 property: &str,
1477 value: &str,
1478 ) -> Result<()> {
1479 tracing::trace!(property, value, "Setting an inline style property");
1480
1481 let script = format!("arguments[0].style.setProperty({property:?}, {value:?});");
1482
1483 self.inner
1484 .execute(script, vec![element.inner.to_json()?])
1485 .await?;
1486
1487 Ok(())
1488 }
1489
1490 pub async fn set_class(&self, element: &TestElement, class: &str, on: bool) -> Result<()> {
1494 tracing::trace!(class, on, "Forcing a class");
1495
1496 let script = format!("arguments[0].classList.toggle({class:?}, {on});");
1497
1498 self.inner
1499 .execute(script, vec![element.inner.to_json()?])
1500 .await?;
1501
1502 Ok(())
1503 }
1504
1505 pub async fn set_value(&self, element: &TestElement, value: &str, event: &str) -> Result<()> {
1509 tracing::trace!(value, event, "Setting a field's value");
1510
1511 self.inner
1512 .execute(
1513 "arguments[0].value = arguments[1]; \
1514 arguments[0].dispatchEvent(new Event(arguments[2], {bubbles: true}));",
1515 vec![
1516 element.inner.to_json()?,
1517 serde_json::json!(value),
1518 serde_json::json!(event),
1519 ],
1520 )
1521 .await?;
1522
1523 Ok(())
1524 }
1525
1526 pub async fn set_text(&self, element: &TestElement, text: &str) -> Result<()> {
1530 tracing::trace!(text, "Replacing an element's text");
1531
1532 let script = format!(
1533 "const node = arguments[0].firstChild; \
1534 if (!node || node.nodeType !== Node.TEXT_NODE) throw new Error('no text node'); \
1535 node.data = {text:?};"
1536 );
1537
1538 self.inner
1539 .execute(script, vec![element.inner.to_json()?])
1540 .await?;
1541
1542 Ok(())
1543 }
1544
1545 pub async fn overflowing(&self, element: &TestElement) -> Result<Vec<String>> {
1551 tracing::trace!("Finding what overflows inside an element");
1552
1553 let script = "const out = []; \
1554 for (const el of [arguments[0], ...arguments[0].querySelectorAll('*')]) { \
1555 if (el.clientHeight <= 1 || el.clientWidth <= 1) continue; \
1556 const cs = getComputedStyle(el); \
1557 const y = el.scrollHeight - el.clientHeight; \
1558 const x = el.scrollWidth - el.clientWidth; \
1559 const shows = v => v === 'auto' || v === 'scroll' || v === 'hidden' || v === 'clip'; \
1560 if ((y > 1 && shows(cs.overflowY)) || (x > 1 && shows(cs.overflowX))) { \
1561 const test = el.getAttribute('data-test'); \
1562 out.push(el.localName + (el.className ? '.' + String(el.className).trim().split(/\\s+/).join('.') : '') \
1563 + (test ? `[data-test=${test}]` : '') \
1564 + ` ${cs.overflowX}/${cs.overflowY} over by ${x}x${y}`); \
1565 } \
1566 } \
1567 return out;";
1568
1569 let found = self
1570 .inner
1571 .execute(script, vec![element.inner.to_json()?])
1572 .await?;
1573
1574 Ok(found
1575 .json()
1576 .as_array()
1577 .into_iter()
1578 .flatten()
1579 .filter_map(|line| line.as_str().map(str::to_owned))
1580 .collect())
1581 }
1582
1583 pub async fn small_text(
1588 &self,
1589 element: &TestElement,
1590 floor: f64,
1591 marks: &str,
1592 ) -> Result<Vec<String>> {
1593 tracing::trace!(floor, marks, "Finding text set below a size");
1594
1595 let script = format!(
1596 "const out = []; \
1597 for (const el of [arguments[0], ...arguments[0].querySelectorAll('*')]) {{ \
1598 if (el.closest({marks:?})) continue; \
1599 const words = Array.from(el.childNodes) \
1600 .filter(n => n.nodeType === Node.TEXT_NODE) \
1601 .map(n => n.textContent.trim()).join(' ').trim(); \
1602 if (!words) continue; \
1603 const rect = el.getBoundingClientRect(); \
1604 if (rect.width <= 1 || rect.height <= 1) continue; \
1605 const cs = getComputedStyle(el); \
1606 if (cs.visibility !== 'visible') continue; \
1607 const size = parseFloat(cs.fontSize); \
1608 if (size < {floor}) {{ \
1609 const test = el.getAttribute('data-test'); \
1610 out.push(el.localName + (el.className ? '.' + String(el.className).trim().split(/\\s+/).join('.') : '') \
1611 + (test ? `[data-test=${{test}}]` : '') \
1612 + ` at ${{cs.fontSize}}: ${{JSON.stringify(words.slice(0, 32))}}`); \
1613 }} \
1614 }} \
1615 return out;"
1616 );
1617
1618 let found = self
1619 .inner
1620 .execute(script, vec![element.inner.to_json()?])
1621 .await?;
1622
1623 Ok(found
1624 .json()
1625 .as_array()
1626 .into_iter()
1627 .flatten()
1628 .filter_map(|line| line.as_str().map(str::to_owned))
1629 .collect())
1630 }
1631
1632 pub async fn wheel_consumed(&self, element: &TestElement, delta: f64) -> Result<bool> {
1637 tracing::trace!(delta, "Turning the wheel and asking who took it");
1638
1639 let script = format!(
1640 "return !arguments[0].dispatchEvent(new WheelEvent('wheel', \
1641 {{ deltaY: {delta}, bubbles: true, cancelable: true }}))"
1642 );
1643
1644 let taken = self
1645 .inner
1646 .execute(script, vec![element.inner.to_json()?])
1647 .await?;
1648
1649 Ok(taken.json().as_bool().unwrap_or(false))
1650 }
1651
1652 pub async fn wheel(&self, element: &TestElement, delta: f64) -> Result<()> {
1660 tracing::trace!(delta, "Turning the wheel over an element");
1661
1662 let script = format!(
1663 "arguments[0].dispatchEvent(new WheelEvent('wheel', \
1664 {{ deltaY: {delta}, bubbles: true, cancelable: true }}))"
1665 );
1666
1667 self.inner
1668 .execute(script, vec![element.inner.to_json()?])
1669 .await?;
1670
1671 Ok(())
1672 }
1673
1674 pub async fn wheel_alt(&self, element: &TestElement, delta: f64, shift: bool) -> Result<()> {
1681 tracing::trace!(delta, shift, "Turning the wheel with alt held");
1682
1683 let script = format!(
1684 "const box = arguments[0].getBoundingClientRect(); \
1685 arguments[0].dispatchEvent(new WheelEvent('wheel', \
1686 {{ deltaY: {delta}, altKey: true, shiftKey: {shift}, \
1687 clientX: box.left + box.width / 2, \
1688 clientY: box.top + box.height / 2, \
1689 bubbles: true, cancelable: true }}))"
1690 );
1691
1692 self.inner
1693 .execute(script, vec![element.inner.to_json()?])
1694 .await?;
1695
1696 Ok(())
1697 }
1698
1699 pub async fn wheel_over(
1710 &self,
1711 element: &TestElement,
1712 across: f64,
1713 down: f64,
1714 ctrl: bool,
1715 ) -> Result<bool> {
1716 tracing::trace!(across, down, ctrl, "Turning the wheel over both axes");
1717
1718 let script = format!(
1719 "const box = arguments[0].getBoundingClientRect(); \
1720 return !arguments[0].dispatchEvent(new WheelEvent('wheel', \
1721 {{ deltaX: {across}, deltaY: {down}, ctrlKey: {ctrl}, \
1722 clientX: box.left + box.width / 2, \
1723 clientY: box.top + box.height / 2, \
1724 bubbles: true, cancelable: true }}))"
1725 );
1726
1727 let taken = self
1728 .inner
1729 .execute(script, vec![element.inner.to_json()?])
1730 .await?;
1731
1732 Ok(taken.json().as_bool().unwrap_or(false))
1733 }
1734
1735 pub async fn wheel_across(&self, element: &TestElement, delta: f64) -> Result<()> {
1738 tracing::trace!(delta, "Turning the wheel sideways over an element");
1739
1740 let script = format!(
1741 "arguments[0].dispatchEvent(new WheelEvent('wheel', \
1742 {{ deltaX: {delta}, bubbles: true, cancelable: true }}))"
1743 );
1744
1745 self.inner
1746 .execute(script, vec![element.inner.to_json()?])
1747 .await?;
1748
1749 Ok(())
1750 }
1751
1752 pub async fn capture_clipboard(&self) -> Result<()> {
1758 self.inner
1759 .execute(
1760 "const inject = document.createElement('script'); \
1761 inject.textContent = `navigator.clipboard.writeText = async text => { \
1762 document.body.setAttribute('data-copied', text); \
1763 };`; \
1764 document.documentElement.appendChild(inject); inject.remove();",
1765 Vec::new(),
1766 )
1767 .await?;
1768 Ok(())
1769 }
1770
1771 pub async fn delay_websocket_sends(&self, millis: u64) -> Result<()> {
1789 self.inner.execute(format!(
1790 "const inject = document.createElement('script'); \
1791 inject.textContent = `(() => {{ \
1792 WebSocket.__e2eOriginalSend = WebSocket.__e2eOriginalSend \
1793 || WebSocket.prototype.send; \
1794 const send = WebSocket.__e2eOriginalSend; \
1795 WebSocket.prototype.send = function(data) {{ \
1796 const copy = data && typeof data.slice === 'function' \
1797 ? data.slice() : data; \
1798 setTimeout(() => {{ if (this.readyState === 1) send.call(this, copy); }}, {millis}); \
1799 }}; \
1800 }})();`; \
1801 document.documentElement.appendChild(inject); inject.remove();"
1802 ), Vec::new()).await?;
1803 Ok(())
1804 }
1805
1806 pub async fn stop_delaying_websocket_sends(&self) -> Result<()> {
1813 self.inner
1814 .execute(
1815 "const inject = document.createElement('script'); \
1816 inject.textContent = `(() => { \
1817 if (WebSocket.__e2eOriginalSend) { \
1818 WebSocket.prototype.send = WebSocket.__e2eOriginalSend; \
1819 delete WebSocket.__e2eOriginalSend; \
1820 } \
1821 })();`; \
1822 document.documentElement.appendChild(inject); inject.remove();"
1823 .to_owned(),
1824 Vec::new(),
1825 )
1826 .await?;
1827 Ok(())
1828 }
1829
1830 pub async fn wait_copied(&self, text: &str) -> Result<()> {
1833 self.wait_until("the full text to be copied", async || {
1834 Ok(self.find_one_by("body").await?.attr("data-copied").await? == text)
1835 })
1836 .await
1837 }
1838
1839 pub async fn watch_for_errors(&self) -> Result<()> {
1850 tracing::trace!("Listening for uncaught errors in the page");
1851
1852 let script = "if (!document.body.hasAttribute('data-watching')) { \
1853 const inject = document.createElement('script'); \
1854 inject.textContent = `(() => { \
1855 const say = what => document.body.setAttribute( \
1856 'data-threw', String(what).slice(0, 6000)); \
1857 const told = (thrown, otherwise) => { \
1858 if (!(thrown instanceof Error)) { return otherwise; } \
1859 const head = String(thrown); \
1860 const stack = thrown.stack || ''; \
1861 return stack.startsWith(head) ? stack : head + '\\\\n' + stack; \
1862 }; \
1863 window.addEventListener('error', e => say(told(e.error, e.message))); \
1864 window.addEventListener('unhandledrejection', \
1865 e => say(told(e.reason, e.reason))); \
1866 const was = console.error; \
1867 console.error = (...a) => { say(a.join(' ')); was(...a); }; \
1868 document.body.setAttribute('data-watching', ''); \
1869 })();`; \
1870 document.documentElement.appendChild(inject); \
1871 inject.remove(); \
1872 } \
1873 return document.body.hasAttribute('data-watching');";
1874
1875 let watching = self.inner.execute(script, Vec::new()).await?;
1876
1877 ensure!(
1878 watching.json().as_bool() == Some(true),
1879 "the script that watches the page for errors did not run"
1880 );
1881 Ok(())
1882 }
1883
1884 pub async fn what_the_page_says(&self) -> Result<String> {
1889 let script = "const b = document.body; \
1890 if (!b) { return 'and the document has no body at all'; } \
1891 const page = b.getAttribute('data-page'); \
1892 const threw = b.getAttribute('data-threw'); \
1893 const mounted = b.children.length; \
1894 let out = page ? `; the page showing is '${page}'` \
1895 : '; nothing has claimed the page yet'; \
1896 out += `, ${mounted} element(s) are mounted under the body`; \
1897 if (threw) { out += `, and the page threw: ${threw}`; } \
1898 out += `, the document is ${document.readyState}`; \
1899 out += `, the bundle's exports are ${typeof window.wasmBindings}`; \
1900 try { new WebAssembly.Module( \
1901 new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0])); \
1902 out += ', an empty module still compiles'; } \
1903 catch (e) { out += ', and an empty module will not compile: ' + e; } \
1904 out += ', history=' + history.length; \
1905 const nav = performance.getEntriesByType('navigation')[0]; \
1906 if (nav) { out += `, the document was answered after \
1907 ${Math.max(0, Math.round(nav.responseEnd))}ms`; } \
1908 for (const got of performance.getEntriesByType('resource')) { \
1909 if (!/\\.(wasm|js)(\\?|$)/.test(got.name)) { continue; } \
1910 out += `, ${got.name.split('/').pop()} was fetched in \
1911 ${Math.round(got.duration)}ms`; } \
1912 return out;";
1913
1914 let told = self.inner.execute(script, Vec::new()).await?;
1915 Ok(told.json().as_str().unwrap_or_default().to_owned())
1916 }
1917
1918 pub async fn error_seen(&self) -> Result<Option<String>> {
1920 let body = self.find_one_by("body").await?;
1921 let seen = body.attr("data-threw").await?;
1922
1923 Ok((!seen.is_empty()).then_some(seen))
1924 }
1925
1926 pub async fn pointer_drag_onto(&self, from: &TestElement, to: &TestElement) -> Result<()> {
1928 from.inner.scroll_into_view().await?;
1929 self.inner
1930 .action_chain()
1931 .move_to_element_center(&from.inner)
1932 .click_and_hold()
1933 .move_by_offset(8, 0)
1934 .release_on_element(&to.inner)
1935 .perform()
1936 .await?;
1937 Ok(())
1938 }
1939
1940 pub async fn native_drag_over(&self, from: &TestElement, to: &TestElement) -> Result<()> {
1947 tracing::trace!("Carrying one element over another with the pointer");
1948
1949 from.inner.scroll_into_view().await?;
1950
1951 self.inner
1952 .action_chain()
1953 .move_to_element_center(&from.inner)
1954 .click_and_hold()
1955 .move_by_offset(4, 0)
1956 .move_by_offset(8, 2)
1957 .move_by_offset(16, 4)
1958 .move_to_element_center(&to.inner)
1959 .move_by_offset(2, 0)
1960 .perform()
1961 .await?;
1962
1963 Ok(())
1964 }
1965
1966 pub async fn release_all_input(&self) -> Result<()> {
1970 self.inner.action_chain().reset_actions().await?;
1971 Ok(())
1972 }
1973
1974 pub async fn native_release(&self) -> Result<()> {
1976 self.inner
1977 .action_chain()
1978 .move_by_offset(1, 0)
1979 .release()
1980 .perform()
1981 .await?;
1982 Ok(())
1983 }
1984
1985 pub async fn watch_mutations(&self, element: &TestElement) -> Result<()> {
1991 self.inner
1992 .execute(
1993 "if (window.__e2eMutations) { \
1994 window.__e2eMutations.observer.disconnect(); \
1995 window.__e2eMutations.outer.disconnect(); \
1996 } \
1997 const watch = { count: 0, kinds: [] }; \
1998 watch.observer = new MutationObserver(records => { \
1999 watch.count += records.length; \
2000 for (const r of records) watch.kinds.push(r.type + ':' + (r.attributeName || '') + ':' + (r.target.className || r.target.nodeName)); \
2001 }); \
2002 watch.observer.observe(arguments[0], \
2003 { subtree: true, childList: true, attributes: true, characterData: true }); \
2004 const node = arguments[0]; \
2005 watch.outer = new MutationObserver(records => { \
2006 for (const r of records) for (const n of r.removedNodes) \
2007 if (n === node || n.contains(node)) { watch.count += 1; watch.kinds.push('removed'); } \
2008 }); \
2009 watch.outer.observe(document.body, { subtree: true, childList: true }); \
2010 if (!window.__e2eClearRect) { \
2011 window.__e2eClearRect = CanvasRenderingContext2D.prototype.clearRect; \
2012 CanvasRenderingContext2D.prototype.clearRect = function (...args) { \
2013 const watch = window.__e2eMutations; \
2014 if (watch && watch.node.contains(this.canvas)) { watch.count += 1; watch.kinds.push('redrawn'); } \
2015 return window.__e2eClearRect.apply(this, args); \
2016 }; \
2017 } \
2018 watch.node = node; \
2019 window.__e2eMutations = watch;",
2020 vec![element.inner.to_json()?],
2021 )
2022 .await?;
2023 Ok(())
2024 }
2025
2026 pub async fn mutations(&self) -> Result<(u64, Vec<String>)> {
2029 let value = self
2030 .inner
2031 .execute(
2032 "const watch = window.__e2eMutations; \
2033 return watch ? [watch.count, watch.kinds] : [0, []];",
2034 Vec::new(),
2035 )
2036 .await?;
2037 Ok(serde_json::from_value(value.json().clone())?)
2038 }
2039
2040 pub async fn external_files(&self, paths: &str) -> Result<TestElement> {
2042 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?;
2043 let input = self.find_one_by("[data-test='external-files']").await?;
2044 input.send_keys(paths).await?;
2045 Ok(input)
2046 }
2047
2048 pub async fn drag_external_files(
2050 &self,
2051 files: &TestElement,
2052 to: &TestElement,
2053 kind: &str,
2054 ) -> Result<bool> {
2055 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?;
2056 Ok(serde_json::from_value(result.json().clone())?)
2057 }
2058
2059 pub async fn drag_onto(&self, from: &TestElement, to: &TestElement) -> Result<()> {
2061 tracing::trace!("Carrying one element onto another");
2062
2063 let script = "const data = new DataTransfer(); \
2064 const fire = (node, kind) => node.dispatchEvent( \
2065 new DragEvent(kind, \
2066 { dataTransfer: data, bubbles: true, cancelable: true })); \
2067 fire(arguments[0], 'dragstart'); \
2068 fire(arguments[1], 'dragover'); \
2069 fire(arguments[1], 'drop'); \
2070 fire(arguments[0], 'dragend');";
2071
2072 self.inner
2073 .execute(script, vec![from.inner.to_json()?, to.inner.to_json()?])
2074 .await?;
2075
2076 Ok(())
2077 }
2078
2079 pub async fn drag_over(&self, from: &TestElement, to: &TestElement) -> Result<()> {
2082 tracing::trace!("Carrying one element over another");
2083
2084 let script = "const data = new DataTransfer(); \
2085 const fire = (node, kind) => node.dispatchEvent( \
2086 new DragEvent(kind, \
2087 { dataTransfer: data, bubbles: true, cancelable: true })); \
2088 fire(arguments[0], 'dragstart'); \
2089 fire(arguments[1], 'dragover');";
2090
2091 self.inner
2092 .execute(script, vec![from.inner.to_json()?, to.inner.to_json()?])
2093 .await?;
2094
2095 Ok(())
2096 }
2097
2098 pub async fn drag_off(&self, left: &TestElement) -> Result<()> {
2103 tracing::trace!("Carrying a drag back off an element");
2104
2105 let script = "const data = new DataTransfer(); \
2106 arguments[0].dispatchEvent( \
2107 new DragEvent('dragleave', \
2108 { dataTransfer: data, bubbles: true, cancelable: true }));";
2109
2110 self.inner
2111 .execute(script, vec![left.inner.to_json()?])
2112 .await?;
2113
2114 Ok(())
2115 }
2116
2117 pub async fn scroll_top(&self, element: &TestElement, top: i32) -> Result<()> {
2119 self.inner
2120 .execute(
2121 "arguments[0].scrollTop = arguments[1];",
2122 vec![element.inner.to_json()?, serde_json::json!(top)],
2123 )
2124 .await?;
2125 Ok(())
2126 }
2127
2128 pub async fn scroll_to_far_end(&self, element: &TestElement) -> Result<()> {
2130 tracing::trace!("Scrolling an element's box to the end of its travel");
2131
2132 let script = "let node = arguments[0].parentElement; \
2133 while (node) { \
2134 const how = getComputedStyle(node).overflowX; \
2135 if ((how === 'auto' || how === 'scroll') \
2136 && node.scrollWidth > node.clientWidth) { \
2137 break; \
2138 } \
2139 node = node.parentElement; \
2140 } \
2141 if (node) { node.scrollLeft = node.scrollWidth; }";
2142
2143 self.inner
2144 .execute(script, vec![element.inner.to_json()?])
2145 .await?;
2146
2147 Ok(())
2148 }
2149
2150 pub async fn computed(
2152 &self,
2153 element: &TestElement,
2154 pseudo: &str,
2155 property: &str,
2156 ) -> Result<String> {
2157 tracing::trace!(pseudo, property, "Asking what a property computed to");
2158
2159 let script = "return getComputedStyle(arguments[0], arguments[1] || null) \
2160 .getPropertyValue(arguments[2]);";
2161
2162 let value = self
2163 .inner
2164 .execute(
2165 script,
2166 vec![
2167 element.inner.to_json()?,
2168 serde_json::json!(pseudo),
2169 serde_json::json!(property),
2170 ],
2171 )
2172 .await?;
2173
2174 Ok(value.json().as_str().unwrap_or_default().trim().to_string())
2175 }
2176
2177 pub async fn reduced_motion(&self) -> Result<bool> {
2184 let value = self
2185 .inner
2186 .execute(
2187 "return matchMedia('(prefers-reduced-motion: reduce)').matches;",
2188 Vec::new(),
2189 )
2190 .await?;
2191 let reduced = value
2192 .json()
2193 .as_bool()
2194 .context("reduced-motion media query")?;
2195 if let Ok(requested) = std::env::var("E2E_MOTION") {
2196 anyhow::ensure!(
2197 reduced == (requested == "reduce"),
2198 "browser did not honor E2E_MOTION={requested}"
2199 );
2200 }
2201 Ok(reduced)
2202 }
2203
2204 pub async fn animation_time(
2207 &self,
2208 element: &TestElement,
2209 name: &str,
2210 millis: f64,
2211 ) -> Result<()> {
2212 self.inner.execute(
2213 "const animation = arguments[0].getAnimations().find(a => a.animationName === arguments[1]); \
2214 if (!animation) throw new Error('Missing animation: ' + arguments[1]); \
2215 animation.pause(); animation.currentTime = arguments[2];",
2216 vec![element.inner.to_json()?, serde_json::json!(name), serde_json::json!(millis)],
2217 ).await?;
2218 Ok(())
2219 }
2220
2221 pub async fn color_alpha(&self, element: &TestElement, property: &str) -> Result<f64> {
2224 let value = self.inner.execute(
2225 "const canvas = document.createElement('canvas'); canvas.width = canvas.height = 1; \
2226 const context = canvas.getContext('2d'); context.fillStyle = 'transparent'; \
2227 context.fillStyle = getComputedStyle(arguments[0]).getPropertyValue(arguments[1]); \
2228 context.fillRect(0, 0, 1, 1); return context.getImageData(0, 0, 1, 1).data[3] / 255;",
2229 vec![element.inner.to_json()?, serde_json::json!(property)],
2230 ).await?;
2231 value.json().as_f64().context("computed color alpha")
2232 }
2233
2234 pub async fn color_shift(&self, element: &TestElement, property: &str) -> Result<f64> {
2240 let [red, green, blue] = self.painted(element, property).await?;
2241 Ok((red + green + blue) / 3.0 - 128.0)
2242 }
2243
2244 pub async fn painted(&self, element: &TestElement, property: &str) -> Result<[f64; 3]> {
2251 let value = self.inner.execute(
2252 "const canvas = document.createElement('canvas'); canvas.width = canvas.height = 1; \
2253 const context = canvas.getContext('2d'); \
2254 context.fillStyle = '#808080'; context.fillRect(0, 0, 1, 1); \
2255 context.fillStyle = 'transparent'; \
2256 context.fillStyle = getComputedStyle(arguments[0]).getPropertyValue(arguments[1]); \
2257 context.fillRect(0, 0, 1, 1); \
2258 const painted = context.getImageData(0, 0, 1, 1).data; \
2259 return [painted[0], painted[1], painted[2]];",
2260 vec![element.inner.to_json()?, serde_json::json!(property)],
2261 ).await?;
2262
2263 let read = value.json();
2264 let read = read.as_array().context("what a computed colour paints")?;
2265
2266 let mut rgb = [0.0; 3];
2267
2268 for (channel, value) in rgb.iter_mut().zip(read) {
2269 *channel = value.as_f64().context("a painted channel")?;
2270 }
2271
2272 Ok(rgb)
2273 }
2274
2275 pub async fn canvas_columns(
2284 &self,
2285 canvas: &TestElement,
2286 columns: usize,
2287 ) -> Result<Vec<(f64, f64, f64)>> {
2288 let script = "const canvas = arguments[0]; \
2289 const columns = Math.max(1, arguments[1]); \
2290 const w = canvas.width, h = canvas.height; \
2291 if (w === 0 || h === 0) return []; \
2292 const ctx = canvas.getContext('2d'); \
2293 const data = ctx.getImageData(0, 0, w, h).data; \
2294 const step = Math.max(1, Math.floor(w / columns)); \
2295 const out = []; \
2296 for (let x = 0; x < w; x += step) { \
2297 let top = -1, bottom = -1; \
2298 for (let y = 0; y < h; y++) { \
2299 if (data[(y * w + x) * 4 + 3] > 0) { \
2300 if (top === -1) top = y; \
2301 bottom = y; \
2302 } \
2303 } \
2304 out.push([x / w, top === -1 ? -1 : top / h, bottom === -1 ? -1 : bottom / h]); \
2305 } \
2306 return out;";
2307
2308 let value = self
2309 .inner
2310 .execute(
2311 script,
2312 vec![canvas.inner.to_json()?, serde_json::json!(columns)],
2313 )
2314 .await?;
2315
2316 let read = value.json();
2317 let read = read.as_array().context("canvas column scan")?;
2318 let mut out = Vec::with_capacity(read.len());
2319
2320 for row in read {
2321 let row = row.as_array().context("a canvas column")?;
2322 let field = |at: usize, name: &str| {
2323 row.get(at)
2324 .and_then(serde_json::Value::as_f64)
2325 .with_context(|| format!("a canvas column's {name}"))
2326 };
2327 out.push((field(0, "x")?, field(1, "top")?, field(2, "bottom")?));
2328 }
2329
2330 Ok(out)
2331 }
2332
2333 pub async fn canvas_size(&self, canvas: &TestElement) -> Result<CanvasSize> {
2338 let script = "const c = arguments[0]; const r = c.getBoundingClientRect(); \
2339 return [c.width, c.height, r.width, r.height, window.devicePixelRatio];";
2340
2341 let value = self
2342 .inner
2343 .execute(script, vec![canvas.inner.to_json()?])
2344 .await?;
2345 let read = value.json();
2346 let read = read.as_array().context("canvas size read")?;
2347 let field = |at: usize, name: &str| {
2348 read.get(at)
2349 .and_then(serde_json::Value::as_f64)
2350 .with_context(|| format!("canvas size's {name}"))
2351 };
2352
2353 Ok(CanvasSize {
2354 device_width: field(0, "device_width")?,
2355 device_height: field(1, "device_height")?,
2356 css_width: field(2, "css_width")?,
2357 css_height: field(3, "css_height")?,
2358 device_pixel_ratio: field(4, "device_pixel_ratio")?,
2359 })
2360 }
2361
2362 pub async fn middle_click(&self, element: &TestElement) -> Result<()> {
2364 tracing::trace!("Middle-clicking an element");
2365
2366 let script = "for (const type of ['mousedown', 'mouseup', 'auxclick']) {\
2367 arguments[0].dispatchEvent(new MouseEvent(type, \
2368 { button: 1, buttons: 4, bubbles: true, cancelable: true })); \
2369 }";
2370
2371 self.inner
2372 .execute(script, vec![element.inner.to_json()?])
2373 .await?;
2374
2375 Ok(())
2376 }
2377
2378 pub async fn middle_drag_by(&self, element: &TestElement, dx: i64) -> Result<()> {
2380 use thirtyfour::common::command::Command;
2381
2382 let actions = serde_json::json!([{
2383 "type": "pointer", "id": "pointer", "parameters": {"pointerType": "mouse"},
2384 "actions": [
2385 {"type": "pointerMove", "duration": 0, "origin": element.inner.to_json()?, "x": 0, "y": 0},
2386 {"type": "pointerDown", "button": 1},
2387 {"type": "pointerMove", "duration": 150, "origin": "pointer", "x": dx, "y": 0},
2388 {"type": "pointerUp", "button": 1}
2389 ]
2390 }]);
2391 self.inner
2392 .cmd(Command::PerformActions(actions.into()))
2393 .await?;
2394 Ok(())
2395 }
2396
2397 pub async fn move_held(&self, dx: i64, dy: i64) -> Result<()> {
2399 tracing::trace!(dx, dy, "Carrying a held drag");
2400
2401 self.inner
2402 .action_chain()
2403 .move_by_offset(dx, dy)
2404 .perform()
2405 .await?;
2406
2407 Ok(())
2408 }
2409
2410 pub async fn drop_held(&self) -> Result<()> {
2412 tracing::trace!("Releasing a held drag");
2413 self.inner.action_chain().release().perform().await?;
2414 Ok(())
2415 }
2416
2417 pub async fn cancel_pointer(&self, element: &TestElement) -> Result<()> {
2420 self.inner
2421 .execute(
2422 "arguments[0].dispatchEvent(new PointerEvent('pointercancel', { bubbles: true }));",
2423 vec![element.inner.to_json()?],
2424 )
2425 .await?;
2426 Ok(())
2427 }
2428
2429 pub async fn drop_held_alt(&self) -> Result<()> {
2432 tracing::trace!("Releasing a held drag and the alt key with it");
2433
2434 self.inner
2435 .action_chain()
2436 .release()
2437 .key_up(thirtyfour::Key::Alt)
2438 .perform()
2439 .await?;
2440
2441 Ok(())
2442 }
2443
2444 pub async fn drawn_inside(&self, selector: &str, x: f64, y: f64) -> Result<bool> {
2459 tracing::trace!(selector, x, y, "Asking what is drawn at a point");
2460
2461 let script = "const [selector, x, y] = arguments; \
2462 const host = document.querySelector(selector); \
2463 const found = document.elementFromPoint(x, y); \
2464 if (!host || !found || !host.contains(found)) return false; \
2465 for (const over of document.body.children) { \
2466 if (over.contains(host) || host.contains(over)) continue; \
2467 const box = over.getBoundingClientRect(); \
2468 if (x >= box.left && x <= box.right && y >= box.top && y <= box.bottom) \
2469 return false; \
2470 } \
2471 return true;";
2472
2473 let value = self
2474 .inner
2475 .execute(
2476 script,
2477 vec![
2478 serde_json::json!(selector),
2479 serde_json::json!(x),
2480 serde_json::json!(y),
2481 ],
2482 )
2483 .await?;
2484
2485 Ok(value.json().as_bool().unwrap_or_default())
2486 }
2487
2488 pub async fn screenshot_png(&self) -> Result<Vec<u8>> {
2493 tracing::trace!("Taking a screenshot");
2494 Ok(self.inner.screenshot_as_png().await?)
2495 }
2496
2497 pub async fn screenshot(&self, path: impl AsRef<std::path::Path>) -> Result<()> {
2499 std::fs::write(path, self.screenshot_png().await?)?;
2500 Ok(())
2501 }
2502
2503 pub async fn snapshot(&self, name: &str) -> Result<()> {
2519 let Some(dir) = std::env::var_os("E2E_SHOTS") else {
2520 return Ok(());
2521 };
2522
2523 let dir = std::path::PathBuf::from(dir);
2524
2525 let dir = match dir.is_absolute() {
2526 true => dir,
2527 false => crate::dist::target_dir()?.join("e2e-shots").join(dir),
2528 };
2529
2530 std::fs::create_dir_all(&dir)?;
2531
2532 let path = dir.join(format!("{name}.png"));
2533 tracing::info!(path = %path.display(), "Writing snapshot");
2534 self.screenshot(&path).await
2535 }
2536
2537 pub async fn press_nth(&self, by: impl IntoBy, index: usize) -> Result<()> {
2540 let by = by.into_by();
2541
2542 tracing::trace!(?by, index, "Pressing element");
2543
2544 let deadline = time::Instant::now() + self.wait_timeout;
2545
2546 loop {
2547 let found = self.find_all(by.clone()).await?;
2548
2549 if let Some(item) = found.get(index)
2550 && item.click().await.is_ok()
2551 {
2552 return Ok(());
2553 }
2554
2555 if time::Instant::now() >= deadline {
2556 bail!(
2557 "Timed out after {:?} pressing {by} at {index}",
2558 self.wait_timeout
2559 );
2560 }
2561
2562 time::sleep(POLL_INTERVAL).await;
2563 }
2564 }
2565
2566 pub async fn context_press_nth(&self, by: impl IntoBy, index: usize) -> Result<()> {
2570 let by = by.into_by();
2571
2572 tracing::trace!(?by, index, "Right-clicking element");
2573
2574 let deadline = time::Instant::now() + self.wait_timeout;
2575
2576 loop {
2577 let found = self.find_all(by.clone()).await?;
2578
2579 if let Some(item) = found.get(index)
2580 && item.context_click().await.is_ok()
2581 {
2582 return Ok(());
2583 }
2584
2585 if time::Instant::now() >= deadline {
2586 bail!(
2587 "Timed out after {:?} right-clicking {by} at {index}",
2588 self.wait_timeout
2589 );
2590 }
2591
2592 time::sleep(POLL_INTERVAL).await;
2593 }
2594 }
2595
2596 pub async fn local_storage(&self, key: &str) -> Result<Option<String>> {
2598 let value = self
2599 .inner
2600 .execute(
2601 "return localStorage.getItem(arguments[0]);",
2602 vec![serde_json::json!(key)],
2603 )
2604 .await?;
2605 Ok(value.json().as_str().map(str::to_owned))
2606 }
2607
2608 pub async fn set_local_storage(&self, key: &str, value: &str) -> Result<()> {
2610 self.inner
2611 .execute(
2612 "localStorage.setItem(arguments[0], arguments[1]);",
2613 vec![serde_json::json!(key), serde_json::json!(value)],
2614 )
2615 .await?;
2616 Ok(())
2617 }
2618
2619 pub async fn block_local_storage(&self) -> Result<()> {
2621 self.inner.execute(
2622 "const script = document.createElement('script'); \
2623 script.textContent = `Object.defineProperty(window, 'localStorage', {configurable: true, get() { throw new DOMException('Storage blocked by test', 'SecurityError'); }});`; \
2624 document.documentElement.appendChild(script); script.remove();",
2625 vec![],
2626 ).await?;
2627 Ok(())
2628 }
2629
2630 pub async fn reload(&self) -> Result<()> {
2632 tracing::trace!("Reloading the page");
2633 self.inner.refresh().await?;
2634
2635 let _ = self.watch_for_errors().await;
2636 Ok(())
2637 }
2638
2639 pub async fn reopen_with(&self, query: &str) -> Result<()> {
2641 tracing::trace!(query, "Reopening the page");
2642
2643 let mut url = self.inner.current_url().await?;
2644 url.set_query(Some(query));
2645 self.inner.goto(url.as_str()).await?;
2646 Ok(())
2647 }
2648
2649 pub async fn in_second_tab(&self, run: impl AsyncFnOnce() -> Result<()>) -> Result<()> {
2654 self.in_second_context(true, run).await
2655 }
2656
2657 pub async fn in_second_window(&self, run: impl AsyncFnOnce() -> Result<()>) -> Result<()> {
2659 self.in_second_context(false, run).await
2660 }
2661
2662 async fn in_second_context(
2663 &self,
2664 tab: bool,
2665 run: impl AsyncFnOnce() -> Result<()>,
2666 ) -> Result<()> {
2667 let original = self.inner.window().await?;
2668 let url = self.inner.current_url().await?;
2669 let opened = if tab {
2670 self.inner.new_tab().await?
2671 } else {
2672 self.inner.new_window().await?
2673 };
2674
2675 let result = async {
2676 self.inner.switch_to_window(opened.clone()).await?;
2677 self.set_window_size(WINDOW.0, WINDOW.1).await?;
2678 self.inner.goto(url.as_str()).await?;
2679 run().await?;
2680 match self.error_seen().await? {
2681 Some(threw) => bail!("the page threw: {threw}"),
2682 None => Ok(()),
2683 }
2684 }
2685 .await;
2686
2687 let cleanup = async {
2688 self.inner.switch_to_window(opened).await?;
2689 self.inner.close_window().await?;
2690 self.inner.switch_to_window(original).await?;
2691 Ok(())
2692 }
2693 .await;
2694
2695 match result {
2696 Ok(()) => cleanup,
2697 Err(error) => Err(with_cleanup(error, cleanup)),
2698 }
2699 }
2700
2701 pub async fn press_key(&self, key: Key) -> Result<()> {
2704 tracing::trace!(?key, "Pressing a key");
2705 self.inner.action_chain().send_keys(key).perform().await?;
2706 Ok(())
2707 }
2708
2709 pub async fn hold_key(&self, key: char) -> Result<()> {
2712 self.inner.action_chain().key_down(key).perform().await?;
2713 Ok(())
2714 }
2715
2716 pub async fn release_key(&self, key: char) -> Result<()> {
2718 self.inner.action_chain().key_up(key).perform().await?;
2719 Ok(())
2720 }
2721
2722 pub async fn find_all_attrs(&self, selector: &str, attr: &str) -> Result<Vec<String>> {
2727 let script = format!(
2728 "return Array.from(document.querySelectorAll({})) \
2729 .map(n => n.getAttribute({}) ?? '')",
2730 serde_json::to_string(selector)?,
2731 serde_json::to_string(attr)?,
2732 );
2733
2734 let read = self.inner.execute(script, Vec::new()).await?;
2735
2736 Ok(read
2737 .json()
2738 .as_array()
2739 .map(|rows| {
2740 rows.iter()
2741 .map(|row| row.as_str().unwrap_or_default().to_owned())
2742 .collect()
2743 })
2744 .unwrap_or_default())
2745 }
2746
2747 pub async fn bands(&self, selector: &str, attr: &str) -> Result<Vec<(String, f64, f64)>> {
2756 let script = format!(
2757 "return Array.from(document.querySelectorAll({})) \
2758 .filter(n => n.getClientRects().length > 0) \
2759 .map(n => [n.getAttribute({}) ?? '', \
2760 n.getBoundingClientRect().top, n.getBoundingClientRect().height])",
2761 serde_json::to_string(selector)?,
2762 serde_json::to_string(attr)?,
2763 );
2764
2765 let read = self.inner.execute(script, Vec::new()).await?;
2766 let read = read.json();
2767
2768 let rows = read.as_array().context("a list of bands")?;
2769 let mut bands = Vec::with_capacity(rows.len());
2770
2771 for row in rows {
2772 let row = row.as_array().context("a band")?;
2773
2774 bands.push((
2775 row.first()
2776 .and_then(|name| name.as_str())
2777 .unwrap_or_default()
2778 .to_owned(),
2779 row.get(1).and_then(|top| top.as_f64()).context("a top")?,
2780 row.get(2)
2781 .and_then(|height| height.as_f64())
2782 .context("a height")?,
2783 ));
2784 }
2785
2786 Ok(bands)
2787 }
2788
2789 pub async fn press_key_on(&self, selector: &str, key: &str) -> Result<()> {
2791 let script = format!(
2792 "const at = document.querySelector({}); \
2793 if (!at) throw new Error('No element for keyboard press'); \
2794 at.focus(); at.dispatchEvent(new KeyboardEvent('keydown', \
2795 {{ key: {}, bubbles: true, cancelable: true }}));",
2796 serde_json::to_string(selector)?,
2797 serde_json::to_string(key)?,
2798 );
2799 self.inner.execute(script, Vec::new()).await?;
2800 Ok(())
2801 }
2802
2803 pub async fn press_key_with_ctrl(&self, selector: &str, key: &str) -> Result<()> {
2811 tracing::trace!(selector, key, "Pressing a key with control held");
2812
2813 let code = match key.chars().collect::<Vec<_>>().as_slice() {
2814 [c] if c.is_ascii_alphabetic() => format!("Key{}", c.to_ascii_uppercase()),
2815 _ => key.to_owned(),
2816 };
2817
2818 let script = format!(
2819 "const at = document.querySelector({}); \
2820 if (at) {{ at.focus(); at.dispatchEvent(new KeyboardEvent('keydown', \
2821 {{ key: {}, code: {}, ctrlKey: true, bubbles: true, cancelable: true }})); }}",
2822 serde_json::to_string(selector)?,
2823 serde_json::to_string(key)?,
2824 serde_json::to_string(&code)?,
2825 );
2826
2827 self.inner.execute(script, Vec::new()).await?;
2828 Ok(())
2829 }
2830
2831 pub async fn press_key_with_shift(&self, selector: &str, key: &str) -> Result<()> {
2834 tracing::trace!(selector, key, "Pressing a key with shift held");
2835
2836 let script = format!(
2837 "const at = document.querySelector({}); \
2838 if (at) {{ at.focus(); at.dispatchEvent(new KeyboardEvent('keydown', \
2839 {{ key: {}, shiftKey: true, bubbles: true, cancelable: true }})); }}",
2840 serde_json::to_string(selector)?,
2841 serde_json::to_string(key)?,
2842 );
2843
2844 self.inner.execute(script, Vec::new()).await?;
2845 Ok(())
2846 }
2847
2848 pub async fn blur(&self) -> Result<()> {
2851 tracing::trace!("Blurring the focused element");
2852
2853 self.inner
2854 .execute(
2855 "document.activeElement && document.activeElement.blur();",
2856 Vec::new(),
2857 )
2858 .await?;
2859
2860 Ok(())
2861 }
2862
2863 pub async fn focused_attr(&self, name: &str) -> Result<Option<String>> {
2869 let found = self
2870 .inner
2871 .execute(
2872 "return document.activeElement \
2873 && document.activeElement.getAttribute(arguments[0])",
2874 vec![serde_json::json!(name)],
2875 )
2876 .await?;
2877
2878 Ok(found.json().as_str().map(str::to_owned))
2879 }
2880
2881 common!();
2882}
2883
2884pub trait IntoBy {
2909 fn into_by(self) -> By;
2911}
2912
2913impl IntoBy for &str {
2914 #[inline]
2915 fn into_by(self) -> By {
2916 By::Css(self)
2917 }
2918}
2919
2920impl IntoBy for &String {
2923 #[inline]
2924 fn into_by(self) -> By {
2925 By::Css(self.as_str())
2926 }
2927}
2928
2929impl IntoBy for By {
2930 #[inline]
2931 fn into_by(self) -> By {
2932 self
2933 }
2934}