use std::future::IntoFuture;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use laravel::Application;
use laravel::config::{Config, Env};
use laravel::console::{Console, clap};
use laravel::container::{Inject, Registrar};
use laravel::foundation::ServiceProvider;
use laravel::testing::MakesConsoleRequests;
use crate::support::failure;
struct Mailer {
from: String,
}
struct Sequence(AtomicUsize);
#[derive(clap::Args)]
struct QueueOptions {
#[arg(long, default_value = "default")]
queue: String,
}
#[derive(clap::Parser)]
#[command(name = "mail:send", alias = "email:send")]
struct SendEmails {
user: u64,
#[command(flatten)]
options: QueueOptions,
}
type MailerDependency = Inject<Mailer>;
#[laravel::console::command]
impl SendEmails {
async fn handle(
self,
mailer: MailerDependency,
app: &Application,
console: &mut Console,
sequence: Inject<Sequence>,
) -> laravel::Result<()> {
let number = next_number().await;
assert_eq!(number, next_number().await);
console.info(format!(
"{}: user={} queue={} from={} app={}",
number,
self.user,
self.options.queue,
mailer.from,
laravel::config().app.name,
));
let resolved = laravel::resolve::<Sequence>().await?;
assert!(std::ptr::eq(&*sequence, &*resolved));
let resolved = app.resolve::<Mailer>().await;
assert!(std::ptr::eq(&*mailer, &*resolved));
assert!(std::ptr::eq(app.config(), &*laravel::config()));
Ok(())
}
}
#[derive(clap::Parser)]
#[command(name = "inspect:commands")]
struct InspectCommands;
#[laravel::console::command]
impl InspectCommands {
async fn handle(self, console: &mut Console, app: &laravel::Application) -> laravel::Result<()> {
let mut definition = laravel::console::commands();
console.line(&app.config().app.name);
for command in definition.get_subcommands() {
console.line(command.get_name());
}
let mail = definition.find_subcommand("email:send").expect("the alias resolves");
assert_eq!(mail.get_about().unwrap().to_string(), "Send marketing emails to a user");
assert!(
mail.get_arguments()
.any(|argument| argument.get_id() == "no-interaction")
);
assert!(mail.get_arguments().any(|argument| argument.get_id() == "queue"));
definition = definition.subcommand(clap::Command::new("local:only"));
assert!(definition.find_subcommand("local:only").is_some());
assert!(laravel::console::commands().find_subcommand("local:only").is_none());
let context = laravel::context::Context::current().unwrap();
tokio::spawn(context.scope(async {
assert!(
laravel::console::commands()
.find_subcommand("inspect:commands")
.is_some()
);
}))
.await?;
Ok(())
}
}
#[tokio::test]
async fn command_introspection_is_scoped_and_returns_detached_complete_metadata() {
let app = configure()
.with_commands(|commands, _| {
commands.add::<InspectCommands>();
})
.create();
app.command("inspect:commands")
.await
.assert_successful()
.assert_output_contains("mail:send")
.assert_output_contains("route:list")
.assert_output_contains("inspect:commands");
app.scope(async || {
let definition = laravel::console::commands();
assert_eq!(definition.get_name(), "app");
assert!(definition.find_subcommand("email:send").is_some());
})
.await;
}
#[tokio::test]
async fn concurrent_applications_have_separate_command_definitions() {
let first = configure()
.with_commands(|commands, _| {
commands.add::<InspectCommands>();
})
.create();
let second = Application::configure().replace_env(Env::default()).create();
tokio::join!(
first.scope(async || {
tokio::task::yield_now().await;
assert!(
laravel::console::commands()
.find_subcommand("inspect:commands")
.is_some()
);
first.command("inspect:commands").await.assert_successful();
}),
second.scope(async || {
tokio::task::yield_now().await;
assert!(
laravel::console::commands()
.find_subcommand("inspect:commands")
.is_none()
);
second.command("list").await.assert_successful();
}),
);
}
#[tokio::test]
async fn http_handlers_can_inspect_their_applications_commands() {
use laravel::testing::MakesHttpRequests;
async fn inspect() -> String {
laravel::console::commands()
.get_subcommands()
.map(clap::Command::get_name)
.collect::<Vec<_>>()
.join(",")
}
configure()
.with_routing(|routing, _| {
routing.api(|route| {
route.get("/commands", inspect);
});
})
.create()
.get("/api/commands")
.await
.assert_ok()
.assert_see("mail:send")
.assert_see("route:list");
}
#[test]
#[should_panic(expected = "laravel::console::commands()")]
fn command_introspection_requires_application_context() {
let _ = laravel::console::commands();
}
async fn next_number() -> usize {
laravel::once(|| async {
laravel::resolve::<Sequence>()
.await
.unwrap()
.0
.fetch_add(1, Ordering::SeqCst)
+ 1
})
.await
}
fn configure() -> laravel::foundation::ApplicationBuilder {
Application::configure()
.replace_env(Env::default())
.with_services(|services| {
services.instance(Mailer {
from: "booted@example.com".to_owned(),
});
services.instance(Sequence(AtomicUsize::new(0)));
})
.booted(|services| async move {
assert!(!services.resolve::<Mailer>().await.unwrap().from.is_empty());
})
.with_commands(|commands, _| {
commands.add::<SendEmails>();
})
}
#[tokio::test]
async fn typed_input_and_injected_services_run_after_boot() {
configure()
.with_config(|config, _| {
config.app.name = "Marketing".to_owned();
})
.create()
.command("mail:send 42 --queue=high")
.await
.assert_successful()
.assert_error_output_contains("1: user=42 queue=high from=booted@example.com app=Marketing");
}
#[tokio::test]
async fn defaults_aliases_and_fresh_contexts_share_the_booted_application() {
let app = configure().create();
app.command("email:send 1")
.await
.assert_successful()
.assert_error_output_contains("1: user=1 queue=default");
app.command("mail:send 2")
.await
.assert_successful()
.assert_error_output_contains("2: user=2 queue=default");
assert!(laravel::context::Context::current().is_none());
}
#[tokio::test]
async fn help_uses_descriptions_and_argument_docs_and_boots_without_resolving_handler_dependencies() {
let boots = Arc::new(AtomicUsize::new(0));
let counter = Arc::clone(&boots);
let app = Application::configure()
.replace_env(Env::default())
.booted(move |_| async move {
counter.fetch_add(1, Ordering::SeqCst);
})
.with_commands(|commands, _| {
commands.add::<SendEmails>();
})
.create();
app.command("mail:send --help")
.await
.assert_successful()
.assert_output_contains("Send marketing emails to a user")
.assert_output_contains("The user to send to");
assert_eq!(boots.load(Ordering::SeqCst), 1);
}
#[tokio::test]
async fn missing_services_are_errors_and_are_reported() {
let reports = Arc::new(AtomicUsize::new(0));
let counter = Arc::clone(&reports);
let app = Application::configure()
.replace_env(Env::default())
.with_commands(|commands, _| {
commands.add::<SendEmails>();
})
.with_errors(move |errors, _| {
errors.report_all(move |_| {
counter.fetch_add(1, Ordering::SeqCst);
});
})
.create();
let result = app.command("mail:send 42").await;
result
.assert_exit_code(1)
.assert_error_output_contains("Mailer")
.assert_error_output_contains("register it");
assert!(result.output().is_empty());
assert_eq!(reports.load(Ordering::SeqCst), 1);
}
#[tokio::test]
async fn boot_failures_prevent_execution_and_help() {
let boots = Arc::new(AtomicUsize::new(0));
let counter = Arc::clone(&boots);
let app = Application::configure()
.replace_env(Env::default())
.booted(move |_| {
counter.fetch_add(1, Ordering::SeqCst);
async { Err(std::io::Error::other("database unavailable").into()) }
})
.with_commands(|commands, _| {
commands.add::<SendEmails>();
})
.create();
for command in [
"mail:send 42",
"mail:send --help",
"list",
"help mail:send",
"route:list --json",
"key:generate --show",
"serve --help",
"--help",
"mail:send not-a-number",
"mail:send",
"mail:send 42 --unknown",
"unknown",
] {
let result = app.command(command).await;
result
.assert_exit_code(1)
.assert_error_output_contains("database unavailable");
assert!(result.output().is_empty());
}
assert_eq!(boots.load(Ordering::SeqCst), 1);
}
#[tokio::test]
async fn failing_factories_fail_only_the_commands_that_use_them() {
let builds = Arc::new(AtomicUsize::new(0));
let counter = Arc::clone(&builds);
let app = Application::configure()
.replace_env(Env::default())
.with_services(move |services| {
services.singleton(move |_| {
counter.fetch_add(1, Ordering::SeqCst);
async { Err::<Mailer, _>(std::io::Error::other("database unavailable").into()) }
});
services.instance(Sequence(AtomicUsize::new(0)));
})
.with_commands(|commands, _| {
commands.add::<SendEmails>();
})
.create();
for _ in 0..2 {
app.command("mail:send 42")
.await
.assert_exit_code(1)
.assert_error_output_contains("database unavailable");
}
app.command("list").await.assert_successful();
assert_eq!(builds.load(Ordering::SeqCst), 2, "a failed build is tried again");
}
#[tokio::test]
async fn builtins_and_custom_commands_share_help_and_listings() {
let app = configure().create();
for invocation in ["list", "help", "--help", "-h"] {
let result = app.command(invocation).await;
result
.assert_successful()
.assert_output_contains("mail:send")
.assert_output_contains("Send marketing emails to a user")
.assert_output_contains("route:list")
.assert_output_contains("key:generate")
.assert_output_contains("serve");
assert!(
result
.output()
.starts_with(&format!("Laravel for Rust {}\n\n", laravel::VERSION)),
"{invocation}"
);
assert_eq!(result.output().matches("mail:send").count(), 1);
assert!(!result.output().contains('\x1b'));
assert!(result.error_output().is_empty());
}
for invocation in ["--version", "-V", "-v --version"] {
let result = app.command(invocation).await;
result.assert_successful();
assert_eq!(
result.output(),
format!("Laravel for Rust {}\n", laravel::VERSION),
"{invocation}"
);
}
for name in [
"mail:send",
"email:send",
"route:list",
"key:generate",
"cache:clear",
"cache:prune",
"schedule:list",
"schedule:run",
"schedule:work",
"schedule:clear-cache",
"schedule:interrupt",
"serve",
"list",
"help",
] {
let help = app.command_args(["help", name]).await;
help.assert_successful();
let direct = app.command_args([name, "--help"]).await;
direct.assert_successful();
assert_eq!(help.output(), direct.output(), "{name}");
let short = app.command_args([name, "-h"]).await;
short.assert_successful();
assert_eq!(help.output(), short.output(), "{name}");
}
app.command("help missing")
.await
.assert_exit_code(2)
.assert_error_output_contains("missing");
}
mod listing_commands {
#[laravel::console::command("reports:cache:refresh", visible_alias = "refresh-reports")]
pub async fn refresh() {}
#[laravel::console::command("reports:build")]
pub async fn build() {}
#[laravel::console::command("zebra")]
pub async fn zebra() {}
#[laravel::console::command("alpha")]
pub async fn alpha() {}
#[laravel::console::command("reports:private", hide = true)]
pub async fn private() {}
}
#[tokio::test]
async fn listings_sort_commands_under_their_first_namespace_and_hide_private_commands() {
let app = configure()
.with_commands(|commands, _| {
commands.add::<listing_commands::refresh>();
commands.add::<listing_commands::zebra>();
commands.add::<listing_commands::private>();
commands.add::<listing_commands::build>();
commands.add::<listing_commands::alpha>();
})
.create();
let mut expected = vec![
"alpha",
"help",
"list",
"migrate",
"serve",
"zebra",
"cache",
"cache:clear",
"cache:prune",
"db",
"db:seed",
"feature",
"feature:purge",
"key",
"key:generate",
"mail",
"mail:send",
"make",
"make:migration",
"migrate",
"migrate:fresh",
"migrate:status",
"queue",
"queue:clear",
"queue:continue",
"queue:failed",
"queue:flush",
"queue:forget",
"queue:pause",
"queue:prune-batches",
"queue:restart",
"queue:retry",
"queue:retry-batch",
"queue:work",
"reports",
"reports:build",
"reports:cache:refresh",
"reverb",
"reverb:start",
"route",
"route:list",
"schedule",
"schedule:clear-cache",
"schedule:interrupt",
"schedule:list",
"schedule:run",
"schedule:work",
"schema",
"schema:dump",
"search",
"search:delete-index",
"search:flush",
"search:import",
"search:index",
"workflow",
"workflow:cancel",
"workflow:list",
"workflow:prune",
"workflow:recover",
"workflow:retry",
"workflow:show",
];
expected.retain(|name| {
cfg!(feature = "database")
|| ![
"db",
"db:seed",
"make",
"make:migration",
"migrate",
"migrate:fresh",
"migrate:status",
"queue:failed",
"queue:flush",
"queue:forget",
"queue:prune-batches",
"queue:retry",
"queue:retry-batch",
]
.contains(name)
});
expected.retain(|name| cfg!(feature = "search") || !name.starts_with("search"));
expected.retain(|name| cfg!(feature = "reverb") || !name.starts_with("reverb"));
for invocation in ["list", "help", "--help", "-h"] {
let result = app.command(invocation).await;
result.assert_successful();
let listing = result.output().split_once("Commands:\n").unwrap().1;
let names: Vec<_> = listing
.lines()
.filter_map(|line| line.split_whitespace().next())
.collect();
assert_eq!(names, expected, "{invocation}");
assert!(listing.contains("Refresh cached reports [aliases: refresh-reports]"));
assert!(!listing.contains("reports:private"));
assert!(!result.output().contains('\x1b'));
assert!(result.error_output().is_empty());
}
app.command("reports:private").await.assert_successful();
app.command("refresh-reports").await.assert_successful();
}
#[tokio::test]
async fn builtin_arguments_are_typed_and_validated() {
let app = configure().create();
for command in [
"route:list --unknown",
"route:list --path",
"route:list --json=yes",
"key:generate --unknown",
"key:generate --show=yes",
"serve --port=invalid",
"serve --port=65536",
"serve --host",
"serve --unknown",
"list --unknown",
"help serve extra",
"unknown",
] {
let result = app.command(command).await;
result.assert_exit_code(2);
assert!(result.output().is_empty(), "{command}");
assert!(!result.error_output().is_empty(), "{command}");
}
}
async fn users() -> &'static str {
"users"
}
async fn posts() -> &'static str {
"posts"
}
#[tokio::test]
async fn routes_are_listed_and_filtered_through_the_command_client() {
let app = configure()
.with_routing(|routing, _| {
routing.api(|route| {
route.get("/users", users);
route
.post("/posts", posts)
.middleware(laravel::http::middleware::LimitBody::bytes(1024));
});
})
.create();
let result = app.command("route:list --json").await;
result.assert_successful();
assert_eq!(result.output().lines().count(), 1);
assert!(result.error_output().is_empty());
let routes: Vec<serde_json::Value> = serde_json::from_str(result.output()).unwrap();
assert_eq!(routes.len(), 3, "the app's two routes and the workflow resume route");
let result = app.command("route:list --json --path=users --handler=users").await;
result.assert_successful();
let routes: Vec<serde_json::Value> = serde_json::from_str(result.output()).unwrap();
assert_eq!(routes.len(), 1);
assert_eq!(routes[0]["uri"], "/api/users");
assert_eq!(routes[0]["methods"], serde_json::json!(["GET", "HEAD"]));
let plain = app.command("route:list").await;
plain.assert_successful();
assert!(plain.output().contains("Method"));
assert!(!plain.output().contains("Domain"));
assert!(!plain.output().contains('┌'));
assert!(!plain.output().contains('│'));
assert!(!plain.output().contains("⇂"));
assert!(!plain.output().contains('\x1b'));
assert!(plain.error_output().is_empty());
assert_eq!(plain.output().lines().count(), 4, "{}", plain.output());
let verbose = app.command("route:list -v --path=posts").await;
verbose.assert_successful();
verbose
.assert_output_contains("POST")
.assert_output_contains("/api/posts")
.assert_output_contains("⇂ LimitBody");
assert!(verbose.output().ends_with("⇂ LimitBody\n"), "{}", verbose.output());
assert!(!verbose.output().contains("laravel::http::middleware"));
app.command("route:list -vv --path=posts")
.await
.assert_output_contains("laravel::http::middleware");
for command in [
"-vv route:list --path=posts",
"route:list --verbose --path=posts",
"route:list -vvv --path=posts",
] {
app.command(command)
.await
.assert_successful()
.assert_output_contains("⇂");
}
let empty = app.command("route:list --path=missing").await;
empty.assert_successful();
assert!(empty.output().is_empty());
assert_eq!(empty.error_output(), "No routes found.\n");
let quiet = app.command("route:list --path=missing -q").await;
quiet.assert_successful();
assert!(quiet.output().is_empty());
assert!(quiet.error_output().is_empty());
assert_eq!(app.command("route:list --json --path=missing").await.output(), "[]\n");
}
mod listing_handlers {
pub mod alpha {
pub mod users {
pub async fn show() -> &'static str {
"alpha"
}
}
}
pub mod beta {
pub mod users {
pub async fn show() -> &'static str {
"beta"
}
}
}
}
#[tokio::test]
async fn route_listings_keep_domains_and_distinguish_shortened_handlers() {
let app = configure()
.with_routing(|routing, _| {
routing.api(|route| {
route.domain("admin.example.com").group(|route| {
route.get("/alpha", listing_handlers::alpha::users::show);
});
route.get("/beta", listing_handlers::beta::users::show);
route.get("/closure", || async { "closure" });
});
})
.create();
let listing = app.command("route:list").await;
listing.assert_successful();
listing
.assert_output_contains("Domain")
.assert_output_contains("admin.example.com")
.assert_output_contains("integration::alpha::users::show")
.assert_output_contains("integration::beta::users::show")
.assert_output_contains("Closure");
assert!(!listing.output().contains("listing_handlers"));
let full = app.command("route:list -vv").await;
full.assert_successful()
.assert_output_contains("integration::console::listing_handlers::alpha::users::show");
let filtered = app.command("route:list --path=beta").await;
filtered.assert_successful();
assert!(!filtered.output().contains("Domain"));
let json = app.command("route:list --json").await;
json.assert_successful()
.assert_output_contains("integration::console::listing_handlers::alpha::users::show");
assert!(!json.output().contains("Closure"));
let quiet = app.command("route:list -q").await;
quiet.assert_successful();
assert!(quiet.output().is_empty());
assert!(quiet.error_output().is_empty());
}
#[tokio::test]
async fn keys_can_be_generated_with_captured_output() {
use laravel::crypt::{Cipher, Encrypter};
for key in [None, Some(""), Some("short"), Some("base64:%%%")] {
let app = configure()
.with_config(move |config, _| {
config.app.cipher = Cipher::Aes128Cbc;
config.app.key = key.map(str::to_owned);
})
.create();
assert!(app.encrypter().is_err());
let result = app.command("key:generate --show").await;
result.assert_successful();
assert!(result.error_output().is_empty());
let mut config = app.config().app.clone();
config.key = Some(result.output().trim().to_owned());
Encrypter::from_config(&config).unwrap();
}
}
#[derive(clap::Parser)]
#[command(name = "serve", about = "Application serve replacement")]
struct ServeReplacement;
#[laravel::console::command]
impl ServeReplacement {
async fn handle(self, console: &mut Console) -> laravel::Result<()> {
console.line("Application serve replacement");
Ok(())
}
}
#[tokio::test]
async fn application_commands_replace_builtins_in_dispatch_and_help() {
let app = configure()
.with_commands(|commands, _| {
commands.add::<ServeReplacement>();
})
.create();
for command in ["", "serve", "help serve", "serve --help"] {
app.command(command)
.await
.assert_successful()
.assert_output_contains("Application serve replacement");
}
let result = app.command("list").await;
result
.assert_successful()
.assert_output_contains("Application serve replacement");
assert_eq!(result.output().matches("Application serve replacement").count(), 1);
}
#[derive(clap::Parser)]
#[command(name = "parser:probe")]
struct ParserProbe {
#[arg(long, value_parser = ["json", "text"])]
format: Option<String>,
#[arg(long, require_equals = true)]
color: Option<String>,
#[arg(long, num_args = 2)]
pair: Vec<String>,
#[arg(long, num_args = 2..)]
many: Vec<String>,
#[arg(long, value_parser = validate_parser_probe)]
custom: Option<String>,
#[arg(long, value_parser = validate_raw_parser_probe)]
raw: Option<String>,
#[arg(long, conflicts_with = "right")]
left: bool,
#[arg(long)]
right: bool,
}
fn validate_parser_probe(_: &str) -> Result<String, String> {
Err("vendor detail?\n\nsecond paragraph without punctuation".to_owned())
}
fn validate_raw_parser_probe(_: &str) -> Result<String, clap::Error> {
Err(clap::Error::raw(
clap::error::ErrorKind::ValueValidation,
"application message without punctuation",
))
}
#[laravel::console::command]
impl ParserProbe {
#[cfg_attr(all(), inline(never))]
async fn handle(self) -> laravel::Result<()> {
Ok(())
}
}
#[tokio::test]
async fn parser_errors_have_consistent_headlines_and_preserve_validation_details() {
let app = configure()
.with_commands(|commands, _| {
commands.add::<ParserProbe>();
})
.create();
for (command, expected) in [
("route:lis", "unknown command `route:lis`"),
("help route:lis", "unknown command `route:lis`"),
("serve --por 8000", "unexpected argument `--por`"),
("mail:send", "missing required argument `<USER>`"),
("list -q -v", "argument `--quiet` can't be used with `--verbose`"),
(
"serve --port 80 --port 81",
"argument `--port` can't be used multiple times",
),
(
"parser:probe --format xml",
"invalid value `xml` for `--format`\nValid values: json, text",
),
(
"parser:probe --format",
"argument `--format` requires a value\nValid values: json, text",
),
(
"parser:probe --color blue",
"argument `--color` requires a value using `=`",
),
(
"parser:probe --pair one",
"argument `--pair` requires 2 values; received 1",
),
(
"parser:probe --many one",
"argument `--many` requires at least 2 values; received 1",
),
(
"serve --port oops",
"invalid value `oops` for `--port`\nexpected a whole number",
),
(
"parser:probe --custom bad",
"invalid value `bad` for `--custom`\nvendor detail?\n\nsecond paragraph without punctuation",
),
(
"parser:probe --raw bad",
"invalid value `bad` for `--raw`\nerror: application message without punctuation",
),
(
"parser:probe --left --right",
"argument `--left` can't be used with `--right`",
),
] {
let result = app.command(command).await;
result.assert_exit_code(2);
let (message, _) = result
.error_output()
.split_once("\n\nUsage:")
.or_else(|| result.error_output().split_once("\n\nFor more information,"))
.unwrap_or_else(|| panic!("{}", result.error_output()));
assert_eq!(message, expected, "{command}");
assert!(!result.error_output().contains("tip:"), "{command}");
assert!(result.output().is_empty(), "{command}");
}
app.command("route:lis")
.await
.assert_error_output_contains("\n\nUsage:");
}
#[tokio::test]
async fn parser_errors_show_the_invoked_commands_usage_rather_than_the_arguments_used_so_far() {
let app = configure()
.with_commands(|commands, _| {
commands.add::<ParserProbe>().add::<SendEmails>();
})
.create();
for (command, usage) in [
("parser:probe --right --nope", "Usage: app parser:probe [OPTIONS]"),
("parser:probe -v --nope", "Usage: app parser:probe [OPTIONS]"),
("parser:probe --left --right", "Usage: app parser:probe [OPTIONS]"),
("mail:send 42 --nope", "Usage: app mail:send [OPTIONS] <USER>"),
("-v mail:send", "Usage: app mail:send [OPTIONS] <USER>"),
("list -q -v", "Usage: app list [OPTIONS]"),
("rouet:list", "Usage: app [OPTIONS] <COMMAND>"),
] {
let result = app.command(command).await;
result.assert_exit_code(2);
let shown = result
.error_output()
.lines()
.find(|line| line.starts_with("Usage:"))
.unwrap_or_else(|| panic!("{}", result.error_output()));
assert_eq!(shown, usage, "{command}");
}
}
#[derive(clap::Parser)]
#[command(name = "mail:send")]
struct Replacement;
#[laravel::console::command]
impl Replacement {
async fn handle(self, console: &mut Console) -> laravel::Result<()> {
console.line("Application replacement");
Ok(())
}
}
struct MailProvider;
impl ServiceProvider for MailProvider {
fn config(&self, config: &mut Config, _: &Env) {
config.app.name = "Provider".to_owned();
}
fn register(&self, services: &mut Registrar) {
services.instance(Mailer {
from: "provider@example.com".to_owned(),
});
services.instance(Sequence(AtomicUsize::new(0)));
assert_eq!(services.config().app.name, "Final configuration");
services.commands().add::<SendEmails>();
}
}
#[tokio::test]
async fn provider_commands_see_final_config_and_application_registration_runs_last() {
Application::configure()
.replace_env(Env::default())
.with_providers(|providers| {
providers.add(MailProvider);
})
.with_config(|config, _| {
config.app.name = "Final configuration".to_owned();
})
.create()
.command("mail:send 42")
.await
.assert_successful()
.assert_error_output_contains("from=provider@example.com app=Final configuration");
let app = Application::configure()
.replace_env(Env::default())
.with_commands(|commands, config| {
assert_eq!(config.app.name, "Final configuration");
commands.add::<Replacement>();
})
.with_providers(|providers| {
providers.add(MailProvider);
})
.with_config(|config, _| {
config.app.name = "Final configuration".to_owned();
})
.create();
app.command("mail:send")
.await
.assert_successful()
.assert_output_contains("Application replacement");
app.command("email:send 1").await.assert_exit_code(2);
}
#[tokio::test]
async fn concurrent_commands_share_boot_and_have_separate_contexts() {
let builds = Arc::new(AtomicUsize::new(0));
let counter = Arc::clone(&builds);
let app = configure()
.with_services(move |services| {
services.singleton(move |_| {
let counter = Arc::clone(&counter);
async move {
tokio::task::yield_now().await;
counter.fetch_add(1, Ordering::SeqCst);
Ok(Mailer {
from: "factory@example.com".to_owned(),
})
}
});
})
.create();
let (first, second) = tokio::join!(
app.command("mail:send 1").into_future(),
app.command("mail:send 2").into_future()
);
first
.assert_successful()
.assert_error_output_contains("user=1 queue=default from=factory@example.com");
second
.assert_successful()
.assert_error_output_contains("user=2 queue=default from=factory@example.com");
assert_ne!(
first.error_output().split(':').next(),
second.error_output().split(':').next()
);
assert_eq!(builds.load(Ordering::SeqCst), 1);
}
#[test]
fn conflicting_command_aliases_are_startup_errors() {
#[derive(clap::Parser)]
#[command(name = "other", alias = "email:send")]
struct Other;
#[laravel::console::command]
impl Other {
async fn handle(self) {}
}
let error = Application::configure()
.replace_env(Env::default())
.with_commands(|commands, _| {
commands.add::<SendEmails>().add::<Other>();
})
.try_create()
.unwrap_err();
assert!(matches!(error, laravel::foundation::StartupError::Commands(_)));
assert!(error.to_string().contains("email:send"));
}
#[test]
fn an_invalid_command_definition_is_a_startup_error_naming_the_command() {
#[derive(clap::Parser)]
#[command(name = "posts:publish")]
struct Publish {
force: bool,
}
#[laravel::console::command]
impl Publish {
async fn handle(self) {}
}
let error = Application::configure()
.replace_env(Env::default())
.with_commands(|commands, _| {
commands.add::<SendEmails>().add::<Publish>();
})
.try_create()
.unwrap_err();
let message = error.to_string();
assert!(
message.starts_with("the application's console commands are invalid: command `posts:publish` is invalid: "),
"{message}"
);
assert!(
message.contains("'force`") && !message.contains("debug_asserts.rs"),
"{message}"
);
}
#[test]
fn an_invalid_command_definition_prints_no_panic_report() {
let output = std::process::Command::new(std::env::current_exe().unwrap())
.args([
"--exact",
"console::an_invalid_command_definition_is_a_startup_error_naming_the_command",
"--nocapture",
])
.output()
.unwrap();
assert!(output.status.success(), "{output:?}");
assert_eq!(String::from_utf8(output.stderr).unwrap(), "");
}
#[derive(clap::Parser)]
#[command(name = "outcome")]
struct Outcome {
code: u8,
#[arg(long)]
fail: bool,
}
#[laravel::console::command]
impl Outcome {
async fn handle(self, console: &mut Console) -> laravel::Result<u8> {
console.line("stdout");
console.warn("stderr");
if self.fail {
std::str::from_utf8(&[self.code | 0x80])?;
}
Ok(self.code)
}
}
#[tokio::test]
async fn explicit_exit_statuses_and_foreign_errors_keep_streams_separate() {
let app = Application::configure()
.replace_env(Env::default())
.with_commands(|commands, _| {
commands.add::<Outcome>();
})
.create();
let result = app.command("outcome 7").await;
result.assert_exit_code(7).assert_failed();
assert_eq!(result.output(), "stdout\n");
assert_eq!(result.error_output(), "stderr\n");
app.command("outcome 0 --fail")
.await
.assert_exit_code(1)
.assert_error_output_contains("invalid utf-8");
}
#[derive(clap::Parser)]
#[command(name = "status")]
struct Status;
#[laravel::console::command]
impl Status {
async fn handle(self) -> u8 {
9
}
}
#[derive(clap::Parser)]
#[command(name = "empty")]
struct Empty;
#[laravel::console::command]
impl Empty {
async fn handle(self) {}
}
#[tokio::test]
async fn handlers_can_return_unit_or_a_status_without_console_arguments() {
let app = Application::configure()
.replace_env(Env::default())
.with_commands(|commands, _| {
commands.add::<Status>().add::<Empty>();
})
.create();
app.command("status").await.assert_exit_code(9);
app.command("empty").await.assert_successful().assert_no_output();
}
#[tokio::test]
async fn output_assertions_check_each_stream_for_what_it_lacks() {
let app = Application::configure()
.replace_env(Env::default())
.with_commands(|commands, _| {
commands.add::<Outcome>();
})
.create();
let result = app.command("outcome 0").await;
result
.assert_output_missing("stderr")
.assert_error_output_missing("stdout");
let printed = failure(|| {
result.assert_output_missing("stdout");
});
let warned = failure(|| {
result.assert_error_output_missing("stderr");
});
let some_output = failure(|| {
result.assert_no_output();
});
assert!(
printed.starts_with(r#"expected stdout not to contain "stdout""#),
"{printed}"
);
assert!(
warned.starts_with(r#"expected stderr not to contain "stderr""#),
"{warned}"
);
assert!(some_output.starts_with("expected no output"), "{some_output}");
}
#[derive(clap::Parser)]
#[command(name = "panic")]
struct Panicking;
#[laravel::console::command]
impl Panicking {
async fn handle(self) {
panic!("command panicked");
}
}
#[laravel::console::command("feeds:watch", long_running)]
async fn watch_feeds() {}
#[derive(clap::Parser)]
#[command(name = "webhooks:work")]
struct WorkWebhooks;
#[laravel::console::command(long_running)]
impl WorkWebhooks {
async fn handle(self) {}
}
#[tokio::test]
async fn long_running_commands_have_no_span_of_their_own() {
let (lines, _guard) = crate::logging::Lines::capture();
let app = Application::configure()
.replace_env(Env::default())
.with_commands(|commands, _| {
commands.add::<watch_feeds>().add::<WorkWebhooks>();
})
.create();
app.command("route:list").await.assert_successful();
app.command("serve").await.assert_exit_code(1);
app.command("schedule:work").await.assert_exit_code(1);
app.command("queue:work sync").await.assert_exit_code(1);
app.command("feeds:watch").await.assert_successful();
app.command("webhooks:work").await.assert_successful();
let spans: serde_json::Value = lines
.json()
.into_iter()
.filter(|line| line["fields"]["message"] == "Command finished")
.map(|line| line["spans"][0]["command"].clone())
.collect();
assert_eq!(spans, serde_json::json!(["route:list", null, null, null, null, null]));
}
#[tokio::test]
async fn panics_become_reported_command_failures() {
let reports = Arc::new(AtomicUsize::new(0));
let counter = Arc::clone(&reports);
let app = Application::configure()
.replace_env(Env::default())
.with_commands(|commands, _| {
commands.add::<Panicking>();
})
.with_errors(move |errors, _| {
errors.report_all(move |_| {
counter.fetch_add(1, Ordering::SeqCst);
});
})
.create();
app.command("panic")
.await
.assert_exit_code(1)
.assert_error_output_contains("command panicked");
assert_eq!(reports.load(Ordering::SeqCst), 1);
}
#[derive(clap::Parser)]
#[command(name = "reject")]
struct Reject;
#[laravel::console::command]
impl Reject {
async fn handle(self) -> laravel::Result<()> {
Err(std::io::Error::other("payload \x1b]0;pwned\x07 rejected").into())
}
}
#[tokio::test]
async fn command_failures_remove_terminal_escapes_from_the_error() {
let app = Application::configure()
.replace_env(Env::default())
.with_commands(|commands, _| {
commands.add::<Reject>();
})
.create();
let result = app.command("reject").await;
result.assert_exit_code(1);
assert_eq!(result.error_output(), "payload rejected\n");
}
#[derive(clap::Parser)]
#[command(name = "echo")]
struct Echo {
value: String,
}
#[laravel::console::command]
impl Echo {
async fn handle(self, console: &mut Console) -> laravel::Result<()> {
console.line(self.value);
Ok(())
}
}
#[tokio::test]
async fn command_strings_support_quoting_without_shell_expansion() {
let app = Application::configure()
.replace_env(Env::default())
.with_commands(|commands, _| {
commands.add::<Echo>();
})
.create();
app.command("echo 'hello $HOME $(whoami)'")
.await
.assert_successful()
.assert_output_contains("hello $HOME $(whoami)");
}
#[cfg(unix)]
#[tokio::test]
async fn exact_arguments_preserve_non_utf8_paths() {
use std::ffi::OsString;
use std::os::unix::ffi::OsStringExt;
#[derive(clap::Parser)]
#[command(name = "path")]
struct Path {
value: std::path::PathBuf,
}
#[laravel::console::command]
impl Path {
async fn handle(self, console: &mut Console) -> laravel::Result<()> {
assert_eq!(self.value.as_os_str().as_encoded_bytes(), &[b'/', 0xff]);
console.line("path received");
Ok(())
}
}
Application::configure()
.replace_env(Env::default())
.with_commands(|commands, _| {
commands.add::<Path>();
})
.create()
.command_args([OsString::from("path"), OsString::from_vec(vec![b'/', 0xff])])
.await
.assert_successful()
.assert_output_contains("path received");
}
#[derive(clap::Parser)]
#[command(name = "setup")]
struct Setup {
#[arg(long)]
defaults: bool,
}
#[laravel::console::command]
impl Setup {
async fn handle(self, console: &mut Console) -> laravel::Result<()> {
let ask = console.ask("Name?");
let name = if self.defaults {
ask.default("Taylor").await?
} else {
ask.await?
};
let choice = console.choice("Queue?", ["default", "high"]);
let queue = if self.defaults {
choice.default("default").await?
} else {
choice.await?
};
let confirm = console.confirm("Send?");
let send = if self.defaults {
confirm.default(false).await?
} else {
confirm.await?
};
if send {
console.table(["Name", "Queue"], [[name.as_str(), queue.as_str()]]);
console.info("Sent.");
} else {
console.warn("Not sent.");
}
Ok(())
}
}
fn prompting_app() -> Application {
configure()
.with_commands(|commands, _| {
commands.add::<Setup>();
})
.create()
}
#[tokio::test]
async fn scripted_prompts_drive_the_real_handler_without_terminal_output() {
let result = prompting_app()
.command("setup")
.expects_question("Name?", "Taylor Otwell")
.expects_choice("Queue?", "high")
.expects_confirmation("Send?", true)
.await;
result
.assert_successful()
.assert_asked("Queue?")
.assert_output_contains("Taylor Otwell")
.assert_output_contains("high")
.assert_error_output_contains("Sent.");
assert_eq!(result.questions(), ["Name?", "Queue?", "Send?"]);
assert!(!result.output().contains('\x1b'));
assert_eq!(result.error_output(), "Sent.\n");
}
#[tokio::test]
async fn noninteractive_prompts_use_explicit_defaults_or_fail_without_waiting() {
let app = prompting_app();
let result = app.command("setup --defaults").await;
result.assert_successful().assert_error_output_contains("Not sent.");
assert_eq!(result.questions(), ["Name?", "Queue?", "Send?"]);
app.command("setup")
.await
.assert_exit_code(1)
.assert_error_output_contains("can't ask \"Name?\"")
.assert_error_output_contains("supply a default");
for command in [
"-n setup --defaults",
"--no-interaction setup --defaults",
"setup --defaults -n",
] {
app.command(command)
.await
.assert_successful()
.assert_error_output_contains("Not sent.");
}
app.command("setup --help")
.await
.assert_successful()
.assert_output_contains("--no-interaction");
app.command("-n --port=invalid")
.await
.assert_exit_code(2)
.assert_error_output_contains("expected a whole number");
}
#[tokio::test]
#[should_panic(expected = "`mail:send 'Taylor` has an unmatched quote or escape")]
async fn command_lines_with_an_unmatched_quote_panic() {
let _ = configure().create().command("mail:send 'Taylor").await;
}
#[tokio::test]
#[should_panic(expected = "exit code: 1")]
async fn failed_stdout_assertions_show_the_exit_code_and_stderr() {
prompting_app().command("setup").await.assert_output_contains("Sent.");
}
#[tokio::test]
#[should_panic(expected = "exit code: 0")]
async fn failed_stderr_assertions_show_the_exit_code_and_stdout() {
prompting_app()
.command("list")
.await
.assert_error_output_contains("can't ask");
}
#[tokio::test]
#[should_panic(expected = "unexpected prompt")]
async fn incorrect_prompt_expectations_fail_even_when_command_errors_are_expected() {
prompting_app()
.command("setup")
.expects_confirmation("Name?", true)
.await
.assert_failed();
}
#[tokio::test]
#[should_panic(expected = "unexpected prompt")]
async fn extra_questions_fail_after_expected_answers_are_used() {
prompting_app()
.command("setup")
.expects_question("Name?", "Taylor")
.await
.assert_failed();
}
#[derive(clap::Parser)]
#[command(name = "invalid-choice")]
struct InvalidChoice {
#[arg(long)]
empty: bool,
}
#[laravel::console::command]
impl InvalidChoice {
async fn handle(self, console: &mut Console) -> laravel::Result<()> {
if self.empty {
console.choice("Queue?", Vec::<String>::new()).await?;
} else {
console.choice("Queue?", ["default", "high"]).default("missing").await?;
}
Ok(())
}
}
#[tokio::test]
async fn empty_choices_and_invalid_defaults_are_errors_in_every_mode() {
let app = configure()
.with_commands(|commands, _| {
commands.add::<InvalidChoice>();
})
.create();
app.command("invalid-choice")
.await
.assert_exit_code(1)
.assert_error_output_contains("isn't an option");
app.command("invalid-choice --empty -n")
.await
.assert_exit_code(1)
.assert_error_output_contains("at least one option");
}
#[derive(clap::Parser)]
#[command(name = "cancel")]
struct Cancel;
#[laravel::console::command]
impl Cancel {
async fn handle(self) -> laravel::Result<()> {
Err(laravel::console::PromptError::Cancelled.into())
}
}
#[tokio::test]
async fn cancelled_prompts_exit_without_reporting_an_application_failure() {
let reports = Arc::new(AtomicUsize::new(0));
let counter = Arc::clone(&reports);
let app = configure()
.with_commands(|commands, _| {
commands.add::<Cancel>();
})
.with_errors(move |errors, _| {
errors.report_all(move |_| {
counter.fetch_add(1, Ordering::SeqCst);
});
})
.create();
let result = app.command("cancel").await;
result.assert_exit_code(130);
assert!(result.output().is_empty());
assert!(result.error_output().is_empty());
assert_eq!(reports.load(Ordering::SeqCst), 0);
}
#[tokio::test]
async fn running_inside_an_async_runtime_fails_without_side_effects() {
let app = Application::configure().replace_env(Env::default()).create();
assert_eq!(app.run(), std::process::ExitCode::FAILURE);
}
#[tokio::test]
async fn awaited_command_failures_name_the_line_that_ran_the_command() {
use futures_util::FutureExt;
let app = prompting_app();
let line = line!() + 1;
let command = app.command("list").expects_question("Name?", "Taylor");
let panic = std::panic::AssertUnwindSafe(command.into_future())
.catch_unwind()
.await
.expect_err("the unasked question should fail the test");
let message = panic.downcast_ref::<String>().cloned().unwrap_or_default();
assert!(message.contains(&format!("\n\nat {}:{line}:", file!())), "{message}");
}