refactor: reorganize source and tests

This commit is contained in:
objz committed 2026-07-27 11:28:57 +02:00
1 parent 15d76c18a0
commit c6205a337c
139 files changed
+5532 -5548

No files matched your search

+2 -28
View File
@@ -244,31 +244,5 @@ pub(crate) fn fallback_icon_large() -> Vec<Vec<IconCell>> {
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn quadrant_raster_has_requested_dimensions() {
let image = image::DynamicImage::ImageRgb8(image::RgbImage::from_pixel(
2,
2,
image::Rgb([12, 34, 56]),
));
let rows = make_icon_quadrants_from_image(&image, 7, 3);
assert_eq!(rows.len(), 3);
assert!(rows.iter().all(|row| row.len() == 7));
assert!(rows.iter().flatten().all(|cell| cell.symbol == '\u{2588}'));
}
#[test]
fn fallback_icon_is_square_and_contains_a_separate_question_mark_dot() {
let icon = fallback_icon();
assert_eq!(icon.len(), 3);
assert!(icon.iter().all(|row| row.len() == 6));
assert_eq!(icon[2][2].bg_r, 45);
assert_eq!(icon[2][2].fg_r, 150);
assert_eq!(icon[2][3].fg_r, 150);
}
}
#[path = "../tests/content/icons.rs"]
mod tests;
+2 -86
View File
@@ -263,89 +263,5 @@ pub fn fingerprint_metadata(path: &Path) -> Result<FileFingerprint, std::io::Err
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn manifest_round_trip_and_lookup_are_exact() {
let temp = tempfile::tempdir().unwrap();
let path = temp.path().join("rmcl/content/manifest.json");
let record = ContentFileRecord {
relative_path: PathBuf::from("mods/fabric-api.jar"),
kind: ContentKind::Mod,
enabled: true,
fingerprint: FileFingerprint {
size: 3,
modified_ns: 4,
hashes: BTreeMap::from([("sha1".to_owned(), "abc".to_owned())]),
},
resolution: Resolution::Resolved {
project: ProviderProject {
provider: "modrinth".to_owned(),
project_id: "P7dR8mSH".to_owned(),
version_id: "version".to_owned(),
},
},
};
let mut manifest = ContentManifest::default();
manifest.upsert(record);
manifest.save(&path).unwrap();
let loaded = ContentManifest::load(&path).unwrap();
assert_eq!(
loaded.resolved_project_path("modrinth", "P7dR8mSH", Path::new("/instance/minecraft")),
Some(PathBuf::from("/instance/minecraft/mods/fabric-api.jar"))
);
assert!(
loaded
.resolved_project_path("modrinth", "fabric-api", Path::new("/minecraft"))
.is_none()
);
}
#[test]
fn fingerprint_contains_both_modrinth_hashes() {
let temp = tempfile::tempdir().unwrap();
let path = temp.path().join("example.jar");
std::fs::write(&path, b"abc").unwrap();
let fingerprint = fingerprint(&path).unwrap();
assert_eq!(
fingerprint.hash("sha1"),
Some("a9993e364706816aba3e25717850c26c9cd0d89d")
);
assert_eq!(fingerprint.hash("sha512").unwrap().len(), 128);
}
#[test]
fn renaming_a_record_preserves_its_resolution() {
let mut manifest = ContentManifest::default();
manifest.upsert(ContentFileRecord {
relative_path: PathBuf::from("mods/example.jar"),
kind: ContentKind::Mod,
enabled: true,
fingerprint: FileFingerprint {
size: 3,
modified_ns: 4,
hashes: BTreeMap::new(),
},
resolution: Resolution::Resolved {
project: ProviderProject {
provider: "modrinth".to_owned(),
project_id: "project".to_owned(),
version_id: "version".to_owned(),
},
},
});
assert!(manifest.rename_record(
Path::new("mods/example.jar"),
Path::new("mods/example.jar.disabled"),
false,
));
let record = manifest
.record(Path::new("mods/example.jar.disabled"))
.unwrap();
assert!(!record.enabled);
assert!(matches!(record.resolution, Resolution::Resolved { .. }));
}
}
#[path = "../tests/content/manifest.rs"]
mod tests;
+1
View File
@@ -6,6 +6,7 @@ mod icons;
pub mod manifest;
pub mod mods;
mod packs;
pub mod provider;
pub mod reconcile;
pub mod resource_packs;
pub mod shaders;
+2 -371
View File
@@ -356,374 +356,5 @@ fn read_zip_bytes(archive: &mut zip::ZipArchive<std::fs::File>, path: &str) -> O
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
fn setup_mods_dir(tmp: &Path, instance: &str) -> PathBuf {
let dir = tmp
.join(instance)
.join(crate::storage::MINECRAFT_DIR_NAME)
.join("mods");
std::fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn scan_mods_empty_dir() {
let tmp = tempfile::tempdir().unwrap();
setup_mods_dir(tmp.path(), "inst");
let mods = scan_mods(tmp.path(), "inst");
assert!(mods.is_empty());
}
#[test]
fn scan_mods_missing_dir_returns_empty() {
let tmp = tempfile::tempdir().unwrap();
let mods = scan_mods(tmp.path(), "ghost");
assert!(mods.is_empty());
}
#[test]
fn scan_mods_enabled_disabled_flags() {
let tmp = tempfile::tempdir().unwrap();
let dir = setup_mods_dir(tmp.path(), "inst");
std::fs::write(dir.join("active.jar"), b"PK\x03\x04").unwrap();
std::fs::write(dir.join("inactive.jar.disabled"), b"PK\x03\x04").unwrap();
let mods = scan_mods(tmp.path(), "inst");
let active = mods.iter().find(|m| m.file_stem == "active").unwrap();
let inactive = mods.iter().find(|m| m.file_stem == "inactive").unwrap();
assert!(active.enabled);
assert!(!inactive.enabled);
}
#[test]
fn scan_mods_ignores_non_jar() {
let tmp = tempfile::tempdir().unwrap();
let dir = setup_mods_dir(tmp.path(), "inst");
std::fs::write(dir.join("readme.txt"), "not a mod").unwrap();
std::fs::write(dir.join("config.json"), "{}").unwrap();
std::fs::write(dir.join("real.jar"), b"PK\x03\x04").unwrap();
let mods = scan_mods(tmp.path(), "inst");
assert_eq!(mods.len(), 1);
}
#[test]
fn scan_mods_sorted_case_insensitive() {
let tmp = tempfile::tempdir().unwrap();
let dir = setup_mods_dir(tmp.path(), "inst");
std::fs::write(dir.join("Zebra.jar"), b"PK\x03\x04").unwrap();
std::fs::write(dir.join("alpha.jar"), b"PK\x03\x04").unwrap();
std::fs::write(dir.join("Beta.jar"), b"PK\x03\x04").unwrap();
let mods = scan_mods(tmp.path(), "inst");
let names: Vec<&str> = mods.iter().map(|m| m.name.as_str()).collect();
assert_eq!(names, vec!["alpha", "Beta", "Zebra"]);
}
#[test]
fn toggle_entry_enable() {
let tmp = tempfile::tempdir().unwrap();
let dir = setup_mods_dir(tmp.path(), "inst");
let disabled_path = dir.join("mymod.jar.disabled");
std::fs::write(&disabled_path, b"PK\x03\x04").unwrap();
let entry = ContentEntry {
file_stem: "mymod".to_string(),
name: "mymod".to_string(),
source_slug: None,
installed_path: None,
provider_project: None,
title_suffix: None,
footer_label: None,
description: String::new(),
enabled: false,
icon_bytes: None,
provider_icon: false,
provider_description: false,
path: disabled_path.clone(),
icon_lines: None,
};
toggle_entry(&entry).unwrap();
assert!(!disabled_path.exists());
assert!(dir.join("mymod.jar").exists());
}
use std::io::Write as _;
fn make_jar(dir: &Path, name: &str, entries: &[(&str, &[u8])]) {
let path = dir.join(name);
let file = std::fs::File::create(&path).unwrap();
let mut zip = zip::ZipWriter::new(file);
let options: zip::write::FileOptions<()> =
zip::write::FileOptions::default().compression_method(zip::CompressionMethod::Stored);
for (entry_name, data) in entries {
zip.start_file(*entry_name, options).unwrap();
zip.write_all(data).unwrap();
}
zip.finish().unwrap();
}
#[test]
fn scan_mods_reads_fabric_metadata() {
let tmp = tempfile::tempdir().unwrap();
let dir = setup_mods_dir(tmp.path(), "inst");
let meta = r#"{"name":"Fabric Mod","description":"A fabric mod","icon":"icon.png"}"#;
make_jar(
&dir,
"fabric-mod.jar",
&[("fabric.mod.json", meta.as_bytes())],
);
let mods = scan_mods(tmp.path(), "inst");
assert_eq!(mods.len(), 1);
assert_eq!(mods[0].name, "Fabric Mod");
assert_eq!(mods[0].description, "A fabric mod");
}
#[test]
fn scan_mods_reads_quilt_metadata() {
let tmp = tempfile::tempdir().unwrap();
let dir = setup_mods_dir(tmp.path(), "inst");
let meta =
r#"{"quilt_loader":{"metadata":{"name":"Quilt Mod","description":"A quilt mod"}}}"#;
make_jar(
&dir,
"quilt-mod.jar",
&[("quilt.mod.json", meta.as_bytes())],
);
let mods = scan_mods(tmp.path(), "inst");
assert_eq!(mods.len(), 1);
assert_eq!(mods[0].name, "Quilt Mod");
assert_eq!(mods[0].description, "A quilt mod");
}
#[test]
fn scan_mods_reads_forge_toml_metadata() {
let tmp = tempfile::tempdir().unwrap();
let dir = setup_mods_dir(tmp.path(), "inst");
let meta = r#"
logoFile = "logo.png"
[[mods]]
displayName = "Forge Mod"
description = "A forge mod"
"#;
make_jar(
&dir,
"forge-mod.jar",
&[("META-INF/mods.toml", meta.as_bytes())],
);
let mods = scan_mods(tmp.path(), "inst");
assert_eq!(mods.len(), 1);
assert_eq!(mods[0].name, "Forge Mod");
assert_eq!(mods[0].description, "A forge mod");
}
#[test]
fn scan_mods_reads_neoforge_toml_metadata() {
let tmp = tempfile::tempdir().unwrap();
let dir = setup_mods_dir(tmp.path(), "inst");
let meta = r#"
logoFile = "logo.png"
[[mods]]
displayName = "NeoForge Mod"
description = "A neoforge mod"
"#;
make_jar(
&dir,
"neoforge-mod.jar",
&[("META-INF/neoforge.mods.toml", meta.as_bytes())],
);
let mods = scan_mods(tmp.path(), "inst");
assert_eq!(mods.len(), 1);
assert_eq!(mods[0].name, "NeoForge Mod");
assert_eq!(mods[0].description, "A neoforge mod");
}
#[test]
fn scan_mods_reads_mcmod_info_array() {
let tmp = tempfile::tempdir().unwrap();
let dir = setup_mods_dir(tmp.path(), "inst");
let meta = r#"[{"name":"Legacy Mod","description":"An old forge mod"}]"#;
make_jar(&dir, "legacy-mod.jar", &[("mcmod.info", meta.as_bytes())]);
let mods = scan_mods(tmp.path(), "inst");
assert_eq!(mods.len(), 1);
assert_eq!(mods[0].name, "Legacy Mod");
assert_eq!(mods[0].description, "An old forge mod");
}
#[test]
fn scan_mods_reads_mcmod_info_modlist() {
let tmp = tempfile::tempdir().unwrap();
let dir = setup_mods_dir(tmp.path(), "inst");
let meta = r#"{"modList":[{"name":"Wrapped Mod","description":"Has modList wrapper"}]}"#;
make_jar(&dir, "wrapped-mod.jar", &[("mcmod.info", meta.as_bytes())]);
let mods = scan_mods(tmp.path(), "inst");
assert_eq!(mods.len(), 1);
assert_eq!(mods[0].name, "Wrapped Mod");
assert_eq!(mods[0].description, "Has modList wrapper");
}
#[test]
fn scan_mods_prefers_fabric_over_forge() {
let tmp = tempfile::tempdir().unwrap();
let dir = setup_mods_dir(tmp.path(), "inst");
let fabric = r#"{"name":"Fabric Name","description":"fabric desc"}"#;
let forge = "[[mods]]\ndisplayName = \"Forge Name\"\ndescription = \"forge desc\"\n";
make_jar(
&dir,
"multi.jar",
&[
("fabric.mod.json", fabric.as_bytes()),
("META-INF/mods.toml", forge.as_bytes()),
],
);
let mods = scan_mods(tmp.path(), "inst");
assert_eq!(mods[0].name, "Fabric Name");
}
#[test]
fn scan_mods_prefers_quilt_over_forge() {
let tmp = tempfile::tempdir().unwrap();
let dir = setup_mods_dir(tmp.path(), "inst");
let quilt = r#"{"quilt_loader":{"id":"x","version":"1","metadata":{"name":"Quilt Name","description":"quilt desc"}}}"#;
let forge = "[[mods]]\ndisplayName = \"Forge Name\"\ndescription = \"forge desc\"\n";
make_jar(
&dir,
"quilt-over-forge.jar",
&[
("quilt.mod.json", quilt.as_bytes()),
("META-INF/mods.toml", forge.as_bytes()),
],
);
let mods = scan_mods(tmp.path(), "inst");
assert_eq!(mods[0].name, "Quilt Name");
}
#[test]
fn scan_mods_prefers_forge_toml_over_mcmod_info() {
let tmp = tempfile::tempdir().unwrap();
let dir = setup_mods_dir(tmp.path(), "inst");
let forge = "[[mods]]\ndisplayName = \"Forge Name\"\ndescription = \"forge desc\"\n";
let mcmod = r#"[{"modid":"legacy","name":"Legacy Name","description":"legacy desc"}]"#;
make_jar(
&dir,
"forge-over-legacy.jar",
&[
("META-INF/mods.toml", forge.as_bytes()),
("mcmod.info", mcmod.as_bytes()),
],
);
let mods = scan_mods(tmp.path(), "inst");
assert_eq!(mods[0].name, "Forge Name");
}
// when both neoforge.mods.toml and mods.toml exist in the same jar (the
// shape a dual-format mod might ship), the neoforge one wins because
// read_forge_toml_meta tries it first via .or_else.
#[test]
fn scan_mods_prefers_neoforge_toml_over_forge_toml() {
let tmp = tempfile::tempdir().unwrap();
let dir = setup_mods_dir(tmp.path(), "inst");
let neoforge =
"[[mods]]\ndisplayName = \"NeoForge Name\"\ndescription = \"neoforge desc\"\n";
let forge = "[[mods]]\ndisplayName = \"Forge Name\"\ndescription = \"forge desc\"\n";
make_jar(
&dir,
"neoforge-over-forge.jar",
&[
("META-INF/neoforge.mods.toml", neoforge.as_bytes()),
("META-INF/mods.toml", forge.as_bytes()),
],
);
let mods = scan_mods(tmp.path(), "inst");
assert_eq!(mods[0].name, "NeoForge Name");
}
// a mods.toml with logoFile but no [[mods]] array (e.g. a dependency-only
// library jar) should still surface as a scanned mod with empty name +
// description but with the icon resolved.
#[test]
fn scan_mods_reads_mods_toml_without_mods_array() {
let tmp = tempfile::tempdir().unwrap();
let dir = setup_mods_dir(tmp.path(), "inst");
let mods_toml = "logoFile = \"icon.png\"\n";
let png_bytes = b"\x89PNG fake icon";
make_jar(
&dir,
"lib-only.jar",
&[
("META-INF/mods.toml", mods_toml.as_bytes()),
("icon.png", png_bytes),
],
);
let mods = scan_mods(tmp.path(), "inst");
assert_eq!(mods.len(), 1);
// file-stem fallback when metadata name is empty - covered here
// because no other test exercises an empty-name + present-logo combo.
assert_eq!(mods[0].name, "lib-only");
assert_eq!(mods[0].icon_bytes.as_deref(), Some(png_bytes.as_slice()));
}
#[test]
fn scan_mods_fallback_icon_paths() {
let tmp = tempfile::tempdir().unwrap();
let dir = setup_mods_dir(tmp.path(), "inst");
let png_bytes = b"\x89PNG fake";
make_jar(&dir, "no-meta.jar", &[("logo.png", png_bytes)]);
let mods = scan_mods(tmp.path(), "inst");
assert_eq!(mods.len(), 1);
assert_eq!(mods[0].name, "no-meta");
assert_eq!(mods[0].icon_bytes.as_deref(), Some(png_bytes.as_slice()));
}
#[test]
fn icon_path_from_value_string() {
let val = serde_json::json!("assets/icon.png");
assert_eq!(icon_path_from_value(&val), "assets/icon.png");
}
#[test]
fn icon_path_from_value_map() {
// serde_json::Map is a BTreeMap, so iteration is sorted by key.
// "128" sorts before "64" lexicographically, so the first value wins.
let val = serde_json::json!({"64": "icon_64.png", "128": "icon_128.png"});
assert_eq!(icon_path_from_value(&val), "icon_128.png");
}
#[test]
fn icon_path_from_value_null() {
let val = serde_json::Value::Null;
assert_eq!(icon_path_from_value(&val), "");
}
#[test]
fn toggle_entry_disable() {
let tmp = tempfile::tempdir().unwrap();
let dir = setup_mods_dir(tmp.path(), "inst");
let enabled_path = dir.join("mymod.jar");
std::fs::write(&enabled_path, b"PK\x03\x04").unwrap();
let entry = ContentEntry {
file_stem: "mymod".to_string(),
name: "mymod".to_string(),
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: enabled_path.clone(),
icon_lines: None,
};
toggle_entry(&entry).unwrap();
assert!(!enabled_path.exists());
assert!(dir.join("mymod.jar.disabled").exists());
}
}
#[path = "../tests/content/mods.rs"]
mod tests;
+211
View File
@@ -0,0 +1,211 @@
use std::collections::HashMap;
use async_trait::async_trait;
use crate::instance::content::manifest::{ContentKind, FileFingerprint, ProviderProject};
use crate::instance::{InstanceConfig, ModLoader};
use crate::net::modrinth::{DiscoveryResults, VersionInfo};
#[derive(Debug, Clone)]
pub struct FingerprintQuery {
pub key: String,
pub kind: ContentKind,
pub fingerprint: FileFingerprint,
}
#[derive(Debug, Clone)]
pub struct ResolvedFile {
pub key: String,
pub project: ProviderProject,
}
#[async_trait]
pub trait ContentProvider: Send + Sync {
fn id(&self) -> &'static str;
async fn search(
&self,
kind: ContentKind,
query: &str,
instance: &InstanceConfig,
offset: usize,
limit: usize,
) -> Result<DiscoveryResults, crate::net::NetError>;
async fn resolve_files(
&self,
files: &[FingerprintQuery],
) -> Result<Vec<ResolvedFile>, crate::net::NetError>;
async fn project(
&self,
project_id: &str,
) -> Result<crate::net::modrinth::ProjectInfo, crate::net::NetError>;
async fn compatible_versions(
&self,
project_id: &str,
kind: ContentKind,
game_version: &str,
loader: ModLoader,
) -> Result<Vec<VersionInfo>, crate::net::NetError>;
async fn icon(&self, url: &str) -> Result<Vec<u8>, crate::net::NetError>;
async fn download_version(
&self,
version: &VersionInfo,
destination: &std::path::Path,
installed_path: Option<&std::path::Path>,
) -> Result<crate::net::modrinth::DownloadOutcome, crate::net::NetError>;
}
#[derive(Clone)]
pub struct ModrinthProvider {
client: crate::net::HttpClient,
}
impl ModrinthProvider {
pub fn new(client: crate::net::HttpClient) -> Self {
Self { client }
}
}
#[async_trait]
impl ContentProvider for ModrinthProvider {
fn id(&self) -> &'static str {
"modrinth"
}
async fn search(
&self,
kind: ContentKind,
query: &str,
instance: &InstanceConfig,
offset: usize,
limit: usize,
) -> Result<DiscoveryResults, crate::net::NetError> {
crate::net::modrinth::search_discovery(
&self.client,
kind,
query,
&instance.game_version,
instance.loader,
offset,
limit,
)
.await
}
async fn resolve_files(
&self,
files: &[FingerprintQuery],
) -> Result<Vec<ResolvedFile>, crate::net::NetError> {
let mut by_hash = HashMap::<String, Vec<String>>::new();
for file in files {
if let Some(hash) = file.fingerprint.hash("sha512") {
by_hash
.entry(hash.to_owned())
.or_default()
.push(file.key.clone());
}
}
let hashes = by_hash.keys().cloned().collect::<Vec<_>>();
let versions =
crate::net::modrinth::resolve_version_files(&self.client, &hashes, "sha512").await?;
Ok(versions
.into_iter()
.flat_map(|(hash, version)| {
let keys = by_hash.get(&hash).cloned().unwrap_or_default();
if version.project_id.is_empty() {
return Vec::new();
}
keys.into_iter()
.map(|key| ResolvedFile {
key,
project: ProviderProject {
provider: self.id().to_owned(),
project_id: version.project_id.clone(),
version_id: version.id.clone(),
},
})
.collect()
})
.collect())
}
async fn project(
&self,
project_id: &str,
) -> Result<crate::net::modrinth::ProjectInfo, crate::net::NetError> {
crate::net::modrinth::fetch_project(&self.client, project_id).await
}
async fn compatible_versions(
&self,
project_id: &str,
kind: ContentKind,
game_version: &str,
loader: ModLoader,
) -> Result<Vec<VersionInfo>, crate::net::NetError> {
crate::net::modrinth::fetch_content_versions(
&self.client,
project_id,
kind,
game_version,
loader,
)
.await
}
async fn icon(&self, url: &str) -> Result<Vec<u8>, crate::net::NetError> {
self.client.get_bytes(url).await
}
async fn download_version(
&self,
version: &VersionInfo,
destination: &std::path::Path,
installed_path: Option<&std::path::Path>,
) -> Result<crate::net::modrinth::DownloadOutcome, crate::net::NetError> {
if let Some(installed_path) = installed_path {
crate::net::modrinth::download_version_file_for_update(
&self.client,
version,
destination,
installed_path,
)
.await
} else {
crate::net::modrinth::download_version_file(&self.client, version, destination).await
}
}
}
pub struct ProviderRegistry {
providers: Vec<Box<dyn ContentProvider>>,
}
impl ProviderRegistry {
pub fn modrinth(client: crate::net::HttpClient) -> Self {
Self {
providers: vec![Box::new(ModrinthProvider::new(client))],
}
}
pub fn providers(&self) -> &[Box<dyn ContentProvider>] {
&self.providers
}
pub fn preferred(&self, id: &str) -> Option<&dyn ContentProvider> {
self.providers
.iter()
.find(|provider| provider.id() == id)
.map(Box::as_ref)
.or_else(|| self.providers.first().map(Box::as_ref))
}
}
#[cfg(test)]
#[path = "../tests/content/provider.rs"]
mod tests;
+5 -121
View File
@@ -3,14 +3,14 @@ use std::path::{Path, PathBuf};
use std::sync::{Arc, LazyLock, Mutex};
use std::time::{SystemTime, UNIX_EPOCH};
use crate::content_provider::{FingerprintQuery, ProviderRegistry};
use crate::feedback::progress::{ProgressTask, ProgressTaskHandle};
use crate::instance::InstanceConfig;
use crate::instance::content::manifest::{
ContentFileRecord, ContentKind, ContentManifest, FileFingerprint, ProviderProject, Resolution,
fingerprint, fingerprint_metadata,
};
use crate::instance::content::provider::{FingerprintQuery, ProviderRegistry};
use crate::storage::InstancePaths;
use crate::tui::progress::{ProgressTask, ProgressTaskHandle};
#[derive(Debug)]
pub struct ReconcileResult {
@@ -126,7 +126,7 @@ async fn reconcile_worker() {
coordinator.scheduled.remove(&instance_name);
}
}
crate::tui::request_redraw();
crate::feedback::request_redraw();
}
}
@@ -545,121 +545,5 @@ fn directory_fingerprint_metadata(path: &Path) -> Result<FileFingerprint, std::i
}
#[cfg(test)]
mod tests {
use super::*;
struct NoopProgress;
impl InventoryProgress for NoopProgress {
fn set_sub_action(&self, _text: &str) {}
fn set_progress(&self, _current: u64, _total: u64) {}
}
fn job(name: &str) -> ReconcileJob {
ReconcileJob {
instance: InstanceConfig {
name: name.to_owned(),
game_version: "1.21.1".to_owned(),
loader: crate::instance::ModLoader::Fabric,
loader_version: None,
created: chrono::Utc::now(),
last_played: None,
java_path: None,
memory_max: None,
memory_min: None,
jvm_args: Vec::new(),
resolution: None,
config_sync_profile: None,
},
instances_dir: PathBuf::new(),
client: crate::net::HttpClient::new(),
}
}
#[test]
fn coordinator_queues_instances_once_and_preserves_order() {
let mut coordinator = ReconcileCoordinator::default();
assert!(coordinator.enqueue(job("one"), false));
assert!(!coordinator.enqueue(job("two"), false));
assert!(!coordinator.enqueue(job("one"), false));
assert!(!coordinator.rerun.contains("one"));
assert!(!coordinator.enqueue(job("one"), true));
assert_eq!(coordinator.queue.len(), 2);
assert!(coordinator.rerun.contains("one"));
assert_eq!(coordinator.queue.pop_front().unwrap().instance.name, "one");
assert_eq!(coordinator.queue.pop_front().unwrap().instance.name, "two");
}
#[test]
fn oversized_content_is_kept_without_hashing_or_provider_query() {
let temp = tempfile::tempdir().unwrap();
let minecraft = temp.path().join("minecraft");
let resource_packs = minecraft.join("resourcepacks");
std::fs::create_dir_all(&resource_packs).unwrap();
let pack = resource_packs.join("large.zip");
let file = std::fs::File::create(&pack).unwrap();
file.set_len(2 * 1024 * 1024).unwrap();
let manifest_path = temp.path().join("manifest.json");
let inventory =
reconcile_inventory(&manifest_path, &minecraft, 24, 1, &NoopProgress).unwrap();
assert!(inventory.queries.is_empty());
assert_eq!(inventory.manifest.files.len(), 1);
assert!(inventory.manifest.files[0].fingerprint.hashes.is_empty());
assert!(matches!(
inventory.manifest.files[0].resolution,
Resolution::Unmatched { .. }
));
}
#[test]
fn unchanged_saved_index_reuses_fingerprint_and_skips_provider_query() {
let temp = tempfile::tempdir().unwrap();
let minecraft = temp.path().join("minecraft");
let mods = minecraft.join("mods");
std::fs::create_dir_all(&mods).unwrap();
std::fs::write(mods.join("example.jar"), b"example").unwrap();
let manifest_path = temp.path().join("manifest.json");
let mut first =
reconcile_inventory(&manifest_path, &minecraft, 24, 512, &NoopProgress).unwrap();
assert_eq!(first.queries.len(), 1);
let fingerprint = first.manifest.files[0].fingerprint.clone();
first.manifest.files[0].resolution = Resolution::Unmatched {
checked_at: chrono::Utc::now().timestamp(),
providers: vec!["modrinth".to_owned()],
};
first.manifest.save(&manifest_path).unwrap();
let second =
reconcile_inventory(&manifest_path, &minecraft, 24, 512, &NoopProgress).unwrap();
assert!(second.queries.is_empty());
assert_eq!(second.manifest.files[0].fingerprint, fingerprint);
}
#[test]
fn directory_packs_are_indexed_without_provider_queries() {
let temp = tempfile::tempdir().unwrap();
let minecraft = temp.path().join("minecraft");
let pack = minecraft.join("resourcepacks/example");
std::fs::create_dir_all(&pack).unwrap();
std::fs::write(pack.join("pack.mcmeta"), b"{}").unwrap();
let inventory = reconcile_inventory(
&temp.path().join("manifest.json"),
&minecraft,
24,
512,
&NoopProgress,
)
.unwrap();
assert!(inventory.queries.is_empty());
assert_eq!(
inventory.manifest.files[0].relative_path,
PathBuf::from("resourcepacks/example")
);
}
}
#[path = "../tests/content/reconcile.rs"]
mod tests;
+2 -20
View File
@@ -13,23 +13,5 @@ pub fn scan_resource_packs(instances_dir: &Path, instance_name: &str) -> Vec<Con
}
#[cfg(test)]
mod tests {
use super::super::packs::extract_description;
use serde_json::json;
// every case exercises a distinct match arm in extract_description.
#[rstest::rstest]
#[case::string(json!("Simple pack"), "Simple pack")]
#[case::object_with_text(json!({"text": "Hello world"}), "Hello world")]
#[case::object_without_text(json!({"color": "red"}), "")]
#[case::array_of_strings(json!(["Hello", " ", "world"]), "Hello world")]
#[case::array_of_objects(json!([{"text": "A"}, {"text": "B"}]), "AB")]
#[case::mixed_array(json!(["Prefix ", {"text": "suffix"}]), "Prefix suffix")]
#[case::empty_array(json!([]), "")]
#[case::null(serde_json::Value::Null, "")]
#[case::number(json!(42), "")]
#[case::bool(json!(true), "")]
fn extract_description_handles(#[case] input: serde_json::Value, #[case] expected: &str) {
assert_eq!(extract_description(&input), expected);
}
}
#[path = "../tests/content/resource_packs.rs"]
mod tests;