Tunal/crates/tunal-core/tests/trash.rs
astar76 35715817aa S032: tests for core, ops, trash, dirmeta and the elevation protocol
Fixes: file over folder with Overwrite, CRLF .directory files, stray blank line
after removing an added group.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-19 01:00:47 -06:00

442 lines
15 KiB
Rust

//! The freedesktop trash with `XDG_DATA_HOME` pointing into a temp dir. The environment is
//! process-wide, so every test holds `lock()` for its whole run.
use std::ffi::OsStr;
use std::fs;
use std::ops::ControlFlow;
use std::os::unix::ffi::OsStrExt;
use std::path::{Path, PathBuf};
use std::sync::mpsc;
use std::sync::{Mutex, MutexGuard, OnceLock};
use tunal_core::ops::{ConflictAction, ConflictChoice, JobEvent, JobKind, Jobs, Report};
use tunal_core::{Error, Location, Locations, TrashLocation, Uri, trash};
struct Env {
/// Holds the scratch dir; leaked on purpose so it lives for the whole run.
data: PathBuf,
scratch: &'static tempfile::TempDir,
}
fn env() -> &'static Env {
static ENV: OnceLock<Env> = OnceLock::new();
ENV.get_or_init(|| {
let scratch: &'static tempfile::TempDir = Box::leak(Box::new(tempfile::tempdir().unwrap()));
let data = scratch.path().join("data");
fs::create_dir(&data).unwrap();
// SAFETY: set once, before any test of this binary reads the environment (they all
// wait on `lock()`, which calls `env()` first).
unsafe { std::env::set_var("XDG_DATA_HOME", &data) };
Env { data, scratch }
})
}
/// Serialises tests and starts each with an empty trash. Skips (None) when a per-mount trash
/// of the real user is visible, so a test can never delete real files.
fn lock() -> Option<(MutexGuard<'static, ()>, &'static Env)> {
static LOCK: Mutex<()> = Mutex::new(());
let guard = LOCK.lock().unwrap_or_else(|e| e.into_inner());
let env = env();
if trash::items()
.iter()
.any(|i| !i.uri.path().starts_with(b"/home:"))
{
eprintln!("skipped: a per-mount trash of this user exists");
return None;
}
let _ = fs::remove_dir_all(env.data.join("Trash"));
Some((guard, env))
}
fn run(kind: JobKind, action: ConflictAction) -> Report {
let (tx, events) = mpsc::channel();
let jobs = Jobs::new(Locations::with_local(), move |_, event| {
let _ = tx.send(event);
});
jobs.submit(kind);
for event in events {
match event {
JobEvent::Conflict(request) => request.reply.send(ConflictChoice {
action: action.clone(),
apply_to_all: false,
}),
JobEvent::Error(request) => request.reply.send(tunal_core::ops::ErrorAction::Skip),
JobEvent::Finished(report) => return report,
JobEvent::Progress(_) => {}
}
}
panic!("job worker stopped");
}
fn uri(p: &Path) -> Uri {
Uri::from_path(p)
}
fn trash_files(p: &[&Path]) -> Report {
run(
JobKind::Trash(p.iter().map(|p| uri(p)).collect()),
ConflictAction::Skip,
)
}
fn names(dir: &Path) -> Vec<String> {
let mut v: Vec<String> = fs::read_dir(dir)
.map(|d| {
d.map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
.collect()
})
.unwrap_or_default();
v.sort();
v
}
fn list(dir: &Uri) -> Vec<String> {
let mut names = Vec::new();
TrashLocation
.list(dir, &mut |chunk| {
names.extend(chunk.into_iter().map(|e| e.display_name));
ControlFlow::Continue(())
})
.unwrap();
names.sort();
names
}
#[test]
fn trash_writes_files_and_a_trashinfo() {
let Some((_guard, env)) = lock() else { return };
let dir = env.scratch.path().join("w1");
fs::create_dir(&dir).unwrap();
fs::write(dir.join("note.txt"), "hello").unwrap();
let report = trash_files(&[&dir.join("note.txt")]);
assert!(report.failures.is_empty());
assert!(!dir.join("note.txt").exists());
let trash_dir = env.data.join("Trash");
assert_eq!(
fs::read_to_string(trash_dir.join("files/note.txt")).unwrap(),
"hello"
);
let info = fs::read_to_string(trash_dir.join("info/note.txt.trashinfo")).unwrap();
let mut lines = info.lines();
assert_eq!(lines.next(), Some("[Trash Info]"));
assert_eq!(
lines.next().unwrap(),
format!("Path={}", dir.join("note.txt").display())
);
let date = lines.next().unwrap().strip_prefix("DeletionDate=").unwrap();
// 2026-11-19T10:20:30, local time, no zone.
assert_eq!(date.len(), 19);
assert_eq!(date.as_bytes()[10], b'T');
let items = trash::items();
assert_eq!(items.len(), 1);
assert_eq!(items[0].entry.display_name, "note.txt");
assert_eq!(items[0].original, uri(&dir.join("note.txt")));
let age = items[0].deleted.unwrap().elapsed().unwrap();
assert!(age.as_secs() < 60);
assert!(items[0].uri.path().starts_with(b"/home:note.txt"));
}
#[test]
fn trashinfo_percent_encodes_the_path() {
let Some((_guard, env)) = lock() else { return };
let dir = env.scratch.path().join("w2 dir");
fs::create_dir(&dir).unwrap();
let odd = dir.join(OsStr::from_bytes(b"100% odd \xff.txt"));
fs::write(&odd, "x").unwrap();
assert!(trash_files(&[&odd]).failures.is_empty());
let info_path = env
.data
.join("Trash/info")
.join(OsStr::from_bytes(b"100% odd \xff.txt.trashinfo"));
let info = fs::read(&info_path).unwrap();
let path_line = info
.split(|&b| b == b'\n')
.find(|l| l.starts_with(b"Path="))
.unwrap();
assert!(
path_line.ends_with(b"/w2%20dir/100%25%20odd%20%FF.txt"),
"{}",
String::from_utf8_lossy(path_line)
);
assert!(path_line.is_ascii());
// And it reads back to the raw bytes.
let item = &trash::items()[0];
assert_eq!(item.original, uri(&odd));
let report = run(
JobKind::Restore(vec![item.uri.clone()]),
ConflictAction::Skip,
);
assert!(report.failures.is_empty());
assert_eq!(fs::read(&odd).unwrap(), b"x");
assert!(trash::items().is_empty());
assert!(!info_path.exists());
}
#[test]
fn same_name_from_two_folders_gets_two_slots() {
let Some((_guard, env)) = lock() else { return };
let (a, b) = (env.scratch.path().join("c1"), env.scratch.path().join("c2"));
for (d, text) in [(&a, "from a"), (&b, "from b")] {
fs::create_dir(d).unwrap();
fs::write(d.join("dup.txt"), text).unwrap();
}
assert!(
trash_files(&[&a.join("dup.txt"), &b.join("dup.txt")])
.failures
.is_empty()
);
assert_eq!(
names(&env.data.join("Trash/files")),
["dup (2).txt", "dup.txt"]
);
assert_eq!(
names(&env.data.join("Trash/info")),
["dup (2).txt.trashinfo", "dup.txt.trashinfo"]
);
let items = trash::items();
assert_eq!(items.len(), 2);
assert!(items.iter().all(|i| i.entry.display_name == "dup.txt"));
let report = run(
JobKind::Restore(items.iter().map(|i| i.uri.clone()).collect()),
ConflictAction::Skip,
);
assert!(report.failures.is_empty());
assert_eq!(fs::read_to_string(a.join("dup.txt")).unwrap(), "from a");
assert_eq!(fs::read_to_string(b.join("dup.txt")).unwrap(), "from b");
}
#[test]
fn leftover_file_without_info_does_not_get_overwritten() {
let Some((_guard, env)) = lock() else { return };
let dir = env.scratch.path().join("l1");
fs::create_dir(&dir).unwrap();
let files = env.data.join("Trash/files");
fs::create_dir_all(&files).unwrap();
fs::write(files.join("x.txt"), "orphan").unwrap();
fs::write(dir.join("x.txt"), "new").unwrap();
assert!(trash_files(&[&dir.join("x.txt")]).failures.is_empty());
assert_eq!(fs::read_to_string(files.join("x.txt")).unwrap(), "orphan");
assert_eq!(fs::read_to_string(files.join("x (2).txt")).unwrap(), "new");
// The orphan has no info, so it is not listed.
assert_eq!(trash::items().len(), 1);
}
#[test]
fn restore_recreates_the_folder_and_handles_conflicts() {
let Some((_guard, env)) = lock() else { return };
let dir = env.scratch.path().join("r1");
fs::create_dir_all(dir.join("deep")).unwrap();
fs::write(dir.join("deep/f.txt"), "old").unwrap();
assert!(trash_files(&[&dir.join("deep/f.txt")]).failures.is_empty());
fs::remove_dir_all(dir.join("deep")).unwrap();
let item = trash::items().remove(0);
let report = run(
JobKind::Restore(vec![item.uri.clone()]),
ConflictAction::Skip,
);
assert!(report.failures.is_empty());
assert_eq!(fs::read_to_string(dir.join("deep/f.txt")).unwrap(), "old");
// Trash it again, make the target exist, and try each resolution.
assert!(trash_files(&[&dir.join("deep/f.txt")]).failures.is_empty());
fs::write(dir.join("deep/f.txt"), "blocker").unwrap();
let item = trash::items().remove(0);
let report = run(
JobKind::Restore(vec![item.uri.clone()]),
ConflictAction::Skip,
);
assert!(report.failures.is_empty());
assert_eq!(
fs::read_to_string(dir.join("deep/f.txt")).unwrap(),
"blocker"
);
assert_eq!(trash::items().len(), 1);
run(
JobKind::Restore(vec![item.uri.clone()]),
ConflictAction::Rename(b"back.txt".to_vec()),
);
assert_eq!(
fs::read_to_string(dir.join("deep/back.txt")).unwrap(),
"old"
);
assert!(trash::items().is_empty());
// Overwrite replaces the blocker.
assert!(
trash_files(&[&dir.join("deep/back.txt")])
.failures
.is_empty()
);
fs::write(dir.join("deep/back.txt"), "blocker").unwrap();
let item = trash::items().remove(0);
run(JobKind::Restore(vec![item.uri]), ConflictAction::Overwrite);
assert_eq!(
fs::read_to_string(dir.join("deep/back.txt")).unwrap(),
"old"
);
}
#[test]
fn trashed_folder_is_browsable_and_readable() {
let Some((_guard, env)) = lock() else { return };
let dir = env.scratch.path().join("b1");
fs::create_dir_all(dir.join("album/disc")).unwrap();
fs::write(dir.join("album/one.txt"), "1").unwrap();
fs::write(dir.join("album/disc/two.txt"), "22").unwrap();
assert!(trash_files(&[&dir.join("album")]).failures.is_empty());
assert_eq!(list(&trash::root()), ["album"]);
let top = trash::items().remove(0).uri;
assert_eq!(list(&top), ["disc", "one.txt"]);
let inner = top.join(b"disc").join(b"two.txt");
assert_eq!(TrashLocation.stat(&inner).unwrap().size, 2);
let mut text = String::new();
std::io::Read::read_to_string(&mut TrashLocation.open_read(&inner).unwrap(), &mut text)
.unwrap();
assert_eq!(text, "22");
// `..` can't climb out, odd URIs are not found.
assert_eq!(
TrashLocation.stat(&top.join(b"..").join(b"x")).err(),
Some(Error::PermissionDenied)
);
for bad in [
"trash:///nocolon",
"trash:///home:",
"trash:///nope:thing",
"trash:///zz:thing",
] {
assert_eq!(
TrashLocation.stat(&Uri::parse(bad).unwrap()).err(),
Some(Error::NotFound),
"{bad}"
);
}
assert_eq!(trash::original(&inner).err(), Some(Error::NotFound));
assert_eq!(trash::original(&top).unwrap(), uri(&dir.join("album")));
}
#[test]
fn copy_out_of_the_trash_uses_the_original_name() {
let Some((_guard, env)) = lock() else { return };
let dir = env.scratch.path().join("o1");
fs::create_dir_all(dir.join("out")).unwrap();
fs::write(dir.join("a.txt"), "data").unwrap();
assert!(trash_files(&[&dir.join("a.txt")]).failures.is_empty());
let item = trash::items().remove(0);
let report = run(
JobKind::Copy {
sources: vec![item.uri],
dest: uri(&dir.join("out")),
},
ConflictAction::Skip,
);
assert!(report.failures.is_empty());
assert_eq!(fs::read_to_string(dir.join("out/a.txt")).unwrap(), "data");
assert_eq!(trash::items().len(), 1);
}
#[test]
fn trashing_a_symlink_leaves_its_target() {
let Some((_guard, env)) = lock() else { return };
let dir = env.scratch.path().join("s1");
fs::create_dir(&dir).unwrap();
fs::write(dir.join("target"), "t").unwrap();
std::os::unix::fs::symlink("target", dir.join("link")).unwrap();
assert!(trash_files(&[&dir.join("link")]).failures.is_empty());
assert!(!dir.join("link").is_symlink());
assert_eq!(fs::read_to_string(dir.join("target")).unwrap(), "t");
let item = trash::items().remove(0);
assert_eq!(item.original, uri(&dir.join("link")));
run(JobKind::Restore(vec![item.uri]), ConflictAction::Skip);
assert_eq!(
fs::read_link(dir.join("link")).unwrap(),
Path::new("target")
);
}
#[test]
fn trashing_a_missing_file_fails() {
let Some((_guard, env)) = lock() else { return };
let report = trash_files(&[&env.scratch.path().join("nope")]);
assert_eq!(report.failures.len(), 1);
assert_eq!(report.failures[0].1, Error::NotFound);
}
#[test]
fn delete_from_the_trash_drops_the_info_file() {
let Some((_guard, env)) = lock() else { return };
let dir = env.scratch.path().join("d1");
fs::create_dir(&dir).unwrap();
fs::write(dir.join("gone.txt"), "x").unwrap();
trash_files(&[&dir.join("gone.txt")]);
let item = trash::items().remove(0);
let report = run(JobKind::Delete(vec![item.uri]), ConflictAction::Skip);
assert!(report.failures.is_empty());
let trash_dir = env.data.join("Trash");
assert!(names(&trash_dir.join("files")).is_empty());
assert!(names(&trash_dir.join("info")).is_empty());
}
#[test]
fn empty_trash_removes_everything() {
let Some((_guard, env)) = lock() else { return };
let dir = env.scratch.path().join("e1");
fs::create_dir_all(dir.join("folder/inner")).unwrap();
fs::write(dir.join("folder/inner/f"), "x").unwrap();
fs::write(dir.join("a"), "x").unwrap();
fs::write(dir.join("b"), "x").unwrap();
trash_files(&[&dir.join("folder"), &dir.join("a"), &dir.join("b")]);
assert_eq!(trash::items().len(), 3);
let report = run(JobKind::EmptyTrash, ConflictAction::Skip);
assert!(report.failures.is_empty() && !report.cancelled);
assert!(trash::items().is_empty());
let trash_dir = env.data.join("Trash");
assert!(names(&trash_dir.join("files")).is_empty());
assert!(names(&trash_dir.join("info")).is_empty());
}
#[test]
fn info_files_are_parsed_leniently() {
let Some((_guard, env)) = lock() else { return };
let root = env.data.join("Trash");
fs::create_dir_all(root.join("files")).unwrap();
fs::create_dir_all(root.join("info")).unwrap();
let put = |name: &str, info: &str| {
fs::write(root.join("files").join(name), "x").unwrap();
fs::write(root.join("info").join(format!("{name}.trashinfo")), info).unwrap();
};
// CRLF, unknown keys, another group first, no date.
put(
"crlf",
"[Other]\r\nPath=/wrong\r\n[Trash Info]\r\nPath=/tmp/x%20y\r\nExtra=1\r\n",
);
put("nopath", "[Trash Info]\nDeletionDate=2020-01-02T03:04:05\n");
put("garbage", "not an ini file");
let items = trash::items();
assert_eq!(items.len(), 1);
assert_eq!(items[0].original, Uri::from_path(Path::new("/tmp/x y")));
assert!(items[0].deleted.is_none());
}
#[test]
fn deletion_date_is_read_back() {
let Some((_guard, env)) = lock() else { return };
let root = env.data.join("Trash");
fs::create_dir_all(root.join("files")).unwrap();
fs::create_dir_all(root.join("info")).unwrap();
fs::write(root.join("files/old"), "x").unwrap();
fs::write(
root.join("info/old.trashinfo"),
"[Trash Info]\nPath=/tmp/old\nDeletionDate=2020-01-02T03:04:05\n",
)
.unwrap();
let item = trash::items().remove(0);
let when = jiff::Timestamp::try_from(item.deleted.unwrap())
.unwrap()
.to_zoned(jiff::tz::TimeZone::system());
assert_eq!(
when.strftime("%Y-%m-%dT%H:%M:%S").to_string(),
"2020-01-02T03:04:05"
);
}