From c6c774b1e3c5d5c5c0485a71b007bc6118d45f3b Mon Sep 17 00:00:00 2001 From: objz Date: Wed, 27 May 2026 18:55:19 +0200 Subject: [PATCH] refactored: final review polish and detect_format + neoforge coverage Addresses the six items the last review flagged. Four are polish for existing tests; two add coverage for previously-untested public APIs. Polish: - instance/content/mods.rs: icon_path_from_value_map now asserts a single deterministic value. serde_json::Map is a BTreeMap so the "128" key sorts before "64" and the test no longer needs an order-tolerant disjunction. - cli/log.rs: replace the hand-rolled unique_temp_dir with tempfile::tempdir() across both tests. Drop the trailing remove_dir_all cleanup since TempDir handles that on Drop. Last inline test file using the hand-rolled pattern. - running.rs: remove drain_empty_returns_empty. Two consecutive calls to drain_last_played in the same test can race with the parallel push_and_drain_last_played test which pushes to the same global LAST_PLAYED state. drain semantics are covered by the existing push_and_drain test. - tui/error_buffer.rs: peek_does_not_remove now actually verifies the invariant the name promises. Pushes a tagged event, captures the count before and after peek_error, asserts the count is unchanged and the tagged event is still in the queue. Previous version only asserted that something was returned. New coverage: - net/neoforge.rs: added fetch_neoforge_game_versions_from(client, api_url) mirroring the existing _from pattern. tests/net_loaders.rs gains neoforge_fetch_game_versions_reverse_engineers_mc_versions covering the maven-version-to-MC-version reverse mapping, which was only touched by the #[ignore] live API test before. - instance/import/mod.rs: six new tests for detect_format covering mrpack detection, mmc-pack at root and nested, the priority case where both markers are present, unknown archives, and missing files. Helper make_pack_zip builds in-memory zips so the tests don't need fixture files on disk. --- src/cli/log.rs | 28 ++++--------- src/instance/content/mods.rs | 6 +-- src/instance/import/mod.rs | 80 ++++++++++++++++++++++++++++++++++++ src/net/neoforge.rs | 9 +++- src/running.rs | 12 +++--- src/tui/error_buffer.rs | 24 +++++++++-- tests/net_loaders.rs | 34 ++++++++++++++- 7 files changed, 157 insertions(+), 36 deletions(-) diff --git a/src/cli/log.rs b/src/cli/log.rs index 3c4f6ad..862469a 100644 --- a/src/cli/log.rs +++ b/src/cli/log.rs @@ -91,47 +91,33 @@ use super::utils::{require_instance, required_arg}; mod tests { use super::resolve_log_path; - fn unique_temp_dir() -> std::path::PathBuf { - std::env::temp_dir().join(format!( - "rmcl_cli_log_test_{}", - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .expect("time should work") - .as_nanos() - )) - } - #[test] fn resolves_latest_log_when_no_file_is_given() { - let root = unique_temp_dir(); - let dir = root.join("demo/.minecraft/logs/launches"); + let tmp = tempfile::tempdir().unwrap(); + let dir = tmp.path().join("demo/.minecraft/logs/launches"); std::fs::create_dir_all(&dir).expect("log directory should exist"); std::fs::write(dir.join("2024-01-02_03-04-05.log"), "newer").expect("write newer log"); std::fs::write(dir.join("2024-01-01_03-04-05.log"), "older").expect("write older log"); - let path = resolve_log_path(&root, "demo", None).expect("latest log should resolve"); + let path = resolve_log_path(tmp.path(), "demo", None).expect("latest log should resolve"); assert_eq!( path.file_name().and_then(|name| name.to_str()), Some("2024-01-02_03-04-05.log") ); - - let _ = std::fs::remove_dir_all(&root); } #[test] fn resolves_named_log_file() { - let root = unique_temp_dir(); - let dir = root.join("demo/.minecraft/logs/launches"); + let tmp = tempfile::tempdir().unwrap(); + let dir = tmp.path().join("demo/.minecraft/logs/launches"); std::fs::create_dir_all(&dir).expect("log directory should exist"); std::fs::write(dir.join("latest.log"), "hello").expect("write named log"); - let path = - resolve_log_path(&root, "demo", Some("latest.log")).expect("named log should resolve"); + let path = resolve_log_path(tmp.path(), "demo", Some("latest.log")) + .expect("named log should resolve"); assert_eq!( path.file_name().and_then(|name| name.to_str()), Some("latest.log") ); - - let _ = std::fs::remove_dir_all(&root); } } diff --git a/src/instance/content/mods.rs b/src/instance/content/mods.rs index 5e98909..c7947d5 100644 --- a/src/instance/content/mods.rs +++ b/src/instance/content/mods.rs @@ -801,10 +801,10 @@ description = "A neoforge mod" #[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"}); - let result = icon_path_from_value(&val); - // should return one of the values - assert!(result == "icon_64.png" || result == "icon_128.png"); + assert_eq!(icon_path_from_value(&val), "icon_128.png"); } #[test] diff --git a/src/instance/import/mod.rs b/src/instance/import/mod.rs index a35a583..d64ff73 100644 --- a/src/instance/import/mod.rs +++ b/src/instance/import/mod.rs @@ -136,6 +136,86 @@ pub async fn execute_import( #[cfg(test)] mod tests { 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 err = detect_format(Path::new("/nonexistent/pack.zip")).unwrap_err(); + assert!(err.contains("Cannot open"), "got: {err}"); + } #[test] fn unique_name_no_collision() { diff --git a/src/net/neoforge.rs b/src/net/neoforge.rs index b560206..19505a5 100644 --- a/src/net/neoforge.rs +++ b/src/net/neoforge.rs @@ -72,7 +72,14 @@ pub async fn fetch_neoforge_versions_from( pub async fn fetch_neoforge_game_versions( client: &HttpClient, ) -> Result, NetError> { - let maven: NeoForgeMavenVersions = client.get_json(NEOFORGE_API_BASE).await?; + fetch_neoforge_game_versions_from(client, NEOFORGE_API_BASE).await +} + +pub async fn fetch_neoforge_game_versions_from( + client: &HttpClient, + api_url: &str, +) -> Result, NetError> { + let maven: NeoForgeMavenVersions = client.get_json(api_url).await?; let mut game_versions: Vec = Vec::new(); for version in &maven.versions { diff --git a/src/running.rs b/src/running.rs index 20dda01..37b84e4 100644 --- a/src/running.rs +++ b/src/running.rs @@ -142,12 +142,12 @@ mod tests { assert!(drained.iter().any(|(k, _)| k == "run_test_lp")); } - #[test] - fn drain_empty_returns_empty() { - let _ = drain_last_played(); - let drained = drain_last_played(); - assert!(drained.is_empty()); - } + // 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() { diff --git a/src/tui/error_buffer.rs b/src/tui/error_buffer.rs index 84c03dd..a1d9130 100644 --- a/src/tui/error_buffer.rs +++ b/src/tui/error_buffer.rs @@ -89,12 +89,28 @@ mod tests { } } + // peek must not mutate the queue: count + identity of the front event + // are preserved across a peek. tagging the message lets us identify + // our own event amid whatever other tests pushed. #[test] fn peek_does_not_remove() { - push_error(make_event("err_peek")); - let before = peek_error(); - assert!(before.is_some()); - assert!(has_errors()); + let tag = "PEEK_DOES_NOT_REMOVE_TAG"; + push_error(make_event(tag)); + let count_before = peek_all_errors().len(); + let peeked = peek_error(); + let count_after = peek_all_errors().len(); + assert_eq!( + count_before, count_after, + "peek should not change queue length" + ); + // and the front entry is the same id we just peeked + assert!(peeked.is_some()); + assert!( + peek_all_errors() + .iter() + .any(|e| e.message.contains(tag)), + "our tagged event should still be in the queue" + ); } // ERROR_EVENTS is a global static shared across tests, so we tag our diff --git a/tests/net_loaders.rs b/tests/net_loaders.rs index 8cbedda..fc01364 100644 --- a/tests/net_loaders.rs +++ b/tests/net_loaders.rs @@ -12,7 +12,7 @@ use rmcl::net::fabric::{ fetch_fabric_game_versions_from, fetch_fabric_profile_from, fetch_fabric_versions_from, }; use rmcl::net::forge::{fetch_forge_game_versions_from, fetch_forge_versions_from}; -use rmcl::net::neoforge::fetch_neoforge_versions_from; +use rmcl::net::neoforge::{fetch_neoforge_game_versions_from, fetch_neoforge_versions_from}; use rmcl::net::quilt::{ fetch_quilt_game_versions_from, fetch_quilt_profile_from, fetch_quilt_versions_from, }; @@ -229,6 +229,38 @@ async fn neoforge_fetch_versions_filters_by_prefix() { assert_eq!(versions, vec!["20.4.190", "20.4.150"]); } +#[tokio::test] +async fn neoforge_fetch_game_versions_reverse_engineers_mc_versions() { + // neoforge "21.0.x" maps back to MC 1.21 (minor=0 strips the suffix); + // "20.4.x" maps to MC 1.20.4. beta/alpha suffixes don't affect the + // reverse mapping since the major/minor extraction happens first. + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/maven-api")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "versions": [ + "21.0.10", + "21.0.5", + "20.4.190", + "20.4.150" + ] + }))) + .mount(&server) + .await; + + let url = format!("{}/maven-api", server.uri()); + let versions = fetch_neoforge_game_versions_from(&HttpClient::new(), &url) + .await + .expect("neoforge game versions"); + let ids: Vec<&str> = versions.iter().map(|v| v.id.as_str()).collect(); + // dedup keeps the first occurrence, output is reversed, so the + // resulting list is in upstream maven-version order, deduped. + assert!(ids.contains(&"1.21")); + assert!(ids.contains(&"1.20.4")); + // both versions should be marked stable (no snapshot flag in maven) + assert!(versions.iter().all(|v| v.stable)); +} + #[tokio::test] async fn neoforge_fetch_versions_rejects_invalid_game_version() { let server = MockServer::start().await;