use assert_cmd::Command;
#[test]
fn help_flag_prints_usage_and_exits_zero() {
let out = Command::cargo_bin("croft").unwrap().arg("--help").assert();
let out = out.success();
let stdout = String::from_utf8(out.get_output().stdout.clone()).unwrap();
assert!(stdout.contains("Usage:"), "stdout was: {stdout}");
assert!(stdout.contains("setup-terminal"));
}
#[test]
fn version_flag_prints_version() {
let out = Command::cargo_bin("croft")
.unwrap()
.arg("--version")
.assert();
let out = out.success();
let stdout = String::from_utf8(out.get_output().stdout.clone()).unwrap();
assert!(stdout.contains("croft"));
}
#[test]
fn build_info_carries_provenance_and_version_does_not() {
let out = Command::cargo_bin("croft")
.unwrap()
.arg("--build-info")
.assert();
let out = out.success();
let build_info = String::from_utf8(out.get_output().stdout.clone()).unwrap();
assert!(
build_info.contains(env!("CARGO_PKG_VERSION")) && build_info.contains("built "),
"--build-info carries version and build time: {build_info}"
);
let out = Command::cargo_bin("croft")
.unwrap()
.arg("--version")
.assert();
let out = out.success();
let version = String::from_utf8(out.get_output().stdout.clone()).unwrap();
assert_eq!(
version.trim(),
format!("croft {}", env!("CARGO_PKG_VERSION")),
"--version stays bare"
);
}
#[test]
fn setup_terminal_help_works() {
Command::cargo_bin("croft")
.unwrap()
.args(["setup-terminal", "--help"])
.assert()
.success();
}
#[test]
fn probe_subcommands_answer_instantly_even_with_a_stripped_path() {
let dir = tempfile::tempdir().unwrap();
let slow_shell = dir.path().join("slow-shell");
std::fs::write(&slow_shell, "#!/bin/sh\nsleep 30\n").unwrap();
let mut perm = std::fs::metadata(&slow_shell).unwrap().permissions();
std::os::unix::fs::PermissionsExt::set_mode(&mut perm, 0o755);
std::fs::set_permissions(&slow_shell, perm).unwrap();
for sub in ["session-host", "collab-relay"] {
let start = std::time::Instant::now();
Command::cargo_bin("croft")
.unwrap()
.args([sub, "--probe"])
.env("PATH", "/usr/bin:/bin:/usr/sbin:/sbin")
.env("SHELL", &slow_shell)
.assert()
.success();
assert!(
start.elapsed() < std::time::Duration::from_secs(15),
"{sub} --probe took {:?} with a stripped PATH",
start.elapsed()
);
}
}
#[test]
fn nonexistent_path_fails_cleanly() {
Command::cargo_bin("croft")
.unwrap()
.arg("/nonexistent/path/that/does/not/exist/abc123")
.assert()
.failure();
}
#[test]
fn pair_off_and_reactivation_keep_the_recorded_backend() {
let home = tempfile::Builder::new()
.prefix("h")
.tempdir_in("/tmp")
.unwrap();
let ws = tempfile::tempdir().unwrap();
let run = |args: &[&str]| {
Command::cargo_bin("croft")
.unwrap()
.args(args)
.arg("--workspace")
.arg(ws.path())
.env("HOME", home.path())
.assert()
.success();
};
run(&[
"pair",
"--provider",
"ollama",
"--model",
"qwen3-coder:30b",
"--base-url",
"http://localhost:9999",
]);
let record_path = || {
let dir = home.path().join(".cache/croft/sessions");
std::fs::read_dir(&dir)
.unwrap()
.filter_map(|e| e.ok())
.map(|e| e.path())
.find(|p| p.to_string_lossy().ends_with(".pair.json"))
.expect("a pair record exists")
};
let read = || std::fs::read_to_string(record_path()).unwrap();
assert!(read().contains("http://localhost:9999"));
run(&["pair", "--provider", "ollama", "--off"]);
let r = read();
assert!(r.contains("\"enabled\":false"), "{r}");
assert!(
r.contains("http://localhost:9999"),
"the default endpoint must not clobber the custom one: {r}"
);
run(&["pair"]);
let r = read();
assert!(r.contains("\"enabled\":true"), "{r}");
assert!(r.contains("\"provider\":\"ollama\""), "{r}");
assert!(r.contains("http://localhost:9999"), "{r}");
assert!(r.contains("qwen3-coder:30b"), "{r}");
run(&["pair", "--provider", "claude"]);
let r = read();
assert!(r.contains("\"provider\":\"claude\""), "{r}");
assert!(
!r.contains("http://localhost:9999"),
"the ollama endpoint must not survive a provider switch: {r}"
);
assert!(!r.contains("qwen3-coder:30b"), "{r}");
let sessions = home.path().join(".cache/croft/sessions");
if let Ok(entries) = std::fs::read_dir(&sessions) {
for e in entries.filter_map(|e| e.ok()) {
let p = e.path();
if p.to_string_lossy().ends_with(".collab.sock") {
let _ = std::process::Command::new("pkill")
.args(["-f", &p.to_string_lossy()])
.status();
}
}
}
}
#[test]
fn view_outside_croft_exits_one_with_an_explanation() {
let out = Command::cargo_bin("croft")
.unwrap()
.env_remove("CROFT_VIEW_SOCK")
.args(["view", "Cargo.toml"])
.assert();
let out = out.failure().code(1);
let stderr = String::from_utf8(out.get_output().stderr.clone()).unwrap();
assert!(
stderr.contains("croft view needs a croft"),
"stderr must say why, was: {stderr}"
);
assert_eq!(
stderr.lines().filter(|l| !l.trim().is_empty()).count(),
1,
"one line, not a backtrace: {stderr}"
);
}
#[test]
fn view_treats_an_empty_socket_variable_as_no_croft_at_all() {
let out = Command::cargo_bin("croft")
.unwrap()
.env("CROFT_VIEW_SOCK", "")
.args(["view", "Cargo.toml"])
.assert();
let out = out.failure().code(1);
let stderr = String::from_utf8(out.get_output().stderr.clone()).unwrap();
assert!(
stderr.contains("croft view needs a croft"),
"stderr was: {stderr}"
);
}
#[test]
fn view_against_a_vanished_croft_says_the_croft_is_gone() {
let tmp = tempfile::tempdir().unwrap();
let out = Command::cargo_bin("croft")
.unwrap()
.env("CROFT_VIEW_SOCK", tmp.path().join("nobody.sock"))
.args(["view", "Cargo.toml"])
.assert();
let out = out.failure().code(1);
let stderr = String::from_utf8(out.get_output().stderr.clone()).unwrap();
assert!(
stderr.contains("is gone"),
"stderr must name the situation, was: {stderr}"
);
}
#[test]
fn view_sends_the_resolved_path_to_the_socket_and_exits_zero() {
use std::io::{BufRead, BufReader, Write};
let tmp = tempfile::tempdir().unwrap();
let sock = tmp.path().join("v.sock");
let target = tmp.path().join("report.txt");
std::fs::write(&target, b"hello").unwrap();
let listener = std::os::unix::net::UnixListener::bind(&sock).unwrap();
let server = std::thread::spawn(move || {
let (mut stream, _) = listener.accept().unwrap();
let mut line = String::new();
BufReader::new(&stream).read_line(&mut line).unwrap();
stream.write_all(b"{\"status\":\"ok\"}\n").unwrap();
line
});
Command::cargo_bin("croft")
.unwrap()
.env("CROFT_VIEW_SOCK", &sock)
.current_dir(tmp.path())
.args(["view", "report.txt"])
.assert()
.success();
let request = server.join().unwrap();
let bytes: Vec<u8> = request
.trim()
.trim_start_matches("{\"path\":[")
.trim_end_matches("]}")
.split(',')
.map(|n| n.trim().parse::<u8>().expect("the wire is a byte array"))
.collect();
let received = std::path::PathBuf::from(String::from_utf8(bytes).unwrap());
assert_eq!(
received.canonicalize().unwrap_or(received),
target.canonicalize().unwrap_or(target.clone()),
"the server must receive the path resolved against the client's cwd"
);
}
#[test]
fn view_refuses_a_missing_file_without_bothering_the_socket() {
let tmp = tempfile::tempdir().unwrap();
let sock = tmp.path().join("v.sock");
let _listener = std::os::unix::net::UnixListener::bind(&sock).unwrap();
let out = Command::cargo_bin("croft")
.unwrap()
.env("CROFT_VIEW_SOCK", &sock)
.current_dir(tmp.path())
.args(["view", "nope.pdf"])
.assert();
let out = out.failure().code(1);
let stderr = String::from_utf8(out.get_output().stderr.clone()).unwrap();
assert!(
stderr.contains("no such file") && stderr.contains("nope.pdf"),
"stderr must name the missing path, was: {stderr}"
);
}
#[cfg(all(unix, not(target_os = "macos")))]
#[test]
fn view_transmits_a_non_utf8_filename_byte_for_byte() {
use std::ffi::OsStr;
use std::io::{BufRead, BufReader, Write};
use std::os::unix::ffi::OsStrExt;
let tmp = tempfile::tempdir().unwrap();
let sock = tmp.path().join("v.sock");
let name = OsStr::from_bytes(b"od\xffd.txt");
let target = tmp.path().join(name);
std::fs::write(&target, b"x").unwrap();
assert!(
target.to_str().is_none(),
"fixture must be invalid UTF-8, or this test proves nothing"
);
let listener = std::os::unix::net::UnixListener::bind(&sock).unwrap();
let server = std::thread::spawn(move || {
let (mut stream, _) = listener.accept().unwrap();
let mut line = String::new();
BufReader::new(&stream).read_line(&mut line).unwrap();
stream.write_all(b"{\"status\":\"ok\"}\n").unwrap();
line
});
Command::cargo_bin("croft")
.unwrap()
.env("CROFT_VIEW_SOCK", &sock)
.current_dir(tmp.path())
.arg("view")
.arg(name)
.assert()
.success();
let request = server.join().unwrap();
let bytes: Vec<u8> = request
.trim()
.trim_start_matches("{\"path\":[")
.trim_end_matches("]}")
.split(',')
.map(|n| n.trim().parse::<u8>().expect("the wire is a byte array"))
.collect();
assert!(
bytes.contains(&0xff),
"the 0xff byte must reach the server intact, got {bytes:?}"
);
assert_eq!(std::path::PathBuf::from(OsStr::from_bytes(&bytes)), target);
}
#[test]
fn view_refuses_an_as_flag_that_cannot_be_a_file_extension() {
let tmp = tempfile::tempdir().unwrap();
let sock = tmp.path().join("v.sock");
let _listener = std::os::unix::net::UnixListener::bind(&sock).unwrap();
let home = tmp.path().join("home");
std::fs::create_dir(&home).unwrap();
let out = Command::cargo_bin("croft")
.unwrap()
.env("CROFT_VIEW_SOCK", &sock)
.env("HOME", &home)
.current_dir(tmp.path())
.write_stdin("a,b\n1,2\n")
.args(["view", "-", "--as", "../x"])
.assert();
let out = out.failure().code(1);
let stderr = String::from_utf8(out.get_output().stderr.clone()).unwrap();
assert!(
stderr.contains("--as"),
"the message must name the flag, was: {stderr}"
);
assert!(
!home.join(".cache/croft/view-stdin").exists(),
"a refused --as must not create the staging directory"
);
}
#[test]
fn view_from_a_pipe_stages_an_owner_only_file_and_sends_its_path() {
use std::io::{BufRead, BufReader, Write};
use std::os::unix::fs::PermissionsExt;
let tmp = tempfile::tempdir().unwrap();
let home = tmp.path().join("home");
std::fs::create_dir(&home).unwrap();
let sock = tmp.path().join("v.sock");
let listener = std::os::unix::net::UnixListener::bind(&sock).unwrap();
let server = std::thread::spawn(move || {
let (mut stream, _) = listener.accept().unwrap();
let mut line = String::new();
BufReader::new(&stream).read_line(&mut line).unwrap();
stream.write_all(b"{\"status\":\"ok\"}\n").unwrap();
line
});
Command::cargo_bin("croft")
.unwrap()
.env("CROFT_VIEW_SOCK", &sock)
.env("HOME", &home)
.current_dir(tmp.path())
.write_stdin("a,b\n1,2\n")
.args(["view", "-"])
.assert()
.success();
let request = server.join().unwrap();
let bytes: Vec<u8> = request
.trim()
.trim_start_matches("{\"path\":[")
.trim_end_matches("]}")
.split(',')
.map(|n| n.trim().parse::<u8>().expect("the wire is a byte array"))
.collect();
let staged = std::path::PathBuf::from(String::from_utf8(bytes).unwrap());
assert_eq!(
staged.extension().and_then(|e| e.to_str()),
Some("csv"),
"delimited text must be staged under the extension the sheet viewer \
routes on, or it arrives as plain text: {staged:?}"
);
assert!(
staged.starts_with(home.join(".cache").join("croft")),
"the staged file belongs under the cache dir, not beside the user's \
own files: {staged:?}"
);
let meta = std::fs::metadata(&staged)
.expect("the staged file must exist by the time the server is told about it");
assert_eq!(
meta.permissions().mode() & 0o777,
0o600,
"piped content is owner-only: `vault read ... | croft view -` is the \
case this command invites"
);
assert_eq!(
std::fs::read(&staged).unwrap(),
b"a,b\n1,2\n",
"and it is the bytes that came down the pipe, unaltered"
);
}
#[test]
fn view_refuses_an_as_flag_on_a_named_file_rather_than_ignoring_it() {
let tmp = tempfile::tempdir().unwrap();
let sock = tmp.path().join("v.sock");
let target = tmp.path().join("data.log");
std::fs::write(&target, b"a,b\n1,2\n").unwrap();
let _listener = std::os::unix::net::UnixListener::bind(&sock).unwrap();
let out = Command::cargo_bin("croft")
.unwrap()
.env("CROFT_VIEW_SOCK", &sock)
.current_dir(tmp.path())
.args(["view", "data.log", "--as", "csv"])
.assert();
let out = out.failure().code(1);
let stderr = String::from_utf8(out.get_output().stderr.clone()).unwrap();
assert!(
stderr.contains("--as"),
"the message must name the flag that was refused, was: {stderr}"
);
assert!(
stderr.contains("piped"),
"and say what it applies to, or the user cannot tell what to do \
instead, was: {stderr}"
);
}
#[test]
fn view_from_an_empty_pipe_says_nothing_arrived() {
let tmp = tempfile::tempdir().unwrap();
let home = tmp.path().join("home");
std::fs::create_dir(&home).unwrap();
let sock = tmp.path().join("v.sock");
let _listener = std::os::unix::net::UnixListener::bind(&sock).unwrap();
let out = Command::cargo_bin("croft")
.unwrap()
.env("CROFT_VIEW_SOCK", &sock)
.env("HOME", &home)
.current_dir(tmp.path())
.write_stdin("")
.args(["view", "-"])
.assert();
let out = out.failure().code(1);
let stderr = String::from_utf8(out.get_output().stderr.clone()).unwrap();
assert!(
stderr.contains("nothing arrived on stdin"),
"an empty pipe must say so rather than staging a zero-byte file and \
reporting success, was: {stderr}"
);
assert!(
!home.join(".cache/croft/view-stdin").exists(),
"and it must not create the staging directory either"
);
}
#[cfg(unix)]
#[test]
fn typing_with_images_on_does_not_stream_images_per_keystroke() {
use std::io::Read;
use std::os::fd::{FromRawFd, OwnedFd};
use std::os::unix::process::CommandExt;
use std::time::{Duration, Instant};
let home = tempfile::tempdir().unwrap();
let file = home.path().join("a.rs");
std::fs::write(&file, "fn main() {\n println!(\"hi\");\n}\n".repeat(300)).unwrap();
let (mut master, mut slave) = (0, 0);
let ws = libc::winsize {
ws_row: 50,
ws_col: 160,
ws_xpixel: 160 * 9,
ws_ypixel: 50 * 18,
};
assert_eq!(
unsafe {
libc::openpty(
&mut master,
&mut slave,
std::ptr::null_mut(),
std::ptr::null(),
&ws,
)
},
0
);
let slave = unsafe { OwnedFd::from_raw_fd(slave) };
let bin = assert_cmd::cargo::cargo_bin("croft");
let mut cmd = std::process::Command::new(bin);
cmd.arg("a.rs")
.current_dir(home.path())
.env("HOME", home.path())
.env("TERM", "xterm-256color")
.env("TERM_PROGRAM", "iTerm.app")
.env("CROFT_FORCE_INLINE_IMAGES", "1")
.stdin(slave.try_clone().unwrap())
.stdout(slave.try_clone().unwrap())
.stderr(slave.try_clone().unwrap());
unsafe {
cmd.pre_exec(|| {
libc::setsid();
libc::ioctl(0, libc::TIOCSCTTY as _, 0);
Ok(())
});
}
let mut child = cmd.spawn().unwrap();
drop(slave);
unsafe {
let flags = libc::fcntl(master, libc::F_GETFL);
libc::fcntl(master, libc::F_SETFL, flags | libc::O_NONBLOCK);
}
let mut pty = unsafe { std::fs::File::from_raw_fd(master) };
let mut tty = pty.try_clone().unwrap();
let mut drain = |for_: Duration| {
let mut n = 0usize;
let mut buf = [0u8; 1 << 16];
let end = Instant::now() + for_;
while Instant::now() < end {
match pty.read(&mut buf) {
Ok(0) => break,
Ok(k) => n += k,
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
std::thread::sleep(Duration::from_millis(10))
}
Err(_) => break,
}
}
n
};
let started = drain(Duration::from_secs(8));
assert!(started > 1000, "croft drew nothing ({started} bytes)");
use std::io::Write;
tty.write_all(b"\x1b").unwrap();
drain(Duration::from_secs(2));
let mut typed = 0;
for _ in 0..20 {
tty.write_all(b"x").unwrap();
typed += drain(Duration::from_millis(80));
}
typed += drain(Duration::from_secs(1));
let _ = child.kill();
let _ = child.wait();
assert!(
typed < 30_000,
"20 keystrokes wrote {typed} bytes: images are being re-sent per frame"
);
}
#[test]
fn locale_template_accepts_a_full_locale() {
let out = Command::cargo_bin("croft")
.unwrap()
.args(["locale-template", "de_DE.UTF-8"])
.assert()
.success();
let stdout = String::from_utf8(out.get_output().stdout.clone()).unwrap();
let stderr = String::from_utf8(out.get_output().stderr.clone()).unwrap();
let catalog: serde_json::Value = serde_json::from_str(&stdout).unwrap();
let filled = catalog
.as_object()
.unwrap()
.values()
.filter(|v| v.as_str().is_some_and(|s| !s.is_empty()))
.count();
assert!(filled > 0, "the built-in German entries seed it");
assert!(stderr.contains("locales/de.json"), "{stderr}");
}