use std::future::IntoFuture;
use std::panic::AssertUnwindSafe;
use std::time::Duration;
use futures_util::FutureExt;
use laravel::Application;
use laravel::config::Env;
use laravel::console::{Console, clap};
use laravel::testing::MakesConsoleRequests;
#[derive(clap::Parser)]
#[command(name = "profile")]
struct Profile;
#[laravel::console::command]
impl Profile {
async fn handle(self, console: &mut Console) -> laravel::Result<()> {
let name = console
.ask("Name?")
.placeholder("Taylor")
.required(true)
.autocomplete(["Taylor", "Jess"])
.default("Taylor")
.validate(|name: &String| {
if name.len() < 3 {
Err("Use at least three characters.")
} else {
Ok(())
}
})
.await?;
let password = console
.password("Password?")
.required(true)
.default("default-secret")
.validate(|password: &String| {
if password.len() < 8 {
Err("Use at least eight characters.")
} else {
Ok(())
}
})
.await?;
assert!(password.len() >= 8);
let queue = console
.choice("Queue?", ["default", "high"])
.searchable()
.default("default")
.await?;
let roles = console
.multiselect("Roles?", ["admin", "editor", "viewer"])
.searchable()
.default(["editor"])
.validate(|roles: &[String]| {
if roles.len() > 2 {
Err("Select at most two roles.")
} else {
Ok(())
}
})
.await?;
let mood = console
.ask("Mood?")
.autocomplete(|query: &str| {
["Curious", "Focused"]
.into_iter()
.filter(|mood| mood.to_lowercase().contains(&query.to_lowercase()))
.map(str::to_owned)
.collect()
})
.default("Curious")
.await?;
console.note("Profile", format!("{name}: {queue}, {}, {mood}", roles.join(",")));
console.line("Saved.");
Ok(())
}
}
#[derive(clap::Parser)]
#[command(name = "input")]
struct Input {
kind: String,
#[arg(long)]
default: Option<String>,
#[arg(long)]
required: bool,
#[arg(long)]
invalid_configuration: bool,
}
#[laravel::console::command]
impl Input {
async fn handle(self, console: &mut Console) -> laravel::Result<()> {
let reject_invalid = |value: &String| {
if value == "invalid" {
Err("Value was rejected.")
} else {
Ok(())
}
};
match self.kind.as_str() {
"text" => {
let mut prompt = console.ask("Value?").required(self.required).validate(reject_invalid);
if let Some(default) = self.default {
prompt = prompt.default(default);
}
if self.invalid_configuration {
prompt = prompt.multiline().autocomplete(["valid"]);
}
let value = prompt.await?;
console.line(format!("Accepted {} characters.", value.len()));
}
"password" => {
let mut prompt = console
.password("Value?")
.required(self.required)
.validate(reject_invalid);
if let Some(default) = self.default {
prompt = prompt.default(default);
}
let value = prompt.await?;
console.line(format!("Accepted {} characters.", value.len()));
}
"confirm" => {
let mut prompt = console.confirm("Accept?").required(self.required);
if let Some(default) = self.default {
prompt = prompt.default(default == "yes");
}
let accepted = prompt.await?;
console.line(format!("Accepted: {accepted}"));
}
"multiple" => {
let mut prompt = console.multiselect("Values?", ["one", "two"]).required(self.required);
if let Some(default) = self.default {
prompt = prompt.default(if default.is_empty() {
vec![]
} else {
default.split(',').collect()
});
}
let values = prompt.await?;
console.line(values.join(","));
}
_ => unreachable!(),
}
Ok(())
}
}
#[derive(clap::Parser)]
#[command(name = "activity")]
struct Activity {
#[arg(default_value = "finish")]
outcome: String,
#[arg(long)]
spinner: bool,
}
#[laravel::console::command]
impl Activity {
async fn handle(self, console: &mut Console) -> laravel::Result<()> {
let shutdown = console.shutdown();
assert!(tokio::time::timeout(Duration::from_millis(1), shutdown).await.is_err());
let mut progress = if self.spinner {
console.spinner("Starting...")?
} else {
console.progress(3, "Starting...")?
};
progress.advance(1);
progress.advance(u64::MAX);
let position = progress.position();
assert_eq!(progress.length(), if self.spinner { None } else { Some(3) });
progress.message("Working...").hint("A temporary hint").hint("");
match self.outcome.as_str() {
"finish" => progress.finish("Done.")?,
"cancel" => progress.cancel("Cancelled explicitly.")?,
"fail" => progress.fail("Failed explicitly.")?,
"error" => return Err(std::io::Error::other("Work failed.").into()),
"panic" => panic!("Work panicked."),
"drop" => drop(progress),
"cancel-future" => {
let (started, ready) = tokio::sync::oneshot::channel();
let work = async move {
let _progress = progress;
started.send(()).unwrap();
std::future::pending::<()>().await;
};
tokio::select! {
() = work => unreachable!(),
_ = ready => {},
}
}
_ => unreachable!(),
}
console.line(format!("Completed count: {position}"));
Ok(())
}
}
fn app() -> Application {
Application::configure()
.replace_env(Env::default())
.with_commands(|commands, _| {
commands.add::<Profile>().add::<Input>().add::<Activity>();
})
.create()
}
#[tokio::test]
async fn extended_prompts_use_scripted_answers_and_keep_secrets_out_of_output() {
let command = app()
.command("profile")
.expects_question("Name?", "Jess")
.expects_password("Password?", "scripted-secret")
.expects_choice("Queue?", "high")
.expects_multiselect("Roles?", ["admin", "viewer"])
.expects_question("Mood?", "Focused");
assert!(!format!("{command:?}").contains("scripted-secret"));
let result = command.await;
result.assert_successful().assert_output_contains("Saved.");
assert_eq!(result.error_output(), "Profile\nJess: high, admin,viewer, Focused\n");
assert!(!result.error_output().contains("secret"));
assert_eq!(result.questions(), ["Name?", "Password?", "Queue?", "Roles?", "Mood?"]);
}
#[tokio::test]
async fn all_extended_prompts_have_consistent_noninteractive_defaults() {
for command in ["profile", "profile -n"] {
let result = app().command(command).await;
result.assert_successful();
assert_eq!(result.error_output(), "Profile\nTaylor: default, editor, Curious\n");
assert!(!format!("{result:?}").contains("default-secret"));
}
for kind in ["text", "password", "multiple"] {
app()
.command(&format!("input {kind} -n"))
.await
.assert_failed()
.assert_error_output_contains("supply a default");
}
}
#[tokio::test]
async fn empty_input_and_selections_can_be_allowed_or_required() {
for kind in ["text", "password", "multiple"] {
app()
.command(&format!("input {kind} --default='' -n"))
.await
.assert_successful();
app()
.command(&format!("input {kind} --default='' --required -n"))
.await
.assert_failed()
.assert_error_output_contains("input required");
}
app()
.command("input text --default=' ' --required -n")
.await
.assert_failed()
.assert_error_output_contains("input required");
app()
.command("input multiple")
.expects_multiselect("Values?", Vec::<String>::new())
.await
.assert_successful();
}
#[tokio::test]
async fn empty_scripted_text_answers_use_the_default_as_enter_does() {
app()
.command("input text --default=fallback --required")
.expects_question("Value?", "")
.await
.assert_successful()
.assert_output_contains("Accepted 8 characters.");
app()
.command("input password --default=fallback --required")
.expects_password("Value?", "")
.await
.assert_successful()
.assert_output_contains("Accepted 8 characters.");
app()
.command("input text")
.expects_question("Value?", "")
.await
.assert_successful()
.assert_output_contains("Accepted 0 characters.");
}
#[tokio::test]
async fn required_confirmations_must_be_accepted() {
app()
.command("input confirm --default=no -n")
.await
.assert_successful()
.assert_output_contains("Accepted: false");
app()
.command("input confirm --default=no --required -n")
.await
.assert_failed()
.assert_error_output_contains("input required");
app()
.command("input confirm --required")
.expects_confirmation("Accept?", true)
.await
.assert_successful()
.assert_output_contains("Accepted: true");
let declined = app()
.command("input confirm --required")
.expects_confirmation("Accept?", false);
assert!(AssertUnwindSafe(declined.into_future()).catch_unwind().await.is_err());
}
#[tokio::test]
async fn defaults_must_pass_validation_and_match_menu_values() {
for kind in ["text", "password"] {
app()
.command(&format!("input {kind} --default=invalid -n"))
.await
.assert_failed()
.assert_error_output_contains("Value was rejected");
}
app()
.command("input multiple --default=missing -n")
.await
.assert_failed()
.assert_error_output_contains("isn't an option");
app()
.command("input multiple --default=one,one -n")
.await
.assert_failed()
.assert_error_output_contains("more than once");
app()
.command("input text --default=valid --invalid-configuration -n")
.await
.assert_failed()
.assert_error_output_contains("multiline input can't use autocomplete");
}
#[tokio::test]
async fn multiselect_defaults_and_scripted_answers_follow_menu_order() {
let application = app();
let defaults = application.command("input multiple --default=two,one -n").await;
let scripted = application
.command("input multiple")
.expects_multiselect("Values?", ["two", "one"])
.await;
defaults.assert_successful();
scripted.assert_successful();
assert_eq!(defaults.output(), "one,two\n");
assert_eq!(scripted.output(), defaults.output());
}
#[tokio::test]
async fn rejected_scripted_answers_fail_even_if_the_command_error_is_expected() {
for command in [
app().command("input text").expects_question("Value?", "invalid"),
app().command("input password").expects_password("Value?", "invalid"),
app()
.command("input multiple")
.expects_multiselect("Values?", ["missing"]),
app()
.command("input multiple")
.expects_multiselect("Values?", ["one", "one"]),
app()
.command("input multiple --required")
.expects_multiselect("Values?", Vec::<String>::new()),
] {
assert!(AssertUnwindSafe(command.into_future()).catch_unwind().await.is_err());
}
}
#[tokio::test]
async fn unused_password_expectations_are_redacted_from_failure_diagnostics() {
let panic = AssertUnwindSafe(
app()
.command("list")
.expects_password("Password?", "never-print-this")
.into_future(),
)
.catch_unwind()
.await
.unwrap_err();
let message = panic.downcast_ref::<String>().unwrap();
assert!(message.contains("didn't ask"));
assert!(!message.contains("never-print-this"));
}
#[tokio::test]
async fn password_prompt_defaults_are_redacted_from_debug_output() {
#[derive(clap::Parser)]
#[command(name = "debug-password")]
struct DebugPassword;
#[laravel::console::command]
impl DebugPassword {
async fn handle(self, console: &mut Console) -> laravel::Result<()> {
let prompt = console.password("Password?").default("never-print-this");
assert!(!format!("{prompt:?}").contains("never-print-this"));
prompt.await?;
Ok(())
}
}
Application::configure()
.replace_env(Env::default())
.with_commands(|commands, _| {
commands.add::<DebugPassword>();
})
.create()
.command("debug-password")
.await
.assert_successful();
}
#[tokio::test]
async fn captured_progress_only_writes_start_and_finish_to_stderr() {
for suffix in ["", " --spinner", " -n"] {
let result = app().command(&format!("activity{suffix}")).await;
result.assert_successful();
assert_eq!(result.error_output(), "Starting...\nDone.\n");
assert_eq!(
result.output(),
if suffix.contains("spinner") {
"Completed count: 0\n"
} else {
"Completed count: 3\n"
}
);
}
for (outcome, message) in [("cancel", "Cancelled explicitly."), ("fail", "Failed explicitly.")] {
let result = app().command(&format!("activity {outcome}")).await;
result.assert_successful();
assert_eq!(result.error_output(), format!("Starting...\n{message}\n"));
}
}
#[tokio::test]
async fn progress_is_cleaned_up_on_errors_panics_and_dropped_work() {
for outcome in ["drop", "cancel-future", "error", "panic"] {
let result = app().command(&format!("activity {outcome}")).await;
result.assert_exit_code(if matches!(outcome, "error" | "panic") { 1 } else { 0 });
assert!(
result
.error_output()
.starts_with("Starting...\nCancelled: Working...\n")
);
assert!(!result.error_output().contains('\x1b'));
}
}