use super::*;
#[test]
fn offload_drop_runs_the_destructor_off_the_calling_thread() {
use std::sync::mpsc;
use std::time::Duration;
struct DropSignal(mpsc::Sender<std::thread::ThreadId>);
impl Drop for DropSignal {
fn drop(&mut self) {
let _ = self.0.send(std::thread::current().id());
}
}
let (tx, rx) = mpsc::channel();
let caller = std::thread::current().id();
super::fs_watch::offload_drop(DropSignal(tx));
let dropped_on = rx
.recv_timeout(Duration::from_secs(5))
.expect("destructor must run within the timeout");
assert_ne!(
dropped_on, caller,
"watcher destructor must run off the calling (UI) thread, not block it"
);
}
#[test]
fn rect_contains_basic() {
let r = Rect {
x: 5,
y: 5,
width: 10,
height: 10,
};
assert!(rect_contains(r, 5, 5));
assert!(rect_contains(r, 14, 14));
assert!(!rect_contains(r, 4, 5));
assert!(!rect_contains(r, 15, 5));
assert!(!rect_contains(r, 5, 15));
}
#[test]
fn rect_contains_zero_sized_is_empty() {
let r = Rect {
x: 0,
y: 0,
width: 0,
height: 0,
};
assert!(!rect_contains(r, 0, 0));
}
#[test]
fn lerp_rgb_hits_endpoints_exactly() {
let a = (10u8, 20, 30);
let b = (100u8, 200, 250);
assert_eq!(lerp_rgb(a, b, 0.0), a);
assert_eq!(lerp_rgb(a, b, 1.0), b);
let mid = lerp_rgb(a, b, 0.5);
assert!(mid.0 > a.0 && mid.0 < b.0);
}
#[test]
fn ctrl_d_is_not_delete_node() {
assert!(!is_delete_node_key(key(
KeyCode::Char('d'),
KeyModifiers::CONTROL
)));
}
#[test]
fn set_title_seq_wraps_with_osc0_and_bel() {
let bytes = set_title_seq("croft");
assert_eq!(bytes, b"\x1b]0;croft\x07");
}
#[test]
fn set_title_seq_handles_empty_title() {
let bytes = set_title_seq("");
assert_eq!(bytes, b"\x1b]0;\x07");
}
#[test]
fn set_title_seq_passes_through_unicode() {
let bytes = set_title_seq("croft README.md");
assert_eq!(bytes, "\x1b]0;croft README.md\x07".as_bytes());
}
#[test]
fn set_title_seq_strips_control_bytes_that_would_break_the_escape() {
let bytes = set_title_seq("evil\x07file");
assert_eq!(bytes, b"\x1b]0;evilfile\x07");
let bytes = set_title_seq("evil\x1bfile");
assert_eq!(bytes, b"\x1b]0;evilfile\x07");
let bytes = set_title_seq("evil\nfile");
assert_eq!(bytes, b"\x1b]0;evilfile\x07");
}
#[test]
fn app_name_constant_is_croft() {
assert_eq!(APP_NAME, "croft");
}
#[test]
fn reset_session_bg_seq_restores_profile_default() {
assert_eq!(reset_session_bg_seq(), "\x1b]1337;SetColors=bg=default\x07");
}
#[test]
fn workspace_cap_carries_the_brand_mark_and_the_folder_name() {
let theme = crate::theme::Theme::default();
let spans = workspace_cap_spans(theme, "proj");
let text: String = spans.iter().map(|s| s.content.as_ref()).collect();
assert_eq!(text, " <> proj \u{e0b4}");
let bracket = spans.iter().find(|s| s.content == "<>").unwrap();
assert_eq!(bracket.style.fg, Some(BRAND_ORANGE));
assert_eq!(bracket.style.bg, Some(theme.selection()));
let cap = spans.iter().find(|s| s.content == PILL_CAP_R).unwrap();
assert_eq!(cap.style.fg, Some(theme.selection()));
}
#[test]
fn workspace_cap_elides_a_long_folder_name() {
let long = "a-workspace-folder-name-far-too-long-for-the-bar";
let text: String = workspace_cap_spans(crate::theme::Theme::default(), long)
.iter()
.map(|s| s.content.as_ref())
.collect();
let name = text
.trim()
.trim_start_matches("<> ")
.trim_end_matches('\u{e0b4}');
assert_eq!(name.trim().chars().count(), WORKSPACE_CAP_MAX, "{text}");
assert!(name.trim().ends_with('\u{2026}'), "{text}");
}
#[test]
fn workspace_cap_elides_a_wide_name_by_the_cells_it_paints() {
let wide = "\u{9879}".repeat(30);
let spans = workspace_cap_spans(crate::theme::Theme::default(), &wide);
let name = spans
.iter()
.find(|s| s.content.contains('\u{9879}'))
.map(|s| s.content.trim().to_string())
.unwrap();
assert!(name.ends_with('\u{2026}'), "{name}");
assert!(status_cells(&name) as usize <= WORKSPACE_CAP_MAX, "{name}");
}
#[test]
fn high_contrast_themes_keep_the_status_bar_text_at_full_strength() {
let hc: Vec<_> = crate::theme::Theme::all()
.iter()
.filter(|t| t.high_contrast())
.collect();
assert!(!hc.is_empty(), "the bundled themes include high contrast");
for theme in hc {
let tones = StatusTones::new(*theme, status_bar_bg(*theme));
assert_eq!(tones.dim, tones.muted, "{}", theme.label());
}
}
#[test]
fn workspace_relative_shortens_paths_inside_the_workspace() {
let root = std::path::Path::new("/home/me/proj");
assert_eq!(
workspace_relative("Saved /home/me/proj/src/main.rs", root),
"Saved src/main.rs"
);
assert_eq!(
workspace_relative("Moved '/home/me/proj/a.rs' to /home/me/proj/b/a.rs", root),
"Moved 'a.rs' to b/a.rs"
);
for kept in [
"Opened /home/me/proj",
"Saved /home/me/proj2/x.rs",
"Saved /mnt/home/me/proj/x.rs",
] {
assert_eq!(workspace_relative(kept, root), kept);
}
let (borrowed, made) = crate::alloc_count::allocations_in(|| workspace_relative("Ready", root));
assert_eq!(borrowed, "Ready");
assert_eq!(
made, 0,
"workspace_relative should not allocate when root is absent, made {made}"
);
}
#[test]
fn no_stale_tcode_pill_literal_in_source() {
let src = app_source();
assert!(
!src.contains("\" tcode \""),
"stale ` tcode ` pill literal still present in the app's source"
);
}
#[test]
fn build_title_uses_basename_and_app_name() {
let p = std::path::Path::new("/Users/somebody/projects/croft");
assert_eq!(build_title(p), "croft croft");
let p = std::path::Path::new("/");
assert_eq!(build_title(p), "croft /");
}
#[test]
fn the_gh_client_gives_up_on_a_command_that_hangs() {
let started = std::time::Instant::now();
let dir = std::env::temp_dir();
let quick = crate::gh::Client::new("sh", &dir, std::time::Duration::from_millis(500));
assert!(matches!(
quick.run(&["-c", "sleep 30"]),
Err(crate::gh::Error::NoAnswer(_))
));
assert!(matches!(
quick.run(&["-c", "exec 1>&-; sleep 30"]),
Err(crate::gh::Error::NoAnswer(_))
));
assert!(started.elapsed() < std::time::Duration::from_secs(10));
let out = crate::gh::Client::new("sh", &dir, std::time::Duration::from_secs(10))
.run(&["-c", "printf 42"])
.unwrap();
assert_eq!(out, b"42");
}
fn busy_script(path: &std::path::Path, hold: std::time::Duration) -> std::thread::JoinHandle<()> {
use std::io::Write as _;
use std::os::unix::fs::OpenOptionsExt;
let mut writer = std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.mode(0o755)
.open(path)
.unwrap();
writer.write_all(b"#!/bin/sh\nsleep 30\n").unwrap();
writer.flush().unwrap();
std::thread::spawn(move || {
std::thread::sleep(hold);
drop(writer);
})
}
#[test]
fn the_gh_client_counts_a_busy_program_against_its_limit() {
use std::time::{Duration, Instant};
let tmp = tempfile::tempdir().unwrap();
let always_busy = tmp.path().join("always-busy");
let release = busy_script(&always_busy, Duration::from_secs(2));
let started = Instant::now();
let none: [&str; 0] = [];
assert!(
crate::gh::Client::new(&always_busy, tmp.path(), Duration::from_millis(50))
.run(&none)
.is_err()
);
let waited = started.elapsed();
assert!(
waited < Duration::from_millis(400),
"a 50 ms budget waited {waited:?} on a busy program"
);
release.join().unwrap();
let late = tmp.path().join("late");
let release = busy_script(&late, Duration::from_millis(400));
let started = Instant::now();
assert!(
crate::gh::Client::new(&late, tmp.path(), Duration::from_millis(450))
.run(&none)
.is_err()
);
let waited = started.elapsed();
assert!(
waited < Duration::from_millis(700),
"a 450 ms budget waited {waited:?} on a program busy for 400 ms"
);
release.join().unwrap();
}
#[test]
fn cmd_active_treats_super_as_command_everywhere() {
assert!(cmd_active(KeyModifiers::SUPER, false));
assert!(cmd_active(KeyModifiers::SUPER, true));
}
#[test]
fn a_relative_block_directory_is_made_absolute() {
let dir = super::absolute_block_dir(PathBuf::from(".cache/croft/blocks"));
assert!(dir.is_absolute(), "{dir:?}");
assert_eq!(
dir,
std::env::current_dir().unwrap().join(".cache/croft/blocks")
);
assert!(super::block_script_dir().is_absolute());
}
#[test]
fn an_unopenable_host_lock_is_reported_as_such_and_re_announced_when_the_reason_changes() {
use std::time::{Duration, Instant};
let tmp = tempfile::tempdir().unwrap();
let socket = tmp.path().join("collab.sock");
{
let s = socket.clone();
std::thread::spawn(move || {
let _ = crate::collab::relay_serve(&s);
});
}
let deadline = Instant::now() + Duration::from_secs(5);
while !crate::session::is_alive(&socket) {
assert!(Instant::now() < deadline, "relay never came up");
std::thread::sleep(Duration::from_millis(10));
}
let lock_dir = tmp.path().join("no-such-dir");
let lock_path = lock_dir.join("host.lock");
let mut b = App::new(tmp.path().to_path_buf()).unwrap();
b.pair.record_path = tmp.path().join("b.pair.json");
b.pair.socket = socket.clone();
b.pair.host_lock_path = lock_path.clone();
b.pair.spawn_override = Some(Box::new(local_test_spawn));
crate::session::write_pair_record(
&b.pair.record_path,
&crate::session::PairRecord {
model: None,
name: "nav".into(),
enabled: true,
task: None,
provider: None,
base_url: None,
},
)
.unwrap();
b.pair.last_check = None;
b.maybe_seat_navigator();
assert!(b.pair.host.is_none(), "cannot host without the lock");
assert!(
b.status.contains("cannot open host lock") && b.status.contains("no-such-dir"),
"an unopenable lock names the path and the error, got: {}",
b.status
);
assert!(
!b.status.to_lowercase().contains("another croft"),
"an open failure must never be blamed on another window: {}",
b.status
);
b.status = String::from("Saved src/foo.rs");
b.pair.last_check = None;
assert!(
!b.maybe_seat_navigator(),
"an unchanged refusal stays quiet"
);
assert_eq!(b.status, "Saved src/foo.rs");
std::fs::create_dir_all(&lock_dir).unwrap();
let holder = crate::session::try_acquire_pair_host_lock(&lock_path).expect("holder acquires");
b.pair.last_check = None;
assert!(
b.maybe_seat_navigator(),
"a changed reason dirties the frame"
);
assert!(
b.status.to_lowercase().contains("another croft"),
"now it IS another window, got: {}",
b.status
);
std::fs::remove_dir_all(&lock_dir).unwrap();
b.pair.last_check = None;
assert!(b.maybe_seat_navigator(), "Busy -> Io is a changed reason");
assert!(
b.status.contains("cannot open host lock"),
"the open failure is named again, got: {}",
b.status
);
std::fs::create_dir_all(&lock_dir).unwrap();
drop(holder);
b.pair.last_check = None;
b.maybe_seat_navigator();
assert!(
b.pair.host.is_some(),
"B hosts once the lock frees: {}",
b.status
);
assert!(b.pair.host_lock.is_some());
}
#[test]
fn a_zero_sized_frame_gets_no_fallback_popup() {
let r = fallback_popup_rect(Rect::new(0, 0, 0, 0), 100);
assert_eq!(r.area(), 0, "no cells exist to draw into: {r:?}");
let r = fallback_popup_rect(Rect::new(0, 0, 80, 0), 110);
assert_eq!(r.area(), 0, "a zero-height frame cannot host rows: {r:?}");
let r = fallback_popup_rect(Rect::new(2, 3, 30, 8), 110);
assert!(
r.x >= 2 && r.y >= 3 && r.right() <= 32 && r.bottom() <= 11,
"a real frame keeps the popup inside it: {r:?}"
);
}
#[cfg(unix)]
#[test]
fn a_check_that_warrants_no_hint_does_not_spend_it() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.queue_project_check_result_for_test(tmp.path(), "", "", true);
app.sync_explorer_panels();
assert!(
!app.project_check_hinted_for_test(),
"a check with no hint must not consume the one-shot"
);
app.send_project_hint_for_test();
app.queue_project_check_result_for_test(tmp.path(), "", "", true);
app.sync_explorer_panels();
assert!(
app.status.contains("too large"),
"the hint the earlier run would have eaten still arrives: {:?}",
app.status
);
assert!(
app.project_check_hinted_for_test(),
"and NOW the one-shot is spent"
);
}
#[cfg(unix)]
#[test]
fn the_size_hint_is_not_erased_by_a_result_in_the_same_tick() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.send_project_hint_for_test();
app.queue_project_check_result_for_test(tmp.path(), "", "", true);
app.sync_explorer_panels();
assert!(
app.status.contains("no problems"),
"the outcome the user asked for still leads: {:?}",
app.status
);
assert!(
app.status.contains("too large"),
"and the one-shot hint survives rather than being overwritten: {:?}",
app.status
);
}
#[test]
fn an_unknowable_cwd_still_allows_reuse_but_a_wrong_one_does_not() {
let root = Path::new("/w/a");
assert!(cwd_matches(Some(Path::new("/w/a")), root, true));
assert!(!cwd_matches(Some(Path::new("/w/a/sub")), root, true));
assert!(!cwd_matches(Some(Path::new("/w/b")), root, true));
assert!(!cwd_matches(None, root, true));
assert!(cwd_matches(None, root, false));
assert!(!cwd_matches(Some(Path::new("/w/a/sub")), root, false));
let tmp = tempfile::tempdir().unwrap();
let real_root = tmp.path().canonicalize().unwrap();
let app = App::new(tmp.path().to_path_buf()).unwrap();
assert!(!pane_is_idle_at(
&app.terminals[0],
"Task: nonexistent",
&real_root
));
}
#[test]
fn every_post_draw_overlay_writer_checks_the_screen_bound() {
let src = app_source();
let guards = src.matches("app.overlay_fits_on_screen(").count();
assert_eq!(
guards, 5,
"expected the five payload writers in the post-draw block to be \
guarded (editor split slots share one call site, plus terminal, \
markdown, minimap, welcome); the activity-bar writer calls \
`self.overlay_fits_on_screen` from inside its own method. A \
change here means a writer was added or removed - guard it."
);
assert!(
src.contains("self.overlay_fits_on_screen(*x, *y, 1, 1)"),
"the activity-bar writer keeps its own guard, which picks the icons \
that go in its batch"
);
}
#[test]
fn no_overlay_is_emittable_before_the_first_frame() {
let tmp = tempfile::tempdir().unwrap();
let app = App::new(tmp.path().to_path_buf()).unwrap();
assert!(
!app.overlay_fits_on_screen(0, 0, 1, 1),
"no frame drawn yet: a 1x1 payload at the origin still has no screen"
);
}
#[test]
fn an_in_memory_refusal_stops_blocking_once_its_window_has_passed() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.remote_offer_refused.clear();
let pane = app.terminals[0].uid();
app.remote_offer_refused.insert(
String::from("db-1"),
std::time::SystemTime::now()
- crate::remote::REFUSED_HOST_TTL
- std::time::Duration::from_secs(60),
);
app.consider_ssh_offer(pane, Some(String::from("db-1")));
assert!(
app.ssh_offer.is_some(),
"a refusal older than the TTL no longer suppresses the offer"
);
}
#[test]
fn draining_an_idle_listener_reports_no_change_and_does_not_block() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
seat_view_listener(&mut app, tmp.path());
let flags = {
use std::os::unix::io::AsRawFd;
let listener = app.view_listener.as_ref().unwrap();
unsafe { libc::fcntl(listener.as_raw_fd(), libc::F_GETFL) }
};
assert!(
flags != -1 && flags & libc::O_NONBLOCK != 0,
"the frame loop polls this listener, so it must be non-blocking"
);
let started = std::time::Instant::now();
assert!(!app.drain_view_requests(), "nothing was sent");
assert!(
started.elapsed() < std::time::Duration::from_millis(500),
"the drain blocked for {:?}",
started.elapsed()
);
}
#[test]
fn a_terminated_request_over_the_cap_is_refused_like_an_unterminated_one() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let sock = seat_view_listener(&mut app, tmp.path());
let sock2 = sock.clone();
let flood = std::thread::spawn(move || {
let Ok(mut c) = std::os::unix::net::UnixStream::connect(&sock2) else {
return;
};
let mut line = vec![b'x'; (crate::view_ipc::MAX_REQUEST_BYTES as usize) + 100];
line.push(b'\n');
let _ = std::io::Write::write_all(&mut c, &line);
let _ = std::io::Write::flush(&mut c);
std::thread::sleep(std::time::Duration::from_millis(300));
});
std::thread::sleep(std::time::Duration::from_millis(50));
let listener = app.view_listener.as_ref().unwrap();
let stream = accept_when_ready(listener);
let deadline = std::time::Instant::now()
+ crate::test_budget::spawn_budget(crate::test_budget::tests::VIEW_SERVER_DEADLINE_BASE);
let (reply, opened) = app.answer_view_client(stream, deadline);
let _ = flood.join();
assert!(!opened, "an oversized request names nothing to open");
match reply {
crate::view_ipc::ViewReply::Err { message } => assert!(
message.contains("exceeded the maximum length"),
"the LENGTH cap must be what refuses this, not an incidental parse \
failure downstream of accepting it: {message}"
),
other => panic!("an oversized request must not be accepted: {other:?}"),
}
}
#[test]
fn index_after_removals_shifts_past_lower_removals_only() {
assert_eq!(index_after_removals(2, &[]), Some(2));
assert_eq!(index_after_removals(2, &[0]), Some(1));
assert_eq!(index_after_removals(3, &[0, 1]), Some(1));
assert_eq!(
index_after_removals(1, &[2, 3]),
Some(1),
"removals above do not move it"
);
assert_eq!(index_after_removals(2, &[0, 2]), None, "it ended itself");
}
#[cfg(unix)]
#[test]
fn a_run_asked_for_mid_run_does_not_take_over_the_first_runs_outcome() {
let mut s = CodeqlStandIn::new();
s.will(STAND_IN_PASS, 0);
s.app.run_named_test(String::from("Find.qlref"));
assert_eq!(s.app.status, "Running test test/Find::Find.qlref");
s.app.run_named_test(String::from("Other.qlref"));
assert_eq!(s.app.status, TEST_RUN_IN_PROGRESS);
s.finish();
assert!(
s.app.status.starts_with("Find.qlref passed ("),
"{}",
s.app.status
);
}
#[test]
fn a_recorded_frame_masks_secrets_even_while_revealed() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.terminals[0].last_inner = ratatui::layout::Rect {
x: 1,
y: 1,
width: 60,
height: 10,
};
app.terminals[0].resize(60, 10);
let key = "AKIAIOSFODNN7EXAMPLE";
app.terminals[0].feed_bytes_for_test(format!("export KEY={key}\r\n").as_bytes());
app.reveal_redacted_secrets();
app.run_command(crate::widgets::command_palette::Command::ToggleSessionRecording);
app.record_active_screen();
app.run_command(crate::widgets::command_palette::Command::ToggleSessionRecording);
let path = std::fs::read_dir(app.workspace_root())
.unwrap()
.filter_map(|e| e.ok().map(|e| e.path()))
.find(|p| p.extension().is_some_and(|x| x == "cast"))
.expect("a .cast file was written");
let text = std::fs::read_to_string(&path).unwrap();
assert!(!text.contains(key), "the key reached the cast:\n{text}");
assert!(text.contains("export KEY="), "{text}");
}
#[test]
fn show_memory_usage_opens_a_per_subsystem_report() {
use crate::lsp::manager::DiagnosticSeverity;
use crate::widgets::command_palette::Command;
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let mut by_server = std::collections::HashMap::new();
by_server.insert(
String::from("ruff"),
vec![
diag(0, 1, DiagnosticSeverity::Warning),
diag(2, 3, DiagnosticSeverity::Error),
],
);
app.lsp
.diagnostics
.insert(tmp.path().join("a.py"), by_server);
app.run_command(Command::DeveloperShowMemoryUsage);
assert_eq!(app.editor.path.as_deref(), Some(Path::new("Memory Usage")));
let text = app.editor.lines.join("\n");
for section in ["Terminal panes", "Undo history", "OUTPUT channels"] {
assert!(text.contains(section), "{text}");
}
assert!(text.contains("`ruff`: 2 diagnostics in 1 files"), "{text}");
assert!(
app.editor.markdown_preview.is_some(),
"the report opens rendered"
);
draw(&mut app, 120, 40);
app.handle_key(key(KeyCode::End, KeyModifiers::NONE))
.unwrap();
draw(&mut app, 120, 40);
let shown = |app: &App| {
let md = app.editor.markdown_preview.as_ref().unwrap();
md.rows
.iter()
.map(|r| r.concat())
.collect::<Vec<_>>()
.join("\n")
};
assert!(
shown(&app).contains("ruff: 2 diagnostics in 1 files"),
"{}",
shown(&app)
);
type_keys(&mut app, "zz");
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
app.handle_key(key(KeyCode::Backspace, KeyModifiers::NONE))
.unwrap();
assert_eq!(
app.editor.lines.join("\n"),
text,
"typing leaves the report alone"
);
assert!(!app.editor.dirty, "nothing was edited");
}
#[test]
fn show_memory_usage_renders_in_the_active_theme() {
use crate::widgets::command_palette::Command;
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let light = crate::theme::Theme::from_id("light");
assert_ne!(light.accent(), crate::theme::Theme::default().accent());
app.apply_theme(light);
app.run_command(Command::DeveloperShowMemoryUsage);
let md = app
.editor
.markdown_preview
.as_ref()
.expect("opens rendered");
let title = (md.lines.iter().flat_map(|l| &l.spans))
.find(|s| s.content.contains("croft memory usage"))
.expect("the title is built");
assert_eq!(
title.style.fg,
Some(light.accent()),
"the title is in the theme's accent"
);
}
#[test]
fn show_memory_usage_lists_running_language_servers_even_without_diagnostics() {
use crate::widgets::command_palette::Command;
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let pid = std::process::id();
app.lsp
.manager
.as_ref()
.expect("LSP manager available")
.set_running_servers_for_test(vec![(String::from("rust-analyzer"), Some(pid))]);
app.run_command(Command::DeveloperShowMemoryUsage);
let text = app.editor.lines.join("\n");
assert!(
text.contains("## Running language servers (1)"),
"running server section must count live servers:\n{text}"
);
assert!(
text.contains(&format!("`rust-analyzer` (pid {pid})")),
"running server must list name and PID:\n{text}"
);
#[cfg(any(target_os = "linux", target_os = "macos"))]
{
assert!(
!text.contains("Process RSS: unavailable"),
"Process RSS must be reported on Linux and macOS:\n{text}"
);
assert!(
text.contains("RSS\n"),
"live server RSS must be reported on Linux and macOS:\n{text}"
);
}
assert!(
text.contains("## Language server diagnostics (0 servers)\n\nNone held."),
"zero diagnostics stays distinct from zero running servers:\n{text}"
);
}
#[test]
fn a_recovered_tasks_crash_notice_does_not_ask_for_a_restart() {
let _slot = crash_slot_lock();
note_background_panic("check-project", true);
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
assert!(app.poll_background_panic(), "the crash is shown");
assert!(
app.status.contains("(check-project)")
&& app.status.contains("croft carried on")
&& !app.status.contains("restart")
&& app.status.contains("~/.cache/croft/panic.log"),
"{}",
app.status
);
}
#[test]
fn an_unrecovered_crash_keeps_the_restart_advice_beside_a_recovered_one() {
let _slot = crash_slot_lock();
note_background_panic("pane-reader", false);
note_background_panic("check-project", true);
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
assert!(app.poll_background_panic());
assert!(
app.status.contains("(pane-reader, check-project)") && app.status.contains("restart croft"),
"{}",
app.status
);
}
#[test]
fn a_task_that_says_what_its_crash_cost_keeps_the_status_line() {
let _slot = crash_slot_lock();
note_background_panic(crate::voice::THREAD, true);
claim_background_panic(crate::voice::THREAD);
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.status = String::from("the task's own message");
assert!(!app.poll_background_panic(), "nothing left to say");
assert_eq!(app.status, "the task's own message");
}
#[test]
fn a_background_crash_keeps_the_terminal_and_says_what_crashed() {
let _slot = crash_slot_lock();
let ui = std::thread::current().id();
assert!(
panic_ends_croft(ui, ui),
"a crash on the screen's thread ends croft"
);
std::thread::Builder::new()
.name(String::from("git-status"))
.spawn(move || {
let me = std::thread::current();
assert!(
!panic_ends_croft(me.id(), ui),
"a background thread's crash does not"
);
note_background_panic(me.name().unwrap(), false);
})
.unwrap()
.join()
.unwrap();
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
assert!(app.poll_background_panic(), "the crash is shown");
assert!(
app.status.contains("(git-status)") && app.status.contains("restart croft"),
"{}",
app.status
);
assert!(!app.poll_background_panic(), "and shown once");
}