mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
Documentation
//! Proving that the language reaches the reader, and that nothing else moves.
//!
//! # Why this file exists
//!
//! The localisation layer can be complete, correct and never called. Its own
//! tests prove it translates; only running the binary proves the mark on the
//! command line reached it at all. Every test here therefore starts where a
//! caller starts: at the argument list.
//!
//! What is proved here is the CHOICE of a language: the mark on the command
//! line, the stored key, the order between the two, and that the choice reaches
//! the auxiliary channel as well as the failure. That the catalogues carry prose
//! for every message the code can name is the other half, and it is proved
//! beside this file in `language_catalogue`.

// The support module serves every test file in this directory, so the parts
// this one does not need are unused here and used elsewhere.
#[allow(dead_code)]
mod support;

use mariadb_cli::i18n::report;
use support::Sandbox;

/// A refusal that needs no server and whose prose the catalogues carry.
///
/// Reached from the argument list, so what is proved is the whole path from the
/// mark to the rendered line, not merely that a bundle can be loaded.
const REFUSED: [&str; 3] = ["--filter", "broken", "meta"];

/// One refusal, in one language, taken apart.
///
/// FR-050. Every test below reaches its message through here, and here the
/// primary channel is asserted empty: a refusal reaches the auxiliary channel
/// and never the channel a caller parses.
fn refusal(sandbox: &Sandbox, language: &str) -> serde_json::Value {
    let mut args = vec!["--lang", language];
    args.extend(REFUSED);
    args.push("version");
    let outcome = sandbox.run(&args);
    assert_ne!(outcome.code, 0, "the sample invocation must be refused");
    assert!(
        outcome.out.is_empty(),
        "a failure never reaches the primary channel: {}",
        outcome.out
    );
    outcome.failure()
}

/// FR-054. The mark reaches the reader, and it moves the prose alone: the
/// language never touches the data a caller branches on.
///
/// FR-047. The same refusal carries a category, a stable code, an exit number
/// and a repeat mark in both languages, and the code is the published one.
///
/// The mark on the command line reaches the rendered failure: the prose changes
/// and every field a caller branches on stays byte-identical.
#[test]
fn the_mark_on_the_command_line_changes_the_prose_and_nothing_else() {
    let sandbox = Sandbox::new();
    let english = refusal(&sandbox, "en");
    let portuguese = refusal(&sandbox, "pt-BR");

    assert_ne!(
        english["error"]["message"], portuguese["error"]["message"],
        "the language did not reach the reader"
    );

    for field in ["code", "category", "exit", "retryable"] {
        assert_eq!(
            english["error"][field], portuguese["error"][field],
            "`{field}` must not change with the language"
        );
    }
    assert_eq!(english["error"]["code"], "filter.no_operator");
}

/// FR-054. Asking for Portuguese is answered in Portuguese, whatever the host
/// speaks.
///
/// Asking for Portuguese really produces Portuguese, rather than merely
/// producing something different from English.
#[test]
fn asking_for_portuguese_is_answered_in_portuguese() {
    let sandbox = Sandbox::new();
    let message = refusal(&sandbox, "pt-BR")["error"]["message"]
        .as_str()
        .unwrap_or_default()
        .to_owned();
    assert!(
        message.contains("filtro"),
        "the refusal was not written in Portuguese: {message}"
    );
}

/// FR-054. Asking for English is answered in English, whatever the host speaks.
///
/// Asking for English really produces English, whatever the host speaks.
#[test]
fn asking_for_english_is_answered_in_english() {
    let sandbox = Sandbox::new();
    let message = refusal(&sandbox, "en")["error"]["message"]
        .as_str()
        .unwrap_or_default()
        .to_owned();
    assert!(
        message.contains("operator"),
        "the refusal was not written in English: {message}"
    );
}

/// FR-054. The mark reaches the refusal the PARSER itself produced.
///
/// Every proof above reaches a refusal the parser accepted and the work then
/// rejected. This one reaches the other kind, and it is the single case where
/// the layer that installs the language is never arrived at: the argument list
/// is consumed by the parse, so a parse that fails leaves nothing to read the
/// mark from afterwards. The mark therefore has to be read BEFORE the parse,
/// and this proof is what keeps it read there.
///
/// Written after the defect, not before it: `--lang en` answered in the host
/// language for every invocation the parser refused, and the whole file beside
/// this test stayed green, because not one of those tests fails at the parse.
/// A layer nothing exercises is a layer that returns to being wrong.
#[test]
fn the_mark_reaches_a_refusal_the_parser_itself_produced() {
    let sandbox = Sandbox::new();
    let unparsable = ["query", "no-such-subcommand-exists"];

    let mut english = vec!["--lang", "en"];
    english.extend(unparsable);
    let mut portuguese = vec!["--lang", "pt-BR"];
    portuguese.extend(unparsable);

    let english = sandbox.run(&english);
    let portuguese = sandbox.run(&portuguese);

    for outcome in [&english, &portuguese] {
        assert_ne!(outcome.code, 0, "the sample invocation must be refused");
    }

    let english = english.failure();
    let portuguese = portuguese.failure();

    assert_eq!(
        english["error"]["code"], "usage.invalid_arguments",
        "the refusal must be the one the parser produces"
    );
    assert_ne!(
        english["error"]["message"], portuguese["error"]["message"],
        "the mark did not reach a refusal the parser produced"
    );

    // Named rather than merely different, for the same reason the two proofs
    // above name their language: two renderings that differ prove only that
    // something moved, and the defect this guards against moved nothing at all.
    let english = english["error"]["message"]
        .as_str()
        .unwrap_or_default()
        .to_owned();
    assert!(
        english.contains("arguments"),
        "the parser's refusal was not written in English: {english}"
    );

    // The equals form is the caller's other spelling, and it travels a
    // different path through the argument list than the separated one.
    let joined = sandbox.run(&["--lang=en", "query", "no-such-subcommand-exists"]);
    assert_ne!(joined.code, 0, "the sample invocation must be refused");
    let joined = joined.failure()["error"]["message"]
        .as_str()
        .unwrap_or_default()
        .to_owned();
    assert_eq!(
        joined, english,
        "`--lang=en` must reach the parser's refusal the same way `--lang en` does"
    );
}

/// FR-054. The published key decides the language when the command line names
/// none, so the key is a second way in and not a name nobody reads.
///
/// The stored key decides when no mark was given, so a caller who set the
/// language once does not have to repeat it on every invocation.
#[test]
fn the_stored_key_decides_when_no_mark_was_given() {
    let sandbox = Sandbox::new();
    let stored = sandbox.run(&["config", "set", "i18n.lang", "pt-BR"]);
    assert_eq!(
        stored.code, 0,
        "the language must be storable: {}",
        stored.err
    );

    let mut args = REFUSED.to_vec();
    args.push("version");
    let message = sandbox.run(&args).failure()["error"]["message"]
        .as_str()
        .unwrap_or_default()
        .to_owned();
    assert!(
        message.contains("filtro"),
        "the stored language did not reach the reader: {message}"
    );
}

/// FR-054. The mark on the command line outranks the stored key, which is the
/// published order between the two ways of asking for a language.
///
/// The mark outranks the stored key, so a caller can override one invocation
/// without unsetting what they stored.
#[test]
fn the_mark_outranks_the_stored_key() {
    let sandbox = Sandbox::new();
    assert_eq!(
        sandbox.run(&["config", "set", "i18n.lang", "pt-BR"]).code,
        0
    );

    let message = refusal(&sandbox, "en")["error"]["message"]
        .as_str()
        .unwrap_or_default()
        .to_owned();
    assert!(
        message.contains("operator"),
        "the mark did not outrank the stored key: {message}"
    );
}

/// Somewhere the auxiliary channel can be caught and read back.
///
/// Progress is written for a person and never reaches the primary channel, so
/// the only honest way to prove a line was emitted is to stand where the
/// channel writes and read what arrived there.
#[derive(Clone, Default)]
struct Captured(std::sync::Arc<std::sync::Mutex<Vec<u8>>>);

impl Captured {
    /// Everything written to the channel so far.
    fn text(&self) -> String {
        let held = self
            .0
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        String::from_utf8_lossy(&held).into_owned()
    }
}

impl std::io::Write for Captured {
    fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
        self.0
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .extend_from_slice(bytes);
        Ok(bytes.len())
    }

    fn flush(&mut self) -> std::io::Result<()> {
        Ok(())
    }
}

impl tracing_subscriber::fmt::MakeWriter<'_> for Captured {
    type Writer = Self;

    fn make_writer(&self) -> Self::Writer {
        self.clone()
    }
}

/// One progress line, emitted in the given language and taken apart.
///
/// The channel is installed for this thread only, so a test running beside
/// this one is never handed the lines this one produced.
fn progress_line(language: &str) -> serde_json::Value {
    let captured = Captured::default();
    let channel = tracing_subscriber::fmt()
        .json()
        .with_max_level(tracing::Level::INFO)
        .with_writer(captured.clone())
        .finish();

    tracing::subscriber::with_default(channel, || {
        mariadb_cli::i18n::install(Some(language), None).expect("carried by this build");
        report::copy_table("orders");
    });

    let written = captured.text();
    let line =
        written.trim_end().lines().next_back().unwrap_or_else(|| {
            panic!("no progress reached the auxiliary channel for `{language}`")
        });
    serde_json::from_str(line)
        .unwrap_or_else(|cause| panic!("the progress line must be parseable: {cause}\n{line}"))
}

/// FR-050. Progress is emitted on the auxiliary channel, where it is caught and
/// read back, and never on the channel that carries the result.
///
/// FR-054. The language reaches that channel too, and the identifier a
/// collector branches on survives the translation unchanged.
///
/// Progress really reaches the auxiliary channel, really changes with the
/// language, and really keeps the one field a collector branches on.
///
/// The catalogue tests beside this file prove the prose exists. Only emitting
/// proves a call site reaches it, and only reading the emitted line proves the
/// identifier survived the translation alongside the sentence.
#[test]
fn a_progress_line_changes_with_the_language_and_keeps_its_identifier() {
    let english = progress_line("en");
    let portuguese = progress_line("pt-BR");

    assert_eq!(
        english["fields"]["message_id"],
        report::COPY_TABLE,
        "the line lost the identifier a collector branches on"
    );
    assert_eq!(
        english["fields"]["message_id"], portuguese["fields"]["message_id"],
        "the identifier must not change with the language"
    );

    let said_in_english = english["fields"]["message"].as_str().unwrap_or_default();
    let said_in_portuguese = portuguese["fields"]["message"].as_str().unwrap_or_default();
    assert_ne!(
        said_in_english, said_in_portuguese,
        "the language did not reach the reader of the auxiliary channel"
    );
    assert!(
        said_in_english.contains("copying") && said_in_english.contains("orders"),
        "the English progress line read: {said_in_english}"
    );
    assert!(
        said_in_portuguese.contains("copiando") && said_in_portuguese.contains("orders"),
        "the Portuguese progress line read: {said_in_portuguese}"
    );
}

/// FR-054. The plain text shape of the PRIMARY channel follows the language.
///
/// # The claim this closes
///
/// The catalogues used to open by saying that nothing they carried ever reached
/// the primary channel, and two English sentences sat in the formatter of the
/// plain text shape: `(no rows)` and the line naming what could not be
/// delivered. Running the product under `--lang pt-BR` and reading `(no rows)`
/// back is what showed it.
///
/// The rule was not wrong so much as over-stated. It protects IDENTIFIERS —
/// command names, flag names, payload keys, failure codes — because a program
/// reads those and they must not move with the reader's language. The plain
/// text shape is published as being for a human reader, so what it carries is
/// prose, and prose follows the reader.
///
/// The other three shapes are for programs and carry no sentence at all, which
/// the proof below this one measures.
#[test]
fn the_plain_text_shape_follows_the_language() {
    let sandbox = Sandbox::new();
    let portuguese = sandbox
        .run(&["--lang", "pt-BR", "conn", "list", "--output-format", "text"])
        .out;
    let english = sandbox
        .run(&["--lang", "en", "conn", "list", "--output-format", "text"])
        .out;

    assert!(
        portuguese.contains("sem linhas"),
        "the empty table was not written in Portuguese: {portuguese}"
    );
    assert!(
        english.contains("no rows"),
        "the empty table was not written in English: {english}"
    );
    assert_ne!(
        portuguese, english,
        "the language never reached the primary channel"
    );
}

/// FR-054. The machine shapes carry no sentence, so the language cannot move
/// anything a program reads.
///
/// This is the other half of the rule the heading of the catalogues states.
/// Widening prose to the plain text shape would be a defect if it also widened
/// to these, so the widening is measured rather than promised.
#[test]
fn the_machine_shapes_do_not_move_with_the_language() {
    let sandbox = Sandbox::new();
    for shape in ["json", "ndjson", "tsv"] {
        let portuguese = sandbox
            .run(&["--lang", "pt-BR", "conn", "list", "--output-format", shape])
            .out;
        let english = sandbox
            .run(&["--lang", "en", "conn", "list", "--output-format", shape])
            .out;
        assert_eq!(
            portuguese, english,
            "the `{shape}` shape moved with the language, and a program reads it"
        );
    }
}