use std::io::Write;
use std::process::{Command, Output, Stdio};
fn strip_ansi(bytes: &[u8]) -> String {
let text = String::from_utf8_lossy(bytes);
let mut out = String::with_capacity(text.len());
let mut chars = text.chars().peekable();
while let Some(c) = chars.next() {
if c == '\x1b' {
if chars.peek() == Some(&'[') {
chars.next();
for c in chars.by_ref() {
if ('\x40'..='\x7e').contains(&c) {
break;
}
}
}
} else {
out.push(c);
}
}
out
}
fn run(args: &[&str], stdin: Option<&[u8]>) -> Output {
let mut child = Command::new(env!("CARGO_BIN_EXE_tale"))
.args(args)
.stdin(if stdin.is_some() { Stdio::piped() } else { Stdio::null() })
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.expect("failed to spawn tale");
if let Some(input) = stdin {
child
.stdin
.take()
.expect("stdin was piped")
.write_all(input)
.expect("failed to write stdin");
}
child.wait_with_output().expect("failed to collect output")
}
fn stdout(out: &Output) -> String {
strip_ansi(&out.stdout)
}
fn stderr(out: &Output) -> String {
strip_ansi(&out.stderr)
}
fn fixture(name: &str) -> String {
format!("{}/fixtures/{name}", env!("CARGO_MANIFEST_DIR"))
}
#[track_caller]
fn assert_success(out: &Output) {
assert!(
out.status.success(),
"tale exited with {:?}\nstderr:\n{}",
out.status.code(),
stderr(out)
);
}
#[track_caller]
fn assert_stdout_free_of_diagnostics(out: &Output) {
assert!(
!stdout(out).contains("JSON Parsing Profile Report"),
"profile report leaked into stdout:\n{}",
stdout(out)
);
}
#[test]
fn piped_output_has_no_ansi_colors() {
let out = run(&[&fixture("mixed_json_types.log")], None);
assert_success(&out);
assert!(
!out.stdout.contains(&0x1b),
"stdout contains ANSI escapes while piped:\n{}",
stdout(&out)
);
assert!(stdout(&out).contains("Service starting up"), ":\n{}", stdout(&out));
}
#[test]
fn reads_entire_file() {
let out = run(&[&fixture("just_loglines.log")], None);
assert_success(&out);
assert_stdout_free_of_diagnostics(&out);
let text = stdout(&out);
for message in [
"Application startup initiated",
"Loading Spring context",
"Failed to initialize database connection",
] {
assert!(text.contains(message), "output missing {message:?}:\n{text}");
}
}
#[test]
fn stdin_formats_json_and_passes_text_through() {
let input = std::fs::read(fixture("mixed_text_json.log")).expect("fixture readable");
let out = run(&[], Some(&input));
assert_success(&out);
assert_stdout_free_of_diagnostics(&out);
let text = stdout(&out);
assert!(text.contains("Application server started on port 8080"), ":\n{text}");
assert!(text.contains("Starting application server..."), ":\n{text}");
assert!(!text.contains("==>"), "stdin output has a file header:\n{text}");
}
#[test]
fn positive_offset_skips_lines() {
let path = fixture("mixed_json_types.log");
let out = run(&["-n", "2", &path], None);
assert_success(&out);
let text = stdout(&out);
assert!(text.contains("User authentication successful"), ":\n{text}");
assert!(!text.contains("Service starting up"), ":\n{text}");
}
#[test]
fn negative_offset_shows_last_lines() {
let path = fixture("mixed_json_types.log");
let out = run(&["-n", "-2", &path], None);
assert_success(&out);
let text = stdout(&out);
assert!(text.contains("Cache warming completed"), ":\n{text}");
assert!(!text.contains("Service starting up"), ":\n{text}");
}
#[test]
fn byte_offset_skips_garbage_prefix() {
let path = fixture("garbage_prefix.log");
let out = run(&["-c", "59", &path], None);
assert_success(&out);
let text = stdout(&out);
assert!(text.contains("First valid log line"), ":\n{text}");
assert!(text.contains("Fourth valid log line"), ":\n{text}");
assert!(!text.contains("GARBAGE_BYTES"), ":\n{text}");
}
#[test]
fn blocks_flag_is_accepted_and_ignored() {
let path = fixture("mixed_json_types.log");
let plain = run(&[&path], None);
let blocked = run(&["-b", "3", &path], None);
assert_success(&plain);
assert_success(&blocked);
assert_eq!(stdout(&plain), stdout(&blocked));
}
#[test]
fn multi_file_static_prints_headers() {
let out = run(
&[&fixture("mixed_text_json.log"), &fixture("windows_line_endings.log")],
None,
);
assert_success(&out);
assert_stdout_free_of_diagnostics(&out);
let text = stdout(&out);
assert!(text.contains("==> mixed_text_json.log <=="), ":\n{text}");
assert!(text.contains("==> windows_line_endings.log <=="), ":\n{text}");
assert!(text.contains("Application server started on port 8080"), ":\n{text}");
assert!(text.contains("Windows service started"), ":\n{text}");
}
#[test]
fn missing_file_fails_with_error_on_stderr() {
let out = run(&["/nonexistent/path/really-not-here.log"], None);
assert_eq!(out.status.code(), Some(1), "missing file should exit 1");
assert!(stdout(&out).is_empty(), "stdout should be empty:\n{}", stdout(&out));
let err = stderr(&out);
assert!(err.contains("File not found"), "stderr:\n{err}");
}
#[test]
fn windows_line_endings_are_handled() {
let out = run(&[&fixture("windows_line_endings.log")], None);
assert_success(&out);
let text = stdout(&out);
assert!(text.contains("Windows service started"), ":\n{text}");
assert!(text.contains("Processing batch job"), ":\n{text}");
assert!(!text.contains('\r'), "CR made it into output:\n{text:?}");
}
#[test]
fn bare_logfmt_lines_are_parsed() {
let line = b"at=info method=GET path=/ status=200 duration=12ms\n";
let out = run(&[], Some(line));
assert_success(&out);
let text = stdout(&out);
assert!(text.contains("status=200"), ":\n{text}");
assert!(
!text.contains("at=info method=GET path=/ status=200"),
"logfmt line passed through raw:\n{text}"
);
}
#[test]
fn quoted_logfmt_json_strings_still_parse() {
let line = b"\"at=info method=GET path=/ status=200\"\n";
let out = run(&[], Some(line));
assert_success(&out);
let text = stdout(&out);
assert!(text.contains("status=200"), ":\n{text}");
}
#[test]
fn plain_text_without_key_value_pairs_passes_through() {
let line = b"this is just a sentence with no equals signs\n";
let out = run(&[], Some(line));
assert_success(&out);
let text = stdout(&out);
assert!(
text.contains("this is just a sentence with no equals signs"),
":\n{text}"
);
}
#[test]
fn stdin_negative_offset_shows_last_lines() {
let mut input = Vec::new();
for i in 0..50_usize {
input.extend_from_slice(format!(r#"{{"level":"INFO","message":"msg-{i:02}"}}"#).as_bytes());
input.push(b'\n');
}
let out = run(&["-n", "-5"], Some(&input));
assert_success(&out);
let text = stdout(&out);
assert!(text.contains("msg-49"), ":\n{text}");
assert!(text.contains("msg-45"), ":\n{text}");
assert!(!text.contains("msg-44"), ":\n{text}");
assert!(!text.contains("msg-00"), ":\n{text}");
}
#[test]
fn closed_pipe_exits_quietly() {
let mut child = Command::new(env!("CARGO_BIN_EXE_tale"))
.arg(fixture("benchmarks/test_mixed_50000_lines.log"))
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.expect("failed to spawn tale");
let mut stdout = child.stdout.take().expect("stdout was piped");
let mut buffer = [0u8; 4096];
use std::io::Read;
let _ = stdout.read(&mut buffer);
drop(stdout);
let status = child.wait().expect("failed to wait for tale");
assert_eq!(status.code(), Some(141), "expected exit 141, got {status:?}");
if let Some(mut stderr) = child.stderr.take() {
let mut collected = Vec::new();
let _ = stderr.read_to_end(&mut collected);
let err = String::from_utf8_lossy(&collected);
assert!(!err.contains("Broken pipe"), "broken pipe leaked to stderr:\n{err}");
}
}
#[test]
fn help_exits_successfully() {
let out = run(&["--help"], None);
assert_success(&out);
assert!(stdout(&out).contains("Usage:"), ":\n{}", stdout(&out));
}