rcom/tests/app_preview.rs

339 lines
13 KiB
Rust

use std::sync::Arc;
use async_trait::async_trait;
use pretty_assertions::assert_eq;
use rcom::app::preview::execute_preview;
use rcom::app::{AppState, Command, Effect, ListingRequest, PaneId, PreviewRequest};
use rcom::domain::{Entry, EntryKind, Location};
use rcom::fs::{FsError, ReadFileSystem, ReadPrefix};
use rcom::preview::{MAX_PREVIEW_BYTES, Preview, PreviewKind, preview_bytes};
use rcom::test_support::{FaultInjectFs, FsOperation, MemoryFs, RecordingFs};
fn one_listing(effects: Vec<Effect>) -> ListingRequest {
let effects: [Effect; 1] = effects.try_into().expect("one listing effect");
let [Effect::LoadListing(request)] = effects else {
panic!("expected exactly one listing effect");
};
request
}
fn one_preview(effects: Vec<Effect>) -> PreviewRequest {
let effects: [Effect; 1] = effects.try_into().expect("one preview effect");
let mut effects = effects.into_iter();
let Some(effect) = effects.next() else {
panic!("expected exactly one preview effect");
};
assert!(
effects.next().is_none(),
"expected exactly one preview effect"
);
match effect {
Effect::LoadPreview(request) | Effect::DebouncePreview(request) => request,
_ => panic!("expected a preview effect"),
}
}
fn poll_preview(app: &mut AppState, entries: Vec<Entry>) -> PreviewRequest {
let listing = one_listing(app.reduce(Command::RefreshPane(PaneId::Left)));
one_preview(app.reduce(Command::ListingFinished(listing.into_result(Ok(entries)))))
}
fn request(target: Location) -> PreviewRequest {
PreviewRequest {
pane: PaneId::Left,
generation: 7,
target,
session_epoch: None,
images_enabled: true,
}
}
#[tokio::test]
async fn text_preview_effect_renders_bounded_sanitized_text() {
let location = Location::local("/notes.txt");
let mut contents = b"hello\t\xff\n".to_vec();
contents.resize(MAX_PREVIEW_BYTES + 128, b'x');
let recording = RecordingFs::new(Arc::new(
MemoryFs::new().with_file(location.clone(), contents),
));
let result = execute_preview(request(location.clone()), &recording).await;
let preview = result.result.expect("text preview");
assert_eq!(result.target, location);
assert_eq!(preview.kind, PreviewKind::Text);
assert!(preview.truncated);
assert!(preview.lines[0].contains("hello\\t"));
assert!(preview.lines[0].contains('\u{fffd}'));
assert_eq!(
preview.lines.last().map(String::as_str),
Some("… truncated …")
);
let operations = recording.operations();
assert_eq!(operations.len(), 2);
assert_eq!(operations[0].operation, FsOperation::Metadata);
assert_eq!(operations[1].operation, FsOperation::ReadPrefix);
assert_eq!(operations[1].limit, Some(MAX_PREVIEW_BYTES));
}
#[tokio::test]
async fn directory_preview_does_not_execute_or_recurse() {
let location = Location::local("/directory");
let fs = MemoryFs::new()
.with_dir(Location::local("/directory/nested"))
.with_file(
Location::local("/directory/nested/hidden-child"),
"not previewed",
)
.with_file(Location::local("/directory/file.txt"), "not read");
let recording = RecordingFs::new(Arc::new(fs));
let result = execute_preview(request(location), &recording).await;
let preview = result.result.expect("directory preview");
assert_eq!(preview.kind, PreviewKind::Directory);
assert_eq!(preview.lines, ["nested/", "file.txt"]);
assert!(
!preview
.lines
.iter()
.any(|line| line.contains("hidden-child"))
);
let operations = recording.operations();
assert_eq!(operations.len(), 2);
assert_eq!(operations[0].operation, FsOperation::Metadata);
assert_eq!(operations[1].operation, FsOperation::List);
assert_eq!(
operations[1].limit,
Some(rcom::preview::DIRECTORY_PREVIEW_LIMIT + 1)
);
}
#[tokio::test]
async fn binary_selection_shows_metadata_placeholder() {
let location = Location::local("/blob.bin");
let fs = MemoryFs::new().with_file(location.clone(), [0, 1, 2, 3]);
let result = execute_preview(request(location), &fs).await;
let preview = result.result.expect("binary placeholder");
assert_eq!(preview.kind, PreviewKind::Binary);
assert!(preview.lines[0].contains("Binary or unsupported"));
assert!(preview.lines.iter().any(|line| line == "Name: blob.bin"));
assert!(preview.lines.iter().any(|line| line == "Size: 4 bytes"));
}
#[test]
fn stale_preview_response_is_not_applied() {
let mut app = AppState::new(Location::local("/workspace"));
let listing = one_listing(app.reduce(Command::Refresh));
let old_request = one_preview(app.reduce(Command::ListingFinished(listing.into_result(Ok(
vec![
Entry::new("a-old.txt", EntryKind::File),
Entry::new("z-new.txt", EntryKind::File),
],
)))));
let new_request = one_preview(app.reduce(Command::MoveSelection(1)));
assert_eq!(old_request.target, Location::local("/workspace/a-old.txt"));
assert_eq!(new_request.target, Location::local("/workspace/z-new.txt"));
assert_ne!(old_request.generation, new_request.generation);
let new_preview = preview_bytes(b"new contents", false);
app.reduce(Command::PreviewFinished(
new_request.clone().into_result(Ok(new_preview.clone())),
));
let stale_effects = app.reduce(Command::PreviewFinished(
old_request.into_result(Ok(preview_bytes(b"stale contents", false))),
));
assert!(stale_effects.is_empty());
assert_eq!(app.active_pane().preview.target, new_request.target.into());
assert_eq!(app.active_pane().preview.content, Some(new_preview));
assert!(!app.active_pane().preview.loading);
}
#[test]
fn background_preview_requires_a_completed_result_for_the_same_target() {
let mut app = AppState::new(Location::local("/workspace"));
let entries = vec![
Entry::new("a.txt", EntryKind::File),
Entry::new("z.txt", EntryKind::File),
];
let initial = one_listing(app.reduce(Command::Refresh));
let initial_preview = one_preview(app.reduce(Command::ListingFinished(
initial.into_result(Ok(entries.clone())),
)));
assert!(!app.active_pane().preview.background_refresh);
assert!(app.active_pane().preview.content.is_none());
// A poll cannot hide an initial request which has not produced content or an error yet.
let poll = one_listing(app.reduce(Command::RefreshPane(PaneId::Left)));
let duplicate = app.reduce(Command::ListingFinished(
poll.into_result(Ok(entries.clone())),
));
assert!(
duplicate.is_empty(),
"an in-flight initial preview is not duplicated"
);
let pending = initial_preview.clone();
assert!(!app.active_pane().preview.background_refresh);
app.reduce(Command::PreviewFinished(
pending.into_result(Ok(preview_bytes(b"completed", false))),
));
let poll = one_listing(app.reduce(Command::RefreshPane(PaneId::Left)));
let background = one_preview(app.reduce(Command::ListingFinished(
poll.into_result(Ok(entries.clone())),
)));
assert!(app.active_pane().preview.background_refresh);
assert!(app.active_pane().preview.content.is_some());
assert_eq!(background.target, Location::local("/workspace/a.txt"));
assert!(background.generation > initial_preview.generation);
let foreground = one_preview(app.reduce(Command::MoveSelection(1)));
assert!(!app.active_pane().preview.background_refresh);
assert!(app.active_pane().preview.content.is_none());
assert_eq!(foreground.target, Location::local("/workspace/z.txt"));
app.reduce(Command::PreviewFinished(
foreground.into_result(Ok(preview_bytes(b"new selection", false))),
));
app.reduce(Command::OpenPreview);
assert!(!app.active_pane().preview.background_refresh);
assert!(app.active_pane().preview.content.is_none());
let poll = one_listing(app.reduce(Command::RefreshPane(PaneId::Left)));
assert!(
app.reduce(Command::ListingFinished(poll.into_result(Ok(Vec::new()))))
.is_empty()
);
assert_eq!(app.active_pane().preview.target, None);
assert!(!app.active_pane().preview.background_refresh);
}
#[test]
fn background_preview_responses_are_current_only_and_recover_atomically() {
let mut app = AppState::new(Location::local("/workspace"));
let entries = vec![Entry::new("a.txt", EntryKind::File)];
let initial = one_listing(app.reduce(Command::Refresh));
let initial_preview = one_preview(app.reduce(Command::ListingFinished(
initial.into_result(Ok(entries.clone())),
)));
app.reduce(Command::PreviewFinished(
initial_preview.into_result(Ok(preview_bytes(b"stable", false))),
));
let first = poll_preview(&mut app, entries.clone());
let second = poll_preview(&mut app, entries.clone());
assert!(app.active_pane().preview.background_refresh);
assert!(
app.reduce(Command::PreviewFinished(
first.into_result(Ok(preview_bytes(b"stale", false))),
))
.is_empty()
);
assert!(app.active_pane().preview.background_refresh);
assert!(app.active_pane().preview.loading);
assert_eq!(
app.active_pane().preview.content,
Some(preview_bytes(b"stable", false))
);
app.reduce(Command::PreviewFinished(
second.into_result(Ok(preview_bytes(b"current", false))),
));
assert!(!app.active_pane().preview.background_refresh);
assert!(!app.active_pane().preview.loading);
assert_eq!(
app.active_pane().preview.content,
Some(preview_bytes(b"current", false))
);
let failing = poll_preview(&mut app, entries.clone());
app.reduce(Command::PreviewFinished(
failing.into_result(Err(FsError::PermissionDenied)),
));
assert!(!app.active_pane().preview.background_refresh);
assert!(app.active_pane().preview.content.is_none());
assert_eq!(
app.active_pane().preview.error,
Some(FsError::PermissionDenied)
);
let recovery = poll_preview(&mut app, entries);
assert!(app.active_pane().preview.background_refresh);
assert_eq!(
app.active_pane().preview.error,
Some(FsError::PermissionDenied)
);
app.reduce(Command::PreviewFinished(
recovery.into_result(Ok(preview_bytes(b"recovered", false))),
));
assert!(!app.active_pane().preview.background_refresh);
assert!(app.active_pane().preview.error.is_none());
assert_eq!(
app.active_pane().preview.content,
Some(preview_bytes(b"recovered", false))
);
}
#[tokio::test]
async fn preview_executor_preserves_typed_filesystem_errors() {
let missing = execute_preview(request(Location::local("/missing")), &MemoryFs::new()).await;
assert_eq!(missing.result, Err(FsError::NotFound));
let file = Location::local("/denied.txt");
let read_fault = FaultInjectFs::new(Arc::new(MemoryFs::new().with_file(file.clone(), "data")));
read_fault.fail_next(FsOperation::ReadPrefix, FsError::PermissionDenied);
let denied = execute_preview(request(file), &read_fault).await;
assert_eq!(denied.result, Err(FsError::PermissionDenied));
let directory = Location::local("/disconnected");
let list_fault = FaultInjectFs::new(Arc::new(MemoryFs::new().with_dir(directory.clone())));
list_fault.fail_next(FsOperation::List, FsError::Disconnected);
let disconnected = execute_preview(request(directory), &list_fault).await;
assert_eq!(disconnected.result, Err(FsError::Disconnected));
}
struct OtherFs;
#[async_trait]
impl ReadFileSystem for OtherFs {
async fn list(&self, _location: &Location) -> Result<Vec<Entry>, FsError> {
panic!("metadata-only entries must not be listed")
}
async fn canonicalize(&self, location: &Location) -> Result<Location, FsError> {
Ok(location.clone())
}
async fn metadata(&self, _location: &Location) -> Result<Entry, FsError> {
Ok(Entry::new("device", EntryKind::Other).with_metadata(Some(42), None, None))
}
async fn read_prefix(
&self,
_location: &Location,
_limit: usize,
) -> Result<ReadPrefix, FsError> {
panic!("metadata-only entries must not be read")
}
}
#[tokio::test]
async fn unsupported_entry_uses_metadata_without_reading_contents() {
let result = execute_preview(request(Location::local("/device")), &OtherFs).await;
assert_eq!(
result.result,
Ok(Preview {
kind: PreviewKind::Metadata,
lines: vec![
"Name: device".into(),
"Size: 42 bytes".into(),
"Type: Other".into(),
],
truncated: false,
directory_entries: Vec::new(),
})
);
}