coip-cli 0.1.0

CLI for converting, importing, exporting, diffing, inspecting, querying, verifying, and benchmarking COI (.coi) IP databases
use std::path::PathBuf;
use std::process::Command;

fn coip_bin() -> PathBuf {
    PathBuf::from(env!("CARGO_BIN_EXE_coip"))
}

fn minimal_vector() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("..")
        .join("..")
        .join("test-vectors")
        .join("minimal_dual_stack.coi")
}

#[test]
fn test_query_and_lookup_pure_json_outputs() {
    let bin = coip_bin();
    let coi = minimal_vector();

    // 1. Single IP with `query --json` -> pure JSON object (no "ip =>" prefix)
    let out_q = Command::new(&bin)
        .args([
            "query",
            coi.to_str().unwrap(),
            "8.8.8.8",
            "--fields",
            "country.iso_code,location.latitude",
            "--json",
        ])
        .output()
        .unwrap();
    assert!(out_q.status.success());
    let stdout_q = String::from_utf8(out_q.stdout).unwrap();
    let parsed_q: serde_json::Value = serde_json::from_str(&stdout_q).unwrap();
    assert_eq!(parsed_q["country"]["iso_code"], "US");
    assert_eq!(parsed_q["location"]["latitude"], 37.7510123);

    // 2. Single IP with `lookup --json` matches `query --json` identically
    let out_l = Command::new(&bin)
        .args([
            "lookup",
            coi.to_str().unwrap(),
            "8.8.8.8",
            "--fields",
            "country.iso_code,location.latitude",
            "--json",
        ])
        .output()
        .unwrap();
    assert!(out_l.status.success());
    assert_eq!(String::from_utf8(out_l.stdout).unwrap(), stdout_q);

    // 3. Not-found single IP with `--json` -> pure `null`
    let out_miss = Command::new(&bin)
        .args(["query", coi.to_str().unwrap(), "0.0.0.1", "--json"])
        .output()
        .unwrap();
    assert!(out_miss.status.success());
    assert_eq!(String::from_utf8(out_miss.stdout).unwrap().trim(), "null");

    // 4. Multiple IPs with `--json --pretty` -> single valid JSON map keyed by IP
    let out_multi = Command::new(&bin)
        .args([
            "query",
            coi.to_str().unwrap(),
            "1.1.1.1",
            "8.8.8.8",
            "0.0.0.1",
            "--fields",
            "country.iso_code,traits.is_anycast",
            "--json",
            "--pretty",
        ])
        .output()
        .unwrap();
    assert!(out_multi.status.success());
    let stdout_m = String::from_utf8(out_multi.stdout).unwrap();
    assert!(stdout_m.contains('\n'));
    let parsed_m: serde_json::Value = serde_json::from_str(&stdout_m).unwrap();
    assert_eq!(parsed_m["1.1.1.1"]["traits"]["is_anycast"], true);
    assert_eq!(parsed_m["8.8.8.8"]["country"]["iso_code"], "US");
    assert!(parsed_m["0.0.0.1"].is_null());

    // 5. Default (without --json) preserves "ip => json" format for both lookup & query
    let out_def = Command::new(&bin)
        .args([
            "query",
            coi.to_str().unwrap(),
            "8.8.8.8",
            "--fields",
            "country.iso_code",
        ])
        .output()
        .unwrap();
    assert!(out_def.status.success());
    assert_eq!(
        String::from_utf8(out_def.stdout).unwrap().trim(),
        r#"8.8.8.8 => {"country":{"iso_code":"US"}}"#
    );
}

#[test]
fn test_query_and_lookup_table_outputs() {
    let bin = coip_bin();
    let coi = minimal_vector();

    // 1. Single IP full record with `query --table` (nested structs + CJK + full float precision)
    let out_q = Command::new(&bin)
        .args(["query", coi.to_str().unwrap(), "8.8.8.8", "--table"])
        .output()
        .unwrap();
    assert!(out_q.status.success());
    let stdout_q = String::from_utf8(out_q.stdout).unwrap();
    let expected_full = "\
╭──────────┬───────────────────────────────────────────────────────╮
│          │ ╭──────────────────────┬────────────────────────────╮ │
│ country  │ │ geoname_id           │ 6252001                    │ │
│          │ │ is_in_european_union │ false                      │ │
│          │ │ iso_code             │ US                         │ │
│          │ │                      │ ╭───────┬────────────────╮ │ │
│          │ │ names                │ │ de    │ USA            │ │ │
│          │ │                      │ │ en    │ United States  │ │ │
│          │ │                      │ │ ja    │ アメリカ合衆国 │ │ │
│          │ │                      │ │ zh-CN │ 美国           │ │ │
│          │ │                      │ ╰───────┴────────────────╯ │ │
│          │ ╰──────────────────────┴────────────────────────────╯ │
│          │ ╭─────────────────┬─────────────────╮                 │
│ location │ │ accuracy_radius │ 1000            │                 │
│          │ │ latitude        │ 37.7510123      │                 │
│          │ │ longitude       │ -97.8220456     │                 │
│          │ │ time_zone       │ America/Chicago │                 │
│          │ ╰─────────────────┴─────────────────╯                 │
│          │ ╭────────────┬───────╮                                │
│ traits   │ │ is_anycast │ false │                                │
│          │ ╰────────────┴───────╯                                │
╰──────────┴───────────────────────────────────────────────────────╯";
    assert_eq!(stdout_q.trim_end_matches(['\r', '\n']), expected_full);

    // 2. `lookup --table` matches `query --table` identically
    let out_l = Command::new(&bin)
        .args(["lookup", coi.to_str().unwrap(), "8.8.8.8", "--table"])
        .output()
        .unwrap();
    assert!(out_l.status.success());
    assert_eq!(String::from_utf8(out_l.stdout).unwrap(), stdout_q);

    // 3. Single not-found IP with `--table` -> single-cell rounded `null` box
    let out_miss = Command::new(&bin)
        .args(["query", coi.to_str().unwrap(), "0.0.0.1", "--table"])
        .output()
        .unwrap();
    assert!(out_miss.status.success());
    assert_eq!(
        String::from_utf8(out_miss.stdout)
            .unwrap()
            .trim_end_matches(['\r', '\n']),
        "╭──────╮\n│ null │\n╰──────╯"
    );

    // 4. Multiple IPs with `--fields` and `--table` preserve CLI IP order
    let out_multi = Command::new(&bin)
        .args([
            "query",
            coi.to_str().unwrap(),
            "8.8.8.8",
            "1.1.1.1",
            "0.0.0.1",
            "--fields",
            "country.iso_code,traits.is_anycast",
            "--table",
        ])
        .output()
        .unwrap();
    assert!(out_multi.status.success());
    let stdout_m = String::from_utf8(out_multi.stdout).unwrap();
    let expected_multi = "\
╭─────────┬──────────────────────────────────────╮
│         │ ╭─────────┬────────────────────────╮ │
│ 8.8.8.8 │ │         │ ╭──────────┬────╮      │ │
│         │ │ country │ │ iso_code │ US │      │ │
│         │ │         │ ╰──────────┴────╯      │ │
│         │ │         │ ╭────────────┬───────╮ │ │
│         │ │ traits  │ │ is_anycast │ false │ │ │
│         │ │         │ ╰────────────┴───────╯ │ │
│         │ ╰─────────┴────────────────────────╯ │
│         │ ╭────────┬───────────────────────╮   │
│ 1.1.1.1 │ │        │ ╭────────────┬──────╮ │   │
│         │ │ traits │ │ is_anycast │ true │ │   │
│         │ │        │ ╰────────────┴──────╯ │   │
│         │ ╰────────┴───────────────────────╯   │
│ 0.0.0.1 │                                      │
╰─────────┴──────────────────────────────────────╯";
    let trimmed_m = stdout_m.trim_end_matches(['\r', '\n']);
    assert!(trimmed_m.find("8.8.8.8").unwrap() < trimmed_m.find("1.1.1.1").unwrap());
    assert!(trimmed_m.find("1.1.1.1").unwrap() < trimmed_m.find("0.0.0.1").unwrap());
    assert_eq!(trimmed_m, expected_multi);

    // 5. `--table` conflicts with `--json` and `--pretty`
    let conflict_json = Command::new(&bin)
        .args([
            "query",
            coi.to_str().unwrap(),
            "8.8.8.8",
            "--table",
            "--json",
        ])
        .output()
        .unwrap();
    assert!(!conflict_json.status.success());

    let conflict_pretty = Command::new(&bin)
        .args([
            "query",
            coi.to_str().unwrap(),
            "8.8.8.8",
            "--table",
            "--pretty",
        ])
        .output()
        .unwrap();
    assert!(!conflict_pretty.status.success());

    // 6. ANSI color respects CLICOLOR_FORCE and NO_COLOR
    let out_color = Command::new(&bin)
        .env("CLICOLOR_FORCE", "1")
        .env_remove("NO_COLOR")
        .args([
            "query",
            coi.to_str().unwrap(),
            "8.8.8.8",
            "--fields",
            "traits.is_anycast",
            "--table",
        ])
        .output()
        .unwrap();
    assert!(out_color.status.success());
    let colored = String::from_utf8(out_color.stdout).unwrap();
    assert!(colored.contains("\x1b[1;32m"));
    assert!(colored.contains("\x1b[96m"));

    let out_no_color = Command::new(&bin)
        .env("CLICOLOR_FORCE", "1")
        .env("NO_COLOR", "1")
        .args([
            "query",
            coi.to_str().unwrap(),
            "8.8.8.8",
            "--fields",
            "traits.is_anycast",
            "--table",
        ])
        .output()
        .unwrap();
    assert!(out_no_color.status.success());
    let plain = String::from_utf8(out_no_color.stdout).unwrap();
    assert!(!plain.contains('\x1b'));
}