use termlens::{Color, Screen};
fn data(name: &str) -> String {
format!("{}/tests/data/{name}", env!("CARGO_MANIFEST_DIR"))
}
#[test]
fn diff_exits_one_and_paints_the_changed_cells_on_a_terminal() -> termlens::Result<()> {
let mut t = termlens::bin!(
"termlens",
args(["diff", &data("before.snap"), &data("after.snap.new")])
)?;
let status = t.wait_exit()?;
assert_eq!(status.code(), Some(1), "{}", t.screen());
let s = t.screen();
assert!(s.contains("size: 30x4"), "{s}");
let (row, col) = s.find("Counter: 1").expect("the before side");
let one = s.cell(row, col + 9).unwrap();
assert_eq!(one.contents(), "1");
assert_eq!(one.style().fg, Color::Indexed(1), "{}", s.with_styles());
let (row, col) = s.find("Counter: 2").expect("the after side");
assert_eq!(s.cell(row, col + 9).unwrap().style().fg, Color::Indexed(2));
assert!(
s.contains("styles: 0: 0-4 fg=6 bold; 7-13 reverse โ 0-4 fg=6 bold"),
"{s}"
);
assert!(s.contains("2 rows unchanged"), "{s}");
Ok(())
}
#[test]
fn diff_stays_plain_when_asked_and_exits_zero_on_the_same_picture() -> termlens::Result<()> {
let mut t = termlens::bin!(
"termlens",
args([
"diff",
"--color",
"never",
&data("before.snap"),
&data("after.snap.new")
])
)?;
assert_eq!(t.wait_exit()?.code(), Some(1));
let s = t.screen();
assert!(
s.contains("^"),
"the marker line stands in for colour:\n{s}"
);
assert!(
s.find_by(|c| c.style().fg != Color::Default).is_none(),
"{}",
s.with_styles()
);
let mut t = termlens::bin!(
"termlens",
args(["diff", &data("before.snap"), &data("before.snap")])
)?;
assert_eq!(t.wait_exit()?.code(), Some(0));
assert!(t.screen().contains("no difference"), "{}", t.screen());
Ok(())
}
#[test]
fn diff_color_always_keeps_the_overlap_note_and_paints_the_rows() -> termlens::Result<()> {
let mut t = termlens::bin!(
"termlens",
args([
"diff",
"--color",
"always",
&data("overlap-before.snap"),
&data("overlap-after.snap")
])
)?;
assert_eq!(t.wait_exit()?.code(), Some(1), "{}", t.screen());
let s = t.screen();
assert!(
s.contains("compared over the 4x2 overlap; the rest is clipped"),
"the note saying the comparison was partial:\n{s}"
);
let (row, col) = s.find("abXX").expect("the after side");
let two = s.cell(row, col + 2).expect("a changed cell");
assert_eq!(two.contents(), "X");
assert_eq!(two.style().fg, Color::Indexed(2), "{}", s.with_styles());
#[cfg(not(windows))]
{
let (row, col) = s.find("โab โ").expect("the before side");
let blank = s.cell(row, col + 4).expect("a painted blank");
assert_eq!(blank.style().fg, Color::Indexed(1), "{}", s.with_styles());
}
let mut t = termlens::bin!(
"termlens",
args([
"diff",
"--color",
"always",
&data("overlap-before.snap"),
&data("overlap-before.snap")
])
)?;
assert_eq!(t.wait_exit()?.code(), Some(0));
let s = t.screen();
assert!(s.contains("no difference"), "{s}");
assert!(
s.find_by(|c| c.style().fg != Color::Default).is_none(),
"{}",
s.with_styles()
);
Ok(())
}
#[test]
fn diff_names_a_missing_or_unknown_color_value() -> termlens::Result<()> {
let out = with_stdin(
&[
"diff",
"--color",
&data("before.snap"),
&data("after.snap.new"),
],
"",
);
assert_eq!(out.status.code(), Some(2), "{out:?}");
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
stderr.starts_with(r#"termlens: --color takes auto, always or never, got ""#)
&& stderr.contains("before.snap")
&& !stderr.contains("Some("),
"the operand named as the value it was taken for: {stderr}"
);
let out = with_stdin(
&[
"diff",
&data("before.snap"),
&data("after.snap.new"),
"--color",
],
"",
);
assert_eq!(out.status.code(), Some(2), "{out:?}");
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
stderr.contains("--color needs a WHEN argument"),
"the missing value, not `None`: {stderr}"
);
let out = with_stdin(
&[
"diff",
"--color=pink",
&data("before.snap"),
&data("after.snap.new"),
],
"",
);
assert_eq!(out.status.code(), Some(2), "{out:?}");
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
stderr.contains(r#"--color takes auto, always or never, got "pink""#),
"the offending word alone: {stderr}"
);
Ok(())
}
#[test]
fn diff_accepts_the_three_color_words_in_both_spellings() -> termlens::Result<()> {
let before = data("before.snap");
let after = data("after.snap.new");
for word in ["auto", "always", "never"] {
let inline = format!("--color={word}");
for args in [
vec!["diff", "--color", word, before.as_str(), after.as_str()],
vec!["diff", inline.as_str(), before.as_str(), after.as_str()],
] {
let out = with_stdin(&args, "");
assert_eq!(out.status.code(), Some(1), "{word}: {out:?}");
let stdout = String::from_utf8_lossy(&out.stdout);
if word == "always" {
assert!(stdout.contains('\x1b'), "painted: {stdout}");
} else {
assert!(stdout.contains('^'), "plain, marker line and all: {stdout}");
}
}
}
let never = with_stdin(&["diff", "--color", "never", &before, &after], "");
let auto = with_stdin(&["diff", "--color=auto", &before, &after], "");
assert_eq!(never.stdout, auto.stdout, "a pipe is not a terminal");
assert!(
!auto.stdout.contains(&0x1b),
"no ANSI in a pipe: {}",
String::from_utf8_lossy(&auto.stdout)
);
Ok(())
}
#[test]
fn render_writes_svg_html_ansi_and_text() -> termlens::Result<()> {
for (flag, needle) in [("--svg", "<svg"), ("--html", "<pre"), ("--text", "styles:")] {
let mut t = termlens::bin!("termlens", args(["render", flag, &data("before.snap")]))?;
assert_eq!(t.wait_exit()?.code(), Some(0), "{flag}: {}", t.screen());
assert!(t.screen().contains(needle), "{flag}:\n{}", t.screen());
}
let mut t = termlens::bin!("termlens", args(["render", "--ansi", &data("before.snap")]))?;
assert_eq!(t.wait_exit()?.code(), Some(0));
let s = t.screen();
let (row, col) = s.find("myapp").expect("the title");
let title = s.cell(row, col).unwrap().style();
assert!(
title.bold && title.fg == Color::Indexed(6),
"{}",
s.with_styles()
);
let (row, col) = s.find("secret").expect("the field");
assert!(
s.cell(row, col).unwrap().style().conceal,
"{}",
s.with_styles()
);
Ok(())
}
#[test]
fn render_json_writes_the_document_render_text_reads_back() -> termlens::Result<()> {
use std::process::Command;
let bin = env!("CARGO_BIN_EXE_termlens");
let json = Command::new(bin)
.args(["render", "--json", &data("before.snap")])
.output()?;
assert_eq!(json.status.code(), Some(0), "{json:?}");
let document = String::from_utf8(json.stdout).expect("utf-8 JSON");
let value: serde_json::Value = serde_json::from_str(&document).expect("a JSON document");
assert_eq!(value["format"], 1, "{document}");
let screen: Screen = serde_json::from_str(&document).expect("a termlens Screen");
assert_eq!(screen.size(), (30, 4));
assert_eq!(
document,
format!(
"{}\n",
serde_json::to_string_pretty(&screen).expect("serialize")
)
);
let from_text = Command::new(bin)
.args(["render", "--text", &data("before.snap")])
.output()?;
assert_eq!(from_text.status.code(), Some(0), "{from_text:?}");
let back = with_stdin(&["render", "--text", "-"], &document);
assert_eq!(back.status.code(), Some(0), "{back:?}");
assert_eq!(
back.stdout, from_text.stdout,
"json -> text is the same screen"
);
let dir = std::env::temp_dir().join(format!("termlens-render-json-{}", std::process::id()));
std::fs::create_dir_all(&dir)?;
let written = dir.join("screen.json");
let out = Command::new(bin)
.args([
"render",
"--json",
"--out",
written.to_str().expect("utf-8 path"),
&data("before.snap"),
])
.output()?;
assert_eq!(out.status.code(), Some(0), "{out:?}");
assert!(out.stdout.is_empty(), "--out means not stdout: {out:?}");
assert_eq!(std::fs::read(&written)?, document.as_bytes());
let piped = with_stdin(&["render", "--json", "-"], &document);
assert_eq!(piped.status.code(), Some(0), "{piped:?}");
assert_eq!(piped.stdout, document.as_bytes(), "stdin is a path's equal");
let again = Command::new(bin)
.args(["render", "--json", written.to_str().expect("utf-8 path")])
.output()?;
assert_eq!(again.status.code(), Some(0), "{again:?}");
assert_eq!(
again.stdout,
document.as_bytes(),
"the JSON twin round-trips through the CLI"
);
let help = Command::new(bin).args(["render", "--help"]).output()?;
let usage = String::from_utf8_lossy(&help.stdout);
let first = usage.lines().next().expect("a usage line");
assert!(
first.contains("--json"),
"the usage line lists --json: {first}"
);
let _ = std::fs::remove_dir_all(&dir);
Ok(())
}
#[test]
fn a_file_that_is_not_a_screen_exits_two_and_names_it() -> termlens::Result<()> {
let mut t = termlens::bin!(
"termlens",
size(200, 10),
args(["render", "--svg", &data("missing.snap")])
)?;
assert_eq!(t.wait_exit()?.code(), Some(2));
assert!(
t.screen().contains("termlens: ") && t.screen().contains("missing.snap"),
"{}",
t.screen()
);
let mut t = termlens::bin!(
"termlens",
args(["diff", &data("cli.rs"), &data("before.snap")])
)?;
assert_eq!(t.wait_exit()?.code(), Some(2));
let mut t = termlens::bin!("termlens", args(["frobnicate"]))?;
assert_eq!(t.wait_exit()?.code(), Some(2));
assert!(t.screen().contains("unknown command"), "{}", t.screen());
Ok(())
}
#[test]
fn a_top_level_flag_is_an_unknown_option_not_a_command() {
use std::process::Command;
let bin = env!("CARGO_BIN_EXE_termlens");
for flag in ["--verbose", "-v"] {
let out = Command::new(bin).arg(flag).output().expect("spawn");
assert_eq!(out.status.code(), Some(2), "{flag}: {out:?}");
let stderr = String::from_utf8_lossy(&out.stderr);
assert_eq!(
stderr,
format!("termlens: unknown option {flag:?} (try --help)\n"),
"{flag}"
);
}
for command in ["nonesuch", "-"] {
let out = Command::new(bin).arg(command).output().expect("spawn");
assert_eq!(out.status.code(), Some(2), "{command}: {out:?}");
assert_eq!(
String::from_utf8_lossy(&out.stderr),
format!("termlens: unknown command {command:?} (try --help)\n"),
"{command}"
);
}
}
#[test]
fn the_text_a_wait_error_prints_is_a_saved_screen_too() -> termlens::Result<()> {
let path = std::env::temp_dir().join(format!("termlens-cli-{}.txt", std::process::id()));
std::fs::write(&path, "size: 10x2 cursor: hidden\nhello\n")?;
let mut t = termlens::bin!(
"termlens",
args(["render", "--text", path.to_str().unwrap()])
)?;
assert_eq!(t.wait_exit()?.code(), Some(0), "{}", t.screen());
let s = t.screen();
assert!(
s.contains("size: 10x2 cursor: hidden") && s.contains("(none)"),
"{s}"
);
let _ = std::fs::remove_file(&path);
Ok(())
}
#[test]
fn a_crlf_checkout_of_a_snap_still_parses() -> termlens::Result<()> {
let crlf = std::fs::read_to_string(data("before.snap"))?
.replace("\r\n", "\n")
.replace('\n', "\r\n");
let path = std::env::temp_dir().join(format!("termlens-cli-crlf-{}.snap", std::process::id()));
std::fs::write(&path, crlf)?;
let mut t = termlens::bin!(
"termlens",
args(["render", "--text", path.to_str().unwrap()])
)?;
assert_eq!(t.wait_exit()?.code(), Some(0), "{}", t.screen());
assert!(t.screen().contains("myapp > Alpha"), "{}", t.screen());
let _ = std::fs::remove_file(&path);
Ok(())
}
#[test]
#[cfg_attr(windows, ignore = "the program under inspection is a POSIX shell")]
fn inspect_prints_the_screen_and_the_exit_trailer() -> termlens::Result<()> {
let path = std::env::var("PATH").unwrap_or_default();
let mut t = termlens::bin!(
"termlens",
env("PATH", &path),
args(["inspect", "--size", "20x3", "sh", "-c", "printf 'hi there'"])
)?;
assert_eq!(t.wait_exit()?.code(), Some(0), "{}", t.screen());
let s = t.screen();
assert!(s.contains("size: 20x3") && s.contains("hi there"), "{s}");
assert!(s.contains("--- exited: exit code 0 ---"), "{s}");
let mut t = termlens::bin!(
"termlens",
env("PATH", &path),
args(["inspect", "--size", "12", "sh"])
)?;
assert_eq!(t.wait_exit()?.code(), Some(2));
assert!(
t.screen().contains("expected e.g. 120x40"),
"{}",
t.screen()
);
let mut t = termlens::bin!(
"termlens",
env("PATH", &path),
args(["inspect", "--size=12", "sh"])
)?;
assert_eq!(t.wait_exit()?.code(), Some(2));
assert!(
t.screen()
.contains("bad --size \"12\", expected e.g. 120x40"),
"{}",
t.screen()
);
Ok(())
}
#[test]
#[cfg_attr(windows, ignore = "the program under inspection is a POSIX shell")]
fn inspect_accepts_the_flag_equals_value_spelling() -> termlens::Result<()> {
let path = std::env::var("PATH").unwrap_or_default();
let mut t = termlens::bin!(
"termlens",
env("PATH", &path),
args([
"inspect",
"--size=60x3",
"--timeout=5",
"--idle=100",
"sh",
"-c",
"printf 'hi there'"
])
)?;
assert_eq!(t.wait_exit()?.code(), Some(0), "{}", t.screen());
let s = t.screen();
assert!(s.contains("size: 60x3") && s.contains("hi there"), "{s}");
Ok(())
}
#[test]
fn inspect_refuses_a_value_on_a_flag_that_takes_none() -> termlens::Result<()> {
let mut t = termlens::bin!(
"termlens",
args(["inspect", "--inherit-env=nonsense", "/bin/echo", "hi"])
)?;
let status = t.wait_exit()?;
assert_eq!(status.code(), Some(2), "{}", t.screen());
let s = t.screen();
assert!(
s.contains(r#"unknown option "--inherit-env=nonsense""#),
"the diagnostic names the whole token: {s}"
);
Ok(())
}
#[test]
#[cfg_attr(windows, ignore = "the program under inspection is a POSIX shell")]
fn inspect_env_equals_splits_on_the_first_equals() -> termlens::Result<()> {
let path = std::env::var("PATH").unwrap_or_default();
let dir = std::env::temp_dir().join(format!("termlens-eq-{}", std::process::id()));
std::fs::create_dir_all(&dir)?;
let real = std::fs::canonicalize(&dir)?;
let cwd = format!("--cwd={}", dir.display());
let mut t = termlens::bin!(
"termlens",
env("PATH", &path),
args([
"inspect",
"--size=200x3",
&cwd,
"--env=A=b=c",
"sh",
"-c",
"echo \"[$A] $(pwd)\""
])
)?;
assert_eq!(t.wait_exit()?.code(), Some(0), "{}", t.screen());
let s = t.screen();
assert!(s.contains("[b=c]"), "the value keeps its second `=`: {s}");
assert!(
s.contains(real.to_str().expect("utf-8 path")),
"the program ran in {}: {s}",
real.display()
);
let _ = std::fs::remove_dir_all(&dir);
Ok(())
}
#[test]
fn help_and_version() -> termlens::Result<()> {
let mut t = termlens::bin!("termlens", args(["--help"]))?;
assert_eq!(t.wait_exit()?.code(), Some(0));
assert!(
t.screen().contains("usage: termlens <command>"),
"{}",
t.screen()
);
let mut t = termlens::bin!("termlens", args(["inspect", "--help"]))?;
assert_eq!(t.wait_exit()?.code(), Some(0));
let help = t.screen().to_string();
assert!(
help.contains("--ansi") && help.contains("gets a saved screen"),
"`inspect --help` must say a redirect gets a saved screen:\n{help}"
);
let mut t = termlens::bin!("termlens", args(["--version"]))?;
assert_eq!(t.wait_exit()?.code(), Some(0));
assert!(
t.screen()
.contains(concat!("termlens ", env!("CARGO_PKG_VERSION"))),
"{}",
t.screen()
);
let mut t = termlens::bin!("termlens")?;
assert_eq!(t.wait_exit()?.code(), Some(2));
let _: Screen = Screen::parse("size: 1x1 cursor: 0,0\n")?;
Ok(())
}
#[test]
fn subcommand_version_prints_same_string_as_top_level() -> termlens::Result<()> {
let mut top = termlens::bin!("termlens", args(["--version"]))?;
assert_eq!(top.wait_exit()?.code(), Some(0));
let expected = concat!("termlens ", env!("CARGO_PKG_VERSION"));
for subcommand in ["diff", "render", "inspect"] {
let mut t = termlens::bin!("termlens", args([subcommand, "--version"]))?;
assert_eq!(
t.wait_exit()?.code(),
Some(0),
"`termlens {subcommand} --version` exited non-zero"
);
assert!(
t.screen().contains(expected),
"`termlens {subcommand} --version` output:\n{}",
t.screen()
);
}
Ok(())
}
#[test]
#[cfg_attr(windows, ignore = "the program under inspection is a POSIX shell")]
fn inspect_stdout_is_a_saved_screen_and_the_trailer_is_on_stderr() -> termlens::Result<()> {
use std::process::Command;
let bin = env!("CARGO_BIN_EXE_termlens");
let out = Command::new(bin)
.args(["inspect", "--size", "20x3", "sh", "-c", "printf 'hi there'"])
.output()?;
assert!(out.status.success(), "{out:?}");
let stdout = String::from_utf8(out.stdout).expect("utf-8");
let stderr = String::from_utf8(out.stderr).expect("utf-8");
assert!(stdout.starts_with("size: 20x3 cursor: "), "{stdout:?}");
assert!(stdout.contains("hi there"), "{stdout:?}");
assert!(
stdout.contains("styles:"),
"a redirect keeps the styles block: {stdout:?}"
);
assert!(!stdout.contains("---"), "no trailer on stdout: {stdout:?}");
assert_eq!(
stderr.trim_end(),
"--- exited: exit code 0 ---",
"{stderr:?}"
);
let parsed = Screen::parse(&stdout)?;
assert_eq!(parsed.size(), (20, 3));
assert_eq!(parsed.find("hi there"), Some((0, 0)));
let path =
std::env::temp_dir().join(format!("termlens-cli-inspect-{}.txt", std::process::id()));
std::fs::write(&path, &stdout)?;
let file = path.to_str().unwrap();
let render = Command::new(bin)
.args(["render", "--text", file])
.output()?;
assert_eq!(render.status.code(), Some(0), "{render:?}");
let diff = Command::new(bin).args(["diff", file, file]).output()?;
assert_eq!(diff.status.code(), Some(0), "{diff:?}");
let old = path.with_extension("old.txt");
std::fs::write(&old, format!("{stdout}--- exited: exit code 0 ---\n"))?;
let render = Command::new(bin)
.args(["render", "--text", old.to_str().unwrap()])
.output()?;
assert_eq!(render.status.code(), Some(0), "{render:?}");
let diff = Command::new(bin)
.args(["diff", file, old.to_str().unwrap()])
.output()?;
assert_eq!(
diff.status.code(),
Some(0),
"the trailer is not a row: {diff:?}"
);
let dashes = path.with_extension("dashes.txt");
std::fs::write(&dashes, "size: 20x2 cursor: 0,0\n--- not a trailer\n")?;
let render = Command::new(bin)
.args(["render", "--text", dashes.to_str().unwrap()])
.output()?;
assert_eq!(render.status.code(), Some(0), "{render:?}");
assert!(
String::from_utf8_lossy(&render.stdout).contains("--- not a trailer"),
"{render:?}"
);
for p in [path, old, dashes] {
let _ = std::fs::remove_file(p);
}
Ok(())
}
#[test]
fn inspect_double_dash_ends_the_options() {
use std::process::Command;
let bin = env!("CARGO_BIN_EXE_termlens");
let with = Command::new(bin)
.args(["inspect", "--size", "20x2", "--", "-weird", "ok"])
.output()
.expect("termlens runs");
assert_eq!(with.status.code(), Some(2), "{with:?}");
let stderr = String::from_utf8_lossy(&with.stderr);
assert!(
stderr.contains("failed to spawn") && stderr.contains("-weird"),
"after `--` a flag-shaped name is a program: {stderr}"
);
assert!(
!stderr.contains("unknown option"),
"`--` must stop option parsing: {stderr}"
);
let without = Command::new(bin)
.args(["inspect", "--size", "20x2", "-weird", "ok"])
.output()
.expect("termlens runs");
assert_eq!(without.status.code(), Some(2), "{without:?}");
assert!(
String::from_utf8_lossy(&without.stderr).contains("unknown option \"-weird\""),
"without `--` the same name is an option: {without:?}"
);
let echo = Command::new(bin)
.args(["inspect", "--size", "20x2", "--", "sh", "-c", "printf hi"])
.output()
.expect("termlens runs");
#[cfg(not(windows))]
{
assert_eq!(echo.status.code(), Some(0), "{echo:?}");
let screen = Screen::parse(&String::from_utf8_lossy(&echo.stdout)).expect("a saved screen");
assert_eq!(screen.find("hi"), Some((0, 0)), "{}", screen.text());
}
#[cfg(windows)]
let _ = echo; }
#[test]
#[cfg_attr(windows, ignore = "the program under inspection is a POSIX shell")]
fn inspect_ansi_redirect_is_a_saved_screen() -> termlens::Result<()> {
use std::process::Command;
let bin = env!("CARGO_BIN_EXE_termlens");
let out = Command::new(bin)
.args([
"inspect",
"--size",
"30x3",
"--ansi",
"sh",
"-c",
r#"printf '\033[1;31mred\033[0m'"#,
])
.output()?;
assert!(out.status.success(), "{out:?}");
let stdout = String::from_utf8(out.stdout).expect("utf-8");
assert!(
!stdout.contains('\u{1b}'),
"a redirect must not write C0: {stdout:?}"
);
let parsed = Screen::parse(&stdout).expect("stdout is a saved screen");
assert_eq!(parsed.size(), (30, 3));
assert_eq!(parsed.find("red"), Some((0, 0)));
let cell = parsed.cell(0, 0).expect("the painted cell");
assert_eq!(
cell.style().fg,
Color::Indexed(1),
"{}",
parsed.with_styles()
);
assert!(cell.style().bold, "{}", parsed.with_styles());
assert!(
stdout.contains("styles:"),
"colour survives as the styles block: {stdout:?}"
);
let path = std::env::temp_dir().join(format!(
"termlens-cli-inspect-ansi-{}.txt",
std::process::id()
));
std::fs::write(&path, &stdout)?;
let file = path.to_str().unwrap();
let render = Command::new(bin)
.args(["render", "--text", file])
.output()?;
assert_eq!(render.status.code(), Some(0), "{render:?}");
let diff = Command::new(bin).args(["diff", file, file]).output()?;
assert_eq!(diff.status.code(), Some(0), "{diff:?}");
let _ = std::fs::remove_file(&path);
Ok(())
}
#[test]
#[cfg_attr(windows, ignore = "the program under inspection is a POSIX shell")]
fn inspect_ansi_paints_on_a_terminal() -> termlens::Result<()> {
let path = std::env::var("PATH").unwrap_or_default();
let mut t = termlens::bin!(
"termlens",
env("PATH", &path),
args([
"inspect",
"--size",
"30x3",
"--ansi",
"sh",
"-c",
r#"printf '\033[1;31mred\033[0m'"#
])
)?;
assert_eq!(t.wait_exit()?.code(), Some(0), "{}", t.screen());
let s = t.screen();
assert!(s.contains("red"), "{s}");
assert!(
!s.contains("styles:"),
"a terminal is painted, not described: {s}"
);
assert!(
s.row_text(0).starts_with("size: 30x3"),
"the header must lead the painted screen: {}",
s.with_styles()
);
let (row, col) = s.find("red").expect("the painted word");
let cell = s.cell(row, col).expect("the painted cell");
assert_eq!(cell.style().fg, Color::Indexed(1), "{}", s.with_styles());
assert!(cell.style().bold, "{}", s.with_styles());
Ok(())
}
#[test]
#[cfg_attr(windows, ignore = "the program under inspection is a POSIX shell")]
fn inspect_on_a_terminal_stays_plain() -> termlens::Result<()> {
let path = std::env::var("PATH").unwrap_or_default();
let mut t = termlens::bin!(
"termlens",
env("PATH", &path),
args([
"inspect",
"--size",
"30x3",
"sh",
"-c",
r#"printf '\033[1;31mred\033[0m'"#
])
)?;
assert_eq!(t.wait_exit()?.code(), Some(0), "{}", t.screen());
let s = t.screen();
assert!(s.contains("red"), "{s}");
assert!(
!s.contains("styles:"),
"a terminal gets what it always got, not a saved screen: {s}"
);
Ok(())
}
#[test]
#[cfg_attr(windows, ignore = "the program under inspection is a POSIX shell")]
fn inspect_redirect_keeps_styles_so_diff_sees_a_colour_change() -> termlens::Result<()> {
use std::process::Command;
let bin = env!("CARGO_BIN_EXE_termlens");
let inspect = |sgr: &str| {
Command::new(bin)
.args([
"inspect",
"--size",
"20x2",
"sh",
"-c",
&format!(r#"printf '\033[{sgr}mred\033[0m'"#),
])
.output()
.expect("inspect ran")
};
let red = inspect("1;31");
let green = inspect("1;32");
assert!(red.status.success(), "{red:?}");
assert!(green.status.success(), "{green:?}");
let red_out = String::from_utf8(red.stdout).expect("utf-8");
let green_out = String::from_utf8(green.stdout).expect("utf-8");
assert!(
red_out.contains("styles:") && green_out.contains("styles:"),
"a redirect keeps the styles block:\n{red_out}\n{green_out}"
);
let red_screen = Screen::parse(&red_out).expect("red is a saved screen");
let green_screen = Screen::parse(&green_out).expect("green is a saved screen");
let red_cell = red_screen.cell(0, 0).expect("the painted cell");
let green_cell = green_screen.cell(0, 0).expect("the painted cell");
assert_eq!(
red_cell.style().fg,
Color::Indexed(1),
"{}",
red_screen.with_styles()
);
assert_eq!(
green_cell.style().fg,
Color::Indexed(2),
"{}",
green_screen.with_styles()
);
assert!(red_cell.style().bold && green_cell.style().bold);
let dir = std::env::temp_dir().join(format!(
"termlens-cli-inspect-styles-{}",
std::process::id()
));
std::fs::create_dir_all(&dir)?;
let red_path = dir.join("red.snap");
let green_path = dir.join("green.snap");
std::fs::write(&red_path, &red_out)?;
std::fs::write(&green_path, &green_out)?;
let red_file = red_path.to_str().unwrap();
let green_file = green_path.to_str().unwrap();
let diff = Command::new(bin)
.args(["diff", "--color", "never", red_file, green_file])
.output()?;
assert_eq!(diff.status.code(), Some(1), "{diff:?}");
let diff_out = String::from_utf8_lossy(&diff.stdout);
assert!(
diff_out.contains("styles:") && diff_out.contains("fg=1") && diff_out.contains("fg=2"),
"diff names the colour change: {diff_out}"
);
let text = Command::new(bin)
.args(["render", "--text", red_file])
.output()?;
assert_eq!(text.status.code(), Some(0), "{text:?}");
assert!(
String::from_utf8_lossy(&text.stdout).contains("styles:"),
"{text:?}"
);
let json = Command::new(bin)
.args(["render", "--json", red_file])
.output()?;
assert_eq!(json.status.code(), Some(0), "{json:?}");
let document = String::from_utf8(json.stdout).expect("utf-8 JSON");
let from_json: Screen = serde_json::from_str(&document).expect("a termlens Screen");
assert_eq!(
from_json.cell(0, 0).expect("the painted cell").style().fg,
Color::Indexed(1),
"{}",
from_json.with_styles()
);
let old = dir.join("old.snap");
std::fs::write(&old, format!("{red_out}--- exited: exit code 0 ---\n"))?;
let render = Command::new(bin)
.args(["render", "--text", old.to_str().unwrap()])
.output()?;
assert_eq!(render.status.code(), Some(0), "{render:?}");
let against_old = Command::new(bin)
.args(["diff", red_file, old.to_str().unwrap()])
.output()?;
assert_eq!(
against_old.status.code(),
Some(0),
"the trailer is not a row: {against_old:?}"
);
let _ = std::fs::remove_dir_all(&dir);
Ok(())
}
#[test]
fn every_corpus_file_renders() -> termlens::Result<()> {
use std::process::Command;
let bin = env!("CARGO_BIN_EXE_termlens");
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../termlens/tests/compat");
let mut files: Vec<std::path::PathBuf> = std::fs::read_dir(&root)?
.map(|entry| entry.map(|e| e.path()))
.collect::<Result<Vec<_>, _>>()?
.into_iter()
.filter(|p| p.is_dir())
.flat_map(|dir| std::fs::read_dir(dir).expect("a version directory"))
.map(|entry| entry.expect("a corpus file").path())
.filter(|p| p.extension().is_some_and(|e| e == "txt" || e == "json"))
.collect();
files.sort();
assert!(
files.len() >= 12,
"the 0.10.1 corpus alone is twelve files, found {}",
files.len()
);
for file in files {
let out = Command::new(bin)
.args(["render", "--text", file.to_str().unwrap()])
.output()?;
assert_eq!(
out.status.code(),
Some(0),
"{}: {}",
file.display(),
String::from_utf8_lossy(&out.stderr)
);
let text = String::from_utf8_lossy(&out.stdout);
assert!(text.starts_with("size: "), "{}: {text}", file.display());
}
Ok(())
}
fn with_stdin(args: &[&str], input: &str) -> std::process::Output {
use std::io::Write;
use std::process::{Command, Stdio};
let mut child = Command::new(env!("CARGO_BIN_EXE_termlens"))
.args(args)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.expect("spawn termlens");
let mut pipe = child.stdin.take().expect("a stdin pipe");
match pipe.write_all(input.as_bytes()) {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::BrokenPipe => {}
Err(e) => panic!("write to the child's stdin: {e}"),
}
drop(pipe);
child.wait_with_output().expect("the child's output")
}
#[test]
fn render_and_diff_read_a_screen_from_stdin() -> termlens::Result<()> {
let before = std::fs::read_to_string(data("before.snap"))?;
let after = std::fs::read_to_string(data("after.snap.new"))?;
let piped = with_stdin(&["render", "--text", "-"], &before);
assert_eq!(piped.status.code(), Some(0), "{piped:?}");
let from_file = std::process::Command::new(env!("CARGO_BIN_EXE_termlens"))
.args(["render", "--text", &data("before.snap")])
.output()?;
assert_eq!(
piped.stdout, from_file.stdout,
"the pipe and the path are the same screen"
);
let right = with_stdin(
&["diff", "--color", "never", &data("before.snap"), "-"],
&after,
);
assert_eq!(right.status.code(), Some(1), "{right:?}");
let left = with_stdin(
&["diff", "--color", "never", "-", &data("after.snap.new")],
&before,
);
assert_eq!(left.status.code(), Some(1), "{left:?}");
assert_eq!(right.stdout, left.stdout, "same two screens, same diff");
assert!(
String::from_utf8_lossy(&right.stdout).contains("Counter: 1"),
"{}",
String::from_utf8_lossy(&right.stdout)
);
let junk = with_stdin(&["render", "--text", "-"], "not a saved screen\n");
assert_eq!(junk.status.code(), Some(2), "{junk:?}");
let stderr = String::from_utf8_lossy(&junk.stderr);
assert!(stderr.contains("<stdin>"), "{stderr}");
Ok(())
}
#[test]
fn diff_refuses_two_stdin_operands() -> termlens::Result<()> {
let out = with_stdin(&["diff", "-", "-"], "size: 1x1 cursor: 0,0\n\n");
assert_eq!(out.status.code(), Some(2), "{out:?}");
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
stderr.contains("only one of the two screens can be `-`"),
"one line, naming the reason: {stderr}"
);
assert_eq!(stderr.lines().count(), 1, "{stderr}");
Ok(())
}
#[test]
fn render_empty_out_value_names_the_flag() -> termlens::Result<()> {
use std::process::Command;
let bin = env!("CARGO_BIN_EXE_termlens");
let out = Command::new(bin)
.args(["render", "--text", "--out=", &data("before.snap")])
.output()?;
assert_eq!(out.status.code(), Some(2), "{out:?}");
let stderr = String::from_utf8_lossy(&out.stderr);
assert_eq!(stderr, "termlens: --out needs a PATH argument\n");
Ok(())
}
#[test]
fn render_out_writes_the_file_and_creates_none_when_the_render_fails() -> termlens::Result<()> {
use std::process::Command;
let bin = env!("CARGO_BIN_EXE_termlens");
let dir = std::env::temp_dir().join(format!("termlens-render-out-{}", std::process::id()));
std::fs::create_dir_all(&dir)?;
let written = dir.join("screen.svg");
let out = Command::new(bin)
.args([
"render",
"--svg",
"--out",
written.to_str().expect("utf-8 path"),
&data("before.snap"),
])
.output()?;
assert_eq!(out.status.code(), Some(0), "{out:?}");
assert!(out.stdout.is_empty(), "--out means not stdout: {out:?}");
let to_stdout = Command::new(bin)
.args(["render", "--svg", &data("before.snap")])
.output()?;
assert_eq!(
std::fs::read(&written)?,
to_stdout.stdout,
"the same bytes stdout would have carried"
);
let junk = dir.join("junk.txt");
std::fs::write(&junk, "not a saved screen\n")?;
let missing = dir.join("never-written.svg");
let out = Command::new(bin)
.args([
"render",
"--svg",
"--out",
missing.to_str().expect("utf-8 path"),
junk.to_str().expect("utf-8 path"),
])
.output()?;
assert_eq!(out.status.code(), Some(2), "{out:?}");
assert!(
!missing.exists(),
"a failing render left a file behind: {}",
missing.display()
);
let _ = std::fs::remove_dir_all(&dir);
Ok(())
}
#[test]
fn render_out_dash_writes_to_stdout_and_creates_no_file() -> termlens::Result<()> {
use std::process::Command;
let bin = env!("CARGO_BIN_EXE_termlens");
let dir = std::env::temp_dir().join(format!("termlens-render-out-dash-{}", std::process::id()));
std::fs::create_dir_all(&dir)?;
let snap = data("before.snap");
let dash = dir.join("-");
let to_stdout = Command::new(bin)
.args(["render", "--text", &snap])
.output()?;
assert_eq!(to_stdout.status.code(), Some(0), "{to_stdout:?}");
let spaced = Command::new(bin)
.current_dir(&dir)
.args(["render", "--text", "--out", "-", &snap])
.output()?;
assert_eq!(spaced.status.code(), Some(0), "{spaced:?}");
assert_eq!(
spaced.stdout, to_stdout.stdout,
"the same bytes stdout would have carried"
);
assert!(
!dash.exists(),
"--out - created a file named -: {}",
dash.display()
);
let equals = Command::new(bin)
.current_dir(&dir)
.args(["render", "--text", "--out=-", &snap])
.output()?;
assert_eq!(equals.status.code(), Some(0), "{equals:?}");
assert_eq!(
equals.stdout, to_stdout.stdout,
"--out=- is the same stream"
);
assert!(
!dash.exists(),
"--out=- created a file named -: {}",
dash.display()
);
let out = Command::new(bin)
.current_dir(&dir)
.args(["render", "--text", "--out", "./-", &snap])
.output()?;
assert_eq!(out.status.code(), Some(0), "{out:?}");
assert!(out.stdout.is_empty(), "--out ./- means not stdout: {out:?}");
assert_eq!(
std::fs::read(&dash)?,
to_stdout.stdout,
"./- is a file named -"
);
let _ = std::fs::remove_dir_all(&dir);
Ok(())
}
#[test]
fn render_refuses_a_second_operand() -> termlens::Result<()> {
use std::process::Command;
let bin = env!("CARGO_BIN_EXE_termlens");
let dir = std::env::temp_dir().join(format!("termlens-render-operands-{}", std::process::id()));
std::fs::create_dir_all(&dir)?;
let a = dir.join("a.snap");
let b = dir.join("b.snap");
std::fs::write(&a, "size: 10x1 cursor: 0,0\nhi\n")?;
std::fs::write(&b, "size: 10x1 cursor: 0,0\nbye\n")?;
let out = Command::new(bin)
.args([
"render",
"--text",
a.to_str().expect("utf-8 path"),
b.to_str().expect("utf-8 path"),
])
.output()?;
assert_eq!(out.status.code(), Some(2), "{out:?}");
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(stderr.contains("usage: termlens render"), "{stderr}");
assert!(
!String::from_utf8_lossy(&out.stdout).contains("bye"),
"the last operand must not win: {out:?}"
);
let shot = dir.join("shot.svg");
let out = Command::new(bin)
.args([
"render",
"--svg",
"--out",
shot.to_str().expect("utf-8 path"),
a.to_str().expect("utf-8 path"),
b.to_str().expect("utf-8 path"),
])
.output()?;
assert_eq!(out.status.code(), Some(2), "{out:?}");
assert!(
!shot.exists(),
"a refused render left a file behind: {}",
shot.display()
);
let out = with_stdin(
&["render", "--text", "-", a.to_str().expect("utf-8 path")],
"not a saved screen\n",
);
assert_eq!(out.status.code(), Some(2), "{out:?}");
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(stderr.contains("usage: termlens render"), "{stderr}");
assert!(!stderr.contains("<stdin>"), "stdin was read: {stderr}");
let out = Command::new(bin)
.args(["render", "--text", a.to_str().expect("utf-8 path")])
.output()?;
assert_eq!(out.status.code(), Some(0), "{out:?}");
assert!(
String::from_utf8_lossy(&out.stdout).contains("hi"),
"{out:?}"
);
let _ = std::fs::remove_dir_all(&dir);
Ok(())
}
#[test]
fn render_refuses_a_second_format_or_a_second_out() -> termlens::Result<()> {
use std::process::Command;
let bin = env!("CARGO_BIN_EXE_termlens");
let dir = std::env::temp_dir().join(format!("termlens-render-twice-{}", std::process::id()));
std::fs::create_dir_all(&dir)?;
let a = dir.join("a.snap");
std::fs::write(&a, "size: 10x1 cursor: 0,0\nhi\n")?;
let a = a.to_str().expect("utf-8 path").to_string();
for (first, second, named) in [
("--svg", "--html", "--svg and --html are two formats"),
("--text", "--json", "--text and --json are two formats"),
("--svg", "--svg", "--svg is given twice"),
] {
let out = Command::new(bin)
.args(["render", first, second, &a])
.output()?;
assert_eq!(out.status.code(), Some(2), "{first} {second}: {out:?}");
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
stderr.contains(named),
"{first} {second} must name the conflict: {stderr}"
);
assert!(stderr.contains("usage: termlens render"), "{stderr}");
assert!(out.stdout.is_empty(), "nothing is rendered: {out:?}");
}
let first = dir.join("first.svg");
let second = dir.join("second.svg");
let (f, s) = (first.to_str().unwrap(), second.to_str().unwrap());
let eq = |p: &str| format!("--out={p}");
for args in [
vec!["render", "--svg", "--out", f, "--out", s, &a],
vec!["render", "--svg", &eq(f), "--out", s, &a],
vec!["render", "--svg", "--out", f, &eq(s), &a],
vec!["render", "--svg", &eq(f), &eq(s), &a],
] {
let out = Command::new(bin).args(&args).output()?;
assert_eq!(out.status.code(), Some(2), "{args:?}: {out:?}");
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
stderr.contains("--out is given twice"),
"{args:?}: {stderr}"
);
assert!(
!first.exists() && !second.exists(),
"a refused render wrote a file: {args:?}"
);
}
for args in [
vec!["render", "--svg", "--out", f, &a],
vec!["render", "--svg", &eq(f), &a],
] {
let _ = std::fs::remove_file(&first);
let out = Command::new(bin).args(&args).output()?;
assert_eq!(out.status.code(), Some(0), "{args:?}: {out:?}");
let svg = std::fs::read_to_string(&first)?;
assert!(svg.contains("<svg"), "{args:?} wrote: {svg}");
}
let _ = std::fs::remove_dir_all(&dir);
Ok(())
}
#[test]
#[cfg_attr(windows, ignore = "the program under inspection is a POSIX shell")]
fn inspect_runs_the_program_where_cwd_says() -> termlens::Result<()> {
let path = std::env::var("PATH").unwrap_or_default();
let dir = std::env::temp_dir().join(format!("termlens-cwd-{}", std::process::id()));
std::fs::create_dir_all(&dir)?;
let real = std::fs::canonicalize(&dir)?;
let mut t = termlens::bin!(
"termlens",
env("PATH", &path),
args([
"inspect",
"--size",
"200x3",
"--cwd",
dir.to_str().expect("utf-8 path"),
"sh",
"-c",
"pwd"
])
)?;
assert_eq!(t.wait_exit()?.code(), Some(0), "{}", t.screen());
let s = t.screen();
assert!(
s.contains(real.to_str().expect("utf-8 path")),
"the program ran in {}: {s}",
real.display()
);
let _ = std::fs::remove_dir_all(&dir);
Ok(())
}
#[test]
fn inspect_refuses_a_cwd_that_is_not_a_directory() -> termlens::Result<()> {
use std::process::Command;
let missing = std::env::temp_dir().join("termlens-no-such-directory-here");
let _ = std::fs::remove_dir_all(&missing);
let out = Command::new(env!("CARGO_BIN_EXE_termlens"))
.args([
"inspect",
"--cwd",
missing.to_str().expect("utf-8 path"),
"true",
])
.output()?;
assert_eq!(out.status.code(), Some(2), "{out:?}");
let stderr = String::from_utf8_lossy(&out.stderr);
assert_eq!(stderr.lines().count(), 1, "one line: {stderr}");
assert!(stderr.contains("--cwd"), "it names the flag: {stderr}");
assert!(
stderr.contains("not an existing directory"),
"and what was wrong with it: {stderr}"
);
Ok(())
}
#[test]
#[cfg_attr(windows, ignore = "the program under inspection is a POSIX shell")]
fn inspect_clears_the_caller_env_unless_inherit_env_is_passed() -> termlens::Result<()> {
let path = std::env::var("PATH").unwrap_or_default();
let mut t = termlens::bin!(
"termlens",
env("PATH", &path),
env("TERMLENS_INSPECT_CALLER", "zzz"),
args([
"inspect",
"--size",
"60x3",
"sh",
"-c",
"echo \"[$TERMLENS_INSPECT_CALLER]\""
])
)?;
assert_eq!(t.wait_exit()?.code(), Some(0), "{}", t.screen());
let s = t.screen();
assert!(s.contains("[]"), "absent without --inherit-env: {s}");
assert!(!s.contains("zzz"), "the caller's variable leaked in: {s}");
let mut t = termlens::bin!(
"termlens",
env("PATH", &path),
env("TERMLENS_INSPECT_CALLER", "zzz"),
args([
"inspect",
"--size",
"60x3",
"--inherit-env",
"sh",
"-c",
"echo \"[$TERMLENS_INSPECT_CALLER]\""
])
)?;
assert_eq!(t.wait_exit()?.code(), Some(0), "{}", t.screen());
assert!(t.screen().contains("[zzz]"), "{}", t.screen());
Ok(())
}
#[test]
#[cfg_attr(windows, ignore = "the program under inspection is a POSIX shell")]
fn inspect_env_sets_a_variable_and_splits_on_the_first_equals() -> termlens::Result<()> {
let path = std::env::var("PATH").unwrap_or_default();
let mut t = termlens::bin!(
"termlens",
env("PATH", &path),
args([
"inspect",
"--size",
"60x3",
"--env",
"TERMLENS_INSPECT_SET=zzz",
"sh",
"-c",
"echo \"[$TERMLENS_INSPECT_SET]\""
])
)?;
assert_eq!(t.wait_exit()?.code(), Some(0), "{}", t.screen());
assert!(t.screen().contains("[zzz]"), "{}", t.screen());
let mut t = termlens::bin!(
"termlens",
env("PATH", &path),
args([
"inspect",
"--size",
"60x3",
"--env",
"TERMLENS_INSPECT_SPLIT=b=c",
"sh",
"-c",
"echo \"[$TERMLENS_INSPECT_SPLIT]\""
])
)?;
assert_eq!(t.wait_exit()?.code(), Some(0), "{}", t.screen());
assert!(t.screen().contains("[b=c]"), "{}", t.screen());
let mut t = termlens::bin!(
"termlens",
env("PATH", &path),
args(["inspect", "--size", "60x3", "--env", "=a=b", "sh", "-c", "echo hi"])
)?;
assert_eq!(t.wait_exit()?.code(), Some(2), "{}", t.screen());
assert!(
t.screen()
.contains(r#"bad --env "=a=b", expected e.g. NO_COLOR=1"#),
"an empty key is refused with the flag's own diagnostic: {}",
t.screen()
);
Ok(())
}
#[test]
#[cfg_attr(windows, ignore = "the program under inspection is a POSIX shell")]
fn inspect_idle_window_decides_what_the_deadline_snapshot_holds() -> termlens::Result<()> {
let path = std::env::var("PATH").unwrap_or_default();
let child = "printf first; sleep 4; printf ' second'; sleep 30";
let run = |idle: &str| {
termlens::bin!(
"termlens",
env("PATH", &path),
timeout(std::time::Duration::from_secs(30)),
args([
"inspect",
"--size",
"60x3",
"--timeout",
"3",
"--idle",
idle,
"sh",
"-c",
child
])
)
};
let mut t = run("300")?;
assert_eq!(t.wait_exit()?.code(), Some(0), "{}", t.screen());
let s = t.screen();
assert!(s.contains("first"), "{s}");
assert!(
!s.contains("second"),
"the gap sits outside the window: {s}"
);
let started = std::time::Instant::now();
let mut t = run("5000")?;
assert_eq!(t.wait_exit()?.code(), Some(0), "{}", t.screen());
assert!(
!t.screen().contains("second"),
"the deadline ends the wait before the overdue window: {}",
t.screen()
);
assert!(
started.elapsed() < std::time::Duration::from_secs(6),
"returned after {:?}: the deadline did not bound the idle window",
started.elapsed()
);
Ok(())
}
#[test]
#[cfg_attr(windows, ignore = "the program under inspection is a POSIX shell")]
fn inspect_timeout_snapshots_a_program_that_outlives_it() -> termlens::Result<()> {
let path = std::env::var("PATH").unwrap_or_default();
let mut t = termlens::bin!(
"termlens",
env("PATH", &path),
timeout(std::time::Duration::from_secs(30)),
args([
"inspect",
"--size",
"60x3",
"--timeout",
"3",
"--idle",
"5000",
"sh",
"-c",
"printf first; sleep 4; printf ' second'; sleep 30"
])
)?;
assert_eq!(t.wait_exit()?.code(), Some(0), "{}", t.screen());
let s = t.screen();
assert!(s.contains("first"), "the pre-deadline output is kept: {s}");
assert!(
!s.contains("second"),
"output past the 3s deadline is not the snapshot: {s}"
);
assert!(
s.contains("--- still running at the deadline (killed on exit) ---"),
"{s}"
);
Ok(())
}
#[test]
#[cfg_attr(windows, ignore = "the program under inspection is a POSIX shell")]
fn inspect_resolves_on_the_idle_window_before_the_deadline() -> termlens::Result<()> {
let path = std::env::var("PATH").unwrap_or_default();
let started = std::time::Instant::now();
let mut t = termlens::bin!(
"termlens",
timeout(std::time::Duration::from_secs(60)),
env("PATH", &path),
args([
"inspect",
"--size",
"20x3",
"--idle",
"200",
"--timeout",
"30",
"sh",
"-c",
"printf READY; sleep 300"
])
)?;
assert_eq!(t.wait_exit()?.code(), Some(0), "{}", t.screen());
let elapsed = started.elapsed();
let s = t.screen();
assert!(
s.contains("READY"),
"the output before idleness is kept: {s}"
);
assert!(
s.contains("--- still running (killed on exit) ---"),
"the program never exited, so the trailer says so โ and the window \
ended the wait, so it does not claim the deadline did: {s}"
);
assert!(
elapsed < std::time::Duration::from_secs(10),
"took {elapsed:?}: the 200ms idle window did not end the wait before the 30s deadline"
);
Ok(())
}
#[test]
#[cfg_attr(windows, ignore = "the program under inspection is a POSIX shell")]
fn inspect_reports_an_exit_without_waiting_for_the_idle_window() -> termlens::Result<()> {
let path = std::env::var("PATH").unwrap_or_default();
let started = std::time::Instant::now();
let mut t = termlens::bin!(
"termlens",
timeout(std::time::Duration::from_secs(30)),
env("PATH", &path),
args([
"inspect",
"--size",
"20x3",
"--idle",
"30000",
"--timeout",
"30",
"sh",
"-c",
"printf 'done here'"
])
)?;
assert_eq!(t.wait_exit()?.code(), Some(0), "{}", t.screen());
let elapsed = started.elapsed();
let s = t.screen();
assert!(
s.contains("done here"),
"the final output is the screen: {s}"
);
assert!(s.contains("--- exited: exit code 0 ---"), "{s}");
assert!(
elapsed < std::time::Duration::from_secs(10),
"took {elapsed:?} for a program that exited at once"
);
Ok(())
}
#[test]
#[cfg_attr(windows, ignore = "the program under inspection is a POSIX shell")]
fn inspect_chatter_waits_for_the_deadline_and_says_still_running() -> termlens::Result<()> {
let path = std::env::var("PATH").unwrap_or_default();
let started = std::time::Instant::now();
let mut t = termlens::bin!(
"termlens",
timeout(std::time::Duration::from_secs(30)),
env("PATH", &path),
args([
"inspect",
"--size",
"20x3",
"--idle",
"500",
"--timeout",
"1",
"sh",
"-c",
"while :; do printf x; sleep 0.01; done"
])
)?;
assert_eq!(t.wait_exit()?.code(), Some(0), "{}", t.screen());
let elapsed = started.elapsed();
let s = t.screen();
assert!(
s.contains("--- still running at the deadline (killed on exit) ---"),
"{s}"
);
assert!(
elapsed >= std::time::Duration::from_millis(800),
"returned after {elapsed:?}: the 1s deadline was not waited"
);
Ok(())
}
#[test]
#[cfg_attr(windows, ignore = "the program under inspection is a POSIX shell")]
fn inspect_reports_still_running_when_the_child_closes_its_terminal() -> termlens::Result<()> {
use std::process::Command;
let (timeout, trailer) = if cfg!(target_os = "macos") {
(
"2",
"--- still running at the deadline (killed on exit) ---",
)
} else {
("30", "--- still running (killed on exit) ---")
};
let bin = env!("CARGO_BIN_EXE_termlens");
let started = std::time::Instant::now();
let out = Command::new(bin)
.args([
"inspect",
"--size",
"20x3",
"--timeout",
timeout,
"sh",
"-c",
"exec 0<&- 1>&- 2>&-; exec sleep 30",
])
.output()?;
assert!(out.status.success(), "{out:?}");
let stderr = String::from_utf8(out.stderr).expect("utf-8");
assert_eq!(stderr.trim_end(), trailer, "{stderr:?}");
if !cfg!(target_os = "macos") {
assert!(
started.elapsed() < std::time::Duration::from_secs(10),
"returned after {:?}: the EOF did not end the wait",
started.elapsed()
);
}
Ok(())
}