use serde::Serialize;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum WaitForState {
Attached,
Detached,
Visible,
Hidden,
}
#[derive(Debug, Clone, Default)]
pub struct WaitForOptions {
pub state: Option<WaitForState>,
pub timeout: Option<f64>,
}
impl WaitForOptions {
pub fn builder() -> WaitForOptionsBuilder {
WaitForOptionsBuilder::default()
}
pub(crate) fn to_json(&self) -> serde_json::Value {
let mut json = serde_json::json!({});
let state = self.state.unwrap_or(WaitForState::Visible);
json["state"] = serde_json::to_value(state).unwrap();
if let Some(timeout) = self.timeout {
json["timeout"] = serde_json::json!(timeout);
} else {
json["timeout"] = serde_json::json!(crate::DEFAULT_TIMEOUT_MS);
}
json
}
}
#[derive(Debug, Clone, Default)]
pub struct WaitForOptionsBuilder {
state: Option<WaitForState>,
timeout: Option<f64>,
}
impl WaitForOptionsBuilder {
pub fn state(mut self, state: WaitForState) -> Self {
self.state = Some(state);
self
}
pub fn timeout(mut self, timeout: f64) -> Self {
self.timeout = Some(timeout);
self
}
pub fn build(self) -> WaitForOptions {
WaitForOptions {
state: self.state,
timeout: self.timeout,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_wait_for_state_serialization() {
assert_eq!(
serde_json::to_string(&WaitForState::Attached).unwrap(),
"\"attached\""
);
assert_eq!(
serde_json::to_string(&WaitForState::Detached).unwrap(),
"\"detached\""
);
assert_eq!(
serde_json::to_string(&WaitForState::Visible).unwrap(),
"\"visible\""
);
assert_eq!(
serde_json::to_string(&WaitForState::Hidden).unwrap(),
"\"hidden\""
);
}
#[test]
fn test_wait_for_options_default_state() {
let options = WaitForOptions::builder().build();
let json = options.to_json();
assert_eq!(json["state"], "visible");
assert!(json["timeout"].is_number());
}
#[test]
fn test_wait_for_options_all_states() {
for (state, expected) in &[
(WaitForState::Attached, "attached"),
(WaitForState::Detached, "detached"),
(WaitForState::Visible, "visible"),
(WaitForState::Hidden, "hidden"),
] {
let options = WaitForOptions::builder().state(*state).build();
let json = options.to_json();
assert_eq!(json["state"], *expected);
}
}
#[test]
fn test_wait_for_options_timeout() {
let options = WaitForOptions::builder().timeout(5000.0).build();
let json = options.to_json();
assert_eq!(json["timeout"], 5000.0);
}
}