fantoccini/wd.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
//! WebDriver types and declarations.
use crate::error;
#[cfg(doc)]
use crate::Client;
use http::Method;
use serde::{Deserialize, Serialize};
use std::borrow::Cow;
use std::convert::TryFrom;
use std::fmt;
use std::fmt::Debug;
use std::time::Duration;
use url::{ParseError, Url};
use webdriver::command::TimeoutsParameters;
/// A command that can be sent to the WebDriver.
///
/// Anything that implements this command can be sent to [`Client::issue_cmd()`] in order
/// to send custom commands to the WebDriver instance.
pub trait WebDriverCompatibleCommand: Debug {
/// The endpoint to send the request to.
fn endpoint(
&self,
base_url: &url::Url,
session_id: Option<&str>,
) -> Result<url::Url, url::ParseError>;
/// The HTTP request method to use, and the request body for the request.
///
/// The `url` will be the one returned from the `endpoint()` method above.
fn method_and_body(&self, request_url: &url::Url) -> (http::Method, Option<String>);
/// Return true if this command starts a new WebDriver session.
fn is_new_session(&self) -> bool {
false
}
/// Return true if this session should only support the legacy webdriver protocol.
///
/// This only applies to the obsolete JSON Wire Protocol and should return `false`
/// for all implementations that follow the W3C specification.
///
/// See <https://www.selenium.dev/documentation/legacy/json_wire_protocol/> for more
/// details about JSON Wire Protocol.
fn is_legacy(&self) -> bool {
false
}
}
/// Blanket implementation for &T, for better ergonomics.
impl<T> WebDriverCompatibleCommand for &T
where
T: WebDriverCompatibleCommand,
{
fn endpoint(&self, base_url: &Url, session_id: Option<&str>) -> Result<Url, ParseError> {
T::endpoint(self, base_url, session_id)
}
fn method_and_body(&self, request_url: &Url) -> (Method, Option<String>) {
T::method_and_body(self, request_url)
}
fn is_new_session(&self) -> bool {
T::is_new_session(self)
}
fn is_legacy(&self) -> bool {
T::is_legacy(self)
}
}
/// Blanket implementation for Box<T>, for better ergonomics.
impl<T> WebDriverCompatibleCommand for Box<T>
where
T: WebDriverCompatibleCommand,
{
fn endpoint(&self, base_url: &Url, session_id: Option<&str>) -> Result<Url, ParseError> {
T::endpoint(self, base_url, session_id)
}
fn method_and_body(&self, request_url: &Url) -> (Method, Option<String>) {
T::method_and_body(self, request_url)
}
fn is_new_session(&self) -> bool {
T::is_new_session(self)
}
fn is_legacy(&self) -> bool {
T::is_legacy(self)
}
}
/// A [handle][1] to a browser window.
///
/// Should be obtained it via [`Client::window()`] method (or similar).
///
/// [1]: https://www.w3.org/TR/webdriver/#dfn-window-handles
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct WindowHandle(String);
impl From<WindowHandle> for String {
fn from(w: WindowHandle) -> Self {
w.0
}
}
impl<'a> TryFrom<Cow<'a, str>> for WindowHandle {
type Error = error::InvalidWindowHandle;
/// Makes the given string a [`WindowHandle`].
///
/// Avoids allocation if possible.
///
/// # Errors
///
/// If the given string is [`"current"`][1].
///
/// [1]: https://www.w3.org/TR/webdriver/#dfn-window-handles
fn try_from(s: Cow<'a, str>) -> Result<Self, Self::Error> {
if s != "current" {
Ok(Self(s.into_owned()))
} else {
Err(error::InvalidWindowHandle)
}
}
}
impl TryFrom<String> for WindowHandle {
type Error = error::InvalidWindowHandle;
/// Makes the given [`String`] a [`WindowHandle`].
///
/// # Errors
///
/// If the given [`String`] is [`"current"`][1].
///
/// [1]: https://www.w3.org/TR/webdriver/#dfn-window-handles
fn try_from(s: String) -> Result<Self, Self::Error> {
Self::try_from(Cow::Owned(s))
}
}
impl TryFrom<&str> for WindowHandle {
type Error = error::InvalidWindowHandle;
/// Makes the given string a [`WindowHandle`].
///
/// Allocates if succeeds.
///
/// # Errors
///
/// If the given string is [`"current"`][1].
///
/// [1]: https://www.w3.org/TR/webdriver/#dfn-window-handles
fn try_from(s: &str) -> Result<Self, Self::Error> {
Self::try_from(Cow::Borrowed(s))
}
}
/// A type of a new browser window.
///
/// Returned by [`Client::new_window()`] method.
///
/// [`Client::new_window()`]: crate::Client::new_window
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum NewWindowType {
/// Opened in a tab.
Tab,
/// Opened in a separate window.
Window,
}
impl fmt::Display for NewWindowType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Tab => write!(f, "tab"),
Self::Window => write!(f, "window"),
}
}
}
/// Dynamic set of [WebDriver capabilities][1].
///
/// [1]: https://www.w3.org/TR/webdriver/#dfn-capability
pub type Capabilities = serde_json::Map<String, serde_json::Value>;
/// An element locator.
///
/// See [the specification][1] for more details.
///
/// [1]: https://www.w3.org/TR/webdriver1/#locator-strategies
#[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Debug, Hash)]
pub enum Locator<'a> {
/// Find an element matching the given [CSS selector][1].
///
/// [1]: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors
Css(&'a str),
/// Find an element using the given [`id`][1].
///
/// [1]: https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id
Id(&'a str),
/// Find a link element with the given link text.
///
/// The text matching is exact.
LinkText(&'a str),
/// Find an element using the given [XPath expression][1].
///
/// You can address pretty much any element this way, if you're willing to
/// put in the time to find the right XPath.
///
/// [1]: https://developer.mozilla.org/en-US/docs/Web/XPath
XPath(&'a str),
}
impl<'a> Locator<'a> {
pub(crate) fn into_parameters(self) -> webdriver::command::LocatorParameters {
use webdriver::command::LocatorParameters;
use webdriver::common::LocatorStrategy;
match self {
Locator::Css(s) => LocatorParameters {
using: LocatorStrategy::CSSSelector,
value: s.to_string(),
},
Locator::Id(s) => LocatorParameters {
using: LocatorStrategy::XPath,
value: format!("//*[@id=\"{}\"]", s),
},
Locator::XPath(s) => LocatorParameters {
using: LocatorStrategy::XPath,
value: s.to_string(),
},
Locator::LinkText(s) => LocatorParameters {
using: LocatorStrategy::LinkText,
value: s.to_string(),
},
}
}
}
/// The WebDriver status as returned by [`Client::status()`].
///
/// See [8.3 Status](https://www.w3.org/TR/webdriver1/#status) of the WebDriver standard.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WebDriverStatus {
/// True if the webdriver is ready to start a new session.
///
/// NOTE: Geckodriver will return `false` if a session has already started, since it
/// only supports a single session.
pub ready: bool,
/// The current status message.
pub message: String,
}
/// Timeout configuration, for various timeout settings.
///
/// Used by [`Client::get_timeouts()`] and [`Client::update_timeouts()`].
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub struct TimeoutConfiguration {
#[serde(skip_serializing_if = "Option::is_none")]
script: Option<u64>,
#[serde(rename = "pageLoad", skip_serializing_if = "Option::is_none")]
page_load: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
implicit: Option<u64>,
}
impl Default for TimeoutConfiguration {
fn default() -> Self {
TimeoutConfiguration::new(
Some(Duration::from_secs(60)),
Some(Duration::from_secs(60)),
Some(Duration::from_secs(0)),
)
}
}
impl TimeoutConfiguration {
/// Create new timeout configuration.
///
/// The various settings are as follows:
/// - script Determines when to interrupt a script that is being evaluated.
/// Default is 60 seconds.
/// - page_load Provides the timeout limit used to interrupt navigation of the browsing
/// context. Default is 60 seconds.
/// - implicit Gives the timeout of when to abort locating an element. Default is 0 seconds.
///
/// NOTE: It is recommended to leave the `implicit` timeout at 0 seconds, because that makes
/// it possible to check for the non-existence of an element without an implicit delay.
/// Also see [`Client::wait()`] for element polling functionality.
pub fn new(
script: Option<Duration>,
page_load: Option<Duration>,
implicit: Option<Duration>,
) -> Self {
TimeoutConfiguration {
script: script.map(|x| x.as_millis() as u64),
page_load: page_load.map(|x| x.as_millis() as u64),
implicit: implicit.map(|x| x.as_millis() as u64),
}
}
/// Get the script timeout.
pub fn script(&self) -> Option<Duration> {
self.script.map(Duration::from_millis)
}
/// Set the script timeout.
pub fn set_script(&mut self, timeout: Option<Duration>) {
self.script = timeout.map(|x| x.as_millis() as u64);
}
/// Get the page load timeout.
pub fn page_load(&self) -> Option<Duration> {
self.page_load.map(Duration::from_millis)
}
/// Set the page load timeout.
pub fn set_page_load(&mut self, timeout: Option<Duration>) {
self.page_load = timeout.map(|x| x.as_millis() as u64);
}
/// Get the implicit wait timeout.
pub fn implicit(&self) -> Option<Duration> {
self.implicit.map(Duration::from_millis)
}
/// Set the implicit wait timeout.
pub fn set_implicit(&mut self, timeout: Option<Duration>) {
self.implicit = timeout.map(|x| x.as_millis() as u64);
}
}
impl TimeoutConfiguration {
pub(crate) fn into_params(self) -> TimeoutsParameters {
TimeoutsParameters {
script: self.script.map(Some),
page_load: self.page_load,
implicit: self.implicit,
}
}
}