Tunal/crates/tunal-core/tests/location.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

251 lines
8.2 KiB
Rust

//! URIs, local listing edge cases and watching, all inside temp dirs.
use std::ffi::OsStr;
use std::fs;
use std::ops::ControlFlow;
use std::os::unix::ffi::OsStrExt;
use std::os::unix::fs::PermissionsExt;
use std::sync::mpsc;
use std::time::Duration;
use tunal_core::{
Error, Kind, LocalLocation, Location, Locations, Uri, WatchEvent, WriteMode, display_name,
};
fn list(dir: &std::path::Path) -> tunal_core::Result<Vec<tunal_core::Entry>> {
let mut all = Vec::new();
LocalLocation.list(&Uri::from_path(dir), &mut |chunk| {
all.extend(chunk);
ControlFlow::Continue(())
})?;
Ok(all)
}
#[test]
fn uri_parse_display_round_trip() {
let uri = Uri::new("file", "", b"/tmp/a b/\xff%.txt".to_vec());
let text = uri.to_string();
assert_eq!(text, "file:///tmp/a%20b/%FF%25.txt");
assert_eq!(Uri::parse(&text), Some(uri));
}
#[test]
fn uri_parts() {
let uri = Uri::parse("SFTP://host/a/b/").unwrap();
assert_eq!(uri.scheme(), "sftp");
assert_eq!(uri.authority(), "host");
assert_eq!(uri.file_name(), Some(&b"b"[..]));
assert_eq!(uri.parent().unwrap().path(), b"/a");
assert_eq!(uri.join(b"c").path(), b"/a/b/c");
let root = Uri::parse("file:///").unwrap();
assert_eq!(root.file_name(), None);
assert_eq!(root.parent(), None);
assert_eq!(root.join(b"x").path(), b"/x");
// Empty path becomes the root.
assert_eq!(Uri::parse("trash://").unwrap().path(), b"/");
}
#[test]
fn uri_parse_rejects_bad_input() {
assert!(Uri::parse("no scheme").is_none());
assert!(Uri::parse("1ab://x/").is_none());
assert!(Uri::parse("file:///bad%2").is_none());
assert!(Uri::parse("file:///bad%zz").is_none());
}
#[test]
fn uri_path_conversion() {
let uri = Uri::from_path(std::path::Path::new("/tmp/x"));
assert_eq!(uri.to_path().unwrap(), std::path::Path::new("/tmp/x"));
assert!(Uri::new("sftp", "h", "/x").to_path().is_none());
}
#[test]
fn registry_resolves_by_scheme() {
let locations = Locations::with_local();
assert!(locations.resolve(&Uri::parse("file:///").unwrap()).is_ok());
assert!(locations.resolve(&Uri::parse("TRASH:///").unwrap()).is_ok());
assert_eq!(
locations.resolve(&Uri::parse("sftp://h/").unwrap()).err(),
Some(Error::Unsupported)
);
}
#[test]
fn lists_non_utf8_names_and_hidden() {
let dir = tempfile::tempdir().unwrap();
let odd = OsStr::from_bytes(b"odd \xff name");
fs::write(dir.path().join(odd), "x").unwrap();
fs::write(dir.path().join(".hidden"), "x").unwrap();
let mut entries = list(dir.path()).unwrap();
entries.sort_by(|a, b| a.name.cmp(&b.name));
assert_eq!(entries.len(), 2);
assert!(entries[0].hidden && entries[0].name == b".hidden");
assert_eq!(entries[1].name, b"odd \xff name");
assert_eq!(entries[1].display_name, display_name(b"odd \xff name"));
assert!(!entries[1].hidden);
// stat through a URI built from the raw name finds it.
let uri = Uri::from_path(dir.path()).join(b"odd \xff name");
assert_eq!(LocalLocation.stat(&uri).unwrap().size, 1);
}
#[test]
fn symlinks_are_not_followed() {
let dir = tempfile::tempdir().unwrap();
fs::create_dir(dir.path().join("folder")).unwrap();
std::os::unix::fs::symlink("folder", dir.path().join("to-dir")).unwrap();
std::os::unix::fs::symlink("missing", dir.path().join("broken")).unwrap();
let entries = list(dir.path()).unwrap();
let find = |n: &[u8]| entries.iter().find(|e| e.name == n).unwrap();
assert!(matches!(
&find(b"to-dir").kind,
Kind::Symlink { target, target_type: Some(_) } if target == b"folder"
));
assert!(find(b"to-dir").kind.is_dir());
assert!(matches!(
&find(b"broken").kind,
Kind::Symlink {
target_type: None,
..
}
));
assert!(!find(b"broken").kind.is_dir());
assert_eq!(find(b"folder").kind, Kind::Dir);
}
#[test]
fn permission_denied_folder() {
let dir = tempfile::tempdir().unwrap();
let locked = dir.path().join("locked");
fs::create_dir(&locked).unwrap();
fs::set_permissions(&locked, fs::Permissions::from_mode(0o000)).unwrap();
let result = list(&locked);
fs::set_permissions(&locked, fs::Permissions::from_mode(0o755)).unwrap();
// Root ignores modes; only check when the kernel really denied it.
if let Err(e) = result {
assert_eq!(e, Error::PermissionDenied);
assert!(e.needs_elevation());
}
// The folder itself is still listed and stat-able from its parent.
assert!(
list(dir.path())
.unwrap()
.iter()
.any(|e| e.name == b"locked")
);
}
#[test]
fn missing_folder_is_not_found() {
let dir = tempfile::tempdir().unwrap();
assert_eq!(list(&dir.path().join("nope")).err(), Some(Error::NotFound));
assert_eq!(
LocalLocation
.stat(&Uri::from_path(&dir.path().join("nope")))
.err(),
Some(Error::NotFound)
);
}
#[test]
fn ten_thousand_entries_arrive_in_chunks() {
let dir = tempfile::tempdir().unwrap();
for i in 0..10_000 {
fs::File::create(dir.path().join(format!("f{i:05}"))).unwrap();
}
let mut chunks = 0;
let mut total = 0;
LocalLocation
.list(&Uri::from_path(dir.path()), &mut |chunk| {
chunks += 1;
total += chunk.len();
ControlFlow::Continue(())
})
.unwrap();
assert_eq!(total, 10_000);
assert!(chunks > 1);
}
#[test]
fn breaking_the_sink_cancels_the_listing() {
let dir = tempfile::tempdir().unwrap();
for i in 0..1000 {
fs::File::create(dir.path().join(format!("f{i}"))).unwrap();
}
let mut calls = 0;
let result = LocalLocation.list(&Uri::from_path(dir.path()), &mut |_| {
calls += 1;
ControlFlow::Break(())
});
assert_eq!(result.err(), Some(Error::Cancelled));
assert_eq!(calls, 1);
}
#[test]
fn write_modes_rename_and_delete() {
use std::io::Write;
let dir = tempfile::tempdir().unwrap();
let a = Uri::from_path(&dir.path().join("a"));
let b = Uri::from_path(&dir.path().join("b"));
let mut w = LocalLocation.open_write(&a, WriteMode::CreateNew).unwrap();
w.write_all(b"one").unwrap();
drop(w);
assert_eq!(
LocalLocation.open_write(&a, WriteMode::CreateNew).err(),
Some(Error::Exists)
);
let mut w = LocalLocation.open_write(&a, WriteMode::Overwrite).unwrap();
w.write_all(b"2").unwrap();
drop(w);
assert_eq!(fs::read(dir.path().join("a")).unwrap(), b"2");
fs::write(dir.path().join("b"), "keep").unwrap();
assert_eq!(LocalLocation.rename(&a, &b).err(), Some(Error::Exists));
assert_eq!(fs::read(dir.path().join("b")).unwrap(), b"keep");
LocalLocation.delete(&b).unwrap();
assert_eq!(LocalLocation.delete(&b).err(), Some(Error::NotFound));
let sub = Uri::from_path(&dir.path().join("sub"));
LocalLocation.mkdir(&sub).unwrap();
assert_eq!(LocalLocation.mkdir(&sub).err(), Some(Error::Exists));
fs::write(dir.path().join("sub/x"), "").unwrap();
assert_eq!(LocalLocation.delete(&sub).err(), Some(Error::NotEmpty));
}
#[test]
fn watch_reports_created_and_removed() {
let dir = tempfile::tempdir().unwrap();
let (tx, rx) = mpsc::channel();
let _watch = LocalLocation
.watch(
&Uri::from_path(dir.path()),
Box::new(move |event| {
let _ = tx.send(event);
}),
)
.unwrap();
let file = dir.path().join("new.txt");
fs::write(&file, "x").unwrap();
let expect = |rx: &mpsc::Receiver<WatchEvent>| loop {
match rx
.recv_timeout(Duration::from_secs(5))
.expect("watch event")
{
WatchEvent::Changed(uris)
if uris.iter().any(|u| u.to_path().as_deref() == Some(&file)) =>
{
return;
}
WatchEvent::Changed(_) => {}
WatchEvent::Error(e) => panic!("watch error: {e}"),
}
};
expect(&rx);
fs::remove_file(&file).unwrap();
expect(&rx);
}
#[test]
fn watch_of_missing_folder_fails() {
let dir = tempfile::tempdir().unwrap();
let result = LocalLocation.watch(&Uri::from_path(&dir.path().join("nope")), Box::new(|_| {}));
assert!(result.is_err());
}