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

+309
View File
@@ -0,0 +1,309 @@
use super::*;
#[test]
fn first_prepare_seeds_shared_config() {
let tmp = tempfile::tempdir().unwrap();
let meta = tmp.path().join("meta");
let minecraft = tmp.path().join("instance/minecraft");
create_profile(&meta, "main").unwrap();
std::fs::create_dir_all(minecraft.join("config/nested")).unwrap();
std::fs::write(minecraft.join("options.txt"), "local-options").unwrap();
std::fs::write(minecraft.join("optionsshaders.txt"), "shader-options").unwrap();
std::fs::write(minecraft.join("config/options.txt"), "local-config").unwrap();
std::fs::write(minecraft.join("config/nested/mod.toml"), "nested").unwrap();
assert!(prepare(Some("main"), &meta, &minecraft).unwrap());
assert_eq!(
std::fs::read_to_string(meta.join("state/profiles/main/options.txt")).unwrap(),
"local-options"
);
assert_eq!(
std::fs::read_to_string(meta.join("state/profiles/main/optionsshaders.txt")).unwrap(),
"shader-options"
);
assert_eq!(
std::fs::read_to_string(meta.join("state/profiles/main/config/options.txt")).unwrap(),
"local-config"
);
assert_eq!(
std::fs::read_to_string(meta.join("state/profiles/main/config/nested/mod.toml")).unwrap(),
"nested"
);
}
#[test]
fn prepare_mirrors_shared_config_into_instance() {
let tmp = tempfile::tempdir().unwrap();
let meta = tmp.path().join("meta");
let minecraft = tmp.path().join("instance/minecraft");
std::fs::create_dir_all(meta.join("state/profiles/main/config")).unwrap();
std::fs::create_dir_all(minecraft.join("config")).unwrap();
std::fs::write(
meta.join("state/profiles/main/options.txt"),
"shared-options",
)
.unwrap();
std::fs::write(
meta.join("state/profiles/main/config/shared.toml"),
"shared",
)
.unwrap();
std::fs::write(minecraft.join("options.txt"), "stale-options").unwrap();
std::fs::write(minecraft.join("config/local.toml"), "stale").unwrap();
assert!(prepare(Some("main"), &meta, &minecraft).unwrap());
assert_eq!(
std::fs::read_to_string(minecraft.join("options.txt")).unwrap(),
"shared-options"
);
assert_eq!(
std::fs::read_to_string(minecraft.join("config/shared.toml")).unwrap(),
"shared"
);
assert!(!minecraft.join("config/local.toml").exists());
}
#[test]
fn finish_mirrors_instance_config_back_to_shared() {
let tmp = tempfile::tempdir().unwrap();
let meta = tmp.path().join("meta");
let minecraft = tmp.path().join("instance/minecraft");
std::fs::create_dir_all(meta.join("state/profiles/main/config")).unwrap();
std::fs::write(meta.join("state/profiles/main/config/old.toml"), "old").unwrap();
std::fs::create_dir_all(minecraft.join("config")).unwrap();
std::fs::write(minecraft.join("options.txt"), "new-options").unwrap();
std::fs::write(minecraft.join("config/new.toml"), "new").unwrap();
finish(Some("main"), &meta, &minecraft).unwrap();
assert_eq!(
std::fs::read_to_string(meta.join("state/profiles/main/options.txt")).unwrap(),
"new-options"
);
assert_eq!(
std::fs::read_to_string(meta.join("state/profiles/main/config/new.toml")).unwrap(),
"new"
);
assert!(!meta.join("state/profiles/main/config/old.toml").exists());
}
#[test]
fn prepare_releases_lock_for_another_instance() {
let tmp = tempfile::tempdir().unwrap();
let meta = tmp.path().join("meta");
let minecraft = tmp.path().join("instance/minecraft");
create_profile(&meta, "main").unwrap();
std::fs::create_dir_all(minecraft.join("config")).unwrap();
assert!(prepare(Some("main"), &meta, &minecraft).unwrap());
let second = tmp.path().join("second/minecraft");
std::fs::create_dir_all(second.join("config")).unwrap();
assert!(prepare(Some("main"), &meta, &second).unwrap());
}
#[test]
fn profile_rejects_path_traversal() {
let tmp = tempfile::tempdir().unwrap();
let err = prepare(Some("../bad"), tmp.path(), tmp.path()).unwrap_err();
assert!(matches!(err, ConfigSyncError::InvalidProfile(_)));
}
#[test]
fn profile_rejects_builtin_names() {
for profile in [
"none",
"default",
"local",
"instance default",
"local default",
] {
let err = validate_profile(profile).unwrap_err();
assert!(matches!(err, ConfigSyncError::InvalidProfile(_)));
}
}
#[test]
fn prepare_ignores_deleted_profile() {
let tmp = tempfile::tempdir().unwrap();
let meta = tmp.path().join("meta");
let minecraft = tmp.path().join("instance/minecraft");
std::fs::create_dir_all(minecraft.join("config")).unwrap();
let lock = prepare(Some("deleted"), &meta, &minecraft).unwrap();
assert!(!lock);
assert!(!meta.join("state/profiles/deleted").exists());
}
#[test]
fn create_profile_trims_and_lists_profiles() {
let tmp = tempfile::tempdir().unwrap();
let profile = create_profile(tmp.path(), " main ").unwrap();
let profiles = list_profiles(tmp.path()).unwrap();
assert_eq!(profile, "main");
assert_eq!(profiles, vec!["main"]);
}
#[test]
fn delete_profile_removes_profile_dir() {
let tmp = tempfile::tempdir().unwrap();
create_profile(tmp.path(), "main").unwrap();
delete_profile(tmp.path(), "main").unwrap();
assert!(list_profiles(tmp.path()).unwrap().is_empty());
}
#[test]
fn switch_to_profile_backs_up_local_config_and_restores_none() {
let tmp = tempfile::tempdir().unwrap();
let meta = tmp.path().join("meta");
let instance = tmp.path().join("instance");
let minecraft = instance.join(crate::storage::MINECRAFT_DIR_NAME);
std::fs::create_dir_all(minecraft.join("config")).unwrap();
std::fs::write(minecraft.join("options.txt"), "local-options").unwrap();
std::fs::write(minecraft.join("config/local.txt"), "local").unwrap();
let selected = switch_profile("inst", None, Some("main"), &meta, &instance).unwrap();
assert_eq!(selected.as_deref(), Some("main"));
assert_eq!(
std::fs::read_to_string(instance.join("rmcl/content/config/options.txt")).unwrap(),
"local-options"
);
assert_eq!(
std::fs::read_to_string(instance.join("rmcl/content/config/config/local.txt")).unwrap(),
"local"
);
std::fs::write(minecraft.join("options.txt"), "shared-options").unwrap();
std::fs::write(minecraft.join("config/shared.txt"), "shared").unwrap();
let selected = switch_profile("inst", Some("main"), None, &meta, &instance).unwrap();
assert_eq!(selected, None);
assert_eq!(
std::fs::read_to_string(meta.join("state/profiles/main/options.txt")).unwrap(),
"shared-options"
);
assert_eq!(
std::fs::read_to_string(meta.join("state/profiles/main/config/shared.txt")).unwrap(),
"shared"
);
assert_eq!(
std::fs::read_to_string(minecraft.join("options.txt")).unwrap(),
"local-options"
);
assert_eq!(
std::fs::read_to_string(minecraft.join("config/local.txt")).unwrap(),
"local"
);
assert!(!minecraft.join("config/shared.txt").exists());
}
#[test]
fn switch_from_deleted_profile_restores_local_without_recreating_profile() {
let tmp = tempfile::tempdir().unwrap();
let meta = tmp.path().join("meta");
let instance = tmp.path().join("instance");
let minecraft = instance.join(crate::storage::MINECRAFT_DIR_NAME);
std::fs::create_dir_all(minecraft.join("config")).unwrap();
std::fs::create_dir_all(instance.join("rmcl/content/config/config")).unwrap();
std::fs::write(minecraft.join("options.txt"), "deleted-profile-options").unwrap();
std::fs::write(
instance.join("rmcl/content/config/options.txt"),
"local-options",
)
.unwrap();
std::fs::write(
instance.join("rmcl/content/config/config/local.txt"),
"local",
)
.unwrap();
let selected = switch_profile("inst", Some("deleted"), None, &meta, &instance).unwrap();
assert_eq!(selected, None);
assert_eq!(
std::fs::read_to_string(minecraft.join("options.txt")).unwrap(),
"local-options"
);
assert_eq!(
std::fs::read_to_string(minecraft.join("config/local.txt")).unwrap(),
"local"
);
assert!(!meta.join("state/profiles/deleted").exists());
}
#[test]
fn switch_between_profiles_saves_old_and_loads_new() {
let tmp = tempfile::tempdir().unwrap();
let meta = tmp.path().join("meta");
let instance = tmp.path().join("instance");
let minecraft = instance.join(crate::storage::MINECRAFT_DIR_NAME);
std::fs::create_dir_all(minecraft.join("config")).unwrap();
std::fs::write(minecraft.join("options.txt"), "changed-a-options").unwrap();
std::fs::write(minecraft.join("config/a.txt"), "changed-a").unwrap();
create_profile(&meta, "a").unwrap();
std::fs::create_dir_all(meta.join("state/profiles/b/config")).unwrap();
std::fs::write(
meta.join("state/profiles/b/options.txt"),
"profile-b-options",
)
.unwrap();
std::fs::write(meta.join("state/profiles/b/config/b.txt"), "profile-b").unwrap();
let selected = switch_profile("inst", Some("a"), Some("b"), &meta, &instance).unwrap();
assert_eq!(selected.as_deref(), Some("b"));
assert_eq!(
std::fs::read_to_string(meta.join("state/profiles/a/options.txt")).unwrap(),
"changed-a-options"
);
assert_eq!(
std::fs::read_to_string(meta.join("state/profiles/a/config/a.txt")).unwrap(),
"changed-a"
);
assert_eq!(
std::fs::read_to_string(minecraft.join("options.txt")).unwrap(),
"profile-b-options"
);
assert_eq!(
std::fs::read_to_string(minecraft.join("config/b.txt")).unwrap(),
"profile-b"
);
assert!(!minecraft.join("config/a.txt").exists());
}
#[test]
fn second_instance_uses_profile_options_saved_by_first_instance() {
let tmp = tempfile::tempdir().unwrap();
let meta = tmp.path().join("meta");
let first = tmp.path().join("first/minecraft");
let second_instance = tmp.path().join("second");
let second = second_instance.join(crate::storage::MINECRAFT_DIR_NAME);
std::fs::create_dir_all(first.join("config")).unwrap();
std::fs::create_dir_all(second.join("config")).unwrap();
std::fs::write(first.join("options.txt"), "first-default").unwrap();
std::fs::write(second.join("options.txt"), "second-local").unwrap();
create_profile(&meta, "main").unwrap();
assert!(prepare(Some("main"), &meta, &first).unwrap());
std::fs::write(first.join("options.txt"), "changed-in-main").unwrap();
finish(Some("main"), &meta, &first).unwrap();
switch_profile("second", None, Some("main"), &meta, &second_instance).unwrap();
assert_eq!(
std::fs::read_to_string(second.join("options.txt")).unwrap(),
"changed-in-main"
);
assert_eq!(
std::fs::read_to_string(second_instance.join("rmcl/content/config/options.txt")).unwrap(),
"second-local"
);
}
+23
View File
@@ -0,0 +1,23 @@
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);
}
+84
View File
@@ -0,0 +1,84 @@
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 { .. }));
}
+367
View File
@@ -0,0 +1,367 @@
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());
}
+7
View File
@@ -0,0 +1,7 @@
use super::*;
#[test]
fn registry_falls_back_to_first_capable_provider() {
let registry = ProviderRegistry::modrinth(crate::net::HttpClient::new());
assert_eq!(registry.preferred("unknown").unwrap().id(), "modrinth");
}
+114
View File
@@ -0,0 +1,114 @@
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")
);
}
@@ -0,0 +1,18 @@
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);
}
+30
View File
@@ -0,0 +1,30 @@
use super::*;
#[test]
fn sanitize_keeps_alphanumeric() {
assert_eq!(sanitize("my-instance_123"), "my-instance_123");
}
#[test]
fn sanitize_replaces_special_chars() {
assert_eq!(sanitize("my instance!"), "my_instance_");
assert_eq!(sanitize("path/traversal"), "path_traversal");
}
#[test]
#[cfg(target_os = "linux")]
fn build_content_linux() {
let content = build_content("TestPack", None);
assert!(content.contains("Name=Minecraft - TestPack"));
assert!(content.contains("Exec=rmcl instance launch \"TestPack\""));
assert!(content.contains("Terminal=false"));
assert!(content.contains("Categories=Game;"));
}
#[test]
#[cfg(target_os = "linux")]
fn build_content_linux_with_icon() {
let icon = PathBuf::from("/tmp/icon.png");
let content = build_content("TestPack", Some(&icon));
assert!(content.contains("Icon=/tmp/icon.png"));
}
@@ -0,0 +1,172 @@
use super::*;
use std::io::Write;
fn make_pack_zip(tmp: &Path, name: &str, entries: &[(&str, &[u8])]) -> std::path::PathBuf {
let path = tmp.join(name);
let file = std::fs::File::create(&path).unwrap();
let mut zip = zip::ZipWriter::new(file);
let opts: zip::write::SimpleFileOptions = Default::default();
for (filename, bytes) in entries {
zip.start_file(*filename, opts).unwrap();
zip.write_all(bytes).unwrap();
}
zip.finish().unwrap();
path
}
#[test]
fn detect_format_recognises_mrpack() {
let tmp = tempfile::tempdir().unwrap();
let path = make_pack_zip(tmp.path(), "pack.mrpack", &[("modrinth.index.json", b"{}")]);
assert_eq!(detect_format(&path), Ok(PackFormat::Mrpack));
}
#[test]
fn detect_format_recognises_mmc_flat() {
// mmc-pack.json at the zip root - the flat layout that some mmc
// archives use.
let tmp = tempfile::tempdir().unwrap();
let path = make_pack_zip(tmp.path(), "pack.zip", &[("mmc-pack.json", b"{}")]);
assert_eq!(detect_format(&path), Ok(PackFormat::Mmc));
}
#[test]
fn detect_format_recognises_mmc_nested() {
// mmc-pack.json one directory deep - the more common layout where
// the archive wraps everything in a named directory.
let tmp = tempfile::tempdir().unwrap();
let path = make_pack_zip(tmp.path(), "pack.zip", &[("MyPack/mmc-pack.json", b"{}")]);
assert_eq!(detect_format(&path), Ok(PackFormat::Mmc));
}
#[test]
fn detect_format_prefers_mrpack_when_both_markers_present() {
// a zip with both markers should resolve to Mrpack since the
// detector checks modrinth.index.json first.
let tmp = tempfile::tempdir().unwrap();
let path = make_pack_zip(
tmp.path(),
"weird.zip",
&[("modrinth.index.json", b"{}"), ("mmc-pack.json", b"{}")],
);
assert_eq!(detect_format(&path), Ok(PackFormat::Mrpack));
}
#[test]
fn detect_format_errors_on_unknown_archive() {
let tmp = tempfile::tempdir().unwrap();
let path = make_pack_zip(tmp.path(), "random.zip", &[("readme.txt", b"hello")]);
let err = detect_format(&path).unwrap_err();
assert!(
err.contains("Unknown pack format"),
"expected unknown format error, got: {err}"
);
}
#[test]
fn detect_format_errors_on_missing_file() {
let tmp = tempfile::tempdir().unwrap();
let err = detect_format(&tmp.path().join("missing.zip")).unwrap_err();
assert!(err.contains("Cannot open"), "got: {err}");
}
#[test]
fn unique_name_no_collision() {
let tmp = tempfile::tempdir().unwrap();
let name = unique_instance_name("TestPack", tmp.path());
assert_eq!(name, "TestPack");
}
#[test]
fn unique_name_with_collision() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join("TestPack");
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("instance.json"), "{}").unwrap();
let name = unique_instance_name("TestPack", tmp.path());
assert_eq!(name, "TestPack (2)");
}
#[test]
fn unique_name_multiple_collisions() {
let tmp = tempfile::tempdir().unwrap();
for suffix in ["", " (2)", " (3)"] {
let dir = tmp.path().join(format!("TestPack{suffix}"));
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("instance.json"), "{}").unwrap();
}
let name = unique_instance_name("TestPack", tmp.path());
assert_eq!(name, "TestPack (4)");
}
#[test]
fn parse_project_url() {
assert_eq!(
parse_import_input("https://modrinth.com/modpack/fabulously-optimized"),
ImportInput::ProjectSlug("fabulously-optimized".to_string())
);
}
#[test]
fn parse_version_url() {
assert_eq!(
parse_import_input("https://modrinth.com/modpack/fabulously-optimized/version/abc123"),
ImportInput::VersionId {
slug: "fabulously-optimized".to_string(),
version_id: "abc123".to_string(),
}
);
}
#[test]
fn parse_local_mrpack() {
assert_eq!(
parse_import_input("/home/user/pack.mrpack"),
ImportInput::LocalFile("/home/user/pack.mrpack".to_string())
);
}
#[test]
fn parse_local_zip() {
assert_eq!(
parse_import_input("GT_New_Horizons.zip"),
ImportInput::LocalFile("GT_New_Horizons.zip".to_string())
);
}
#[test]
fn parse_tilde_path() {
assert_eq!(
parse_import_input("~/Downloads/pack.mrpack"),
ImportInput::LocalFile("~/Downloads/pack.mrpack".to_string())
);
}
#[test]
fn parse_bare_slug() {
assert_eq!(
parse_import_input("fabulously-optimized"),
ImportInput::ProjectSlug("fabulously-optimized".to_string())
);
}
#[test]
fn parse_input_trims_whitespace() {
assert_eq!(
parse_import_input(" fabulously-optimized "),
ImportInput::ProjectSlug("fabulously-optimized".to_string())
);
}
#[test]
fn failed_import_cleanup_removes_the_partial_instance() {
let tmp = tempfile::tempdir().unwrap();
let manager = InstanceManager::new(tmp.path().join("instances"), tmp.path().join("meta"));
let instance_dir = manager.instances_dir.join("Broken");
std::fs::create_dir_all(&instance_dir).unwrap();
std::fs::write(instance_dir.join("partial"), b"data").unwrap();
cleanup_failed_import(&manager, "Broken");
assert!(!instance_dir.exists());
}
+108
View File
@@ -0,0 +1,108 @@
use super::*;
#[test]
fn parse_mmc_pack_json() {
let json = r#"{
"formatVersion": 1,
"components": [
{
"uid": "net.minecraft",
"version": "1.7.10",
"cachedName": "Minecraft"
},
{
"uid": "net.minecraftforge",
"version": "10.13.4.1614",
"cachedName": "Forge"
}
]
}"#;
let pack: MmcPack = serde_json::from_str(json).unwrap();
assert_eq!(pack.game_version(), Some("1.7.10".to_string()));
let (loader, version) = pack.loader();
assert_eq!(loader, Some(ModLoader::Forge));
assert_eq!(version, Some("10.13.4.1614".to_string()));
}
#[test]
fn parse_mmc_pack_vanilla() {
let json = r#"{
"formatVersion": 1,
"components": [
{"uid": "net.minecraft", "version": "1.21.4"}
]
}"#;
let pack: MmcPack = serde_json::from_str(json).unwrap();
assert!(pack.loader().0.is_none());
}
// builds an in-memory mmc-style pack zip and verifies that
// extract_mmc_archive copies only the .minecraft/ subtree into the
// destination, preserving relative paths and skipping siblings.
#[test]
fn extract_mmc_archive_copies_minecraft_subtree() {
use std::io::Write;
let tmp = tempfile::tempdir().unwrap();
let archive_path = tmp.path().join("pack.zip");
let dest = tmp.path().join("instance/.minecraft");
std::fs::create_dir_all(&dest).unwrap();
// Pack/ is the prefix; only .minecraft/ entries should land in dest.
// mmc-style pack: a root dir "Pack/" wrapping the .minecraft tree
// plus a sibling mmc-pack.json that should NOT be extracted.
{
let file = std::fs::File::create(&archive_path).unwrap();
let mut zip = zip::ZipWriter::new(file);
let opts: zip::write::SimpleFileOptions = Default::default();
zip.start_file("Pack/mmc-pack.json", opts).unwrap();
zip.write_all(b"{}").unwrap();
zip.start_file("Pack/.minecraft/options.txt", opts).unwrap();
zip.write_all(b"lang:en_us").unwrap();
zip.start_file("Pack/.minecraft/mods/test-mod.jar", opts)
.unwrap();
zip.write_all(b"jar-bytes").unwrap();
zip.finish().unwrap();
}
extract_mmc_archive(&archive_path, &dest).expect("extract");
// .minecraft/ entries must have been copied with their relative paths
let options = std::fs::read(dest.join("options.txt")).expect("options.txt");
assert_eq!(options, b"lang:en_us");
let modjar = std::fs::read(dest.join("mods/test-mod.jar")).expect("mods/test-mod.jar");
assert_eq!(modjar, b"jar-bytes");
// and the sibling outside .minecraft/ must not have been copied
assert!(
!dest.join("mmc-pack.json").exists(),
"mmc-pack.json should not land in the instance dir"
);
}
#[test]
fn extract_mmc_archive_rejects_path_traversal() {
use std::io::Write;
let tmp = tempfile::tempdir().unwrap();
let archive_path = tmp.path().join("pack.zip");
let dest = tmp.path().join("instance/minecraft");
let file = std::fs::File::create(&archive_path).unwrap();
let mut zip = zip::ZipWriter::new(file);
let options: zip::write::SimpleFileOptions = Default::default();
zip.start_file("Pack/mmc-pack.json", options).unwrap();
zip.write_all(b"{}").unwrap();
zip.start_file("Pack/.minecraft/../../escaped.txt", options)
.unwrap();
zip.write_all(b"escaped").unwrap();
zip.finish().unwrap();
let error = extract_mmc_archive(&archive_path, &dest).unwrap_err();
assert!(error.to_string().contains("archive path"));
assert!(!tmp.path().join("escaped.txt").exists());
}
+215
View File
@@ -0,0 +1,215 @@
use std::collections::HashMap;
use std::io::Write;
use std::path::{Path, PathBuf};
use super::*;
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};
const INDEX: &[u8] = br#"{
"formatVersion": 1,
"game": "minecraft",
"versionId": "1.0.0",
"name": "Test Pack",
"dependencies": {
"minecraft": "1.21.1",
"fabric-loader": "0.16.14"
},
"files": []
}"#;
fn make_mrpack(dir: &Path, entries: &[(&str, &[u8])]) -> PathBuf {
let path = dir.join("test.mrpack");
let file = std::fs::File::create(&path).unwrap();
let mut zip = zip::ZipWriter::new(file);
let options: zip::write::SimpleFileOptions = Default::default();
zip.start_file("modrinth.index.json", options).unwrap();
zip.write_all(INDEX).unwrap();
for (name, contents) in entries {
zip.start_file(*name, options).unwrap();
zip.write_all(contents).unwrap();
}
zip.finish().unwrap();
path
}
#[test]
fn summary_counts_both_override_roots() {
let tmp = tempfile::tempdir().unwrap();
let path = make_mrpack(
tmp.path(),
&[
("overrides/config/test.toml", b"config"),
("client-overrides/options.txt", b"options"),
],
);
let summary = build_summary(&path).unwrap();
assert_eq!(summary.name, "Test Pack");
assert_eq!(summary.game_version, "1.21.1");
assert_eq!(summary.loader, ModLoader::Fabric);
assert_eq!(summary.loader_version.as_deref(), Some("0.16.14"));
assert_eq!(summary.override_count, 2);
}
#[test]
fn dependencies_resolve_fabric_loader() {
let dependencies = HashMap::from([
("minecraft".to_owned(), "1.21.4".to_owned()),
("fabric-loader".to_owned(), "0.16.10".to_owned()),
]);
assert_eq!(
loader_from_dependencies(&dependencies),
(Some(ModLoader::Fabric), Some("0.16.10".to_owned()))
);
assert_eq!(
game_version_from_dependencies(&dependencies),
Some("1.21.4".to_owned())
);
}
#[test]
fn dependencies_resolve_forge_loader() {
let dependencies = HashMap::from([
("minecraft".to_owned(), "1.20.1".to_owned()),
("forge".to_owned(), "47.2.0".to_owned()),
]);
assert_eq!(
loader_from_dependencies(&dependencies),
(Some(ModLoader::Forge), Some("47.2.0".to_owned()))
);
}
#[test]
fn dependencies_without_a_loader_are_vanilla() {
let dependencies = HashMap::from([("minecraft".to_owned(), "1.21.4".to_owned())]);
assert_eq!(loader_from_dependencies(&dependencies), (None, None));
}
#[test]
fn extraction_merges_both_override_roots() {
let tmp = tempfile::tempdir().unwrap();
let path = make_mrpack(
tmp.path(),
&[
("overrides/config/test.toml", b"config"),
("client-overrides/options.txt", b"options"),
],
);
let minecraft = tmp.path().join("minecraft");
extract_overrides(&path, &minecraft).unwrap();
assert_eq!(
std::fs::read(minecraft.join("config/test.toml")).unwrap(),
b"config"
);
assert_eq!(
std::fs::read(minecraft.join("options.txt")).unwrap(),
b"options"
);
}
#[test]
fn extraction_rejects_path_traversal() {
let tmp = tempfile::tempdir().unwrap();
let path = make_mrpack(tmp.path(), &[("overrides/../../escaped.txt", b"escaped")]);
let minecraft = tmp.path().join("minecraft");
let error = extract_overrides(&path, &minecraft).unwrap_err();
assert!(error.to_string().contains("Unsafe override path"));
assert!(!tmp.path().join("escaped.txt").exists());
}
#[test]
fn mod_files_download_to_their_manifest_paths() {
let _guard = crate::tests::TEST_LOCK
.lock()
.unwrap_or_else(|error| error.into_inner());
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
runtime.block_on(async {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/first.jar"))
.respond_with(ResponseTemplate::new(200).set_body_bytes(b"first".to_vec()))
.expect(1)
.mount(&server)
.await;
Mock::given(method("GET"))
.and(path("/second.jar"))
.respond_with(ResponseTemplate::new(200).set_body_bytes(b"second".to_vec()))
.expect(1)
.mount(&server)
.await;
let index = MrpackIndex {
format_version: 1,
game: "minecraft".to_owned(),
version_id: "1".to_owned(),
name: "Downloads".to_owned(),
dependencies: Default::default(),
files: vec![
MrpackFile {
path: "mods/first.jar".to_owned(),
downloads: vec![format!("{}/first.jar", server.uri())],
file_size: 5,
},
MrpackFile {
path: "resourcepacks/second.jar".to_owned(),
downloads: vec![format!("{}/second.jar", server.uri())],
file_size: 6,
},
],
};
let tmp = tempfile::tempdir().unwrap();
download_mod_files(&index, tmp.path()).await.unwrap();
assert_eq!(
std::fs::read(tmp.path().join("mods/first.jar")).unwrap(),
b"first"
);
assert_eq!(
std::fs::read(tmp.path().join("resourcepacks/second.jar")).unwrap(),
b"second"
);
crate::feedback::progress::clear();
});
}
#[test]
fn mod_file_without_a_download_url_fails_without_creating_a_file() {
let _guard = crate::tests::TEST_LOCK
.lock()
.unwrap_or_else(|error| error.into_inner());
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
runtime.block_on(async {
let index = MrpackIndex {
format_version: 1,
game: "minecraft".to_owned(),
version_id: "1".to_owned(),
name: "Missing URL".to_owned(),
dependencies: Default::default(),
files: vec![MrpackFile {
path: "mods/missing.jar".to_owned(),
downloads: Vec::new(),
file_size: 0,
}],
};
let tmp = tempfile::tempdir().unwrap();
assert!(download_mod_files(&index, tmp.path()).await.is_err());
assert!(!tmp.path().join("mods/missing.jar").exists());
crate::feedback::progress::clear();
});
}
+102
View File
@@ -0,0 +1,102 @@
use super::*;
fn parse_all(lines: &[(LogStream, &str)]) -> Vec<ParsedLogEvent> {
let mut parser = MinecraftLogParser::new();
let mut events = Vec::new();
for (stream, line) in lines {
events.extend(parser.push_line(*stream, *line));
}
events.extend(parser.flush());
events
}
#[test]
fn classifies_minecraft_headers() {
let events = parse_all(&[
(LogStream::Stdout, "[Render thread/INFO]: hello"),
(LogStream::Stdout, "[Render thread/WARN]: careful"),
(LogStream::Stdout, "[Render thread/ERROR]: broken"),
(LogStream::Stdout, "[Render thread/DEBUG]: noisy"),
(LogStream::Stdout, "[Render thread/TRACE]: tiny"),
]);
assert_eq!(events.len(), 5);
assert_eq!(events[0].level, LogLevel::Info);
assert_eq!(events[1].level, LogLevel::Warn);
assert_eq!(events[2].level, LogLevel::Error);
assert_eq!(events[3].level, LogLevel::Debug);
assert_eq!(events[4].level, LogLevel::Trace);
}
#[test]
fn explicit_stderr_info_stays_info() {
let events = parse_all(&[(LogStream::Stderr, "[Render thread/INFO]: hello")]);
assert_eq!(events[0].level, LogLevel::Info);
}
#[test]
fn unstructured_stderr_falls_back_to_error() {
let events = parse_all(&[(LogStream::Stderr, "native library failed")]);
assert_eq!(events[0].level, LogLevel::Error);
}
#[test]
fn groups_java_stacktrace() {
let events = parse_all(&[
(
LogStream::Stderr,
"Exception in thread \"main\" java.lang.RuntimeException: boom",
),
(
LogStream::Stderr,
"\tat net.minecraft.client.Main.main(Main.java:42)",
),
(
LogStream::Stderr,
"Caused by: java.lang.IllegalStateException: bad",
),
(LogStream::Stderr, "\tat example.Mod.load(Mod.java:7)"),
(LogStream::Stdout, "[Render thread/INFO]: after"),
]);
assert_eq!(events.len(), 2);
assert_eq!(events[0].level, LogLevel::Error);
assert_eq!(events[0].lines.len(), 4);
assert!(
events[0]
.java
.as_ref()
.is_some_and(|java| java.has_stacktrace)
);
assert_eq!(events[1].level, LogLevel::Info);
}
#[test]
fn groups_jvm_startup_failure_burst() {
let events = parse_all(&[
(LogStream::Stderr, "Unrecognized option: --bad"),
(
LogStream::Stderr,
"Could not create the Java Virtual Machine.",
),
(
LogStream::Stderr,
"A fatal exception has occurred. Program will exit.",
),
]);
assert_eq!(events.len(), 1);
assert_eq!(events[0].level, LogLevel::Error);
assert_eq!(events[0].lines.len(), 3);
}
#[test]
fn colored_header_classifies_but_keeps_original_text() {
let line = "\u{1b}[31m[Render thread/ERROR]: red\u{1b}[0m";
let events = parse_all(&[(LogStream::Stdout, line)]);
assert_eq!(events[0].level, LogLevel::Error);
assert_eq!(events[0].lines[0], line);
}
+135
View File
@@ -0,0 +1,135 @@
use super::*;
use std::io::Write;
// builds an in-memory zip with the given entries, writes it to tmp, and
// returns the path. shared by parse_add_opens tests.
fn make_zip(tmp: &Path, name: &str, entries: &[(&str, &[u8])]) -> PathBuf {
let path = tmp.join(name);
let file = std::fs::File::create(&path).unwrap();
let mut zip = zip::ZipWriter::new(file);
let opts: zip::write::SimpleFileOptions = Default::default();
for (filename, bytes) in entries {
zip.start_file(*filename, opts).unwrap();
zip.write_all(bytes).unwrap();
}
zip.finish().unwrap();
path
}
#[test]
fn strip_replaced_libs_removes_dominated_prefixes() {
let mut classpath = vec![
PathBuf::from("/libs/launchwrapper-1.12.jar"),
PathBuf::from("/libs/asm-all-5.0.3.jar"),
PathBuf::from("/libs/lwjgl-2.9.4.jar"),
PathBuf::from("/libs/lwjgl_util-2.9.4.jar"),
PathBuf::from("/libs/commons-compress-1.4.1.jar"),
PathBuf::from("/libs/commons-io-2.4.jar"),
PathBuf::from("/libs/guava-15.0.jar"),
// these stay
PathBuf::from("/libs/log4j-core-2.0.jar"),
PathBuf::from("/libs/guava-21.0.jar"),
];
strip_replaced_libs(&mut classpath);
assert_eq!(
classpath,
vec![
PathBuf::from("/libs/log4j-core-2.0.jar"),
PathBuf::from("/libs/guava-21.0.jar"),
]
);
}
#[test]
fn strip_replaced_libs_keeps_unrelated_entries() {
let mut classpath = vec![
PathBuf::from("/libs/log4j-core-2.0.jar"),
PathBuf::from("/libs/mixin-0.8.5.jar"),
];
let original = classpath.clone();
strip_replaced_libs(&mut classpath);
assert_eq!(classpath, original);
}
#[test]
fn parse_add_opens_extracts_module_args() {
let tmp = tempfile::tempdir().unwrap();
let manifest = b"Manifest-Version: 1.0\nAdd-Opens: java.base/java.lang java.base/java.util\n";
let zip_path = make_zip(
tmp.path(),
"patches.zip",
&[("META-INF/MANIFEST.MF", manifest)],
);
let args = parse_add_opens(&zip_path).expect("parsed");
assert_eq!(
args,
vec![
"--add-opens",
"java.base/java.lang=ALL-UNNAMED",
"--add-opens",
"java.base/java.util=ALL-UNNAMED",
]
);
}
#[test]
fn parse_add_opens_handles_continuation_lines() {
// jar manifests wrap long lines: the line ends with a trailing space,
// then the next physical line starts with a leading space marker.
// when joined per the MANIFEST.MF spec, the trailing space remains
// and the leading space marker is consumed, so the two values stay
// separated by exactly one space when split_whitespace runs.
let tmp = tempfile::tempdir().unwrap();
let manifest =
b"Manifest-Version: 1.0\nAdd-Opens: java.base/java.lang \n java.base/sun.security.util\n";
let zip_path = make_zip(
tmp.path(),
"patches-continuation.zip",
&[("META-INF/MANIFEST.MF", manifest)],
);
let args = parse_add_opens(&zip_path).expect("parsed");
assert_eq!(
args,
vec![
"--add-opens",
"java.base/java.lang=ALL-UNNAMED",
"--add-opens",
"java.base/sun.security.util=ALL-UNNAMED",
]
);
}
#[test]
fn parse_add_opens_returns_none_when_manifest_missing() {
let tmp = tempfile::tempdir().unwrap();
let zip_path = make_zip(tmp.path(), "no-manifest.zip", &[("other.txt", b"x")]);
assert!(parse_add_opens(&zip_path).is_none());
}
#[test]
fn parse_add_opens_returns_none_for_missing_file() {
let tmp = tempfile::tempdir().unwrap();
assert!(parse_add_opens(&tmp.path().join("missing.zip")).is_none());
}
#[test]
fn add_lwjgl3_inserts_only_jars_that_exist() {
let tmp = tempfile::tempdir().unwrap();
let lib_dir = tmp.path();
// pre-create only the lwjgl core jar; everything else absent so the
// function should skip them silently. proves we don't insert paths
// for jars that aren't there.
let core_jar = lib_dir.join("org/lwjgl/lwjgl/3.3.3/lwjgl-3.3.3.jar");
std::fs::create_dir_all(core_jar.parent().unwrap()).unwrap();
std::fs::write(&core_jar, b"jar").unwrap();
let mut classpath = vec![PathBuf::from("/leading/forge-patches.jar")];
add_lwjgl3(lib_dir, &mut classpath);
// forge-patches stays at index 0; lwjgl core is inserted at index 1.
// none of the other modules existed so nothing else was added.
assert_eq!(classpath[0], PathBuf::from("/leading/forge-patches.jar"));
assert_eq!(classpath[1], core_jar);
assert_eq!(classpath.len(), 2);
}
+232
View File
@@ -0,0 +1,232 @@
use super::*;
#[rstest::rstest]
#[case("openjdk version \"25.0.3\" 2026-04-21", Some(25))]
#[case("openjdk version \"21.0.11\" 2026-04-21", Some(21))]
#[case("java version \"1.8.0_402\"", Some(8))]
#[case("garbage", None)]
fn parse_java_major_version_handles_common_outputs(
#[case] output: &str,
#[case] expected: Option<u32>,
) {
assert_eq!(parse_java_major_version(output), expected);
}
#[test]
fn build_game_args_renders_upstream_arguments() {
use crate::launch_profile::model::{Argument, Arguments, LaunchProfile};
use crate::launch_profile::rules::{FeatureSet, RuleContext};
use TemplateContext;
use std::path::PathBuf;
let lib = PathBuf::from("/m/libraries");
let nat = PathBuf::from("/m/natives");
let game_dir = PathBuf::from("/i/.minecraft");
let assets = PathBuf::from("/m/assets");
let template_ctx = TemplateContext {
library_directory: &lib,
classpath_separator: ":",
version_name: "1.20.1",
natives_directory: &nat,
classpath: "a.jar:b.jar",
game_directory: &game_dir,
assets_root: &assets,
assets_index_name: "5",
auth_player_name: "Player",
auth_uuid: "00000000-0000-0000-0000-000000000000",
auth_access_token: "token",
auth_xuid: "0",
user_type: "msa",
user_properties: "{}",
launcher_name: "rmcl",
launcher_version: "test",
clientid: "0",
version_type: "release",
};
let features = FeatureSet::default();
let rule_ctx = RuleContext {
os_name: "linux",
os_version: "6.0",
arch: "x86_64",
features: &features,
};
let profile = LaunchProfile {
id: "1.20.1".into(),
inherits_from: None,
main_class: Some("net.minecraft.client.main.Main".into()),
libraries: Vec::new(),
arguments: Some(Arguments {
game: vec![
Argument::Literal("--username".into()),
Argument::Literal("${auth_player_name}".into()),
],
jvm: vec![Argument::Literal(
"-Djava.library.path=${natives_directory}".into(),
)],
}),
..Default::default()
};
let (jvm, game_args) = build_game_args(&profile, &rule_ctx, &template_ctx).unwrap();
assert_eq!(jvm, vec!["-Djava.library.path=/m/natives"]);
assert_eq!(game_args, vec!["--username", "Player"]);
}
// exercises the early-return branch of migrate_legacy_meta_if_needed.
// a profile with either arguments or minecraftArguments is not legacy
// and must produce Ok(None) without touching the network. covers both
// shapes in one parameterised test so a regression that drops one of
// the two predicate conditions is caught.
#[rstest::rstest]
#[case::modern_arguments(true, false)]
#[case::legacy_minecraft_arguments(false, true)]
#[tokio::test]
async fn migrate_legacy_meta_skips_when_arguments_present(
#[case] modern: bool,
#[case] legacy: bool,
) {
use crate::launch_profile::model::{Arguments, LaunchProfile};
use tempfile::TempDir;
let tmp = TempDir::new().unwrap();
let meta_path = tmp.path().join("meta.json");
std::fs::write(&meta_path, b"{}").unwrap();
let profile = LaunchProfile {
id: "1.20.1".into(),
main_class: Some("net.test.Main".into()),
arguments: modern.then(Arguments::default),
minecraft_arguments: legacy.then(|| "--username Player".into()),
..Default::default()
};
let result = migrate_legacy_meta_if_needed(&meta_path, &profile, "1.20.1").await;
assert!(
matches!(result, Ok(None)),
"expected Ok(None) for non-legacy profile, got {result:?}"
);
}
// each loader maps to a distinct directory-naming branch. one rstest
// exercises every variant so a regression that misorders the match
// arms in installer_version_dir_name is caught.
#[rstest::rstest]
#[case::forge(ModLoader::Forge, "1.20.1", "47.2.0", Some("1.20.1-forge-47.2.0"))]
#[case::neoforge(ModLoader::NeoForge, "1.21.1", "21.1.0", Some("neoforge-21.1.0"))]
#[case::vanilla(ModLoader::Vanilla, "1.20.1", "v", None)]
#[case::fabric(ModLoader::Fabric, "1.20.1", "0.14.21", None)]
#[case::quilt(ModLoader::Quilt, "1.20.1", "0.20.0", None)]
fn installer_version_dir_name_per_loader(
#[case] loader: ModLoader,
#[case] game_version: &str,
#[case] loader_version: &str,
#[case] expected: Option<&str>,
) {
assert_eq!(
installer_version_dir_name(loader, game_version, loader_version),
expected.map(str::to_owned)
);
}
// exercises the modern-profile early-return in
// migrate_legacy_loader_profile_if_needed. any of inheritsFrom,
// arguments, minecraftArguments present (or game_arguments absent)
// means "not legacy" and the function must return Ok(None) without
// touching the installer JSON path.
#[tokio::test]
async fn migrate_legacy_loader_profile_skips_modern_with_inherits_from() {
use LaunchProfile;
use chrono::Utc;
use tempfile::TempDir;
let tmp = TempDir::new().unwrap();
let instance_dir = tmp.path().join("instance");
std::fs::create_dir_all(&instance_dir).unwrap();
let profile_path = tmp.path().join("forge-1.20.1-47.2.0.json");
std::fs::write(&profile_path, b"{}").unwrap();
let modern = LaunchProfile {
id: "1.20.1-forge-47.2.0".into(),
inherits_from: Some("1.20.1".into()),
main_class: Some("cpw.mods.bootstraplauncher.BootstrapLauncher".into()),
..Default::default()
};
let config = InstanceConfig {
name: "test".into(),
game_version: "1.20.1".into(),
loader: ModLoader::Forge,
loader_version: Some("47.2.0".into()),
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,
};
let result =
migrate_legacy_loader_profile_if_needed(&profile_path, &modern, &config, &instance_dir)
.await;
assert!(
matches!(result, Ok(None)),
"expected Ok(None), got {result:?}"
);
}
#[tokio::test]
async fn migrate_legacy_loader_profile_skips_fabric() {
// a fresh upstream Fabric profile happens to match the "legacy"
// shape (no inheritsFrom, no arguments, no minecraftArguments).
// make sure the migration helper recognises this is Fabric and
// returns Ok(None) instead of erroring with "reinstall Fabric".
use LaunchProfile;
use chrono::Utc;
use tempfile::TempDir;
let tmp = TempDir::new().unwrap();
let instance_dir = tmp.path().join("instance");
std::fs::create_dir_all(&instance_dir).unwrap();
let profile_path = tmp.path().join("fabric-1.20.1-0.14.21.json");
std::fs::write(&profile_path, b"{}").unwrap();
let upstream_fabric_shape = LaunchProfile {
id: "fabric-loader-0.14.21-1.20.1".into(),
inherits_from: None,
main_class: Some("net.fabricmc.loader.impl.launch.knot.KnotClient".into()),
libraries: Vec::new(),
..Default::default()
};
let config = InstanceConfig {
name: "test".into(),
game_version: "1.20.1".into(),
loader: ModLoader::Fabric,
loader_version: Some("0.14.21".into()),
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,
};
let result = migrate_legacy_loader_profile_if_needed(
&profile_path,
&upstream_fabric_shape,
&config,
&instance_dir,
)
.await;
assert!(
matches!(result, Ok(None)),
"expected Ok(None), got {result:?}"
);
}
+55
View File
@@ -0,0 +1,55 @@
use super::*;
// builds an in-memory zip in a tempdir with the given json as
// install_profile.json. lets the legacy-install-profile detector be
// tested without an actual forge installer.
fn make_installer_zip(tmp: &std::path::Path, json: &serde_json::Value) -> std::path::PathBuf {
use std::io::Write;
let path = tmp.join("installer.jar");
let file = std::fs::File::create(&path).unwrap();
let mut zip = zip::ZipWriter::new(file);
let opts: zip::write::SimpleFileOptions = Default::default();
zip.start_file("install_profile.json", opts).unwrap();
zip.write_all(serde_json::to_string(json).unwrap().as_bytes())
.unwrap();
zip.finish().unwrap();
path
}
#[test]
fn has_legacy_install_profile_true_when_version_info_present() {
let tmp = tempfile::tempdir().unwrap();
let jar = make_installer_zip(
tmp.path(),
&serde_json::json!({
"install": {},
"versionInfo": {
"id": "1.7.10-Forge10.13.4.1614-1.7.10",
"mainClass": "net.minecraft.launchwrapper.Launch"
}
}),
);
assert!(has_legacy_install_profile(&jar));
}
#[test]
fn has_legacy_install_profile_false_when_version_info_absent() {
let tmp = tempfile::tempdir().unwrap();
let jar = make_installer_zip(
tmp.path(),
&serde_json::json!({
"spec": 1,
"minecraft": "1.20.1",
"data": {}
}),
);
assert!(!has_legacy_install_profile(&jar));
}
#[test]
fn has_legacy_install_profile_false_for_missing_jar() {
let tmp = tempfile::tempdir().unwrap();
assert!(!has_legacy_install_profile(
&tmp.path().join("missing-installer.jar")
));
}
+144
View File
@@ -0,0 +1,144 @@
use super::*;
// the factory maps every ModLoader variant to its concrete installer.
// covering all five arms catches a misordered match or a copy-paste typo
// that would route, say, NeoForge to the Forge installer.
#[rstest::rstest]
#[case::vanilla(ModLoader::Vanilla)]
#[case::forge(ModLoader::Forge)]
#[case::neoforge(ModLoader::NeoForge)]
#[case::fabric(ModLoader::Fabric)]
#[case::quilt(ModLoader::Quilt)]
fn get_installer_returns_matching_loader_type(#[case] loader: ModLoader) {
let installer = get_installer(loader);
assert_eq!(installer.loader_type(), loader);
}
#[test]
fn save_installer_profile_copies_raw_bytes_verbatim() {
use tempfile::TempDir;
let tmp = TempDir::new().unwrap();
let instance_dir = tmp.path().join("instance");
let meta_dir = tmp.path().join("meta");
// a synthetic installer version JSON with the modern arguments
// object - exactly the shape we used to strip.
let installer_json = br#"{
"id": "1.20.1-forge-47.2.0",
"inheritsFrom": "1.20.1",
"mainClass": "cpw.mods.bootstraplauncher.BootstrapLauncher",
"libraries": [{ "name": "net.minecraftforge:forge:47.2.0" }],
"arguments": {
"game": ["--launchTarget", "forge_client"],
"jvm": ["--add-opens", "java.base/sun.security.util=cpw.mods.securejarhandler"]
}
}"#;
let ver_dir = instance_dir
.join(crate::storage::MINECRAFT_DIR_NAME)
.join("versions")
.join("1.20.1-forge-47.2.0");
std::fs::create_dir_all(&ver_dir).unwrap();
let ver_json_path = ver_dir.join("1.20.1-forge-47.2.0.json");
std::fs::write(&ver_json_path, installer_json).unwrap();
save_installer_profile(
&instance_dir,
&meta_dir,
"1.20.1-forge-47.2.0",
"forge-1.20.1-47.2.0.json",
)
.unwrap();
let saved = std::fs::read(
meta_dir
.join("cache/loaders/profiles")
.join("forge-1.20.1-47.2.0.json"),
)
.unwrap();
assert_eq!(
saved,
installer_json.to_vec(),
"saved profile should be byte-for-byte identical to installer output"
);
}
// shape-pinning test: a synthetic versionInfo from a 1.7.10 forge
// install_profile.json must deserialise as a LaunchProfile so the
// launch flow's render_args + resolve pipeline can consume it. no
// filesystem round-trip; serde_json directly on the literal bytes.
#[test]
fn legacy_forge_version_info_deserialises_as_launch_profile() {
let bytes = br#"{
"id": "1.7.10-Forge10.13.4.1614-1.7.10",
"mainClass": "net.minecraft.launchwrapper.Launch",
"minecraftArguments": "--username ${auth_player_name} --tweakClass cpw.mods.fml.common.launcher.FMLTweaker",
"libraries": [
{ "name": "net.minecraftforge:forge:10.13.4.1614", "url": "http://files.minecraftforge.net/maven/" },
{ "name": "net.minecraft:launchwrapper:1.9" }
]
}"#;
let profile: crate::launch_profile::model::LaunchProfile =
serde_json::from_slice(bytes).unwrap();
assert_eq!(profile.id, "1.7.10-Forge10.13.4.1614-1.7.10");
assert_eq!(
profile.main_class.as_deref(),
Some("net.minecraft.launchwrapper.Launch")
);
// legacy forge profiles omit inheritsFrom; the launch flow's
// implicit fallback adds it before resolve.
assert!(profile.inherits_from.is_none());
assert!(
profile
.minecraft_arguments
.as_deref()
.unwrap()
.contains("--tweakClass")
);
assert_eq!(profile.libraries.len(), 2);
assert_eq!(
profile.libraries[0].name,
"net.minecraftforge:forge:10.13.4.1614"
);
assert_eq!(
profile.libraries[0].url.as_deref(),
Some("http://files.minecraftforge.net/maven/")
);
// legacy libs typically have no downloads.artifact; they resolve
// at launch time via maven_coord_to_path(name).
assert!(profile.libraries[0].downloads.is_none());
}
// shape-pinning test: a synthetic upstream fabric profile (no
// inheritsFrom, no arguments, libraries with name+url) must
// deserialise as a LaunchProfile so the install path can write it
// through to disk and the launch flow can read it back.
#[test]
fn raw_fabric_profile_bytes_parse_as_launch_profile() {
let bytes = br#"{
"id": "fabric-loader-0.14.21-1.20.1",
"mainClass": "net.fabricmc.loader.impl.launch.knot.KnotClient",
"libraries": [
{ "name": "net.fabricmc:fabric-loader:0.14.21", "url": "https://maven.fabricmc.net/" },
{ "name": "net.fabricmc:intermediary:1.20.1", "url": "https://maven.fabricmc.net/" }
]
}"#;
let parsed: crate::launch_profile::model::LaunchProfile =
serde_json::from_slice(bytes).unwrap();
assert_eq!(parsed.id, "fabric-loader-0.14.21-1.20.1");
assert_eq!(
parsed.main_class.as_deref(),
Some("net.fabricmc.loader.impl.launch.knot.KnotClient")
);
// upstream Fabric profiles omit inheritsFrom; the launch flow's
// implicit fallback handles it before resolve.
assert!(parsed.inherits_from.is_none());
assert!(parsed.arguments.is_none());
assert_eq!(parsed.libraries.len(), 2);
assert_eq!(
parsed.libraries[0].url.as_deref(),
Some("https://maven.fabricmc.net/")
);
}
+32
View File
@@ -0,0 +1,32 @@
use super::*;
#[test]
fn maven_3_part_coord() {
assert_eq!(
maven_coord_to_path("org.example:artifact:1.0"),
Some("org/example/artifact/1.0/artifact-1.0.jar".to_string())
);
}
#[test]
fn maven_4_part_coord_with_classifier() {
assert_eq!(
maven_coord_to_path("org.example:artifact:1.0:sources"),
Some("org/example/artifact/1.0/artifact-1.0-sources.jar".to_string())
);
}
#[test]
fn maven_nested_group() {
assert_eq!(
maven_coord_to_path("com.google.code.gson:gson:2.10"),
Some("com/google/code/gson/gson/2.10/gson-2.10.jar".to_string())
);
}
#[test]
fn maven_invalid_coordinates() {
for coordinate in ["org.example:artifact", "a:b:c:d:e", "just-a-string", ""] {
assert_eq!(maven_coord_to_path(coordinate), None);
}
}
+33
View File
@@ -0,0 +1,33 @@
use super::*;
use crate::net::mojang::{LatestVersions, VersionEntry, VersionManifest};
#[test]
fn manifest_types_map_to_stable_game_versions() {
let manifest = VersionManifest {
latest: LatestVersions {
release: "1.21.1".to_owned(),
snapshot: "24w01a".to_owned(),
},
versions: vec![
VersionEntry {
id: "1.21.1".to_owned(),
version_type: "release".to_owned(),
url: String::new(),
sha1: String::new(),
},
VersionEntry {
id: "24w01a".to_owned(),
version_type: "snapshot".to_owned(),
url: String::new(),
sha1: String::new(),
},
],
};
let versions = game_versions_from_manifest(manifest);
assert_eq!(versions[0].id, "1.21.1");
assert!(versions[0].stable);
assert_eq!(versions[1].id, "24w01a");
assert!(!versions[1].stable);
}
+10
View File
@@ -0,0 +1,10 @@
use super::*;
#[test]
fn log_dir_builds_correct_path() {
let p = log_dir(Path::new("/instances"), "my-world");
assert_eq!(
p,
PathBuf::from("/instances/my-world/minecraft/logs/launches")
);
}
+47
View File
@@ -0,0 +1,47 @@
use super::*;
#[test]
fn push_and_get_all() {
let name = "test_push_get";
push(name, "line1");
push(name, "line2");
let lines = get_all(name);
assert!(lines.contains(&"line1".to_string()));
assert!(lines.contains(&"line2".to_string()));
}
#[test]
fn get_all_missing_instance_returns_empty() {
let lines = get_all("nonexistent_instance_xyz");
assert!(lines.is_empty());
}
#[test]
fn clear_removes_instance() {
let name = "test_clear";
push(name, "data");
assert!(!get_all(name).is_empty());
clear(name);
assert!(get_all(name).is_empty());
}
#[test]
fn clear_nonexistent_is_noop() {
clear("never_existed_xyz");
}
#[test]
fn buffer_respects_max_lines() {
let name = "test_max_lines";
for i in 0..(MAX_LINES + 100) {
push(name, format!("line-{i}"));
}
let lines = get_all(name);
assert_eq!(lines.len(), MAX_LINES);
assert!(
lines
.last()
.unwrap()
.contains(&format!("{}", MAX_LINES + 99))
);
}
+166
View File
@@ -0,0 +1,166 @@
use super::*;
use crate::instance::models::ModLoader;
use tempfile::TempDir;
// tmp owns the temp directory; its Drop impl cleans up everything when
// the test ends. the returned InstanceManager points at tmp.path() so
// tests can join("name") off of either to refer to the same locations.
fn test_manager() -> (InstanceManager, TempDir) {
let tmp = tempfile::tempdir().unwrap();
let meta = tmp.path().join("meta");
std::fs::create_dir_all(&meta).unwrap();
(InstanceManager::new(tmp.path().to_path_buf(), meta), tmp)
}
fn dummy_config(name: &str) -> InstanceConfig {
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 validate_name_accepts_safe_names() {
assert!(validate_name("my-instance").is_ok());
assert!(validate_name("test_world").is_ok());
}
#[test]
fn validate_name_rejects_empty_traversal_and_hidden() {
assert!(validate_name("").is_err());
assert!(validate_name("path/traversal").is_err());
assert!(validate_name(".hidden").is_err());
}
#[test]
fn delete_missing_instance_returns_not_found() {
let (manager, _tmp) = test_manager();
let result = manager.delete("ghost-instance");
assert!(matches!(result, Err(InstanceError::NotFound(_))));
}
#[test]
fn save_then_load_all_round_trips_config() {
let (manager, tmp) = test_manager();
std::fs::create_dir_all(tmp.path().join("test-save")).unwrap();
manager.save(&dummy_config("test-save")).expect("save");
let all = manager.load_all();
assert_eq!(all.len(), 1);
assert_eq!(all[0].name, "test-save");
assert_eq!(all[0].game_version, "1.20.1");
}
#[test]
fn load_all_accepts_numeric_memory() {
let (manager, tmp) = test_manager();
let instance_dir = tmp.path().join("test-memory");
std::fs::create_dir_all(&instance_dir).unwrap();
std::fs::write(
instance_dir.join("instance.json"),
r#"{
"name": "test-memory",
"game_version": "1.7.10",
"loader": "forge",
"loader_version": "10.13.4.1614",
"created": "2026-04-20T18:04:25.567993893Z",
"memory_max": 8,
"memory_min": 512
}"#,
)
.expect("write config");
let all = manager.load_all();
assert_eq!(all.len(), 1);
assert_eq!(all[0].memory_max.as_deref(), Some("8G"));
assert_eq!(all[0].memory_min.as_deref(), Some("512M"));
}
#[test]
fn load_one_missing_returns_not_found() {
let (manager, _tmp) = test_manager();
let result = manager.load_one("ghost-instance");
assert!(matches!(result, Err(InstanceError::NotFound(_))));
}
#[test]
fn rename_moves_dir_and_updates_config_name() {
let (manager, tmp) = test_manager();
let old_dir = tmp.path().join("old-name");
std::fs::create_dir_all(&old_dir).unwrap();
manager.save(&dummy_config("old-name")).expect("save");
manager.rename("old-name", "new-name").expect("rename");
assert!(!old_dir.exists(), "old dir should be gone");
let new_dir = tmp.path().join("new-name");
assert!(new_dir.exists(), "new dir should exist");
let reloaded = manager.load_one("new-name").expect("load_one new-name");
assert_eq!(reloaded.name, "new-name");
}
#[test]
fn rename_to_same_name_is_noop() {
let (manager, tmp) = test_manager();
let dir = tmp.path().join("same");
std::fs::create_dir_all(&dir).unwrap();
manager.save(&dummy_config("same")).expect("save");
manager.rename("same", "same").expect("noop rename");
assert!(dir.exists());
}
#[test]
fn rename_empty_target_rejects() {
let (manager, tmp) = test_manager();
std::fs::create_dir_all(tmp.path().join("orig")).unwrap();
manager.save(&dummy_config("orig")).expect("save");
let err = manager.rename("orig", " ").unwrap_err();
assert!(matches!(err, InstanceError::InvalidName(_)));
}
#[test]
fn rename_missing_source_errors() {
let (manager, _tmp) = test_manager();
let err = manager.rename("ghost", "anything").unwrap_err();
assert!(matches!(err, InstanceError::NotFound(_)));
}
#[test]
fn rename_target_exists_errors() {
let (manager, tmp) = test_manager();
std::fs::create_dir_all(tmp.path().join("source")).unwrap();
std::fs::create_dir_all(tmp.path().join("collision")).unwrap();
manager.save(&dummy_config("source")).expect("save src");
manager.save(&dummy_config("collision")).expect("save dst");
let err = manager.rename("source", "collision").unwrap_err();
assert!(matches!(err, InstanceError::AlreadyExists(_)));
}
#[test]
fn touch_last_played_updates_field() {
let (manager, tmp) = test_manager();
std::fs::create_dir_all(tmp.path().join("ticker")).unwrap();
manager.save(&dummy_config("ticker")).expect("save");
assert!(manager.load_one("ticker").unwrap().last_played.is_none());
manager.touch_last_played("ticker").expect("touch");
let reloaded = manager.load_one("ticker").unwrap();
let stamp = reloaded
.last_played
.expect("last_played should be Some now");
let age = chrono::Utc::now() - stamp;
assert!(
age.num_seconds().abs() < 5,
"last_played should be roughly now, got age {age:?}"
);
}
+79
View File
@@ -0,0 +1,79 @@
use super::*;
#[test]
fn instance_config_roundtrips_through_json() {
let config = InstanceConfig {
name: "test".to_string(),
game_version: "1.20.1".to_string(),
loader: ModLoader::Fabric,
loader_version: Some("0.15.0".to_string()),
created: Utc::now(),
last_played: None,
java_path: None,
memory_max: Some("4G".to_string()),
memory_min: Some("512M".to_string()),
jvm_args: vec![],
resolution: Some((1920, 1080)),
config_sync_profile: None,
};
let json = serde_json::to_string_pretty(&config).expect("serialize");
let parsed: InstanceConfig = serde_json::from_str(&json).expect("deserialize");
assert_eq!(parsed.name, config.name);
assert_eq!(parsed.game_version, config.game_version);
assert_eq!(parsed.loader, config.loader);
assert_eq!(parsed.resolution, config.resolution);
}
#[test]
fn instance_config_accepts_numeric_memory() {
let json = r#"
{
"name": "test",
"game_version": "1.7.10",
"loader": "forge",
"loader_version": "10.13.4.1614",
"created": "2026-04-20T18:04:25.567993893Z",
"memory_max": 8,
"memory_min": 512
}
"#;
let parsed: InstanceConfig = serde_json::from_str(json).expect("deserialize");
assert_eq!(parsed.memory_max.as_deref(), Some("8G"));
assert_eq!(parsed.memory_min.as_deref(), Some("512M"));
}
#[test]
fn normalize_memory_value_handles_bare_numbers() {
assert_eq!(normalize_memory_value("8").as_deref(), Some("8G"));
assert_eq!(normalize_memory_value("4096").as_deref(), Some("4096M"));
assert_eq!(normalize_memory_value("8G").as_deref(), Some("8G"));
assert_eq!(normalize_memory_value("2048m").as_deref(), Some("2048M"));
assert_eq!(normalize_memory_value(""), None);
}
#[test]
fn instance_config_ignores_invalid_memory_values() {
let json = r#"
{
"name": "test",
"game_version": "1.7.10",
"loader": "forge",
"loader_version": "10.13.4.1614",
"created": "2026-04-20T18:04:25.567993893Z",
"memory_max": ["8G"],
"memory_min": "8GB"
}
"#;
let parsed: InstanceConfig = serde_json::from_str(json).expect("deserialize");
assert_eq!(parsed.memory_max, None);
assert_eq!(parsed.memory_min, None);
}
#[test]
fn normalize_memory_value_rejects_invalid_values() {
assert_eq!(normalize_memory_value("0"), None);
assert_eq!(normalize_memory_value("-1"), None);
assert_eq!(normalize_memory_value("1.5G"), None);
assert_eq!(normalize_memory_value("8GB"), None);
assert_eq!(normalize_memory_value("banana"), None);
}
+75
View File
@@ -0,0 +1,75 @@
use super::*;
#[test]
fn set_and_get_state() {
set_state("run_test_1", RunState::Starting);
assert_eq!(get("run_test_1"), Some(RunState::Starting));
}
#[test]
fn get_missing_returns_none() {
assert_eq!(get("run_never_set_xyz"), None);
}
#[test]
fn remove_clears_state() {
set_state("run_test_2", RunState::Running);
remove("run_test_2");
assert_eq!(get("run_test_2"), None);
}
#[test]
fn set_state_overwrites() {
set_state("run_test_3", RunState::Starting);
set_state("run_test_3", RunState::Running);
assert_eq!(get("run_test_3"), Some(RunState::Running));
}
#[test]
fn all_returns_entries() {
set_state("run_test_all_a", RunState::Running);
let entries = all();
assert!(entries.iter().any(|(k, _)| k == "run_test_all_a"));
}
#[test]
fn crashed_state_stores_exit_code() {
set_state("run_test_crash", RunState::Crashed(Some(1)));
assert_eq!(get("run_test_crash"), Some(RunState::Crashed(Some(1))));
}
#[test]
fn push_and_drain_last_played() {
let time = Utc::now();
push_last_played("run_test_lp", time);
let drained = drain_last_played();
assert!(drained.iter().any(|(k, _)| k == "run_test_lp"));
}
// Removed drain_empty_returns_empty: it relied on no other test pushing
// to LAST_PLAYED between the two drain calls, which races with the
// parallel push_and_drain_last_played test. The drain semantics are
// already covered by push_and_drain_last_played, which asserts a
// specific entry is present, and the empty-result path is exercised
// implicitly any time drain runs after that test's cleanup.
#[test]
fn send_kill_returns_false_for_missing() {
assert!(!send_kill("run_never_registered_xyz"));
}
#[test]
fn register_and_send_kill() {
let (tx, mut rx) = tokio::sync::oneshot::channel::<()>();
register_kill("run_test_kill", tx);
assert!(send_kill("run_test_kill"));
let _ = rx.try_recv();
}
#[test]
fn cleanup_kill_sender_removes() {
let (tx, _rx) = tokio::sync::oneshot::channel::<()>();
register_kill("run_test_cleanup", tx);
cleanup_kill_sender("run_test_cleanup");
assert!(!send_kill("run_test_cleanup"));
}