#[allow(dead_code)]
mod support;
use clap::{CommandFactory as _, Parser as _};
use mariadb_cli::cli::meta::{MetaCommand, SchemaArgs};
use mariadb_cli::cli::Cli;
use mariadb_cli::commands::{contract, meta, SERVED_LEAVES};
use support::Sandbox;
fn contract_of(leaf: &str) -> serde_json::Value {
let cli = Cli::try_parse_from(["mariadb-cli", "meta", "version"])
.expect("the simplest invocation of all must parse");
let asked = MetaCommand::Schema(SchemaArgs {
command: Some(leaf.to_owned()),
types: false,
});
let envelope = meta::execute(&asked, &cli)
.unwrap_or_else(|failure| panic!("`{leaf}` has no contract: {}", failure.code()));
envelope.data
}
#[test]
fn the_published_contract_names_every_field_a_failure_carries() {
let sandbox = Sandbox::new();
let published = contract::failure_shape()["shape"]
.as_object()
.expect("the contract describes the shape of a failure")
.keys()
.cloned()
.collect::<std::collections::BTreeSet<String>>();
assert!(
!published.is_empty(),
"a contract that describes no failure field cannot catch an undeclared one"
);
let refusals: [&[&str]; 3] = [
&["query", "run", "--zzz-not-a-flag"],
&["meta", "schema", "--command", "no-such-command"],
&[
"--dsn",
"this is not a destination",
"query",
"run",
"SELECT 1",
],
];
for args in refusals {
let refused = sandbox.run(args);
assert_ne!(
refused.code, 0,
"this invocation must be refused, or it proves nothing: {args:?}"
);
let body = refused.failure();
let carried = body["error"]
.as_object()
.unwrap_or_else(|| panic!("a failure is an object: {body}"))
.keys()
.cloned()
.collect::<std::collections::BTreeSet<String>>();
let unpublished: Vec<&String> = carried.difference(&published).collect();
assert!(
unpublished.is_empty(),
"the failure of {args:?} carries fields the contract never names: {unpublished:?}"
);
}
}
#[test]
fn every_published_command_declares_what_it_can_change() {
let published = ["local", "reads", "may_change"];
let missing: Vec<String> = SERVED_LEAVES
.iter()
.map(|leaf| (*leaf, contract::effect_of(leaf)))
.filter(|(_, effect)| !published.contains(effect))
.map(|(leaf, effect)| format!("{leaf} => {effect}"))
.collect();
assert!(
missing.is_empty(),
"these commands publish no effect from the closed set {published:?}: {missing:?}"
);
}
#[test]
fn every_input_the_contract_names_is_accepted_by_the_parser() {
let root = Cli::command();
let mut checked = 0_usize;
let mut rejected: Vec<String> = Vec::new();
for leaf in SERVED_LEAVES {
let inputs = contract::inputs_of(&root, leaf);
let inputs = inputs
.as_array()
.unwrap_or_else(|| panic!("`{leaf}` publishes no list of inputs"));
for input in inputs {
if input["kind"] == "positional" {
continue;
}
let name = input["name"].as_str().expect("an input has a name");
let written = format!("--{name}");
let mut argv: Vec<String> = vec!["mariadb-cli".to_owned()];
argv.extend(leaf.split(' ').map(ToOwned::to_owned));
argv.push(written.clone());
checked += 1;
if let Err(refusal) = Cli::command().try_get_matches_from(&argv) {
if refusal.kind() == clap::error::ErrorKind::UnknownArgument {
rejected.push(format!("{leaf} {written}"));
}
}
}
}
assert!(
checked > 40,
"the inputs must be read, or this proof checks nothing"
);
assert!(
rejected.is_empty(),
"the contract names inputs the parser does not accept: {rejected:?}"
);
}
#[test]
fn the_contract_of_every_command_carries_inputs_effect_failures_and_envelope() {
let promised = ["inputs", "effect", "data", "failures", "envelope"];
let mut short: Vec<String> = Vec::new();
for leaf in SERVED_LEAVES {
let data = contract_of(leaf);
let absent: Vec<&str> = promised
.iter()
.copied()
.filter(|field| data.get(*field).is_none())
.collect();
if !absent.is_empty() {
short.push(format!("{leaf} lacks {absent:?}"));
}
}
assert!(
short.is_empty(),
"the contract does not carry everything FR-053 promises: {short:?}"
);
}
#[test]
fn no_payload_is_described_for_a_command_this_build_does_not_serve() {
let stray: Vec<&str> = contract::commands_with_published_data()
.into_iter()
.chain(contract::commands_whose_data_varies())
.filter(|leaf| !SERVED_LEAVES.contains(leaf))
.collect();
assert!(
stray.is_empty(),
"a payload is described for commands that are not served: {stray:?}"
);
}
const UNTYPED: [(&str, &str, &str); 3] = [
(
"config get",
"value",
"the type is the setting's own, so no single word covers it",
),
(
"config set",
"value",
"the type is the setting's own, so no single word covers it",
),
(
"config unset",
"value",
"the type is the setting's own, so no single word covers it",
),
];
#[test]
fn every_described_field_declares_its_type_or_is_named_as_not_declaring_one() {
let mut prose: Vec<String> = Vec::new();
for leaf in contract::commands_with_published_data() {
let shape = contract::data_shape_of(leaf);
let fields = shape.as_object().expect("a described payload is an object");
for (field, about) in fields {
let described = about.as_str().unwrap_or_default();
if support::described::declared_type(described).is_some() {
continue;
}
if UNTYPED
.iter()
.any(|(command, name, _)| *command == leaf && name == field)
{
continue;
}
prose.push(format!("{leaf}.{field}"));
}
}
assert!(
prose.is_empty(),
"these are described in prose, so no proof checks their type, and none \
of them is named as an exception: {prose:?}"
);
let stray: Vec<String> = UNTYPED
.iter()
.filter(|(leaf, field, _)| {
contract::data_shape_of(leaf)
.get(field)
.and_then(serde_json::Value::as_str)
.is_none_or(|about| support::described::declared_type(about).is_some())
})
.map(|(leaf, field, _)| format!("{leaf}.{field}"))
.collect();
assert!(
stray.is_empty(),
"these are named as untyped and either declare a type now or are not \
described at all; the exception has to go when its reason does: {stray:?}"
);
}
#[test]
fn every_declared_absence_names_a_field_that_is_described() {
let described = contract::commands_with_published_data();
let mut stray: Vec<String> = Vec::new();
for (leaf, field) in contract::conditional_fields() {
if !described.contains(&leaf) {
stray.push(format!("{leaf} has no published payload for `{field}`"));
continue;
}
let shape = contract::data_shape_of(leaf);
if shape.get(field).is_none() {
stray.push(format!("{leaf} describes no field named `{field}`"));
}
}
assert!(
stray.is_empty(),
"these declared absences excuse nothing: {stray:?}"
);
}
#[test]
fn no_command_both_publishes_a_payload_and_declares_it_variable() {
let fixed = contract::commands_with_published_data();
let both: Vec<&str> = contract::commands_whose_data_varies()
.into_iter()
.filter(|leaf| fixed.contains(leaf))
.collect();
assert!(
both.is_empty(),
"these commands claim a fixed payload and a variable one at once: {both:?}"
);
}
#[test]
fn a_command_with_a_variable_payload_publishes_the_reason() {
let mut silent: Vec<String> = Vec::new();
for leaf in contract::commands_whose_data_varies() {
let data = contract_of(leaf);
if data["data"]["shape_varies_by_input"].as_str().is_none() {
silent.push(leaf.to_owned());
}
}
assert!(
silent.is_empty(),
"these commands declare a variable payload without saying why: {silent:?}"
);
}
#[test]
fn a_command_without_a_described_payload_states_that_limit_itself() {
let described = contract::commands_with_published_data();
let variable = contract::commands_whose_data_varies();
let mut silent: Vec<String> = Vec::new();
for leaf in SERVED_LEAVES {
if described.contains(&leaf) || variable.contains(&leaf) {
continue;
}
let data = contract_of(leaf);
if data["data"]["declared_limit"].as_str().is_none() {
silent.push(leaf.to_owned());
}
}
assert!(
silent.is_empty(),
"these commands describe no payload and state no limit either: {silent:?}"
);
}
const SETTING: &str = "conn.default";
const SECRET: &str = "a-secret-that-never-travels\n";
const INVOCATIONS: [(&str, &[&str], Option<&str>); 21] = [
("meta version", &["meta", "version"], None),
("meta commands", &["meta", "commands"], None),
(
"meta commands",
&["meta", "commands", "--with-globals"],
None,
),
("meta completions", &["meta", "completions", "bash"], None),
("meta manual", &["meta", "manual"], None),
("config path", &["config", "path"], None),
("config list", &["config", "list"], None),
("config doctor", &["config", "doctor"], None),
("config set", &["config", "set", SETTING, "alfa"], None),
("config get", &["config", "get", SETTING], None),
("config unset", &["config", "unset", SETTING], None),
(
"conn add",
&[
"conn",
"add",
"alfa",
"--host",
"127.0.0.1",
"--port",
"3306",
"--user",
"quem",
"--password-stdin",
],
Some(SECRET),
),
("conn list", &["conn", "list"], None),
("conn show", &["conn", "show", "alfa"], None),
("conn default", &["conn", "default", "alfa"], None),
(
"conn edit",
&["conn", "edit", "alfa", "--port", "3307"],
None,
),
("conn remove", &["conn", "remove", "alfa"], None),
(
"query lineage",
&["query", "lineage", "SELECT 1 AS um"],
None,
),
(
"query named save",
&["query", "named", "save", "guardada", "SELECT 1"],
None,
),
("query named list", &["query", "named", "list"], None),
(
"query named remove",
&["query", "named", "remove", "guardada"],
None,
),
];
#[test]
fn every_described_payload_matches_the_answer_the_command_gives() {
let sandbox = Sandbox::new();
let invocations = INVOCATIONS;
let mut wrong: Vec<String> = Vec::new();
for (leaf, argv, input) in invocations {
let outcome = match input {
Some(text) => sandbox.run_with_input(argv, text),
None => sandbox.run(argv),
};
assert_eq!(
outcome.code, 0,
"`{leaf}` must answer before its payload can be compared: {}",
outcome.err
);
let emitted = outcome.answer();
let mut real: Vec<String> = emitted["data"]
.as_object()
.unwrap_or_else(|| panic!("`{leaf}` must answer with a payload object"))
.keys()
.cloned()
.collect();
real.sort();
let mut described: Vec<String> = contract_of(leaf)["data"]
.as_object()
.unwrap_or_else(|| panic!("`{leaf}` must describe its payload"))
.keys()
.cloned()
.collect();
described.sort();
wrong.extend(support::described::disagreements(
leaf,
&contract::data_shape_of(leaf),
&emitted["data"],
));
}
assert!(
wrong.is_empty(),
"the published payload and the real one differ: {wrong:?}"
);
let mut invoked: Vec<&str> = invocations.iter().map(|(leaf, _, _)| *leaf).collect();
invoked.sort_unstable();
invoked.dedup();
let mut described: Vec<&str> = contract::commands_with_published_data()
.into_iter()
.filter(|leaf| contract::effect_of(leaf) == "local")
.collect();
described.sort_unstable();
assert_eq!(
invoked, described,
"every command with a published payload and no destination must be run \
here, and only those"
);
}
#[test]
fn the_contract_the_process_publishes_is_the_one_the_library_builds() {
let sandbox = Sandbox::new();
let published = sandbox.run(&["meta", "schema", "--command", "query run"]);
assert_eq!(
published.code, 0,
"the contract is served: {}",
published.err
);
assert_eq!(
published.answer()["data"],
contract_of("query run"),
"the process and the library disagree about the contract of `query run`"
);
}