use std::fmt::Write as _;
use std::sync::Arc;
use std::time::Duration;
use thiserror::Error;
use crate::terminal::error::SessionError;
use crate::terminal::session::Session;
const MAX_LABEL_ARG: usize = 48;
#[derive(Debug, Clone, Error)]
pub enum DriverError {
#[error("{op} failed (driver call #{call}): {cause}")]
Session {
op: String,
call: usize,
cause: Arc<SessionError>,
},
#[error("{op} was not satisfied (driver call #{call})")]
Unsatisfied {
op: String,
call: usize,
},
#[error("{expectation}\n--- screen ---\n{screen}\n--------------")]
Expectation {
expectation: String,
screen: String,
},
}
impl DriverError {
pub fn op(&self) -> &str {
match self {
Self::Session { op, .. } | Self::Unsatisfied { op, .. } => op,
Self::Expectation { expectation, .. } => expectation,
}
}
pub fn session_error(&self) -> Option<&SessionError> {
match self {
Self::Session { cause, .. } => Some(cause),
Self::Unsatisfied { .. } | Self::Expectation { .. } => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DriverTimeouts {
pub stable: Duration,
pub idle: Duration,
pub text: Duration,
pub exit: Duration,
pub read: Duration,
}
impl Default for DriverTimeouts {
fn default() -> Self {
Self {
stable: Duration::from_millis(500),
idle: Duration::from_secs(10),
text: Duration::from_secs(10),
exit: Duration::from_secs(30),
read: Duration::from_secs(3),
}
}
}
pub struct SessionDriver {
session: Box<dyn Session>,
timeouts: DriverTimeouts,
failure: Option<DriverError>,
calls: usize,
}
impl std::fmt::Debug for SessionDriver {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SessionDriver")
.field("argv", &self.session.argv())
.field("timeouts", &self.timeouts)
.field("failure", &self.failure)
.field("calls", &self.calls)
.finish()
}
}
impl SessionDriver {
pub fn new(session: Box<dyn Session>) -> Self {
Self::with_timeouts(session, DriverTimeouts::default())
}
pub fn with_timeouts(session: Box<dyn Session>, timeouts: DriverTimeouts) -> Self {
Self {
session,
timeouts,
failure: None,
calls: 0,
}
}
pub fn timeouts(&self) -> &DriverTimeouts {
&self.timeouts
}
pub fn set_timeouts(&mut self, timeouts: DriverTimeouts) -> &mut Self {
self.timeouts = timeouts;
self
}
pub fn failure(&self) -> Option<&DriverError> {
self.failure.as_ref()
}
pub fn is_failed(&self) -> bool {
self.failure.is_some()
}
pub fn check(&self) -> Result<(), DriverError> {
match &self.failure {
Some(err) => Err(err.clone()),
None => Ok(()),
}
}
pub fn clear_failure(&mut self) -> Option<DriverError> {
self.failure.take()
}
fn fail(&mut self, err: DriverError) {
if self.failure.is_none() {
self.failure = Some(err);
}
}
fn drive<F>(&mut self, op: String, f: F) -> &mut Self
where
F: FnOnce(&mut dyn Session) -> Result<(), SessionError>,
{
self.calls += 1;
if self.failure.is_some() {
return self;
}
let call = self.calls;
if let Err(cause) = f(self.session.as_mut()) {
self.fail(DriverError::Session {
op,
call,
cause: Arc::new(cause),
});
}
self
}
fn drive_wait<F>(&mut self, op: String, require: bool, f: F) -> &mut Self
where
F: FnOnce(&mut dyn Session) -> Result<bool, SessionError>,
{
self.calls += 1;
if self.failure.is_some() {
return self;
}
let call = self.calls;
match f(self.session.as_mut()) {
Ok(true) => {}
Ok(false) => {
if require {
self.fail(DriverError::Unsatisfied { op, call });
}
}
Err(cause) => self.fail(DriverError::Session {
op,
call,
cause: Arc::new(cause),
}),
}
self
}
pub fn send_text(&mut self, text: &str) -> &mut Self {
let op = label("send_text", &[quoted(text)]);
self.drive(op, |s| s.send_text(text))
}
pub fn send_line(&mut self, text: &str) -> &mut Self {
let op = label("send_line", &[quoted(text)]);
self.drive(op, |s| s.send_line(text))
}
pub fn press(&mut self, key: &str) -> &mut Self {
let op = label("press", &[quoted(key)]);
self.drive(op, |s| s.press(key))
}
pub fn wait_for_idle(&mut self) -> &mut Self {
let (stable, timeout) = (self.timeouts.stable, self.timeouts.idle);
self.wait_for_idle_within(stable, timeout)
}
pub fn wait_for_idle_within(&mut self, stable: Duration, timeout: Duration) -> &mut Self {
let op = label(
"wait_for_idle",
&[format!("stable={stable:?}"), format!("timeout={timeout:?}")],
);
self.drive_wait(op, true, |s| s.wait_for_idle(stable, timeout))
}
pub fn settle(&mut self) -> &mut Self {
let (stable, timeout) = (self.timeouts.stable, self.timeouts.idle);
let op = label(
"settle",
&[format!("stable={stable:?}"), format!("timeout={timeout:?}")],
);
self.drive_wait(op, false, |s| s.wait_for_idle(stable, timeout))
}
pub fn wait_for_text(&mut self, text: &str) -> &mut Self {
let timeout = self.timeouts.text;
self.wait_for_text_within(text, timeout)
}
pub fn wait_for_text_within(&mut self, text: &str, timeout: Duration) -> &mut Self {
let op = label(
"wait_for_text",
&[quoted(text), format!("timeout={timeout:?}")],
);
self.drive_wait(op, true, |s| s.wait_for_text(text, timeout))
}
pub fn read_available(&mut self) -> &mut Self {
let timeout = self.timeouts.read;
self.read_available_within(timeout)
}
pub fn read_available_within(&mut self, timeout: Duration) -> &mut Self {
let op = label("read_available", &[format!("timeout={timeout:?}")]);
self.drive(op, |s| s.read_available(timeout))
}
pub fn wait_for_exit(&mut self) -> &mut Self {
let timeout = self.timeouts.exit;
self.wait_for_exit_within(timeout)
}
pub fn wait_for_exit_within(&mut self, timeout: Duration) -> &mut Self {
let op = label("wait_for_exit", &[format!("timeout={timeout:?}")]);
self.drive_wait(op, true, |s| Ok(s.wait_for_exit(timeout)?.is_some()))
}
pub fn close(&mut self) -> &mut Self {
let op = label("close", &[]);
self.drive(op, |s| s.close())
}
pub fn screen(&self) -> Result<&str, DriverError> {
self.check()?;
Ok(self.session.screen())
}
pub fn screen_contains(&self, needle: &str) -> Result<bool, DriverError> {
Ok(self.screen()?.contains(needle))
}
pub fn raw_output(&self) -> Result<&str, DriverError> {
self.check()?;
Ok(self.session.raw_output())
}
pub fn raw_contains(&self, needle: &str) -> Result<bool, DriverError> {
Ok(self.raw_output()?.contains(needle))
}
pub fn exit_code(&self) -> Result<Option<i32>, DriverError> {
self.check()?;
Ok(self.session.exit_code())
}
pub fn is_alive(&mut self) -> Result<bool, DriverError> {
self.check()?;
Ok(self.session.is_alive())
}
pub fn expect_screen_contains(&self, needle: &str) -> Result<(), DriverError> {
let screen = self.screen()?;
if screen.contains(needle) {
return Ok(());
}
Err(DriverError::Expectation {
expectation: format!(
"expected the screen to contain {}, but it is absent",
quoted(needle)
),
screen: screen.to_string(),
})
}
pub fn expect_screen_lacks(&self, needle: &str) -> Result<(), DriverError> {
let screen = self.screen()?;
if !screen.contains(needle) {
return Ok(());
}
Err(DriverError::Expectation {
expectation: format!(
"expected the screen not to contain {}, but it is present",
quoted(needle)
),
screen: screen.to_string(),
})
}
pub fn session(&self) -> &dyn Session {
self.session.as_ref()
}
pub fn session_mut(&mut self) -> &mut dyn Session {
self.session.as_mut()
}
pub fn into_inner(self) -> Box<dyn Session> {
self.session
}
pub fn finish(self) -> Result<Box<dyn Session>, DriverError> {
match self.failure {
Some(err) => Err(err),
None => Ok(self.session),
}
}
}
fn quoted(text: &str) -> String {
let mut out = String::with_capacity(text.len() + 2);
out.push('"');
for (i, ch) in text.chars().enumerate() {
if i == MAX_LABEL_ARG {
out.push('…');
break;
}
match ch {
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
'"' => out.push_str("\\\""),
c if c.is_control() => {
let _ = write!(out, "\\u{{{:02x}}}", c as u32);
}
c => out.push(c),
}
}
out.push('"');
out
}
fn label(name: &str, args: &[String]) -> String {
format!("{name}({})", args.join(", "))
}