use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;
use engine::{
AuthorizationData, AuthorizationPolicy, AuthorizationRequest, AuthorizationResult,
CreateOptions, Engine, Error, EventType, MetadataPatch, MetadataValue, Name, SubscriptionId,
Timestamp, VirtualPath,
};
fn new_engine() -> Arc<Engine> {
Arc::new(Engine::default())
}
fn name(value: &str) -> Name {
Name::new(value).expect("valid name")
}
#[derive(Default)]
struct DenyAll;
impl AuthorizationPolicy for DenyAll {
fn authorize(&self, _request: &AuthorizationRequest<'_>) -> AuthorizationResult {
AuthorizationResult::Denied {
reason: Some("denied by test policy".to_owned()),
}
}
}
#[test]
fn root_is_a_directory() {
let engine = new_engine();
let root = engine.root();
assert!(engine.exists(root));
assert_eq!(engine.metadata(None, root).unwrap().name().as_str(), "/");
assert!(engine.list(None, root).unwrap().is_empty());
}
#[test]
fn create_and_lookup_roundtrip() {
let engine = new_engine();
let root = engine.root();
let path = "/usr/bin/ls".parse::<VirtualPath>().unwrap();
let usr = engine.create_directory(None, root, name("usr")).unwrap();
let bin = engine.create_directory(None, usr, name("bin")).unwrap();
let ls = engine
.create_file(None, bin, name("ls"), Some(b"#!/bin/sh\n".to_vec()))
.unwrap();
assert_eq!(engine.lookup(None, &path).unwrap(), ls);
assert_eq!(engine.read(None, ls).unwrap().unwrap(), b"#!/bin/sh\n");
assert_eq!(engine.list(None, usr).unwrap(), vec![(name("bin"), bin)]);
}
#[test]
fn identity_survives_move() {
let engine = new_engine();
let root = engine.root();
let home = engine.create_directory(None, root, name("home")).unwrap();
let rey = engine.create_directory(None, home, name("rey")).unwrap();
let usr = engine.create_directory(None, root, name("usr")).unwrap();
let ls = engine.create_file(None, usr, name("ls"), None).unwrap();
let metadata_before = engine.metadata(None, ls).unwrap();
engine
.move_object(None, ls, rey, Some(name("my_ls")))
.unwrap();
let new_path = "/home/rey/my_ls".parse::<VirtualPath>().unwrap();
let old_path = "/usr/bin/ls".parse::<VirtualPath>().unwrap();
assert_eq!(
engine.lookup(None, &new_path).unwrap(),
ls,
"the moved object must keep its identity"
);
assert!(matches!(
engine.lookup(None, &old_path),
Err(Error::PathNotFound(_))
));
let metadata_after = engine.metadata(None, ls).unwrap();
assert_eq!(metadata_after.name().as_str(), "my_ls");
assert_eq!(metadata_after.created(), metadata_before.created());
assert_eq!(metadata_after.modified(), metadata_before.modified());
assert_eq!(metadata_after.accessed(), metadata_before.accessed());
assert_eq!(metadata_after.owner(), metadata_before.owner());
}
#[test]
fn move_rejects_cycles() {
let engine = new_engine();
let root = engine.root();
let a = engine.create_directory(None, root, name("a")).unwrap();
let b = engine.create_directory(None, a, name("b")).unwrap();
assert!(matches!(
engine.move_object(None, a, b, None),
Err(Error::CyclicMove(_))
));
assert!(matches!(
engine.move_object(None, a, a, None),
Err(Error::CyclicMove(_))
));
}
#[test]
fn move_rejects_name_conflicts() {
let engine = new_engine();
let root = engine.root();
let dir = engine.create_directory(None, root, name("dir")).unwrap();
engine.create_file(None, dir, name("a"), None).unwrap();
let b = engine.create_file(None, dir, name("b"), None).unwrap();
assert!(matches!(
engine.move_object(None, b, dir, Some(name("a"))),
Err(Error::NameAlreadyExists { .. })
));
}
#[test]
fn attach_rejects_an_attached_object() {
let engine = new_engine();
let root = engine.root();
let p = engine.create_directory(None, root, name("p")).unwrap();
let q = engine.create_directory(None, root, name("q")).unwrap();
let f = engine.create_file(None, p, name("f"), None).unwrap();
assert!(matches!(
engine.attach_object(None, f, q),
Err(Error::AttachedObject(_))
));
assert_eq!(engine.children(None, p).unwrap(), vec![f]);
assert!(engine.children(None, q).unwrap().is_empty());
}
#[test]
fn attach_rejects_cycles() {
let engine = new_engine();
let root = engine.root();
let a = engine.create_directory(None, root, name("a")).unwrap();
let b = engine.create_directory(None, a, name("b")).unwrap();
engine.detach_object(None, a).unwrap();
assert!(matches!(
engine.attach_object(None, a, b),
Err(Error::CyclicAttach(_))
));
assert!(matches!(
engine.attach_object(None, a, a),
Err(Error::CyclicAttach(_))
));
engine.attach_object(None, a, root).unwrap();
}
#[test]
fn moving_onto_itself_is_a_noop() {
let engine = new_engine();
let root = engine.root();
let dir = engine.create_directory(None, root, name("dir")).unwrap();
let f = engine.create_file(None, dir, name("f"), None).unwrap();
engine.move_object(None, f, dir, None).unwrap();
engine.move_object(None, f, dir, Some(name("f"))).unwrap();
assert_eq!(engine.metadata(None, f).unwrap().name().as_str(), "f");
}
#[test]
fn unsubscribing_during_dispatch_takes_effect_afterwards() {
use std::sync::{Arc, Mutex};
let engine = new_engine();
let root = engine.root();
let seen: Arc<Mutex<usize>> = Arc::new(Mutex::new(0));
let id_slot: Arc<Mutex<Option<SubscriptionId>>> = Arc::new(Mutex::new(None));
let seen_handle = Arc::clone(&seen);
let id_handle = Arc::clone(&id_slot);
let engine_handle = Arc::clone(&engine);
let subscription = engine.subscribe(None, move |_event| {
*seen_handle.lock().unwrap() += 1;
if let Some(id) = *id_handle.lock().unwrap() {
engine_handle.unsubscribe(id);
}
});
*id_slot.lock().unwrap() = Some(subscription);
engine.create_file(None, root, name("first"), None).unwrap();
engine
.create_file(None, root, name("second"), None)
.unwrap();
assert_eq!(
*seen.lock().unwrap(),
1,
"the self-unsubscribing listener fires exactly once"
);
assert_eq!(engine.listener_count(), 0, "the unsubscribe took effect");
}
#[test]
fn a_panicking_listener_is_contained() {
use std::sync::atomic::{AtomicUsize, Ordering};
let engine = new_engine();
let root = engine.root();
let _poison = engine.subscribe(None, |_event| panic!("a broken listener"));
let good_count = Arc::new(AtomicUsize::new(0));
let good = {
let count = Arc::clone(&good_count);
engine.subscribe(None, move |_event| {
count.fetch_add(1, Ordering::Relaxed);
})
};
let _ = good;
engine.create_file(None, root, name("f"), None).unwrap();
assert_eq!(
good_count.load(Ordering::Relaxed),
1,
"listeners after the broken one still observe events"
);
assert_eq!(
engine.listener_count(),
1,
"only the broken listener is evicted"
);
}
#[test]
fn an_invalid_extension_key_applies_nothing() {
let engine = new_engine();
let root = engine.root();
let file = engine.create_file(None, root, name("f"), None).unwrap();
let seed = MetadataPatch {
version: Some(Some("1.0".to_owned())),
..MetadataPatch::default()
};
engine.update_metadata(None, file, &seed).unwrap();
let patch = MetadataPatch {
version: Some(Some("2.0".to_owned())),
extensions: [(String::new(), Some(MetadataValue::Unsigned(1)))].into(),
..MetadataPatch::default()
};
assert!(engine.update_metadata(None, file, &patch).is_err());
let metadata = engine.metadata(None, file).unwrap();
assert_eq!(metadata.version(), Some("1.0"), "version untouched");
}
#[test]
fn root_cannot_be_moved_or_deleted() {
let engine = new_engine();
let root = engine.root();
assert!(matches!(
engine.move_object(None, root, root, None),
Err(Error::RootMove)
));
assert!(matches!(engine.delete(None, root), Err(Error::RootDelete)));
}
#[test]
fn copy_is_deep_and_independent() {
let engine = new_engine();
let root = engine.root();
let src = engine.create_directory(None, root, name("src")).unwrap();
let file = engine
.create_file(None, src, name("data.txt"), Some(b"hello".to_vec()))
.unwrap();
let backup = engine.create_directory(None, root, name("backup")).unwrap();
let copy = engine
.copy_object(None, src, backup, name("src_copy"))
.unwrap();
let copy_file = engine
.lookup(
None,
&"/backup/src_copy/data.txt".parse::<VirtualPath>().unwrap(),
)
.unwrap();
assert_ne!(copy, src);
assert_ne!(copy_file, file);
assert_eq!(engine.read(None, copy_file).unwrap().unwrap(), b"hello");
engine.write(None, copy_file, b"changed".to_vec()).unwrap();
assert_eq!(engine.read(None, file).unwrap().unwrap(), b"hello");
}
#[test]
fn copy_into_own_subtree_is_rejected() {
let engine = new_engine();
let root = engine.root();
let a = engine.create_directory(None, root, name("a")).unwrap();
let b = engine.create_directory(None, a, name("b")).unwrap();
assert!(matches!(
engine.copy_object(None, a, a, name("a2")),
Err(Error::CyclicCopy(_))
));
assert!(matches!(
engine.copy_object(None, a, b, name("a2")),
Err(Error::CyclicCopy(_))
));
}
#[test]
fn delete_removes_subtree_deepest_first() {
let engine = new_engine();
let root = engine.root();
let dir = engine.create_directory(None, root, name("dir")).unwrap();
let file = engine.create_file(None, dir, name("f"), None).unwrap();
let nested = engine.create_directory(None, dir, name("nested")).unwrap();
let leaf = engine
.create_file(None, nested, name("leaf"), None)
.unwrap();
let deleted: Arc<std::sync::Mutex<Vec<engine::ObjectId>>> =
Arc::new(std::sync::Mutex::new(Vec::new()));
let deleted_clone = Arc::clone(&deleted);
engine.subscribe(EventType::ObjectDeleted, move |event| {
deleted_clone.lock().unwrap().push(event.object);
});
engine.delete(None, dir).unwrap();
assert!(!engine.exists(dir));
assert!(!engine.exists(file));
assert!(!engine.exists(nested));
assert!(!engine.exists(leaf));
let order = deleted.lock().unwrap();
assert_eq!(&*order, &[file, leaf, nested, dir]);
}
#[test]
fn duplicate_names_are_rejected() {
let engine = new_engine();
let root = engine.root();
engine.create_file(None, root, name("a"), None).unwrap();
assert!(matches!(
engine.create_file(None, root, name("a"), None),
Err(Error::NameAlreadyExists { .. })
));
}
#[test]
fn metadata_only_files_report_declared_size() {
let engine = new_engine();
let root = engine.root();
let opaque = engine
.create_file(None, root, name("opaque.bundle"), None)
.unwrap();
engine
.update_metadata(
None,
opaque,
&MetadataPatch {
declared_size: Some(Some(4096)),
..MetadataPatch::default()
},
)
.unwrap();
assert_eq!(engine.size(None, opaque).unwrap(), 4096);
engine.write(None, opaque, vec![1, 2, 3]).unwrap();
assert_eq!(engine.size(None, opaque).unwrap(), 3);
}
#[test]
fn events_fire_synchronously_before_the_mutation_returns() {
let engine = new_engine();
let root = engine.root();
let file = engine
.create_file(None, root, name("file.txt"), None)
.unwrap();
let report = engine
.create_file(None, root, name("SCORING_REPORT"), None)
.unwrap();
let engine_clone = Arc::clone(&engine);
engine.subscribe(EventType::ObjectWritten, move |event| {
if event.object == file {
engine_clone
.write(
None,
report,
format!("scored after {:?}", event.event_type).into_bytes(),
)
.unwrap();
}
});
engine.write(None, file, b"new contents".to_vec()).unwrap();
let report_contents = engine.read(None, report).unwrap().unwrap();
assert_eq!(report_contents, b"scored after ObjectWritten");
}
#[test]
fn subscribing_during_dispatch_does_not_deadlock() {
let engine = new_engine();
let root = engine.root();
let file = engine.create_file(None, root, name("a.txt"), None).unwrap();
let engine_clone = Arc::clone(&engine);
engine.subscribe(EventType::ObjectWritten, move |_| {
engine_clone.subscribe(EventType::ObjectWritten, |_| {});
});
engine.write(None, file, vec![1]).unwrap();
assert_eq!(engine.subscribe(EventType::ObjectCreated, |_| {}).get(), 3);
}
#[test]
fn read_emits_object_read_events() {
let engine = new_engine();
let root = engine.root();
let file = engine
.create_file(None, root, name("f"), Some(b"x".to_vec()))
.unwrap();
let reads = Arc::new(AtomicUsize::new(0));
let reads_clone = Arc::clone(&reads);
engine.subscribe(EventType::ObjectRead, move |_| {
reads_clone.fetch_add(1, Ordering::Relaxed);
});
engine.read(None, file).unwrap();
engine.read(None, file).unwrap();
assert_eq!(reads.load(Ordering::Relaxed), 2);
}
#[test]
fn unsubscribing_stops_events() {
let engine = new_engine();
let root = engine.root();
let file = engine.create_file(None, root, name("f"), None).unwrap();
let writes = Arc::new(AtomicUsize::new(0));
let writes_clone = Arc::clone(&writes);
let subscription = engine.subscribe(EventType::ObjectWritten, move |_| {
writes_clone.fetch_add(1, Ordering::Relaxed);
});
engine.write(None, file, vec![1]).unwrap();
engine.unsubscribe(subscription);
engine.write(None, file, vec![2]).unwrap();
assert_eq!(writes.load(Ordering::Relaxed), 1);
}
#[test]
fn metadata_events_fire_for_patches() {
let engine = new_engine();
let root = engine.root();
let file = engine.create_file(None, root, name("f"), None).unwrap();
let owner_events = Arc::new(AtomicUsize::new(0));
let owner_events_clone = Arc::clone(&owner_events);
engine.subscribe(EventType::OwnerChanged, move |_| {
owner_events_clone.fetch_add(1, Ordering::Relaxed);
});
engine
.set_owner(None, file, Some(engine::ActorId::new(1000)))
.unwrap();
assert_eq!(owner_events.load(Ordering::Relaxed), 1);
assert_eq!(
engine.metadata(None, file).unwrap().owner(),
Some(engine::ActorId::new(1000))
);
engine
.update_metadata(
None,
file,
&MetadataPatch {
version: Some(Some("1.0".to_owned())),
extensions: [(
"kind".to_owned(),
Some(MetadataValue::String("bundle".to_owned())),
)]
.into(),
..MetadataPatch::default()
},
)
.unwrap();
let metadata = engine.metadata(None, file).unwrap();
assert_eq!(metadata.version(), Some("1.0"));
assert_eq!(
metadata.extension("kind"),
Some(&MetadataValue::String("bundle".to_owned()))
);
}
#[test]
fn denied_operations_fail_without_mutating_state() {
let engine = Arc::new(Engine::with_virtual_clock(Box::new(DenyAll)));
let root = engine.root();
let events = Arc::new(AtomicUsize::new(0));
let events_clone = Arc::clone(&events);
engine.subscribe(None, move |_| {
events_clone.fetch_add(1, Ordering::Relaxed);
});
let denied: Vec<Result<(), Error>> = vec![
engine.create_file(None, root, name("f"), None).map(|_| ()),
engine.create_directory(None, root, name("d")).map(|_| ()),
engine.read(None, root).map(|_| ()),
engine.metadata(None, root).map(|_| ()),
engine.delete(None, root).map(|_| ()),
];
for result in denied {
assert!(matches!(result, Err(Error::NotAuthorized { .. })));
}
assert_eq!(events.load(Ordering::Relaxed), 0);
}
#[test]
fn lookup_authorizes_traversal_before_the_final_object() {
struct DenyTraversal;
impl AuthorizationPolicy for DenyTraversal {
fn authorize(&self, request: &AuthorizationRequest<'_>) -> AuthorizationResult {
match request.operation {
engine::Operation::Execute => AuthorizationResult::Denied {
reason: Some("traversal forbidden".to_owned()),
},
_ => AuthorizationResult::Allowed,
}
}
}
let engine = Arc::new(Engine::with_virtual_clock(Box::new(DenyTraversal)));
let root = engine.root();
let dir = engine.create_directory(None, root, name("dir")).unwrap();
engine.create_file(None, dir, name("f"), None).unwrap();
engine
.lookup(None, &"/".parse::<VirtualPath>().unwrap())
.expect("the root has no components to traverse");
let error = engine
.lookup(None, &"/dir/f".parse::<VirtualPath>().unwrap())
.expect_err("traversal through dir is denied");
assert!(matches!(
error,
Error::NotAuthorized {
operation: engine::Operation::Execute,
..
}
));
}
#[test]
fn change_owner_is_a_distinct_operation() {
struct NoOwnerChanges;
impl AuthorizationPolicy for NoOwnerChanges {
fn authorize(&self, request: &AuthorizationRequest<'_>) -> AuthorizationResult {
match request.operation {
engine::Operation::ChangeOwner => AuthorizationResult::Denied {
reason: Some("owner changes forbidden".to_owned()),
},
_ => AuthorizationResult::Allowed,
}
}
}
let engine = Arc::new(Engine::with_virtual_clock(Box::new(NoOwnerChanges)));
let root = engine.root();
let file = engine.create_file(None, root, name("f"), None).unwrap();
let owner_change = engine.set_owner(None, file, Some(engine::ActorId::new(7)));
assert!(matches!(owner_change, Err(Error::NotAuthorized { .. })));
let metadata_change = engine.touch(None, file);
assert!(metadata_change.is_ok());
}
#[test]
fn create_with_options_sets_owner_and_authorization_atomically() {
let engine = new_engine();
let root = engine.root();
let options = CreateOptions {
owner: Some(engine::ActorId::new(501)),
authorization: {
let mut data = AuthorizationData::new();
data.insert("mode", "755");
data
},
};
let file = engine
.create_file_with_options(None, root, name("f"), Some(b"x".to_vec()), options)
.unwrap();
let metadata = engine.metadata(None, file).unwrap();
assert_eq!(metadata.owner(), Some(engine::ActorId::new(501)));
assert_eq!(metadata.authorization().get("mode"), Some("755"));
}
#[test]
fn replace_file_with_options_commits_content_and_metadata_together() {
let engine = new_engine();
let file = engine
.create_file(None, engine.root(), name("f"), Some(b"old".to_vec()))
.unwrap();
let mut authorization = AuthorizationData::new();
authorization.insert("mode", "600");
engine
.replace_file_with_options(
None,
file,
b"new".to_vec(),
CreateOptions {
owner: Some(engine::ActorId::new(501)),
authorization,
},
)
.unwrap();
assert_eq!(engine.read(None, file).unwrap().unwrap(), b"new");
let metadata = engine.metadata(None, file).unwrap();
assert_eq!(metadata.owner(), Some(engine::ActorId::new(501)));
assert_eq!(metadata.authorization().get("mode"), Some("600"));
}
#[test]
fn create_with_options_is_authorization_checked_like_create() {
let engine = Arc::new(Engine::with_virtual_clock(Box::new(DenyAll)));
let result = engine.create_directory_with_options(
None,
engine.root(),
name("d"),
CreateOptions::default(),
);
assert!(matches!(result, Err(Error::NotAuthorized { .. })));
}
#[test]
fn copy_events_carry_the_source() {
let engine = new_engine();
let root = engine.root();
let dir = engine.create_directory(None, root, name("dir")).unwrap();
engine.create_file(None, dir, name("f"), None).unwrap();
let copies: Arc<std::sync::Mutex<Vec<engine::ObjectEvent>>> =
Arc::new(std::sync::Mutex::new(Vec::new()));
let copies_clone = Arc::clone(&copies);
engine.subscribe(EventType::ObjectCopied, move |event| {
copies_clone.lock().unwrap().push(event.clone());
});
let backup = engine.create_directory(None, root, name("backup")).unwrap();
engine
.copy_object(None, dir, backup, name("dir_copy"))
.unwrap();
let copy_event = &copies.lock().unwrap()[0];
assert_eq!(
copy_event.data.get("source"),
Some(&MetadataValue::Unsigned(dir.get()))
);
}
#[test]
fn detached_namespaces_are_invisible_from_the_root() {
let engine = new_engine();
let root = engine.root();
let namespace = engine
.create_detached_namespace(None, name("processes"))
.unwrap();
let proc = engine
.create_file(None, namespace.id(), name("4812"), None)
.unwrap();
assert!(engine.exists(proc));
assert!(matches!(
engine.lookup(None, &"/processes/4812".parse::<VirtualPath>().unwrap()),
Err(Error::PathNotFound(_))
));
assert!(engine.list(None, root).unwrap().is_empty());
engine.write(None, proc, b"running".to_vec()).unwrap();
assert_eq!(engine.read(None, proc).unwrap().unwrap(), b"running");
}
#[test]
fn detach_and_attach_move_objects_between_tree_and_store() {
let engine = new_engine();
let root = engine.root();
let file = engine.create_file(None, root, name("f"), None).unwrap();
let mnt = engine.create_directory(None, root, name("mnt")).unwrap();
engine.detach_object(None, file).unwrap();
assert_eq!(engine.parent(None, file).unwrap(), None);
assert!(matches!(
engine.lookup(None, &"/f".parse::<VirtualPath>().unwrap()),
Err(Error::PathNotFound(_))
));
engine.attach_object(None, file, mnt).unwrap();
assert_eq!(
engine
.lookup(None, &"/mnt/f".parse::<VirtualPath>().unwrap())
.unwrap(),
file
);
}
#[test]
fn virtual_clock_is_frozen_until_advanced() {
let engine = new_engine();
let root = engine.root();
engine.set_time(Timestamp::from_nanos(1_000));
let file = engine.create_file(None, root, name("f"), None).unwrap();
let created = engine.metadata(None, file).unwrap().created();
assert_eq!(created, Timestamp::from_nanos(1_000));
engine.advance_time(Duration::from_secs(10));
engine.write(None, file, vec![1]).unwrap();
let metadata = engine.metadata(None, file).unwrap();
assert_eq!(metadata.created(), created);
assert_eq!(metadata.modified(), Timestamp::from_nanos(10_000_001_000));
}
#[test]
fn read_does_not_update_access_time() {
let engine = new_engine();
let root = engine.root();
let file = engine.create_file(None, root, name("f"), None).unwrap();
engine.advance_time(Duration::from_secs(60));
engine.read(None, file).unwrap();
let metadata = engine.metadata(None, file).unwrap();
assert_eq!(metadata.accessed(), metadata.created());
}
#[test]
fn suspended_time_advances_locally_but_not_the_shared_timeline() {
let engine = new_engine();
engine.set_time(Timestamp::from_nanos(1_000));
let (observed, consumed) = Engine::suspend_time(|| {
engine.advance_time(Duration::from_secs(30));
engine.time()
});
assert_eq!(observed, Timestamp::from_nanos(30_000_001_000));
assert_eq!(consumed, Duration::from_secs(30));
assert_eq!(engine.time(), Timestamp::from_nanos(1_000));
}
#[test]
fn nested_suspensions_each_report_their_own_consumed_time() {
let engine = new_engine();
let (outer_result, outer_elapsed) = Engine::suspend_time(|| {
engine.advance_time(Duration::from_secs(5));
let (inner_result, inner_elapsed) = Engine::suspend_time(|| {
engine.advance_time(Duration::from_secs(2));
engine.time()
});
assert_eq!(inner_result, Timestamp::from_nanos(7_000_000_000));
assert_eq!(inner_elapsed, Duration::from_secs(2));
engine.advance_time(Duration::from_secs(1));
"outer"
});
assert_eq!(outer_result, "outer");
assert_eq!(
outer_elapsed,
Duration::from_secs(8),
"the enclosing scope also covers the time its inner scope ran"
);
assert_eq!(engine.time(), Timestamp::ZERO);
}
#[test]
fn suspension_does_not_leak_when_the_closure_panics() {
let engine = new_engine();
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let _ = Engine::suspend_time(|| {
engine.advance_time(Duration::from_secs(9));
panic!("a crashing command must not strand the timeline");
});
}));
assert!(result.is_err());
engine.advance_time(Duration::from_secs(1));
assert_eq!(engine.time(), Timestamp::from_nanos(1_000_000_000));
}
#[test]
fn lookup_follows_symlinks_to_their_targets() {
let engine = new_engine();
let root = engine.root();
let private = engine
.create_directory(None, root, name("private"))
.unwrap();
let etc = engine.create_directory(None, private, name("etc")).unwrap();
engine
.create_file(None, etc, name("hosts"), Some(b"127.0.0.1".to_vec()))
.unwrap();
engine
.create_symlink(None, root, name("etc"), "/private/etc".to_owned())
.unwrap();
let hosts = engine.lookup(None, &"/etc/hosts".parse().unwrap()).unwrap();
assert_eq!(
engine.read(None, hosts).unwrap(),
Some(b"127.0.0.1".to_vec()),
"reading through the link reaches the target"
);
let resolved_etc = engine.lookup(None, &"/etc".parse().unwrap()).unwrap();
assert_eq!(
resolved_etc, etc,
"the final component follows too (stat semantics)"
);
assert_eq!(engine.children(None, resolved_etc).unwrap().len(), 1);
}
#[test]
fn relative_symlinks_resolve_against_the_link_parent() {
let engine = new_engine();
let root = engine.root();
let a = engine.create_directory(None, root, name("a")).unwrap();
engine
.create_file(None, a, name("f"), Some(vec![1]))
.unwrap();
engine
.create_symlink(None, a, name("link"), "f".to_owned())
.unwrap();
let object = engine.lookup(None, &"/a/link".parse().unwrap()).unwrap();
assert_eq!(engine.read(None, object).unwrap(), Some(vec![1]));
}
#[test]
fn symlink_loops_fail_with_the_depth_error() {
let engine = new_engine();
let root = engine.root();
let a = engine.create_directory(None, root, name("a")).unwrap();
engine
.create_symlink(None, a, name("loop"), "/a/loop".to_owned())
.unwrap();
assert!(matches!(
engine.lookup(None, &"/a/loop".parse().unwrap()),
Err(Error::SymlinkLoop(_))
));
}
#[test]
fn symlink_operations_follow_stat_semantics() {
let engine = new_engine();
let root = engine.root();
let d = engine.create_directory(None, root, name("d")).unwrap();
let target = engine
.create_file(None, d, name("f"), Some(vec![1, 2]))
.unwrap();
let link = engine
.create_symlink(None, root, name("link"), "/d/f".to_owned())
.unwrap();
assert_eq!(
engine.read_link(None, link).unwrap(),
Some("/d/f".to_owned())
);
assert!(engine.is_link(None, link).unwrap());
assert_eq!(engine.size(None, link).unwrap(), 2);
assert_eq!(engine.size(None, target).unwrap(), 2);
assert_eq!(engine.read(None, link).unwrap(), Some(vec![1, 2]));
engine.write(None, link, vec![3]).unwrap();
assert_eq!(engine.read(None, target).unwrap(), Some(vec![3]));
engine.append(None, link, vec![4]).unwrap();
assert_eq!(engine.read(None, target).unwrap(), Some(vec![3, 4]));
engine.touch(None, link).unwrap();
assert_eq!(
engine
.lookup_no_follow(None, &"/link".parse().unwrap())
.unwrap(),
link
);
assert!(!engine.is_link(None, target).unwrap());
}
#[test]
fn deleting_a_symlink_removes_the_link_not_the_target() {
let engine = new_engine();
let root = engine.root();
let d = engine.create_directory(None, root, name("d")).unwrap();
let _target = engine
.create_file(None, d, name("f"), Some(vec![1]))
.unwrap();
let link = engine
.create_symlink(None, root, name("link"), "/d/f".to_owned())
.unwrap();
engine.delete(None, link).unwrap();
assert!(engine.lookup(None, &"/link".parse().unwrap()).is_err());
assert!(engine.lookup(None, &"/d/f".parse().unwrap()).is_ok());
}
#[test]
fn resolve_links_walks_a_chain_of_links() {
let engine = new_engine();
let root = engine.root();
let target = engine
.create_file(None, root, name("f"), Some(vec![1]))
.unwrap();
let _link = engine
.create_symlink(None, root, name("one"), "/f".to_owned())
.unwrap();
let link_two = engine
.create_symlink(None, root, name("two"), "/one".to_owned())
.unwrap();
assert_eq!(engine.resolve_links(link_two).unwrap(), target);
assert_eq!(engine.resolve_links(target).unwrap(), target);
}