wdxtools 0.4.2

Everyday formatting tools for the command line
Documentation
//! End-to-end tests over the built binary: argument handling, batch mode,
//! templates, the busybox symlink pattern and exit codes.

use std::io::Write;
use std::process::{Command, Stdio};

fn bin() -> std::path::PathBuf {
    // The integration test binary lives next to the CLI binary.
    let mut p = std::env::current_exe().unwrap();
    p.pop();
    if p.ends_with("deps") {
        p.pop();
    }
    p.join(format!("wdxtools{}", std::env::consts::EXE_SUFFIX))
}

struct Out {
    code: i32,
    stdout: String,
    stderr: String,
}

fn run(args: &[&str], stdin: Option<&str>) -> Out {
    run_as(bin(), args, stdin)
}

fn run_as(program: impl AsRef<std::ffi::OsStr>, args: &[&str], stdin: Option<&str>) -> Out {
    let mut child = Command::new(program)
        .args(args)
        .env("TZ", "UTC")
        .stdin(if stdin.is_some() {
            Stdio::piped()
        } else {
            Stdio::null()
        })
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("spawn wdxtools");

    if let Some(input) = stdin {
        child
            .stdin
            .as_mut()
            .unwrap()
            .write_all(input.as_bytes())
            .unwrap();
    }

    let out = child.wait_with_output().unwrap();
    Out {
        code: out.status.code().unwrap_or(-1),
        stdout: String::from_utf8_lossy(&out.stdout).into_owned(),
        stderr: String::from_utf8_lossy(&out.stderr).into_owned(),
    }
}

#[test]
fn numcrn_arguments() {
    let cases: &[(&[&str], &str)] = &[
        (&["numcrn", "489939"], "490K\n"),
        (&["numcrn", "-m", "2", "489939"], "489.94K\n"),
        (&["numcrn", "-p", "2", "1000000"], "1.00M\n"),
        (&["numcrn", "-l", "1000000"], "1 million\n"),
        (&["numcrn", "1000000000000000000"], "1KQ\n"),
        // Negative values pass through positionally.
        (&["numcrn", "-1000"], "-1K\n"),
        (&["numcrn", "-m", "2", "-489939"], "-489.94K\n"),
        // Multiple arguments produce one line each.
        (&["numcrn", "1000", "2000000"], "1K\n2M\n"),
    ];

    for (args, want) in cases {
        let out = run(args, None);
        assert_eq!(out.stdout, *want, "args: {args:?}");
        assert_eq!(out.code, 0, "args: {args:?}");
    }
}

#[test]
fn numcrn_batch_and_errors() {
    let out = run(&["numcrn", "-m", "2"], Some("1000\n489939\n\n-1000\n"));
    assert_eq!(out.stdout, "1K\n489.94K\n-1K\n");
    assert_eq!(out.code, 0);

    let out = run(&["numcrn"], Some("1000\nabc\n"));
    assert_eq!(out.stdout, "1K\n", "output before the error is preserved");
    assert!(out.stderr.contains("invalid number"), "{}", out.stderr);
    assert_eq!(out.code, 1);

    let out = run(&["numcrn", "abc"], None);
    assert!(out.stderr.contains("invalid number"));
    assert_eq!(out.code, 1);
}

#[test]
fn diffh_arguments() {
    let cases: &[(&[&str], &str)] = &[
        (&["diffh", "2024-01-15", "2025-01-15"], "1 year before\n"),
        (&["diffh", "-s", "2024-01-15", "2025-01-15"], "1y before\n"),
        (&["diffh", "-a", "2024-01-15", "2025-01-15"], "1 year\n"),
        (
            &["diffh", "-a", "-p", "3", "2024-01-15", "2025-03-20"],
            "1 year, 2 months, and 5 days\n",
        ),
        (&["diffh", "-a", "2025-01-15", "2024-01-15"], "1 year\n"),
        // Every accepted input format resolves to the same instant.
        (
            &["diffh", "-a", "2024-01-15T10:30:00", "2024-01-15 10:30:00"],
            "0 seconds\n",
        ),
        (
            &["diffh", "-a", "2024-01-15T10:30:00Z", "2024-01-15T10:30:00"],
            "0 seconds\n",
        ),
        (
            &[
                "diffh",
                "-a",
                "2024-01-15T06:30:00-04:00",
                "2024-01-15T10:30:00Z",
            ],
            "0 seconds\n",
        ),
        (&["diffh", "-a", "0", "1970-01-01"], "0 seconds\n"),
        // Pre-epoch timestamps pass through positionally.
        (&["diffh", "-a", "-86400", "0"], "1 day\n"),
    ];

    for (args, want) in cases {
        let out = run(args, None);
        assert_eq!(out.stdout, *want, "args: {args:?} stderr: {}", out.stderr);
        assert_eq!(out.code, 0, "args: {args:?}");
    }
}

#[test]
fn diffh_option_flags() {
    let cases: &[(&[&str], &str)] = &[
        (
            &["diffh", "-a", "-j", "2024-01-15", "2024-01-15"],
            "0 seconds\n",
        ),
        (
            &["diffh", "-a", "-n", "2024-01-15", "2024-01-15"],
            "1 second\n",
        ),
        // Sequential stops at the first gap: years is set, months is 0.
        (
            &[
                "diffh",
                "-a",
                "-S",
                "-p",
                "7",
                "2024-01-15T10:00:00",
                "2025-01-15T12:00:00",
            ],
            "1 year\n",
        ),
        // Without -S the same interval keeps collecting past the gap.
        (
            &[
                "diffh",
                "-a",
                "-p",
                "7",
                "2024-01-15T10:00:00",
                "2025-01-15T12:00:00",
            ],
            "1 year and 2 hours\n",
        ),
        (
            &[
                "diffh",
                "-a",
                "-p",
                "7",
                "2024-01-15T10:00:00",
                "2024-01-15T12:30:15",
            ],
            "2 hours, 30 minutes, and 15 seconds\n",
        ),
    ];

    for (args, want) in cases {
        let out = run(args, None);
        assert_eq!(out.stdout, *want, "args: {args:?}");
    }
}

#[test]
fn diffh_batch_and_templates() {
    // Batch mode compares against "now", so assert on shape rather than value.
    let out = run(&["diffh"], Some("2024-01-15\n2025-06-01\n\n"));
    assert_eq!(out.stdout.lines().count(), 2);
    assert!(
        out.stdout.lines().all(|l| l.ends_with(" ago")),
        "{}",
        out.stdout
    );
    assert_eq!(out.code, 0);

    let out = run(
        &["diffh", "-f", "$2 ($d)"],
        Some("2024-01-15 alpha\n2025-06-01 beta\n"),
    );
    let lines: Vec<&str> = out.stdout.lines().collect();
    assert_eq!(lines.len(), 2);
    assert!(lines[0].starts_with("alpha ("), "{}", lines[0]);
    assert!(lines[1].starts_with("beta ("), "{}", lines[1]);

    let out = run(&["diffh", "-f", "$1\\t$d"], Some("2024-01-15 x\n"));
    assert!(out.stdout.starts_with("2024-01-15\t"), "{:?}", out.stdout);

    // Unknown field indices expand to nothing; unknown `$` sequences survive.
    let out = run(&["diffh", "-f", "[$9][$$][a$]"], Some("2024-01-15\n"));
    assert_eq!(out.stdout, "[][$$][a$]\n");

    // A bad date in batch mode fails after flushing prior output.
    let out = run(&["diffh"], Some("2024-01-15\nnope\n"));
    assert_eq!(out.stdout.lines().count(), 1);
    assert!(out.stderr.contains("invalid date"), "{}", out.stderr);
    assert_eq!(out.code, 1);
}

#[test]
fn version_and_help() {
    let out = run(&["version"], None);
    assert!(out.stdout.starts_with("wdxtools "), "{}", out.stdout);
    assert_eq!(out.code, 0);

    let out = run(&["--version"], None);
    assert!(out.stdout.contains(env!("CARGO_PKG_VERSION")));

    // No subcommand prints help and fails, matching the original.
    let out = run(&[], None);
    assert_ne!(out.code, 0);
    assert!(out.stderr.contains("Usage") || out.stdout.contains("Usage"));
}

#[test]
fn busybox_symlinks() {
    let dir = std::env::temp_dir().join(format!("wdx-symlink-{}", std::process::id()));
    let _ = std::fs::create_dir_all(&dir);

    for name in ["diffh", "numcrn"] {
        let link = dir.join(format!("{name}{}", std::env::consts::EXE_SUFFIX));
        let _ = std::fs::remove_file(&link);
        #[cfg(unix)]
        std::os::unix::fs::symlink(bin(), &link).unwrap();
        #[cfg(windows)]
        std::fs::copy(bin(), &link).unwrap();
    }

    let out = run_as(
        dir.join(format!("numcrn{}", std::env::consts::EXE_SUFFIX)),
        &["-m", "2", "489939"],
        None,
    );
    assert_eq!(out.stdout, "489.94K\n", "stderr: {}", out.stderr);

    let out = run_as(
        dir.join(format!("diffh{}", std::env::consts::EXE_SUFFIX)),
        &["-a", "2024-01-15", "2025-01-15"],
        None,
    );
    assert_eq!(out.stdout, "1 year\n", "stderr: {}", out.stderr);

    let _ = std::fs::remove_dir_all(&dir);
}