test(tui): externalize and expand UI coverage
This commit is contained in:
1 parent
868f3e5b9d
commit
6138e248cb
60 files changed
+3193
-2700
No files matched your search
@@ -529,3 +529,6 @@ fn render_device_code_popup(frame: &mut Frame, info: &DeviceCodeInfo) {
|
||||
}
|
||||
.render(area, frame.buffer_mut());
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,22 @@
|
||||
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
|
||||
|
||||
use super::*;
|
||||
|
||||
fn key(code: KeyCode) -> KeyEvent {
|
||||
KeyEvent::new(code, KeyModifiers::NONE)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offline_account_requires_a_microsoft_account_and_can_be_dismissed() {
|
||||
let mut state = AccountState::default();
|
||||
state.store.accounts.clear();
|
||||
|
||||
assert!(handle_key(&key(KeyCode::Char('a')), &mut state));
|
||||
assert!(matches!(state.add_mode, AddMode::ChooseType));
|
||||
|
||||
assert!(handle_key(&key(KeyCode::Char('o')), &mut state));
|
||||
assert!(matches!(state.add_mode, AddMode::OfflineBlocked));
|
||||
|
||||
assert!(handle_key(&key(KeyCode::Esc), &mut state));
|
||||
assert!(matches!(state.add_mode, AddMode::None));
|
||||
}
|
||||
@@ -872,749 +872,4 @@ fn format_downloads(downloads: u64) -> String {
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
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 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);
|
||||
}
|
||||
}
|
||||
mod tests;
|
||||
@@ -0,0 +1,744 @@
|
||||
use super::*;
|
||||
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 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);
|
||||
}
|
||||
@@ -2218,487 +2218,4 @@ fn read_dir_stems(dir: &std::path::Path, ext: &str) -> HashMap<String, (std::pat
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
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(¬ify::EventKind::Access(notify::event::AccessKind::Any)),
|
||||
WatcherEventHandling::Ignore
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn content_watcher_handles_mutations_without_full_rescan() {
|
||||
assert_eq!(
|
||||
watcher_event_handling(¬ify::EventKind::Modify(notify::event::ModifyKind::Any)),
|
||||
WatcherEventHandling::Paths
|
||||
);
|
||||
assert_eq!(
|
||||
watcher_event_handling(¬ify::EventKind::Modify(notify::event::ModifyKind::Name(
|
||||
notify::event::RenameMode::Both
|
||||
))),
|
||||
WatcherEventHandling::Rescan
|
||||
);
|
||||
assert_eq!(
|
||||
watcher_event_handling(¬ify::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);
|
||||
for _ in 0..20 {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(5)).await;
|
||||
state.drain_image_loads(&picker);
|
||||
if !state.filtered_indices().is_empty() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
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");
|
||||
}
|
||||
}
|
||||
mod tests;
|
||||
@@ -0,0 +1,481 @@
|
||||
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(¬ify::EventKind::Access(notify::event::AccessKind::Any)),
|
||||
WatcherEventHandling::Ignore
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn content_watcher_handles_mutations_without_full_rescan() {
|
||||
assert_eq!(
|
||||
watcher_event_handling(¬ify::EventKind::Modify(notify::event::ModifyKind::Any)),
|
||||
WatcherEventHandling::Paths
|
||||
);
|
||||
assert_eq!(
|
||||
watcher_event_handling(¬ify::EventKind::Modify(notify::event::ModifyKind::Name(
|
||||
notify::event::RenameMode::Both
|
||||
))),
|
||||
WatcherEventHandling::Rescan
|
||||
);
|
||||
assert_eq!(
|
||||
watcher_event_handling(¬ify::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);
|
||||
for _ in 0..20 {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(5)).await;
|
||||
state.drain_image_loads(&picker);
|
||||
if !state.filtered_indices().is_empty() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
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");
|
||||
}
|
||||
@@ -866,72 +866,4 @@ pub fn title(
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
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");
|
||||
}
|
||||
}
|
||||
mod tests;
|
||||
@@ -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");
|
||||
}
|
||||
@@ -338,85 +338,4 @@ pub fn render(frame: &mut Frame, area: Rect, focused: FocusedArea, state: &mut S
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn format_last_played_none_returns_never_played() {
|
||||
assert_eq!(format_last_played(None), "Never played");
|
||||
}
|
||||
|
||||
// each #[case] picks a "seconds ago" value that lands in exactly one
|
||||
// bucket of the match. mutating any bucket boundary (e.g. 3600 to 3601,
|
||||
// or "minutes" to "seconds") makes one of these cases fail.
|
||||
#[rstest::rstest]
|
||||
#[case::just_now(0, "Just now")]
|
||||
#[case::just_now_upper(59, "Just now")]
|
||||
#[case::minutes(60, "1 minutes ago")]
|
||||
#[case::minutes_upper(3599, "59 minutes ago")]
|
||||
#[case::hours(3600, "1 hours ago")]
|
||||
#[case::hours_upper(86_399, "23 hours ago")]
|
||||
#[case::days(86_400, "1 days ago")]
|
||||
#[case::days_upper(2_591_999, "29 days ago")]
|
||||
#[case::months(2_592_000, "1 months ago")]
|
||||
#[case::months_upper(31_535_999, "12 months ago")]
|
||||
#[case::over_a_year(31_536_000, "Over a year ago")]
|
||||
fn format_last_played_buckets(#[case] seconds_ago: i64, #[case] expected: &str) {
|
||||
let dt = chrono::Utc::now() - chrono::Duration::seconds(seconds_ago);
|
||||
assert_eq!(format_last_played(Some(dt)), expected);
|
||||
}
|
||||
|
||||
use crate::instance::models::{InstanceConfig, ModLoader};
|
||||
use ratatui::Terminal;
|
||||
use ratatui::backend::TestBackend;
|
||||
|
||||
fn synthetic_instance(name: &str) -> InstanceConfig {
|
||||
// last_played intentionally None so the rendered text is the
|
||||
// deterministic "Never played" string. anything else would make the
|
||||
// snapshot drift relative to chrono::Utc::now().
|
||||
InstanceConfig {
|
||||
name: name.to_string(),
|
||||
game_version: "1.20.1".to_string(),
|
||||
loader: ModLoader::Vanilla,
|
||||
loader_version: None,
|
||||
created: chrono::Utc::now(),
|
||||
last_played: None,
|
||||
java_path: None,
|
||||
memory_max: None,
|
||||
memory_min: None,
|
||||
jvm_args: vec![],
|
||||
resolution: None,
|
||||
config_sync_profile: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instances_list_renders_three_instances() {
|
||||
let mut state = State::with_instances(vec![
|
||||
synthetic_instance("Vanilla 1.20.1"),
|
||||
synthetic_instance("Forge Pack"),
|
||||
synthetic_instance("Fabric Test"),
|
||||
]);
|
||||
|
||||
let backend = TestBackend::new(40, 12);
|
||||
let mut terminal = Terminal::new(backend).unwrap();
|
||||
terminal
|
||||
.draw(|f| render(f, f.area(), FocusedArea::Instances, &mut state))
|
||||
.unwrap();
|
||||
|
||||
insta::assert_snapshot!(terminal.backend());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instances_list_renders_empty() {
|
||||
let mut state = State::with_instances(vec![]);
|
||||
|
||||
let backend = TestBackend::new(40, 8);
|
||||
let mut terminal = Terminal::new(backend).unwrap();
|
||||
terminal
|
||||
.draw(|f| render(f, f.area(), FocusedArea::Instances, &mut state))
|
||||
.unwrap();
|
||||
|
||||
insta::assert_snapshot!(terminal.backend());
|
||||
}
|
||||
}
|
||||
mod tests;
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
---
|
||||
source: src/tui/widgets/instances.rs
|
||||
source: src/tui/widgets/instances/tests.rs
|
||||
expression: terminal.backend()
|
||||
---
|
||||
"╭Instances─────────────────────────────╮"
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
---
|
||||
source: src/tui/widgets/instances.rs
|
||||
source: src/tui/widgets/instances/tests.rs
|
||||
expression: terminal.backend()
|
||||
---
|
||||
"╭Instances─────────────────────────────╮"
|
||||
@@ -0,0 +1,80 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn format_last_played_none_returns_never_played() {
|
||||
assert_eq!(format_last_played(None), "Never played");
|
||||
}
|
||||
|
||||
// each #[case] picks a "seconds ago" value that lands in exactly one
|
||||
// bucket of the match. mutating any bucket boundary (e.g. 3600 to 3601,
|
||||
// or "minutes" to "seconds") makes one of these cases fail.
|
||||
#[rstest::rstest]
|
||||
#[case::just_now(0, "Just now")]
|
||||
#[case::just_now_upper(59, "Just now")]
|
||||
#[case::minutes(60, "1 minutes ago")]
|
||||
#[case::minutes_upper(3599, "59 minutes ago")]
|
||||
#[case::hours(3600, "1 hours ago")]
|
||||
#[case::hours_upper(86_399, "23 hours ago")]
|
||||
#[case::days(86_400, "1 days ago")]
|
||||
#[case::days_upper(2_591_999, "29 days ago")]
|
||||
#[case::months(2_592_000, "1 months ago")]
|
||||
#[case::months_upper(31_535_999, "12 months ago")]
|
||||
#[case::over_a_year(31_536_000, "Over a year ago")]
|
||||
fn format_last_played_buckets(#[case] seconds_ago: i64, #[case] expected: &str) {
|
||||
let dt = chrono::Utc::now() - chrono::Duration::seconds(seconds_ago);
|
||||
assert_eq!(format_last_played(Some(dt)), expected);
|
||||
}
|
||||
|
||||
use crate::instance::models::{InstanceConfig, ModLoader};
|
||||
use ratatui::Terminal;
|
||||
use ratatui::backend::TestBackend;
|
||||
|
||||
fn synthetic_instance(name: &str) -> InstanceConfig {
|
||||
// last_played intentionally None so the rendered text is the
|
||||
// deterministic "Never played" string. anything else would make the
|
||||
// snapshot drift relative to chrono::Utc::now().
|
||||
InstanceConfig {
|
||||
name: name.to_string(),
|
||||
game_version: "1.20.1".to_string(),
|
||||
loader: ModLoader::Vanilla,
|
||||
loader_version: None,
|
||||
created: chrono::Utc::now(),
|
||||
last_played: None,
|
||||
java_path: None,
|
||||
memory_max: None,
|
||||
memory_min: None,
|
||||
jvm_args: vec![],
|
||||
resolution: None,
|
||||
config_sync_profile: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instances_list_renders_three_instances() {
|
||||
let mut state = State::with_instances(vec![
|
||||
synthetic_instance("Vanilla 1.20.1"),
|
||||
synthetic_instance("Forge Pack"),
|
||||
synthetic_instance("Fabric Test"),
|
||||
]);
|
||||
|
||||
let backend = TestBackend::new(40, 12);
|
||||
let mut terminal = Terminal::new(backend).unwrap();
|
||||
terminal
|
||||
.draw(|f| render(f, f.area(), FocusedArea::Instances, &mut state))
|
||||
.unwrap();
|
||||
|
||||
insta::assert_snapshot!(terminal.backend());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instances_list_renders_empty() {
|
||||
let mut state = State::with_instances(vec![]);
|
||||
|
||||
let backend = TestBackend::new(40, 8);
|
||||
let mut terminal = Terminal::new(backend).unwrap();
|
||||
terminal
|
||||
.draw(|f| render(f, f.area(), FocusedArea::Instances, &mut state))
|
||||
.unwrap();
|
||||
|
||||
insta::assert_snapshot!(terminal.backend());
|
||||
}
|
||||
@@ -687,3 +687,6 @@ fn line_level_style(line: &str) -> Style {
|
||||
Style::default().fg(theme.text())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,47 @@
|
||||
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
|
||||
|
||||
use super::*;
|
||||
|
||||
fn key(code: KeyCode) -> KeyEvent {
|
||||
KeyEvent::new(code, KeyModifiers::NONE)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn list_and_viewer_navigation_loads_and_scrolls_the_selected_log() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let first = temp.path().join("first.log");
|
||||
let second = temp.path().join("second.log");
|
||||
std::fs::write(&first, "first").unwrap();
|
||||
std::fs::write(&second, "second\nline").unwrap();
|
||||
|
||||
let mut state = LogsState {
|
||||
entries: vec![
|
||||
LogFileEntry {
|
||||
name: "first.log".to_owned(),
|
||||
path: first,
|
||||
},
|
||||
LogFileEntry {
|
||||
name: "second.log".to_owned(),
|
||||
path: second,
|
||||
},
|
||||
],
|
||||
..Default::default()
|
||||
};
|
||||
state.list_state.selected = Some(0);
|
||||
|
||||
assert!(handle_key(&key(KeyCode::Down), &mut state));
|
||||
assert_eq!(state.list_state.selected, Some(1));
|
||||
assert_eq!(state.viewer_lines, ["second", "line"]);
|
||||
|
||||
assert!(handle_key(&key(KeyCode::Enter), &mut state));
|
||||
assert!(state.viewer_focused);
|
||||
state.viewer_max_scroll = 4;
|
||||
|
||||
assert!(handle_key(&key(KeyCode::Char('G')), &mut state));
|
||||
assert_eq!(state.viewer_scroll, 4);
|
||||
assert!(handle_key(&key(KeyCode::Char('g')), &mut state));
|
||||
assert_eq!(state.viewer_scroll, 0);
|
||||
|
||||
assert!(handle_key(&key(KeyCode::Esc), &mut state));
|
||||
assert!(!state.viewer_focused);
|
||||
}
|
||||
+1
-634
@@ -1583,637 +1583,4 @@ fn render_raster(frame: &mut Frame, area: Rect, raster: &[Vec<IconCell>], hidden
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use ratatui::{Terminal, backend::TestBackend};
|
||||
|
||||
#[test]
|
||||
fn html_images_are_extracted_and_raw_html_is_removed() {
|
||||
let document = super::Document::new(
|
||||
"Sodium",
|
||||
"<center><img src=\"https://cdn.example/comparison.png\" alt=\"Comparison\"></center>\n\n<h1>Installation</h1>",
|
||||
);
|
||||
assert_eq!(
|
||||
document.image_urls(),
|
||||
vec!["https://cdn.example/comparison.png"]
|
||||
);
|
||||
assert!(matches!(
|
||||
&document.blocks[0],
|
||||
super::DocumentBlock::ImageRow { alignment, .. }
|
||||
if *alignment == super::ImageAlignment::Center
|
||||
));
|
||||
assert!(document.blocks.iter().any(
|
||||
|block| matches!(block, super::DocumentBlock::Text(text) if text.source.contains("Installation") && !text.source.contains("<h1>"))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inline_html_images_use_the_document_image_pipeline() {
|
||||
let document = super::Document::new(
|
||||
"Euphoria Patches",
|
||||
r#"<img src="https://cdn.example/logo.png" alt="Euphoria logo" width="30" /> A shader add-on"#,
|
||||
);
|
||||
assert_eq!(document.image_urls(), vec!["https://cdn.example/logo.png"]);
|
||||
assert!(matches!(
|
||||
&document.blocks[0],
|
||||
super::DocumentBlock::ImageRow { images, .. }
|
||||
if images[0].alt == "Euphoria logo"
|
||||
));
|
||||
assert!(document.blocks.iter().any(
|
||||
|block| matches!(block, super::DocumentBlock::Text(text) if text.source.contains("A shader add-on") && !text.source.contains("<img"))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn html_image_dimensions_are_kept_for_terminal_layout() {
|
||||
let document = super::Document::new(
|
||||
"Euphoria Patches",
|
||||
r#"<img src="https://cdn.example/logo.png" alt="Euphoria logo" width="30" height="auto" />"#,
|
||||
);
|
||||
assert!(matches!(
|
||||
&document.blocks[0],
|
||||
super::DocumentBlock::ImageRow { images, .. }
|
||||
if images[0].size == super::ImageSizeHint {
|
||||
width: Some(30),
|
||||
height: None,
|
||||
}
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn html_width_limits_the_rendered_terminal_image() {
|
||||
let image = super::DocumentImage {
|
||||
load: super::ImageLoad::Ready(image::DynamicImage::new_rgba8(300, 300)),
|
||||
prepared: None,
|
||||
pending: None,
|
||||
};
|
||||
let picker = ratatui_image::picker::Picker::halfblocks();
|
||||
assert_eq!(
|
||||
super::image_dimensions(
|
||||
&image,
|
||||
super::ImageSizeHint {
|
||||
width: Some(30),
|
||||
height: None,
|
||||
},
|
||||
120,
|
||||
&picker,
|
||||
),
|
||||
(3, 2)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inserted_html_keeps_its_content_and_hides_tag_shells() {
|
||||
let document = super::Document::new(
|
||||
"Project",
|
||||
"Support <ins>Reimagined</ins> and <ins>Unbound</ins>.</b>",
|
||||
);
|
||||
let source = document
|
||||
.blocks
|
||||
.iter()
|
||||
.find_map(|block| match block {
|
||||
super::DocumentBlock::Text(text) => Some(text.source.as_str()),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
let text = super::formatted_text(source, 80);
|
||||
let rendered = text
|
||||
.lines
|
||||
.iter()
|
||||
.flat_map(|line| &line.spans)
|
||||
.collect::<Vec<_>>();
|
||||
assert!(rendered.iter().all(|span| !span.content.contains('<')));
|
||||
assert!(
|
||||
["Reimagined", "Unbound"]
|
||||
.iter()
|
||||
.all(|expected| rendered.iter().any(|span| span.content.contains(expected)))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_inline_html_uses_dom_conversion_for_links_and_emphasis() {
|
||||
let document = super::Document::new(
|
||||
"Project",
|
||||
concat!(
|
||||
r#"<span class="badge"><a href="https://example.com">"#,
|
||||
"<strong>Supported</strong></a></span></strong></spanw>"
|
||||
),
|
||||
);
|
||||
let source = document
|
||||
.blocks
|
||||
.iter()
|
||||
.find_map(|block| match block {
|
||||
super::DocumentBlock::Text(text) => Some(text.source.as_str()),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
assert!(source.contains("[**Supported**](https://example.com)"));
|
||||
assert!(!source.contains('<'));
|
||||
|
||||
let text = super::formatted_text(source, 80);
|
||||
let supported = text
|
||||
.lines
|
||||
.iter()
|
||||
.flat_map(|line| &line.spans)
|
||||
.find(|span| span.content.contains("Supported"))
|
||||
.unwrap();
|
||||
assert!(
|
||||
supported
|
||||
.style
|
||||
.add_modifier
|
||||
.contains(ratatui::style::Modifier::BOLD)
|
||||
);
|
||||
assert!(
|
||||
supported
|
||||
.style
|
||||
.add_modifier
|
||||
.contains(ratatui::style::Modifier::UNDERLINED)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn markdown_images_inside_links_do_not_leave_the_link_destination() {
|
||||
let document = super::Document::new(
|
||||
"Project",
|
||||
"[](https://example.com/donate)",
|
||||
);
|
||||
assert_eq!(document.blocks.len(), 1);
|
||||
assert!(matches!(
|
||||
&document.blocks[0],
|
||||
super::DocumentBlock::ImageRow { images, alignment }
|
||||
if images.len() == 1 && images[0].url == "https://cdn.example/button.png"
|
||||
&& images[0].link.as_deref() == Some("https://example.com/donate")
|
||||
&& *alignment == super::ImageAlignment::Left
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn visible_link_text_does_not_include_the_destination() {
|
||||
let text = super::formatted_text("[buying me a coffee](https://example.com/donate)", 80);
|
||||
let rendered = text
|
||||
.lines
|
||||
.iter()
|
||||
.flat_map(|line| &line.spans)
|
||||
.map(|span| span.content.as_ref())
|
||||
.collect::<String>();
|
||||
assert_eq!(rendered, "buying me a coffee");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adjacent_images_share_a_row() {
|
||||
let document = super::Document::new(
|
||||
"Project",
|
||||
"[](https://example.com) [](https://example.com/chat)",
|
||||
);
|
||||
assert!(matches!(
|
||||
&document.blocks[0],
|
||||
super::DocumentBlock::ImageRow { images, .. } if images.len() == 2
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicitly_centered_html_images_share_a_centered_row() {
|
||||
let document = super::Document::new(
|
||||
"Project",
|
||||
r#"<p align="center"><a href="https://example.com"><img src="https://cdn.example/support.svg"></a> <img src="https://cdn.example/chat.svg"></p>"#,
|
||||
);
|
||||
assert!(matches!(
|
||||
&document.blocks[0],
|
||||
super::DocumentBlock::ImageRow { images, alignment }
|
||||
if images.len() == 2 && *alignment == super::ImageAlignment::Center
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_explicitly_centered_project_images_are_centered() {
|
||||
let document = super::Document::new(
|
||||
"Project",
|
||||
concat!(
|
||||
"\n\n",
|
||||
"<center><img src=\"https://cdn.example/comparison.png\"></center>\n\n",
|
||||
""
|
||||
),
|
||||
);
|
||||
let alignments = document
|
||||
.blocks
|
||||
.iter()
|
||||
.filter_map(|block| match block {
|
||||
super::DocumentBlock::ImageRow { alignment, .. } => Some(*alignment),
|
||||
super::DocumentBlock::Text(_) => None,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(
|
||||
alignments,
|
||||
[
|
||||
super::ImageAlignment::Left,
|
||||
super::ImageAlignment::Center,
|
||||
super::ImageAlignment::Left
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn headings_hide_markers_and_rules_use_terminal_lines() {
|
||||
let text = super::formatted_text("## Known Issues\n\n---", 12);
|
||||
let rendered = text
|
||||
.lines
|
||||
.iter()
|
||||
.map(|line| {
|
||||
line.spans
|
||||
.iter()
|
||||
.map(|span| span.content.as_ref())
|
||||
.collect::<String>()
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
assert!(rendered.iter().any(|line| line == "Known Issues"));
|
||||
assert!(rendered.iter().any(|line| line == "────────────"));
|
||||
assert!(!rendered.iter().any(|line| line == "---"));
|
||||
assert!(!rendered.iter().any(|line| line.starts_with('#')));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn all_heading_levels_are_bold() {
|
||||
let text = super::formatted_text("### Performance", 20);
|
||||
let heading = text
|
||||
.lines
|
||||
.iter()
|
||||
.find(|line| {
|
||||
line.spans
|
||||
.iter()
|
||||
.any(|span| span.content.contains("Performance"))
|
||||
})
|
||||
.unwrap();
|
||||
assert!(heading.spans.iter().any(|span| {
|
||||
span.style
|
||||
.add_modifier
|
||||
.contains(ratatui::style::Modifier::BOLD)
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matching_leading_project_title_is_removed_from_the_description() {
|
||||
let document = super::Document::new(
|
||||
"ImmediatelyFast",
|
||||
"# ImmediatelyFast\n\nImmediatelyFast is an open source Minecraft mod.",
|
||||
);
|
||||
let rendered = document
|
||||
.blocks
|
||||
.iter()
|
||||
.filter_map(|block| match block {
|
||||
super::DocumentBlock::Text(text) => Some(text.source.as_str()),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<String>();
|
||||
assert_eq!(rendered.matches("ImmediatelyFast").count(), 1);
|
||||
assert!(!rendered.contains("# ImmediatelyFast"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unrelated_and_later_headings_are_kept() {
|
||||
let document = super::Document::new(
|
||||
"ImmediatelyFast",
|
||||
"# Performance\n\nText\n\n## ImmediatelyFast",
|
||||
);
|
||||
let rendered = document
|
||||
.blocks
|
||||
.iter()
|
||||
.filter_map(|block| match block {
|
||||
super::DocumentBlock::Text(text) => Some(text.source.as_str()),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<String>();
|
||||
assert!(rendered.contains("# Performance"));
|
||||
assert!(rendered.contains("## ImmediatelyFast"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lists_use_terminal_bullets() {
|
||||
let text = super::formatted_text("- first\n - nested\n- second", 20);
|
||||
let rendered = text
|
||||
.lines
|
||||
.iter()
|
||||
.map(|line| {
|
||||
line.spans
|
||||
.iter()
|
||||
.map(|span| span.content.as_ref())
|
||||
.collect::<String>()
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(rendered, [" • first", " • nested", " • second"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrapped_list_items_keep_a_hanging_indent() {
|
||||
let text = super::formatted_text("- one two three four", 16);
|
||||
let rendered = text
|
||||
.lines
|
||||
.iter()
|
||||
.map(|line| {
|
||||
line.spans
|
||||
.iter()
|
||||
.map(|span| span.content.as_ref())
|
||||
.collect::<String>()
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(rendered, [" • one two", " three four"]);
|
||||
assert!(text.lines.iter().all(|line| line.width() <= 16));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn markdown_headings_with_inline_html_are_converted_as_one_block() {
|
||||
let document = super::Document::new(
|
||||
"Project",
|
||||
r#"### Follow me? <a href="https://example.com"><span style="text-decoration: underline;">example.com</span></a>"#,
|
||||
);
|
||||
let source = document
|
||||
.blocks
|
||||
.iter()
|
||||
.find_map(|block| match block {
|
||||
super::DocumentBlock::Text(text) => Some(text.source.as_str()),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
assert!(!source.contains('<'), "{source}");
|
||||
let rendered = super::formatted_text(source, 80)
|
||||
.lines
|
||||
.iter()
|
||||
.flat_map(|line| &line.spans)
|
||||
.map(|span| span.content.as_ref())
|
||||
.collect::<String>();
|
||||
assert_eq!(rendered, "Follow me? example.com");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn html_lists_are_converted_as_one_document() {
|
||||
let document = super::Document::new(
|
||||
"Project",
|
||||
"### Features\n<ul><li><strong>First feature</strong>.</li><li>Second feature.</li></ul>",
|
||||
);
|
||||
let source = document
|
||||
.blocks
|
||||
.iter()
|
||||
.filter_map(|block| match block {
|
||||
super::DocumentBlock::Text(text) => Some(text.source.as_str()),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<String>();
|
||||
assert!(source.contains("- **First feature**."));
|
||||
assert!(source.contains("- Second feature."));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn emphasis_survives_html_list_conversion_without_literal_markers() {
|
||||
let document = super::Document::new(
|
||||
"Project",
|
||||
"<ul><li>The effects are <strong>important</strong> and <em>optional</em>.</li></ul>",
|
||||
);
|
||||
let source = document
|
||||
.blocks
|
||||
.iter()
|
||||
.find_map(|block| match block {
|
||||
super::DocumentBlock::Text(text) => Some(text.source.as_str()),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
let text = super::formatted_text(source, 80);
|
||||
let rendered = text
|
||||
.lines
|
||||
.iter()
|
||||
.flat_map(|line| &line.spans)
|
||||
.map(|span| span.content.as_ref())
|
||||
.collect::<String>();
|
||||
assert!(!rendered.contains('*'));
|
||||
assert!(rendered.contains("important"));
|
||||
assert!(rendered.contains("optional"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn emphasis_next_to_html_tag_boundaries_does_not_leak_markers() {
|
||||
let document = super::Document::new(
|
||||
"Project",
|
||||
concat!(
|
||||
"<ul><li>The effects are <em>xaerominimap:no_cave_maps. ",
|
||||
"</em>The effects are neutral.</li>",
|
||||
"<li><strong>Hostile and friendly</strong> mobs can be colored ",
|
||||
"<strong>differently.</strong>Can also be displayed as icons.</li></ul>"
|
||||
),
|
||||
);
|
||||
let source = document
|
||||
.blocks
|
||||
.iter()
|
||||
.find_map(|block| match block {
|
||||
super::DocumentBlock::Text(text) => Some(text.source.as_str()),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
let rendered = super::formatted_text(source, 100)
|
||||
.lines
|
||||
.iter()
|
||||
.flat_map(|line| &line.spans)
|
||||
.map(|span| span.content.as_ref())
|
||||
.collect::<String>();
|
||||
assert!(!rendered.contains('*'), "{rendered}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fenced_code_blocks_are_rendered_without_fences() {
|
||||
let text = super::formatted_text("```json5\n{\n \"enabled\": true\n}\n```", 24);
|
||||
let rendered = text
|
||||
.lines
|
||||
.iter()
|
||||
.map(|line| {
|
||||
line.spans
|
||||
.iter()
|
||||
.map(|span| span.content.as_ref())
|
||||
.collect::<String>()
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
assert!(
|
||||
rendered
|
||||
.iter()
|
||||
.any(|line| line.contains("\"enabled\": true"))
|
||||
);
|
||||
assert!(rendered.iter().all(|line| !line.contains("```")));
|
||||
let code_lines = text
|
||||
.lines
|
||||
.iter()
|
||||
.filter(|line| line.width() == 24)
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(code_lines.len(), 4);
|
||||
assert!(
|
||||
code_lines.iter().all(|line| {
|
||||
line.style.bg == Some(crate::config::theme::THEME.as_ref().surface())
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tables_wrap_cells_without_breaking_the_columns() {
|
||||
let text = super::formatted_text(
|
||||
"| Mod | Status | Note |\n| --- | --- | --- |\n| Player Animator | Supported | This means mods that use it like Better Combat and Emotecraft |",
|
||||
48,
|
||||
);
|
||||
assert!(text.lines.len() > 3);
|
||||
assert!(text.lines.iter().all(|line| line.width() <= 48));
|
||||
assert!(
|
||||
text.lines
|
||||
.iter()
|
||||
.flat_map(|line| &line.spans)
|
||||
.any(|span| span.content.contains("Emotecraft"))
|
||||
);
|
||||
let column_offsets = text
|
||||
.lines
|
||||
.iter()
|
||||
.filter_map(|line| {
|
||||
let mut offset = 0;
|
||||
let separators = line
|
||||
.spans
|
||||
.iter()
|
||||
.filter_map(|span| {
|
||||
let start = offset;
|
||||
offset += span.width();
|
||||
span.content.contains('│').then_some(start)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
(!separators.is_empty()).then_some(separators)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
assert!(
|
||||
column_offsets.windows(2).all(|pair| pair[0] == pair[1]),
|
||||
"{column_offsets:?}\n{:#?}",
|
||||
text.lines
|
||||
.iter()
|
||||
.map(|line| line
|
||||
.spans
|
||||
.iter()
|
||||
.map(|span| span.content.as_ref())
|
||||
.collect::<String>())
|
||||
.collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rendered_links_keep_click_targets_after_wrapping() {
|
||||
let backend = TestBackend::new(24, 5);
|
||||
let mut terminal = Terminal::new(backend).unwrap();
|
||||
let picker = ratatui_image::picker::Picker::halfblocks();
|
||||
let mut document = super::Document::new(
|
||||
"Project",
|
||||
"Open the [project documentation](https://example.com/docs) here.",
|
||||
);
|
||||
let mut scroll = 0;
|
||||
terminal
|
||||
.draw(|frame| {
|
||||
super::render(frame, frame.area(), &mut document, &mut scroll, &picker);
|
||||
})
|
||||
.unwrap();
|
||||
let hit = document.link_hits.first().unwrap();
|
||||
assert_eq!(
|
||||
document.link_at(hit.area.x, hit.area.y),
|
||||
Some("https://example.com/docs")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn svg_images_are_rasterized_for_terminal_protocols() {
|
||||
let image = super::decode_image(
|
||||
br##"<svg xmlns="http://www.w3.org/2000/svg" width="32" height="16">
|
||||
<rect width="32" height="16" fill="#48a23f"/>
|
||||
</svg>"##,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(image.width(), 32);
|
||||
assert_eq!(image.height(), 16);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gif_images_decode_their_first_frame() {
|
||||
let image = super::decode_image(&[
|
||||
0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x01, 0x00, 0x01, 0x00, 0x80, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0xff, 0xff, 0xff, 0x2c, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00,
|
||||
0x00, 0x02, 0x02, 0x44, 0x01, 0x00, 0x3b,
|
||||
])
|
||||
.unwrap();
|
||||
assert_eq!(image.width(), 1);
|
||||
assert_eq!(image.height(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_rows_align_fitted_images_to_the_bottom() {
|
||||
let picker = ratatui_image::picker::Picker::halfblocks();
|
||||
let image = image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(
|
||||
1,
|
||||
3,
|
||||
image::Rgba([255, 255, 255, 255]),
|
||||
));
|
||||
let aligned = super::bottom_align_to_cells(
|
||||
image,
|
||||
super::ImageRenderKey {
|
||||
width: 1,
|
||||
height: 2,
|
||||
protocol: picker.protocol_type(),
|
||||
mode: crate::config::settings::ImageProtocol::Halfblocks,
|
||||
},
|
||||
&picker,
|
||||
)
|
||||
.to_rgba8();
|
||||
|
||||
assert_eq!(aligned.get_pixel(0, 0).0[3], 0);
|
||||
assert_eq!(aligned.get_pixel(0, aligned.height() - 1).0[3], 255);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn markdown_rendering_clamps_scroll_to_the_document() {
|
||||
let backend = TestBackend::new(40, 8);
|
||||
let mut terminal = Terminal::new(backend).unwrap();
|
||||
let mut scroll = 0;
|
||||
let mut document = super::Document::new(
|
||||
"Project",
|
||||
"**Bold** text\n\n- one\n- two\n- three\n- four\n- five\n- six\n- seven\n- eight\n- nine\n- ten",
|
||||
);
|
||||
let picker = ratatui_image::picker::Picker::halfblocks();
|
||||
let mut max_scroll = 0;
|
||||
|
||||
terminal
|
||||
.draw(|frame| {
|
||||
max_scroll =
|
||||
super::render(frame, frame.area(), &mut document, &mut scroll, &picker);
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
let rendered = terminal
|
||||
.backend()
|
||||
.buffer()
|
||||
.content()
|
||||
.iter()
|
||||
.map(|cell| cell.symbol())
|
||||
.collect::<String>();
|
||||
assert!(rendered.contains("Bold text"));
|
||||
|
||||
scroll = usize::MAX;
|
||||
terminal
|
||||
.draw(|frame| {
|
||||
max_scroll =
|
||||
super::render(frame, frame.area(), &mut document, &mut scroll, &picker);
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(scroll, max_scroll);
|
||||
assert_eq!(terminal.backend().buffer()[(39, 7)].symbol(), "█");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multiple_images_inside_one_link_do_not_overlap() {
|
||||
let document = super::Document::new(
|
||||
"Project",
|
||||
"[ ](https://example.com)",
|
||||
);
|
||||
let mut urls = document.image_urls();
|
||||
urls.sort();
|
||||
assert_eq!(
|
||||
urls,
|
||||
[
|
||||
"https://cdn.example/first.png",
|
||||
"https://cdn.example/second.png"
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
mod tests;
|
||||
@@ -0,0 +1,630 @@
|
||||
use ratatui::{Terminal, backend::TestBackend};
|
||||
|
||||
#[test]
|
||||
fn html_images_are_extracted_and_raw_html_is_removed() {
|
||||
let document = super::Document::new(
|
||||
"Sodium",
|
||||
"<center><img src=\"https://cdn.example/comparison.png\" alt=\"Comparison\"></center>\n\n<h1>Installation</h1>",
|
||||
);
|
||||
assert_eq!(
|
||||
document.image_urls(),
|
||||
vec!["https://cdn.example/comparison.png"]
|
||||
);
|
||||
assert!(matches!(
|
||||
&document.blocks[0],
|
||||
super::DocumentBlock::ImageRow { alignment, .. }
|
||||
if *alignment == super::ImageAlignment::Center
|
||||
));
|
||||
assert!(document.blocks.iter().any(
|
||||
|block| matches!(block, super::DocumentBlock::Text(text) if text.source.contains("Installation") && !text.source.contains("<h1>"))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inline_html_images_use_the_document_image_pipeline() {
|
||||
let document = super::Document::new(
|
||||
"Euphoria Patches",
|
||||
r#"<img src="https://cdn.example/logo.png" alt="Euphoria logo" width="30" /> A shader add-on"#,
|
||||
);
|
||||
assert_eq!(document.image_urls(), vec!["https://cdn.example/logo.png"]);
|
||||
assert!(matches!(
|
||||
&document.blocks[0],
|
||||
super::DocumentBlock::ImageRow { images, .. }
|
||||
if images[0].alt == "Euphoria logo"
|
||||
));
|
||||
assert!(document.blocks.iter().any(
|
||||
|block| matches!(block, super::DocumentBlock::Text(text) if text.source.contains("A shader add-on") && !text.source.contains("<img"))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn html_image_dimensions_are_kept_for_terminal_layout() {
|
||||
let document = super::Document::new(
|
||||
"Euphoria Patches",
|
||||
r#"<img src="https://cdn.example/logo.png" alt="Euphoria logo" width="30" height="auto" />"#,
|
||||
);
|
||||
assert!(matches!(
|
||||
&document.blocks[0],
|
||||
super::DocumentBlock::ImageRow { images, .. }
|
||||
if images[0].size == super::ImageSizeHint {
|
||||
width: Some(30),
|
||||
height: None,
|
||||
}
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn html_width_limits_the_rendered_terminal_image() {
|
||||
let image = super::DocumentImage {
|
||||
load: super::ImageLoad::Ready(image::DynamicImage::new_rgba8(300, 300)),
|
||||
prepared: None,
|
||||
pending: None,
|
||||
};
|
||||
let picker = ratatui_image::picker::Picker::halfblocks();
|
||||
assert_eq!(
|
||||
super::image_dimensions(
|
||||
&image,
|
||||
super::ImageSizeHint {
|
||||
width: Some(30),
|
||||
height: None,
|
||||
},
|
||||
120,
|
||||
&picker,
|
||||
),
|
||||
(3, 2)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inserted_html_keeps_its_content_and_hides_tag_shells() {
|
||||
let document = super::Document::new(
|
||||
"Project",
|
||||
"Support <ins>Reimagined</ins> and <ins>Unbound</ins>.</b>",
|
||||
);
|
||||
let source = document
|
||||
.blocks
|
||||
.iter()
|
||||
.find_map(|block| match block {
|
||||
super::DocumentBlock::Text(text) => Some(text.source.as_str()),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
let text = super::formatted_text(source, 80);
|
||||
let rendered = text
|
||||
.lines
|
||||
.iter()
|
||||
.flat_map(|line| &line.spans)
|
||||
.collect::<Vec<_>>();
|
||||
assert!(rendered.iter().all(|span| !span.content.contains('<')));
|
||||
assert!(
|
||||
["Reimagined", "Unbound"]
|
||||
.iter()
|
||||
.all(|expected| rendered.iter().any(|span| span.content.contains(expected)))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_inline_html_uses_dom_conversion_for_links_and_emphasis() {
|
||||
let document = super::Document::new(
|
||||
"Project",
|
||||
concat!(
|
||||
r#"<span class="badge"><a href="https://example.com">"#,
|
||||
"<strong>Supported</strong></a></span></strong></spanw>"
|
||||
),
|
||||
);
|
||||
let source = document
|
||||
.blocks
|
||||
.iter()
|
||||
.find_map(|block| match block {
|
||||
super::DocumentBlock::Text(text) => Some(text.source.as_str()),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
assert!(source.contains("[**Supported**](https://example.com)"));
|
||||
assert!(!source.contains('<'));
|
||||
|
||||
let text = super::formatted_text(source, 80);
|
||||
let supported = text
|
||||
.lines
|
||||
.iter()
|
||||
.flat_map(|line| &line.spans)
|
||||
.find(|span| span.content.contains("Supported"))
|
||||
.unwrap();
|
||||
assert!(
|
||||
supported
|
||||
.style
|
||||
.add_modifier
|
||||
.contains(ratatui::style::Modifier::BOLD)
|
||||
);
|
||||
assert!(
|
||||
supported
|
||||
.style
|
||||
.add_modifier
|
||||
.contains(ratatui::style::Modifier::UNDERLINED)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn markdown_images_inside_links_do_not_leave_the_link_destination() {
|
||||
let document = super::Document::new(
|
||||
"Project",
|
||||
"[](https://example.com/donate)",
|
||||
);
|
||||
assert_eq!(document.blocks.len(), 1);
|
||||
assert!(matches!(
|
||||
&document.blocks[0],
|
||||
super::DocumentBlock::ImageRow { images, alignment }
|
||||
if images.len() == 1 && images[0].url == "https://cdn.example/button.png"
|
||||
&& images[0].link.as_deref() == Some("https://example.com/donate")
|
||||
&& *alignment == super::ImageAlignment::Left
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn visible_link_text_does_not_include_the_destination() {
|
||||
let text = super::formatted_text("[buying me a coffee](https://example.com/donate)", 80);
|
||||
let rendered = text
|
||||
.lines
|
||||
.iter()
|
||||
.flat_map(|line| &line.spans)
|
||||
.map(|span| span.content.as_ref())
|
||||
.collect::<String>();
|
||||
assert_eq!(rendered, "buying me a coffee");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adjacent_images_share_a_row() {
|
||||
let document = super::Document::new(
|
||||
"Project",
|
||||
"[](https://example.com) [](https://example.com/chat)",
|
||||
);
|
||||
assert!(matches!(
|
||||
&document.blocks[0],
|
||||
super::DocumentBlock::ImageRow { images, .. } if images.len() == 2
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicitly_centered_html_images_share_a_centered_row() {
|
||||
let document = super::Document::new(
|
||||
"Project",
|
||||
r#"<p align="center"><a href="https://example.com"><img src="https://cdn.example/support.svg"></a> <img src="https://cdn.example/chat.svg"></p>"#,
|
||||
);
|
||||
assert!(matches!(
|
||||
&document.blocks[0],
|
||||
super::DocumentBlock::ImageRow { images, alignment }
|
||||
if images.len() == 2 && *alignment == super::ImageAlignment::Center
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_explicitly_centered_project_images_are_centered() {
|
||||
let document = super::Document::new(
|
||||
"Project",
|
||||
concat!(
|
||||
"\n\n",
|
||||
"<center><img src=\"https://cdn.example/comparison.png\"></center>\n\n",
|
||||
""
|
||||
),
|
||||
);
|
||||
let alignments = document
|
||||
.blocks
|
||||
.iter()
|
||||
.filter_map(|block| match block {
|
||||
super::DocumentBlock::ImageRow { alignment, .. } => Some(*alignment),
|
||||
super::DocumentBlock::Text(_) => None,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(
|
||||
alignments,
|
||||
[
|
||||
super::ImageAlignment::Left,
|
||||
super::ImageAlignment::Center,
|
||||
super::ImageAlignment::Left
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn headings_hide_markers_and_rules_use_terminal_lines() {
|
||||
let text = super::formatted_text("## Known Issues\n\n---", 12);
|
||||
let rendered = text
|
||||
.lines
|
||||
.iter()
|
||||
.map(|line| {
|
||||
line.spans
|
||||
.iter()
|
||||
.map(|span| span.content.as_ref())
|
||||
.collect::<String>()
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
assert!(rendered.iter().any(|line| line == "Known Issues"));
|
||||
assert!(rendered.iter().any(|line| line == "────────────"));
|
||||
assert!(!rendered.iter().any(|line| line == "---"));
|
||||
assert!(!rendered.iter().any(|line| line.starts_with('#')));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn all_heading_levels_are_bold() {
|
||||
let text = super::formatted_text("### Performance", 20);
|
||||
let heading = text
|
||||
.lines
|
||||
.iter()
|
||||
.find(|line| {
|
||||
line.spans
|
||||
.iter()
|
||||
.any(|span| span.content.contains("Performance"))
|
||||
})
|
||||
.unwrap();
|
||||
assert!(heading.spans.iter().any(|span| {
|
||||
span.style
|
||||
.add_modifier
|
||||
.contains(ratatui::style::Modifier::BOLD)
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matching_leading_project_title_is_removed_from_the_description() {
|
||||
let document = super::Document::new(
|
||||
"ImmediatelyFast",
|
||||
"# ImmediatelyFast\n\nImmediatelyFast is an open source Minecraft mod.",
|
||||
);
|
||||
let rendered = document
|
||||
.blocks
|
||||
.iter()
|
||||
.filter_map(|block| match block {
|
||||
super::DocumentBlock::Text(text) => Some(text.source.as_str()),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<String>();
|
||||
assert_eq!(rendered.matches("ImmediatelyFast").count(), 1);
|
||||
assert!(!rendered.contains("# ImmediatelyFast"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unrelated_and_later_headings_are_kept() {
|
||||
let document = super::Document::new(
|
||||
"ImmediatelyFast",
|
||||
"# Performance\n\nText\n\n## ImmediatelyFast",
|
||||
);
|
||||
let rendered = document
|
||||
.blocks
|
||||
.iter()
|
||||
.filter_map(|block| match block {
|
||||
super::DocumentBlock::Text(text) => Some(text.source.as_str()),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<String>();
|
||||
assert!(rendered.contains("# Performance"));
|
||||
assert!(rendered.contains("## ImmediatelyFast"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lists_use_terminal_bullets() {
|
||||
let text = super::formatted_text("- first\n - nested\n- second", 20);
|
||||
let rendered = text
|
||||
.lines
|
||||
.iter()
|
||||
.map(|line| {
|
||||
line.spans
|
||||
.iter()
|
||||
.map(|span| span.content.as_ref())
|
||||
.collect::<String>()
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(rendered, [" • first", " • nested", " • second"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrapped_list_items_keep_a_hanging_indent() {
|
||||
let text = super::formatted_text("- one two three four", 16);
|
||||
let rendered = text
|
||||
.lines
|
||||
.iter()
|
||||
.map(|line| {
|
||||
line.spans
|
||||
.iter()
|
||||
.map(|span| span.content.as_ref())
|
||||
.collect::<String>()
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(rendered, [" • one two", " three four"]);
|
||||
assert!(text.lines.iter().all(|line| line.width() <= 16));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn markdown_headings_with_inline_html_are_converted_as_one_block() {
|
||||
let document = super::Document::new(
|
||||
"Project",
|
||||
r#"### Follow me? <a href="https://example.com"><span style="text-decoration: underline;">example.com</span></a>"#,
|
||||
);
|
||||
let source = document
|
||||
.blocks
|
||||
.iter()
|
||||
.find_map(|block| match block {
|
||||
super::DocumentBlock::Text(text) => Some(text.source.as_str()),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
assert!(!source.contains('<'), "{source}");
|
||||
let rendered = super::formatted_text(source, 80)
|
||||
.lines
|
||||
.iter()
|
||||
.flat_map(|line| &line.spans)
|
||||
.map(|span| span.content.as_ref())
|
||||
.collect::<String>();
|
||||
assert_eq!(rendered, "Follow me? example.com");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn html_lists_are_converted_as_one_document() {
|
||||
let document = super::Document::new(
|
||||
"Project",
|
||||
"### Features\n<ul><li><strong>First feature</strong>.</li><li>Second feature.</li></ul>",
|
||||
);
|
||||
let source = document
|
||||
.blocks
|
||||
.iter()
|
||||
.filter_map(|block| match block {
|
||||
super::DocumentBlock::Text(text) => Some(text.source.as_str()),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<String>();
|
||||
assert!(source.contains("- **First feature**."));
|
||||
assert!(source.contains("- Second feature."));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn emphasis_survives_html_list_conversion_without_literal_markers() {
|
||||
let document = super::Document::new(
|
||||
"Project",
|
||||
"<ul><li>The effects are <strong>important</strong> and <em>optional</em>.</li></ul>",
|
||||
);
|
||||
let source = document
|
||||
.blocks
|
||||
.iter()
|
||||
.find_map(|block| match block {
|
||||
super::DocumentBlock::Text(text) => Some(text.source.as_str()),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
let text = super::formatted_text(source, 80);
|
||||
let rendered = text
|
||||
.lines
|
||||
.iter()
|
||||
.flat_map(|line| &line.spans)
|
||||
.map(|span| span.content.as_ref())
|
||||
.collect::<String>();
|
||||
assert!(!rendered.contains('*'));
|
||||
assert!(rendered.contains("important"));
|
||||
assert!(rendered.contains("optional"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn emphasis_next_to_html_tag_boundaries_does_not_leak_markers() {
|
||||
let document = super::Document::new(
|
||||
"Project",
|
||||
concat!(
|
||||
"<ul><li>The effects are <em>xaerominimap:no_cave_maps. ",
|
||||
"</em>The effects are neutral.</li>",
|
||||
"<li><strong>Hostile and friendly</strong> mobs can be colored ",
|
||||
"<strong>differently.</strong>Can also be displayed as icons.</li></ul>"
|
||||
),
|
||||
);
|
||||
let source = document
|
||||
.blocks
|
||||
.iter()
|
||||
.find_map(|block| match block {
|
||||
super::DocumentBlock::Text(text) => Some(text.source.as_str()),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
let rendered = super::formatted_text(source, 100)
|
||||
.lines
|
||||
.iter()
|
||||
.flat_map(|line| &line.spans)
|
||||
.map(|span| span.content.as_ref())
|
||||
.collect::<String>();
|
||||
assert!(!rendered.contains('*'), "{rendered}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fenced_code_blocks_are_rendered_without_fences() {
|
||||
let text = super::formatted_text("```json5\n{\n \"enabled\": true\n}\n```", 24);
|
||||
let rendered = text
|
||||
.lines
|
||||
.iter()
|
||||
.map(|line| {
|
||||
line.spans
|
||||
.iter()
|
||||
.map(|span| span.content.as_ref())
|
||||
.collect::<String>()
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
assert!(
|
||||
rendered
|
||||
.iter()
|
||||
.any(|line| line.contains("\"enabled\": true"))
|
||||
);
|
||||
assert!(rendered.iter().all(|line| !line.contains("```")));
|
||||
let code_lines = text
|
||||
.lines
|
||||
.iter()
|
||||
.filter(|line| line.width() == 24)
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(code_lines.len(), 4);
|
||||
assert!(
|
||||
code_lines
|
||||
.iter()
|
||||
.all(|line| { line.style.bg == Some(crate::config::theme::THEME.as_ref().surface()) })
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tables_wrap_cells_without_breaking_the_columns() {
|
||||
let text = super::formatted_text(
|
||||
"| Mod | Status | Note |\n| --- | --- | --- |\n| Player Animator | Supported | This means mods that use it like Better Combat and Emotecraft |",
|
||||
48,
|
||||
);
|
||||
assert!(text.lines.len() > 3);
|
||||
assert!(text.lines.iter().all(|line| line.width() <= 48));
|
||||
assert!(
|
||||
text.lines
|
||||
.iter()
|
||||
.flat_map(|line| &line.spans)
|
||||
.any(|span| span.content.contains("Emotecraft"))
|
||||
);
|
||||
let column_offsets = text
|
||||
.lines
|
||||
.iter()
|
||||
.filter_map(|line| {
|
||||
let mut offset = 0;
|
||||
let separators = line
|
||||
.spans
|
||||
.iter()
|
||||
.filter_map(|span| {
|
||||
let start = offset;
|
||||
offset += span.width();
|
||||
span.content.contains('│').then_some(start)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
(!separators.is_empty()).then_some(separators)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
assert!(
|
||||
column_offsets.windows(2).all(|pair| pair[0] == pair[1]),
|
||||
"{column_offsets:?}\n{:#?}",
|
||||
text.lines
|
||||
.iter()
|
||||
.map(|line| line
|
||||
.spans
|
||||
.iter()
|
||||
.map(|span| span.content.as_ref())
|
||||
.collect::<String>())
|
||||
.collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rendered_links_keep_click_targets_after_wrapping() {
|
||||
let backend = TestBackend::new(24, 5);
|
||||
let mut terminal = Terminal::new(backend).unwrap();
|
||||
let picker = ratatui_image::picker::Picker::halfblocks();
|
||||
let mut document = super::Document::new(
|
||||
"Project",
|
||||
"Open the [project documentation](https://example.com/docs) here.",
|
||||
);
|
||||
let mut scroll = 0;
|
||||
terminal
|
||||
.draw(|frame| {
|
||||
super::render(frame, frame.area(), &mut document, &mut scroll, &picker);
|
||||
})
|
||||
.unwrap();
|
||||
let hit = document.link_hits.first().unwrap();
|
||||
assert_eq!(
|
||||
document.link_at(hit.area.x, hit.area.y),
|
||||
Some("https://example.com/docs")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn svg_images_are_rasterized_for_terminal_protocols() {
|
||||
let image = super::decode_image(
|
||||
br##"<svg xmlns="http://www.w3.org/2000/svg" width="32" height="16">
|
||||
<rect width="32" height="16" fill="#48a23f"/>
|
||||
</svg>"##,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(image.width(), 32);
|
||||
assert_eq!(image.height(), 16);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gif_images_decode_their_first_frame() {
|
||||
let image = super::decode_image(&[
|
||||
0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x01, 0x00, 0x01, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0xff, 0xff, 0xff, 0x2c, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x02,
|
||||
0x02, 0x44, 0x01, 0x00, 0x3b,
|
||||
])
|
||||
.unwrap();
|
||||
assert_eq!(image.width(), 1);
|
||||
assert_eq!(image.height(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_rows_align_fitted_images_to_the_bottom() {
|
||||
let picker = ratatui_image::picker::Picker::halfblocks();
|
||||
let image = image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(
|
||||
1,
|
||||
3,
|
||||
image::Rgba([255, 255, 255, 255]),
|
||||
));
|
||||
let aligned = super::bottom_align_to_cells(
|
||||
image,
|
||||
super::ImageRenderKey {
|
||||
width: 1,
|
||||
height: 2,
|
||||
protocol: picker.protocol_type(),
|
||||
mode: crate::config::settings::ImageProtocol::Halfblocks,
|
||||
},
|
||||
&picker,
|
||||
)
|
||||
.to_rgba8();
|
||||
|
||||
assert_eq!(aligned.get_pixel(0, 0).0[3], 0);
|
||||
assert_eq!(aligned.get_pixel(0, aligned.height() - 1).0[3], 255);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn markdown_rendering_clamps_scroll_to_the_document() {
|
||||
let backend = TestBackend::new(40, 8);
|
||||
let mut terminal = Terminal::new(backend).unwrap();
|
||||
let mut scroll = 0;
|
||||
let mut document = super::Document::new(
|
||||
"Project",
|
||||
"**Bold** text\n\n- one\n- two\n- three\n- four\n- five\n- six\n- seven\n- eight\n- nine\n- ten",
|
||||
);
|
||||
let picker = ratatui_image::picker::Picker::halfblocks();
|
||||
let mut max_scroll = 0;
|
||||
|
||||
terminal
|
||||
.draw(|frame| {
|
||||
max_scroll = super::render(frame, frame.area(), &mut document, &mut scroll, &picker);
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
let rendered = terminal
|
||||
.backend()
|
||||
.buffer()
|
||||
.content()
|
||||
.iter()
|
||||
.map(|cell| cell.symbol())
|
||||
.collect::<String>();
|
||||
assert!(rendered.contains("Bold text"));
|
||||
|
||||
scroll = usize::MAX;
|
||||
terminal
|
||||
.draw(|frame| {
|
||||
max_scroll = super::render(frame, frame.area(), &mut document, &mut scroll, &picker);
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(scroll, max_scroll);
|
||||
assert_eq!(terminal.backend().buffer()[(39, 7)].symbol(), "█");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multiple_images_inside_one_link_do_not_overlap() {
|
||||
let document = super::Document::new(
|
||||
"Project",
|
||||
"[ ](https://example.com)",
|
||||
);
|
||||
let mut urls = document.image_urls();
|
||||
urls.sort();
|
||||
assert_eq!(
|
||||
urls,
|
||||
[
|
||||
"https://cdn.example/first.png",
|
||||
"https://cdn.example/second.png"
|
||||
]
|
||||
);
|
||||
}
|
||||
@@ -96,112 +96,7 @@ pub fn popup_area(frame_area: Rect, message: &str, base_y: u16, elapsed_ms: u128
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod render_tests {
|
||||
use super::*;
|
||||
use ratatui::Terminal;
|
||||
use ratatui::backend::TestBackend;
|
||||
use std::time::Instant;
|
||||
use tracing::Level;
|
||||
|
||||
use crate::tui::error_buffer::ErrorEvent;
|
||||
|
||||
fn render(event: ErrorEvent, width: u16, height: u16) -> Terminal<TestBackend> {
|
||||
let backend = TestBackend::new(width, height);
|
||||
let mut terminal = Terminal::new(backend).unwrap();
|
||||
terminal
|
||||
.draw(|f| {
|
||||
let popup = ErrorPopup::new(event);
|
||||
f.render_widget(popup, f.area());
|
||||
})
|
||||
.unwrap();
|
||||
terminal
|
||||
}
|
||||
|
||||
fn event(level: Level, message: &str) -> ErrorEvent {
|
||||
ErrorEvent {
|
||||
id: 1,
|
||||
level,
|
||||
message: message.to_string(),
|
||||
pushed_at: Instant::now(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn warn_level_renders() {
|
||||
let term = render(event(Level::WARN, "Disk space low"), 40, 5);
|
||||
insta::assert_snapshot!(term.backend());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn error_level_renders() {
|
||||
let term = render(event(Level::ERROR, "Connection refused"), 40, 5);
|
||||
insta::assert_snapshot!(term.backend());
|
||||
}
|
||||
|
||||
// info-level events hit the catch-all `_` arm in the label match; previously
|
||||
// there was no test covering it.
|
||||
#[test]
|
||||
fn info_level_renders() {
|
||||
let term = render(event(Level::INFO, "Reloaded config"), 40, 5);
|
||||
insta::assert_snapshot!(term.backend());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_message_wraps() {
|
||||
let msg = "The Minecraft launcher could not reach the Mojang version manifest \
|
||||
after three retries. Check your network connection or proxy settings.";
|
||||
let term = render(event(Level::ERROR, msg), 40, 10);
|
||||
insta::assert_snapshot!(term.backend());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn narrow_frame_renders() {
|
||||
let term = render(event(Level::WARN, "Short message"), 18, 5);
|
||||
insta::assert_snapshot!(term.backend());
|
||||
}
|
||||
}
|
||||
mod render_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod area_tests {
|
||||
use super::popup_area;
|
||||
use crate::config::SETTINGS;
|
||||
use ratatui::layout::Rect;
|
||||
|
||||
fn frame() -> Rect {
|
||||
Rect::new(0, 0, 80, 24)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn returns_none_after_dismiss_timeout() {
|
||||
let past_dismiss = SETTINGS.ui.error_auto_dismiss_ms as u128 + 1;
|
||||
assert!(popup_area(frame(), "msg", 0, past_dismiss).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn returns_some_inside_dismiss_window() {
|
||||
assert!(popup_area(frame(), "msg", 0, 0).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn returns_none_when_vertical_room_too_small() {
|
||||
// base_y = 22 leaves only height 24 - 22 - 1 = 1 row of usable space,
|
||||
// less than the minimum 3 needed for border + content + border.
|
||||
assert!(popup_area(frame(), "msg", 22, 0).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clamps_popup_width_to_frame() {
|
||||
// a wider-than-the-frame message gets clamped so the popup fits
|
||||
// inside frame.width minus the right-edge padding (saturating_sub(4)).
|
||||
let huge = "x".repeat(200);
|
||||
let area = popup_area(frame(), &huge, 0, 0).unwrap();
|
||||
assert!(area.width <= frame().width.saturating_sub(4));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn anchors_popup_to_right_edge() {
|
||||
let area = popup_area(frame(), "msg", 0, 0).unwrap();
|
||||
// popup_w is added to base_x to reach frame.width - 2 (right-edge gutter)
|
||||
assert_eq!(area.x + area.width + 2, frame().width);
|
||||
}
|
||||
}
|
||||
mod area_tests;
|
||||
@@ -0,0 +1,41 @@
|
||||
use super::popup_area;
|
||||
use crate::config::SETTINGS;
|
||||
use ratatui::layout::Rect;
|
||||
|
||||
fn frame() -> Rect {
|
||||
Rect::new(0, 0, 80, 24)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn returns_none_after_dismiss_timeout() {
|
||||
let past_dismiss = SETTINGS.ui.error_auto_dismiss_ms as u128 + 1;
|
||||
assert!(popup_area(frame(), "msg", 0, past_dismiss).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn returns_some_inside_dismiss_window() {
|
||||
assert!(popup_area(frame(), "msg", 0, 0).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn returns_none_when_vertical_room_too_small() {
|
||||
// base_y = 22 leaves only height 24 - 22 - 1 = 1 row of usable space,
|
||||
// less than the minimum 3 needed for border + content + border.
|
||||
assert!(popup_area(frame(), "msg", 22, 0).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clamps_popup_width_to_frame() {
|
||||
// a wider-than-the-frame message gets clamped so the popup fits
|
||||
// inside frame.width minus the right-edge padding (saturating_sub(4)).
|
||||
let huge = "x".repeat(200);
|
||||
let area = popup_area(frame(), &huge, 0, 0).unwrap();
|
||||
assert!(area.width <= frame().width.saturating_sub(4));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn anchors_popup_to_right_edge() {
|
||||
let area = popup_area(frame(), "msg", 0, 0).unwrap();
|
||||
// popup_w is added to base_x to reach frame.width - 2 (right-edge gutter)
|
||||
assert_eq!(area.x + area.width + 2, frame().width);
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
use super::*;
|
||||
use ratatui::Terminal;
|
||||
use ratatui::backend::TestBackend;
|
||||
use std::time::Instant;
|
||||
use tracing::Level;
|
||||
|
||||
use crate::tui::error_buffer::ErrorEvent;
|
||||
|
||||
fn render(event: ErrorEvent, width: u16, height: u16) -> Terminal<TestBackend> {
|
||||
let backend = TestBackend::new(width, height);
|
||||
let mut terminal = Terminal::new(backend).unwrap();
|
||||
terminal
|
||||
.draw(|f| {
|
||||
let popup = ErrorPopup::new(event);
|
||||
f.render_widget(popup, f.area());
|
||||
})
|
||||
.unwrap();
|
||||
terminal
|
||||
}
|
||||
|
||||
fn event(level: Level, message: &str) -> ErrorEvent {
|
||||
ErrorEvent {
|
||||
id: 1,
|
||||
level,
|
||||
message: message.to_string(),
|
||||
pushed_at: Instant::now(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn warn_level_renders() {
|
||||
let term = render(event(Level::WARN, "Disk space low"), 40, 5);
|
||||
insta::assert_snapshot!(term.backend());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn error_level_renders() {
|
||||
let term = render(event(Level::ERROR, "Connection refused"), 40, 5);
|
||||
insta::assert_snapshot!(term.backend());
|
||||
}
|
||||
|
||||
// info-level events hit the catch-all `_` arm in the label match; previously
|
||||
// there was no test covering it.
|
||||
#[test]
|
||||
fn info_level_renders() {
|
||||
let term = render(event(Level::INFO, "Reloaded config"), 40, 5);
|
||||
insta::assert_snapshot!(term.backend());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_message_wraps() {
|
||||
let msg = "The Minecraft launcher could not reach the Mojang version manifest \
|
||||
after three retries. Check your network connection or proxy settings.";
|
||||
let term = render(event(Level::ERROR, msg), 40, 10);
|
||||
insta::assert_snapshot!(term.backend());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn narrow_frame_renders() {
|
||||
let term = render(event(Level::WARN, "Short message"), 18, 5);
|
||||
insta::assert_snapshot!(term.backend());
|
||||
}
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
---
|
||||
source: src/tui/widgets/popups/error.rs
|
||||
source: src/tui/widgets/popups/error/render_tests.rs
|
||||
expression: term.backend()
|
||||
---
|
||||
"╭ ERROR ───────────────────────────────╮"
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
---
|
||||
source: src/tui/widgets/popups/error.rs
|
||||
source: src/tui/widgets/popups/error/render_tests.rs
|
||||
expression: term.backend()
|
||||
---
|
||||
"╭ INFO ────────────────────────────────╮"
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
---
|
||||
source: src/tui/widgets/popups/error.rs
|
||||
source: src/tui/widgets/popups/error/render_tests.rs
|
||||
expression: term.backend()
|
||||
---
|
||||
"╭ ERROR ───────────────────────────────╮"
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
---
|
||||
source: src/tui/widgets/popups/error.rs
|
||||
source: src/tui/widgets/popups/error/render_tests.rs
|
||||
expression: term.backend()
|
||||
---
|
||||
"╭ WARN ──────────╮"
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
---
|
||||
source: src/tui/widgets/popups/error.rs
|
||||
source: src/tui/widgets/popups/error/render_tests.rs
|
||||
expression: term.backend()
|
||||
---
|
||||
"╭ WARN ────────────────────────────────╮"
|
||||
@@ -240,158 +240,4 @@ fn step_keybinds(state: &ImportWizardState) -> Line<'static> {
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use ratatui::Terminal;
|
||||
use ratatui::backend::TestBackend;
|
||||
|
||||
// serialise against parallel tests of the same global IMPORT_STATE.
|
||||
static TEST_SERIAL: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
|
||||
fn reset_import_state(step: ImportStep) {
|
||||
let mut guard = IMPORT_STATE.lock().expect("IMPORT_STATE lock");
|
||||
*guard = ImportWizardState::default();
|
||||
guard.step = step;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_modpack_renders_input_step() {
|
||||
let _serial = TEST_SERIAL.lock().unwrap_or_else(|e| e.into_inner());
|
||||
reset_import_state(ImportStep::Input);
|
||||
|
||||
let backend = TestBackend::new(60, 12);
|
||||
let mut terminal = Terminal::new(backend).unwrap();
|
||||
terminal
|
||||
.draw(|f| render(f, f.area(), FocusedArea::ImportPopup))
|
||||
.unwrap();
|
||||
insta::assert_snapshot!(terminal.backend());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_modpack_renders_fetching_step() {
|
||||
let _serial = TEST_SERIAL.lock().unwrap_or_else(|e| e.into_inner());
|
||||
reset_import_state(ImportStep::Fetching);
|
||||
|
||||
let backend = TestBackend::new(60, 12);
|
||||
let mut terminal = Terminal::new(backend).unwrap();
|
||||
terminal
|
||||
.draw(|f| render(f, f.area(), FocusedArea::ImportPopup))
|
||||
.unwrap();
|
||||
insta::assert_snapshot!(terminal.backend());
|
||||
}
|
||||
|
||||
// Version step: pre-populate versions as LoadState::Loaded with synthetic
|
||||
// VersionInfo entries so render walks the list path without triggering
|
||||
// any network helpers.
|
||||
#[test]
|
||||
fn import_modpack_renders_version_step() {
|
||||
use crate::net::modrinth::VersionInfo;
|
||||
|
||||
let _serial = TEST_SERIAL.lock().unwrap_or_else(|e| e.into_inner());
|
||||
{
|
||||
let mut guard = IMPORT_STATE.lock().expect("IMPORT_STATE lock");
|
||||
*guard = ImportWizardState::default();
|
||||
guard.step = ImportStep::Version;
|
||||
guard.project_title = Some("Synthetic Pack".into());
|
||||
guard.versions = LoadState::Loaded(vec![
|
||||
VersionInfo {
|
||||
id: "v1".into(),
|
||||
project_id: "project".into(),
|
||||
name: "1.0.0".into(),
|
||||
version_number: "1.0.0".into(),
|
||||
game_versions: vec!["1.20.1".into()],
|
||||
loaders: vec!["fabric".into()],
|
||||
date_published: String::new(),
|
||||
files: vec![],
|
||||
},
|
||||
VersionInfo {
|
||||
id: "v2".into(),
|
||||
project_id: "project".into(),
|
||||
name: "0.9.0".into(),
|
||||
version_number: "0.9.0".into(),
|
||||
game_versions: vec!["1.20.1".into()],
|
||||
loaders: vec!["fabric".into()],
|
||||
date_published: String::new(),
|
||||
files: vec![],
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
let backend = TestBackend::new(60, 14);
|
||||
let mut terminal = Terminal::new(backend).unwrap();
|
||||
terminal
|
||||
.draw(|f| render(f, f.area(), FocusedArea::ImportPopup))
|
||||
.unwrap();
|
||||
insta::assert_snapshot!(terminal.backend());
|
||||
}
|
||||
|
||||
// Confirm step: needs a populated ImportSummary so the render path
|
||||
// doesn't bail. ImportSummary is constructed manually with synthetic
|
||||
// values; archive_path is a fake tempdir-ish path that never gets read.
|
||||
#[test]
|
||||
fn import_modpack_renders_confirm_step() {
|
||||
use crate::instance::import::{ImportSummary, PackFormat};
|
||||
use crate::instance::models::ModLoader;
|
||||
use std::path::PathBuf;
|
||||
|
||||
let _serial = TEST_SERIAL.lock().unwrap_or_else(|e| e.into_inner());
|
||||
{
|
||||
let mut guard = IMPORT_STATE.lock().expect("IMPORT_STATE lock");
|
||||
*guard = ImportWizardState::default();
|
||||
guard.step = ImportStep::Confirm;
|
||||
guard.summary = Some(ImportSummary {
|
||||
name: "Synthetic Pack".into(),
|
||||
pack_version: "1.0.0".into(),
|
||||
game_version: "1.20.1".into(),
|
||||
loader: ModLoader::Fabric,
|
||||
loader_version: Some("0.15.0".into()),
|
||||
mod_count: 42,
|
||||
override_count: 3,
|
||||
format: PackFormat::Mrpack,
|
||||
archive_path: PathBuf::from("/tmp/synthetic.mrpack"),
|
||||
});
|
||||
}
|
||||
|
||||
let backend = TestBackend::new(60, 14);
|
||||
let mut terminal = Terminal::new(backend).unwrap();
|
||||
terminal
|
||||
.draw(|f| render(f, f.area(), FocusedArea::ImportPopup))
|
||||
.unwrap();
|
||||
insta::assert_snapshot!(terminal.backend());
|
||||
}
|
||||
|
||||
// Confirm step with loader_version=None: covers the branch where the
|
||||
// pack didn't declare a loader version (rare upstream, but happens for
|
||||
// older mmc packs). render_confirm_step has to handle the Option.
|
||||
#[test]
|
||||
fn import_modpack_renders_confirm_step_without_loader_version() {
|
||||
use crate::instance::import::{ImportSummary, PackFormat};
|
||||
use crate::instance::models::ModLoader;
|
||||
use std::path::PathBuf;
|
||||
|
||||
let _serial = TEST_SERIAL.lock().unwrap_or_else(|e| e.into_inner());
|
||||
{
|
||||
let mut guard = IMPORT_STATE.lock().expect("IMPORT_STATE lock");
|
||||
*guard = ImportWizardState::default();
|
||||
guard.step = ImportStep::Confirm;
|
||||
guard.summary = Some(ImportSummary {
|
||||
name: "Vanilla Pack".into(),
|
||||
pack_version: "2.0".into(),
|
||||
game_version: "1.20.1".into(),
|
||||
loader: ModLoader::Vanilla,
|
||||
loader_version: None,
|
||||
mod_count: 0,
|
||||
override_count: 12,
|
||||
format: PackFormat::Mmc,
|
||||
archive_path: PathBuf::from("/tmp/vanilla.zip"),
|
||||
});
|
||||
}
|
||||
|
||||
let backend = TestBackend::new(60, 14);
|
||||
let mut terminal = Terminal::new(backend).unwrap();
|
||||
terminal
|
||||
.draw(|f| render(f, f.area(), FocusedArea::ImportPopup))
|
||||
.unwrap();
|
||||
insta::assert_snapshot!(terminal.backend());
|
||||
}
|
||||
}
|
||||
mod tests;
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
---
|
||||
source: src/tui/widgets/popups/import_modpack/render.rs
|
||||
source: src/tui/widgets/popups/import_modpack/render/tests.rs
|
||||
expression: terminal.backend()
|
||||
---
|
||||
"╭Import Modpack────────────────────────────────────────────╮"
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
---
|
||||
source: src/tui/widgets/popups/import_modpack/render.rs
|
||||
source: src/tui/widgets/popups/import_modpack/render/tests.rs
|
||||
expression: terminal.backend()
|
||||
---
|
||||
"╭Import Modpack────────────────────────────────────────────╮"
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
---
|
||||
source: src/tui/widgets/popups/import_modpack/render.rs
|
||||
source: src/tui/widgets/popups/import_modpack/render/tests.rs
|
||||
expression: terminal.backend()
|
||||
---
|
||||
"╭Import Modpack────────────────────────────────────────────╮"
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
---
|
||||
source: src/tui/widgets/popups/import_modpack/render.rs
|
||||
source: src/tui/widgets/popups/import_modpack/render/tests.rs
|
||||
expression: terminal.backend()
|
||||
---
|
||||
"╭Import Modpack────────────────────────────────────────────╮"
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
---
|
||||
source: src/tui/widgets/popups/import_modpack/render.rs
|
||||
source: src/tui/widgets/popups/import_modpack/render/tests.rs
|
||||
expression: terminal.backend()
|
||||
---
|
||||
"╭Import Modpack────────────────────────────────────────────╮"
|
||||
@@ -0,0 +1,152 @@
|
||||
use super::*;
|
||||
use crate::tui::tests::UI_TEST_LOCK;
|
||||
use ratatui::Terminal;
|
||||
use ratatui::backend::TestBackend;
|
||||
|
||||
// serialise against parallel tests of the same global IMPORT_STATE.
|
||||
fn reset_import_state(step: ImportStep) {
|
||||
let mut guard = IMPORT_STATE.lock().expect("IMPORT_STATE lock");
|
||||
*guard = ImportWizardState::default();
|
||||
guard.step = step;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_modpack_renders_input_step() {
|
||||
let _serial = UI_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
reset_import_state(ImportStep::Input);
|
||||
|
||||
let backend = TestBackend::new(60, 12);
|
||||
let mut terminal = Terminal::new(backend).unwrap();
|
||||
terminal
|
||||
.draw(|f| render(f, f.area(), FocusedArea::ImportPopup))
|
||||
.unwrap();
|
||||
insta::assert_snapshot!(terminal.backend());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_modpack_renders_fetching_step() {
|
||||
let _serial = UI_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
reset_import_state(ImportStep::Fetching);
|
||||
|
||||
let backend = TestBackend::new(60, 12);
|
||||
let mut terminal = Terminal::new(backend).unwrap();
|
||||
terminal
|
||||
.draw(|f| render(f, f.area(), FocusedArea::ImportPopup))
|
||||
.unwrap();
|
||||
insta::assert_snapshot!(terminal.backend());
|
||||
}
|
||||
|
||||
// Version step: pre-populate versions as LoadState::Loaded with synthetic
|
||||
// VersionInfo entries so render walks the list path without triggering
|
||||
// any network helpers.
|
||||
#[test]
|
||||
fn import_modpack_renders_version_step() {
|
||||
use crate::net::modrinth::VersionInfo;
|
||||
|
||||
let _serial = UI_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
{
|
||||
let mut guard = IMPORT_STATE.lock().expect("IMPORT_STATE lock");
|
||||
*guard = ImportWizardState::default();
|
||||
guard.step = ImportStep::Version;
|
||||
guard.project_title = Some("Synthetic Pack".into());
|
||||
guard.versions = LoadState::Loaded(vec![
|
||||
VersionInfo {
|
||||
id: "v1".into(),
|
||||
project_id: "project".into(),
|
||||
name: "1.0.0".into(),
|
||||
version_number: "1.0.0".into(),
|
||||
game_versions: vec!["1.20.1".into()],
|
||||
loaders: vec!["fabric".into()],
|
||||
date_published: String::new(),
|
||||
files: vec![],
|
||||
},
|
||||
VersionInfo {
|
||||
id: "v2".into(),
|
||||
project_id: "project".into(),
|
||||
name: "0.9.0".into(),
|
||||
version_number: "0.9.0".into(),
|
||||
game_versions: vec!["1.20.1".into()],
|
||||
loaders: vec!["fabric".into()],
|
||||
date_published: String::new(),
|
||||
files: vec![],
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
let backend = TestBackend::new(60, 14);
|
||||
let mut terminal = Terminal::new(backend).unwrap();
|
||||
terminal
|
||||
.draw(|f| render(f, f.area(), FocusedArea::ImportPopup))
|
||||
.unwrap();
|
||||
insta::assert_snapshot!(terminal.backend());
|
||||
}
|
||||
|
||||
// Confirm step: needs a populated ImportSummary so the render path
|
||||
// doesn't bail. ImportSummary is constructed manually with synthetic
|
||||
// values; archive_path is a fake tempdir-ish path that never gets read.
|
||||
#[test]
|
||||
fn import_modpack_renders_confirm_step() {
|
||||
use crate::instance::import::{ImportSummary, PackFormat};
|
||||
use crate::instance::models::ModLoader;
|
||||
use std::path::PathBuf;
|
||||
|
||||
let _serial = UI_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
{
|
||||
let mut guard = IMPORT_STATE.lock().expect("IMPORT_STATE lock");
|
||||
*guard = ImportWizardState::default();
|
||||
guard.step = ImportStep::Confirm;
|
||||
guard.summary = Some(ImportSummary {
|
||||
name: "Synthetic Pack".into(),
|
||||
pack_version: "1.0.0".into(),
|
||||
game_version: "1.20.1".into(),
|
||||
loader: ModLoader::Fabric,
|
||||
loader_version: Some("0.15.0".into()),
|
||||
mod_count: 42,
|
||||
override_count: 3,
|
||||
format: PackFormat::Mrpack,
|
||||
archive_path: PathBuf::from("/tmp/synthetic.mrpack"),
|
||||
});
|
||||
}
|
||||
|
||||
let backend = TestBackend::new(60, 14);
|
||||
let mut terminal = Terminal::new(backend).unwrap();
|
||||
terminal
|
||||
.draw(|f| render(f, f.area(), FocusedArea::ImportPopup))
|
||||
.unwrap();
|
||||
insta::assert_snapshot!(terminal.backend());
|
||||
}
|
||||
|
||||
// Confirm step with loader_version=None: covers the branch where the
|
||||
// pack didn't declare a loader version (rare upstream, but happens for
|
||||
// older mmc packs). render_confirm_step has to handle the Option.
|
||||
#[test]
|
||||
fn import_modpack_renders_confirm_step_without_loader_version() {
|
||||
use crate::instance::import::{ImportSummary, PackFormat};
|
||||
use crate::instance::models::ModLoader;
|
||||
use std::path::PathBuf;
|
||||
|
||||
let _serial = UI_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
{
|
||||
let mut guard = IMPORT_STATE.lock().expect("IMPORT_STATE lock");
|
||||
*guard = ImportWizardState::default();
|
||||
guard.step = ImportStep::Confirm;
|
||||
guard.summary = Some(ImportSummary {
|
||||
name: "Vanilla Pack".into(),
|
||||
pack_version: "2.0".into(),
|
||||
game_version: "1.20.1".into(),
|
||||
loader: ModLoader::Vanilla,
|
||||
loader_version: None,
|
||||
mod_count: 0,
|
||||
override_count: 12,
|
||||
format: PackFormat::Mmc,
|
||||
archive_path: PathBuf::from("/tmp/vanilla.zip"),
|
||||
});
|
||||
}
|
||||
|
||||
let backend = TestBackend::new(60, 14);
|
||||
let mut terminal = Terminal::new(backend).unwrap();
|
||||
terminal
|
||||
.draw(|f| render(f, f.area(), FocusedArea::ImportPopup))
|
||||
.unwrap();
|
||||
insta::assert_snapshot!(terminal.backend());
|
||||
}
|
||||
@@ -465,3 +465,6 @@ fn clamp_version_index(state: &mut ImportWizardState) {
|
||||
state.version_idx = count.saturating_sub(1);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,71 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
|
||||
|
||||
use super::*;
|
||||
use crate::instance::{
|
||||
ModLoader,
|
||||
import::{ImportSummary, PackFormat},
|
||||
};
|
||||
use crate::tui::tests::UI_TEST_LOCK;
|
||||
|
||||
fn key(code: KeyCode) -> KeyEvent {
|
||||
KeyEvent::new(code, KeyModifiers::NONE)
|
||||
}
|
||||
|
||||
fn summary() -> ImportSummary {
|
||||
ImportSummary {
|
||||
name: "Test Pack".to_owned(),
|
||||
pack_version: "1.0.0".to_owned(),
|
||||
game_version: "1.21.1".to_owned(),
|
||||
loader: ModLoader::Fabric,
|
||||
loader_version: Some("0.16.14".to_owned()),
|
||||
mod_count: 2,
|
||||
override_count: 1,
|
||||
format: PackFormat::Mrpack,
|
||||
archive_path: PathBuf::from("test.mrpack"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_input_is_ignored_and_escape_closes_the_popup() {
|
||||
let _guard = UI_TEST_LOCK
|
||||
.lock()
|
||||
.unwrap_or_else(|error| error.into_inner());
|
||||
let mut instances = instances::State {
|
||||
show_import_popup: true,
|
||||
..instances::State::default()
|
||||
};
|
||||
*IMPORT_STATE.lock().unwrap() = ImportWizardState::default();
|
||||
|
||||
handle_key(&key(KeyCode::Enter), &mut instances);
|
||||
assert_eq!(IMPORT_STATE.lock().unwrap().step, ImportStep::Input);
|
||||
|
||||
handle_key(&key(KeyCode::Esc), &mut instances);
|
||||
assert!(!instances.show_import_popup);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn confirm_returns_the_import_summary() {
|
||||
let _guard = UI_TEST_LOCK
|
||||
.lock()
|
||||
.unwrap_or_else(|error| error.into_inner());
|
||||
let mut instances = instances::State {
|
||||
show_import_popup: true,
|
||||
..instances::State::default()
|
||||
};
|
||||
{
|
||||
let mut state = IMPORT_STATE.lock().unwrap();
|
||||
*state = ImportWizardState {
|
||||
step: ImportStep::Confirm,
|
||||
summary: Some(summary()),
|
||||
..ImportWizardState::default()
|
||||
};
|
||||
}
|
||||
*IMPORT_RESULT.lock().unwrap() = None;
|
||||
|
||||
handle_key(&key(KeyCode::Enter), &mut instances);
|
||||
let result = take_result().expect("import result");
|
||||
assert_eq!(result.summary.name, "Test Pack");
|
||||
assert!(!instances.show_import_popup);
|
||||
}
|
||||
@@ -320,146 +320,4 @@ fn render_confirm_step(state: &WizardState, area: Rect, buf: &mut ratatui::buffe
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use ratatui::Terminal;
|
||||
use ratatui::backend::TestBackend;
|
||||
|
||||
// WIZARD_STATE is a process-global static; without serialisation, parallel
|
||||
// tests would race when each test sets the step and then renders, since
|
||||
// render re-acquires the WIZARD_STATE mutex internally. this guard mutex
|
||||
// ensures only one wizard snapshot test runs at a time.
|
||||
static TEST_SERIAL: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
|
||||
fn reset_wizard_state(step: WizardStep) {
|
||||
let mut guard = WIZARD_STATE.lock().expect("WIZARD_STATE lock");
|
||||
*guard = WizardState::default();
|
||||
guard.step = step;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_instance_renders_name_step() {
|
||||
let _serial = TEST_SERIAL.lock().unwrap_or_else(|e| e.into_inner());
|
||||
// Name is the default step; render touches no network helpers.
|
||||
reset_wizard_state(WizardStep::Name);
|
||||
|
||||
let backend = TestBackend::new(60, 12);
|
||||
let mut terminal = Terminal::new(backend).unwrap();
|
||||
terminal
|
||||
.draw(|f| render(f, f.area(), FocusedArea::Popup))
|
||||
.unwrap();
|
||||
insta::assert_snapshot!(terminal.backend());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_instance_renders_loader_step() {
|
||||
let _serial = TEST_SERIAL.lock().unwrap_or_else(|e| e.into_inner());
|
||||
// Loader step is reached after Name; render just paints the hardcoded
|
||||
// loader list, no network.
|
||||
reset_wizard_state(WizardStep::Loader);
|
||||
|
||||
let backend = TestBackend::new(60, 12);
|
||||
let mut terminal = Terminal::new(backend).unwrap();
|
||||
terminal
|
||||
.draw(|f| render(f, f.area(), FocusedArea::Popup))
|
||||
.unwrap();
|
||||
insta::assert_snapshot!(terminal.backend());
|
||||
}
|
||||
|
||||
// Version step: pre-populate versions as LoadState::Loaded so
|
||||
// ensure_versions_loaded short-circuits and never spawns a network task.
|
||||
// the three synthetic versions are marked stable=true so they show with
|
||||
// show_snapshots=false (the default).
|
||||
#[test]
|
||||
fn new_instance_renders_version_step() {
|
||||
use crate::instance::loader::GameVersion;
|
||||
|
||||
let _serial = TEST_SERIAL.lock().unwrap_or_else(|e| e.into_inner());
|
||||
{
|
||||
let mut guard = WIZARD_STATE.lock().expect("WIZARD_STATE lock");
|
||||
*guard = WizardState::default();
|
||||
guard.step = WizardStep::Version;
|
||||
guard.versions = LoadState::Loaded(vec![
|
||||
GameVersion {
|
||||
id: "1.20.1".into(),
|
||||
stable: true,
|
||||
},
|
||||
GameVersion {
|
||||
id: "1.19.4".into(),
|
||||
stable: true,
|
||||
},
|
||||
GameVersion {
|
||||
id: "1.18.2".into(),
|
||||
stable: true,
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
let backend = TestBackend::new(60, 14);
|
||||
let mut terminal = Terminal::new(backend).unwrap();
|
||||
terminal
|
||||
.draw(|f| render(f, f.area(), FocusedArea::Popup))
|
||||
.unwrap();
|
||||
insta::assert_snapshot!(terminal.backend());
|
||||
}
|
||||
|
||||
// LoaderVersion step: needs both versions and loader_versions pre-loaded.
|
||||
// pick a non-Vanilla loader (loader_idx=2 = Forge) so the step doesn't
|
||||
// skip itself to Confirm.
|
||||
#[test]
|
||||
fn new_instance_renders_loader_version_step() {
|
||||
use crate::instance::loader::GameVersion;
|
||||
|
||||
let _serial = TEST_SERIAL.lock().unwrap_or_else(|e| e.into_inner());
|
||||
{
|
||||
let mut guard = WIZARD_STATE.lock().expect("WIZARD_STATE lock");
|
||||
*guard = WizardState::default();
|
||||
guard.step = WizardStep::LoaderVersion;
|
||||
guard.loader_idx = 2; // Forge
|
||||
guard.versions = LoadState::Loaded(vec![GameVersion {
|
||||
id: "1.20.1".into(),
|
||||
stable: true,
|
||||
}]);
|
||||
guard.loader_versions =
|
||||
LoadState::Loaded(vec!["47.2.0".into(), "47.1.0".into(), "47.0.50".into()]);
|
||||
}
|
||||
|
||||
let backend = TestBackend::new(60, 14);
|
||||
let mut terminal = Terminal::new(backend).unwrap();
|
||||
terminal
|
||||
.draw(|f| render(f, f.area(), FocusedArea::Popup))
|
||||
.unwrap();
|
||||
insta::assert_snapshot!(terminal.backend());
|
||||
}
|
||||
|
||||
// Confirm step: paints a summary, no network, no list. requires
|
||||
// versions + loader_versions Loaded so selected_*() return Some.
|
||||
#[test]
|
||||
fn new_instance_renders_confirm_step() {
|
||||
use crate::instance::loader::GameVersion;
|
||||
use tui_prompts::TextState;
|
||||
|
||||
let _serial = TEST_SERIAL.lock().unwrap_or_else(|e| e.into_inner());
|
||||
{
|
||||
let mut guard = WIZARD_STATE.lock().expect("WIZARD_STATE lock");
|
||||
*guard = WizardState::default();
|
||||
guard.step = WizardStep::Confirm;
|
||||
guard.loader_idx = 1; // Fabric
|
||||
guard.versions = LoadState::Loaded(vec![GameVersion {
|
||||
id: "1.20.1".into(),
|
||||
stable: true,
|
||||
}]);
|
||||
guard.loader_versions = LoadState::Loaded(vec!["0.15.0".into()]);
|
||||
// TextState exposes only constructors; rebuilding with the
|
||||
// desired initial value is the supported path.
|
||||
guard.name_state = TextState::new().with_value("MyPack");
|
||||
}
|
||||
|
||||
let backend = TestBackend::new(60, 12);
|
||||
let mut terminal = Terminal::new(backend).unwrap();
|
||||
terminal
|
||||
.draw(|f| render(f, f.area(), FocusedArea::Popup))
|
||||
.unwrap();
|
||||
insta::assert_snapshot!(terminal.backend());
|
||||
}
|
||||
}
|
||||
mod tests;
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
---
|
||||
source: src/tui/widgets/popups/new_instance/render.rs
|
||||
source: src/tui/widgets/popups/new_instance/render/tests.rs
|
||||
expression: terminal.backend()
|
||||
---
|
||||
"╭New Instance──────────────────────────────────────────────╮"
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
---
|
||||
source: src/tui/widgets/popups/new_instance/render.rs
|
||||
source: src/tui/widgets/popups/new_instance/render/tests.rs
|
||||
expression: terminal.backend()
|
||||
---
|
||||
"╭New Instance──────────────────────────────────────────────╮"
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
---
|
||||
source: src/tui/widgets/popups/new_instance/render.rs
|
||||
source: src/tui/widgets/popups/new_instance/render/tests.rs
|
||||
expression: terminal.backend()
|
||||
---
|
||||
"╭New Instance──────────────────────────────────────────────╮"
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
---
|
||||
source: src/tui/widgets/popups/new_instance/render.rs
|
||||
source: src/tui/widgets/popups/new_instance/render/tests.rs
|
||||
expression: terminal.backend()
|
||||
---
|
||||
"╭New Instance──────────────────────────────────────────────╮"
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
---
|
||||
source: src/tui/widgets/popups/new_instance/render.rs
|
||||
source: src/tui/widgets/popups/new_instance/render/tests.rs
|
||||
expression: terminal.backend()
|
||||
---
|
||||
"╭New Instance──────────────────────────────────────────────╮"
|
||||
@@ -0,0 +1,140 @@
|
||||
use super::*;
|
||||
use crate::tui::tests::UI_TEST_LOCK;
|
||||
use ratatui::Terminal;
|
||||
use ratatui::backend::TestBackend;
|
||||
|
||||
// WIZARD_STATE is a process-global static; without serialisation, parallel
|
||||
// tests would race when each test sets the step and then renders, since
|
||||
// render re-acquires the WIZARD_STATE mutex internally. this guard mutex
|
||||
// ensures only one wizard snapshot test runs at a time.
|
||||
fn reset_wizard_state(step: WizardStep) {
|
||||
let mut guard = WIZARD_STATE.lock().expect("WIZARD_STATE lock");
|
||||
*guard = WizardState::default();
|
||||
guard.step = step;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_instance_renders_name_step() {
|
||||
let _serial = UI_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
// Name is the default step; render touches no network helpers.
|
||||
reset_wizard_state(WizardStep::Name);
|
||||
|
||||
let backend = TestBackend::new(60, 12);
|
||||
let mut terminal = Terminal::new(backend).unwrap();
|
||||
terminal
|
||||
.draw(|f| render(f, f.area(), FocusedArea::Popup))
|
||||
.unwrap();
|
||||
insta::assert_snapshot!(terminal.backend());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_instance_renders_loader_step() {
|
||||
let _serial = UI_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
// Loader step is reached after Name; render just paints the hardcoded
|
||||
// loader list, no network.
|
||||
reset_wizard_state(WizardStep::Loader);
|
||||
|
||||
let backend = TestBackend::new(60, 12);
|
||||
let mut terminal = Terminal::new(backend).unwrap();
|
||||
terminal
|
||||
.draw(|f| render(f, f.area(), FocusedArea::Popup))
|
||||
.unwrap();
|
||||
insta::assert_snapshot!(terminal.backend());
|
||||
}
|
||||
|
||||
// Version step: pre-populate versions as LoadState::Loaded so
|
||||
// ensure_versions_loaded short-circuits and never spawns a network task.
|
||||
// the three synthetic versions are marked stable=true so they show with
|
||||
// show_snapshots=false (the default).
|
||||
#[test]
|
||||
fn new_instance_renders_version_step() {
|
||||
use crate::instance::loader::GameVersion;
|
||||
|
||||
let _serial = UI_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
{
|
||||
let mut guard = WIZARD_STATE.lock().expect("WIZARD_STATE lock");
|
||||
*guard = WizardState::default();
|
||||
guard.step = WizardStep::Version;
|
||||
guard.versions = LoadState::Loaded(vec![
|
||||
GameVersion {
|
||||
id: "1.20.1".into(),
|
||||
stable: true,
|
||||
},
|
||||
GameVersion {
|
||||
id: "1.19.4".into(),
|
||||
stable: true,
|
||||
},
|
||||
GameVersion {
|
||||
id: "1.18.2".into(),
|
||||
stable: true,
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
let backend = TestBackend::new(60, 14);
|
||||
let mut terminal = Terminal::new(backend).unwrap();
|
||||
terminal
|
||||
.draw(|f| render(f, f.area(), FocusedArea::Popup))
|
||||
.unwrap();
|
||||
insta::assert_snapshot!(terminal.backend());
|
||||
}
|
||||
|
||||
// LoaderVersion step: needs both versions and loader_versions pre-loaded.
|
||||
// pick a non-Vanilla loader (loader_idx=2 = Forge) so the step doesn't
|
||||
// skip itself to Confirm.
|
||||
#[test]
|
||||
fn new_instance_renders_loader_version_step() {
|
||||
use crate::instance::loader::GameVersion;
|
||||
|
||||
let _serial = UI_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
{
|
||||
let mut guard = WIZARD_STATE.lock().expect("WIZARD_STATE lock");
|
||||
*guard = WizardState::default();
|
||||
guard.step = WizardStep::LoaderVersion;
|
||||
guard.loader_idx = 2; // Forge
|
||||
guard.versions = LoadState::Loaded(vec![GameVersion {
|
||||
id: "1.20.1".into(),
|
||||
stable: true,
|
||||
}]);
|
||||
guard.loader_versions =
|
||||
LoadState::Loaded(vec!["47.2.0".into(), "47.1.0".into(), "47.0.50".into()]);
|
||||
}
|
||||
|
||||
let backend = TestBackend::new(60, 14);
|
||||
let mut terminal = Terminal::new(backend).unwrap();
|
||||
terminal
|
||||
.draw(|f| render(f, f.area(), FocusedArea::Popup))
|
||||
.unwrap();
|
||||
insta::assert_snapshot!(terminal.backend());
|
||||
}
|
||||
|
||||
// Confirm step: paints a summary, no network, no list. requires
|
||||
// versions + loader_versions Loaded so selected_*() return Some.
|
||||
#[test]
|
||||
fn new_instance_renders_confirm_step() {
|
||||
use crate::instance::loader::GameVersion;
|
||||
use tui_prompts::TextState;
|
||||
|
||||
let _serial = UI_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
{
|
||||
let mut guard = WIZARD_STATE.lock().expect("WIZARD_STATE lock");
|
||||
*guard = WizardState::default();
|
||||
guard.step = WizardStep::Confirm;
|
||||
guard.loader_idx = 1; // Fabric
|
||||
guard.versions = LoadState::Loaded(vec![GameVersion {
|
||||
id: "1.20.1".into(),
|
||||
stable: true,
|
||||
}]);
|
||||
guard.loader_versions = LoadState::Loaded(vec!["0.15.0".into()]);
|
||||
// TextState exposes only constructors; rebuilding with the
|
||||
// desired initial value is the supported path.
|
||||
guard.name_state = TextState::new().with_value("MyPack");
|
||||
}
|
||||
|
||||
let backend = TestBackend::new(60, 12);
|
||||
let mut terminal = Terminal::new(backend).unwrap();
|
||||
terminal
|
||||
.draw(|f| render(f, f.area(), FocusedArea::Popup))
|
||||
.unwrap();
|
||||
insta::assert_snapshot!(terminal.backend());
|
||||
}
|
||||
@@ -480,3 +480,6 @@ fn compare_semver(a: &str, b: &str) -> std::cmp::Ordering {
|
||||
fn sort_versions_semver(versions: &mut [GameVersion]) {
|
||||
versions.sort_by(|a, b| compare_semver(&b.id, &a.id));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,74 @@
|
||||
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
|
||||
use tui_prompts::TextState;
|
||||
|
||||
use super::*;
|
||||
use crate::tui::tests::UI_TEST_LOCK;
|
||||
|
||||
fn key(code: KeyCode) -> KeyEvent {
|
||||
KeyEvent::new(code, KeyModifiers::NONE)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vanilla_wizard_reaches_confirm_and_returns_parameters() {
|
||||
let _guard = UI_TEST_LOCK
|
||||
.lock()
|
||||
.unwrap_or_else(|error| error.into_inner());
|
||||
let mut instances = instances::State {
|
||||
show_popup: true,
|
||||
..instances::State::default()
|
||||
};
|
||||
|
||||
{
|
||||
let mut state = WIZARD_STATE.lock().unwrap();
|
||||
*state = WizardState::default();
|
||||
state.name_state = TextState::new().with_value("Test Instance");
|
||||
}
|
||||
*WIZARD_RESULT.lock().unwrap() = None;
|
||||
|
||||
handle_key(&key(KeyCode::Enter), &mut instances);
|
||||
assert_eq!(WIZARD_STATE.lock().unwrap().step, WizardStep::Loader);
|
||||
|
||||
{
|
||||
let mut state = WIZARD_STATE.lock().unwrap();
|
||||
state.step = WizardStep::Version;
|
||||
state.versions = LoadState::Loaded(vec![GameVersion {
|
||||
id: "1.21.1".to_owned(),
|
||||
stable: true,
|
||||
}]);
|
||||
}
|
||||
handle_key(&key(KeyCode::Enter), &mut instances);
|
||||
assert_eq!(WIZARD_STATE.lock().unwrap().step, WizardStep::Confirm);
|
||||
|
||||
handle_key(&key(KeyCode::Enter), &mut instances);
|
||||
let result = take_result().expect("wizard result");
|
||||
assert_eq!(result.name, "Test Instance");
|
||||
assert_eq!(result.game_version, "1.21.1");
|
||||
assert_eq!(result.loader, ModLoader::Vanilla);
|
||||
assert_eq!(result.loader_version, None);
|
||||
assert!(!instances.show_popup);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn version_filter_clamps_a_stale_selection() {
|
||||
let mut state = WizardState {
|
||||
versions: LoadState::Loaded(vec![
|
||||
GameVersion {
|
||||
id: "1.21.1".to_owned(),
|
||||
stable: true,
|
||||
},
|
||||
GameVersion {
|
||||
id: "25w01a".to_owned(),
|
||||
stable: false,
|
||||
},
|
||||
]),
|
||||
version_idx: 9,
|
||||
..WizardState::default()
|
||||
};
|
||||
|
||||
clamp_version_index(&mut state);
|
||||
assert_eq!(state.version_idx, 0);
|
||||
assert_eq!(visible_versions(&state).len(), 1);
|
||||
|
||||
state.show_snapshots = true;
|
||||
assert_eq!(visible_versions(&state).len(), 2);
|
||||
}
|
||||
@@ -449,3 +449,6 @@ pub fn render(frame: &mut Frame, area: Rect, state: &mut ScreenshotsState, is_fo
|
||||
&mut state.scrollbar_state,
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,48 @@
|
||||
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
|
||||
|
||||
use super::*;
|
||||
|
||||
fn key(code: KeyCode, modifiers: KeyModifiers) -> KeyEvent {
|
||||
KeyEvent::new(code, modifiers)
|
||||
}
|
||||
|
||||
fn entry(name: &str) -> ScreenshotEntry {
|
||||
ScreenshotEntry {
|
||||
name: name.to_owned(),
|
||||
path: name.into(),
|
||||
width: 1920,
|
||||
height: 1080,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grid_navigation_and_search_clamp_the_selection() {
|
||||
let mut state = ScreenshotsState {
|
||||
entries: vec![entry("one.png"), entry("two.png"), entry("three.png")],
|
||||
cols: 2,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
assert!(handle_key(
|
||||
&key(KeyCode::Right, KeyModifiers::SHIFT),
|
||||
&mut state
|
||||
));
|
||||
assert_eq!(state.selected, 1);
|
||||
|
||||
assert!(handle_key(
|
||||
&key(KeyCode::Down, KeyModifiers::SHIFT),
|
||||
&mut state
|
||||
));
|
||||
assert_eq!(state.selected, 1);
|
||||
|
||||
assert!(handle_key(
|
||||
&key(KeyCode::Char('/'), KeyModifiers::NONE),
|
||||
&mut state
|
||||
));
|
||||
assert!(handle_key(
|
||||
&key(KeyCode::Char('t'), KeyModifiers::NONE),
|
||||
&mut state
|
||||
));
|
||||
assert_eq!(state.selected, 0);
|
||||
assert_eq!(state.search.query, "t");
|
||||
}
|
||||
@@ -118,67 +118,4 @@ impl SearchState {
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn confirm_keeps_query_but_deactivates() {
|
||||
let mut s = SearchState::default();
|
||||
s.activate();
|
||||
s.push('a');
|
||||
s.push('b');
|
||||
s.confirm();
|
||||
assert!(!s.active);
|
||||
assert_eq!(s.query, "ab");
|
||||
// filter should still match
|
||||
assert!(s.matches("abc"));
|
||||
assert!(!s.matches("xyz"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deactivate_clears_query() {
|
||||
let mut s = SearchState::default();
|
||||
s.activate();
|
||||
s.push('x');
|
||||
s.deactivate();
|
||||
assert!(!s.active);
|
||||
assert!(s.query.is_empty());
|
||||
// with empty query, everything matches
|
||||
assert!(s.matches("anything"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn confirm_then_reactivate_preserves_query() {
|
||||
let mut s = SearchState::default();
|
||||
s.activate();
|
||||
s.push('t');
|
||||
s.push('e');
|
||||
s.confirm();
|
||||
// user presses search key again to edit
|
||||
s.activate();
|
||||
assert!(s.active);
|
||||
assert_eq!(s.query, "te");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn highlight_spans_marks_each_case_insensitive_match() {
|
||||
let search = SearchState {
|
||||
query: "di".to_owned(),
|
||||
..SearchState::default()
|
||||
};
|
||||
|
||||
let spans = search.highlight_spans("Discovery DISK", Style::default());
|
||||
|
||||
assert_eq!(
|
||||
spans
|
||||
.iter()
|
||||
.map(|span| span.content.as_ref())
|
||||
.collect::<String>(),
|
||||
"Discovery DISK"
|
||||
);
|
||||
assert!(spans[0].style.add_modifier.contains(Modifier::BOLD));
|
||||
assert!(spans[0].style.add_modifier.contains(Modifier::UNDERLINED));
|
||||
assert!(spans[2].style.add_modifier.contains(Modifier::BOLD));
|
||||
assert!(spans[2].style.add_modifier.contains(Modifier::UNDERLINED));
|
||||
}
|
||||
}
|
||||
mod tests;
|
||||
@@ -0,0 +1,52 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn confirm_keeps_query_but_deactivates() {
|
||||
let mut s = SearchState::default();
|
||||
s.activate();
|
||||
s.push('a');
|
||||
s.push('b');
|
||||
s.confirm();
|
||||
assert!(!s.active);
|
||||
assert_eq!(s.query, "ab");
|
||||
// filter should still match
|
||||
assert!(s.matches("abc"));
|
||||
assert!(!s.matches("xyz"));
|
||||
s.activate();
|
||||
assert!(s.active);
|
||||
assert_eq!(s.query, "ab");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deactivate_clears_query() {
|
||||
let mut s = SearchState::default();
|
||||
s.activate();
|
||||
s.push('x');
|
||||
s.deactivate();
|
||||
assert!(!s.active);
|
||||
assert!(s.query.is_empty());
|
||||
// with empty query, everything matches
|
||||
assert!(s.matches("anything"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn highlight_spans_marks_each_case_insensitive_match() {
|
||||
let search = SearchState {
|
||||
query: "di".to_owned(),
|
||||
..SearchState::default()
|
||||
};
|
||||
|
||||
let spans = search.highlight_spans("Discovery DISK", Style::default());
|
||||
|
||||
assert_eq!(
|
||||
spans
|
||||
.iter()
|
||||
.map(|span| span.content.as_ref())
|
||||
.collect::<String>(),
|
||||
"Discovery DISK"
|
||||
);
|
||||
assert!(spans[0].style.add_modifier.contains(Modifier::BOLD));
|
||||
assert!(spans[0].style.add_modifier.contains(Modifier::UNDERLINED));
|
||||
assert!(spans[2].style.add_modifier.contains(Modifier::BOLD));
|
||||
assert!(spans[2].style.add_modifier.contains(Modifier::UNDERLINED));
|
||||
}
|
||||
@@ -565,21 +565,4 @@ pub fn handle_key(
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn removing_selected_last_profile_clamps_selection() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mut state = SettingsState::new(tmp.path().to_path_buf());
|
||||
state.profiles = vec!["first".to_string(), "second".to_string()];
|
||||
state.active_profile = Some("second".to_string());
|
||||
state.list_state.selected = Some(2);
|
||||
|
||||
state.remove_profile("second");
|
||||
|
||||
assert_eq!(state.profiles, vec!["first"]);
|
||||
assert_eq!(state.active_profile, None);
|
||||
assert_eq!(state.list_state.selected, Some(1));
|
||||
}
|
||||
}
|
||||
mod tests;
|
||||
@@ -0,0 +1,16 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn removing_selected_last_profile_clamps_selection() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mut state = SettingsState::new(tmp.path().to_path_buf());
|
||||
state.profiles = vec!["first".to_string(), "second".to_string()];
|
||||
state.active_profile = Some("second".to_string());
|
||||
state.list_state.selected = Some(2);
|
||||
|
||||
state.remove_profile("second");
|
||||
|
||||
assert_eq!(state.profiles, vec!["first"]);
|
||||
assert_eq!(state.active_profile, None);
|
||||
assert_eq!(state.list_state.selected, Some(1));
|
||||
}
|
||||
Reference in new issue
Block a user