use super::*;
#[test]
fn a_file_not_written_yet_opens_at_launch_and_its_save_creates_it() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("notes.md");
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.open_file_at_launch(&path);
assert_eq!(app.editor.path.as_deref(), Some(path.as_path()));
assert!(app.status.contains("saving creates it"), "{}", app.status);
assert!(!path.exists());
app.editor.insert_str("# Notes");
app.write_current_to_disk();
assert_eq!(
std::fs::read_to_string(&path).unwrap().trim_end(),
"# Notes"
);
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.open_file_at_launch(&tmp.path().join("gone/new.md"));
assert!(app.editor.path.is_none());
assert!(app.status.contains("Couldn't open"), "{}", app.status);
}
#[test]
fn fs_watcher_does_not_descend_into_protected_top_level_dirs() {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir(tmp.path().join("src")).unwrap();
std::fs::write(tmp.path().join("src").join("a.txt"), "hi").unwrap();
let library = tmp.path().join("Library");
std::fs::create_dir(&library).unwrap();
std::fs::create_dir(library.join("Containers")).unwrap();
std::fs::write(library.join("Containers").join("payload"), "x").unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&library, std::fs::Permissions::from_mode(0o000)).unwrap();
}
let result = super::fs_watch::FsWatch::spawn_watcher(tmp.path());
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let _ = std::fs::set_permissions(&library, std::fs::Permissions::from_mode(0o755));
}
assert!(
result.is_ok(),
"watcher must skip protected dirs and start cleanly"
);
}
#[test]
fn fs_watcher_does_not_deliver_events_from_target_or_node_modules_subtrees() {
let tmp = tempfile::tempdir().unwrap();
let src_raw = tmp.path().join("src");
let target_raw = tmp.path().join("target");
let node_modules_raw = tmp.path().join("node_modules");
std::fs::create_dir(&src_raw).unwrap();
std::fs::create_dir(&target_raw).unwrap();
std::fs::create_dir(&node_modules_raw).unwrap();
let src = src_raw.canonicalize().unwrap();
let target = target_raw.canonicalize().unwrap();
let node_modules = node_modules_raw.canonicalize().unwrap();
let (_debouncer, rx) = super::fs_watch::FsWatch::spawn_watcher(tmp.path())
.expect("watcher must start cleanly with noise dirs present");
for _ in 0..30 {
while rx.try_recv().is_ok() {}
std::thread::sleep(std::time::Duration::from_millis(10));
}
for i in 0..50 {
std::fs::write(target.join(format!("cargo_{i}.o")), b"x").unwrap();
std::fs::write(node_modules.join(format!("pkg_{i}.js")), b"x").unwrap();
}
std::thread::sleep(std::time::Duration::from_millis(400));
let mut noise_events: Vec<std::path::PathBuf> = Vec::new();
while let Ok(batch) = rx.try_recv() {
for ev in batch.unwrap_or_default() {
for path in &ev.event.paths {
if path.starts_with(&target) || path.starts_with(&node_modules) {
noise_events.push(path.clone());
}
}
}
}
assert!(
noise_events.is_empty(),
"writes under target/ and node_modules/ must not produce debouncer events; got {noise_events:?}"
);
std::fs::write(src.join("a.rs"), b"fn main() {}").unwrap();
let started = std::time::Instant::now();
let mut signal_events: Vec<std::path::PathBuf> = Vec::new();
while started.elapsed() < std::time::Duration::from_millis(1500) {
while let Ok(batch) = rx.try_recv() {
for ev in batch.unwrap_or_default() {
for path in &ev.event.paths {
if path.starts_with(&src) {
signal_events.push(path.clone());
}
}
}
}
if !signal_events.is_empty() {
break;
}
std::thread::sleep(std::time::Duration::from_millis(10));
}
assert!(
!signal_events.is_empty(),
"writes under src/ must still produce debouncer events after the noise-dir split"
);
}
#[test]
fn fs_watcher_prunes_a_go_module_cache_below_the_workspace_root() {
let tmp = tempfile::tempdir().unwrap();
let cache_raw = tmp.path().join("go/pkg/mod/golang.org/x");
let src_raw = tmp.path().join("go/cmd");
std::fs::create_dir_all(&cache_raw).unwrap();
std::fs::create_dir_all(&src_raw).unwrap();
let cache = cache_raw.canonicalize().unwrap();
let src = src_raw.canonicalize().unwrap();
let (_debouncer, rx) = super::fs_watch::FsWatch::spawn_watcher(tmp.path())
.expect("watcher must start cleanly with a go module cache present");
for _ in 0..30 {
while rx.try_recv().is_ok() {}
std::thread::sleep(std::time::Duration::from_millis(10));
}
for i in 0..50 {
std::fs::write(cache.join(format!("mod_{i}.go")), b"x").unwrap();
}
std::thread::sleep(std::time::Duration::from_millis(400));
let mut noise_events: Vec<std::path::PathBuf> = Vec::new();
while let Ok(batch) = rx.try_recv() {
for ev in batch.unwrap_or_default() {
for path in &ev.event.paths {
if path.starts_with(&cache) {
noise_events.push(path.clone());
}
}
}
}
assert!(
noise_events.is_empty(),
"writes under go/pkg/mod must not produce debouncer events; got {noise_events:?}"
);
std::fs::write(src.join("main.go"), b"package main").unwrap();
let started = std::time::Instant::now();
let mut signal_events: Vec<std::path::PathBuf> = Vec::new();
while started.elapsed() < std::time::Duration::from_millis(1500) {
while let Ok(batch) = rx.try_recv() {
for ev in batch.unwrap_or_default() {
for path in &ev.event.paths {
if path.starts_with(&src) {
signal_events.push(path.clone());
}
}
}
}
if !signal_events.is_empty() {
break;
}
std::thread::sleep(std::time::Duration::from_millis(25));
}
assert!(
!signal_events.is_empty(),
"writes under a real go/cmd source dir must still produce events"
);
}
#[test]
fn fs_watcher_still_watches_a_workspace_whose_own_path_is_noise_named() {
let tmp = tempfile::tempdir().unwrap();
let root_raw = tmp.path().join("build/myapp");
let src_raw = root_raw.join("src");
std::fs::create_dir_all(&src_raw).unwrap();
let root = root_raw.canonicalize().unwrap();
let src = src_raw.canonicalize().unwrap();
let (_debouncer, rx) = super::fs_watch::FsWatch::spawn_watcher(&root)
.expect("watcher must start for a root under a noise-named ancestor");
for _ in 0..30 {
while rx.try_recv().is_ok() {}
std::thread::sleep(std::time::Duration::from_millis(10));
}
std::fs::write(src.join("a.rs"), b"fn main() {}").unwrap();
let started = std::time::Instant::now();
let mut signal_events: Vec<std::path::PathBuf> = Vec::new();
while started.elapsed() < std::time::Duration::from_millis(1500) {
while let Ok(batch) = rx.try_recv() {
for ev in batch.unwrap_or_default() {
for path in &ev.event.paths {
if path.starts_with(&src) {
signal_events.push(path.clone());
}
}
}
}
if !signal_events.is_empty() {
break;
}
std::thread::sleep(std::time::Duration::from_millis(25));
}
assert!(
!signal_events.is_empty(),
"a workspace under a build/ ancestor must still deliver its own events"
);
}
#[test]
fn drain_reports_writes_in_a_workspace_under_a_noise_named_ancestor() {
let tmp = tempfile::tempdir().unwrap();
let src_raw = tmp.path().join("build/myapp/src");
std::fs::create_dir_all(&src_raw).unwrap();
let root = tmp
.path()
.join("build/myapp")
.canonicalize()
.expect("the workspace root exists");
let src = src_raw.canonicalize().unwrap();
let mut app = App::new(root.clone()).unwrap();
for _ in 1..=FS_SYNC_TICKS {
app.try_install_pending_init();
let _ = app.fs_watch.drain(&mut app.tree, &app.editor);
std::thread::sleep(std::time::Duration::from_millis(10));
}
let signal = src.join("a.rs");
std::fs::write(&signal, b"fn main() {}").unwrap();
let mut changed: std::collections::BTreeSet<std::path::PathBuf> =
std::collections::BTreeSet::new();
let mut finder_relevant = false;
for _ in 1..=FS_SYNC_TICKS {
let d = app.fs_watch.drain(&mut app.tree, &app.editor);
changed.extend(d.changed_files);
finder_relevant |= d.finder_relevant;
if changed.contains(&signal) {
break;
}
std::thread::sleep(std::time::Duration::from_millis(25));
}
assert!(
changed.contains(&signal),
"a write inside a workspace under a build/ ancestor is the workspace's \
own content, not noise; got {changed:?}"
);
assert!(
finder_relevant,
"and it is worth a finder index rebuild, since the finder indexes it"
);
}
#[test]
fn writes_inside_a_directory_made_after_startup_are_reported() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().canonicalize().unwrap();
let mut app = App::new(root.clone()).unwrap();
for _ in 1..=FS_SYNC_TICKS {
app.try_install_pending_init();
let _ = app.fs_watch.drain(&mut app.tree, &app.editor);
std::thread::sleep(std::time::Duration::from_millis(10));
}
let dir = root.join("newdir");
std::fs::create_dir(&dir).unwrap();
let early = dir.join("early.rs");
std::fs::write(&early, b"1").unwrap();
let mut changed: std::collections::BTreeSet<std::path::PathBuf> =
std::collections::BTreeSet::new();
for _ in 1..=FS_SYNC_TICKS {
changed.extend(app.fs_watch.drain(&mut app.tree, &app.editor).changed_files);
if changed.contains(&early) {
break;
}
std::thread::sleep(std::time::Duration::from_millis(25));
}
assert!(changed.contains(&early), "{changed:?}");
let late = dir.join("late.rs");
std::fs::write(&late, b"2").unwrap();
for _ in 1..=FS_SYNC_TICKS {
changed.extend(app.fs_watch.drain(&mut app.tree, &app.editor).changed_files);
if changed.contains(&late) {
break;
}
std::thread::sleep(std::time::Duration::from_millis(25));
}
assert!(
changed.contains(&late),
"the new folder is watched: {changed:?}"
);
}
#[test]
fn fs_watcher_prunes_noise_dirs_nested_below_the_workspace_root() {
let tmp = tempfile::tempdir().unwrap();
let repo_raw = tmp.path().join("repo");
let src_raw = repo_raw.join("src");
let node_modules_raw = repo_raw.join("node_modules");
let git_raw = repo_raw.join(".git");
std::fs::create_dir_all(&src_raw).unwrap();
std::fs::create_dir_all(&node_modules_raw).unwrap();
std::fs::create_dir_all(&git_raw).unwrap();
let src = src_raw.canonicalize().unwrap();
let node_modules = node_modules_raw.canonicalize().unwrap();
let git = git_raw.canonicalize().unwrap();
let (_debouncer, rx) = super::fs_watch::FsWatch::spawn_watcher(tmp.path())
.expect("watcher must start cleanly with nested noise dirs present");
for _ in 0..30 {
while rx.try_recv().is_ok() {}
std::thread::sleep(std::time::Duration::from_millis(10));
}
for i in 0..50 {
std::fs::write(node_modules.join(format!("pkg_{i}.js")), b"x").unwrap();
std::fs::write(git.join(format!("obj_{i}")), b"x").unwrap();
}
std::thread::sleep(std::time::Duration::from_millis(400));
let mut noise_events: Vec<std::path::PathBuf> = Vec::new();
while let Ok(batch) = rx.try_recv() {
for ev in batch.unwrap_or_default() {
for path in &ev.event.paths {
if path.starts_with(&node_modules) || path.starts_with(&git) {
noise_events.push(path.clone());
}
}
}
}
assert!(
noise_events.is_empty(),
"writes under a repo's nested node_modules/ and .git/ must not produce \
debouncer events even when the repo is itself a subdir of the root; got {noise_events:?}"
);
std::fs::write(src.join("a.rs"), b"fn main() {}").unwrap();
let started = std::time::Instant::now();
let mut signal_events: Vec<std::path::PathBuf> = Vec::new();
while started.elapsed() < std::time::Duration::from_millis(1500) {
while let Ok(batch) = rx.try_recv() {
for ev in batch.unwrap_or_default() {
for path in &ev.event.paths {
if path.starts_with(&src) {
signal_events.push(path.clone());
}
}
}
}
if !signal_events.is_empty() {
break;
}
std::thread::sleep(std::time::Duration::from_millis(10));
}
assert!(
!signal_events.is_empty(),
"writes under a nested repo/src/ must still produce events after the depth-aware split"
);
}
#[cfg(target_os = "macos")]
#[test]
fn macos_watch_walk_stops_when_the_dir_budget_is_spent() {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir_all(tmp.path().join(".git")).unwrap();
for i in 0..300 {
std::fs::create_dir_all(tmp.path().join(format!("d{i}/sub"))).unwrap();
}
let mut targets: Vec<(std::path::PathBuf, notify::RecursiveMode)> = Vec::new();
let mut budget = 50usize; super::fs_watch::collect_macos_watch_targets(tmp.path(), tmp.path(), &mut targets, &mut budget);
assert_eq!(
budget, 0,
"the walk must spend its whole budget and stop, not visit every dir"
);
assert!(
targets.len() < 300,
"once the budget caps, not every clean subtree is watched (the poll covers the rest); got {}",
targets.len()
);
}
#[cfg(target_os = "macos")]
#[test]
fn macos_watch_targets_never_root_a_stream_above_a_noise_dir() {
use crate::file_index::is_noise_dir;
let tmp = tempfile::tempdir().unwrap();
for repo in ["alpha", "beta"] {
let r = tmp.path().join(repo);
std::fs::create_dir_all(r.join("src/inner")).unwrap();
std::fs::create_dir_all(r.join("target/debug/incremental")).unwrap();
std::fs::create_dir_all(r.join("node_modules/pkg")).unwrap();
std::fs::create_dir_all(r.join(".git/objects")).unwrap();
}
let mut targets: Vec<(std::path::PathBuf, notify::RecursiveMode)> = Vec::new();
let mut budget = usize::MAX; super::fs_watch::collect_macos_watch_targets(tmp.path(), tmp.path(), &mut targets, &mut budget);
for (path, _mode) in &targets {
for entry in walkdir_noise(path) {
if let Some(name) = entry.file_name() {
assert!(
!is_noise_dir(name),
"watch target {path:?} roots an FSEvents stream over noise dir {entry:?}; \
cargo/npm build churn there would peg the fsevents callback"
);
}
}
}
assert!(
targets.iter().any(|(p, _)| p.ends_with("alpha/src")
|| p.canonicalize()
.map(|c| c.ends_with("alpha/src"))
.unwrap_or(false)),
"the clean repo subtree (alpha/src) must still be watched; got {targets:?}"
);
}
#[cfg(target_os = "macos")]
fn walkdir_noise(root: &std::path::Path) -> Vec<std::path::PathBuf> {
let mut out = Vec::new();
let mut stack = vec![root.to_path_buf()];
while let Some(dir) = stack.pop() {
let Ok(rd) = std::fs::read_dir(&dir) else {
continue;
};
for entry in rd.filter_map(Result::ok) {
let p = entry.path();
if entry.file_type().map(|ft| ft.is_dir()).unwrap_or(false) {
out.push(p.clone());
stack.push(p);
}
}
}
out
}
#[test]
fn drain_fs_events_returns_false_when_nothing_pending() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.fs_watch.disable();
for _ in 0..20 {
let _ = app.drain_fs_events();
std::thread::sleep(std::time::Duration::from_millis(10));
}
assert!(!app.drain_fs_events(), "no fs events ⇒ no redraw needed");
}
const FS_SYNC_TICKS: usize = 20;
#[test]
fn drain_fs_events_returns_true_after_workspace_write() {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir(tmp.path().join(".git")).unwrap();
std::fs::write(tmp.path().join(".gitignore"), "*.txt\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
for _ in 0..20 {
let _ = app.drain_fs_events();
std::thread::sleep(std::time::Duration::from_millis(10));
}
let new_file = tmp.path().join("new.txt");
std::fs::write(&new_file, "hi").unwrap();
let mut saw = false;
let mut landed = false;
for _ in 1..=FS_SYNC_TICKS {
if app.drain_fs_events() {
saw = true;
}
if app.tree.nodes.iter().any(|n| n.path == new_file) {
landed = true;
break;
}
std::thread::sleep(std::time::Duration::from_millis(10));
}
assert!(saw, "workspace write should propagate as a dirty signal");
assert!(
landed,
"created file should appear in Explorer within {FS_SYNC_TICKS} drain ticks (never landed)"
);
}
#[test]
fn drain_fs_events_removes_deleted_root_file_from_tree() {
let tmp = tempfile::tempdir().unwrap();
let doomed = tmp.path().join("doomed.txt");
std::fs::write(&doomed, "bye").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
assert!(
app.tree.nodes.iter().any(|n| n.path == doomed),
"precondition: initial tree contains the file"
);
std::fs::remove_file(&doomed).unwrap();
let mut gone = false;
for _ in 1..=FS_SYNC_TICKS {
let _ = app.drain_fs_events();
if !app.tree.nodes.iter().any(|n| n.path == doomed) {
gone = true;
break;
}
std::thread::sleep(std::time::Duration::from_millis(10));
}
assert!(
gone,
"deleted file should disappear from Explorer within {FS_SYNC_TICKS} drain ticks (never left)"
);
}
#[test]
#[ignore = "wall clock: run serially on a quiet machine"]
fn fs_sync_reflects_external_changes_within_200ms_wall_clock() {
let tmp = tempfile::tempdir().unwrap();
let doomed = tmp.path().join("doomed.txt");
std::fs::write(&doomed, "bye").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
for _ in 0..20 {
let _ = app.drain_fs_events();
std::thread::sleep(std::time::Duration::from_millis(10));
}
let budget = std::time::Duration::from_millis(200);
let new_file = tmp.path().join("new.txt");
std::fs::write(&new_file, "hi").unwrap();
let started = std::time::Instant::now();
while !app.tree.nodes.iter().any(|n| n.path == new_file) {
let _ = app.drain_fs_events();
assert!(
started.elapsed() <= budget,
"created file should appear in Explorer within {budget:?} (deadline passed mid-drain)"
);
std::thread::sleep(std::time::Duration::from_millis(10));
}
assert!(
started.elapsed() <= budget,
"created file should appear in Explorer within {budget:?} (deadline passed at the last check)"
);
std::fs::remove_file(&doomed).unwrap();
let started = std::time::Instant::now();
while app.tree.nodes.iter().any(|n| n.path == doomed) {
let _ = app.drain_fs_events();
assert!(
started.elapsed() <= budget,
"deleted file should disappear from Explorer within {budget:?} (deadline passed mid-drain)"
);
std::thread::sleep(std::time::Duration::from_millis(10));
}
assert!(
started.elapsed() <= budget,
"deleted file should disappear from Explorer within {budget:?} (deadline passed at the last check)"
);
}
#[test]
fn drain_fs_events_polling_fallback_refreshes_tree_without_watcher_event() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.fs_watch.disable();
app.fs_watch.clear_dir_mtimes();
app.fs_watch.force_poll_due();
let new_file = tmp.path().join("new.txt");
std::fs::write(&new_file, "hi").unwrap();
assert!(app.drain_fs_events());
assert!(
app.tree.nodes.iter().any(|n| n.path == new_file),
"polling fallback should refresh the tree when no watcher event arrives"
);
}
#[test]
fn drain_fs_events_polling_fallback_reloads_clean_open_file_without_watcher_event() {
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("open.txt");
std::fs::write(&file, "old\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&file).unwrap();
app.sync_open_file_poll_mtime();
app.fs_watch.disable();
app.fs_watch.force_poll_due();
std::fs::write(&file, "new content\n").unwrap();
assert!(app.drain_fs_events());
assert_eq!(app.editor.lines, vec!["new content"]);
assert!(!app.editor.dirty);
}
#[test]
fn reopen_with_encoding_refuses_to_discard_unsaved_edits() {
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("notes.txt");
std::fs::write(&f, "keep me\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&f).unwrap();
app.editor.cursor_col = 0;
app.editor.insert_char('X');
assert!(app.editor.dirty, "the buffer has unsaved work");
app.dispatch_menu_action(
MenuAction::SetEncoding(encoding_rs::UTF_8),
tmp.path().to_path_buf(),
);
assert!(
app.editor.lines[0].starts_with('X'),
"the unsaved edit must survive, got {:?}",
app.editor.lines[0]
);
assert!(app.editor.dirty, "and the buffer is still dirty");
let msg = app.status.to_lowercase();
assert!(
msg.contains("undo"),
"the refusal must point at the non-destructive route, got {:?}",
app.status
);
assert!(
!msg.contains("save the file first") && !msg.contains("save first"),
"must not advise the destructive route, got {:?}",
app.status
);
}
#[test]
fn vs_code_files_encoding_decodes_a_legacy_file() {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir_all(tmp.path().join(".vscode")).unwrap();
std::fs::write(
tmp.path().join(".vscode/settings.json"),
r#"{ "files.encoding": "windows1252" }"#,
)
.unwrap();
let f = tmp.path().join("notes.txt");
std::fs::write(&f, b"Gr\xfc\xdfe aus K\xf6ln\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&f).unwrap();
assert_eq!(app.editor.lines[0], "Grüße aus Köln");
assert_eq!(app.editor.encoding, encoding_rs::WINDOWS_1252);
}
#[test]
fn without_a_declared_encoding_a_legacy_file_opens_as_utf_8() {
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("notes.txt");
std::fs::write(&f, b"Gr\xfc\xdfe aus K\xf6ln\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&f).unwrap();
assert_eq!(app.editor.encoding, encoding_rs::UTF_8);
assert!(app.editor.decode_lossy);
}
#[test]
fn the_status_bar_encoding_pick_survives_closing_the_tab() {
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("notes.txt");
std::fs::write(&f, b"Gr\xfc\xdfe aus K\xf6ln\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&f).unwrap();
app.dispatch_menu_action(
MenuAction::SetEncoding(encoding_rs::WINDOWS_1252),
tmp.path().to_path_buf(),
);
assert_eq!(app.editor.lines[0], "Grüße aus Köln");
app.editor.close_active();
app.editor.open_pinned(&f).unwrap();
assert_eq!(app.editor.encoding, encoding_rs::WINDOWS_1252);
assert_eq!(app.editor.lines[0], "Grüße aus Köln");
}
#[test]
fn make_root_into_a_nested_folder_drops_the_parent_files_encoding() {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir_all(tmp.path().join(".vscode")).unwrap();
std::fs::write(
tmp.path().join(".vscode/settings.json"),
r#"{ "files.encoding": "windows1252" }"#,
)
.unwrap();
let inner = tmp.path().join("inner");
std::fs::create_dir_all(&inner).unwrap();
let f = inner.join("notes.txt");
std::fs::write(&f, "Grüße aus Köln\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.change_workspace_root(inner.clone());
app.editor.open_pinned(&f).unwrap();
assert_eq!(app.editor.encoding, encoding_rs::UTF_8);
assert_eq!(app.editor.lines[0], "Grüße aus Köln");
}
#[test]
fn an_external_write_reloads_a_tab_in_an_inactive_split_group() {
let tmp = tempfile::tempdir().unwrap();
let side = tmp.path().join("side.txt");
let front = tmp.path().join("front.txt");
std::fs::write(&side, "old\n").unwrap();
std::fs::write(&front, "front\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&side).unwrap();
app.split_editor(); app.editor.open_pinned(&front).unwrap(); app.sync_open_file_poll_mtime();
app.fs_watch.disable();
app.fs_watch.force_poll_due();
let _ = app.drain_fs_events();
std::fs::write(&side, "new content\n").unwrap();
app.fs_watch.force_poll_due();
let _ = app.drain_fs_events();
let stale: Vec<String> = app
.editor_layout
.inactive_groups()
.flat_map(|g| g.editors.iter())
.filter(|e| e.path.as_deref() == Some(side.as_path()))
.map(|e| e.lines.join("\n"))
.collect();
assert!(
!stale.is_empty(),
"the inactive group still holds a tab on side.txt"
);
for text in stale {
assert_eq!(
text, "new content",
"a tab in an inactive split group must reload too"
);
}
}
#[test]
fn watched_file_events_cover_a_moved_directory_and_an_atomic_save() {
use crate::app::fs_watch::watched_file_changes;
use lsp_types::FileChangeType;
use notify::Event as NotifyEvent;
use notify::event::{EventKind, ModifyKind, RenameMode};
use notify_debouncer_full::DebouncedEvent;
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
std::fs::create_dir_all(root.join("old/sub")).unwrap();
for f in ["old/a.rs", "old/sub/b.rs", "old2.rs", "lib.rs"] {
std::fs::write(root.join(f), "x").unwrap();
}
let index = crate::file_index::build_file_index(root);
let mut app = App::new(root.to_path_buf()).unwrap();
let (tx, rx) = std::sync::mpsc::channel();
app.fs_watch.set_test_events(rx);
std::fs::rename(root.join("old"), root.join("new")).unwrap();
std::fs::write(root.join("fresh.rs"), "y").unwrap();
let rename = |mode, paths: &[&str]| {
let mut ev = NotifyEvent::new(EventKind::Modify(ModifyKind::Name(mode)));
for p in paths {
ev = ev.add_path(root.join(p));
}
DebouncedEvent::new(ev, std::time::Instant::now())
};
tx.send(Ok(vec![
rename(RenameMode::Both, &["old", "new"]),
rename(RenameMode::To, &["lib.rs"]),
rename(RenameMode::To, &["fresh.rs"]),
]))
.unwrap();
let drain = app.fs_watch.drain(&mut app.tree, &app.editor);
let got = watched_file_changes(&drain, &index);
let typ = |rel: &str| {
let path = root.join(rel);
got.iter().find(|(p, _)| *p == path).map(|(_, t)| *t)
};
assert_eq!(
typ("lib.rs"),
Some(FileChangeType::CHANGED),
"an atomic save"
);
assert_eq!(typ("fresh.rs"), Some(FileChangeType::CREATED));
assert_eq!(typ("old/a.rs"), Some(FileChangeType::DELETED));
assert_eq!(typ("old/sub/b.rs"), Some(FileChangeType::DELETED));
assert_eq!(
typ("old2.rs"),
None,
"a sibling sharing the prefix is not in it"
);
}
#[test]
fn drain_fs_events_preserves_editor_selection_on_access_only_event() {
use notify::Event as NotifyEvent;
use notify::event::{AccessKind, AccessMode, EventKind};
use notify_debouncer_full::DebouncedEvent;
use std::sync::mpsc;
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("readme.md");
std::fs::write(&file, "hello world\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&file).unwrap();
app.editor.select_all();
assert!(
app.editor.selection.is_some(),
"precondition: selection set after select_all"
);
let (tx, rx) = mpsc::channel();
app.fs_watch.set_test_events(rx);
app.sync_open_file_poll_mtime();
let access_event = NotifyEvent::new(EventKind::Access(AccessKind::Open(AccessMode::Read)))
.add_path(file.clone());
tx.send(Ok(vec![DebouncedEvent::new(
access_event,
std::time::Instant::now(),
)]))
.unwrap();
app.drain_fs_events();
assert!(
app.editor.selection.is_some(),
"Access(Read) on the open file must not clobber editor selection"
);
}
#[test]
fn drain_ignores_read_only_access_events_from_croft_s_own_reads() {
use notify::Event as NotifyEvent;
use notify::event::{AccessKind, AccessMode, EventKind};
use notify_debouncer_full::DebouncedEvent;
use std::sync::mpsc;
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().to_path_buf();
let file = root.join("x.txt");
std::fs::write(&file, "x\n").unwrap();
let mut app = App::new(root.clone()).unwrap();
let (tx, rx) = mpsc::channel();
app.fs_watch.set_test_events(rx);
let now = std::time::Instant::now();
let access = |kind: AccessKind, path: &std::path::Path| {
let event = NotifyEvent::new(EventKind::Access(kind)).add_path(path.to_path_buf());
DebouncedEvent::new(event, now)
};
tx.send(Ok(vec![
access(AccessKind::Open(AccessMode::Any), &root),
access(AccessKind::Close(AccessMode::Read), &root),
access(AccessKind::Open(AccessMode::Any), &file),
access(AccessKind::Read, &file),
access(AccessKind::Close(AccessMode::Read), &file),
]))
.unwrap();
let drained = app.fs_watch.drain(&mut app.tree, &app.editor);
assert!(
!drained.got_any,
"reading the root and a file in it is not a change"
);
assert!(
!drained.dirs_changed,
"so it must not re-list the tree or re-run git status"
);
assert!(!drained.finder_relevant, "nor rebuild the Quick Open index");
tx.send(Ok(vec![access(
AccessKind::Close(AccessMode::Write),
&file,
)]))
.unwrap();
let drained = app.fs_watch.drain(&mut app.tree, &app.editor);
assert!(
drained.got_any && drained.dirs_changed,
"a close after writing may mean new content, so it still counts"
);
}
#[test]
fn drain_fs_events_preserves_editor_selection_on_metadata_event() {
use notify::Event as NotifyEvent;
use notify::event::{EventKind, MetadataKind, ModifyKind};
use notify_debouncer_full::DebouncedEvent;
use std::sync::mpsc;
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("readme.md");
std::fs::write(&file, "hello world\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&file).unwrap();
app.editor.select_all();
let (tx, rx) = mpsc::channel();
app.fs_watch.set_test_events(rx);
app.sync_open_file_poll_mtime();
let metadata_event = NotifyEvent::new(EventKind::Modify(ModifyKind::Metadata(
MetadataKind::AccessTime,
)))
.add_path(file.clone());
tx.send(Ok(vec![DebouncedEvent::new(
metadata_event,
std::time::Instant::now(),
)]))
.unwrap();
app.drain_fs_events();
assert!(
app.editor.selection.is_some(),
"Modify(Metadata(AccessTime)) on the open file must not clobber editor selection"
);
}
#[test]
fn drain_fs_events_reloads_on_modify_data_event() {
use notify::Event as NotifyEvent;
use notify::event::{DataChange, EventKind, ModifyKind};
use notify_debouncer_full::DebouncedEvent;
use std::sync::mpsc;
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("readme.md");
std::fs::write(&file, "old\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&file).unwrap();
let (tx, rx) = mpsc::channel();
app.fs_watch.set_test_events(rx);
app.sync_open_file_poll_mtime();
std::fs::write(&file, "new content\n").unwrap();
let modify_event = NotifyEvent::new(EventKind::Modify(ModifyKind::Data(DataChange::Content)))
.add_path(file.clone());
tx.send(Ok(vec![DebouncedEvent::new(
modify_event,
std::time::Instant::now(),
)]))
.unwrap();
app.drain_fs_events();
assert_eq!(app.editor.lines, vec!["new content"]);
}
#[test]
fn drain_fs_events_reloads_background_tab_on_external_change() {
use notify::Event as NotifyEvent;
use notify::event::{DataChange, EventKind, ModifyKind};
use notify_debouncer_full::DebouncedEvent;
use std::sync::mpsc;
let tmp = tempfile::tempdir().unwrap();
let bg = tmp.path().join("background.txt");
let fg = tmp.path().join("foreground.txt");
std::fs::write(&bg, "bg old\n").unwrap();
std::fs::write(&fg, "fg old\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&bg).unwrap(); app.editor.open_pinned(&fg).unwrap();
let (tx, rx) = mpsc::channel();
app.fs_watch.set_test_events(rx);
app.sync_open_file_poll_mtime();
std::fs::write(&bg, "bg NEW\n").unwrap();
let ev = NotifyEvent::new(EventKind::Modify(ModifyKind::Data(DataChange::Content)))
.add_path(bg.clone());
tx.send(Ok(vec![DebouncedEvent::new(ev, std::time::Instant::now())]))
.unwrap();
app.drain_fs_events();
let bg_tab = app
.editor
.iter_tabs()
.find(|e| e.path.as_deref() == Some(bg.as_path()))
.unwrap();
assert_eq!(
bg_tab.lines,
vec!["bg NEW"],
"a background tab must reload when its file changes on disk"
);
assert_eq!(app.editor.lines, vec!["fg old"], "active tab untouched");
}
#[test]
fn ctrl_s_is_save_key() {
for kitty in [false, true] {
assert!(is_save_key(
key(KeyCode::Char('s'), KeyModifiers::CONTROL),
kitty
));
}
}
#[test]
fn cmd_s_is_save_key() {
for kitty in [false, true] {
assert!(is_save_key(
key(KeyCode::Char('s'), KeyModifiers::SUPER),
kitty
));
}
}
#[test]
fn shift_ctrl_s_is_save_key() {
let mods = KeyModifiers::CONTROL | KeyModifiers::SHIFT;
assert!(is_save_key(key(KeyCode::Char('S'), mods), false));
for kitty in [false, true] {
assert!(is_save_key(
key(KeyCode::Char('S'), KeyModifiers::CONTROL),
kitty
));
}
}
#[test]
fn ctrl_s_without_a_reported_shift_still_saves_and_stays_put() {
let cases = [
(true, KeyCode::Char('s'), KeyModifiers::CONTROL),
(true, KeyCode::Char('S'), KeyModifiers::CONTROL),
(
false,
KeyCode::Char('s'),
KeyModifiers::CONTROL | KeyModifiers::SHIFT,
),
];
for (kitty, code, mods) in cases {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("notes.txt");
std::fs::write(&path, "on disk").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.kitty_keys = kitty;
app.editor.open_pinned(&path).unwrap();
app.focus_pane(Pane::Editor);
let before = app.sidebar_view;
app.editor.insert_str("edited ");
app.handle_key(key(code, mods)).unwrap();
assert_eq!(
std::fs::read_to_string(&path).unwrap().trim_end(),
"edited on disk",
"{code:?} {mods:?} kitty={kitty} saves"
);
assert_eq!(app.sidebar_view, before, "{code:?} {mods:?}: no jump");
assert_ne!(app.sidebar_view, SidebarView::SourceControl);
}
}
#[test]
fn plain_s_is_not_save_key() {
assert!(!is_save_key(
key(KeyCode::Char('s'), KeyModifiers::NONE),
true
));
}
#[test]
fn ctrl_q_is_not_save_key() {
assert!(!is_save_key(
key(KeyCode::Char('q'), KeyModifiers::CONTROL),
true
));
}
#[test]
fn alt_s_is_not_save_key() {
assert!(!is_save_key(
key(KeyCode::Char('s'), KeyModifiers::ALT),
true
));
}
#[test]
fn open_create_prompt_populates_state() {
use crate::widgets::file_tree::{create_file_in, create_folder_in, validate_new_name};
use tempfile::TempDir;
let tmp = TempDir::new().unwrap();
assert!(validate_new_name("hello.rs").is_ok());
let p = create_file_in(tmp.path(), "hello.rs").unwrap();
assert!(p.is_file());
let d = create_folder_in(tmp.path(), "newdir").unwrap();
assert!(d.is_dir());
}
#[test]
fn cmd_shift_slash_on_a_file_changes_workspace_root_to_the_file_s_parent_dir() {
let tmp = tempfile::tempdir().unwrap();
let inner = tmp.path().join("inner");
std::fs::create_dir(&inner).unwrap();
let file = inner.join("note.txt");
std::fs::write(&file, "").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let target_idx = app
.tree
.nodes
.iter()
.position(|n| n.path == file)
.or_else(|| {
let i = app.tree.nodes.iter().position(|n| n.path == inner).unwrap();
app.tree.selected = i;
app.tree.expand_selected();
app.tree.nodes.iter().position(|n| n.path == file)
})
.expect("file node must be visible after expanding inner/");
app.tree.selected = target_idx;
app.focus = Pane::Tree;
app.sidebar_view = SidebarView::Explorer;
let handled = app.handle_explorer_shortcut(key(
KeyCode::Char('/'),
KeyModifiers::SUPER | KeyModifiers::SHIFT,
));
assert!(
handled,
"Cmd+Shift+/ must be handled by the Explorer dispatcher"
);
assert_eq!(app.workspace_root(), inner);
assert_eq!(app.tree.root, inner);
}
#[test]
fn save_all_does_not_quit_while_an_untitled_buffer_holds_text() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.focus_pane(Pane::Editor);
type_keys(&mut app, "note");
assert!(app.editor.path.is_none() && app.editor.dirty, "setup");
press_ctrl_q(&mut app);
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
assert!(!app.quit, "the untitled text would be lost");
assert!(app.status.contains("untitled"), "{}", app.status);
assert_eq!(app.editor.lines, vec![String::from("note")]);
press_ctrl_q(&mut app);
app.handle_key(key(KeyCode::Char('D'), KeyModifiers::SHIFT))
.unwrap();
assert!(app.quit);
}
#[test]
fn save_all_does_not_quit_when_a_save_is_refused() {
let tmp = tempfile::tempdir().unwrap();
let (mut app, a) = app_with_unsaved_file(tmp.path());
std::fs::write(&a, "changed elsewhere\n").unwrap();
press_ctrl_q(&mut app);
app.handle_key(key(KeyCode::Char('s'), KeyModifiers::NONE))
.unwrap();
assert!(!app.quit);
assert!(
app.status.contains("a.txt (changed on disk)"),
"{}",
app.status
);
assert_eq!(
std::fs::read_to_string(&a).unwrap(),
"changed elsewhere\n",
"the other writer's change is not overwritten"
);
assert!(app.editor.dirty, "the edits are still in the buffer");
}
#[test]
fn save_all_writes_a_file_open_in_two_groups_with_the_same_edits_once_and_quits() {
let tmp = tempfile::tempdir().unwrap();
let (mut app, a) = app_with_unsaved_file(tmp.path());
let edited = app.editor.lines.clone();
app.split_editor();
app.editor.lines = edited.clone();
app.editor.dirty = true;
press_ctrl_q(&mut app);
app.handle_key(key(KeyCode::Char('s'), KeyModifiers::NONE))
.unwrap();
assert!(app.quit, "{}", app.status);
assert_eq!(std::fs::read_to_string(&a).unwrap(), "xalpha\n");
}
#[test]
fn save_all_writes_neither_of_two_different_unsaved_copies_of_a_file() {
let tmp = tempfile::tempdir().unwrap();
let (mut app, a) = app_with_unsaved_file(tmp.path());
app.split_editor();
app.editor.lines = vec![String::from("yalpha"), String::new()];
app.editor.dirty = true;
press_ctrl_q(&mut app);
app.handle_key(key(KeyCode::Char('s'), KeyModifiers::NONE))
.unwrap();
assert!(!app.quit);
assert!(
app.status
.contains("a.txt (open in 2 editor groups with different unsaved text)"),
"{}",
app.status
);
assert_eq!(std::fs::read_to_string(&a).unwrap(), "alpha\n");
let mut texts: Vec<String> = app
.editor_layout
.all_groups(&app.editor)
.flat_map(|g| g.editors.iter())
.filter(|e| e.path.as_deref() == Some(a.as_path()))
.inspect(|e| assert!(e.dirty, "both copies stay unsaved"))
.map(|e| e.lines[0].clone())
.collect();
texts.sort();
assert_eq!(texts, ["xalpha", "yalpha"]);
}
#[test]
fn s_at_the_close_prompt_saves_then_closes() {
let tmp = tempfile::tempdir().unwrap();
let (mut app, a) = app_with_unsaved_file(tmp.path());
app.handle_key(key(KeyCode::Char('w'), KeyModifiers::SUPER))
.unwrap();
app.handle_key(key(KeyCode::Char('s'), KeyModifiers::NONE))
.unwrap();
assert_eq!(std::fs::read_to_string(&a).unwrap(), "xalpha\n");
assert_eq!(app.editor.path, None, "the tab closed");
assert_eq!(app.status, "Saved and closed tab");
assert!(!app.quit, "closing a tab never quits");
}
#[test]
fn d_at_the_close_prompt_closes_without_saving() {
let tmp = tempfile::tempdir().unwrap();
let (mut app, a) = app_with_unsaved_file(tmp.path());
app.run_command(crate::widgets::command_palette::Command::CloseEditor);
assert!(app.pending_unsaved.is_some(), "View: Close Editor asks too");
app.handle_key(key(KeyCode::Char('d'), KeyModifiers::NONE))
.unwrap();
assert_eq!(app.editor.path, None, "the tab closed");
assert_eq!(app.status, "Closed tab without saving");
assert_eq!(std::fs::read_to_string(&a).unwrap(), "alpha\n");
app.reopen_closed_tab();
assert_eq!(app.editor.path.as_deref(), Some(a.as_path()));
assert_eq!(app.editor.lines[0], "alpha", "reopened from disk");
}
fn app_with_edited_search_editor(tmp: &std::path::Path, query: &str) -> (App, String) {
let mut app = App::new(tmp.to_path_buf()).unwrap();
app.search.query = query.to_string();
app.run_command(crate::widgets::command_palette::Command::OpenSearchEditor);
app.focus_pane(Pane::Editor);
type_keys(&mut app, "x");
assert!(app.editor.scratch && app.editor.dirty, "setup");
(app, format!("Search: {query}"))
}
fn scratch_label_written(workspace: &std::path::Path, label: &str) -> bool {
let mut written = false;
for p in [workspace.join(label), PathBuf::from(label)] {
written |= std::fs::remove_file(&p).is_ok();
}
written
}
#[test]
fn ctrl_s_on_a_scratch_tab_writes_no_file_and_points_to_save_as() {
let tmp = tempfile::tempdir().unwrap();
let (mut app, label) = app_with_edited_search_editor(tmp.path(), "issue951 ctrl-s");
let ctrl_s = key(KeyCode::Char('s'), KeyModifiers::CONTROL);
app.handle_key(ctrl_s).unwrap();
assert!(!scratch_label_written(tmp.path(), &label));
assert_eq!(app.status, crate::widgets::editor::SCRATCH_SAVE_REFUSAL);
assert!(app.editor.dirty, "the edits stay in the tab");
save_as(&mut app, "results.txt");
let kept = tmp.path().join("results.txt");
assert!(
std::fs::read_to_string(&kept)
.unwrap()
.contains("Query: issue951 ctrl-s"),
"{}",
app.status
);
assert_eq!(app.editor.path.as_deref(), Some(kept.as_path()));
type_keys(&mut app, "y");
app.handle_key(ctrl_s).unwrap();
assert!(!app.editor.dirty, "the file now saves: {}", app.status);
}
#[test]
fn auto_save_writes_the_files_but_never_a_scratch_tab() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.txt", "hello");
app.auto_save = true;
type_keys(&mut app, "x");
let label = "commit 951a5e7";
app.editor
.open_text_buffer(std::path::Path::new(label), "commit 951a5e7\n")
.unwrap();
type_keys(&mut app, "y");
assert!(app.editor.scratch && app.editor.dirty, "setup");
app.editor.editors.iter_mut().for_each(age_last_edit);
assert!(app.tick_auto_save(), "a.txt is due");
assert!(!scratch_label_written(tmp.path(), label));
assert!(app.editor.dirty, "the scratch tab keeps its edits");
let on_disk = std::fs::read_to_string(tmp.path().join("a.txt")).unwrap();
assert!(on_disk.contains('x'), "a.txt is written: {on_disk:?}");
}
#[test]
fn an_edited_scratch_tab_closes_without_offering_to_save() {
let tmp = tempfile::tempdir().unwrap();
let (mut app, label) = app_with_edited_search_editor(tmp.path(), "issue951 close");
assert!(app.unsaved_files().is_empty(), "a quit has nothing to ask");
assert!(
app.capture_hot_exit().buffers.is_empty(),
"nor hot exit to keep"
);
app.run_command(crate::widgets::command_palette::Command::SaveAll);
assert_eq!(app.status, "Save All: nothing to save");
app.handle_key(key(KeyCode::Char('w'), KeyModifiers::SUPER))
.unwrap();
assert!(app.pending_unsaved.is_none(), "no prompt offers to save it");
assert_ne!(
app.editor.path.as_deref(),
Some(std::path::Path::new(&label)),
"the tab closed"
);
assert!(!scratch_label_written(tmp.path(), &label));
}
#[test]
fn save_all_and_commit_commits_the_text_in_the_tab() {
let (tmp, mut app) = scm_with_unsaved_tab();
app.handle_source_control_key(key(KeyCode::Enter, KeyModifiers::NONE));
app.handle_key(key(KeyCode::Char('s'), KeyModifiers::NONE))
.unwrap();
wait_for_git_net(&mut app);
assert!(app.pending_unsaved_scm.is_none());
assert!(!app.editor.dirty, "the tab was saved");
assert_eq!(
git_stdout_untrimmed(tmp.path(), &["show", "HEAD:seed.txt"]),
"edited changed\n"
);
assert_eq!(last_commit_message(tmp.path()), "bump seed\n\n");
}
#[test]
fn save_all_and_stash_stashes_the_text_in_the_tab() {
let (tmp, mut app) = scm_with_unsaved_tab();
app.stash_source_control();
let pending = app.pending_unsaved_scm.as_ref().expect("the prompt opens");
assert_eq!(pending.op, ScmWrite::Stash);
assert_eq!(
git_stdout_untrimmed(tmp.path(), &["stash", "list"]),
"",
"nothing stashed yet"
);
let rendered = draw_screen(&mut app, 120, 40);
assert!(rendered.contains("Save All & Stash"), "{rendered}");
app.handle_key(key(KeyCode::Char('s'), KeyModifiers::NONE))
.unwrap();
assert!(app.pending_unsaved_scm.is_none());
assert!(!app.editor.dirty, "the tab was saved");
app.submit_input_prompt();
assert_eq!(
git_stdout_untrimmed(tmp.path(), &["stash", "list", "--format=%gs"]),
"On main: bump seed\n"
);
assert_eq!(
git_stdout_untrimmed(tmp.path(), &["show", "stash@{0}:seed.txt"]),
"edited changed\n"
);
assert_eq!(
std::fs::read_to_string(tmp.path().join("seed.txt")).unwrap(),
"seed\n",
"the stash put the work aside"
);
}
#[test]
fn a_file_outside_the_workspace_still_lists_its_local_snapshots() {
let tmp = tempfile::tempdir().unwrap();
let outside = tempfile::tempdir().unwrap();
let hist = tempfile::tempdir().unwrap();
let f = outside.path().join("note.txt");
std::fs::write(&f, "v2\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.history_root = hist.path().to_path_buf();
crate::history::record_in(&app.history_root, &f, b"v1\n", 1000).unwrap();
app.editor.open(&f).unwrap();
app.focus_pane(Pane::Editor);
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
let target = loop {
app.sync_explorer_panels();
if let Some(t) = app.timeline.diff_target(0) {
break Some(t);
}
if std::time::Instant::now() > deadline {
break None;
}
std::thread::sleep(std::time::Duration::from_millis(20));
};
assert_eq!(
target,
Some((f.clone(), "local:1000".to_string())),
"the out-of-root file's snapshot never reached the TIMELINE"
);
}
#[test]
fn saving_a_windows_1252_file_records_a_byte_exact_snapshot() {
let tmp = tempfile::tempdir().unwrap();
let hist = tempfile::tempdir().unwrap();
let f = tmp.path().join("latin.txt");
std::fs::write(&f, b"caf\xE9\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.history_root = hist.path().to_path_buf();
app.editor.open(&f).unwrap();
app.editor
.reopen_with_encoding(encoding_rs::WINDOWS_1252)
.unwrap();
app.focus_pane(Pane::Editor);
app.handle_key(key(KeyCode::Char('X'), KeyModifiers::NONE))
.unwrap();
app.save();
let snaps = wait_for_snapshots(&app.history_root, &f);
assert_eq!(
snaps.len(),
1,
"a non-UTF-8 file's save must record history"
);
let disk = std::fs::read(&f).unwrap();
assert!(disk.contains(&0xE9), "staging: the save re-encoded to 1252");
assert_eq!(
std::fs::read(&snaps[0].file).unwrap(),
disk,
"the snapshot must hold the exact on-disk bytes"
);
}
#[test]
fn cmd_p_index_is_built_in_the_background_so_open_does_not_walk_synchronously() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("alpha.rs"), b"").unwrap();
std::fs::create_dir(tmp.path().join(".croft")).unwrap();
std::fs::write(tmp.path().join(".croft").join("lsp.log"), b"").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let mut waited_ms = 0u32;
loop {
app.poll_file_finder_index();
if app.file_finder_index.is_some() {
break;
}
if waited_ms >= 5000 {
panic!(
"background walker thread must deliver the file index within 5s of App::new on a 2-file workspace"
);
}
std::thread::sleep(std::time::Duration::from_millis(20));
waited_ms += 20;
}
let rels: Vec<String> = app
.file_finder_index
.as_ref()
.unwrap()
.iter()
.map(|e| e.rel.clone())
.collect();
assert!(
rels.iter().any(|r| r == ".croft/lsp.log"),
"background index must contain .croft/lsp.log; got {rels:?}"
);
}
#[test]
fn change_workspace_root_rebuilds_cmd_p_index_against_the_new_root() {
let tmp = tempfile::tempdir().unwrap();
let a = tmp.path().join("root_a");
let b = tmp.path().join("root_b");
std::fs::create_dir_all(&a).unwrap();
std::fs::create_dir_all(&b).unwrap();
std::fs::write(a.join("only_in_a.rs"), b"").unwrap();
std::fs::write(b.join("only_in_b.rs"), b"").unwrap();
let mut app = App::new(a.clone()).unwrap();
let mut waited = 0u32;
loop {
app.poll_file_finder_index();
if let Some(idx) = app.file_finder_index.as_ref()
&& idx.iter().any(|e| e.rel == "only_in_a.rs")
{
break;
}
if waited >= 5000 {
panic!("initial index against root_a must land within 5s");
}
std::thread::sleep(std::time::Duration::from_millis(20));
waited += 20;
}
app.change_workspace_root(b.clone());
let mut saw_b = false;
for _ in 0..400 {
app.poll_file_finder_index();
if let Some(idx) = app.file_finder_index.as_ref() {
let rels: Vec<&str> = idx.iter().map(|e| e.rel.as_str()).collect();
if rels.contains(&"only_in_b.rs") && !rels.contains(&"only_in_a.rs") {
saw_b = true;
break;
}
}
std::thread::sleep(std::time::Duration::from_millis(10));
}
assert!(
saw_b,
"after change_workspace_root(b), the Cmd+P index must reflect root_b's files (only_in_b.rs present, only_in_a.rs gone); without this, Cmd+/ leaves Cmd+P searching the previous project"
);
}
#[test]
fn a_relative_launch_path_opens_the_absolute_file_under_the_workspace() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().canonicalize().unwrap();
std::fs::create_dir_all(root.join("pkg")).unwrap();
std::fs::write(root.join("pkg/util.py"), "x = 1\n").unwrap();
let mut app = App::new(root.clone()).unwrap();
app.open_file_at_launch(std::path::Path::new("pkg/util.py"));
assert_eq!(
app.editor.path.as_deref(),
Some(root.join("pkg/util.py").as_path())
);
assert!(app.focus == Pane::Editor);
}
#[test]
fn a_launch_file_that_cannot_be_opened_says_why() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.open_file_at_launch(std::path::Path::new("pkg/missing.py"));
assert!(app.editor.path.is_none());
assert!(
app.status.starts_with("Couldn't open ") && app.status.contains("pkg/missing.py"),
"status: {:?}",
app.status
);
}
#[test]
fn open_file_at_launch_opens_the_file_and_focuses_the_editor() {
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("hi.rs");
std::fs::write(&file, "fn main() {}").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.open_file_at_launch(&file);
assert_eq!(
app.editor.path.as_deref(),
Some(file.as_path()),
"`croft --open-file <path>` opens that file on launch"
);
assert!(
app.focus == Pane::Editor,
"the editor takes focus on launch open"
);
}
#[test]
fn status_path_speaks_workspace_relative_inside_the_root() {
let tmp = tempfile::tempdir().unwrap();
let app = App::new(tmp.path().to_path_buf()).unwrap();
let inside = tmp.path().join("src").join("main.rs");
assert_eq!(
app.status_path(&inside),
format!("src{}main.rs", std::path::MAIN_SEPARATOR),
"paths under the workspace root must render root-relative, like tabs \
and breadcrumbs"
);
let outside = std::path::Path::new("/etc/hosts");
assert_eq!(
app.status_path(outside),
"/etc/hosts",
"paths outside the root keep their absolute form"
);
}
#[test]
fn auto_save_on_focus_change_writes_when_the_editor_loses_focus() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.txt", "hello");
app.auto_save = false;
app.auto_save_on_focus_change = true;
app.focus_pane(Pane::Editor);
app.tick_auto_save(); app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
.unwrap();
assert!(app.editor.dirty);
assert!(
!app.tick_auto_save(),
"no focus change yet, and the delay mode is off"
);
assert!(app.editor.dirty, "still dirty while focus has not moved");
app.focus_pane(Pane::Terminal);
assert!(app.tick_auto_save(), "losing focus saves the buffer");
assert!(!app.editor.dirty, "saving clears the dirty flag");
let on_disk = std::fs::read_to_string(tmp.path().join("a.txt")).unwrap();
assert!(
on_disk.contains('x'),
"the edit must be on disk: {on_disk:?}"
);
}
#[test]
fn auto_save_on_focus_change_writes_the_tab_that_lost_focus() {
let tmp = tempfile::tempdir().unwrap();
let a = tmp.path().join("a.txt");
let b = tmp.path().join("b.txt");
std::fs::write(&a, "aaa").unwrap();
std::fs::write(&b, "bbb").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.auto_save = false;
app.auto_save_on_focus_change = true;
app.editor.open_pinned(&a).unwrap();
app.focus_pane(Pane::Editor);
app.tick_auto_save();
app.handle_key(key(KeyCode::Char('Z'), KeyModifiers::NONE))
.unwrap();
assert!(app.editor.dirty, "a.txt is dirty");
app.editor.open_pinned(&b).unwrap();
assert!(app.tick_auto_save(), "the tab that lost focus is saved");
let on_disk = std::fs::read_to_string(&a).unwrap();
assert!(
on_disk.contains('Z'),
"a.txt must be written when it lost focus: {on_disk:?}"
);
}
#[test]
fn focus_changes_do_not_save_when_the_mode_is_off() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.txt", "hello");
app.auto_save = false;
app.auto_save_on_focus_change = false;
app.focus_pane(Pane::Editor);
app.tick_auto_save();
app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
.unwrap();
app.focus_pane(Pane::Terminal);
assert!(!app.tick_auto_save(), "the mode is off");
assert!(app.editor.dirty, "the buffer stays dirty");
}
#[test]
fn auto_save_writes_a_dirty_buffer_after_the_delay() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.txt", "hello");
app.auto_save = true;
app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
.unwrap();
assert!(app.editor.dirty, "typing dirties the buffer");
assert!(
!app.tick_auto_save(),
"a buffer edited a moment ago must not save yet"
);
assert!(app.editor.dirty, "still dirty before the delay elapses");
age_last_edit(&mut app.editor);
assert!(app.tick_auto_save(), "the aged buffer must save");
assert!(!app.editor.dirty, "saving clears the dirty flag");
let on_disk = std::fs::read_to_string(tmp.path().join("a.txt")).unwrap();
assert!(
on_disk.contains('x'),
"the edit must be on disk, got: {on_disk:?}"
);
}
#[test]
fn auto_save_surfaces_a_disk_conflict_instead_of_latching_silently() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.txt", "hello");
app.auto_save = true;
app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
.unwrap();
std::fs::write(tmp.path().join("a.txt"), "external change wins\n").unwrap();
age_last_edit(&mut app.editor);
assert!(
app.tick_auto_save(),
"a conflict-only tick must signal a redraw so the prompt shows now, not on the next blink"
);
assert!(app.editor.disk_conflict, "the conflict latches");
assert!(
app.input_prompt.is_some() || app.status.to_lowercase().contains("conflict"),
"the collision must be surfaced, not swallowed; status: {:?}",
app.status
);
}
#[test]
fn explicit_save_asks_before_a_lossy_encoding_write_and_only_s_consents() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.txt", "plain");
app.editor
.reopen_with_encoding(encoding_rs::WINDOWS_1252)
.unwrap();
app.editor.lines = vec![String::from("日本語 costs 5€")];
app.editor.dirty = true;
app.save();
assert_eq!(
std::fs::read_to_string(tmp.path().join("a.txt")).unwrap(),
"plain",
"the first Cmd+S must refuse, leaving the file untouched"
);
let [what, ..] = app.pending_lossy_save.as_ref().expect("it asks").text();
assert_eq!(what, "windows-1252 cannot represent 日 本 語 in a.txt.");
assert!(
!app.editor.lossy_save_armed,
"nothing is consented to until the prompt is answered"
);
app.handle_key(key(KeyCode::Char('s'), KeyModifiers::NONE))
.unwrap();
assert_eq!(
std::fs::read(tmp.path().join("a.txt")).unwrap(),
b"日本語 costs 5\x80",
"S in the prompt is explicit consent to the lossy write"
);
assert!(!app.editor.dirty, "the consented save completes normally");
assert!(app.pending_lossy_save.is_none());
}
#[test]
fn saving_over_invalid_utf8_asks_in_a_modal_a_second_cmd_s_cannot_answer() {
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("latin1.txt");
std::fs::write(&file, b"caf\xe9 alpha_beta\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&file).unwrap();
app.focus_pane(Pane::Editor);
app.editor.cursor_col = app.editor.lines[0].chars().count();
app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
.unwrap();
let ctrl_s = key(KeyCode::Char('s'), KeyModifiers::CONTROL);
app.handle_key(ctrl_s).unwrap();
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(160, 30)).unwrap();
term.draw(|frame| app.render(frame)).unwrap();
let screen = screen_text(&term);
for part in [
"SAVE WOULD LOSE DATA",
"latin1.txt has bytes that are not valid UTF-8, shown as \u{fffd}.",
"Saving writes \u{fffd} in their place: the original bytes are lost for good.",
"[S] save anyway [Esc] keep the file as it is",
] {
assert!(screen.contains(part), "{part:?} missing:\n{screen}");
}
for answer in [ctrl_s, key(KeyCode::Char('d'), KeyModifiers::NONE)] {
app.handle_key(answer).unwrap();
assert!(app.pending_lossy_save.is_some(), "{answer:?} is no answer");
}
for cancel in [KeyCode::Enter, KeyCode::Esc] {
app.handle_key(key(cancel, KeyModifiers::NONE)).unwrap();
assert!(app.pending_lossy_save.is_none());
assert_eq!(app.status, "Not saved: the file on disk is unchanged");
assert_eq!(std::fs::read(&file).unwrap(), b"caf\xe9 alpha_beta\n");
app.handle_key(ctrl_s).unwrap();
}
app.handle_key(key(KeyCode::Char('S'), KeyModifiers::SHIFT))
.unwrap();
assert_eq!(
std::fs::read(&file).unwrap(),
"caf\u{fffd} alpha_betax\n".as_bytes()
);
}
#[test]
fn the_lossy_prompt_after_a_disk_conflict_answers_for_the_overwrite_too() {
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("a.txt");
let mut app = app_with_open_file(tmp.path(), "a.txt", "plain");
app.editor
.reopen_with_encoding(encoding_rs::WINDOWS_1252)
.unwrap();
app.editor.lines = vec![String::from("æ—¥")];
app.editor.dirty = true;
std::fs::write(&file, "changed elsewhere").unwrap();
for (answer, on_disk) in [
(KeyCode::Esc, &b"changed elsewhere"[..]),
(KeyCode::Char('s'), b"日"),
] {
app.save();
assert!(app.status.contains("changed on disk"), "{}", app.status);
app.save();
assert!(app.pending_lossy_save.is_some(), "{}", app.status);
app.handle_key(key(answer, KeyModifiers::NONE)).unwrap();
assert_eq!(std::fs::read(&file).unwrap(), on_disk, "{}", app.status);
}
}
#[test]
fn the_lossy_prompt_is_read_out_whole() {
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("latin1.txt");
std::fs::write(&file, b"caf\xe9\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&file).unwrap();
app.focus_pane(Pane::Editor);
app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
.unwrap();
app.handle_key(key(KeyCode::Char('s'), KeyModifiers::CONTROL))
.unwrap();
let snap = app.a11y_snapshot();
assert_eq!(snap.focus, "Save would lose data");
assert_eq!(
snap.item.as_deref(),
Some(
"latin1.txt has invalid UTF-8 bytes. Saving turns them into \u{fffd} for good. \
To keep them, undo, then Reopen with Encoding. S, save anyway. Escape, cancel"
)
);
}
#[test]
fn the_lossy_prompt_answers_before_an_unsaved_prompt_beneath_it() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.txt", "plain");
app.editor
.reopen_with_encoding(encoding_rs::WINDOWS_1252)
.unwrap();
app.editor.lines = vec![String::from("æ—¥")];
app.editor.dirty = true;
app.pending_unsaved = Some(UnsavedExit::Quit);
app.save();
app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
.unwrap();
assert!(app.pending_lossy_save.is_none(), "Esc answered the top one");
assert_eq!(app.pending_unsaved, Some(UnsavedExit::Quit));
assert_eq!(app.a11y_snapshot().focus, "Unsaved changes");
}
#[cfg(unix)]
fn app_with_protected_file(tmp: &std::path::Path, body: &str) -> (App, PathBuf) {
use std::os::unix::fs::PermissionsExt as _;
let f = tmp.join("nginx.conf");
std::fs::write(&f, body).unwrap();
std::fs::set_permissions(&f, std::fs::Permissions::from_mode(0o444)).unwrap();
let mut app = App::new(tmp.to_path_buf()).unwrap();
app.editor.open_pinned(&f).unwrap();
app.focus_pane(Pane::Editor);
(app, f)
}
#[cfg(unix)]
fn file_mode(path: &std::path::Path) -> u32 {
use std::os::unix::fs::PermissionsExt as _;
std::fs::metadata(path).unwrap().permissions().mode() & 0o777
}
#[cfg(unix)]
#[test]
fn a_write_protected_file_shows_a_lock_and_read_only_before_any_edit() {
let tmp = tempfile::tempdir().unwrap();
let (mut app, _) = app_with_protected_file(tmp.path(), "listen 80;\n");
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(140, 30)).unwrap();
term.draw(|frame| app.render(frame)).unwrap();
let screen = screen_text(&term);
assert!(screen.contains("nginx.conf \u{f023}"), "{screen}");
assert!(screen.contains("Read-only"), "{screen}");
}
#[cfg(unix)]
#[test]
fn a_writable_file_shows_no_lock_and_saves_on_the_first_press() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "site.conf", "a\n");
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(140, 30)).unwrap();
term.draw(|frame| app.render(frame)).unwrap();
let screen = screen_text(&term);
assert!(!screen.contains('\u{f023}'), "{screen}");
assert!(!screen.contains("Read-only"), "{screen}");
app.editor.insert_char('b');
app.save();
assert_eq!(
std::fs::read_to_string(tmp.path().join("site.conf")).unwrap(),
"ba\n"
);
assert!(!app.editor.dirty);
assert_eq!(app.sudo_save_armed, None);
}
#[cfg(unix)]
#[test]
fn saving_a_write_protected_file_asks_then_overwrites_it_and_keeps_it_protected() {
let tmp = tempfile::tempdir().unwrap();
let (mut app, f) = app_with_protected_file(tmp.path(), "listen 80;\n");
app.editor.insert_char('#');
app.save();
assert_eq!(std::fs::read_to_string(&f).unwrap(), "listen 80;\n");
assert!(app.editor.dirty);
assert!(
app.status.contains("write-protected") && app.status.contains("Cmd+S again"),
"{}",
app.status
);
app.save();
assert_eq!(std::fs::read_to_string(&f).unwrap(), "#listen 80;\n");
assert_eq!(file_mode(&f), 0o444, "its permissions are put back");
assert!(!app.editor.dirty);
}
#[cfg(unix)]
#[test]
fn auto_save_never_writes_a_write_protected_file() {
let tmp = tempfile::tempdir().unwrap();
let (mut app, f) = app_with_protected_file(tmp.path(), "listen 80;\n");
app.auto_save = true;
app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
.unwrap();
age_last_edit(&mut app.editor);
app.tick_auto_save();
assert_eq!(std::fs::read_to_string(&f).unwrap(), "listen 80;\n");
assert!(app.editor.dirty);
assert!(
!app.editor.overwrite_protected_armed,
"only an explicit save may consent"
);
}
#[test]
fn a_save_refused_for_permission_offers_sudo_and_the_next_press_stages_it() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "hosts", "127.0.0.1 localhost\n");
let f = tmp.path().join("hosts");
app.editor.insert_char('#');
app.report_save_error(anyhow::Error::from(std::io::Error::from(
std::io::ErrorKind::PermissionDenied,
)));
assert!(
app.status.contains("Cmd+S again to save it with sudo"),
"{}",
app.status
);
assert_eq!(app.sudo_save_armed.as_ref(), Some(&f));
let panes = app.terminals.len();
app.save();
assert_eq!(app.terminals.len(), panes + 1, "sudo runs in its own pane");
assert_eq!(app.terminal().label(), "sudo save");
assert!(
app.focus == Pane::Terminal,
"sudo's password prompt has the keys"
);
let pending: Vec<_> = app
.pending_sudo_saves
.iter()
.map(|(p, bytes, _)| (p.clone(), bytes.clone()))
.collect();
assert_eq!(
pending,
vec![(f.clone(), b"#127.0.0.1 localhost\n".to_vec())]
);
assert!(
app.editor.dirty,
"nothing is saved until tee has written it"
);
assert_eq!(
std::fs::read_to_string(&f).unwrap(),
"127.0.0.1 localhost\n"
);
std::fs::write(&f, b"#127.0.0.1 localhost\n").unwrap();
assert!(app.reload_open_file_after_external_change());
assert!(!app.editor.dirty);
assert!(!app.editor.disk_conflict);
assert!(app.pending_sudo_saves.is_empty());
assert_eq!(app.status, "Saved hosts with sudo");
}
#[test]
fn a_sudo_save_waits_while_the_file_holds_anything_else() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "hosts", "a\n");
let f = tmp.path().join("hosts");
app.editor.insert_char('b');
app.run_command(crate::widgets::command_palette::Command::SaveWithSudo);
assert_eq!(app.pending_sudo_saves.len(), 1);
std::fs::write(&f, "someone else\n").unwrap();
app.reload_open_file_after_external_change();
assert!(app.editor.dirty, "another write is not this save");
assert_eq!(app.pending_sudo_saves.len(), 1, "still waiting on tee");
}
#[test]
fn a_sudo_save_over_an_external_change_asks_first() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "hosts", "a\n");
let f = tmp.path().join("hosts");
app.editor.insert_char('b');
std::fs::write(&f, "someone else's longer line\n").unwrap();
let panes = app.terminals.len();
app.run_command(crate::widgets::command_palette::Command::SaveWithSudo);
assert_eq!(app.terminals.len(), panes, "nothing staged yet");
assert!(app.pending_sudo_saves.is_empty());
assert!(app.editor.disk_conflict);
assert!(
app.status.contains("changed on disk") && app.status.contains("Cmd+S again"),
"{}",
app.status
);
app.save();
assert_eq!(
app.terminals.len(),
panes + 1,
"the second press overwrites"
);
assert_eq!(app.pending_sudo_saves.len(), 1);
}
#[test]
fn a_second_sudo_save_waits_for_the_first_ones_terminal() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "hosts", "a\n");
app.editor.insert_char('b');
app.run_command(crate::widgets::command_palette::Command::SaveWithSudo);
let panes = app.terminals.len();
let first = app.pending_sudo_saves.clone();
assert_eq!(first.len(), 1);
app.focus_pane(Pane::Editor);
app.editor.insert_char('c');
app.run_command(crate::widgets::command_palette::Command::SaveWithSudo);
assert_eq!(app.terminals.len(), panes, "no second sudo prompt");
assert_eq!(app.pending_sudo_saves, first);
assert!(app.status.contains("still waiting"), "{}", app.status);
let pane = first[0].2;
let idx = app
.terminals
.iter()
.position(|t| t.shell_pid() == pane)
.unwrap();
app.close_terminal_at(idx);
app.run_command(crate::widgets::command_palette::Command::SaveWithSudo);
assert_eq!(app.pending_sudo_saves.len(), 1);
assert_eq!(app.pending_sudo_saves[0].1, b"bca\n".to_vec());
}
#[test]
fn a_finished_sudo_save_runs_the_usual_save_follow_ups() {
let tmp = tempfile::tempdir().unwrap();
let hist = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "hosts", "a\n");
app.history_root = hist.path().to_path_buf();
let f = tmp.path().join("hosts");
app.editor.insert_char('b');
app.run_command(crate::widgets::command_palette::Command::SaveWithSudo);
std::fs::write(&f, "ba\n").unwrap();
assert!(app.reload_open_file_after_external_change());
let snaps = wait_for_snapshots(&app.history_root, &f);
assert_eq!(snaps.len(), 1, "a sudo save records a snapshot");
assert_eq!(std::fs::read_to_string(&snaps[0].file).unwrap(), "ba\n");
}
#[test]
fn a_save_that_fails_for_another_reason_offers_no_sudo() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.txt", "a\n");
app.editor.insert_char('b');
app.report_save_error(anyhow::Error::from(std::io::Error::from(
std::io::ErrorKind::StorageFull,
)));
assert!(app.status.starts_with("Save failed: "), "{}", app.status);
assert!(!app.status.contains("sudo"), "{}", app.status);
assert_eq!(app.sudo_save_armed, None);
let panes = app.terminals.len();
app.save();
assert_eq!(app.terminals.len(), panes, "a plain save, no terminal");
assert!(!app.editor.dirty);
}
#[test]
fn save_with_sudo_needs_a_file_on_disk() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.insert_char('a');
let panes = app.terminals.len();
app.run_command(crate::widgets::command_palette::Command::SaveWithSudo);
assert_eq!(app.terminals.len(), panes);
assert!(app.pending_sudo_saves.is_empty());
assert!(app.status.contains("Save As"), "{}", app.status);
}
#[test]
fn the_sudo_save_command_quotes_both_paths() {
assert_eq!(
sudo_save_command("/etc/it's here.conf", "/tmp/croft-sudo-save-1"),
"sudo tee -- '/etc/it'\\''s here.conf' < '/tmp/croft-sudo-save-1' > /dev/null; rm -f -- '/tmp/croft-sudo-save-1'"
);
}
#[cfg(unix)]
#[test]
fn a_sudo_save_is_staged_where_only_this_user_can_read_it() {
let staged = stage_sudo_save(b"secret\n").unwrap();
assert_eq!(std::fs::read(&staged).unwrap(), b"secret\n");
assert_eq!(file_mode(&staged), 0o600);
std::fs::remove_file(&staged).unwrap();
}
#[test]
fn auto_save_surfaces_an_encoding_refusal_instead_of_latching_silently() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.txt", "plain");
app.auto_save = true;
app.editor
.reopen_with_encoding(encoding_rs::WINDOWS_1252)
.unwrap();
app.editor.lines = vec![String::from("日本語")];
app.editor.dirty = true;
age_last_edit(&mut app.editor);
assert!(
app.tick_auto_save(),
"a refusal-only tick must signal a redraw so the message shows now"
);
assert_eq!(
std::fs::read_to_string(tmp.path().join("a.txt")).unwrap(),
"plain",
"auto save must never write the substituted bytes"
);
assert!(app.editor.encoding_loss, "the refusal latches");
assert!(
!app.editor.lossy_save_armed,
"auto save must never consent to the lossy write on the user's behalf"
);
assert!(
app.status.contains("a.txt") && app.status.contains("windows-1252"),
"the stall must be surfaced with the tab and its encoding; status: {:?}",
app.status
);
assert!(
!app.tick_auto_save(),
"the latch keeps later ticks quiet instead of re-refusing every second"
);
}
#[test]
fn auto_save_stays_off_by_default() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.txt", "hello");
assert!(!app.auto_save, "auto save defaults off, like VS Code");
app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
.unwrap();
age_last_edit(&mut app.editor);
assert!(!app.tick_auto_save());
assert!(app.editor.dirty, "nothing saves while the pref is off");
}
fn app_with_trailing_spaces_typed() -> (App, tempfile::TempDir) {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(
tmp.path().join(".editorconfig"),
"root = true\n[*]\ntrim_trailing_whitespace = true\n",
)
.unwrap();
let mut app = app_with_open_file(tmp.path(), "app.txt", "def f():\n return 1\n");
app.handle_key(key(KeyCode::End, KeyModifiers::NONE))
.unwrap();
type_keys(&mut app, " # TODO ");
(app, tmp)
}
#[test]
fn an_explicit_save_trims_the_line_just_edited() {
let (mut app, tmp) = app_with_trailing_spaces_typed();
app.save();
assert_eq!(
std::fs::read_to_string(tmp.path().join("app.txt")).unwrap(),
"def f(): # TODO\n return 1\n"
);
assert!(!app.editor.dirty);
}
#[test]
fn an_auto_save_spares_the_line_being_typed() {
let (mut app, tmp) = app_with_trailing_spaces_typed();
app.auto_save = true;
age_last_edit(&mut app.editor);
assert!(app.tick_auto_save());
assert_eq!(
std::fs::read_to_string(tmp.path().join("app.txt")).unwrap(),
"def f(): # TODO \n return 1\n"
);
}
#[test]
fn auto_save_never_overwrites_an_external_disk_change() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.txt", "hello");
app.auto_save = true;
app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
.unwrap();
std::fs::write(tmp.path().join("a.txt"), "external edit").unwrap();
age_last_edit(&mut app.editor);
app.tick_auto_save();
let on_disk = std::fs::read_to_string(tmp.path().join("a.txt")).unwrap();
assert_eq!(
on_disk, "external edit",
"auto save must refuse the write and keep the external content"
);
}
#[test]
fn auto_save_sweeps_dirty_background_tabs() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.txt", "first");
app.auto_save = true;
app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
.unwrap();
let b = tmp.path().join("b.txt");
std::fs::write(&b, "second").unwrap();
app.editor.open_pinned(&b).unwrap();
for e in app.editor.editors.iter_mut() {
age_last_edit(e);
}
assert!(app.tick_auto_save(), "the background tab must save");
let on_disk = std::fs::read_to_string(tmp.path().join("a.txt")).unwrap();
assert!(
on_disk.contains('x'),
"the background tab's edit must be on disk, got: {on_disk:?}"
);
}
#[test]
fn toggle_auto_save_command_flips_the_pref_and_reports_it() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.txt", "hello");
app.run_command(crate::widgets::command_palette::Command::ToggleAutoSave);
assert!(app.auto_save);
assert_eq!(app.status, "Auto Save: on");
app.run_command(crate::widgets::command_palette::Command::ToggleAutoSave);
assert!(!app.auto_save);
assert_eq!(app.status, "Auto Save: off");
}
#[test]
fn a_file_name_with_a_line_still_opens_that_file_at_the_line() {
let tmp = tempfile::tempdir().unwrap();
let body: String = (1..=50).map(|i| format!("y = {i}\n")).collect();
std::fs::write(tmp.path().join("b.py"), body).unwrap();
let mut app = app_with_open_file(tmp.path(), "a.py", "x = 1\n");
quick_open_typing(&mut app, "b@>");
assert!(
app.file_finder.is_some(),
"a later @ or > is part of the name"
);
assert!(app.command_palette.is_none() && app.go_to_symbol.is_none());
app.file_finder = None;
quick_open_typing(&mut app, "b.py:12");
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
assert_eq!(
app.editor.path.as_deref(),
Some(tmp.path().join("b.py").as_path())
);
assert_eq!(app.editor.cursor_row, 11);
}
#[cfg(unix)]
#[test]
fn write_private_refuses_a_symlinked_dir_and_tightens_a_loose_one() {
use std::os::unix::fs::PermissionsExt;
let tmp = tempfile::tempdir().unwrap();
let loose = tmp.path().join("loose");
std::fs::create_dir(&loose).unwrap();
std::fs::set_permissions(&loose, std::fs::Permissions::from_mode(0o755)).unwrap();
let stale = loose.join("old.log");
std::fs::write(&stale, "old").unwrap();
std::fs::set_permissions(&stale, std::fs::Permissions::from_mode(0o644)).unwrap();
write_private(&loose, &stale, "new").expect("a real dir is written");
let mode = |p: &Path| std::fs::metadata(p).unwrap().permissions().mode() & 0o777;
assert_eq!(
mode(&loose),
0o700,
"a loose dir from an older run is tightened"
);
assert_eq!(mode(&stale), 0o600, "and so is a stale dump file");
assert_eq!(std::fs::read_to_string(&stale).unwrap(), "new");
let target = tmp.path().join("target");
std::fs::create_dir(&target).unwrap();
std::fs::set_permissions(&target, std::fs::Permissions::from_mode(0o755)).unwrap();
let link = tmp.path().join("link");
std::os::unix::fs::symlink(&target, &link).unwrap();
let outcome = write_private(&link, &link.join("x.log"), "x");
assert!(
outcome.is_err(),
"a symlinked dir is refused, not written through"
);
assert_eq!(mode(&target), 0o755, "the link's target keeps its mode");
assert!(!target.join("x.log").exists(), "and gains no file");
let outside = tmp.path().join("outside.txt");
std::fs::write(&outside, "secret").unwrap();
std::fs::set_permissions(&outside, std::fs::Permissions::from_mode(0o644)).unwrap();
let planted = loose.join("planted.log");
std::os::unix::fs::symlink(&outside, &planted).unwrap();
let outcome = write_private(&loose, &planted, "new");
assert!(outcome.is_err(), "a symlinked dump file is refused");
assert_eq!(
std::fs::read_to_string(&outside).unwrap(),
"secret",
"its target is untouched"
);
assert_eq!(mode(&outside), 0o644, "and keeps its mode");
}
#[test]
fn a_symlinked_wire_file_key_cannot_escape_the_workspace() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("workspace");
std::fs::create_dir(&root).unwrap();
std::fs::write(tmp.path().join("secret.txt"), "SECRET").unwrap();
std::fs::write(root.join("inner.txt"), "inner").unwrap();
std::os::unix::fs::symlink(tmp.path().join("secret.txt"), root.join("leak.txt")).unwrap();
std::fs::create_dir(tmp.path().join("outside")).unwrap();
std::fs::write(tmp.path().join("outside").join("deep.txt"), "DEEP").unwrap();
std::os::unix::fs::symlink(tmp.path().join("outside"), root.join("sub")).unwrap();
std::os::unix::fs::symlink(root.join("inner.txt"), root.join("alias.txt")).unwrap();
let mut app = App::new(root.clone()).unwrap();
assert_eq!(
app.owner_buffer_text(&root, "leak.txt"),
None,
"a symlink to a file outside the workspace must be declined"
);
assert_eq!(
app.owner_buffer_text(&root, "sub/deep.txt"),
None,
"a path through a symlinked directory must not escape the workspace"
);
assert_eq!(
app.owner_buffer_text(&root, "alias.txt").as_deref(),
Some("inner"),
"a symlink resolving inside the workspace still works"
);
}
#[test]
fn cmd_k_y_yields_the_active_file_and_commentary_reaches_output() {
use std::time::{Duration, Instant};
if !crate::lsp::manager::is_on_path("python3") {
eprintln!("SKIPPED: python3 not on PATH");
return;
}
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("f.txt");
std::fs::write(&file, "a\nb\nc").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 script = tmp.path().join("fake_claude.py");
std::fs::write(&script, crate::pair::FAKE_CLAUDE).unwrap();
let log = tmp.path().join("stdin.log");
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.open_file_at_launch(&file);
assert!(app.handle_cmd_k_chord(key(KeyCode::Char('y'), KeyModifiers::NONE)));
assert!(
app.status.to_lowercase().contains("not active"),
"got: {}",
app.status
);
let mut cmd = std::process::Command::new("python3");
cmd.arg(&script).arg(&log).arg("notes");
app.pair.host =
Some(crate::pair_host::PairHost::spawn_cmd(&socket, "navigator", None, cmd).unwrap());
assert!(app.handle_cmd_k_chord(key(KeyCode::Char('y'), KeyModifiers::NONE)));
assert!(
app.status.to_lowercase().contains("yielded"),
"got: {}",
app.status
);
let deadline = Instant::now() + Duration::from_secs(10);
loop {
let sent = std::fs::read_to_string(&log).unwrap_or_default();
if sent.contains("COMMENT-ONLY") && sent.contains("0|a") {
break;
}
assert!(
Instant::now() < deadline,
"yield turn never reached claude; log: {sent}"
);
std::thread::sleep(Duration::from_millis(10));
}
let baseline = crate::output::snapshot("Navigator")
.unwrap_or_default()
.len();
let deadline = Instant::now() + Duration::from_secs(10);
loop {
app.poll_pair();
let lines = crate::output::snapshot("Navigator").unwrap_or_default();
if lines
.iter()
.skip(baseline)
.any(|l| l.text.contains("Reviewing."))
{
break;
}
assert!(
Instant::now() < deadline,
"commentary never reached OUTPUT; got {lines:?}"
);
std::thread::sleep(Duration::from_millis(10));
}
}
#[test]
fn a_failed_external_reload_reports_in_the_status_line() {
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("f.txt");
std::fs::write(&f, "one\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&f).unwrap();
std::fs::remove_file(&f).unwrap();
std::fs::create_dir(&f).unwrap();
assert!(
app.reload_open_file_after_external_change(),
"a failed reload is redraw-worthy, not an empty sweep"
);
assert!(
app.status.contains("Reload failed"),
"the status line must name the failure; got: {}",
app.status
);
assert_eq!(
app.editor.lines[0], "one",
"the last good buffer survives the failed reload"
);
app.status = String::from("Saved g.txt");
assert!(!app.reload_open_file_after_external_change());
assert_eq!(app.status, "Saved g.txt");
}
#[test]
fn a_deletion_and_a_failed_reload_in_one_sweep_are_both_reported() {
let tmp = tempfile::tempdir().unwrap();
let gone = tmp.path().join("gone.txt");
let bad = tmp.path().join("bad.txt");
std::fs::write(&gone, "a\n").unwrap();
std::fs::write(&bad, "b\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&gone).unwrap();
app.editor.open_pinned(&bad).unwrap();
std::fs::remove_file(&gone).unwrap();
std::fs::remove_file(&bad).unwrap();
std::fs::create_dir(&bad).unwrap();
assert!(app.reload_open_file_after_external_change());
assert_eq!(
app.status,
"gone.txt was deleted on disk; save to recreate it; \
reload failed for bad.txt, keeping its last good view"
);
}
#[test]
fn a_file_deleted_on_disk_is_reported_once_and_one_save_recreates_it() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "notes.txt", "alpha\n");
let f = tmp.path().join("notes.txt");
app.editor.insert_char('x');
std::fs::remove_file(&f).unwrap();
assert!(app.reload_open_file_after_external_change());
assert_eq!(
app.status,
"notes.txt was deleted on disk; save to recreate it"
);
assert!(app.input_prompt.is_none(), "nothing to reload: no modal");
app.status = String::from("Deleted 1 line");
assert!(!app.reload_open_file_after_external_change());
assert_eq!(app.status, "Deleted 1 line", "a later status stays visible");
app.save();
assert_eq!(std::fs::read_to_string(&f).unwrap(), "xalpha\n");
assert!(!app.editor.dirty);
assert!(app.status.starts_with("Saved"), "{}", app.status);
}
#[test]
fn create_prompt_labels_speak_workspace_relative() {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir(tmp.path().join("src")).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.open_create_prompt(CreateKind::File, tmp.path().join("src"));
let label = app.prompt.as_ref().unwrap().label.clone();
assert_eq!(
label, "New File in src",
"the prompt title's one job is naming the target directory; a deep \
absolute workspace path truncates it out of the popup (#105)"
);
app.prompt = None;
app.open_create_prompt(CreateKind::Folder, tmp.path().to_path_buf());
let label = app.prompt.as_ref().unwrap().label.clone();
assert_eq!(
label, "New Folder in .",
"the workspace root itself reads as '.'"
);
}
#[test]
fn save_workspace_as_replaces_the_suggested_path_with_what_is_typed() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.run_command(crate::widgets::command_palette::Command::SaveWorkspaceAs);
for c in "team.code-workspace".chars() {
app.handle_key(key(KeyCode::Char(c), KeyModifiers::NONE))
.unwrap();
}
assert_eq!(
app.input_prompt.as_ref().unwrap().value,
"team.code-workspace"
);
}
#[test]
fn prompt_chords_clear_the_value_and_a_paste_replaces_it() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.run_command(crate::widgets::command_palette::Command::SaveWorkspaceAs);
app.handle_key(key(KeyCode::End, KeyModifiers::NONE))
.unwrap();
app.handle_key(key(KeyCode::Backspace, KeyModifiers::ALT))
.unwrap();
let v = app.input_prompt.as_ref().unwrap().value.clone();
assert!(v.ends_with('/') || v.ends_with('\\'), "{v}");
app.handle_key(key(KeyCode::Char('w'), KeyModifiers::CONTROL))
.unwrap();
assert!(app.input_prompt.as_ref().unwrap().value.len() < v.len());
app.handle_key(key(KeyCode::Char('u'), KeyModifiers::CONTROL))
.unwrap();
assert_eq!(app.input_prompt.as_ref().unwrap().value, "");
app.handle_paste("/tmp/x.code-workspace");
app.handle_key(key(KeyCode::Char('a'), KeyModifiers::CONTROL))
.unwrap();
app.handle_paste("/tmp/y.code-workspace");
assert_eq!(
app.input_prompt.as_ref().unwrap().value,
"/tmp/y.code-workspace"
);
}
#[test]
fn prompt_chords_leave_the_editor_alone() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.txt", "alpha beta");
app.run_command(crate::widgets::command_palette::Command::SaveWorkspaceAs);
for (c, m) in [('a', KeyModifiers::CONTROL), ('u', KeyModifiers::CONTROL)] {
app.handle_key(key(KeyCode::Char(c), m)).unwrap();
}
assert_eq!(app.editor.lines, vec!["alpha beta"]);
assert!(app.editor.selection.is_none_or(|s| !s.has_area()));
}
#[test]
fn the_sweep_auto_enables_only_under_the_file_threshold() {
let tmp = tempfile::tempdir().unwrap();
for i in 0..12 {
std::fs::write(tmp.path().join(format!("f{i}.ts")), "export const x = 1;\n").unwrap();
}
assert!(
!App::workspace_exceeds(tmp.path(), 100),
"12 files is under a cap of 100"
);
assert!(
!App::workspace_exceeds(tmp.path(), 12),
"exactly 12 files does not exceed a cap of 12"
);
assert!(
App::workspace_exceeds(tmp.path(), 11),
"12 files exceeds a cap of 11"
);
assert!(
App::project_check_auto_enabled(tmp.path(), "auto", 100),
"auto enables under the cap"
);
assert!(
App::workspace_exceeds(tmp.path(), 5),
"12 files exceeds a cap of 5"
);
assert!(
!App::project_check_auto_enabled(tmp.path(), "auto", 5),
"auto declines over the cap"
);
assert!(
App::project_check_auto_enabled(tmp.path(), "on", 5),
"`on` runs on a root the cap would have declined"
);
assert!(
!App::project_check_auto_enabled(tmp.path(), "off", 100),
"`off` declines a root the cap would have allowed"
);
assert!(
!App::project_check_auto_enabled(tmp.path(), "definitely-not-a-mode", 5),
"an unknown setting falls back to auto, which declines here"
);
assert!(
App::project_check_auto_enabled(tmp.path(), "definitely-not-a-mode", 100),
"and to auto's yes under the cap, not a blanket no"
);
}
#[test]
fn the_size_hint_fires_once_and_only_under_auto() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.problems_project_scope = String::from("on");
assert!(
App::project_check_auto_enabled(tmp.path(), &app.problems_project_scope, 0),
"`on` runs even against a zero-file cap"
);
app.problems_project_scope = String::from("off");
assert!(!App::project_check_auto_enabled(
tmp.path(),
&app.problems_project_scope,
usize::MAX
));
std::fs::write(tmp.path().join("a.ts"), "export const a = 1;\n").unwrap();
app.problems_project_scope = String::from("auto");
assert!(
!App::project_check_auto_enabled(tmp.path(), "auto", 0),
"auto declines when the root exceeds the cap"
);
assert!(
App::project_check_auto_enabled(tmp.path(), "auto", usize::MAX),
"and enables under it - the paired case, so the line above cannot \
pass by the predicate always saying no"
);
assert_eq!(App::project_scope_mode(" Off "), "off");
assert_eq!(App::project_scope_mode("ON"), "on");
assert_eq!(App::project_scope_mode("always"), "on");
assert_eq!(App::project_scope_mode("never"), "off");
assert_eq!(
App::project_scope_mode("wat"),
"auto",
"an unknown value is auto, never on"
);
assert!(
!App::project_check_auto_enabled(tmp.path(), " Off ", usize::MAX),
"a padded, capitalised off is honoured rather than read as auto"
);
}
#[test]
fn the_threshold_check_stops_counting_at_the_limit() {
let tmp = tempfile::tempdir().unwrap();
for d in 0..10 {
let dir = tmp.path().join(format!("d{d}"));
std::fs::create_dir_all(&dir).unwrap();
for i in 0..50 {
std::fs::write(dir.join(format!("f{i}.ts")), "x\n").unwrap();
}
}
assert!(App::workspace_exceeds(tmp.path(), 3), "500 files exceeds 3");
let clean = tempfile::tempdir().unwrap();
let heavy = clean.path().join("node_modules").join("pkg");
std::fs::create_dir_all(&heavy).unwrap();
for i in 0..200 {
std::fs::write(heavy.join(format!("m{i}.js")), "x\n").unwrap();
}
std::fs::write(clean.path().join("a.ts"), "export const a = 1;\n").unwrap();
assert!(
!App::workspace_exceeds(clean.path(), 10),
"node_modules is not the user's code and must not trip the cap"
);
}
fn move_calc_to_sums(app: &App, file: &Path) -> PendingFileMove {
let root = app.tree.root.clone();
PendingFileMove {
request_id: 9,
op: FileMove::Rename {
parent: root.clone(),
old: file.to_path_buf(),
new_name: String::from("sums.srn"),
},
renames: vec![crate::lsp::manager::FileRenameOp {
old: file.to_path_buf(),
new: root.join("sums.srn"),
is_dir: false,
}],
deadline: std::time::Instant::now(),
baseline: app.editor.edit_seqs(),
}
}
#[test]
fn a_file_move_moves_but_leaves_a_buffer_typed_into_since_the_request_alone() {
let tmp = tempfile::tempdir().unwrap();
let (mut app, file) = app_with_calc_open(&tmp);
let pending = move_calc_to_sums(&app, &file);
type_a_header_line(&mut app);
app.finish_file_move(pending, rename_total_to_sum(&file));
assert!(
app.tree.root.join("sums.srn").exists(),
"the move still ran"
);
assert_eq!(
app.editor.lines.join("\n"),
"# header\ntotal = 1\nprint(total)\ntotal += 2"
);
assert!(
app.status
.ends_with("; references not updated: sums.srn changed while the server was working"),
"{}",
app.status
);
}
#[test]
fn a_file_move_still_updates_an_untouched_buffer_it_moved() {
let tmp = tempfile::tempdir().unwrap();
let (mut app, file) = app_with_calc_open(&tmp);
let pending = move_calc_to_sums(&app, &file);
app.finish_file_move(pending, rename_total_to_sum(&file));
assert_eq!(
app.editor.path.as_deref(),
Some(app.tree.root.join("sums.srn").as_path())
);
assert_eq!(app.editor.lines.join("\n"), "sum = 1\nprint(sum)\nsum += 2");
assert!(
app.status.contains("references updated in 1 file"),
"{}",
app.status
);
}
#[test]
fn auto_save_writes_a_file_with_a_symbol_tab_once_and_cleans_both() {
let tmp = tempfile::tempdir().unwrap();
let (mut app, file) = app_with_symbol_tab_on_b(&tmp);
app.auto_save = true;
app.sync_symbol_views();
app.editor.cursor_row = 4;
app.editor.cursor_col = 5;
app.handle_key(key(KeyCode::Char('7'), KeyModifiers::NONE))
.unwrap();
app.sync_symbol_views();
let past = std::time::Instant::now() - std::time::Duration::from_secs(5);
for e in app.editor.editors.iter_mut() {
assert!(e.dirty, "fixture: both tabs hold the edit");
e.last_edit_at = Some(past);
}
assert!(app.tick_auto_save());
assert_eq!(
std::fs::read_to_string(&file).unwrap(),
"fn a() {\n 1\n}\nfn b() {\n 27\n}"
);
for e in &app.editor.editors {
assert!(!e.dirty && !e.disk_conflict, "both tabs are saved");
}
assert!(app.input_prompt.is_none(), "no conflict prompt");
assert!(!app.reload_open_file_after_external_change());
}
#[test]
fn auto_save_reports_a_symbol_tabs_file_conflict_once() {
use crate::widgets::input_prompt::InputPurpose;
let tmp = tempfile::tempdir().unwrap();
let (mut app, file) = app_with_symbol_tab_on_b(&tmp);
app.auto_save = true;
app.sync_symbol_views();
app.editor.cursor_row = 4;
app.editor.cursor_col = 5;
app.handle_key(key(KeyCode::Char('7'), KeyModifiers::NONE))
.unwrap();
app.sync_symbol_views();
std::fs::write(
&file,
"fn a() {\n 1\n}\nfn b() {\n changed elsewhere\n}",
)
.unwrap();
let past = std::time::Instant::now() - std::time::Duration::from_secs(5);
for e in app.editor.editors.iter_mut() {
e.last_edit_at = Some(past);
}
assert!(app.tick_auto_save());
assert!(
app.editor.editors.iter().all(|e| e.disk_conflict),
"both tabs latch the conflict"
);
match app.input_prompt.as_ref().map(|p| &p.purpose) {
Some(InputPurpose::ReloadConflict { paths }) => assert_eq!(paths, &vec![file]),
_ => panic!("a conflict prompt"),
}
}
#[test]
fn auto_save_names_a_symbol_tabs_file_once_when_its_encoding_refuses() {
let tmp = tempfile::tempdir().unwrap();
let (mut app, _file) = app_with_symbol_tab_on_b(&tmp);
app.auto_save = true;
app.sync_symbol_views();
let past = std::time::Instant::now() - std::time::Duration::from_secs(5);
for e in app.editor.editors.iter_mut() {
e.encoding = encoding_rs::WINDOWS_1252;
e.lines[4] = String::from(" \u{65e5}\u{672c}");
e.dirty = true;
e.last_edit_at = Some(past);
}
assert!(app.tick_auto_save());
assert!(app.editor.editors.iter().all(|e| e.encoding_loss));
assert_eq!(app.status.matches("two.rs").count(), 1, "{}", app.status);
}
#[test]
fn the_watcher_reports_rescans_and_keeps_directories_out_of_the_ledger() {
use notify::Event as NotifyEvent;
use notify::event::{EventKind, ModifyKind, RemoveKind};
use notify_debouncer_full::DebouncedEvent;
use std::sync::mpsc;
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("touched.rs");
std::fs::write(&file, "fn a() {}\n").unwrap();
let doomed_dir = tmp.path().join("subdir");
std::fs::create_dir(&doomed_dir).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.terminals[0].set_agent(Some(crate::agents::AgentLane {
name: String::from("claude"),
status: crate::agents::AgentStatus::Working,
}));
let (tx, rx) = mpsc::channel();
app.fs_watch.set_test_events(rx);
let mut dir_gone = NotifyEvent::new(EventKind::Remove(RemoveKind::Folder));
dir_gone = dir_gone.add_path(doomed_dir.clone());
let mut written = NotifyEvent::new(EventKind::Modify(ModifyKind::Any));
written = written.add_path(file.clone());
let now = std::time::Instant::now();
tx.send(Ok(vec![
DebouncedEvent::new(dir_gone, now),
DebouncedEvent::new(written, now),
]))
.unwrap();
app.drain_fs_events();
assert!(
app.agent_ledger.is_unreviewed(&file),
"the written file is attributed to the working agent"
);
assert!(
!app.agent_ledger.is_unreviewed(&doomed_dir),
"a removed DIRECTORY must not enter a file-only ledger"
);
assert!(
!app.agent_ledger.may_be_incomplete(),
"no rescan yet, so the queue is not a lower bound"
);
let doomed = tmp.path().join("doomed.rs");
std::fs::write(&doomed, "fn gone() {}\n").unwrap();
let mut doomed_set = std::collections::BTreeSet::new();
doomed_set.insert(doomed.clone());
assert!(app.attribute_writes_to_working_agents(&doomed_set));
assert!(app.agent_ledger.is_unreviewed(&doomed));
std::fs::remove_file(&doomed).unwrap();
let (tx3, rx3) = mpsc::channel();
app.fs_watch.set_test_events(rx3);
let removed = NotifyEvent::new(EventKind::Remove(RemoveKind::Any)).add_path(doomed.clone());
tx3.send(Ok(vec![DebouncedEvent::new(
removed,
std::time::Instant::now(),
)]))
.unwrap();
app.drain_fs_events();
assert!(
!app.agent_ledger.is_unreviewed(&doomed),
"the removed file's row leaves the queue rather than stranding"
);
let (tx2, rx2) = mpsc::channel();
app.fs_watch.set_test_events(rx2);
let rescan = NotifyEvent::new(EventKind::Modify(ModifyKind::Any))
.add_path(file.clone())
.set_flag(notify::event::Flag::Rescan);
tx2.send(Ok(vec![DebouncedEvent::new(
rescan,
std::time::Instant::now(),
)]))
.unwrap();
app.drain_fs_events();
assert!(
app.agent_ledger.may_be_incomplete(),
"a rescan makes every count a lower bound, durably"
);
app.status = String::from("something else entirely");
assert!(app.agent_ledger.may_be_incomplete());
}
#[test]
fn an_overlay_past_the_screen_edge_is_refused_before_it_is_written() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let backend = ratatui::backend::TestBackend::new(80, 24);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
assert!(
app.overlay_fits_on_screen(0, 0, 80, 24),
"a payload filling the screen exactly must be allowed"
);
assert!(app.overlay_fits_on_screen(10, 5, 20, 10), "well inside");
assert!(
!app.overlay_fits_on_screen(70, 0, 20, 5),
"past the right edge (70+20 > 80)"
);
assert!(
!app.overlay_fits_on_screen(0, 20, 10, 10),
"past the bottom edge (20+10 > 24)"
);
assert!(
!app.overlay_fits_on_screen(u16::MAX - 1, 0, 4, 4),
"a wild origin must saturate rather than wrap into range"
);
assert!(!app.overlay_fits_on_screen(0, 0, 0, 5), "zero width");
assert!(!app.overlay_fits_on_screen(0, 0, 5, 0), "zero height");
}
#[test]
fn a_same_length_rewrite_with_a_preserved_mtime_refreshes_on_the_watcher_path() {
let (tmp, f) = repo_with_seed("one\ntwo\n");
let root = tmp.path().to_path_buf();
let mut app = App::new(root.clone()).unwrap();
std::fs::write(&f, "one\ntwo\nAAA\n").unwrap();
app.editor
.open_head_diff_with_text(
std::path::PathBuf::from("seed.txt (HEAD)"),
"one\ntwo\n",
&f,
true,
)
.unwrap();
app.tag_open_diff(crate::widgets::diff::DiffSource::HeadVsWorking {
root: root.clone(),
rel: String::from("seed.txt"),
});
let mtime = std::fs::metadata(&f).unwrap().modified().unwrap();
std::fs::write(&f, "one\ntwo\nBBB\n").unwrap();
std::fs::File::options()
.write(true)
.open(&f)
.unwrap()
.set_modified(mtime)
.unwrap();
assert_eq!(
std::fs::metadata(&f).unwrap().modified().unwrap(),
mtime,
"precondition: the rewrite preserved the mtime"
);
assert!(
!app.refresh_open_diff_views(false, &[], &no_paths()),
"the poll's stamp gate cannot see this rewrite"
);
let mut written = std::collections::BTreeSet::new();
written.insert(f.clone());
assert!(
app.refresh_open_diff_views(false, &[], &written),
"the watcher naming the path rebuilds the view regardless of the stamp"
);
assert!(
app.editor
.diff
.as_ref()
.unwrap()
.right_lines
.iter()
.any(|l| l == "BBB"),
"the view shows the rewritten bytes"
);
}
#[test]
fn a_view_request_for_a_directory_is_refused_with_a_reason_the_client_prints() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join("subdir");
std::fs::create_dir(&dir).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let sock = seat_view_listener(&mut app, tmp.path());
let client = view_from_a_pane(&sock, &dir);
drain_until_answered(&mut app, &client);
match client.join().unwrap() {
crate::view_ipc::ViewReply::Err { message } => {
assert!(
message.contains("is a directory"),
"the reason must name what went wrong, got {message:?}"
);
}
other => panic!("a directory must not open as a file: {other:?}"),
}
}
#[test]
fn the_socket_sweep_removes_a_dead_crofts_file_and_spares_a_live_one() {
let tmp = tempfile::tempdir().unwrap();
let dead = {
let mut child = std::process::Command::new("true").spawn().unwrap();
let pid = child.id();
child.wait().unwrap();
pid
};
let mut peer = std::process::Command::new("sleep")
.arg("30")
.spawn()
.unwrap();
let live = peer.id();
let dead_sock = tmp.path().join(format!("view-{dead}.sock"));
let dead_nonce_sock = tmp.path().join(format!("view-{dead}-a1b2c3d4.sock"));
let live_sock = tmp.path().join(format!("view-{live}-e5f6a7b8.sock"));
let stranger = tmp.path().join("not-a-view-socket");
let dead_lock = tmp.path().join(format!("view-{dead}-a1b2c3d4.bind.lock"));
let live_lock = tmp.path().join(format!("view-{live}-e5f6a7b8.bind.lock"));
let orphan_lock = tmp.path().join(format!("view-{dead}-99887766.bind.lock"));
let dead_stage = tmp.path().join(format!(".s{dead}-0"));
let live_stage = tmp.path().join(format!(".s{live}-0"));
let stage_lookalike = tmp.path().join(format!(".s{dead}-notanumber"));
for d in [&dead_stage, &live_stage, &stage_lookalike] {
std::fs::create_dir(d).unwrap();
std::fs::write(d.join("s"), b"").unwrap();
}
for p in [
&dead_sock,
&dead_nonce_sock,
&live_sock,
&stranger,
&dead_lock,
&live_lock,
&orphan_lock,
] {
std::fs::write(p, b"").unwrap();
}
crate::app::sweep_dead_view_sockets(tmp.path());
let live_survived = live_sock.exists();
let live_lock_survived = live_lock.exists();
let live_stage_survived = live_stage.exists();
let _ = peer.kill();
let _ = peer.wait();
assert!(!dead_sock.exists(), "a dead croft's socket must be cleared");
assert!(
!dead_nonce_sock.exists(),
"and the nonce-shaped name, which is the only one production writes"
);
assert!(
!dead_lock.exists(),
"the lock beside a dead croft's socket goes with it"
);
assert!(
!orphan_lock.exists(),
"a lock whose socket never appeared must be swept too, or it leaks \
forever: nothing else in croft ever looks at it again"
);
assert!(
live_survived,
"another croft is alive, so its socket must survive the sweep"
);
assert!(
live_lock_survived,
"and so must its lock: removing it lets a second croft bind the \
socket this one is serving"
);
assert!(
!dead_stage.exists(),
"a dead croft's bind staging directory leaks forever otherwise: \
nothing but this sweep ever reads that name again"
);
assert!(
live_stage_survived,
"and a LIVE croft's staging directory must survive: removing one \
mid-bind takes the socket it is about to rename out with it"
);
assert!(
stage_lookalike.exists(),
"the counter must parse as a number, or the sweep is matching on a \
prefix and will eat directories it did not create"
);
assert!(
stranger.exists(),
"the sweep must only touch files it recognises by name"
);
}
#[test]
fn one_drain_answers_every_client_already_waiting() {
use std::io::{BufRead, Write};
let tmp = tempfile::tempdir().unwrap();
let first = tmp.path().join("first.txt");
let second = tmp.path().join("second.txt");
std::fs::write(&first, "one").unwrap();
std::fs::write(&second, "two").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.view_drain_budget =
crate::test_budget::spawn_budget(crate::test_budget::tests::VIEW_DRAIN_BASE);
let sock = seat_view_listener(&mut app, tmp.path());
let mut clients = Vec::new();
for target in [&first, &second] {
let mut c = std::os::unix::net::UnixStream::connect(&sock).unwrap();
c.set_read_timeout(Some(crate::test_budget::spawn_budget(
crate::test_budget::tests::VIEW_DRAIN_BASE,
)))
.unwrap();
let req = crate::view_ipc::ViewRequest::new(target);
let mut line = serde_json::to_string(&req).unwrap();
line.push('\n');
c.write_all(line.as_bytes()).unwrap();
c.flush().unwrap();
clients.push(c);
}
assert!(
app.drain_view_requests(),
"one drain, with two complete requests already on the socket"
);
for (i, c) in clients.iter().enumerate() {
let mut reply = String::new();
std::io::BufReader::new(c)
.read_line(&mut reply)
.unwrap_or_else(|e| {
panic!(
"client {i} was never answered ({e}): one drain must serve \
every client already waiting, not just the first"
)
});
let reply: crate::view_ipc::ViewReply = serde_json::from_str(reply.trim())
.unwrap_or_else(|e| panic!("client {i} got no parseable reply: {e}"));
assert_eq!(
reply,
crate::view_ipc::ViewReply::Ok,
"client {i} must be answered by the SAME drain as client 0: a loop \
that serves one connection and returns leaves this one waiting a \
whole frame, and every other test hands the drain a single client"
);
}
let open: Vec<_> = app
.editor
.editors
.iter()
.filter_map(|e| e.path.clone())
.collect();
assert!(
open.contains(&first) && open.contains(&second),
"both files must be open, got {open:?}"
);
}
#[test]
fn a_relative_path_in_a_request_is_refused_rather_than_resolved_here() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let reply = app.apply_view_request(std::path::Path::new("relative.txt"));
match reply {
crate::view_ipc::ViewReply::Err { message } => assert!(
message.contains("absolute"),
"the refusal must name the invariant it is enforcing, got {message:?}"
),
other => panic!("a relative path must not be resolved here: {other:?}"),
}
}
#[test]
fn a_failed_view_bind_reaches_the_status_line_with_its_cause() {
assert_eq!(
crate::app::view_status(None),
"Ready",
"a croft whose bind succeeded says nothing about it"
);
let said = crate::app::view_status(Some("Permission denied (os error 13)"));
assert!(
said.contains("croft view"),
"the message must name the feature that is off, or the user cannot \
connect it to the command that fails: {said:?}"
);
assert!(
said.contains("Permission denied (os error 13)"),
"and it must carry the CAUSE: a bare 'unavailable' sends the user \
looking in the wrong place, which is what the latch exists to \
prevent: {said:?}"
);
}
#[test]
fn a_client_that_never_sends_a_newline_is_refused_by_the_deadline() {
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 served = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let dribbling = std::sync::Arc::clone(&served);
let dribbler = std::thread::spawn(move || {
let Ok(mut c) = std::os::unix::net::UnixStream::connect(&sock2) else {
return;
};
let _ = std::io::Write::write_all(&mut c, br#"{"path":[47"#);
let _ = std::io::Write::flush(&mut c);
while !dribbling.load(std::sync::atomic::Ordering::Relaxed) {
std::thread::sleep(std::time::Duration::from_millis(5));
if std::io::Write::write_all(&mut c, b",47").is_err() {
return;
}
let _ = std::io::Write::flush(&mut c);
}
});
let listener = app.view_listener.as_ref().unwrap();
let stream = accept_when_ready(listener);
let deadline = std::time::Instant::now() + std::time::Duration::from_millis(20);
let (reply, opened) = app.answer_view_client(stream, deadline);
served.store(true, std::sync::atomic::Ordering::Relaxed);
let _ = dribbler.join();
assert!(
!opened,
"nothing was ever named, so nothing can have opened"
);
match reply {
crate::view_ipc::ViewReply::Err { message } => assert!(
message.contains("did not arrive within the frame budget"),
"the DEADLINE must be what refuses this client. Any other error \
means some incidental bound fired instead and the deadline is \
still unenforced: {message}"
),
other => panic!("a request with no newline cannot succeed: {other:?}"),
}
}
#[test]
fn a_non_blocking_accepted_stream_is_still_answered() {
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 target = tmp.path().join("seen.txt");
std::fs::write(&target, b"hello").unwrap();
let sock2 = sock.clone();
let target2 = target.clone();
let client = std::thread::spawn(move || {
let mut c = std::os::unix::net::UnixStream::connect(&sock2).unwrap();
std::thread::sleep(std::time::Duration::from_millis(120));
let req = crate::view_ipc::ViewRequest::new(&target2);
let mut line = serde_json::to_string(&req).unwrap();
line.push('\n');
let _ = std::io::Write::write_all(&mut c, line.as_bytes());
let _ = std::io::Write::flush(&mut c);
std::thread::sleep(std::time::Duration::from_millis(300));
});
std::thread::sleep(std::time::Duration::from_millis(30));
let listener = app.view_listener.as_ref().unwrap();
let stream = accept_when_ready(listener);
stream.set_nonblocking(true).unwrap();
let probe = stream.try_clone().expect("a dup of the accepted stream");
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 _ = client.join();
let flags = unsafe { libc::fcntl(std::os::fd::AsRawFd::as_raw_fd(&probe), libc::F_GETFL) };
assert!(
flags >= 0,
"F_GETFL on the dup failed: {}",
std::io::Error::last_os_error()
);
assert_eq!(
flags & libc::O_NONBLOCK,
0,
"production must clear O_NONBLOCK on an accepted stream: macOS inherits \
the listener's flags across accept, and a non-blocking read there \
returns before the client has written"
);
assert_eq!(
reply,
crate::view_ipc::ViewReply::Ok,
"and the request is still answered: a cleared flag with no reply \
behind it would not be a pass"
);
assert!(opened, "and the file must actually have been opened");
}
#[test]
fn the_sweep_spares_staged_stdin_a_croft_may_still_be_showing() {
let tmp = tempfile::tempdir().unwrap();
let fresh = crate::view_ipc::stage_stdin(tmp.path(), b"a,b\n1,2\n", None).unwrap();
assert!(fresh.exists(), "precondition: the pipe was staged");
crate::app::sweep_dead_view_sockets(tmp.path());
assert!(
fresh.exists(),
"a just-staged pipe must survive: a pane may be showing it right now"
);
}
#[test]
fn opening_a_staged_pipe_claims_it_for_this_croft() {
let tmp = tempfile::tempdir().unwrap();
let staged = crate::view_ipc::stage_stdin(tmp.path(), b"a,b\n1,2\n", None).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let reply = app.apply_view_request(&staged);
assert_eq!(reply, crate::view_ipc::ViewReply::Ok, "the pipe must open");
assert!(
!staged.exists(),
"the staged name must be gone: it is the name the sweep judges by age"
);
let open = app.editor.editors[app.editor.active_index()]
.path
.clone()
.expect("a file is open");
let name = open.file_name().unwrap().to_str().unwrap();
assert_eq!(
crate::view_ipc::holder_of_staged(name),
Some(std::process::id()),
"the EDITOR must hold the claimed path, or a page turn re-opens a \
name that no longer exists: {name}"
);
assert!(
open.exists(),
"and the claimed file must be on disk under its new name"
);
}
#[test]
fn opening_a_named_file_does_not_rename_it() {
let tmp = tempfile::tempdir().unwrap();
let decoy = tmp.path().join("stdin-1-0.txt");
std::fs::write(&decoy, b"mine").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let reply = app.apply_view_request(&decoy);
assert_eq!(reply, crate::view_ipc::ViewReply::Ok, "it must still open");
assert!(
decoy.exists(),
"a file the user named must keep its name, whatever it looks like"
);
assert_eq!(
app.editor.editors[app.editor.active_index()]
.path
.as_deref(),
Some(decoy.as_path()),
"and the editor holds the path the user asked for"
);
}
#[test]
fn the_sweep_removes_staged_stdin_old_enough_that_nothing_can_be_showing_it() {
let tmp = tempfile::tempdir().unwrap();
let stale = crate::view_ipc::stage_stdin(tmp.path(), b"secret", Some("txt")).unwrap();
let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60 * 60 * 30);
let f = std::fs::File::options().write(true).open(&stale).unwrap();
f.set_modified(old).unwrap();
drop(f);
crate::app::sweep_dead_view_sockets(tmp.path());
assert!(
!stale.exists(),
"a staged pipe older than the window must not outlive it: the module's \
own rationale names `vault read | croft view -`"
);
}
#[test]
fn the_view_socket_is_bound_before_the_first_pane_is_spawned() {
let files = app_source_files();
let src = files
.iter()
.map(|(_, text)| text.as_str())
.find(|text| text.contains("pub fn new(root: PathBuf)"))
.expect("App::new must exist for this guard to mean anything");
let ctor = src.find("pub fn new(root: PathBuf)").unwrap();
let end = src[ctor..]
.find("\n }\n")
.map(|i| ctor + i)
.expect("App::new's body must end in its closing brace");
let body = &src[ctor..end];
for marker in ["Self::bind_view_socket()", "PtyTerminal::new(&root)"] {
assert_eq!(
files
.iter()
.map(|(_, text)| text.matches(marker).count())
.sum::<usize>(),
1,
"{marker} must appear exactly once, or this guard measures whichever \
copy comes first rather than the one that runs"
);
}
let bind = body
.find("Self::bind_view_socket()")
.expect("App::new must bind the view socket");
let pane = body
.find("PtyTerminal::new(&root)")
.expect("App::new must spawn the first pane");
assert!(
bind < pane,
"the view socket must be bound BEFORE the first pane is spawned: \
portable-pty snapshots the environment when a pane's CommandBuilder \
is built, so a pane constructed first never learns the socket and \
`croft view` fails in it while working in every pane opened later"
);
}
#[test]
fn a_view_request_for_a_fifo_is_refused_rather_than_opened() {
let tmp = tempfile::tempdir().unwrap();
let fifo = tmp.path().join("pipe");
let c = std::ffi::CString::new(fifo.as_os_str().as_encoded_bytes()).unwrap();
assert_eq!(
unsafe { libc::mkfifo(c.as_ptr(), 0o600) },
0,
"precondition: the fixture must actually create a FIFO"
);
assert!(
fifo.exists(),
"and `exists()` must say yes, as it did in production"
);
let root = tmp.path().to_path_buf();
let target = fifo.clone();
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let mut app = App::new(root).unwrap();
let _ = tx.send(app.apply_view_request(&target));
});
let reply = rx
.recv_timeout(crate::test_budget::spawn_budget(
crate::test_budget::tests::VIEW_FIFO_RECV_BASE,
))
.expect("opening a FIFO must not block the frame loop forever");
assert!(
matches!(reply, crate::view_ipc::ViewReply::Err { .. }),
"a FIFO is not a regular file and must be refused with a reason the \
client prints, got {reply:?}"
);
}
#[test]
fn copying_a_file_leaves_its_history_with_the_original() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().canonicalize().unwrap();
std::fs::create_dir_all(root.join("sub")).unwrap();
std::fs::write(root.join("a.txt"), "a\n").unwrap();
let (mut app, _hist) = app_with_history(&root);
crate::history::record_in(&app.history_root, &root.join("a.txt"), b"a0\n", 1_000).unwrap();
assert!(app.apply_paste_or_drop(
&root.join("sub"),
&[root.join("a.txt")],
ExplorerClipMode::Copy
));
assert!(root.join("sub").join("a.txt").exists());
assert_eq!(
crate::history::entries_in(&app.history_root, &root.join("a.txt")).len(),
1
);
assert!(
crate::history::entries_in(&app.history_root, &root.join("sub").join("a.txt")).is_empty()
);
}
#[test]
fn a_file_move_applies_the_servers_edits_before_renaming() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().canonicalize().unwrap();
std::fs::write(root.join("util.py"), "def f(): pass\n").unwrap();
std::fs::write(root.join("main.py"), "import util\n").unwrap();
let mut app = App::new(root.clone()).unwrap();
let pending = PendingFileMove {
request_id: 7,
op: FileMove::Rename {
parent: root.clone(),
old: root.join("util.py"),
new_name: String::from("helpers.py"),
},
renames: vec![crate::lsp::manager::FileRenameOp {
old: root.join("util.py"),
new: root.join("helpers.py"),
is_dir: false,
}],
deadline: std::time::Instant::now(),
baseline: Vec::new(),
};
let edits = vec![(
root.join("main.py"),
vec![crate::widgets::editor::TextSpanEdit {
start: (0, 7),
end: (0, 11),
new_text: String::from("helpers"),
utf16: false,
}],
)];
app.finish_file_move(pending, edits);
assert!(root.join("helpers.py").exists(), "the file moved");
assert!(!root.join("util.py").exists());
assert_eq!(
std::fs::read_to_string(root.join("main.py")).unwrap(),
"import helpers\n",
"the import followed it"
);
assert!(
app.status.contains("references updated in 1 file"),
"{}",
app.status
);
}
#[test]
fn a_pending_move_goes_ahead_at_its_deadline_without_an_answer() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().canonicalize().unwrap();
std::fs::write(root.join("a.txt"), "x").unwrap();
let mut app = App::new(root.clone()).unwrap();
app.pending_file_move = Some(PendingFileMove {
request_id: u64::MAX,
op: FileMove::Rename {
parent: root.clone(),
old: root.join("a.txt"),
new_name: String::from("b.txt"),
},
renames: Vec::new(),
deadline: std::time::Instant::now() - std::time::Duration::from_millis(1),
baseline: Vec::new(),
});
assert!(app.tick_file_moves());
assert!(app.pending_file_move.is_none());
assert!(
root.join("b.txt").exists(),
"a silent server cannot block the move"
);
}
#[test]
fn a_probe_reports_whether_the_file_is_still_open() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "git-rebase-todo", "pick a b\n");
let path = app.editor.path.clone().unwrap();
assert_eq!(
app.probe_view_path(&path),
crate::view_ipc::ViewReply::Err {
message: String::from(crate::view_ipc::PROBE_OPEN)
}
);
app.run_command(crate::widgets::command_palette::Command::CloseEditor);
assert!(matches!(
app.probe_view_path(&path),
crate::view_ipc::ViewReply::Err { .. }
));
}
#[test]
fn a_plain_view_request_has_no_probe_field_on_the_wire() {
let json = serde_json::to_string(&crate::view_ipc::ViewRequest::new(std::path::Path::new(
"/a",
)))
.unwrap();
assert!(!json.contains("probe"), "{json}");
let probe = serde_json::to_string(&crate::view_ipc::ViewRequest::probe(std::path::Path::new(
"/a",
)))
.unwrap();
assert!(probe.contains("\"probe\":true"));
}
#[test]
fn a_file_that_did_not_exist_yet_says_so() {
let repo = scrub_repo();
std::fs::write(repo.path().join("new.txt"), "fresh\n").unwrap();
let mut app = App::new(repo.path().to_path_buf()).unwrap();
app.editor.open(&repo.path().join("new.txt")).unwrap();
app.scrub_history();
app.handle_scrubber_key(KeyCode::Left);
let view = app
.scrub
.view
.as_ref()
.expect("a view even for a missing file");
assert!(view.lines[0].contains("did not exist"), "{:?}", view.lines);
}
#[test]
fn a_missing_file_asks_to_locate_it_and_the_mapping_is_learned_and_kept() {
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir_all(tmp.path().join("src")).unwrap();
std::fs::create_dir_all(tmp.path().join("lib")).unwrap();
std::fs::write(tmp.path().join("src/a.rs"), "a1\na2\n").unwrap();
std::fs::write(tmp.path().join("lib/b.rs"), "b1\nb2\nb3\n").unwrap();
let log = tmp.path().join("ci.sarif");
std::fs::write(
&log,
r#"{"version":"2.1.0","runs":[{"tool":{"driver":{"name":"ci"}},"results":[
{"message":{"text":"in a"},"locations":[{"physicalLocation":{"artifactLocation":{"uri":"file:///home/runner/work/app/src/a.rs"},"region":{"startLine":2}}}]},
{"message":{"text":"in b"},"locations":[{"physicalLocation":{"artifactLocation":{"uri":"file:///home/runner/work/app/lib/b.rs"},"region":{"startLine":3}}}]}
]}]}"#,
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_preview(&log).unwrap();
app.handle_sarif_key(key(KeyCode::Enter, KeyModifiers::NONE));
assert!(
matches!(
app.input_prompt.as_ref().map(|p| &p.purpose),
Some(crate::widgets::input_prompt::InputPurpose::SarifLocate { .. })
),
"a Locate prompt: {}",
app.status
);
assert_eq!(
app.editor
.sarif
.as_ref()
.unwrap()
.selected_entry()
.map(|e| e.message.clone())
.as_deref(),
Some("in b")
);
app.submit_sarif_locate(&tmp.path().join("src/a.rs").display().to_string());
assert!(app.status.contains("names must match"), "{}", app.status);
app.submit_sarif_locate(&tmp.path().join("lib/b.rs").display().to_string());
assert_eq!(
app.editor.path.as_deref(),
Some(tmp.path().join("lib/b.rs").as_path())
);
assert_eq!(app.editor.cursor_row, 2);
let mut again = App::new(tmp.path().to_path_buf()).unwrap();
again.editor.open_preview(&log).unwrap();
let rows = again.editor.sarif.as_ref().unwrap().rows();
let a_row = rows
.iter()
.position(|r| match r {
crate::sarif::view::Row::Item { entry } => {
again.editor.sarif.as_ref().unwrap().entries[*entry].message == "in a"
}
_ => false,
})
.unwrap();
again.editor.sarif.as_mut().unwrap().selected = a_row;
again.handle_sarif_key(key(KeyCode::Enter, KeyModifiers::NONE));
assert_eq!(
again.editor.path.as_deref(),
Some(tmp.path().join("src/a.rs").as_path()),
"resolved through the saved prefix: {}",
again.status
);
assert_eq!(again.editor.cursor_row, 1);
});
}
#[test]
fn a_read_that_began_before_a_write_settled_does_not_undo_it() {
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let (gh, _log) = viewed_sync_gh(tmp.path(), " *FileAsViewed*) echo '{}' ;;");
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.review.gh = gh.display().to_string();
let pr = || {
crate::pr_review::parse_pr(
r#"{"number": 42, "url": "https://github.com/x/y/pull/42", "files": [{"path": "a.rs"}]}"#,
)
.unwrap()
};
app.open_pr_review(pr(), String::from("x/y#42"));
app.editor.pr_review.as_mut().unwrap().github_id = Some(String::from("PR_kw42"));
app.handle_pr_review_key(key(KeyCode::Char(' '), KeyModifiers::NONE));
app.poll_pr_viewed();
assert!(app.review.pr_viewed_write.is_some(), "in flight");
app.open_pr_review(pr(), String::from("x/y#42"));
let (tx, rx) = std::sync::mpsc::channel();
app.review.pr_viewed_fetch = Some((String::from("x/y#42"), app.review.pr_viewed_seq, rx));
settle_viewed_writes(&mut app);
assert!(app.review.pr_viewed_queue.is_empty() && app.review.pr_viewed_write.is_none());
let mut states = std::collections::BTreeMap::new();
states.insert(
String::from("a.rs"),
crate::pr_review::ViewedState::Unviewed,
);
tx.send(Ok((String::from("PR_kw42"), states))).unwrap();
app.poll_pr_viewed();
let view = app.editor.pr_review.as_ref().unwrap();
assert!(view.viewed.contains("a.rs"), "the stale answer is ignored");
assert!(
crate::pr_review::ViewedStore::load(&App::pr_viewed_path())
.viewed("x/y#42")
.contains("a.rs"),
"and does not reach the local store"
);
let (tx, rx) = std::sync::mpsc::channel();
app.review.pr_viewed_fetch = Some((String::from("x/y#42"), app.review.pr_viewed_seq, rx));
let mut states = std::collections::BTreeMap::new();
states.insert(
String::from("a.rs"),
crate::pr_review::ViewedState::Unviewed,
);
tx.send(Ok((String::from("PR_kw42"), states))).unwrap();
app.poll_pr_viewed();
assert!(
!app.editor
.pr_review
.as_ref()
.unwrap()
.viewed
.contains("a.rs")
);
});
}
#[test]
fn save_as_writes_the_buffer_to_a_new_path_and_moves_the_tab_there() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_plan_whose_folder_was_removed(tmp.path());
let cmd = crate::widgets::command_palette::Command::from_id("save_as")
.expect("there is a File: Save As… command");
app.run_command(cmd);
assert_eq!(
app.prompt.as_ref().map(|p| p.buffer.as_str()),
Some("notes/plan.md"),
"the prompt starts from the tab's own path"
);
app.prompt = None;
save_as(&mut app, "drafts/plan.txt");
let saved = tmp.path().join("drafts/plan.txt");
assert!(
app.prompt.is_none(),
"{:?}",
app.prompt.as_ref().map(|p| &p.error)
);
assert_eq!(
std::fs::read_to_string(&saved).unwrap(),
"# Plan\n\n- step one\n- step two\n"
);
assert_eq!(app.editor.path.as_deref(), Some(saved.as_path()));
assert!(!app.editor.dirty);
assert!(
app.editor.language().is_none(),
"a .txt file has no grammar"
);
assert!(
!tmp.path().join("notes").exists(),
"the old path is not recreated"
);
app.editor.insert_str("!");
app.save();
assert!(!app.editor.dirty, "{}", app.status);
assert!(
std::fs::read_to_string(&saved)
.unwrap()
.contains("- step two!")
);
}
#[test]
fn save_as_does_not_overwrite_another_file() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_plan_whose_folder_was_removed(tmp.path());
std::fs::write(tmp.path().join("README.md"), "# app\n").unwrap();
save_as(&mut app, "README.md");
let error = app.prompt.as_ref().and_then(|p| p.error.clone());
assert!(
error
.as_deref()
.is_some_and(|e| e.contains("already exists")),
"{error:?}"
);
assert_eq!(
std::fs::read_to_string(tmp.path().join("README.md")).unwrap(),
"# app\n"
);
assert_eq!(
app.editor.path.as_deref(),
Some(tmp.path().join("notes/plan.md").as_path())
);
assert!(app.editor.dirty);
save_as(&mut app, " ");
assert!(app.prompt.as_ref().is_some_and(|p| p.error.is_some()));
assert!(app.editor.dirty);
}
#[test]
fn a_save_as_that_fails_leaves_the_tab_where_it_was() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_plan_whose_folder_was_removed(tmp.path());
std::fs::write(tmp.path().join("blocker"), "").unwrap();
save_as(&mut app, "blocker/plan.md");
assert_eq!(
app.editor.path.as_deref(),
Some(tmp.path().join("notes/plan.md").as_path())
);
assert!(app.editor.dirty);
let error = app.prompt.as_ref().and_then(|p| p.error.clone());
assert!(error.is_some(), "the prompt stays open with the reason");
}
fn save_with_settings(
text: &str,
editorconfig: Option<&str>,
settings: &str,
row: usize,
) -> String {
let tmp = tempfile::tempdir().unwrap();
if let Some(ec) = editorconfig {
std::fs::write(tmp.path().join(".editorconfig"), ec).unwrap();
}
let f = tmp.path().join("f.txt");
std::fs::write(&f, text).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.apply_merged_settings(&serde_json::from_str(settings).unwrap());
app.editor.open_pinned(&f).unwrap();
app.focus_pane(Pane::Editor);
app.editor.cursor_row = row;
app.editor.cursor_col = app.editor.lines[row].chars().count();
app.handle_key(key(KeyCode::Char('y'), KeyModifiers::NONE))
.unwrap();
app.handle_key(key(KeyCode::Char('s'), KeyModifiers::SUPER))
.unwrap();
assert!(!app.editor.dirty, "saved: {}", app.status);
std::fs::read_to_string(&f).unwrap()
}
#[test]
fn insert_final_newline_ends_every_save_with_a_newline() {
assert_eq!(
save_with_settings(
"hello world \nsecond line",
None,
r#"{"insert_final_newline": true}"#,
1
),
"hello world \nsecond liney\n"
);
}
#[test]
fn trim_trailing_whitespace_strips_lines_on_save() {
assert_eq!(
save_with_settings(
"hello world \nsecond line",
None,
r#"{"trim_trailing_whitespace": true}"#,
1
),
"hello world\nsecond liney"
);
}
#[test]
fn trim_final_newlines_keeps_one_newline_on_save() {
assert_eq!(
save_with_settings("a\n\n\n", None, r#"{"trim_final_newlines": true}"#, 0),
"ay\n"
);
assert_eq!(
save_with_settings(
"a\n\n\n",
None,
r#"{"trim_final_newlines": true, "insert_final_newline": true}"#,
0
),
"ay\n",
"both on still leaves exactly one"
);
}
#[test]
fn save_clean_ups_default_off_leave_the_file_as_typed() {
assert_eq!(
save_with_settings("hello world \nsecond line", None, "{}", 1),
"hello world \nsecond liney"
);
assert_eq!(save_with_settings("a\n\n\n", None, "{}", 0), "ay\n\n\n");
}
#[test]
fn an_editorconfig_value_overrides_the_global_clean_up() {
let off = "root = true\n[*]\ninsert_final_newline = false\ntrim_trailing_whitespace = false\n";
assert_eq!(
save_with_settings(
"hello world \nsecond line",
Some(off),
r#"{"insert_final_newline": true, "trim_trailing_whitespace": true}"#,
1
),
"hello world \nsecond liney"
);
let on = "root = true\n[*]\ninsert_final_newline = true\n";
assert_eq!(
save_with_settings("second line", Some(on), "{}", 0),
"second liney\n"
);
}
#[test]
fn trim_final_newlines_spares_the_caret_line() {
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("f.txt");
std::fs::write(&f, "a\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.apply_merged_settings(&serde_json::from_str(r#"{"trim_final_newlines": true}"#).unwrap());
app.editor.open_pinned(&f).unwrap();
app.focus_pane(Pane::Editor);
app.editor.cursor_row = 0;
app.editor.cursor_col = 1;
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
app.handle_key(key(KeyCode::Char('s'), KeyModifiers::SUPER))
.unwrap();
assert_eq!(app.editor.cursor_row, 1);
assert_eq!(std::fs::read_to_string(&f).unwrap(), "a\n\n");
}
#[test]
fn vscode_save_clean_up_settings_import() {
let (settings, unmapped, _) = crate::import_vscode::map_settings(
serde_json::json!({
"files.insertFinalNewline": true,
"files.trimTrailingWhitespace": true,
"files.trimFinalNewlines": false
})
.as_object()
.unwrap(),
);
assert!(unmapped.is_empty(), "{unmapped:?}");
assert_eq!(settings["insert_final_newline"], serde_json::json!(true));
assert_eq!(
settings["trim_trailing_whitespace"],
serde_json::json!(true)
);
assert_eq!(settings["trim_final_newlines"], serde_json::json!(false));
}
#[test]
fn save_all_writes_every_dirty_tab() {
let tmp = tempfile::tempdir().unwrap();
let a = tmp.path().join("a.txt");
let b = tmp.path().join("b.txt");
std::fs::write(&a, "aaa").unwrap();
std::fs::write(&b, "bbb").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.auto_save = false;
app.auto_save_on_focus_change = false;
app.format_on_save = false;
app.editor.open_pinned(&a).unwrap();
app.focus_pane(Pane::Editor);
app.handle_key(key(KeyCode::Char('X'), KeyModifiers::NONE))
.unwrap();
app.editor.open_pinned(&b).unwrap();
app.handle_key(key(KeyCode::Char('Y'), KeyModifiers::NONE))
.unwrap();
assert_eq!(app.unsaved_count(), 2);
app.handle_key(key(
KeyCode::Char('s'),
KeyModifiers::CONTROL | KeyModifiers::ALT,
))
.unwrap();
assert_eq!(app.unsaved_count(), 0, "{}", app.status);
assert!(std::fs::read_to_string(&a).unwrap().contains('X'));
assert!(std::fs::read_to_string(&b).unwrap().contains('Y'));
assert_eq!(app.status, "Saved 2 editors");
app.run_command(crate::widgets::command_palette::Command::SaveAll);
assert_eq!(app.status, "Save All: nothing to save");
assert!(!is_save_all_key(key(
KeyCode::Char('S'),
KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SHIFT
)));
assert!(!is_save_all_key(key(
KeyCode::Char('s'),
KeyModifiers::CONTROL
)));
}
#[test]
fn save_all_never_overwrites_an_external_change_on_disk() {
let tmp = tempfile::tempdir().unwrap();
let a = tmp.path().join("a.txt");
let b = tmp.path().join("b.txt");
std::fs::write(&a, "aaa").unwrap();
std::fs::write(&b, "bbb").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.auto_save = false;
app.auto_save_on_focus_change = false;
app.format_on_save = false;
app.editor.open_pinned(&a).unwrap();
app.focus_pane(Pane::Editor);
app.handle_key(key(KeyCode::Char('X'), KeyModifiers::NONE))
.unwrap();
std::fs::write(&a, "external change wins\n").unwrap();
app.editor.open_pinned(&b).unwrap();
app.handle_key(key(KeyCode::Char('Y'), KeyModifiers::NONE))
.unwrap();
app.run_command(crate::widgets::command_palette::Command::SaveAll);
assert_eq!(
std::fs::read_to_string(&a).unwrap(),
"external change wins\n",
"Save All must not write over a file changed on disk"
);
assert!(std::fs::read_to_string(&b).unwrap().contains('Y'));
assert_eq!(app.unsaved_count(), 1, "the conflicted tab stays dirty");
assert!(
app.status.contains("1 editor still unsaved"),
"the leftover tab is reported, not a clean \"Saved\": {:?}",
app.status
);
}
#[test]
fn clicking_save_all_on_the_open_editors_header_saves_every_dirty_tab() {
let tmp = tempfile::tempdir().unwrap();
let a = tmp.path().join("a.txt");
let b = tmp.path().join("b.txt");
std::fs::write(&a, "aaa").unwrap();
std::fs::write(&b, "bbb").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.auto_save = false;
app.auto_save_on_focus_change = false;
app.format_on_save = false;
app.editor.open_pinned(&a).unwrap();
app.focus_pane(Pane::Editor);
app.handle_key(key(KeyCode::Char('X'), KeyModifiers::NONE))
.unwrap();
app.editor.open_pinned(&b).unwrap();
app.handle_key(key(KeyCode::Char('Y'), KeyModifiers::NONE))
.unwrap();
app.explorer_views = Default::default();
app.explorer_views.toggle(ExplorerView::OpenEditors);
app.open_editors.collapsed = false;
app.sidebar_view = SidebarView::Explorer;
app.show_tree = true;
let buf = draw_buffer(&mut app, 120, 40);
let hdr = app.open_editors.last_area;
assert!(hdr.height > 0, "OPEN EDITORS is on screen");
let save_all_x = (hdr.x..hdr.x + hdr.width)
.find(|&x| buf[(x, hdr.y)].symbol() == "\u{eb49}")
.expect("the OPEN EDITORS header paints a Save All (codicon save-all) action");
left_click(&mut app, save_all_x, hdr.y);
assert!(
std::fs::read_to_string(&a).unwrap().contains('X'),
"Save All writes the inactive tab"
);
assert!(std::fs::read_to_string(&b).unwrap().contains('Y'));
assert!(
!app.open_editors.collapsed,
"the button's click does not also collapse the section"
);
}
#[test]
fn save_all_counts_a_file_dirty_in_two_splits_once() {
let tmp = tempfile::tempdir().unwrap();
let a = tmp.path().join("a.txt");
std::fs::write(&a, "aaa").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.auto_save = false;
app.auto_save_on_focus_change = false;
app.editor.open_pinned(&a).unwrap();
app.focus_pane(Pane::Editor);
app.split_editor();
app.handle_key(key(KeyCode::Char('X'), KeyModifiers::NONE))
.unwrap();
app.focus_editor_group(true);
app.handle_key(key(KeyCode::Char('Y'), KeyModifiers::NONE))
.unwrap();
let dirty_buffers = app
.editor
.editors
.iter()
.chain(
app.editor_layout
.inactive_groups()
.flat_map(|g| g.editors.iter()),
)
.filter(|e| e.dirty && e.path.as_deref() == Some(a.as_path()))
.count();
assert_eq!(dirty_buffers, 2, "fixture: a.txt is dirty in both splits");
assert_eq!(app.unsaved_count(), 1, "one file, counted once");
}
#[test]
fn save_all_reports_a_file_with_a_symbol_tab_as_one_editor() {
let tmp = tempfile::tempdir().unwrap();
let (mut app, file) = app_with_symbol_tab_on_b(&tmp);
app.auto_save = false;
app.auto_save_on_focus_change = false;
app.format_on_save = false;
app.sync_symbol_views();
app.editor.cursor_row = 4;
app.editor.cursor_col = 5;
app.handle_key(key(KeyCode::Char('7'), KeyModifiers::NONE))
.unwrap();
app.sync_symbol_views();
assert!(
app.editor.editors.iter().all(|e| e.dirty),
"fixture: both tabs hold the edit"
);
app.run_command(crate::widgets::command_palette::Command::SaveAll);
assert_eq!(
std::fs::read_to_string(&file).unwrap(),
"fn a() {\n 1\n}\nfn b() {\n 27\n}"
);
assert_eq!(app.status, "Saved 1 editor");
}
#[test]
fn save_all_does_not_report_a_file_waiting_on_its_formatter_as_saved() {
assert_eq!(
save_all_summary(1, 0, Some("m.py"), String::new()),
"Formatting m.py before saving it"
);
assert_eq!(
save_all_summary(3, 0, Some("m.py"), String::new()),
"Saved 2 editors; formatting m.py before saving it"
);
assert_eq!(
save_all_summary(2, 0, None, String::new()),
"Saved 2 editors"
);
assert_eq!(
save_all_summary(1, 0, None, String::new()),
"Saved 1 editor"
);
}
#[test]
fn opening_a_closed_file_again_brings_back_the_undo_history() {
let (_tmp, a, mut app) = app_with_a_saved_edit();
app.run_command(crate::widgets::command_palette::Command::CloseEditor);
app.editor.open_preview(&a).unwrap();
assert!(app.editor.undo());
assert_eq!(app.editor.lines[0], "value = 1");
}
#[test]
fn a_text_files_wal_named_sibling_is_not_part_of_its_stamp() {
let tmp = tempfile::tempdir().unwrap();
let txt = tmp.path().join("notes.txt");
std::fs::write(&txt, "x\n").unwrap();
let sibling = tmp.path().join("notes.txt-wal");
std::fs::write(&sibling, "one").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&txt).unwrap();
app.editor.insert_char('y');
std::fs::write(&sibling, "a longer second write").unwrap();
assert!(!app.editor.disk_changed_externally());
assert!(!app.reload_open_file_after_external_change());
assert!(!app.editor.disk_conflict);
assert_eq!(app.editor.lines[0], "yx");
}
fn serve_view_request_1606(
app: &mut App,
path: &std::path::Path,
at: Option<(usize, usize)>,
) -> crate::view_ipc::ViewReply {
let (mut client, server) = std::os::unix::net::UnixStream::pair().unwrap();
let mut line = serde_json::to_vec(&crate::view_ipc::ViewRequest::at(path, at)).unwrap();
line.push(b'\n');
std::io::Write::write_all(&mut client, &line).unwrap();
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
app.answer_view_client(server, deadline).0
}
#[test]
fn a_view_request_with_a_location_puts_the_caret_there() {
let tmp = tempfile::tempdir().unwrap();
let big = tmp.path().join("big.txt");
let text: String = (1..=300).map(|n| format!("line {n}\n")).collect();
std::fs::write(&big, text).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let reply = serve_view_request_1606(&mut app, &big, Some((149, 2)));
assert_eq!(reply, crate::view_ipc::ViewReply::Ok);
assert_eq!(app.editor.path.as_deref(), Some(big.as_path()));
assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (149, 2));
assert!(app.editor.scroll > 0 && app.editor.scroll <= 149);
assert!(app.focus == Pane::Editor);
}
#[test]
fn a_view_request_location_clamps_and_none_leaves_the_caret_at_the_top() {
let tmp = tempfile::tempdir().unwrap();
let small = tmp.path().join("small.txt");
std::fs::write(&small, "one\ntwo\n").unwrap();
let other = tmp.path().join("other.txt");
std::fs::write(&other, "alpha\nbeta\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
serve_view_request_1606(&mut app, &small, Some((99, 99)));
let last = app.editor.lines.len() - 1;
assert_eq!(app.editor.cursor_row, last);
assert!(app.editor.cursor_col <= app.editor.lines[last].chars().count());
serve_view_request_1606(&mut app, &other, None);
assert_eq!(app.editor.path.as_deref(), Some(other.as_path()));
assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (0, 0));
}
#[test]
fn the_window_losing_focus_saves_the_buffer_being_edited() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.txt", "hello");
app.auto_save = false;
app.auto_save_on_focus_change = true;
app.focus_pane(Pane::Editor);
app.tick_auto_save();
app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
.unwrap();
assert!(app.editor.dirty);
assert!(!app.tick_auto_save(), "focus inside croft has not moved");
assert!(app.on_window_focus_lost(), "the window lost focus");
assert!(!app.editor.dirty, "the active buffer is saved");
let on_disk = std::fs::read_to_string(tmp.path().join("a.txt")).unwrap();
assert!(on_disk.contains('x'), "the edit is on disk: {on_disk:?}");
}
#[test]
fn the_window_losing_focus_saves_every_dirty_tab() {
let tmp = tempfile::tempdir().unwrap();
let a = tmp.path().join("a.txt");
let b = tmp.path().join("b.txt");
std::fs::write(&a, "aaa").unwrap();
std::fs::write(&b, "bbb").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.auto_save = false;
app.auto_save_on_focus_change = false;
app.editor.open_pinned(&a).unwrap();
app.focus_pane(Pane::Editor);
app.handle_key(key(KeyCode::Char('A'), KeyModifiers::NONE))
.unwrap();
app.editor.open_pinned(&b).unwrap();
app.handle_key(key(KeyCode::Char('B'), KeyModifiers::NONE))
.unwrap();
app.tick_auto_save();
app.auto_save_on_focus_change = true;
assert!(app.on_window_focus_lost());
let a_disk = std::fs::read_to_string(&a).unwrap();
let b_disk = std::fs::read_to_string(&b).unwrap();
assert!(
a_disk.contains('A'),
"the background tab is saved: {a_disk:?}"
);
assert!(b_disk.contains('B'), "the active tab is saved: {b_disk:?}");
}
#[test]
fn the_window_losing_focus_saves_nothing_when_the_mode_is_off() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.txt", "hello");
app.auto_save = true;
app.auto_save_on_focus_change = false;
app.focus_pane(Pane::Editor);
app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
.unwrap();
age_last_edit(&mut app.editor);
assert!(!app.on_window_focus_lost(), "the mode is off");
assert!(app.editor.dirty, "the buffer stays dirty");
assert_eq!(
std::fs::read_to_string(tmp.path().join("a.txt")).unwrap(),
"hello"
);
}
#[test]
fn the_window_losing_focus_leaves_clean_buffers_alone() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.txt", "hello");
app.auto_save = false;
app.auto_save_on_focus_change = true;
app.focus_pane(Pane::Editor);
let before = std::fs::metadata(tmp.path().join("a.txt"))
.unwrap()
.modified()
.unwrap();
std::thread::sleep(std::time::Duration::from_millis(20));
assert!(!app.on_window_focus_lost(), "nothing to save");
let after = std::fs::metadata(tmp.path().join("a.txt"))
.unwrap()
.modified()
.unwrap();
assert_eq!(before, after, "a clean file is not rewritten");
}