fix(tui): harden rendering and centralize tests

This commit is contained in:
objz committed 2026-07-27 01:09:33 +02:00
1 parent 9b17ec96c5
commit 64bb5e2d16
66 files changed
+271 -48

No files matched your search

+748
View File
@@ -0,0 +1,748 @@
use super::*;
use crate::tui::tests::UI_TEST_LOCK;
use chrono::Utc;
use crossterm::event::KeyModifiers;
fn instance(name: &str, version: &str) -> InstanceConfig {
InstanceConfig {
name: name.to_string(),
game_version: version.to_string(),
loader: ModLoader::Fabric,
loader_version: None,
created: Utc::now(),
last_played: None,
java_path: None,
memory_max: None,
memory_min: None,
jvm_args: Vec::new(),
resolution: None,
config_sync_profile: None,
}
}
fn version(id: &str) -> VersionInfo {
VersionInfo {
id: id.to_owned(),
project_id: "project".to_owned(),
name: format!("Version {id}"),
version_number: id.to_owned(),
game_versions: vec!["1.21.1".to_owned()],
loaders: vec!["fabric".to_owned()],
date_published: "2026-01-02T12:00:00Z".to_owned(),
files: Vec::new(),
}
}
#[test]
fn content_mode_toggles_both_ways() {
assert_eq!(ContentMode::Installed.toggle(), ContentMode::Discover);
assert_eq!(ContentMode::Discover.toggle(), ContentMode::Installed);
}
#[test]
fn project_metadata_is_split_between_title_and_footer_badges() {
let entry = project_entry(
DiscoveryProject {
id: "example".to_owned(),
slug: "example".to_owned(),
title: "Example".to_owned(),
description: "Project description".to_owned(),
downloads: 1_234,
icon_url: None,
icon_bytes: None,
},
Some(PathBuf::from("example.jar")),
);
assert_eq!(entry.title_suffix.as_deref(), Some("Installed"));
assert_eq!(entry.footer_label.as_deref(), Some("1.2K downloads"));
assert_eq!(entry.description, "Project description");
assert_eq!(entry.path, PathBuf::from("example"));
assert_eq!(entry.installed_path, Some(PathBuf::from("example.jar")));
}
#[test]
fn install_and_change_version_popups_only_differ_in_title() {
let project = DiscoveryProject {
id: "project".to_owned(),
slug: "project".to_owned(),
title: "Project".to_owned(),
description: String::new(),
downloads: 0,
icon_url: None,
icon_bytes: None,
};
let mut state = DiscoveryState::new(DiscoveryKind::Mod);
state
.list
.entries
.push(project_entry(project.clone(), None));
state.list.list_state.selected = Some(0);
state.begin_versions().unwrap();
assert_eq!(
state.version_popup.as_ref().unwrap().title(),
"Install Project"
);
state.version_popup = None;
state.list.entries[0] = project_entry(project, Some(PathBuf::from("mods/project.jar")));
state.begin_versions().unwrap();
assert_eq!(
state.version_popup.as_ref().unwrap().title(),
"Change Project version"
);
}
#[test]
fn compatible_versions_populate_the_open_popup() {
let project = DiscoveryProject {
id: "project".to_owned(),
slug: "project".to_owned(),
title: "Project".to_owned(),
description: String::new(),
downloads: 0,
icon_url: None,
icon_bytes: None,
};
let mut state = DiscoveryState::new(DiscoveryKind::Mod);
state.list.entries.push(project_entry(project, None));
state.list.list_state.selected = Some(0);
let request = state.begin_versions().unwrap();
DiscoveryState::push_action_result(
&request.pending,
DiscoveryActionResult::Versions {
request_id: request.request_id,
project_id: request.project_id,
result: Ok(vec![version("1.0.0"), version("1.1.0")]),
},
);
state.drain_pending();
let popup = state.version_popup.as_ref().unwrap();
assert!(!popup.loading);
assert_eq!(popup.versions.len(), 2);
assert_eq!(popup.selected, 0);
}
#[test]
fn project_page_loads_for_the_selected_discovery_entry() {
let project = DiscoveryProject {
id: "project".to_owned(),
slug: "project".to_owned(),
title: "Project".to_owned(),
description: String::new(),
downloads: 0,
icon_url: None,
icon_bytes: None,
};
let mut state = DiscoveryState::new(DiscoveryKind::Mod);
state.list.entries.push(project_entry(project, None));
state.list.list_state.selected = Some(0);
let request = state.begin_project_page().unwrap();
assert!(state.project_page_open());
DiscoveryState::push_action_result(
&request.pending,
DiscoveryActionResult::ProjectPage {
request_id: request.request_id,
project_id: request.project_id,
result: Ok(crate::net::modrinth::ProjectInfo {
id: "project".to_owned(),
slug: "project".to_owned(),
title: "Project page".to_owned(),
description: "Short description".to_owned(),
body: "Long **Markdown** description.".to_owned(),
icon_url: None,
}),
},
);
state.drain_pending();
let page = state.project_page.as_ref().unwrap();
assert_eq!(page.title, "Project page");
assert!(page.document.is_some());
state.project_page = None;
assert!(state.begin_project_page().is_none());
assert!(
state
.project_page
.as_ref()
.is_some_and(|page| page.document.is_some())
);
}
#[test]
fn project_page_navigation_is_bounded_and_can_go_back() {
let mut state = DiscoveryState::new(DiscoveryKind::Mod);
state.project_page = Some(ProjectPageState {
request_id: 1,
project_id: "project".to_owned(),
title: "Project".to_owned(),
document: Some(crate::tui::widgets::markdown::Document::new(
"Project", "Body",
)),
error: None,
scroll: 0,
max_scroll: 20,
});
handle_key(
&KeyEvent::new(KeyCode::Char('d'), KeyModifiers::NONE),
&mut state,
);
assert_eq!(state.project_page.as_ref().unwrap().scroll, 10);
handle_key(
&KeyEvent::new(KeyCode::Char('G'), KeyModifiers::NONE),
&mut state,
);
assert_eq!(state.project_page.as_ref().unwrap().scroll, 20);
handle_key(
&KeyEvent::new(KeyCode::Char('h'), KeyModifiers::NONE),
&mut state,
);
assert!(!state.project_page_open());
}
#[test]
fn confirmation_can_return_to_version_selection() {
let project = DiscoveryProject {
id: "project".to_owned(),
slug: "project".to_owned(),
title: "Project".to_owned(),
description: String::new(),
downloads: 0,
icon_url: None,
icon_bytes: None,
};
let mut state = DiscoveryState::new(DiscoveryKind::Mod);
state.list.entries.push(project_entry(project, None));
state.list.list_state.selected = Some(0);
let request = state.begin_versions().unwrap();
DiscoveryState::push_action_result(
&request.pending,
DiscoveryActionResult::Versions {
request_id: request.request_id,
project_id: request.project_id,
result: Ok(vec![version("1.0.0")]),
},
);
state.drain_pending();
assert!(state.begin_confirmation());
handle_key(
&KeyEvent::new(KeyCode::Char('h'), KeyModifiers::NONE),
&mut state,
);
assert!(!state.version_popup.as_ref().unwrap().confirming);
assert!(state.version_popup.is_some());
}
#[test]
fn discovery_delete_only_clears_the_matching_installed_badge() {
let first_path = PathBuf::from("mods/first.jar");
let second_path = PathBuf::from("mods/second.jar");
let project = |id: &str| DiscoveryProject {
id: id.to_owned(),
slug: id.to_owned(),
title: id.to_owned(),
description: String::new(),
downloads: 0,
icon_url: None,
icon_bytes: None,
};
let mut state = DiscoveryState::new(DiscoveryKind::Mod);
state
.list
.entries
.push(project_entry(project("first"), Some(first_path.clone())));
state
.list
.entries
.push(project_entry(project("second"), Some(second_path.clone())));
state.list.list_state.selected = Some(0);
let pending = state.pending_installed_delete().unwrap();
assert_eq!(pending.path, first_path);
assert!(state.clear_installed_path(&pending.path));
assert_eq!(state.list.entries.len(), 2);
assert!(state.list.entries[0].installed_path.is_none());
assert!(state.list.entries[0].title_suffix.is_none());
assert_eq!(
state.list.entries[1].installed_path.as_deref(),
Some(second_path.as_path())
);
assert_eq!(
state.list.entries[1].title_suffix.as_deref(),
Some("Installed")
);
assert!(state.pending_installed_delete().is_none());
}
#[test]
fn successful_install_marks_the_project_and_closes_the_popup() {
let _guard = UI_TEST_LOCK
.lock()
.unwrap_or_else(|error| error.into_inner());
let project = DiscoveryProject {
id: "project".to_owned(),
slug: "project".to_owned(),
title: "Project".to_owned(),
description: String::new(),
downloads: 0,
icon_url: None,
icon_bytes: None,
};
let mut state = DiscoveryState::new(DiscoveryKind::Mod);
state.list.entries.push(project_entry(project, None));
state.list.list_state.selected = Some(0);
let versions_request = state.begin_versions().unwrap();
DiscoveryState::push_action_result(
&versions_request.pending,
DiscoveryActionResult::Versions {
request_id: versions_request.request_id,
project_id: versions_request.project_id,
result: Ok(vec![version("1.0.0")]),
},
);
state.drain_pending();
assert!(state.begin_confirmation());
let install = state.begin_install().unwrap();
assert!(state.version_popup.is_none());
DiscoveryState::push_action_result(
&install.pending,
DiscoveryActionResult::Install {
request_id: install.request_id,
generation: install.generation,
project_id: install.project_id,
project_title: install.project_title,
result: Ok(InstallCompletion {
path: PathBuf::from("mods/project.jar"),
replaced: false,
skipped: false,
}),
},
);
state.drain_pending();
assert!(state.version_popup.is_none());
assert_eq!(
state.list.entries[0].title_suffix.as_deref(),
Some("Installed")
);
assert_eq!(
state.list.entries[0].installed_path,
Some(PathBuf::from("mods/project.jar"))
);
assert_eq!(state.list.entries[0].path, PathBuf::from("project"));
}
#[test]
fn installed_labels_follow_exact_manifest_projects() {
let project = DiscoveryProject {
id: "project-id".to_owned(),
slug: "example-project".to_owned(),
title: "Example Project".to_owned(),
description: String::new(),
downloads: 0,
icon_url: None,
icon_bytes: None,
};
let mut state = DiscoveryState::new(DiscoveryKind::Mod);
state.list.entries.push(project_entry(project, None));
let mut manifest = crate::instance::ContentManifest::default();
manifest.upsert(crate::instance::ContentFileRecord {
relative_path: PathBuf::from("mods/example-project-1.0.0.jar"),
kind: crate::instance::ContentKind::Mod,
enabled: true,
fingerprint: crate::instance::FileFingerprint {
size: 1,
modified_ns: 1,
hashes: Default::default(),
},
resolution: crate::instance::Resolution::Resolved {
project: crate::instance::ProviderProject {
provider: "modrinth".to_owned(),
project_id: "project-id".to_owned(),
version_id: "version".to_owned(),
},
},
});
state.refresh_installed_manifest(&manifest, std::path::Path::new("first"));
assert_eq!(
state.list.entries[0].title_suffix.as_deref(),
Some("Installed")
);
assert_eq!(
state.list.entries[0].installed_path,
Some(PathBuf::from("first/mods/example-project-1.0.0.jar"))
);
state.refresh_installed_manifest(
&crate::instance::ContentManifest::default(),
std::path::Path::new("first"),
);
assert_eq!(state.list.entries[0].title_suffix, None);
assert_eq!(state.list.entries[0].installed_path, None);
assert_eq!(state.list.entries[0].path, PathBuf::from("project-id"));
}
#[test]
fn changing_instance_invalidates_results() {
let mut state = DiscoveryState::new(DiscoveryKind::Mod);
let first = instance("one", "1.21.1");
let second = instance("two", "1.21.1");
let _request = state.begin_search(&first);
assert!(!state.needs_search(&first));
assert!(state.needs_search(&second));
}
#[test]
fn unavailable_vanilla_discovery_clears_cached_results() {
let mut state = DiscoveryState::new(DiscoveryKind::Mod);
state.list.entries.push(project_entry(
DiscoveryProject {
id: "cached".to_owned(),
slug: "cached".to_owned(),
title: "Cached".to_owned(),
description: String::new(),
downloads: 0,
icon_url: None,
icon_bytes: None,
},
None,
));
let mut vanilla = instance("vanilla", "1.21.1");
vanilla.loader = ModLoader::Vanilla;
state.set_unavailable(&vanilla);
assert!(state.list.entries.is_empty());
assert!(!state.page_loading);
assert!(state.exhausted);
}
#[test]
fn changing_instance_compatibility_invalidates_results() {
let mut state = DiscoveryState::new(DiscoveryKind::Mod);
let original = instance("one", "1.21.1");
let mut other_version = original.clone();
other_version.game_version = "1.20.1".to_owned();
let mut other_loader = original.clone();
other_loader.loader = ModLoader::NeoForge;
let _request = state.begin_search(&original);
assert!(state.needs_search(&other_version));
assert!(state.needs_search(&other_loader));
}
#[test]
fn stale_search_result_is_ignored() {
let mut state = DiscoveryState::new(DiscoveryKind::Mod);
let instance = instance("one", "1.21.1");
let old = state.begin_search(&instance);
let _new = state.begin_search(&instance);
DiscoveryState::push_result(
&old.pending,
old.generation,
old.offset,
Ok(DiscoveryPageResult {
received: 20,
total_hits: 99,
}),
);
state.drain_pending();
assert_eq!(state.total_hits, 0);
assert!(state.list.loading);
}
#[test]
fn next_page_prefetches_before_selection_reaches_the_end() {
let mut state = DiscoveryState::new(DiscoveryKind::Mod);
state.set_viewport_rows(30);
let instance = instance("one", "1.21.1");
let first = state.begin_search(&instance);
for index in 0..PAGE_SIZE {
assert!(first.stream.send(project_entry(
DiscoveryProject {
id: index.to_string(),
slug: index.to_string(),
title: index.to_string(),
description: String::new(),
downloads: 0,
icon_url: None,
icon_bytes: None,
},
None
)));
}
state.list.drain_pending();
DiscoveryState::push_result(
&first.pending,
first.generation,
first.offset,
Ok(DiscoveryPageResult {
received: PAGE_SIZE,
total_hits: 300,
}),
);
state.drain_pending();
state.list.list_state.selected = Some(80);
let next = state.begin_next_page().expect("next page should prefetch");
assert_eq!(next.offset, PAGE_SIZE);
assert!(state.begin_next_page().is_none());
}
#[test]
fn large_page_fills_a_tall_viewport_without_another_request() {
let mut state = DiscoveryState::new(DiscoveryKind::Mod);
state.set_viewport_rows(90);
let first = state.begin_search(&instance("one", "1.21.1"));
for index in 0..PAGE_SIZE {
assert!(first.stream.send(project_entry(
DiscoveryProject {
id: index.to_string(),
slug: index.to_string(),
title: index.to_string(),
description: String::new(),
downloads: 0,
icon_url: None,
icon_bytes: None,
},
None
)));
}
state.list.drain_pending();
DiscoveryState::push_result(
&first.pending,
first.generation,
first.offset,
Ok(DiscoveryPageResult {
received: PAGE_SIZE,
total_hits: 300,
}),
);
state.drain_pending();
assert!(state.begin_next_page().is_none());
}
#[test]
fn typing_keeps_loaded_results_until_remote_search_is_due() {
let mut state = DiscoveryState::new(DiscoveryKind::Mod);
let request = state.begin_search(&instance("one", "1.21.1"));
for title in ["Sodium", "Lithium"] {
assert!(request.stream.send(project_entry(
DiscoveryProject {
id: title.to_lowercase(),
slug: title.to_lowercase(),
title: title.to_owned(),
description: String::new(),
downloads: 0,
icon_url: None,
icon_bytes: None,
},
None
)));
}
state.list.drain_pending();
handle_key(
&KeyEvent::new(KeyCode::Char('/'), KeyModifiers::NONE),
&mut state,
);
for character in "sod".chars() {
handle_key(
&KeyEvent::new(KeyCode::Char(character), KeyModifiers::NONE),
&mut state,
);
}
assert_eq!(state.list.filtered_indices(), vec![0, 1]);
assert_eq!(state.list.search.query, "sod");
assert!(!state.search_due());
state.search_changed_at = Some(std::time::Instant::now() - SEARCH_DEBOUNCE);
assert!(state.search_due());
}
#[test]
fn search_refresh_keeps_rows_until_the_diff_arrives() {
let mut state = DiscoveryState::new(DiscoveryKind::Mod);
let instance = instance("one", "1.21.1");
let initial = state.begin_search(&instance);
for title in ["Sodium", "Lithium"] {
assert!(initial.stream.upsert(project_entry(
DiscoveryProject {
id: title.to_lowercase(),
slug: title.to_lowercase(),
title: title.to_owned(),
description: String::new(),
downloads: 0,
icon_url: None,
icon_bytes: (title == "Sodium").then(|| vec![1, 2, 3]),
},
None
)));
}
state.list.drain_pending();
state.search.query = "sodium".to_owned();
state.search_changed();
let refresh = state.begin_search(&instance);
assert!(refresh.reconcile);
assert!(refresh.loaded_icon_stems.contains("sodium"));
assert!(!refresh.loaded_icon_stems.contains("lithium"));
assert_eq!(state.list.entries.len(), 2);
assert!(!state.list.loading);
}
#[test]
fn pagination_continues_across_multiple_pages() {
let mut state = DiscoveryState::new(DiscoveryKind::Mod);
let instance = instance("one", "1.21.1");
let first = state.begin_search(&instance);
for index in 0..PAGE_SIZE {
assert!(first.stream.upsert(project_entry(
DiscoveryProject {
id: index.to_string(),
slug: index.to_string(),
title: index.to_string(),
description: String::new(),
downloads: 0,
icon_url: None,
icon_bytes: None,
},
None
)));
}
state.list.drain_pending();
DiscoveryState::push_result(
&first.pending,
first.generation,
first.offset,
Ok(DiscoveryPageResult {
received: PAGE_SIZE,
total_hits: 300,
}),
);
state.drain_pending();
state.list.list_state.selected = Some(PAGE_SIZE - MIN_PREFETCH_ITEMS);
let second = state.begin_next_page().unwrap();
for index in PAGE_SIZE..PAGE_SIZE * 2 {
assert!(second.stream.upsert(project_entry(
DiscoveryProject {
id: index.to_string(),
slug: index.to_string(),
title: index.to_string(),
description: String::new(),
downloads: 0,
icon_url: None,
icon_bytes: None,
},
None
)));
}
state.list.drain_pending();
DiscoveryState::push_result(
&second.pending,
second.generation,
second.offset,
Ok(DiscoveryPageResult {
received: PAGE_SIZE,
total_hits: 300,
}),
);
state.drain_pending();
state.list.list_state.selected = Some(PAGE_SIZE * 2 - MIN_PREFETCH_ITEMS);
let third = state.begin_next_page().unwrap();
assert_eq!(third.offset, PAGE_SIZE * 2);
}
#[test]
fn permanent_pagination_failure_stops_without_discarding_loaded_entries() {
let mut state = DiscoveryState::new(DiscoveryKind::Mod);
let first = state.begin_search(&instance("one", "1.21.1"));
for index in 0..PAGE_SIZE {
assert!(first.stream.upsert(project_entry(
DiscoveryProject {
id: index.to_string(),
slug: index.to_string(),
title: index.to_string(),
description: String::new(),
downloads: 0,
icon_url: None,
icon_bytes: None,
},
None
)));
}
state.list.drain_pending();
DiscoveryState::push_result(
&first.pending,
first.generation,
first.offset,
Ok(DiscoveryPageResult {
received: PAGE_SIZE,
total_hits: 300,
}),
);
state.drain_pending();
state.list.list_state.selected = Some(PAGE_SIZE - MIN_PREFETCH_ITEMS);
let second = state.begin_next_page().unwrap();
DiscoveryState::push_result(
&second.pending,
second.generation,
second.offset,
Err(DiscoveryPageError {
message: "invalid response".to_owned(),
retryable: false,
}),
);
state.drain_pending();
assert!(state.begin_next_page().is_none());
assert_eq!(state.list.entries.len(), PAGE_SIZE);
assert!(state.exhausted);
}
#[test]
fn transient_pagination_failure_retries_the_same_offset_after_a_delay() {
let mut state = DiscoveryState::new(DiscoveryKind::Mod);
let first = state.begin_search(&instance("one", "1.21.1"));
DiscoveryState::push_result(
&first.pending,
first.generation,
first.offset,
Ok(DiscoveryPageResult {
received: PAGE_SIZE,
total_hits: 300,
}),
);
state.drain_pending();
let second = state.begin_next_page().unwrap();
DiscoveryState::push_result(
&second.pending,
second.generation,
second.offset,
Err(DiscoveryPageError {
message: "connection reset".to_owned(),
retryable: true,
}),
);
state.drain_pending();
assert!(state.begin_next_page().is_none());
state.retry_page_at = Some(std::time::Instant::now() - PAGE_RETRY_BASE_DELAY);
assert_eq!(state.begin_next_page().unwrap().offset, PAGE_SIZE);
}
+485
View File
@@ -0,0 +1,485 @@
use std::{
collections::{HashMap, HashSet},
path::PathBuf,
sync::{Arc, Mutex},
};
use crate::instance::content::mods::ContentEntry;
use ratatui::{
buffer::Buffer,
layout::Rect,
style::{Color, Modifier, Style},
text::{Line, Span, Text},
widgets::Widget,
};
use super::{
ContentListState, WatcherEventHandling, available_description_width, description_text_width,
diff_directory, diff_event_paths, ellipsize, load_provider_metadata, read_dir_stems,
right_aligned_footer_spans, square_icon_columns, title_suffix_spans, watcher_event_handling,
};
fn entry(name: &str) -> ContentEntry {
ContentEntry {
file_stem: name.to_lowercase(),
name: name.to_owned(),
source_slug: None,
installed_path: None,
provider_project: None,
title_suffix: None,
footer_label: None,
description: String::new(),
enabled: true,
icon_bytes: None,
provider_icon: false,
provider_description: false,
path: PathBuf::from(name.to_lowercase()),
icon_lines: None,
}
}
#[test]
fn content_watcher_ignores_file_access_events() {
assert_eq!(
watcher_event_handling(&notify::EventKind::Access(notify::event::AccessKind::Any)),
WatcherEventHandling::Ignore
);
}
#[test]
fn content_watcher_handles_mutations_without_full_rescan() {
assert_eq!(
watcher_event_handling(&notify::EventKind::Modify(notify::event::ModifyKind::Any)),
WatcherEventHandling::Paths
);
assert_eq!(
watcher_event_handling(&notify::EventKind::Modify(notify::event::ModifyKind::Name(
notify::event::RenameMode::Both
))),
WatcherEventHandling::Rescan
);
assert_eq!(
watcher_event_handling(&notify::EventKind::Any),
WatcherEventHandling::Rescan
);
}
#[test]
fn content_watcher_keeps_a_renamed_disabled_entry() {
let temp = tempfile::tempdir().unwrap();
let enabled = temp.path().join("example.jar");
let disabled = temp.path().join("example.jar.disabled");
std::fs::write(&enabled, b"mod").unwrap();
let known = Arc::new(Mutex::new(read_dir_stems(temp.path(), ".jar")));
std::fs::rename(enabled, &disabled).unwrap();
let diff = diff_directory(temp.path(), ".jar", None, &known).unwrap();
assert_eq!(diff.toggled, vec![("example".to_owned(), false, disabled)]);
assert!(diff.removed.is_empty());
assert!(diff.added.is_empty());
}
#[test]
fn pure_toggle_does_not_request_reconciliation() {
let mut state = ContentListState::default();
let mut content = entry("Example");
content.path = PathBuf::from("mods/example.jar.disabled");
content.enabled = false;
state.entries.push(content);
*state.watcher_diff.lock().unwrap() = Some(super::WatcherDiff {
toggled: vec![(
"example".to_owned(),
false,
PathBuf::from("mods/example.jar.disabled"),
)],
removed: Vec::new(),
added: Vec::new(),
});
let update = state.drain_watcher();
assert!(!update.requires_reconcile);
assert_eq!(update.toggles.len(), 1);
assert_eq!(
update.toggles[0].old_path,
PathBuf::from("mods/example.jar")
);
}
#[test]
fn irrelevant_watcher_paths_do_not_emit_an_empty_diff() {
let temp = tempfile::tempdir().unwrap();
let known = Arc::new(Mutex::new(HashMap::new()));
let paths = vec![temp.path().join("notes.txt")];
assert!(diff_event_paths(temp.path(), &paths, ".jar", None, &known).is_none());
}
#[test]
fn square_columns_follow_terminal_cell_ratio() {
assert_eq!(square_icon_columns(3, (8, 16)), 6);
assert_eq!(square_icon_columns(3, (8, 18)), 7);
assert_eq!(square_icon_columns(6, (8, 18)), 14);
}
#[test]
fn square_columns_handle_missing_cell_size() {
assert_eq!(square_icon_columns(3, (0, 0)), 3);
}
#[test]
fn title_badge_is_rendered_after_a_small_gap() {
let label_style = Style::default()
.fg(Color::Black)
.bg(Color::Cyan)
.add_modifier(Modifier::BOLD);
let spans = title_suffix_spans(Some("Installed"), Style::default(), label_style);
let text = spans
.iter()
.map(|span| span.content.as_ref())
.collect::<Vec<_>>()
.concat();
assert_eq!(text, " Installed ");
assert_eq!(spans[1].style, label_style);
assert!(title_suffix_spans(None, Style::default(), label_style).is_empty());
}
#[test]
fn title_suffix_keeps_label_style_after_the_row_background_is_applied() {
let label_style = Style::default()
.fg(Color::Black)
.bg(Color::Cyan)
.add_modifier(Modifier::BOLD);
let text = Text::from(Line::from(title_suffix_spans(
Some("downloads"),
Style::default(),
label_style,
)))
.style(Style::default().bg(Color::Black));
let area = Rect::new(0, 0, 20, 1);
let mut buffer = Buffer::empty(area);
text.render(area, &mut buffer);
let label_cell = buffer.cell((5, 0)).unwrap();
assert_eq!(label_cell.fg, Color::Black);
assert_eq!(label_cell.bg, Color::Cyan);
assert!(label_cell.modifier.contains(Modifier::BOLD));
}
#[test]
fn descriptions_are_ellipsized_to_the_available_cell_width() {
assert_eq!(ellipsize("short", 5), "short");
assert_eq!(ellipsize("a longer description", 10), "a longe...");
assert_eq!(ellipsize("narrow", 3), "...");
assert_eq!(ellipsize("narrow", 2), "..");
assert_eq!(ellipsize("界界界", 5), "界...");
}
#[test]
fn description_width_reserves_the_row_chrome() {
assert_eq!(available_description_width(100, 6, true), 91);
assert_eq!(available_description_width(100, 0, false), 98);
assert_eq!(available_description_width(4, 6, true), 0);
}
#[test]
fn description_width_reserves_the_download_metadata() {
assert_eq!(description_text_width(40, Some("1.2K downloads"), true), 25);
assert_eq!(description_text_width(10, Some("1.2K downloads"), true), 0);
assert_eq!(description_text_width(40, None, true), 40);
}
#[test]
fn footer_metadata_is_right_aligned_without_a_separator() {
let mut spans = vec![Span::raw("Description")];
spans.extend(right_aligned_footer_spans(
30,
"Description",
true,
"1.2K downloads",
Style::default(),
));
let line = Line::from(spans);
assert_eq!(line.width(), 30);
assert_eq!(line.to_string(), "Description 1.2K downloads");
}
#[test]
fn content_stream_inserts_entries_and_icons_incrementally() {
let mut state = ContentListState::default();
let stream = state.start_stream("remote");
assert!(stream.send(entry("Zulu")));
state.drain_pending();
assert_eq!(state.entries[0].name, "Zulu");
assert!(!state.loading);
assert!(stream.send(entry("Alpha")));
assert!(stream.send_icon("alpha".to_owned(), PathBuf::from("alpha"), vec![1, 2, 3],));
state.drain_pending();
assert_eq!(
state
.entries
.iter()
.map(|entry| entry.name.as_str())
.collect::<Vec<_>>(),
["Alpha", "Zulu"]
);
assert_eq!(
state.entries[0].icon_bytes.as_deref(),
Some([1, 2, 3].as_slice())
);
}
#[test]
fn source_stream_preserves_remote_result_order() {
let mut state = ContentListState::default();
let stream = state.start_source_stream("remote");
assert!(stream.send(entry("Zulu")));
assert!(stream.send(entry("Alpha")));
state.drain_pending();
assert_eq!(
state
.entries
.iter()
.map(|entry| entry.name.as_str())
.collect::<Vec<_>>(),
["Zulu", "Alpha"]
);
}
#[test]
fn source_refresh_reconciles_without_rebuilding_unchanged_entries() {
let mut state = ContentListState::default();
let initial = state.start_source_stream("remote");
let mut alpha = entry("Alpha");
alpha.icon_bytes = Some(vec![1, 2, 3]);
assert!(initial.upsert(alpha));
assert!(initial.upsert(entry("Beta")));
assert!(initial.upsert(entry("Gamma")));
state.drain_pending();
state.list_state.selected = Some(0);
let refresh = state.refresh_source_stream("remote");
let mut alpha_update = entry("Alpha");
alpha_update.description = "Updated".to_owned();
assert!(refresh.upsert(alpha_update));
assert!(refresh.upsert(entry("Delta")));
assert!(refresh.retain(HashSet::from(["alpha".to_owned(), "delta".to_owned(),])));
state.drain_pending();
assert_eq!(
state
.entries
.iter()
.map(|entry| entry.name.as_str())
.collect::<Vec<_>>(),
["Alpha", "Delta"]
);
assert_eq!(state.entries[0].description, "Updated");
assert_eq!(
state.entries[0].icon_bytes.as_deref(),
Some([1, 2, 3].as_slice())
);
assert_eq!(state.list_state.selected, Some(0));
assert!(!state.loading);
}
#[test]
fn provider_icons_are_requested_only_for_visible_missing_icons() {
let mut state = ContentListState::default();
let mut visible = entry("Visible");
visible.icon_lines = Some(crate::instance::content::mods::fallback_icon());
visible.provider_project = Some(crate::instance::ProviderProject {
provider: "modrinth".to_owned(),
project_id: "visible-project".to_owned(),
version_id: "version".to_owned(),
});
let mut offscreen = entry("Offscreen");
offscreen.icon_lines = Some(crate::instance::content::mods::fallback_icon());
offscreen.provider_project = Some(crate::instance::ProviderProject {
provider: "modrinth".to_owned(),
project_id: "offscreen-project".to_owned(),
version_id: "version".to_owned(),
});
state.entries = vec![visible, offscreen];
state.rebuild_display_metadata();
let projects = state.visible_provider_projects(&[0, 1], 3);
assert_eq!(projects.len(), 1);
assert_eq!(projects[0].project_id, "visible-project");
}
#[test]
fn embedded_icons_do_not_request_provider_fallbacks() {
let mut state = ContentListState::default();
let mut visible = entry("Visible");
visible.icon_bytes = Some(vec![1, 2, 3]);
visible.icon_lines = Some(crate::instance::content::mods::fallback_icon());
visible.provider_project = Some(crate::instance::ProviderProject {
provider: "modrinth".to_owned(),
project_id: "visible-project".to_owned(),
version_id: "version".to_owned(),
});
state.entries = vec![visible];
state.rebuild_display_metadata();
assert!(state.visible_provider_projects(&[0], 3).is_empty());
}
#[tokio::test]
async fn streamed_entries_wait_for_their_rendered_icon() {
let mut state = ContentListState::default();
let mut png = std::io::Cursor::new(Vec::new());
image::DynamicImage::new_rgba8(1, 1)
.write_to(&mut png, image::ImageFormat::Png)
.unwrap();
let mut with_icon = entry("With icon");
with_icon.icon_bytes = Some(png.into_inner());
let stream = state.start_stream("local");
assert!(stream.send(with_icon));
state.drain_pending();
assert!(state.filtered_indices().is_empty());
let picker = ratatui_image::picker::Picker::halfblocks();
state.request_image_loads(&picker);
tokio::time::timeout(std::time::Duration::from_secs(5), async {
loop {
state.drain_image_loads(&picker);
if !state.filtered_indices().is_empty() {
break;
}
tokio::task::yield_now().await;
}
})
.await
.expect("icon render completed");
assert_eq!(state.filtered_indices(), vec![0]);
}
#[test]
fn streamed_entries_without_icons_are_visible_immediately() {
let mut state = ContentListState::default();
let stream = state.start_stream("local");
assert!(stream.send(entry("Without icon")));
state.drain_pending();
assert_eq!(state.filtered_indices(), vec![0]);
}
#[test]
fn manifest_metadata_keeps_an_embedded_icon_renderer() {
let minecraft_dir = PathBuf::from("instance/minecraft");
let mut state = ContentListState::default();
let mut installed = entry("Installed");
installed.path = minecraft_dir.join("mods/installed.jar");
installed.icon_bytes = Some(vec![1, 2, 3]);
state.entries.push(installed);
let picker = ratatui_image::picker::Picker::halfblocks();
state.image_protocols.insert(
"installed".to_owned(),
picker.new_resize_protocol(image::DynamicImage::new_rgba8(1, 1)),
);
let mut manifest = crate::instance::ContentManifest::default();
manifest.upsert(crate::instance::ContentFileRecord {
relative_path: PathBuf::from("mods/installed.jar"),
kind: crate::instance::ContentKind::Mod,
enabled: true,
fingerprint: crate::instance::FileFingerprint {
size: 3,
modified_ns: 1,
hashes: Default::default(),
},
resolution: crate::instance::Resolution::Resolved {
project: crate::instance::ProviderProject {
provider: "modrinth".to_owned(),
project_id: "project".to_owned(),
version_id: "version".to_owned(),
},
},
});
state.apply_manifest(&manifest, &minecraft_dir, crate::instance::ContentKind::Mod);
assert!(state.image_protocols.contains_key("installed"));
}
#[test]
fn provider_metadata_fills_a_missing_installed_description() {
let mut state = ContentListState::default();
let mut installed = entry("Shader");
installed.provider_project = Some(crate::instance::ProviderProject {
provider: "modrinth".to_owned(),
project_id: "shader-project".to_owned(),
version_id: "version".to_owned(),
});
state.entries.push(installed);
state
.pending_provider_icons
.lock()
.unwrap()
.push(super::PendingProviderIcon {
provider: "modrinth".to_owned(),
project_id: "shader-project".to_owned(),
bytes: Vec::new(),
description: "A cached shader description".to_owned(),
});
assert!(state.drain_provider_icons());
assert_eq!(state.entries[0].description, "A cached shader description");
assert!(state.entries[0].provider_description);
}
#[tokio::test]
async fn provider_metadata_loads_from_cache_without_network() {
let temp = tempfile::tempdir().unwrap();
let mut png = std::io::Cursor::new(Vec::new());
image::DynamicImage::new_rgba8(1, 1)
.write_to(&mut png, image::ImageFormat::Png)
.unwrap();
let png = png.into_inner();
let icon_path = crate::storage::MetadataPaths::new(temp.path())
.provider_icons("modrinth")
.join("cached-project.img");
std::fs::create_dir_all(icon_path.parent().unwrap()).unwrap();
std::fs::write(&icon_path, &png).unwrap();
let project_path = crate::storage::MetadataPaths::new(temp.path())
.provider_projects("modrinth")
.join("cached-project.json");
std::fs::create_dir_all(project_path.parent().unwrap()).unwrap();
std::fs::write(
project_path,
serde_json::to_vec(&crate::net::modrinth::ProjectInfo {
id: "cached-project".to_owned(),
slug: "cached-project".to_owned(),
title: "Cached project".to_owned(),
description: "Cached description".to_owned(),
body: String::new(),
icon_url: None,
})
.unwrap(),
)
.unwrap();
let (bytes, description) = load_provider_metadata(
&crate::net::HttpClient::new(),
temp.path(),
"modrinth",
"cached-project",
)
.await
.unwrap();
assert_eq!(bytes, png);
assert_eq!(description, "Cached description");
}
+67
View File
@@ -0,0 +1,67 @@
use super::*;
#[test]
fn mode_labels_have_the_same_rendered_width() {
assert_eq!(
mode_label(ContentMode::Installed).chars().count(),
mode_label(ContentMode::Discover).chars().count()
);
}
#[test]
fn discovery_navigation_only_cycles_downloadable_tabs() {
assert_eq!(
ContentTab::Shaders.next_for_mode(ContentMode::Discover),
ContentTab::Mods
);
assert_eq!(
ContentTab::Mods.previous_for_mode(ContentMode::Discover),
ContentTab::Shaders
);
}
#[test]
fn discovery_navigation_recovers_from_hidden_local_tab() {
assert_eq!(
ContentTab::Logs.next_for_mode(ContentMode::Discover),
ContentTab::ResourcePacks
);
}
#[test]
fn discovery_version_rows_only_show_the_version_number() {
let version = crate::net::modrinth::VersionInfo {
id: "version-id".to_owned(),
project_id: "project-id".to_owned(),
name: "A descriptive release title".to_owned(),
version_number: "3.2.4-fabric-26.1".to_owned(),
game_versions: vec![],
loaders: vec![],
date_published: String::new(),
files: vec![],
};
assert_eq!(discovery_version_label(&version), "3.2.4-fabric-26.1");
}
#[test]
fn discovery_version_popup_uses_compact_heights() {
assert_eq!(version_popup_height(1, false, false, false), 6);
assert_eq!(version_popup_height(100, false, false, false), 18);
assert_eq!(version_popup_height(1, true, false, false), 8);
assert_eq!(version_popup_height(0, false, true, false), 5);
assert_eq!(version_popup_height(0, false, false, true), 8);
}
#[test]
fn confirmation_metadata_is_human_readable() {
assert_eq!(
confirmation_loaders(&["fabric".to_owned(), "neoforge".to_owned()]),
"Fabric, NeoForge"
);
assert_eq!(
confirmation_release_date("2026-07-26T14:30:00Z"),
"2026-07-26"
);
assert_eq!(confirmation_values(&[]), "Unknown");
}