#[allow(dead_code)]
mod support;
use support::{published_leaves, Sandbox};
const NOT_ROUTED: &str = "usage.served_without_a_connection";
#[test]
fn every_published_command_is_reachable() {
let sandbox = Sandbox::new();
let leaves = published_leaves(&sandbox);
assert!(leaves.len() >= 59, "the whole surface must be published");
let mut unreachable = Vec::new();
for leaf in &leaves {
let mut args: Vec<&str> = vec!["--print-schema"];
args.extend(leaf.split(' '));
let outcome = sandbox.run(&args);
if outcome.code != 0 || outcome.out.is_empty() {
unreachable.push(format!(
"{leaf} -> exit {} {}",
outcome.code,
outcome.err.trim()
));
}
}
assert!(
unreachable.is_empty(),
"these published commands cannot be reached:\n{}",
unreachable.join("\n")
);
}
#[test]
fn nothing_declared_served_answers_that_it_is_not_routed() {
let sandbox = Sandbox::new();
let mut lying = Vec::new();
for row in sandbox.run(&["meta", "commands"]).rows() {
let (Some(name), Some(state)) = (row["name"].as_str(), row["state"].as_str()) else {
continue;
};
if state != "served" {
continue;
}
let mut args: Vec<&str> = vec!["--print-schema"];
args.extend(name.split(' '));
let outcome = sandbox.run(&args);
if outcome.code != 0 || outcome.err.contains(NOT_ROUTED) {
lying.push(name.to_owned());
}
}
assert!(
lying.is_empty(),
"these commands are declared served and are not: {lying:?}"
);
}
#[test]
fn the_commands_that_need_no_server_answer_without_one() {
let sandbox = Sandbox::new();
let lineage = sandbox.run(&["query", "lineage", "SELECT p.total FROM pedidos AS p"]);
assert_eq!(
lineage.code, 0,
"lineage must not need a server: {}",
lineage.err
);
assert_eq!(lineage.answer()["command"], "query lineage");
assert_eq!(
lineage.answer()["data"]["rows"][0]["sources"][0]["table"],
"pedidos"
);
let saved = sandbox.run(&[
"query",
"named",
"save",
"pedidos",
"SELECT * FROM pedidos WHERE pago = 1",
]);
assert_eq!(
saved.code, 0,
"saving must not need a server: {}",
saved.err
);
let listed = sandbox.run(&["query", "named", "list"]);
assert_eq!(
listed.code, 0,
"listing must not need a server: {}",
listed.err
);
assert_eq!(listed.answer()["data"]["rows"][0]["name"], "pedidos");
let removed = sandbox.run(&["query", "named", "remove", "pedidos"]);
assert_eq!(
removed.code, 0,
"removing must not need a server: {}",
removed.err
);
}
#[test]
fn running_a_kept_statement_asks_for_a_destination() {
let sandbox = Sandbox::new();
let outcome = sandbox.run(&["query", "named", "run", "pedidos"]);
assert_ne!(outcome.code, 0);
assert_ne!(
outcome.code(),
NOT_ROUTED,
"needing a destination is not the same as not being routed"
);
}
#[test]
fn the_published_surface_carries_the_expected_count() {
let sandbox = Sandbox::new();
let leaves = published_leaves(&sandbox);
assert_eq!(leaves.len(), 63, "published leaves: {leaves:?}");
let mut sorted = leaves.clone();
sorted.sort();
sorted.dedup();
assert_eq!(sorted.len(), leaves.len(), "a command is published twice");
}
#[test]
fn the_published_surface_is_byte_for_byte_stable() {
let sandbox = Sandbox::new();
let first = sandbox.run(&["meta", "commands"]).out;
let second = sandbox.run(&["meta", "commands"]).out;
assert_eq!(first, second);
}
#[test]
fn a_missing_destination_is_a_configuration_failure() {
let sandbox = Sandbox::new();
let outcome = sandbox.run(&["schema", "tables"]);
assert_eq!(outcome.code, 4, "stderr: {}", outcome.err);
assert_eq!(outcome.code(), "profile.no_default");
assert!(
outcome.out.is_empty(),
"a failure must never reach the primary channel"
);
}
const REDECLARES_A_GLOBAL_NAME: &[&str] = &[];
#[test]
fn no_command_redeclares_a_name_the_global_flags_already_own() {
let root = <mariadb_cli::cli::Cli as clap::CommandFactory>::command();
let owned: std::collections::BTreeSet<String> = root
.get_arguments()
.filter(|argument| argument.is_global_set())
.filter_map(|argument| argument.get_long().map(ToOwned::to_owned))
.collect();
assert!(
owned.contains("output"),
"the global flags must own --output, or this test proves nothing"
);
let mut clashes = Vec::new();
walk(&root, &mut Vec::new(), &owned, &mut clashes);
clashes.sort_unstable();
let mut declared = REDECLARES_A_GLOBAL_NAME.to_vec();
declared.sort_unstable();
assert_eq!(
clashes, declared,
"these commands redeclare a name the global flags already own"
);
}
#[test]
fn the_one_database_flag_still_selects_on_every_family() {
use clap::Parser as _;
for command in [
vec!["schema", "tables"],
vec!["query", "sample", "--table", "orders"],
vec!["data", "export", "--to", "/tmp/copy.sql"],
vec!["history", "tables"],
] {
let argv: Vec<String> = std::iter::once("mariadb-cli".to_owned())
.chain(command.iter().map(|piece| (*piece).to_owned()))
.chain(["--database".to_owned(), "sales".to_owned()])
.collect();
let cli = mariadb_cli::cli::Cli::try_parse_from(argv).unwrap_or_else(|refused| {
panic!(
"`{}` no longer accepts --database: {refused}",
command.join(" ")
)
});
assert_eq!(
cli.globals.destination.database.as_deref(),
Some("sales"),
"`{}` accepted --database and it reached nothing",
command.join(" ")
);
}
}
#[test]
fn the_two_destinations_of_a_copy_stay_independent() {
use clap::Parser as _;
let command_line = [
"mariadb-cli",
"data",
"export",
"--to",
"/tmp/copy.sql",
"--output",
"/tmp/receipt.json",
];
let cli = mariadb_cli::cli::Cli::try_parse_from(command_line.iter().map(ToString::to_string))
.expect("the sample invocation parses");
let mariadb_cli::cli::Command::Data(mariadb_cli::cli::data::DataCommand::Export(args)) =
&cli.command
else {
panic!("the sample invocation is a copy");
};
assert_eq!(
args.to.as_deref(),
Some(std::path::Path::new("/tmp/copy.sql")),
"the copy goes where the command was told"
);
assert_eq!(
cli.globals.output.output.as_deref(),
Some(std::path::Path::new("/tmp/receipt.json")),
"and the receipt goes somewhere else entirely"
);
assert_ne!(
args.to.as_deref(),
cli.globals.output.output.as_deref(),
"one word typed once must no longer reach both"
);
}
fn walk(
command: &clap::Command,
path: &mut Vec<String>,
owned: &std::collections::BTreeSet<String>,
clashes: &mut Vec<String>,
) {
for child in command.get_subcommands() {
path.push(child.get_name().to_owned());
for argument in child.get_arguments() {
if argument.is_global_set() {
continue;
}
if let Some(long) = argument.get_long() {
if owned.contains(long) {
clashes.push(format!("{} redeclares --{long}", path.join(" ")));
}
}
}
walk(child, path, owned, clashes);
path.pop();
}
}
const SPELLED_TWO_WAYS: &[&str] = &["table {\"unset/append\", \"unset/set\"}"];
fn accepted_forms(argument: &clap::Arg) -> String {
let takes = argument.get_num_args().map_or_else(
|| "unset".to_owned(),
|range| format!("{}..={}", range.min_values(), range.max_values()),
);
let action = match argument.get_action() {
clap::ArgAction::Set => "set",
clap::ArgAction::Append => "append",
clap::ArgAction::SetTrue => "set-true",
clap::ArgAction::SetFalse => "set-false",
clap::ArgAction::Count => "count",
clap::ArgAction::Help | clap::ArgAction::HelpShort | clap::ArgAction::HelpLong => "help",
clap::ArgAction::Version => "version",
other => panic!("an action this walk does not name yet: {other:?}"),
};
format!("{takes}/{action}")
}
#[test]
fn a_flag_spelled_the_same_on_two_commands_accepts_the_same_forms() {
let root = <mariadb_cli::cli::Cli as clap::CommandFactory>::command();
let mut seen: std::collections::BTreeMap<String, std::collections::BTreeSet<String>> =
std::collections::BTreeMap::new();
gather_forms(&root, &mut seen);
assert!(
seen.contains_key("pin-database"),
"the walk must reach --pin-database, or this test proves nothing"
);
let mut split: Vec<String> = seen
.into_iter()
.filter(|(_, forms)| forms.len() > 1)
.map(|(name, forms)| format!("{name} {forms:?}"))
.collect();
split.sort_unstable();
let mut declared: Vec<String> = SPELLED_TWO_WAYS
.iter()
.map(|name| (*name).to_owned())
.collect();
declared.sort_unstable();
assert_eq!(
split, declared,
"these flags are spelled the same on more than one command and accept \
different forms, so a caller who learns one is wrong on the other"
);
}
fn gather_forms(
command: &clap::Command,
seen: &mut std::collections::BTreeMap<String, std::collections::BTreeSet<String>>,
) {
for argument in command.get_arguments() {
if argument.is_global_set() {
continue;
}
if let Some(long) = argument.get_long() {
seen.entry(long.to_owned())
.or_default()
.insert(accepted_forms(argument));
}
}
for child in command.get_subcommands() {
gather_forms(child, seen);
}
}