1use std::fmt::Write;
168use std::future::Future;
169use std::panic::AssertUnwindSafe;
170use std::path::{Path, PathBuf};
171use std::pin::pin;
172use std::sync::{Arc, Mutex};
173
174use anyhow::{Context, Result, anyhow, bail, ensure};
175use futures_util::FutureExt;
176use thirtyfour::common::types::ElementRect;
177use thirtyfour::prelude::*;
178use tokio::time::{self, Duration};
179
180mod dist;
181mod driver;
182mod fetch;
183pub mod harness;
184#[cfg(test)]
185mod lib_tests;
186mod run_lock;
187mod sandbox;
188mod sessions;
189
190pub use self::dist::{dist, target_dir, workspace_root};
191pub use self::driver::Engine;
192
193use self::driver::{Driver, QUIT_TIMEOUT, STARTUP_TIMEOUT, with_cleanup};
194
195pub mod prelude {
196 pub use anyhow::{Context, Result, anyhow, bail, ensure};
197 pub use thirtyfour::prelude::*;
198
199 pub use crate::{TestDriver, TestElement};
202}
203
204pub trait Fixture: Sized + 'static {
211 type Setup: Default;
215
216 fn config() -> Config {
218 Config::default()
219 }
220
221 fn init_tracing() {
224 _ = tracing_subscriber::fmt()
225 .with_max_level(tracing::Level::INFO)
226 .try_init();
227 }
228
229 fn enter_sandbox(root: &Path) -> Result<()> {
234 _ = root;
235 Ok(())
236 }
237
238 fn check() -> Result<()> {
241 Ok(())
242 }
243
244 fn start(setup: Self::Setup) -> impl Future<Output = Result<Self>>;
246
247 fn url(&self) -> String;
249
250 fn quit(self) -> impl Future<Output = Result<()>>;
252}
253
254#[derive(Debug, Clone)]
256pub struct Config {
257 pub(crate) about: String,
258 pub(crate) frontend: Frontend,
259 pub(crate) lock: String,
260 pub(crate) sessions: String,
261}
262
263impl Default for Config {
264 fn default() -> Self {
265 Self {
266 about: String::from("A browser suite."),
267 frontend: Frontend::Trunk(PathBuf::new()),
268 lock: String::from("yew-e2e.lock"),
269 sessions: String::from("e2e-sessions"),
270 }
271 }
272}
273
274impl Config {
275 pub fn about(mut self, about: impl Into<String>) -> Self {
277 self.about = about.into();
278 self
279 }
280
281 pub fn frontend(mut self, frontend: Frontend) -> Self {
283 self.frontend = frontend;
284 self
285 }
286
287 pub fn lock_name(mut self, name: impl Into<String>) -> Self {
289 self.lock = name.into();
290 self
291 }
292
293 pub fn sessions_dir(mut self, name: impl Into<String>) -> Self {
297 self.sessions = name.into();
298 self
299 }
300}
301
302#[derive(Debug, Clone)]
305pub enum Frontend {
306 None,
308 Trunk(PathBuf),
312}
313
314#[derive(Clone, Default)]
323pub(crate) struct Waiting(Arc<Mutex<Option<String>>>);
324
325impl Waiting {
326 fn on(&self, what: impl std::fmt::Display) {
328 *self.held() = Some(what.to_string());
329 }
330
331 fn clear(&self) {
333 *self.held() = None;
334 }
335
336 pub(crate) fn clause(&self) -> String {
339 match &*self.held() {
340 Some(what) => format!(", last waiting for {what}"),
341 None => String::new(),
342 }
343 }
344
345 fn held(&self) -> std::sync::MutexGuard<'_, Option<String>> {
348 self.0.lock().unwrap_or_else(|held| held.into_inner())
349 }
350}
351
352pub(crate) struct Browser {
354 webdriver: Driver,
355 driver: TestDriver,
356}
357
358impl Browser {
359 pub(crate) async fn open() -> Result<Self> {
361 let engine = crate::harness::engine();
362 let deadline = time::Instant::now() + STARTUP_TIMEOUT;
363 let caps = engine.capabilities(crate::harness::headed())?;
364 let webdriver = Driver::new(engine, deadline).await?;
365 Self::connect(webdriver, caps, deadline).await
366 }
367
368 async fn connect(
369 mut webdriver: Driver,
370 mut caps: Capabilities,
371 deadline: time::Instant,
372 ) -> Result<Self> {
373 let downloads = tempfile::tempdir().context("creating browser download directory")?;
374 let directory = downloads.path().to_string_lossy().into_owned();
375 let key = match webdriver.engine() {
376 Engine::Firefox => "moz:firefoxOptions",
377 Engine::Chrome => "goog:chromeOptions",
378 };
379 if !caps.contains_key(key) {
380 caps.set(key, serde_json::json!({}))?;
381 }
382 match webdriver.engine() {
383 Engine::Firefox => {
384 let options = caps
385 .get_mut("moz:firefoxOptions")
386 .context("Firefox capabilities have no options")?;
387 let prefs = options
388 .as_object_mut()
389 .context("Firefox options")?
390 .entry("prefs")
391 .or_insert_with(|| serde_json::json!({}));
392 let prefs = prefs.as_object_mut().context("Firefox preferences")?;
393 prefs.insert("browser.download.folderList".into(), 2.into());
394 prefs.insert("browser.download.dir".into(), directory.into());
395 prefs.insert("browser.download.useDownloadDir".into(), true.into());
396 prefs.insert(
397 "browser.helperApps.neverAsk.saveToDisk".into(),
398 "audio/wav,application/zip,application/json".into(),
399 );
400 }
401 Engine::Chrome => {
402 let options = caps
403 .get_mut("goog:chromeOptions")
404 .context("Chrome capabilities have no options")?;
405 options["prefs"] = serde_json::json!({
406 "download.default_directory": directory,
407 "download.prompt_for_download": false,
408 });
409 }
410 }
411 tracing::info!(
412 "{} address: {:?}",
413 webdriver.engine().driver(),
414 webdriver.address
415 );
416
417 let url = format!("http://{}", webdriver.address);
418 let connected = webdriver
419 .during(deadline, "startup", async {
420 Ok(WebDriver::new(&url, caps).await?)
421 })
422 .await;
423 let driver = match connected {
424 Ok(driver) => driver,
425 Err(error) => return Err(with_cleanup(error, webdriver.terminate().await)),
426 };
427
428 Ok(Self {
429 webdriver,
430 driver: TestDriver {
431 inner: driver,
432 wait_timeout: WAIT_TIMEOUT,
433 load_timeout: LOAD_TIMEOUT,
434 waiting: Waiting::default(),
435 downloads,
436 },
437 })
438 }
439
440 async fn reset(&mut self, url: &str) -> Result<()> {
446 self.driver.waiting.clear();
447 for file in std::fs::read_dir(self.driver.downloads.path())? {
448 std::fs::remove_file(file?.path())?;
449 }
450 let old = self.driver.inner.window().await?;
451 let fresh = self.driver.inner.new_tab().await?;
452 self.driver.inner.switch_to_window(fresh.clone()).await?;
453 self.driver.inner.switch_to_window(old).await?;
454 self.driver.inner.close_window().await?;
455 self.driver.inner.switch_to_window(fresh).await?;
456 self.driver.set_window_size(WINDOW.0, WINDOW.1).await?;
457 self.driver.inner.goto(url).await?;
458 Ok(())
459 }
460
461 pub(crate) async fn close(mut self) -> Result<Option<anyhow::Error>> {
467 let driver = self.driver.inner.clone();
471 let quit = self
472 .webdriver
473 .during(time::Instant::now() + QUIT_TIMEOUT, "quit", async {
474 Ok(driver.quit().await?)
475 })
476 .await;
477 let reaped = self.webdriver.terminate().await;
478 match (quit, reaped) {
479 (Ok(()), reaped) => reaped.map(|()| None),
480 (Err(error), Ok(())) if error.downcast_ref::<driver::TimedOut>().is_some() => {
481 Ok(Some(error))
482 }
483 (Err(error), reaped) => Err(with_cleanup(error, reaped)),
484 }
485 }
486}
487
488impl Drop for Browser {
489 fn drop(&mut self) {
490 let _ = self.driver.inner.clone().leak();
493 }
494}
495
496#[cfg(test)]
497mod browser_tests {
498 use anyhow::{Context, Result, ensure};
499
500 use super::Browser;
501
502 #[tokio::test]
508 #[ignore = "requires a real WebDriver"]
509 async fn a_reset_discards_the_preceding_document() -> Result<()> {
510 let mut browser = Browser::open().await?;
511
512 let result = async {
513 browser.reset("data:text/html,first").await?;
514 let first = browser.driver.inner.window().await?;
515
516 browser.reset("data:text/html,second").await?;
517 let second = browser.driver.inner.window().await?;
518 let windows = browser.driver.inner.windows().await?;
519 let history = browser
520 .driver
521 .inner
522 .execute("return history.length", Vec::new())
523 .await?
524 .json()
525 .as_u64()
526 .context("browser history length")?;
527
528 ensure!(first != second, "the second reset kept the first tab");
529 ensure!(windows == [second], "reset left tabs behind: {windows:?}");
530 ensure!(history <= 2, "the fresh tab has {history} history entries");
531 Ok(())
532 }
533 .await;
534
535 match (result, browser.close().await) {
536 (Ok(()), Ok(_)) => Ok(()),
537 (Err(error), Ok(_)) | (Ok(()), Err(error)) => Err(error),
538 (Err(error), Err(cleanup)) => Err(super::driver::with_cleanup(error, Err(cleanup))),
539 }
540 }
541}
542
543const WINDOW: (u32, u32) = (1600, 1000);
545
546const SESSION_DEATH: &[&str] = &[
557 "invalid session id",
558 "session id is invalid",
559 "session deleted because of page crash",
560 "session terminated",
561 "the webdriver server's output ended",
562 "error sending request",
563];
564
565pub(crate) fn browser_death(error: &anyhow::Error) -> Option<&'static str> {
568 let mut source: Option<&dyn std::error::Error> = Some(error.as_ref());
569
570 while let Some(error) = source {
571 let said = error.to_string().to_lowercase();
572
573 if let Some(mark) = SESSION_DEATH.iter().find(|mark| said.contains(**mark)) {
574 return Some(mark);
575 }
576
577 source = error.source();
578 }
579
580 None
581}
582
583fn went_away(browser: &Browser, mark: &str) -> anyhow::Error {
589 let name = browser.webdriver.engine().driver();
590
591 anyhow!(
592 "the browser went away ({mark}); {name} last said: {}",
593 driver_said(browser)
594 )
595}
596
597fn driver_said(browser: &Browser) -> String {
600 let said = browser.webdriver.diagnostics();
601
602 said.lines()
603 .rev()
604 .take(3)
605 .collect::<Vec<_>>()
606 .into_iter()
607 .rev()
608 .collect::<Vec<_>>()
609 .join(" | ")
610}
611
612pub(crate) async fn run_one<F: Fixture>(
614 browser: &mut Browser,
615 start: crate::harness::Start<F>,
616 setup: F::Setup,
617 limit: Option<Duration>,
618) -> Result<()> {
619 let mut fixture = F::start(setup).await?;
620
621 let mut errors = String::new();
622
623 let result = match browser.reset(&fixture.url()).await {
624 Ok(()) => drive_one(browser, &mut fixture, start, limit).await,
625 Err(error) => Err(error),
626 };
627
628 let fixture_result = fixture.quit().await;
629
630 if let Err(error) = result.as_ref() {
631 if let Some(mark) = browser_death(error) {
632 let mut error = went_away(browser, mark);
633
634 if let Err(quit) = fixture_result {
635 error = error.context(format!("the fixture also failed to quit: {quit}"));
636 }
637
638 return Err(error);
639 }
640
641 writeln!(errors, "Test error: {error}")?;
642
643 let mut source = error.source();
644
645 while let Some(e) = source.take() {
646 writeln!(errors, " Caused by: {e}")?;
647 source = e.source();
648 }
649 }
650
651 if let Err(error) = fixture_result {
652 writeln!(errors, "Fixture error: {error}")?;
653
654 let mut source = error.source();
655
656 while let Some(e) = source.take() {
657 writeln!(errors, " Caused by: {e}")?;
658 source = e.source();
659 }
660 }
661
662 if let Err(error) = F::check() {
663 writeln!(errors, "Check error: {error}")?;
664 }
665
666 if !errors.is_empty() {
667 return Err(anyhow!("{errors}"));
668 }
669
670 Ok(())
671}
672
673async fn drive_one<F: Fixture>(
683 browser: &mut Browser,
684 fixture: &mut F,
685 start: crate::harness::Start<F>,
686 limit: Option<Duration>,
687) -> Result<()> {
688 let mut timeout = pin!(async move {
689 match limit {
690 Some(limit) => time::sleep(limit).await,
691 None => std::future::pending::<()>().await,
692 }
693 });
694
695 let Browser { webdriver, driver } = browser;
696
697 let waiting = driver.waiting.clone();
698
699 let outcome = {
700 let task = AssertUnwindSafe(start(driver, fixture)).catch_unwind();
701 let mut task = pin!(task);
702
703 loop {
704 tokio::select! {
705 _ = timeout.as_mut() => {
706 break Err(overran(limit, &waiting));
707 }
708 result = task.as_mut() => {
709 break Ok(result);
710 }
711 result = webdriver.io() => {
712 if !result? {
713 break Err("the WebDriver server's output ended".to_string());
714 }
715 }
716 }
717 }
718 };
719
720 match outcome {
721 Ok(Ok(Ok(()))) => match driver.error_seen().await? {
722 Some(threw) => bail!("the page threw: {threw}"),
723 None => Ok(()),
724 },
725 Ok(Ok(result)) => result,
726 Ok(Err(panicked)) => bail!("the test panicked: {}", panic_message(&panicked)),
727 Err(error) => bail!(error),
728 }
729}
730
731pub(crate) fn overran(limit: Option<Duration>, waiting: &Waiting) -> String {
734 let seconds = limit.map_or(0, |limit| limit.as_secs());
735
736 format!(
737 "the test was still running after {seconds}s, which is --timeout{}",
738 waiting.clause()
739 )
740}
741
742fn panic_message(payload: &Box<dyn std::any::Any + Send>) -> &str {
744 if let Some(message) = payload.downcast_ref::<&'static str>() {
745 return message;
746 }
747
748 if let Some(message) = payload.downcast_ref::<String>() {
749 return message;
750 }
751
752 "a payload that is neither a string nor a &str"
753}
754
755pub const POLL_INTERVAL: Duration = Duration::from_millis(25);
757
758const WAIT_TIMEOUT: Duration = Duration::from_secs(5);
760
761const LOAD_TIMEOUT: Duration = Duration::from_secs(15);
766
767macro_rules! common {
768 () => {
769 pub async fn wait_until(
771 &self,
772 what: impl std::fmt::Display,
773 condition: impl AsyncFnMut() -> Result<bool>,
774 ) -> Result<()> {
775 self.wait_for(self.wait_timeout, what, condition).await
776 }
777
778 pub async fn wait_until_within(
783 &self,
784 timeout: Duration,
785 what: impl std::fmt::Display,
786 condition: impl AsyncFnMut() -> Result<bool>,
787 ) -> Result<()> {
788 self.wait_for(timeout, what, condition).await
789 }
790
791 async fn wait_for(
793 &self,
794 timeout: Duration,
795 what: impl std::fmt::Display,
796 mut condition: impl AsyncFnMut() -> Result<bool>,
797 ) -> Result<()> {
798 let deadline = time::Instant::now() + timeout;
799
800 self.waiting.on(&what);
801
802 loop {
803 if condition().await? {
804 return Ok(());
805 }
806
807 if time::Instant::now() >= deadline {
808 bail!("Timed out after {timeout:?} waiting for {what}");
809 }
810
811 time::sleep(POLL_INTERVAL).await;
812 }
813 }
814
815 pub async fn wait_texts<const N: usize>(
817 &self,
818 by: impl IntoBy,
819 expected: [&str; N],
820 ) -> Result<()> {
821 let by = by.into_by();
822
823 tracing::trace!(?by, ?expected, "Waiting for texts");
824
825 let seen = std::cell::RefCell::new(Vec::new());
826
827 let result = self
828 .wait_until(format_args!("{by} to read {expected:?}"), async || {
829 let texts = self.find_all_texts(by.clone()).await?;
830 let matched = texts == expected;
831 *seen.borrow_mut() = texts;
832 Ok(matched)
833 })
834 .await;
835
836 match result {
837 Ok(()) => Ok(()),
838 Err(error) => {
839 let seen = seen.into_inner();
840 Err(error.context(format!("last read {seen:?}")))
841 }
842 }
843 }
844
845 pub async fn wait_count(&self, by: impl IntoBy, expected: usize) -> Result<()> {
860 let by = by.into_by();
861
862 tracing::trace!(?by, expected, "Waiting for count");
863
864 self.wait_until(format_args!("{by} to match {expected} nodes"), async || {
865 Ok(self.find_all(by.clone()).await?.len() == expected)
866 })
867 .await
868 }
869
870 #[inline]
874 pub async fn count(&self, by: impl IntoBy) -> Result<usize> {
875 Ok(self.find_all(by.into_by()).await?.len())
876 }
877
878 pub async fn wait_count_from(
892 &self,
893 by: impl IntoBy,
894 before: usize,
895 expected: usize,
896 ) -> Result<()> {
897 let by = by.into_by();
898
899 ensure!(
900 before != expected,
901 "Waiting for {by} to match {expected} nodes verifies nothing: \
902 {expected} is also the count read before the action, so the \
903 first poll agrees whether or not the action has landed. Assert \
904 the count this action is supposed to produce, or if it really \
905 is meant to leave the count alone, assert what it did change.",
906 );
907
908 tracing::trace!(?by, before, expected, "Waiting for count to change");
909
910 self.wait_until(
911 format_args!("{by} to go from {before} to {expected} nodes"),
912 async || Ok(self.find_all(by.clone()).await?.len() == expected),
913 )
914 .await
915 }
916
917 #[inline]
919 pub async fn find_all_texts(&self, by: impl IntoBy) -> Result<Vec<String>> {
920 let mut texts = Vec::new();
921
922 for item in self.find_all(by.into_by()).await? {
923 texts.push(item.text().await?);
924 }
925
926 Ok(texts)
927 }
928
929 #[inline]
931 pub async fn find_one_by_xpath(&self, xpath: &str) -> Result<TestElement> {
932 self.find_one_by(By::XPath(xpath)).await
933 }
934
935 pub async fn find_one_by(&self, by: impl IntoBy) -> Result<TestElement> {
942 let by = by.into_by();
943
944 tracing::trace!(?by, "Finding one element");
945
946 let deadline = time::Instant::now() + self.wait_timeout;
947
948 loop {
949 let items = self.find_all(by.clone()).await?;
950
951 ensure!(
952 items.len() <= 1,
953 "Expected exactly one by {by}, but got {}: where several is \
954 what the page is, ask for one of them by index with \
955 find_nth, or for the first of them with find_first",
956 items.len()
957 );
958
959 if let Some(item) = items.into_iter().next() {
960 return Ok(item);
961 }
962
963 if time::Instant::now() >= deadline {
964 bail!(
965 "Timed out after {:?} waiting for {by}",
966 self.wait_timeout
967 );
968 }
969
970 time::sleep(POLL_INTERVAL).await;
971 }
972 }
973
974 pub async fn find_nth(&self, by: impl IntoBy, index: usize) -> Result<TestElement> {
989 let by = by.into_by();
990
991 tracing::trace!(?by, index, "Finding one of several elements");
992
993 let deadline = time::Instant::now() + self.wait_timeout;
994
995 loop {
996 if let Some(item) = self.find_all(by.clone()).await?.into_iter().nth(index) {
997 return Ok(item);
998 }
999
1000 if time::Instant::now() >= deadline {
1001 bail!(
1002 "Timed out after {:?} waiting for {by} at {index}",
1003 self.wait_timeout
1004 );
1005 }
1006
1007 time::sleep(POLL_INTERVAL).await;
1008 }
1009 }
1010
1011 #[inline]
1014 pub async fn find_first(&self, by: impl IntoBy) -> Result<TestElement> {
1015 self.find_nth(by, 0).await
1016 }
1017
1018 pub async fn find_all(&self, by: impl Into<By>) -> Result<Vec<TestElement>> {
1020 self.find_all_within(self.wait_timeout, by).await
1021 }
1022
1023 pub async fn find_all_within(
1027 &self,
1028 timeout: Duration,
1029 by: impl Into<By>,
1030 ) -> Result<Vec<TestElement>> {
1031 let by = by.into();
1032 tracing::trace!(?by, "Finding all elements");
1033
1034 let task = self.inner.find_all(by.clone());
1035 let sleep = time::sleep(timeout);
1036
1037 tokio::select! {
1038 _ = sleep => {
1039 Err(anyhow!("find_elements({by:?}) timed out after {timeout:?}"))
1040 }
1041 result = task => {
1042 Ok(result?.into_iter().map(|inner| TestElement { inner, wait_timeout: self.wait_timeout, waiting: self.waiting.clone() }).collect::<Vec<_>>())
1043 }
1044 }
1045 }
1046 }
1047}
1048
1049#[derive(Debug, Clone, Copy)]
1051pub struct CanvasSize {
1052 pub device_width: f64,
1054 pub device_height: f64,
1056 pub css_width: f64,
1058 pub css_height: f64,
1060 pub device_pixel_ratio: f64,
1062}
1063
1064pub struct TestElement {
1066 inner: WebElement,
1067 wait_timeout: Duration,
1068 waiting: Waiting,
1069}
1070
1071impl TestElement {
1072 pub fn element(&self) -> &WebElement {
1075 &self.inner
1076 }
1077
1078 pub async fn click(&self) -> Result<()> {
1080 tracing::trace!("Clicking element");
1081 self.inner.click().await?;
1082 Ok(())
1083 }
1084
1085 pub async fn extend_click(&self) -> Result<()> {
1088 tracing::trace!("Extend-clicking element");
1089
1090 self.inner.scroll_into_view().await?;
1091
1092 self.inner
1093 .handle()
1094 .action_chain()
1095 .key_down(thirtyfour::Key::Control)
1096 .click_element(&self.inner)
1097 .key_up(thirtyfour::Key::Control)
1098 .perform()
1099 .await?;
1100
1101 Ok(())
1102 }
1103
1104 pub async fn shift_click(&self) -> Result<()> {
1107 tracing::trace!("Shift-clicking element");
1108
1109 self.inner.scroll_into_view().await?;
1110
1111 self.inner
1112 .handle()
1113 .action_chain()
1114 .key_down(thirtyfour::Key::Shift)
1115 .click_element(&self.inner)
1116 .key_up(thirtyfour::Key::Shift)
1117 .perform()
1118 .await?;
1119
1120 Ok(())
1121 }
1122
1123 pub async fn hover(&self) -> Result<()> {
1125 tracing::trace!("Hovering element");
1126
1127 self.inner.scroll_into_view().await?;
1128
1129 self.inner
1130 .handle()
1131 .action_chain()
1132 .move_to_element_center(&self.inner)
1133 .perform()
1134 .await?;
1135
1136 Ok(())
1137 }
1138
1139 pub async fn double_click(&self) -> Result<()> {
1141 tracing::trace!("Double-clicking element");
1142
1143 self.inner.scroll_into_view().await?;
1144
1145 self.inner
1146 .handle()
1147 .action_chain()
1148 .double_click_element(&self.inner)
1149 .perform()
1150 .await?;
1151
1152 Ok(())
1153 }
1154
1155 pub async fn double_click_by(&self, dx: i64, dy: i64) -> Result<()> {
1159 tracing::trace!(dx, dy, "Double-clicking element off centre");
1160
1161 self.inner.scroll_into_view().await?;
1162
1163 self.inner
1164 .handle()
1165 .action_chain()
1166 .move_to_element_center(&self.inner)
1167 .move_by_offset(dx, dy)
1168 .double_click()
1169 .perform()
1170 .await?;
1171
1172 Ok(())
1173 }
1174
1175 pub async fn click_by(&self, dx: i64, dy: i64) -> Result<()> {
1179 tracing::trace!(dx, dy, "Clicking element off centre");
1180
1181 self.inner.scroll_into_view().await?;
1182
1183 self.inner
1184 .handle()
1185 .action_chain()
1186 .move_to_element_center(&self.inner)
1187 .move_by_offset(dx, dy)
1188 .click()
1189 .perform()
1190 .await?;
1191
1192 Ok(())
1193 }
1194
1195 pub async fn context_click(&self) -> Result<()> {
1197 tracing::trace!("Context-clicking element");
1198
1199 self.inner.scroll_into_view().await?;
1200
1201 self.inner
1202 .handle()
1203 .action_chain()
1204 .context_click_element(&self.inner)
1205 .perform()
1206 .await?;
1207
1208 Ok(())
1209 }
1210
1211 pub async fn drag_by(&self, dx: i64, dy: i64) -> Result<()> {
1214 tracing::trace!(dx, dy, "Dragging element");
1215
1216 self.inner.scroll_into_view().await?;
1217
1218 self.inner
1219 .handle()
1220 .action_chain()
1221 .move_to_element_center(&self.inner)
1222 .click_and_hold()
1223 .move_by_offset(dx.signum() * 8, dy.signum() * 8)
1224 .move_by_offset(dx, dy)
1225 .perform()
1226 .await?;
1227
1228 Ok(())
1229 }
1230
1231 pub async fn drag_from_by(&self, at_x: i64, at_y: i64, dx: i64, dy: i64) -> Result<()> {
1237 tracing::trace!(at_x, at_y, dx, dy, "Dragging from a point in an element");
1238
1239 self.inner.scroll_into_view().await?;
1240
1241 self.inner
1242 .handle()
1243 .action_chain()
1244 .move_to_element_center(&self.inner)
1245 .move_by_offset(at_x, at_y)
1246 .click_and_hold()
1247 .move_by_offset(dx.signum() * 8, dy.signum() * 8)
1248 .move_by_offset(dx, dy)
1249 .perform()
1250 .await?;
1251
1252 Ok(())
1253 }
1254
1255 pub async fn alt_drag_by(&self, dx: i64, dy: i64) -> Result<()> {
1257 tracing::trace!(dx, dy, "Dragging element with alt held");
1258
1259 self.inner.scroll_into_view().await?;
1260
1261 self.inner
1262 .handle()
1263 .action_chain()
1264 .key_down(thirtyfour::Key::Alt)
1265 .move_to_element_center(&self.inner)
1266 .click_and_hold()
1267 .move_by_offset(dx.signum() * 8, dy.signum() * 8)
1268 .move_by_offset(dx, dy)
1269 .perform()
1270 .await?;
1271
1272 Ok(())
1273 }
1274
1275 pub async fn text(&self) -> Result<String> {
1277 tracing::trace!("Getting element text");
1278 Ok(self.inner.text().await?)
1279 }
1280
1281 pub async fn prop(&self, name: &str) -> Result<String> {
1283 tracing::trace!(name, "Getting element property");
1284 Ok(self.inner.prop(name).await?.unwrap_or_default())
1285 }
1286
1287 pub async fn attr(&self, name: &str) -> Result<String> {
1290 tracing::trace!(name, "Getting element attribute");
1291 Ok(self.inner.attr(name).await?.unwrap_or_default())
1292 }
1293
1294 pub async fn scroll_into_view(&self) -> Result<()> {
1296 tracing::trace!("Scrolling element into view");
1297 self.inner.scroll_into_view().await?;
1298 Ok(())
1299 }
1300
1301 pub async fn focus(&self) -> Result<()> {
1303 tracing::trace!("Focusing element");
1304 self.inner.focus().await?;
1305 Ok(())
1306 }
1307
1308 pub async fn visible(&self) -> Result<bool> {
1309 Ok(self.inner.is_displayed().await?)
1310 }
1311
1312 pub async fn rect(&self) -> Result<ElementRect> {
1314 tracing::trace!("Measuring element");
1315 Ok(self.inner.rect().await?)
1316 }
1317
1318 pub async fn css(&self, name: &str) -> Result<String> {
1320 tracing::trace!(name, "Getting element style");
1321 Ok(self.inner.css_value(name).await?)
1322 }
1323
1324 pub async fn value(&self) -> Result<String> {
1326 tracing::trace!("Getting element value");
1327 Ok(self.inner.prop("value").await?.unwrap_or_default())
1328 }
1329
1330 pub async fn clear(&self) -> Result<()> {
1332 tracing::trace!("Clearing element text");
1333 self.inner.clear().await?;
1334 Ok(())
1335 }
1336
1337 pub async fn send_keys(&self, keys: &str) -> Result<()> {
1339 tracing::trace!(?keys, "Sending keys to element");
1340 self.inner.send_keys(keys).await?;
1341 Ok(())
1342 }
1343
1344 pub async fn pressed(&self) -> Result<bool> {
1346 Ok(self.prop("ariaPressed").await? == "true")
1347 }
1348
1349 pub async fn enabled(&self) -> Result<bool> {
1351 Ok(self.inner.is_enabled().await?)
1352 }
1353
1354 pub async fn disabled(&self) -> Result<bool> {
1359 Ok(self.prop("ariaDisabled").await? == "true")
1360 }
1361
1362 common!();
1363}
1364
1365pub struct TestDriver {
1367 inner: WebDriver,
1368 downloads: tempfile::TempDir,
1369 wait_timeout: Duration,
1370 load_timeout: Duration,
1371 waiting: Waiting,
1372}
1373
1374impl TestDriver {
1375 pub async fn local_clock(&self, epoch_ms: u64) -> Result<[u32; 4]> {
1379 let read = self
1380 .inner
1381 .execute(
1382 "const d = new Date(arguments[0]); \
1383 return [d.getMonth() + 1, d.getDate(), d.getHours(), d.getMinutes()]",
1384 vec![serde_json::json!(epoch_ms)],
1385 )
1386 .await?;
1387 let parts = read.json().as_array().context("clock array")?;
1388 let mut clock = [0; 4];
1389
1390 for (slot, part) in clock.iter_mut().zip(parts) {
1391 *slot = u32::try_from(part.as_u64().context("clock part")?)?;
1392 }
1393
1394 Ok(clock)
1395 }
1396
1397 pub async fn rendered_texts(&self, selector: &str) -> Result<Vec<String>> {
1404 let read = self
1405 .inner
1406 .execute(
1407 "return Array.from(document.querySelectorAll(arguments[0])) \
1408 .map(n => n.innerText)",
1409 vec![serde_json::json!(selector)],
1410 )
1411 .await?;
1412 let rows = read.json().as_array().context("rendered text array")?;
1413
1414 rows.iter()
1415 .map(|row| row.as_str().context("rendered text").map(str::to_owned))
1416 .collect()
1417 }
1418
1419 pub fn downloads(&self) -> &std::path::Path {
1421 self.downloads.path()
1422 }
1423
1424 pub(crate) fn waiting(&self) -> Waiting {
1427 self.waiting.clone()
1428 }
1429
1430 pub fn webdriver(&self) -> &WebDriver {
1433 &self.inner
1434 }
1435
1436 pub fn wait_timeout(&self) -> Duration {
1439 self.wait_timeout
1440 }
1441
1442 pub fn load_timeout(&self) -> Duration {
1446 self.load_timeout
1447 }
1448
1449 pub async fn set_window_size(&self, width: u32, height: u32) -> Result<()> {
1451 tracing::trace!(width, height, "Sizing the window");
1452 self.inner.set_window_rect(0, 0, width, height).await?;
1453 Ok(())
1454 }
1455
1456 pub async fn set_style(
1460 &self,
1461 element: &TestElement,
1462 property: &str,
1463 value: &str,
1464 ) -> Result<()> {
1465 tracing::trace!(property, value, "Setting an inline style property");
1466
1467 let script = format!("arguments[0].style.setProperty({property:?}, {value:?});");
1468
1469 self.inner
1470 .execute(script, vec![element.inner.to_json()?])
1471 .await?;
1472
1473 Ok(())
1474 }
1475
1476 pub async fn set_class(&self, element: &TestElement, class: &str, on: bool) -> Result<()> {
1480 tracing::trace!(class, on, "Forcing a class");
1481
1482 let script = format!("arguments[0].classList.toggle({class:?}, {on});");
1483
1484 self.inner
1485 .execute(script, vec![element.inner.to_json()?])
1486 .await?;
1487
1488 Ok(())
1489 }
1490
1491 pub async fn set_value(&self, element: &TestElement, value: &str, event: &str) -> Result<()> {
1495 tracing::trace!(value, event, "Setting a field's value");
1496
1497 self.inner
1498 .execute(
1499 "arguments[0].value = arguments[1]; \
1500 arguments[0].dispatchEvent(new Event(arguments[2], {bubbles: true}));",
1501 vec![
1502 element.inner.to_json()?,
1503 serde_json::json!(value),
1504 serde_json::json!(event),
1505 ],
1506 )
1507 .await?;
1508
1509 Ok(())
1510 }
1511
1512 pub async fn set_text(&self, element: &TestElement, text: &str) -> Result<()> {
1516 tracing::trace!(text, "Replacing an element's text");
1517
1518 let script = format!(
1519 "const node = arguments[0].firstChild; \
1520 if (!node || node.nodeType !== Node.TEXT_NODE) throw new Error('no text node'); \
1521 node.data = {text:?};"
1522 );
1523
1524 self.inner
1525 .execute(script, vec![element.inner.to_json()?])
1526 .await?;
1527
1528 Ok(())
1529 }
1530
1531 pub async fn overflowing(&self, element: &TestElement) -> Result<Vec<String>> {
1537 tracing::trace!("Finding what overflows inside an element");
1538
1539 let script = "const out = []; \
1540 for (const el of [arguments[0], ...arguments[0].querySelectorAll('*')]) { \
1541 if (el.clientHeight <= 1 || el.clientWidth <= 1) continue; \
1542 const cs = getComputedStyle(el); \
1543 const y = el.scrollHeight - el.clientHeight; \
1544 const x = el.scrollWidth - el.clientWidth; \
1545 const shows = v => v === 'auto' || v === 'scroll' || v === 'hidden' || v === 'clip'; \
1546 if ((y > 1 && shows(cs.overflowY)) || (x > 1 && shows(cs.overflowX))) { \
1547 const test = el.getAttribute('data-test'); \
1548 out.push(el.localName + (el.className ? '.' + String(el.className).trim().split(/\\s+/).join('.') : '') \
1549 + (test ? `[data-test=${test}]` : '') \
1550 + ` ${cs.overflowX}/${cs.overflowY} over by ${x}x${y}`); \
1551 } \
1552 } \
1553 return out;";
1554
1555 let found = self
1556 .inner
1557 .execute(script, vec![element.inner.to_json()?])
1558 .await?;
1559
1560 Ok(found
1561 .json()
1562 .as_array()
1563 .into_iter()
1564 .flatten()
1565 .filter_map(|line| line.as_str().map(str::to_owned))
1566 .collect())
1567 }
1568
1569 pub async fn small_text(
1574 &self,
1575 element: &TestElement,
1576 floor: f64,
1577 marks: &str,
1578 ) -> Result<Vec<String>> {
1579 tracing::trace!(floor, marks, "Finding text set below a size");
1580
1581 let script = format!(
1582 "const out = []; \
1583 for (const el of [arguments[0], ...arguments[0].querySelectorAll('*')]) {{ \
1584 if (el.closest({marks:?})) continue; \
1585 const words = Array.from(el.childNodes) \
1586 .filter(n => n.nodeType === Node.TEXT_NODE) \
1587 .map(n => n.textContent.trim()).join(' ').trim(); \
1588 if (!words) continue; \
1589 const rect = el.getBoundingClientRect(); \
1590 if (rect.width <= 1 || rect.height <= 1) continue; \
1591 const cs = getComputedStyle(el); \
1592 if (cs.visibility !== 'visible') continue; \
1593 const size = parseFloat(cs.fontSize); \
1594 if (size < {floor}) {{ \
1595 const test = el.getAttribute('data-test'); \
1596 out.push(el.localName + (el.className ? '.' + String(el.className).trim().split(/\\s+/).join('.') : '') \
1597 + (test ? `[data-test=${{test}}]` : '') \
1598 + ` at ${{cs.fontSize}}: ${{JSON.stringify(words.slice(0, 32))}}`); \
1599 }} \
1600 }} \
1601 return out;"
1602 );
1603
1604 let found = self
1605 .inner
1606 .execute(script, vec![element.inner.to_json()?])
1607 .await?;
1608
1609 Ok(found
1610 .json()
1611 .as_array()
1612 .into_iter()
1613 .flatten()
1614 .filter_map(|line| line.as_str().map(str::to_owned))
1615 .collect())
1616 }
1617
1618 pub async fn wheel_consumed(&self, element: &TestElement, delta: f64) -> Result<bool> {
1621 tracing::trace!(delta, "Turning the wheel and asking who took it");
1622
1623 let script = format!(
1624 "return !arguments[0].dispatchEvent(new WheelEvent('wheel', \
1625 {{ deltaY: {delta}, bubbles: true, cancelable: true }}))"
1626 );
1627
1628 let taken = self
1629 .inner
1630 .execute(script, vec![element.inner.to_json()?])
1631 .await?;
1632
1633 Ok(taken.json().as_bool().unwrap_or(false))
1634 }
1635
1636 pub async fn wheel(&self, element: &TestElement, delta: f64) -> Result<()> {
1637 tracing::trace!(delta, "Turning the wheel over an element");
1638
1639 let script = format!(
1640 "arguments[0].dispatchEvent(new WheelEvent('wheel', \
1641 {{ deltaY: {delta}, bubbles: true, cancelable: true }}))"
1642 );
1643
1644 self.inner
1645 .execute(script, vec![element.inner.to_json()?])
1646 .await?;
1647
1648 Ok(())
1649 }
1650
1651 pub async fn wheel_alt(&self, element: &TestElement, delta: f64, shift: bool) -> Result<()> {
1658 tracing::trace!(delta, shift, "Turning the wheel with alt held");
1659
1660 let script = format!(
1661 "const box = arguments[0].getBoundingClientRect(); \
1662 arguments[0].dispatchEvent(new WheelEvent('wheel', \
1663 {{ deltaY: {delta}, altKey: true, shiftKey: {shift}, \
1664 clientX: box.left + box.width / 2, \
1665 clientY: box.top + box.height / 2, \
1666 bubbles: true, cancelable: true }}))"
1667 );
1668
1669 self.inner
1670 .execute(script, vec![element.inner.to_json()?])
1671 .await?;
1672
1673 Ok(())
1674 }
1675
1676 pub async fn wheel_over(
1687 &self,
1688 element: &TestElement,
1689 across: f64,
1690 down: f64,
1691 ctrl: bool,
1692 ) -> Result<bool> {
1693 tracing::trace!(across, down, ctrl, "Turning the wheel over both axes");
1694
1695 let script = format!(
1696 "const box = arguments[0].getBoundingClientRect(); \
1697 return !arguments[0].dispatchEvent(new WheelEvent('wheel', \
1698 {{ deltaX: {across}, deltaY: {down}, ctrlKey: {ctrl}, \
1699 clientX: box.left + box.width / 2, \
1700 clientY: box.top + box.height / 2, \
1701 bubbles: true, cancelable: true }}))"
1702 );
1703
1704 let taken = self
1705 .inner
1706 .execute(script, vec![element.inner.to_json()?])
1707 .await?;
1708
1709 Ok(taken.json().as_bool().unwrap_or(false))
1710 }
1711
1712 pub async fn wheel_across(&self, element: &TestElement, delta: f64) -> Result<()> {
1715 tracing::trace!(delta, "Turning the wheel sideways over an element");
1716
1717 let script = format!(
1718 "arguments[0].dispatchEvent(new WheelEvent('wheel', \
1719 {{ deltaX: {delta}, bubbles: true, cancelable: true }}))"
1720 );
1721
1722 self.inner
1723 .execute(script, vec![element.inner.to_json()?])
1724 .await?;
1725
1726 Ok(())
1727 }
1728
1729 pub async fn capture_clipboard(&self) -> Result<()> {
1731 self.inner
1732 .execute(
1733 "const inject = document.createElement('script'); \
1734 inject.textContent = `navigator.clipboard.writeText = async text => { \
1735 document.body.setAttribute('data-copied', text); \
1736 };`; \
1737 document.documentElement.appendChild(inject); inject.remove();",
1738 Vec::new(),
1739 )
1740 .await?;
1741 Ok(())
1742 }
1743
1744 pub async fn delay_websocket_sends(&self, millis: u64) -> Result<()> {
1760 self.inner.execute(format!(
1761 "const inject = document.createElement('script'); \
1762 inject.textContent = `(() => {{ \
1763 WebSocket.__e2eOriginalSend = WebSocket.__e2eOriginalSend \
1764 || WebSocket.prototype.send; \
1765 const send = WebSocket.__e2eOriginalSend; \
1766 WebSocket.prototype.send = function(data) {{ \
1767 const copy = data && typeof data.slice === 'function' \
1768 ? data.slice() : data; \
1769 setTimeout(() => {{ if (this.readyState === 1) send.call(this, copy); }}, {millis}); \
1770 }}; \
1771 }})();`; \
1772 document.documentElement.appendChild(inject); inject.remove();"
1773 ), Vec::new()).await?;
1774 Ok(())
1775 }
1776
1777 pub async fn stop_delaying_websocket_sends(&self) -> Result<()> {
1784 self.inner
1785 .execute(
1786 "const inject = document.createElement('script'); \
1787 inject.textContent = `(() => { \
1788 if (WebSocket.__e2eOriginalSend) { \
1789 WebSocket.prototype.send = WebSocket.__e2eOriginalSend; \
1790 delete WebSocket.__e2eOriginalSend; \
1791 } \
1792 })();`; \
1793 document.documentElement.appendChild(inject); inject.remove();"
1794 .to_owned(),
1795 Vec::new(),
1796 )
1797 .await?;
1798 Ok(())
1799 }
1800
1801 pub async fn wait_copied(&self, text: &str) -> Result<()> {
1803 self.wait_until("the full text to be copied", async || {
1804 Ok(self.find_one_by("body").await?.attr("data-copied").await? == text)
1805 })
1806 .await
1807 }
1808
1809 pub async fn watch_for_errors(&self) -> Result<()> {
1811 tracing::trace!("Listening for uncaught errors in the page");
1812
1813 let script = "if (!document.body.hasAttribute('data-watching')) { \
1814 document.body.setAttribute('data-watching', ''); \
1815 const inject = document.createElement('script'); \
1816 inject.textContent = `\
1817 const say = what => document.body.setAttribute( \
1818 'data-threw', String(what).slice(0, 6000)); \
1819 window.addEventListener('error', e => say( \
1820 (e.error && e.error.stack) || e.message)); \
1821 window.addEventListener('unhandledrejection', e => say(e.reason)); \
1822 const was = console.error; \
1823 console.error = (...a) => { say(a.join(' ')); was(...a); }; \
1824 `; \
1825 document.documentElement.appendChild(inject); \
1826 inject.remove(); \
1827 }";
1828
1829 self.inner.execute(script, Vec::new()).await?;
1830 Ok(())
1831 }
1832
1833 pub async fn what_the_page_says(&self) -> Result<String> {
1838 let script = "const b = document.body; \
1839 if (!b) { return 'and the document has no body at all'; } \
1840 const page = b.getAttribute('data-page'); \
1841 const threw = b.getAttribute('data-threw'); \
1842 const mounted = b.children.length; \
1843 let out = page ? `; the page showing is '${page}'` \
1844 : '; nothing has claimed the page yet'; \
1845 out += `, ${mounted} element(s) are mounted under the body`; \
1846 if (threw) { out += `, and the page threw: ${threw}`; } \
1847 out += `, the document is ${document.readyState}`; \
1848 out += `, the bundle's exports are ${typeof window.wasmBindings}`; \
1849 try { new WebAssembly.Module( \
1850 new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0])); \
1851 out += ', an empty module still compiles'; } \
1852 catch (e) { out += ', and an empty module will not compile: ' + e; } \
1853 out += ', history=' + history.length; \
1854 const nav = performance.getEntriesByType('navigation')[0]; \
1855 if (nav) { out += `, the document was answered after \
1856 ${Math.max(0, Math.round(nav.responseEnd))}ms`; } \
1857 for (const got of performance.getEntriesByType('resource')) { \
1858 if (!/\\.(wasm|js)(\\?|$)/.test(got.name)) { continue; } \
1859 out += `, ${got.name.split('/').pop()} was fetched in \
1860 ${Math.round(got.duration)}ms`; } \
1861 return out;";
1862
1863 let told = self.inner.execute(script, Vec::new()).await?;
1864 Ok(told.json().as_str().unwrap_or_default().to_owned())
1865 }
1866
1867 pub async fn error_seen(&self) -> Result<Option<String>> {
1869 let body = self.find_one_by("body").await?;
1870 let seen = body.attr("data-threw").await?;
1871
1872 Ok((!seen.is_empty()).then_some(seen))
1873 }
1874
1875 pub async fn pointer_drag_onto(&self, from: &TestElement, to: &TestElement) -> Result<()> {
1877 from.inner.scroll_into_view().await?;
1878 self.inner
1879 .action_chain()
1880 .move_to_element_center(&from.inner)
1881 .click_and_hold()
1882 .move_by_offset(8, 0)
1883 .release_on_element(&to.inner)
1884 .perform()
1885 .await?;
1886 Ok(())
1887 }
1888
1889 pub async fn native_drag_over(&self, from: &TestElement, to: &TestElement) -> Result<()> {
1896 tracing::trace!("Carrying one element over another with the pointer");
1897
1898 from.inner.scroll_into_view().await?;
1899
1900 self.inner
1901 .action_chain()
1902 .move_to_element_center(&from.inner)
1903 .click_and_hold()
1904 .move_by_offset(4, 0)
1905 .move_by_offset(8, 2)
1906 .move_by_offset(16, 4)
1907 .move_to_element_center(&to.inner)
1908 .move_by_offset(2, 0)
1909 .perform()
1910 .await?;
1911
1912 Ok(())
1913 }
1914
1915 pub async fn release_all_input(&self) -> Result<()> {
1919 self.inner.action_chain().reset_actions().await?;
1920 Ok(())
1921 }
1922
1923 pub async fn native_release(&self) -> Result<()> {
1925 self.inner
1926 .action_chain()
1927 .move_by_offset(1, 0)
1928 .release()
1929 .perform()
1930 .await?;
1931 Ok(())
1932 }
1933
1934 pub async fn watch_mutations(&self, element: &TestElement) -> Result<()> {
1940 self.inner
1941 .execute(
1942 "if (window.__e2eMutations) { \
1943 window.__e2eMutations.observer.disconnect(); \
1944 window.__e2eMutations.outer.disconnect(); \
1945 } \
1946 const watch = { count: 0, kinds: [] }; \
1947 watch.observer = new MutationObserver(records => { \
1948 watch.count += records.length; \
1949 for (const r of records) watch.kinds.push(r.type + ':' + (r.attributeName || '') + ':' + (r.target.className || r.target.nodeName)); \
1950 }); \
1951 watch.observer.observe(arguments[0], \
1952 { subtree: true, childList: true, attributes: true, characterData: true }); \
1953 const node = arguments[0]; \
1954 watch.outer = new MutationObserver(records => { \
1955 for (const r of records) for (const n of r.removedNodes) \
1956 if (n === node || n.contains(node)) { watch.count += 1; watch.kinds.push('removed'); } \
1957 }); \
1958 watch.outer.observe(document.body, { subtree: true, childList: true }); \
1959 if (!window.__e2eClearRect) { \
1960 window.__e2eClearRect = CanvasRenderingContext2D.prototype.clearRect; \
1961 CanvasRenderingContext2D.prototype.clearRect = function (...args) { \
1962 const watch = window.__e2eMutations; \
1963 if (watch && watch.node.contains(this.canvas)) { watch.count += 1; watch.kinds.push('redrawn'); } \
1964 return window.__e2eClearRect.apply(this, args); \
1965 }; \
1966 } \
1967 watch.node = node; \
1968 window.__e2eMutations = watch;",
1969 vec![element.inner.to_json()?],
1970 )
1971 .await?;
1972 Ok(())
1973 }
1974
1975 pub async fn mutations(&self) -> Result<(u64, Vec<String>)> {
1978 let value = self
1979 .inner
1980 .execute(
1981 "const watch = window.__e2eMutations; \
1982 return watch ? [watch.count, watch.kinds] : [0, []];",
1983 Vec::new(),
1984 )
1985 .await?;
1986 Ok(serde_json::from_value(value.json().clone())?)
1987 }
1988
1989 pub async fn external_files(&self, paths: &str) -> Result<TestElement> {
1991 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?;
1992 let input = self.find_one_by("[data-test='external-files']").await?;
1993 input.send_keys(paths).await?;
1994 Ok(input)
1995 }
1996
1997 pub async fn drag_external_files(
1999 &self,
2000 files: &TestElement,
2001 to: &TestElement,
2002 kind: &str,
2003 ) -> Result<bool> {
2004 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?;
2005 Ok(serde_json::from_value(result.json().clone())?)
2006 }
2007
2008 pub async fn drag_onto(&self, from: &TestElement, to: &TestElement) -> Result<()> {
2010 tracing::trace!("Carrying one element onto another");
2011
2012 let script = "const data = new DataTransfer(); \
2013 const fire = (node, kind) => node.dispatchEvent( \
2014 new DragEvent(kind, \
2015 { dataTransfer: data, bubbles: true, cancelable: true })); \
2016 fire(arguments[0], 'dragstart'); \
2017 fire(arguments[1], 'dragover'); \
2018 fire(arguments[1], 'drop'); \
2019 fire(arguments[0], 'dragend');";
2020
2021 self.inner
2022 .execute(script, vec![from.inner.to_json()?, to.inner.to_json()?])
2023 .await?;
2024
2025 Ok(())
2026 }
2027
2028 pub async fn drag_over(&self, from: &TestElement, to: &TestElement) -> Result<()> {
2031 tracing::trace!("Carrying one element over another");
2032
2033 let script = "const data = new DataTransfer(); \
2034 const fire = (node, kind) => node.dispatchEvent( \
2035 new DragEvent(kind, \
2036 { dataTransfer: data, bubbles: true, cancelable: true })); \
2037 fire(arguments[0], 'dragstart'); \
2038 fire(arguments[1], 'dragover');";
2039
2040 self.inner
2041 .execute(script, vec![from.inner.to_json()?, to.inner.to_json()?])
2042 .await?;
2043
2044 Ok(())
2045 }
2046
2047 pub async fn drag_off(&self, left: &TestElement) -> Result<()> {
2052 tracing::trace!("Carrying a drag back off an element");
2053
2054 let script = "const data = new DataTransfer(); \
2055 arguments[0].dispatchEvent( \
2056 new DragEvent('dragleave', \
2057 { dataTransfer: data, bubbles: true, cancelable: true }));";
2058
2059 self.inner
2060 .execute(script, vec![left.inner.to_json()?])
2061 .await?;
2062
2063 Ok(())
2064 }
2065
2066 pub async fn scroll_top(&self, element: &TestElement, top: i32) -> Result<()> {
2068 self.inner
2069 .execute(
2070 "arguments[0].scrollTop = arguments[1];",
2071 vec![element.inner.to_json()?, serde_json::json!(top)],
2072 )
2073 .await?;
2074 Ok(())
2075 }
2076
2077 pub async fn scroll_to_far_end(&self, element: &TestElement) -> Result<()> {
2079 tracing::trace!("Scrolling an element's box to the end of its travel");
2080
2081 let script = "let node = arguments[0].parentElement; \
2082 while (node) { \
2083 const how = getComputedStyle(node).overflowX; \
2084 if ((how === 'auto' || how === 'scroll') \
2085 && node.scrollWidth > node.clientWidth) { \
2086 break; \
2087 } \
2088 node = node.parentElement; \
2089 } \
2090 if (node) { node.scrollLeft = node.scrollWidth; }";
2091
2092 self.inner
2093 .execute(script, vec![element.inner.to_json()?])
2094 .await?;
2095
2096 Ok(())
2097 }
2098
2099 pub async fn computed(
2101 &self,
2102 element: &TestElement,
2103 pseudo: &str,
2104 property: &str,
2105 ) -> Result<String> {
2106 tracing::trace!(pseudo, property, "Asking what a property computed to");
2107
2108 let script = "return getComputedStyle(arguments[0], arguments[1] || null) \
2109 .getPropertyValue(arguments[2]);";
2110
2111 let value = self
2112 .inner
2113 .execute(
2114 script,
2115 vec![
2116 element.inner.to_json()?,
2117 serde_json::json!(pseudo),
2118 serde_json::json!(property),
2119 ],
2120 )
2121 .await?;
2122
2123 Ok(value.json().as_str().unwrap_or_default().trim().to_string())
2124 }
2125
2126 pub async fn reduced_motion(&self) -> Result<bool> {
2129 let value = self
2130 .inner
2131 .execute(
2132 "return matchMedia('(prefers-reduced-motion: reduce)').matches;",
2133 Vec::new(),
2134 )
2135 .await?;
2136 let reduced = value
2137 .json()
2138 .as_bool()
2139 .context("reduced-motion media query")?;
2140 if let Ok(requested) = std::env::var("E2E_MOTION") {
2141 anyhow::ensure!(
2142 reduced == (requested == "reduce"),
2143 "browser did not honor E2E_MOTION={requested}"
2144 );
2145 }
2146 Ok(reduced)
2147 }
2148
2149 pub async fn animation_time(
2152 &self,
2153 element: &TestElement,
2154 name: &str,
2155 millis: f64,
2156 ) -> Result<()> {
2157 self.inner.execute(
2158 "const animation = arguments[0].getAnimations().find(a => a.animationName === arguments[1]); \
2159 if (!animation) throw new Error('Missing animation: ' + arguments[1]); \
2160 animation.pause(); animation.currentTime = arguments[2];",
2161 vec![element.inner.to_json()?, serde_json::json!(name), serde_json::json!(millis)],
2162 ).await?;
2163 Ok(())
2164 }
2165
2166 pub async fn color_alpha(&self, element: &TestElement, property: &str) -> Result<f64> {
2169 let value = self.inner.execute(
2170 "const canvas = document.createElement('canvas'); canvas.width = canvas.height = 1; \
2171 const context = canvas.getContext('2d'); context.fillStyle = 'transparent'; \
2172 context.fillStyle = getComputedStyle(arguments[0]).getPropertyValue(arguments[1]); \
2173 context.fillRect(0, 0, 1, 1); return context.getImageData(0, 0, 1, 1).data[3] / 255;",
2174 vec![element.inner.to_json()?, serde_json::json!(property)],
2175 ).await?;
2176 value.json().as_f64().context("computed color alpha")
2177 }
2178
2179 pub async fn color_shift(&self, element: &TestElement, property: &str) -> Result<f64> {
2185 let [red, green, blue] = self.painted(element, property).await?;
2186 Ok((red + green + blue) / 3.0 - 128.0)
2187 }
2188
2189 pub async fn painted(&self, element: &TestElement, property: &str) -> Result<[f64; 3]> {
2196 let value = self.inner.execute(
2197 "const canvas = document.createElement('canvas'); canvas.width = canvas.height = 1; \
2198 const context = canvas.getContext('2d'); \
2199 context.fillStyle = '#808080'; context.fillRect(0, 0, 1, 1); \
2200 context.fillStyle = 'transparent'; \
2201 context.fillStyle = getComputedStyle(arguments[0]).getPropertyValue(arguments[1]); \
2202 context.fillRect(0, 0, 1, 1); \
2203 const painted = context.getImageData(0, 0, 1, 1).data; \
2204 return [painted[0], painted[1], painted[2]];",
2205 vec![element.inner.to_json()?, serde_json::json!(property)],
2206 ).await?;
2207
2208 let read = value.json();
2209 let read = read.as_array().context("what a computed colour paints")?;
2210
2211 let mut rgb = [0.0; 3];
2212
2213 for (channel, value) in rgb.iter_mut().zip(read) {
2214 *channel = value.as_f64().context("a painted channel")?;
2215 }
2216
2217 Ok(rgb)
2218 }
2219
2220 pub async fn canvas_columns(
2229 &self,
2230 canvas: &TestElement,
2231 columns: usize,
2232 ) -> Result<Vec<(f64, f64, f64)>> {
2233 let script = "const canvas = arguments[0]; \
2234 const columns = Math.max(1, arguments[1]); \
2235 const w = canvas.width, h = canvas.height; \
2236 if (w === 0 || h === 0) return []; \
2237 const ctx = canvas.getContext('2d'); \
2238 const data = ctx.getImageData(0, 0, w, h).data; \
2239 const step = Math.max(1, Math.floor(w / columns)); \
2240 const out = []; \
2241 for (let x = 0; x < w; x += step) { \
2242 let top = -1, bottom = -1; \
2243 for (let y = 0; y < h; y++) { \
2244 if (data[(y * w + x) * 4 + 3] > 0) { \
2245 if (top === -1) top = y; \
2246 bottom = y; \
2247 } \
2248 } \
2249 out.push([x / w, top === -1 ? -1 : top / h, bottom === -1 ? -1 : bottom / h]); \
2250 } \
2251 return out;";
2252
2253 let value = self
2254 .inner
2255 .execute(
2256 script,
2257 vec![canvas.inner.to_json()?, serde_json::json!(columns)],
2258 )
2259 .await?;
2260
2261 let read = value.json();
2262 let read = read.as_array().context("canvas column scan")?;
2263 let mut out = Vec::with_capacity(read.len());
2264
2265 for row in read {
2266 let row = row.as_array().context("a canvas column")?;
2267 let field = |at: usize, name: &str| {
2268 row.get(at)
2269 .and_then(serde_json::Value::as_f64)
2270 .with_context(|| format!("a canvas column's {name}"))
2271 };
2272 out.push((field(0, "x")?, field(1, "top")?, field(2, "bottom")?));
2273 }
2274
2275 Ok(out)
2276 }
2277
2278 pub async fn canvas_size(&self, canvas: &TestElement) -> Result<CanvasSize> {
2283 let script = "const c = arguments[0]; const r = c.getBoundingClientRect(); \
2284 return [c.width, c.height, r.width, r.height, window.devicePixelRatio];";
2285
2286 let value = self
2287 .inner
2288 .execute(script, vec![canvas.inner.to_json()?])
2289 .await?;
2290 let read = value.json();
2291 let read = read.as_array().context("canvas size read")?;
2292 let field = |at: usize, name: &str| {
2293 read.get(at)
2294 .and_then(serde_json::Value::as_f64)
2295 .with_context(|| format!("canvas size's {name}"))
2296 };
2297
2298 Ok(CanvasSize {
2299 device_width: field(0, "device_width")?,
2300 device_height: field(1, "device_height")?,
2301 css_width: field(2, "css_width")?,
2302 css_height: field(3, "css_height")?,
2303 device_pixel_ratio: field(4, "device_pixel_ratio")?,
2304 })
2305 }
2306
2307 pub async fn middle_click(&self, element: &TestElement) -> Result<()> {
2309 tracing::trace!("Middle-clicking an element");
2310
2311 let script = "for (const type of ['mousedown', 'mouseup', 'auxclick']) {\
2312 arguments[0].dispatchEvent(new MouseEvent(type, \
2313 { button: 1, buttons: 4, bubbles: true, cancelable: true })); \
2314 }";
2315
2316 self.inner
2317 .execute(script, vec![element.inner.to_json()?])
2318 .await?;
2319
2320 Ok(())
2321 }
2322
2323 pub async fn middle_drag_by(&self, element: &TestElement, dx: i64) -> Result<()> {
2325 use thirtyfour::common::command::Command;
2326
2327 let actions = serde_json::json!([{
2328 "type": "pointer", "id": "pointer", "parameters": {"pointerType": "mouse"},
2329 "actions": [
2330 {"type": "pointerMove", "duration": 0, "origin": element.inner.to_json()?, "x": 0, "y": 0},
2331 {"type": "pointerDown", "button": 1},
2332 {"type": "pointerMove", "duration": 150, "origin": "pointer", "x": dx, "y": 0},
2333 {"type": "pointerUp", "button": 1}
2334 ]
2335 }]);
2336 self.inner
2337 .cmd(Command::PerformActions(actions.into()))
2338 .await?;
2339 Ok(())
2340 }
2341
2342 pub async fn move_held(&self, dx: i64, dy: i64) -> Result<()> {
2344 tracing::trace!(dx, dy, "Carrying a held drag");
2345
2346 self.inner
2347 .action_chain()
2348 .move_by_offset(dx, dy)
2349 .perform()
2350 .await?;
2351
2352 Ok(())
2353 }
2354
2355 pub async fn drop_held(&self) -> Result<()> {
2357 tracing::trace!("Releasing a held drag");
2358 self.inner.action_chain().release().perform().await?;
2359 Ok(())
2360 }
2361
2362 pub async fn cancel_pointer(&self, element: &TestElement) -> Result<()> {
2365 self.inner
2366 .execute(
2367 "arguments[0].dispatchEvent(new PointerEvent('pointercancel', { bubbles: true }));",
2368 vec![element.inner.to_json()?],
2369 )
2370 .await?;
2371 Ok(())
2372 }
2373
2374 pub async fn drop_held_alt(&self) -> Result<()> {
2377 tracing::trace!("Releasing a held drag and the alt key with it");
2378
2379 self.inner
2380 .action_chain()
2381 .release()
2382 .key_up(thirtyfour::Key::Alt)
2383 .perform()
2384 .await?;
2385
2386 Ok(())
2387 }
2388
2389 pub async fn drawn_inside(&self, selector: &str, x: f64, y: f64) -> Result<bool> {
2404 tracing::trace!(selector, x, y, "Asking what is drawn at a point");
2405
2406 let script = "const [selector, x, y] = arguments; \
2407 const host = document.querySelector(selector); \
2408 const found = document.elementFromPoint(x, y); \
2409 if (!host || !found || !host.contains(found)) return false; \
2410 for (const over of document.body.children) { \
2411 if (over.contains(host) || host.contains(over)) continue; \
2412 const box = over.getBoundingClientRect(); \
2413 if (x >= box.left && x <= box.right && y >= box.top && y <= box.bottom) \
2414 return false; \
2415 } \
2416 return true;";
2417
2418 let value = self
2419 .inner
2420 .execute(
2421 script,
2422 vec![
2423 serde_json::json!(selector),
2424 serde_json::json!(x),
2425 serde_json::json!(y),
2426 ],
2427 )
2428 .await?;
2429
2430 Ok(value.json().as_bool().unwrap_or_default())
2431 }
2432
2433 pub async fn screenshot_png(&self) -> Result<Vec<u8>> {
2438 tracing::trace!("Taking a screenshot");
2439 Ok(self.inner.screenshot_as_png().await?)
2440 }
2441
2442 pub async fn screenshot(&self, path: impl AsRef<std::path::Path>) -> Result<()> {
2444 std::fs::write(path, self.screenshot_png().await?)?;
2445 Ok(())
2446 }
2447
2448 pub async fn snapshot(&self, name: &str) -> Result<()> {
2464 let Some(dir) = std::env::var_os("E2E_SHOTS") else {
2465 return Ok(());
2466 };
2467
2468 let dir = std::path::PathBuf::from(dir);
2469
2470 let dir = match dir.is_absolute() {
2471 true => dir,
2472 false => crate::dist::target_dir()?.join("e2e-shots").join(dir),
2473 };
2474
2475 std::fs::create_dir_all(&dir)?;
2476
2477 let path = dir.join(format!("{name}.png"));
2478 tracing::info!(path = %path.display(), "Writing snapshot");
2479 self.screenshot(&path).await
2480 }
2481
2482 pub async fn press_nth(&self, by: impl IntoBy, index: usize) -> Result<()> {
2485 let by = by.into_by();
2486
2487 tracing::trace!(?by, index, "Pressing element");
2488
2489 let deadline = time::Instant::now() + self.wait_timeout;
2490
2491 loop {
2492 let found = self.find_all(by.clone()).await?;
2493
2494 if let Some(item) = found.get(index)
2495 && item.click().await.is_ok()
2496 {
2497 return Ok(());
2498 }
2499
2500 if time::Instant::now() >= deadline {
2501 bail!(
2502 "Timed out after {:?} pressing {by} at {index}",
2503 self.wait_timeout
2504 );
2505 }
2506
2507 time::sleep(POLL_INTERVAL).await;
2508 }
2509 }
2510
2511 pub async fn context_press_nth(&self, by: impl IntoBy, index: usize) -> Result<()> {
2515 let by = by.into_by();
2516
2517 tracing::trace!(?by, index, "Right-clicking element");
2518
2519 let deadline = time::Instant::now() + self.wait_timeout;
2520
2521 loop {
2522 let found = self.find_all(by.clone()).await?;
2523
2524 if let Some(item) = found.get(index)
2525 && item.context_click().await.is_ok()
2526 {
2527 return Ok(());
2528 }
2529
2530 if time::Instant::now() >= deadline {
2531 bail!(
2532 "Timed out after {:?} right-clicking {by} at {index}",
2533 self.wait_timeout
2534 );
2535 }
2536
2537 time::sleep(POLL_INTERVAL).await;
2538 }
2539 }
2540
2541 pub async fn local_storage(&self, key: &str) -> Result<Option<String>> {
2543 let value = self
2544 .inner
2545 .execute(
2546 "return localStorage.getItem(arguments[0]);",
2547 vec![serde_json::json!(key)],
2548 )
2549 .await?;
2550 Ok(value.json().as_str().map(str::to_owned))
2551 }
2552
2553 pub async fn set_local_storage(&self, key: &str, value: &str) -> Result<()> {
2555 self.inner
2556 .execute(
2557 "localStorage.setItem(arguments[0], arguments[1]);",
2558 vec![serde_json::json!(key), serde_json::json!(value)],
2559 )
2560 .await?;
2561 Ok(())
2562 }
2563
2564 pub async fn block_local_storage(&self) -> Result<()> {
2566 self.inner.execute(
2567 "const script = document.createElement('script'); \
2568 script.textContent = `Object.defineProperty(window, 'localStorage', {configurable: true, get() { throw new DOMException('Storage blocked by test', 'SecurityError'); }});`; \
2569 document.documentElement.appendChild(script); script.remove();",
2570 vec![],
2571 ).await?;
2572 Ok(())
2573 }
2574
2575 pub async fn reload(&self) -> Result<()> {
2577 tracing::trace!("Reloading the page");
2578 self.inner.refresh().await?;
2579
2580 let _ = self.watch_for_errors().await;
2581 Ok(())
2582 }
2583
2584 pub async fn reopen_with(&self, query: &str) -> Result<()> {
2586 tracing::trace!(query, "Reopening the page");
2587
2588 let mut url = self.inner.current_url().await?;
2589 url.set_query(Some(query));
2590 self.inner.goto(url.as_str()).await?;
2591 Ok(())
2592 }
2593
2594 pub async fn in_second_tab(&self, run: impl AsyncFnOnce() -> Result<()>) -> Result<()> {
2599 self.in_second_context(true, run).await
2600 }
2601
2602 pub async fn in_second_window(&self, run: impl AsyncFnOnce() -> Result<()>) -> Result<()> {
2604 self.in_second_context(false, run).await
2605 }
2606
2607 async fn in_second_context(
2608 &self,
2609 tab: bool,
2610 run: impl AsyncFnOnce() -> Result<()>,
2611 ) -> Result<()> {
2612 let original = self.inner.window().await?;
2613 let url = self.inner.current_url().await?;
2614 let opened = if tab {
2615 self.inner.new_tab().await?
2616 } else {
2617 self.inner.new_window().await?
2618 };
2619
2620 let result = async {
2621 self.inner.switch_to_window(opened.clone()).await?;
2622 self.set_window_size(WINDOW.0, WINDOW.1).await?;
2623 self.inner.goto(url.as_str()).await?;
2624 run().await?;
2625 match self.error_seen().await? {
2626 Some(threw) => bail!("the page threw: {threw}"),
2627 None => Ok(()),
2628 }
2629 }
2630 .await;
2631
2632 let cleanup = async {
2633 self.inner.switch_to_window(opened).await?;
2634 self.inner.close_window().await?;
2635 self.inner.switch_to_window(original).await?;
2636 Ok(())
2637 }
2638 .await;
2639
2640 match result {
2641 Ok(()) => cleanup,
2642 Err(error) => Err(with_cleanup(error, cleanup)),
2643 }
2644 }
2645
2646 pub async fn press_key(&self, key: Key) -> Result<()> {
2649 tracing::trace!(?key, "Pressing a key");
2650 self.inner.action_chain().send_keys(key).perform().await?;
2651 Ok(())
2652 }
2653
2654 pub async fn hold_key(&self, key: char) -> Result<()> {
2657 self.inner.action_chain().key_down(key).perform().await?;
2658 Ok(())
2659 }
2660
2661 pub async fn release_key(&self, key: char) -> Result<()> {
2662 self.inner.action_chain().key_up(key).perform().await?;
2663 Ok(())
2664 }
2665
2666 pub async fn find_all_attrs(&self, selector: &str, attr: &str) -> Result<Vec<String>> {
2671 let script = format!(
2672 "return Array.from(document.querySelectorAll({})) \
2673 .map(n => n.getAttribute({}) ?? '')",
2674 serde_json::to_string(selector)?,
2675 serde_json::to_string(attr)?,
2676 );
2677
2678 let read = self.inner.execute(script, Vec::new()).await?;
2679
2680 Ok(read
2681 .json()
2682 .as_array()
2683 .map(|rows| {
2684 rows.iter()
2685 .map(|row| row.as_str().unwrap_or_default().to_owned())
2686 .collect()
2687 })
2688 .unwrap_or_default())
2689 }
2690
2691 pub async fn bands(&self, selector: &str, attr: &str) -> Result<Vec<(String, f64, f64)>> {
2700 let script = format!(
2701 "return Array.from(document.querySelectorAll({})) \
2702 .filter(n => n.getClientRects().length > 0) \
2703 .map(n => [n.getAttribute({}) ?? '', \
2704 n.getBoundingClientRect().top, n.getBoundingClientRect().height])",
2705 serde_json::to_string(selector)?,
2706 serde_json::to_string(attr)?,
2707 );
2708
2709 let read = self.inner.execute(script, Vec::new()).await?;
2710 let read = read.json();
2711
2712 let rows = read.as_array().context("a list of bands")?;
2713 let mut bands = Vec::with_capacity(rows.len());
2714
2715 for row in rows {
2716 let row = row.as_array().context("a band")?;
2717
2718 bands.push((
2719 row.first()
2720 .and_then(|name| name.as_str())
2721 .unwrap_or_default()
2722 .to_owned(),
2723 row.get(1).and_then(|top| top.as_f64()).context("a top")?,
2724 row.get(2)
2725 .and_then(|height| height.as_f64())
2726 .context("a height")?,
2727 ));
2728 }
2729
2730 Ok(bands)
2731 }
2732
2733 pub async fn press_key_on(&self, selector: &str, key: &str) -> Result<()> {
2735 let script = format!(
2736 "const at = document.querySelector({}); \
2737 if (!at) throw new Error('No element for keyboard press'); \
2738 at.focus(); at.dispatchEvent(new KeyboardEvent('keydown', \
2739 {{ key: {}, bubbles: true, cancelable: true }}));",
2740 serde_json::to_string(selector)?,
2741 serde_json::to_string(key)?,
2742 );
2743 self.inner.execute(script, Vec::new()).await?;
2744 Ok(())
2745 }
2746
2747 pub async fn press_key_with_ctrl(&self, selector: &str, key: &str) -> Result<()> {
2755 tracing::trace!(selector, key, "Pressing a key with control held");
2756
2757 let code = match key.chars().collect::<Vec<_>>().as_slice() {
2758 [c] if c.is_ascii_alphabetic() => format!("Key{}", c.to_ascii_uppercase()),
2759 _ => key.to_owned(),
2760 };
2761
2762 let script = format!(
2763 "const at = document.querySelector({}); \
2764 if (at) {{ at.focus(); at.dispatchEvent(new KeyboardEvent('keydown', \
2765 {{ key: {}, code: {}, ctrlKey: true, bubbles: true, cancelable: true }})); }}",
2766 serde_json::to_string(selector)?,
2767 serde_json::to_string(key)?,
2768 serde_json::to_string(&code)?,
2769 );
2770
2771 self.inner.execute(script, Vec::new()).await?;
2772 Ok(())
2773 }
2774
2775 pub async fn press_key_with_shift(&self, selector: &str, key: &str) -> Result<()> {
2778 tracing::trace!(selector, key, "Pressing a key with shift held");
2779
2780 let script = format!(
2781 "const at = document.querySelector({}); \
2782 if (at) {{ at.focus(); at.dispatchEvent(new KeyboardEvent('keydown', \
2783 {{ key: {}, shiftKey: true, bubbles: true, cancelable: true }})); }}",
2784 serde_json::to_string(selector)?,
2785 serde_json::to_string(key)?,
2786 );
2787
2788 self.inner.execute(script, Vec::new()).await?;
2789 Ok(())
2790 }
2791
2792 pub async fn blur(&self) -> Result<()> {
2795 tracing::trace!("Blurring the focused element");
2796
2797 self.inner
2798 .execute(
2799 "document.activeElement && document.activeElement.blur();",
2800 Vec::new(),
2801 )
2802 .await?;
2803
2804 Ok(())
2805 }
2806
2807 pub async fn focused_attr(&self, name: &str) -> Result<Option<String>> {
2808 let found = self
2809 .inner
2810 .execute(
2811 &format!(
2812 "return document.activeElement \
2813 && document.activeElement.getAttribute('{name}')"
2814 ),
2815 Vec::new(),
2816 )
2817 .await?;
2818
2819 Ok(found.json().as_str().map(str::to_owned))
2820 }
2821
2822 common!();
2823}
2824
2825pub trait IntoBy {
2826 fn into_by(self) -> By;
2827}
2828
2829impl IntoBy for &str {
2830 #[inline]
2831 fn into_by(self) -> By {
2832 By::Css(self)
2833 }
2834}
2835
2836impl IntoBy for &String {
2839 #[inline]
2840 fn into_by(self) -> By {
2841 By::Css(self.as_str())
2842 }
2843}
2844
2845impl IntoBy for By {
2846 #[inline]
2847 fn into_by(self) -> By {
2848 self
2849 }
2850}