use std::future::IntoFuture;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use futures_util::FutureExt;
use laravel::Application;
use laravel::config::Env;
use laravel::console::{Choice, Console, PromptError, clap};
use laravel::testing::MakesConsoleRequests;
#[derive(clap::Parser)]
#[command(name = "markup")]
struct Markup {
text: String,
}
#[laravel::console::command]
impl Markup {
async fn handle(self, console: &mut Console) {
console.markup(&self.text);
}
}
#[tokio::test]
async fn markup_capture_removes_valid_styles_and_preserves_literal_and_invalid_tags() {
let application = Application::configure()
.replace_env(Env::default())
.with_commands(|commands, _| {
commands.add::<Markup>();
})
.create();
for (input, expected) in [
(
"<fg=red>red <bg=cyan;options=bold,underscore>nested</> restored</> plain",
"red nested restored plain",
),
(
"<fg=sky-400>Sky</> <fg=emerald-400;options=bold>Ready</> <bg=#abc;fg=#123456>Hex</>",
"Sky Ready Hex",
),
(
"<fg=red>outer <fg=unknown>literal</> restored</>",
"outer <fg=unknown>literal</> restored",
),
(
"<fg=red;fg=blue>duplicate</> <options=oops>bad</>",
"<fg=red;fg=blue>duplicate</> <options=oops>bad</>",
),
("</> <fg=red>unclosed", "</> unclosed"),
("<fg=red", "<fg=red"),
(r"\<fg=red>literal\</> \\ path\name", r"<fg=red>literal</> \ path\name"),
("<fg=red>雪 🦀\n\tline</>\x1b[31m raw\x1b[0m\x07", "雪 🦀\n\tline raw"),
] {
let result = application.command_args(["markup", input]).await;
result.assert_successful();
assert_eq!(result.output(), format!("{expected}\n"), "{input}");
assert_eq!(result.error_output(), "");
}
let untrusted = "Taylor\\</><options=conceal>hidden</>\x1b[2J\x07";
let result = application
.command_args([
"markup",
&format!("<fg=red>{}</>", laravel::console::escape_markup(untrusted)),
])
.await;
assert_eq!(result.output(), "Taylor\\</><options=conceal>hidden</>\n");
}
#[derive(clap::Parser)]
#[command(name = "describe")]
struct Describe {
#[arg(long)]
label_default: bool,
}
#[laravel::console::command]
impl Describe {
async fn handle(self, console: &mut Console) -> laravel::Result<()> {
let description = console
.ask("Description?")
.multiline()
.placeholder("Tell us about the project")
.required(true)
.default("First line\nSecond line")
.validate(|value: &String| {
if value.lines().count() >= 2 {
Ok(())
} else {
Err("Use at least two lines.")
}
})
.await?;
let environment = console
.choice(
"Environment?",
[
Choice::new("production".to_owned(), "Production").hint("Live traffic"),
Choice::new("staging".to_owned(), "Staging").hint("Test traffic"),
],
)
.searchable()
.default(if self.label_default { "Staging" } else { "staging" })
.validate(|value: &String| {
assert!(matches!(value.as_str(), "staging" | "production"));
Ok::<_, String>(())
})
.await?;
let targets = console
.multiselect(
"Targets?",
[
Choice::new("a", "Same label").hint("First"),
Choice::new("b", "Same label").hint("Second"),
],
)
.searchable()
.default(["b", "a"])
.await?;
console.line(format!("{description}\n{environment}: {}", targets.join(",")));
console.step("Saving configuration...");
console.success("Configuration saved.");
Ok(())
}
}
#[derive(clap::Parser)]
#[command(name = "present")]
struct Present {
#[arg(default_value = "success")]
outcome: String,
#[arg(long)]
grouped: bool,
}
#[laravel::console::command]
impl Present {
async fn handle(self, console: &mut Console) -> laravel::Result<()> {
if self.grouped {
let group = console.progress_group("Preparing...")?;
let assets = group.spinner("Assets...")?;
let mut records = group.progress(2, "Records...")?;
let (assets, records) = tokio::join!(
async move {
tokio::task::yield_now().await;
assert!(!laravel::config().app.name.is_empty());
assets
},
async move {
records.advance(u64::MAX);
assert_eq!(records.position(), 2);
assert_eq!(records.length(), Some(2));
records.message("Importing...").hint("Saving {records}");
tokio::task::yield_now().await;
records
}
);
records.finish("Records imported.")?;
match self.outcome.as_str() {
"success" => {
assets.finish("Assets built.")?;
group.finish("Ready.")?;
}
"cancel" => {
assets.cancel("Assets cancelled.")?;
group.cancel("Preparation cancelled.")?;
}
"fail" => {
assets.fail("Assets failed.")?;
group.fail("Preparation failed.")?;
}
"error" => return Err(std::io::Error::other("Build failed.").into()),
"panic" => panic!("Build panicked."),
"drop" => drop(assets),
"cancel-future" => {
let (started, ready) = tokio::sync::oneshot::channel();
let work = async move {
let _assets = assets;
started.send(()).unwrap();
std::future::pending::<()>().await;
};
tokio::select! {
() = work => unreachable!(),
_ = ready => {},
}
}
_ => unreachable!(),
}
} else {
let calls = Arc::new(AtomicUsize::new(0));
let invoked = Arc::clone(&calls);
let cancel_future = self.outcome == "cancel-future";
let work = || async move {
invoked.fetch_add(1, Ordering::Relaxed);
assert!(!laravel::config().app.name.is_empty());
tokio::task::yield_now().await;
match self.outcome.as_str() {
"success" => Ok(42),
"error" => Err(std::io::Error::other("Build failed.").into()),
"cancel" => Err(PromptError::Cancelled.into()),
"panic" => panic!("Build panicked."),
"cancel-future" => std::future::pending().await,
_ => unreachable!(),
}
};
if cancel_future {
let mut spin = Box::pin(console.spin("Preparing...", work));
assert!(spin.as_mut().now_or_never().is_none());
drop(spin);
} else {
let value = console.spin("Preparing...", work).await?;
console.line(format!("Value: {value}"));
}
assert_eq!(calls.load(Ordering::Relaxed), 1);
}
Ok(())
}
}
fn app() -> Application {
Application::configure()
.replace_env(Env::default())
.with_commands(|commands, _| {
commands.add::<Describe>().add::<Present>().add::<ProcessItems>();
})
.create()
}
#[tokio::test]
async fn multiline_and_menu_values_work_with_defaults_and_scripted_answers() {
let application = app();
let defaults = application.command("describe -n").await;
let scripted = application
.command("describe")
.expects_question("Description?", "First line\nSecond line")
.expects_choice("Environment?", "staging")
.expects_multiselect("Targets?", ["b", "a"])
.await;
for result in [&defaults, &scripted] {
result.assert_successful();
assert_eq!(result.output(), "First line\nSecond line\nstaging: a,b\n");
assert_eq!(result.error_output(), "Saving configuration...\nConfiguration saved.\n");
}
}
#[tokio::test]
async fn menu_defaults_use_values_not_labels() {
app()
.command("describe -n --label-default")
.await
.assert_failed()
.assert_error_output_contains("isn't an option");
}
#[tokio::test]
async fn multiline_scripted_answers_are_validated() {
let command = app()
.command("describe")
.expects_question("Description?", "Just one line");
assert!(
std::panic::AssertUnwindSafe(command.into_future())
.catch_unwind()
.await
.is_err()
);
}
#[tokio::test]
async fn groups_capture_concurrent_work_and_explicit_outcomes_without_animation() {
for (outcome, message) in [
("success", "Ready."),
("cancel", "Preparation cancelled."),
("fail", "Preparation failed."),
] {
let result = app().command(&format!("present {outcome} --grouped -n")).await;
result.assert_successful();
assert!(
result
.error_output()
.starts_with("Preparing...\nAssets...\nRecords...\nRecords imported.\n")
);
assert!(result.error_output().ends_with(&format!("{message}\n")));
assert!(!result.error_output().contains('\x1b'));
}
}
#[tokio::test]
async fn groups_clean_up_children_and_heading_on_error_panic_or_cancellation() {
for outcome in ["error", "panic", "drop", "cancel-future"] {
let result = app().command(&format!("present {outcome} --grouped")).await;
result.assert_exit_code(if matches!(outcome, "error" | "panic") { 1 } else { 0 });
result.assert_error_output_contains("Cancelled: Assets...\nCancelled: Preparing...\n");
}
}
#[tokio::test]
async fn spin_returns_the_value_and_original_error_and_cleans_up_other_exits() {
let success = app().command("present -n").await;
success.assert_successful().assert_output_contains("Value: 42");
assert_eq!(success.error_output(), "Preparing...\nPreparing...\n");
let failed = app().command("present error").await;
failed
.assert_exit_code(1)
.assert_error_output_contains("Failed: Preparing...\n");
failed.assert_error_output_contains("Build failed.");
let cancelled = app().command("present cancel").await;
cancelled.assert_exit_code(130);
assert_eq!(cancelled.error_output(), "Preparing...\nCancelled: Preparing...\n");
for outcome in ["panic", "cancel-future"] {
let result = app().command(&format!("present {outcome}")).await;
result.assert_exit_code(if outcome == "panic" { 1 } else { 0 });
result.assert_error_output_contains("Preparing...\nCancelled: Preparing...\n");
}
}
#[derive(clap::Parser)]
#[command(name = "process-items")]
struct ProcessItems {
#[arg(default_value = "success")]
outcome: String,
#[arg(long)]
empty: bool,
}
#[laravel::console::command]
impl ProcessItems {
async fn handle(self, console: &mut Console) -> laravel::Result<()> {
use std::sync::Mutex;
let seen = Arc::new(Mutex::new(Vec::new()));
let failed_update = Arc::new(Mutex::new(None::<laravel::console::ProgressUpdate>));
let total = if self.empty { 0usize } else { 3 };
let work = console.progress_each("Updating users", 0..total, |item, mut progress| {
let seen = Arc::clone(&seen);
let failed_update = Arc::clone(&failed_update);
let outcome = &self.outcome;
async move {
assert!(!laravel::config().app.name.is_empty());
assert_eq!(progress.length(), Some(total as u64));
assert_eq!(progress.position(), item as u64);
seen.lock().unwrap().push(item);
progress
.message(format!("Updating user {item}"))
.hint("Saving {profile}");
tokio::task::yield_now().await;
match (outcome.as_str(), item) {
("error", 1) => {
*failed_update.lock().unwrap() = Some(progress);
return Err(std::io::Error::other("User update failed.").into());
}
("cancel", 1) => {
*failed_update.lock().unwrap() = Some(progress);
return Err(PromptError::Cancelled.into());
}
("panic", 1) => panic!("User update panicked."),
("cancel-future", _) => std::future::pending::<()>().await,
_ => {}
}
Ok((item * 10, progress))
}
});
if self.outcome == "cancel-future" {
let mut work = Box::pin(work);
assert!(work.as_mut().now_or_never().is_none());
drop(work);
assert_eq!(*seen.lock().unwrap(), [0]);
return Ok(());
}
let result = work.await;
match result {
Ok(results) => {
assert_eq!(*seen.lock().unwrap(), (0..total).collect::<Vec<_>>());
let values = results
.into_iter()
.map(|(value, mut progress)| {
assert_eq!(progress.position(), total as u64);
let before = format!("{progress:?}");
progress.message("Late update").hint("Should not appear");
assert_eq!(format!("{progress:?}"), before);
value.to_string()
})
.collect::<Vec<_>>();
console.line(values.join(","));
Ok(())
}
Err(error) => {
assert_eq!(*seen.lock().unwrap(), [0, 1]);
let progress = failed_update.lock().unwrap().take().unwrap();
assert_eq!(progress.position(), 1);
if self.outcome == "error" {
assert!(error.is::<std::io::Error>());
} else {
assert!(error.is::<PromptError>());
}
Err(error)
}
}
}
}
#[tokio::test]
async fn progress_each_maps_in_order_and_advances_only_after_success() {
let result = app().command("process-items -n").await;
result.assert_successful();
assert_eq!(result.output(), "0,10,20\n");
assert_eq!(result.error_output(), "Updating users\nUpdating users\n");
let empty = app().command("process-items --empty").await;
empty.assert_successful();
assert_eq!(empty.output(), "\n");
assert_eq!(empty.error_output(), "Updating users\nUpdating users\n");
}
#[tokio::test]
async fn progress_each_stops_on_error_or_cancellation_and_returns_the_original_error() {
for (outcome, status, message) in [
("error", 1, "Failed: Updating user 1"),
("cancel", 130, "Cancelled: Updating user 1"),
] {
app()
.command(&format!("process-items {outcome}"))
.await
.assert_exit_code(status)
.assert_error_output_contains(message);
}
}
#[tokio::test]
async fn progress_each_cleans_up_after_a_panic_or_dropped_future() {
for (outcome, status, item) in [("panic", 1, 1), ("cancel-future", 0, 0)] {
app()
.command(&format!("process-items {outcome}"))
.await
.assert_exit_code(status)
.assert_error_output_contains(&format!("Cancelled: Updating user {item}"));
}
}