use crate::console::ConsoleInternals as _;
use std::ffi::OsString;
use std::future::{Future, IntoFuture};
use std::panic::Location;
use std::pin::Pin;
use crate::Application;
use crate::console::{Answer, ChoiceAnswer, Console, ExpectedPrompt, Signal};
pub trait MakesConsoleRequests {
#[track_caller]
fn command(&self, command: &str) -> TestCommand;
#[track_caller]
fn command_args<I, S>(&self, arguments: I) -> TestCommand
where
I: IntoIterator<Item = S>,
S: Into<OsString>;
}
impl MakesConsoleRequests for Application {
#[track_caller]
fn command(&self, command: &str) -> TestCommand {
let Some(arguments) = shlex::split(command) else {
panic!("`{command}` has an unmatched quote or escape");
};
TestCommand::new(self, arguments.into_iter().map(OsString::from).collect())
}
#[track_caller]
fn command_args<I, S>(&self, arguments: I) -> TestCommand
where
I: IntoIterator<Item = S>,
S: Into<OsString>,
{
TestCommand::new(self, arguments.into_iter().map(Into::into).collect())
}
}
#[derive(Debug)]
#[must_use = "a test command does nothing unless awaited"]
pub struct TestCommand {
application: Application,
arguments: Vec<OsString>,
prompts: Vec<ExpectedPrompt>,
signals: Vec<Signal>,
location: &'static Location<'static>,
}
impl TestCommand {
#[track_caller]
fn new(application: &Application, arguments: Vec<OsString>) -> Self {
Self {
application: application.clone(),
arguments,
prompts: Vec::new(),
signals: Vec::new(),
location: Location::caller(),
}
}
pub fn expects_question(self, question: impl Into<String>, answer: impl Into<String>) -> Self {
self.expect(question.into(), Answer::Text(answer.into()))
}
pub fn expects_confirmation(self, question: impl Into<String>, answer: bool) -> Self {
self.expect(question.into(), Answer::Confirmation(answer))
}
pub fn expects_choice<T: Send + 'static>(self, question: impl Into<String>, answer: T) -> Self {
self.expect(question.into(), Answer::Choice(ChoiceAnswer::new(answer)))
}
pub fn expects_multiselect<I, S>(self, question: impl Into<String>, answers: I) -> Self
where
I: IntoIterator<Item = S>,
S: Send + 'static,
{
self.expect(
question.into(),
Answer::Multiple(ChoiceAnswer::new(answers.into_iter().collect::<Vec<S>>())),
)
}
pub fn expects_password(self, question: impl Into<String>, answer: impl Into<String>) -> Self {
self.expect(question.into(), Answer::Secret(answer.into()))
}
fn expect(mut self, question: String, answer: Answer) -> Self {
self.prompts.push(ExpectedPrompt { question, answer });
self
}
pub fn sends_signal(mut self, signal: Signal) -> Self {
self.signals.push(signal);
self
}
}
impl IntoFuture for TestCommand {
type Output = TestCommandResult;
type IntoFuture = Pin<Box<dyn Future<Output = TestCommandResult> + Send>>;
fn into_future(self) -> Self::IntoFuture {
Box::pin(async move {
let mut console = Console::captured();
console.expect_prompts(self.prompts);
console.signals.expect(self.signals);
let exit_code = self
.application
.run_command(OsString::from("app"), self.arguments, &mut console)
.await;
let mut unmet = console.unmet_prompts();
unmet.extend(console.signals.unmet());
let questions = std::mem::take(&mut console.questions);
let (output, error_output) = console.into_output();
let result = TestCommandResult {
exit_code,
output,
error_output,
questions,
};
assert!(
unmet.is_empty(),
"{}\n\n{}\n\nat {}",
unmet.join("\n"),
result.diagnostics(),
self.location
);
result
})
}
}
#[derive(Debug)]
pub struct TestCommandResult {
exit_code: u8,
output: String,
error_output: String,
questions: Vec<String>,
}
impl TestCommandResult {
#[must_use]
pub const fn exit_code(&self) -> u8 {
self.exit_code
}
#[must_use]
pub fn output(&self) -> &str {
&self.output
}
#[must_use]
pub fn error_output(&self) -> &str {
&self.error_output
}
#[must_use]
pub fn questions(&self) -> &[String] {
&self.questions
}
#[track_caller]
pub fn assert_exit_code(&self, expected: u8) -> &Self {
assert!(
self.exit_code == expected,
"expected exit code {expected}\n{}",
self.diagnostics()
);
self
}
#[track_caller]
pub fn assert_successful(&self) -> &Self {
self.assert_exit_code(0)
}
#[track_caller]
pub fn assert_failed(&self) -> &Self {
assert!(
self.exit_code != 0,
"expected the command to fail\n{}",
self.diagnostics()
);
self
}
#[track_caller]
pub fn assert_output_contains(&self, expected: &str) -> &Self {
assert!(
self.output.contains(expected),
"expected stdout to contain {expected:?}\n{}",
self.diagnostics()
);
self
}
#[track_caller]
pub fn assert_error_output_contains(&self, expected: &str) -> &Self {
assert!(
self.error_output.contains(expected),
"expected stderr to contain {expected:?}\n{}",
self.diagnostics()
);
self
}
#[track_caller]
pub fn assert_output_missing(&self, unexpected: &str) -> &Self {
assert!(
!self.output.contains(unexpected),
"expected stdout not to contain {unexpected:?}\n{}",
self.diagnostics()
);
self
}
#[track_caller]
pub fn assert_error_output_missing(&self, unexpected: &str) -> &Self {
assert!(
!self.error_output.contains(unexpected),
"expected stderr not to contain {unexpected:?}\n{}",
self.diagnostics()
);
self
}
#[track_caller]
pub fn assert_no_output(&self) -> &Self {
assert!(
self.output.is_empty() && self.error_output.is_empty(),
"expected no output\n{}",
self.diagnostics()
);
self
}
#[track_caller]
pub fn assert_asked(&self, question: &str) -> &Self {
assert!(
self.questions.iter().any(|asked| asked == question),
"expected question {question:?}; asked: {:?}\n{}",
self.questions,
self.diagnostics()
);
self
}
fn diagnostics(&self) -> String {
format!(
"exit code: {}\nstdout:\n{}\nstderr:\n{}",
self.exit_code, self.output, self.error_output
)
}
}