From aeeef26614b4a994f7c7af7ada437f504ddf73bf Mon Sep 17 00:00:00 2001 From: objz Date: Mon, 25 May 2026 21:52:49 +0200 Subject: [PATCH 01/20] added: lib.rs split + tests/ scaffold for integration testing --- Cargo.lock | 229 ++++++++++++++++++++++++++++++++++++++++++++ Cargo.toml | 3 + src/lib.rs | 13 +++ src/main.rs | 17 +--- tests/common/mod.rs | 4 + tests/smoke.rs | 10 ++ 6 files changed, 262 insertions(+), 14 deletions(-) create mode 100644 src/lib.rs create mode 100644 tests/common/mod.rs create mode 100644 tests/smoke.rs diff --git a/Cargo.lock b/Cargo.lock index 3fb39d2..c711d1b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -120,6 +120,16 @@ version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d902e3d592a523def97af8f317b08ce16b7ab854c1985a0c671e6f15cebc236" +[[package]] +name = "assert-json-diff" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e4f2b81832e72834d7518d8487a0396a28cc408186a2e8854c0f98011faf12" +dependencies = [ + "serde", + "serde_json", +] + [[package]] name = "async-trait" version = "0.1.89" @@ -480,6 +490,17 @@ dependencies = [ "yaml-rust2", ] +[[package]] +name = "console" +version = "0.16.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d64e8af5551369d19cf50138de61f1c42074ab970f74e99be916646777f8fc87" +dependencies = [ + "encode_unicode", + "libc", + "windows-sys 0.61.2", +] + [[package]] name = "const-oid" version = "0.10.2" @@ -761,6 +782,24 @@ dependencies = [ "syn 2.0.117", ] +[[package]] +name = "deadpool" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0be2b1d1d6ec8d846f05e137292d0b89133caf95ef33695424c09568bdd39b1b" +dependencies = [ + "deadpool-runtime", + "lazy_static", + "num_cpus", + "tokio", +] + +[[package]] +name = "deadpool-runtime" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "092966b41edc516079bdf31ec78a2e0588d1d0c08f78b91d8307215928642b2b" + [[package]] name = "deflate64" version = "0.1.12" @@ -927,6 +966,12 @@ version = "1.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719" +[[package]] +name = "encode_unicode" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0" + [[package]] name = "encoding_rs" version = "0.8.35" @@ -1105,6 +1150,21 @@ version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c" +[[package]] +name = "futures" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b147ee9d1f6d097cef9ce628cd2ee62288d963e16fb287bd9286455b241382d" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + [[package]] name = "futures-channel" version = "0.3.32" @@ -1112,6 +1172,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d" dependencies = [ "futures-core", + "futures-sink", ] [[package]] @@ -1120,6 +1181,17 @@ version = "0.3.32" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d" +[[package]] +name = "futures-executor" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf29c38818342a3b26b5b923639e7b1f4a61fc5e76102d4b1981c6dc7a7579d" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + [[package]] name = "futures-io" version = "0.3.32" @@ -1149,12 +1221,19 @@ version = "0.3.32" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393" +[[package]] +name = "futures-timer" +version = "3.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af43fadb8a98512d547e37b4e92e0ced13e205c061b87b4623eff01d918d6968" + [[package]] name = "futures-util" version = "0.3.32" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6" dependencies = [ + "futures-channel", "futures-core", "futures-io", "futures-macro", @@ -1235,6 +1314,31 @@ version = "0.32.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e629b9b98ef3dd8afe6ca2bd0f89306cec16d43d907889945bc5d6687f2f13c7" +[[package]] +name = "glob" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280" + +[[package]] +name = "h2" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "171fefbc92fe4a4de27e0698d6a5b392d6a0e333506bc49133760b3bcf948733" +dependencies = [ + "atomic-waker", + "bytes", + "fnv", + "futures-core", + "futures-sink", + "http", + "indexmap", + "slab", + "tokio", + "tokio-util", + "tracing", +] + [[package]] name = "hashbrown" version = "0.14.5" @@ -1282,6 +1386,12 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" +[[package]] +name = "hermit-abi" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c" + [[package]] name = "hex" version = "0.4.3" @@ -1336,6 +1446,12 @@ version = "1.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + [[package]] name = "hybrid-array" version = "0.4.11" @@ -1355,9 +1471,11 @@ dependencies = [ "bytes", "futures-channel", "futures-core", + "h2", "http", "http-body", "httparse", + "httpdate", "itoa", "pin-project-lite", "smallvec", @@ -1622,6 +1740,18 @@ dependencies = [ "hybrid-array", ] +[[package]] +name = "insta" +version = "1.47.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b4a6248eb93a4401ed2f37dfe8ea592d3cf05b7cf4f8efa867b6895af7e094e" +dependencies = [ + "console", + "once_cell", + "similar", + "tempfile", +] + [[package]] name = "instability" version = "0.3.12" @@ -2118,6 +2248,16 @@ dependencies = [ "libm", ] +[[package]] +name = "num_cpus" +version = "1.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91df4bbde75afed763b708b7eee1e8e7651e02d97f6d5dd763e89367e957b23b" +dependencies = [ + "hermit-abi", + "libc", +] + [[package]] name = "num_threads" version = "0.1.7" @@ -2498,6 +2638,15 @@ dependencies = [ "syn 2.0.117", ] +[[package]] +name = "proc-macro-crate" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +dependencies = [ + "toml_edit", +] + [[package]] name = "proc-macro-error-attr2" version = "2.0.0" @@ -2945,6 +3094,12 @@ version = "0.8.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a" +[[package]] +name = "relative-path" +version = "1.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba39f3699c378cd8970968dcbff9c43159ea4cfbd88d43c00b22f2ef10a435d2" + [[package]] name = "reqwest" version = "0.12.28" @@ -3013,6 +3168,7 @@ dependencies = [ "dirs", "dirs-next", "image", + "insta", "log", "minecraft-msa-auth", "notify", @@ -3023,6 +3179,7 @@ dependencies = [ "ratatui-textarea", "ratatui-themekit", "reqwest", + "rstest", "serde", "serde_json", "tachyonfx", @@ -3040,6 +3197,7 @@ dependencies = [ "tui-scrollview", "tui-widget-list", "which", + "wiremock", "zip", ] @@ -3057,6 +3215,36 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "rstest" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a2c585be59b6b5dd66a9d2084aa1d8bd52fbdb806eafdeffb52791147862035" +dependencies = [ + "futures", + "futures-timer", + "rstest_macros", + "rustc_version", +] + +[[package]] +name = "rstest_macros" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "825ea780781b15345a146be27eaefb05085e337e869bff01b4306a4fd4a9ad5a" +dependencies = [ + "cfg-if", + "glob", + "proc-macro-crate", + "proc-macro2", + "quote", + "regex", + "relative-path", + "rustc_version", + "syn 2.0.117", + "unicode-ident", +] + [[package]] name = "rust-ini" version = "0.21.3" @@ -3352,6 +3540,12 @@ version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "703d5c7ef118737c72f1af64ad2f6f8c5e1921f818cdcb97b8fe6fc69bf66214" +[[package]] +name = "similar" +version = "2.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbbb5d9659141646ae647b42fe094daf6c6192d1620870b449d9557f748b2daa" + [[package]] name = "siphasher" version = "1.0.2" @@ -3783,6 +3977,18 @@ dependencies = [ "serde_core", ] +[[package]] +name = "toml_edit" +version = "0.25.11+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b59c4d22ed448339746c59b905d24568fcbb3ab65a500494f7b8c3e97739f2b" +dependencies = [ + "indexmap", + "toml_datetime", + "toml_parser", + "winnow", +] + [[package]] name = "toml_parser" version = "1.1.2+spec-1.1.0" @@ -4729,6 +4935,29 @@ dependencies = [ "memchr", ] +[[package]] +name = "wiremock" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08db1edfb05d9b3c1542e521aea074442088292f00b5f28e435c714a98f85031" +dependencies = [ + "assert-json-diff", + "base64", + "deadpool", + "futures", + "http", + "http-body-util", + "hyper", + "hyper-util", + "log", + "once_cell", + "regex", + "serde", + "serde_json", + "tokio", + "url", +] + [[package]] name = "wit-bindgen" version = "0.51.0" diff --git a/Cargo.toml b/Cargo.toml index 0b99f1b..c4cb89c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -73,3 +73,6 @@ lto = "thin" [dev-dependencies] tempfile = "3" +insta = "1" +wiremock = "0.6" +rstest = "0.23" diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..5985c28 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,13 @@ +//! rmcl crate root. main.rs is a thin wrapper around this library so +//! integration tests in tests/ can import everything. + +pub mod auth; +pub mod cli; +pub mod config; +pub mod instance; +pub mod instance_logs; +pub mod launch_profile; +pub mod migrate; +pub mod net; +pub mod running; +pub mod tui; diff --git a/src/main.rs b/src/main.rs index c9cd4b6..c11a440 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,25 +1,14 @@ -pub mod auth; -mod cli; -pub mod config; -pub mod instance; -pub mod instance_logs; -pub mod launch_profile; -mod migrate; -pub mod net; -pub mod running; -pub mod tui; - #[tokio::main] async fn main() { // Run before logging::init() so the cache rename isn't blocked by a // freshly-created ~/.cache/rmcl/ directory. - migrate::run_legacy_rename(); + rmcl::migrate::run_legacy_rename(); // Guard must stay in scope to keep the log file writer alive - let _guard = tui::logging::init(); + let _guard = rmcl::tui::logging::init(); if let Err(e) = color_eyre::install() { eprintln!("Failed to install color-eyre: {}", e); } - cli::init().await + rmcl::cli::init().await } diff --git a/tests/common/mod.rs b/tests/common/mod.rs new file mode 100644 index 0000000..edf3a38 --- /dev/null +++ b/tests/common/mod.rs @@ -0,0 +1,4 @@ +//! shared helpers for integration tests in tests/. populated by phase C +//! when filesystem-touching tests move out of inline modules. + +// intentionally empty for now. diff --git a/tests/smoke.rs b/tests/smoke.rs new file mode 100644 index 0000000..3e81265 --- /dev/null +++ b/tests/smoke.rs @@ -0,0 +1,10 @@ +//! verifies the lib/main split worked: integration tests can see crate items +//! through the public API. + +#[test] +fn lib_target_is_importable() { + // touch one pure function from each major module so the linker fails if + // any module went private by mistake during the split. + assert!(rmcl::net::maven_coord_to_path("a:b:1.0").is_some()); + let _ = rmcl::config::SETTINGS.paths.effective_java_path(); +} From 961983d1fe702c65066834b9c2aae4bfcb4941e1 Mon Sep 17 00:00:00 2001 From: objz Date: Mon, 25 May 2026 22:07:05 +0200 Subject: [PATCH 02/20] removed: 6 useless tests (4 theatre + 2 wrapper redundancy) --- src/config/settings.rs | 37 ------------------------------------- src/config/theme.rs | 8 -------- src/tui/error_buffer.rs | 8 -------- 3 files changed, 53 deletions(-) diff --git a/src/config/settings.rs b/src/config/settings.rs index 857f03d..ed2c545 100644 --- a/src/config/settings.rs +++ b/src/config/settings.rs @@ -197,43 +197,6 @@ mod tests { assert!(!resolved.to_string_lossy().starts_with('~')); } - #[test] - fn resolve_instances_dir_absolute() { - let paths = Paths { - instances_dir: "/opt/rmcl/instances".to_owned(), - ..Paths::default() - }; - assert_eq!( - paths.resolve_instances_dir(), - PathBuf::from("/opt/rmcl/instances") - ); - } - - #[test] - fn resolve_meta_dir_absolute() { - let paths = Paths { - meta_dir: "/opt/rmcl/meta".to_owned(), - ..Paths::default() - }; - assert_eq!(paths.resolve_meta_dir(), PathBuf::from("/opt/rmcl/meta")); - } - - #[test] - fn defaults_have_expected_values() { - let d = Defaults::default(); - assert_eq!(d.memory_min, "512M"); - assert_eq!(d.memory_max, "2G"); - } - - #[test] - fn ui_defaults_have_expected_values() { - let ui = Ui::default(); - assert_eq!(ui.error_auto_dismiss_ms, 5000); - assert_eq!(ui.error_slide_start_ms, 3500); - assert_eq!(ui.error_fly_out_ms, 300); - assert_eq!(ui.max_error_events, 50); - } - #[test] fn config_deserializes_from_empty_toml() { let config: Config = toml::from_str("").unwrap(); diff --git a/src/config/theme.rs b/src/config/theme.rs index 9ac25ba..5d782b1 100644 --- a/src/config/theme.rs +++ b/src/config/theme.rs @@ -172,14 +172,6 @@ pub static BORDER_STYLE: LazyLock = mod tests { use super::*; - #[test] - fn default_theme_config() { - let config = ThemeConfig::default(); - assert_eq!(config.theme, "catppuccin"); - assert_eq!(config.border_style, BorderStyle::Rounded); - assert!(config.custom.is_none()); - } - #[test] fn border_style_roundtrip() { let style = BorderStyle::Double; diff --git a/src/tui/error_buffer.rs b/src/tui/error_buffer.rs index 07d9d98..bbf8cfc 100644 --- a/src/tui/error_buffer.rs +++ b/src/tui/error_buffer.rs @@ -89,14 +89,6 @@ mod tests { } } - #[test] - fn push_and_pop_fifo() { - push_error(make_event("err_fifo_1")); - push_error(make_event("err_fifo_2")); - let first = pop_error(); - assert!(first.is_some() || has_errors()); - } - #[test] fn has_errors_after_push() { push_error(make_event("err_has")); From c15cb9a378eacee15634c731284961f7c2ca3e8b Mon Sep 17 00:00:00 2001 From: objz Date: Mon, 25 May 2026 22:20:11 +0200 Subject: [PATCH 03/20] added: ratatui snapshot tests for ErrorPopup (4 scenarios) --- src/tui/widgets/popups/error.rs | 58 +++++++++++++++++++ ...or__render_tests__error_level_renders.snap | 9 +++ ...ror__render_tests__long_message_wraps.snap | 14 +++++ ...or__render_tests__narrow_frame_clamps.snap | 9 +++ ...ror__render_tests__warn_level_renders.snap | 9 +++ 5 files changed, 99 insertions(+) create mode 100644 src/tui/widgets/popups/snapshots/rmcl__tui__widgets__popups__error__render_tests__error_level_renders.snap create mode 100644 src/tui/widgets/popups/snapshots/rmcl__tui__widgets__popups__error__render_tests__long_message_wraps.snap create mode 100644 src/tui/widgets/popups/snapshots/rmcl__tui__widgets__popups__error__render_tests__narrow_frame_clamps.snap create mode 100644 src/tui/widgets/popups/snapshots/rmcl__tui__widgets__popups__error__render_tests__warn_level_renders.snap diff --git a/src/tui/widgets/popups/error.rs b/src/tui/widgets/popups/error.rs index af208d1..ce8d99a 100644 --- a/src/tui/widgets/popups/error.rs +++ b/src/tui/widgets/popups/error.rs @@ -94,3 +94,61 @@ pub fn popup_area(frame_area: Rect, message: &str, base_y: u16, elapsed_ms: u128 height: popup_h, }) } + +#[cfg(test)] +mod render_tests { + use super::*; + use ratatui::Terminal; + use ratatui::backend::TestBackend; + use std::time::Instant; + use tracing::Level; + + use crate::tui::error_buffer::ErrorEvent; + + fn render(event: ErrorEvent, width: u16, height: u16) -> Terminal { + let backend = TestBackend::new(width, height); + let mut terminal = Terminal::new(backend).unwrap(); + terminal + .draw(|f| { + let popup = ErrorPopup::new(event); + f.render_widget(popup, f.area()); + }) + .unwrap(); + terminal + } + + fn event(level: Level, message: &str) -> ErrorEvent { + ErrorEvent { + id: 1, + level, + message: message.to_string(), + pushed_at: Instant::now(), + } + } + + #[test] + fn warn_level_renders() { + let term = render(event(Level::WARN, "Disk space low"), 40, 5); + insta::assert_snapshot!(term.backend()); + } + + #[test] + fn error_level_renders() { + let term = render(event(Level::ERROR, "Connection refused"), 40, 5); + insta::assert_snapshot!(term.backend()); + } + + #[test] + fn long_message_wraps() { + let msg = "The Minecraft launcher could not reach the Mojang version manifest \ + after three retries. Check your network connection or proxy settings."; + let term = render(event(Level::ERROR, msg), 40, 10); + insta::assert_snapshot!(term.backend()); + } + + #[test] + fn narrow_frame_clamps() { + let term = render(event(Level::WARN, "Short message"), 18, 5); + insta::assert_snapshot!(term.backend()); + } +} diff --git a/src/tui/widgets/popups/snapshots/rmcl__tui__widgets__popups__error__render_tests__error_level_renders.snap b/src/tui/widgets/popups/snapshots/rmcl__tui__widgets__popups__error__render_tests__error_level_renders.snap new file mode 100644 index 0000000..91cab2f --- /dev/null +++ b/src/tui/widgets/popups/snapshots/rmcl__tui__widgets__popups__error__render_tests__error_level_renders.snap @@ -0,0 +1,9 @@ +--- +source: src/tui/widgets/popups/error.rs +expression: term.backend() +--- +"╭ ERROR ───────────────────────────────╮" +"│Connection refused │" +"│ │" +"│ │" +"╰──────────────────────────────────────╯" diff --git a/src/tui/widgets/popups/snapshots/rmcl__tui__widgets__popups__error__render_tests__long_message_wraps.snap b/src/tui/widgets/popups/snapshots/rmcl__tui__widgets__popups__error__render_tests__long_message_wraps.snap new file mode 100644 index 0000000..be8c6ae --- /dev/null +++ b/src/tui/widgets/popups/snapshots/rmcl__tui__widgets__popups__error__render_tests__long_message_wraps.snap @@ -0,0 +1,14 @@ +--- +source: src/tui/widgets/popups/error.rs +expression: term.backend() +--- +"╭ ERROR ───────────────────────────────╮" +"│The Minecraft launcher could not reach│" +"│the Mojang version manifest after │" +"│three retries. Check your network │" +"│connection or proxy settings. │" +"│ │" +"│ │" +"│ │" +"│ │" +"╰──────────────────────────────────────╯" diff --git a/src/tui/widgets/popups/snapshots/rmcl__tui__widgets__popups__error__render_tests__narrow_frame_clamps.snap b/src/tui/widgets/popups/snapshots/rmcl__tui__widgets__popups__error__render_tests__narrow_frame_clamps.snap new file mode 100644 index 0000000..2a059ba --- /dev/null +++ b/src/tui/widgets/popups/snapshots/rmcl__tui__widgets__popups__error__render_tests__narrow_frame_clamps.snap @@ -0,0 +1,9 @@ +--- +source: src/tui/widgets/popups/error.rs +expression: term.backend() +--- +"╭ WARN ──────────╮" +"│Short message │" +"│ │" +"│ │" +"╰────────────────╯" diff --git a/src/tui/widgets/popups/snapshots/rmcl__tui__widgets__popups__error__render_tests__warn_level_renders.snap b/src/tui/widgets/popups/snapshots/rmcl__tui__widgets__popups__error__render_tests__warn_level_renders.snap new file mode 100644 index 0000000..cbca974 --- /dev/null +++ b/src/tui/widgets/popups/snapshots/rmcl__tui__widgets__popups__error__render_tests__warn_level_renders.snap @@ -0,0 +1,9 @@ +--- +source: src/tui/widgets/popups/error.rs +expression: term.backend() +--- +"╭ WARN ────────────────────────────────╮" +"│Disk space low │" +"│ │" +"│ │" +"╰──────────────────────────────────────╯" From 63fb96a0d2cf98205d9d947db98ad44416d77c1c Mon Sep 17 00:00:00 2001 From: objz Date: Mon, 25 May 2026 22:21:49 +0200 Subject: [PATCH 04/20] added: run network canaries on master push only --- .github/workflows/build.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 2619ef0..c51a7b2 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -55,3 +55,8 @@ jobs: - name: cargo build run: cargo build --locked + + - name: cargo test --ignored (network canaries, master only) + if: github.event_name == 'push' && github.ref == 'refs/heads/master' + continue-on-error: true + run: cargo test --locked --all-targets -- --ignored From 05bea59ef1f9e8f4d41d3a2375fcc006a0e556dc Mon Sep 17 00:00:00 2001 From: objz Date: Mon, 25 May 2026 22:39:49 +0200 Subject: [PATCH 05/20] refactored: narrow lib.rs visibility + drop speculative tests/common --- src/lib.rs | 14 ++++++++++---- src/main.rs | 4 ++-- tests/common/mod.rs | 4 ---- 3 files changed, 12 insertions(+), 10 deletions(-) delete mode 100644 tests/common/mod.rs diff --git a/src/lib.rs b/src/lib.rs index 5985c28..be43188 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,13 +1,19 @@ -//! rmcl crate root. main.rs is a thin wrapper around this library so -//! integration tests in tests/ can import everything. +// crate root. main.rs is a thin wrapper that imports the two entry points +// re-exported below; everything else stays crate-private. integration tests +// in tests/ that need to reach in deeper can use `rmcl::auth`, `rmcl::net`, +// etc. directly; cli + migrate stay private because they have nothing +// general to expose. pub mod auth; -pub mod cli; +mod cli; pub mod config; pub mod instance; pub mod instance_logs; pub mod launch_profile; -pub mod migrate; +mod migrate; pub mod net; pub mod running; pub mod tui; + +pub use cli::init as cli_init; +pub use migrate::run_legacy_rename as migrate_legacy_rename; diff --git a/src/main.rs b/src/main.rs index c11a440..ec7b258 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,7 +2,7 @@ async fn main() { // Run before logging::init() so the cache rename isn't blocked by a // freshly-created ~/.cache/rmcl/ directory. - rmcl::migrate::run_legacy_rename(); + rmcl::migrate_legacy_rename(); // Guard must stay in scope to keep the log file writer alive let _guard = rmcl::tui::logging::init(); @@ -10,5 +10,5 @@ async fn main() { eprintln!("Failed to install color-eyre: {}", e); } - rmcl::cli::init().await + rmcl::cli_init().await } diff --git a/tests/common/mod.rs b/tests/common/mod.rs deleted file mode 100644 index edf3a38..0000000 --- a/tests/common/mod.rs +++ /dev/null @@ -1,4 +0,0 @@ -//! shared helpers for integration tests in tests/. populated by phase C -//! when filesystem-touching tests move out of inline modules. - -// intentionally empty for now. From 2163fef17540ad08a0421394361dd4b3a6adbd72 Mon Sep 17 00:00:00 2001 From: objz Date: Mon, 25 May 2026 22:44:49 +0200 Subject: [PATCH 06/20] added: INFO-level snapshot + popup_area unit tests; rename narrow_frame test --- src/tui/widgets/popups/error.rs | 55 ++++++++++++++++++- ...ror__render_tests__info_level_renders.snap | 9 +++ ...__render_tests__narrow_frame_renders.snap} | 0 3 files changed, 63 insertions(+), 1 deletion(-) create mode 100644 src/tui/widgets/popups/snapshots/rmcl__tui__widgets__popups__error__render_tests__info_level_renders.snap rename src/tui/widgets/popups/snapshots/{rmcl__tui__widgets__popups__error__render_tests__narrow_frame_clamps.snap => rmcl__tui__widgets__popups__error__render_tests__narrow_frame_renders.snap} (100%) diff --git a/src/tui/widgets/popups/error.rs b/src/tui/widgets/popups/error.rs index ce8d99a..4ca8511 100644 --- a/src/tui/widgets/popups/error.rs +++ b/src/tui/widgets/popups/error.rs @@ -138,6 +138,14 @@ mod render_tests { insta::assert_snapshot!(term.backend()); } + // info-level events hit the catch-all `_` arm in the label match; previously + // there was no test covering it. + #[test] + fn info_level_renders() { + let term = render(event(Level::INFO, "Reloaded config"), 40, 5); + insta::assert_snapshot!(term.backend()); + } + #[test] fn long_message_wraps() { let msg = "The Minecraft launcher could not reach the Mojang version manifest \ @@ -147,8 +155,53 @@ mod render_tests { } #[test] - fn narrow_frame_clamps() { + fn narrow_frame_renders() { let term = render(event(Level::WARN, "Short message"), 18, 5); insta::assert_snapshot!(term.backend()); } } + +#[cfg(test)] +mod area_tests { + use super::popup_area; + use crate::config::SETTINGS; + use ratatui::layout::Rect; + + fn frame() -> Rect { + Rect::new(0, 0, 80, 24) + } + + #[test] + fn returns_none_after_dismiss_timeout() { + let past_dismiss = SETTINGS.ui.error_auto_dismiss_ms as u128 + 1; + assert!(popup_area(frame(), "msg", 0, past_dismiss).is_none()); + } + + #[test] + fn returns_some_inside_dismiss_window() { + assert!(popup_area(frame(), "msg", 0, 0).is_some()); + } + + #[test] + fn returns_none_when_vertical_room_too_small() { + // base_y = 22 leaves only height 24 - 22 - 1 = 1 row of usable space, + // less than the minimum 3 needed for border + content + border. + assert!(popup_area(frame(), "msg", 22, 0).is_none()); + } + + #[test] + fn clamps_popup_width_to_frame() { + // a wider-than-the-frame message gets clamped so the popup fits + // inside frame.width minus the right-edge padding (saturating_sub(4)). + let huge = "x".repeat(200); + let area = popup_area(frame(), &huge, 0, 0).unwrap(); + assert!(area.width <= frame().width.saturating_sub(4)); + } + + #[test] + fn anchors_popup_to_right_edge() { + let area = popup_area(frame(), "msg", 0, 0).unwrap(); + // popup_w is added to base_x to reach frame.width - 2 (right-edge gutter) + assert_eq!(area.x + area.width + 2, frame().width); + } +} diff --git a/src/tui/widgets/popups/snapshots/rmcl__tui__widgets__popups__error__render_tests__info_level_renders.snap b/src/tui/widgets/popups/snapshots/rmcl__tui__widgets__popups__error__render_tests__info_level_renders.snap new file mode 100644 index 0000000..8331205 --- /dev/null +++ b/src/tui/widgets/popups/snapshots/rmcl__tui__widgets__popups__error__render_tests__info_level_renders.snap @@ -0,0 +1,9 @@ +--- +source: src/tui/widgets/popups/error.rs +expression: term.backend() +--- +"╭ INFO ────────────────────────────────╮" +"│Reloaded config │" +"│ │" +"│ │" +"╰──────────────────────────────────────╯" diff --git a/src/tui/widgets/popups/snapshots/rmcl__tui__widgets__popups__error__render_tests__narrow_frame_clamps.snap b/src/tui/widgets/popups/snapshots/rmcl__tui__widgets__popups__error__render_tests__narrow_frame_renders.snap similarity index 100% rename from src/tui/widgets/popups/snapshots/rmcl__tui__widgets__popups__error__render_tests__narrow_frame_clamps.snap rename to src/tui/widgets/popups/snapshots/rmcl__tui__widgets__popups__error__render_tests__narrow_frame_renders.snap From c6fce8592a969ac9cda66836e7fe4e16b4382fd9 Mon Sep 17 00:00:00 2001 From: objz Date: Mon, 25 May 2026 22:45:11 +0200 Subject: [PATCH 07/20] fixed: let CI network canaries actually red the build when they break --- .github/workflows/build.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index c51a7b2..1feab5c 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -58,5 +58,4 @@ jobs: - name: cargo test --ignored (network canaries, master only) if: github.event_name == 'push' && github.ref == 'refs/heads/master' - continue-on-error: true run: cargo test --locked --all-targets -- --ignored From cc0dde106a7d1a2a719de174aa20104f81875d65 Mon Sep 17 00:00:00 2001 From: objz Date: Tue, 26 May 2026 21:11:38 +0200 Subject: [PATCH 08/20] refactored: move public-API filesystem tests to tests/ Per Phase C of the test overhaul: tests that touch the filesystem and exercise the public API surface (scan_screenshots, scan_shaders, scan_worlds, scan_resource_packs, log_files) move from inline mod tests into tests/. They now consume rmcl as an external crate, mirroring how real callers would. AccountStore::store_save_and_reload stays inline because the helper it needs (constructing AccountStore directly with a tempdir path) requires reaching into a private field; exposing that just for tests would leak implementation detail. The other accounts tests are in-memory and stay inline regardless. The extract_description_* tests in resource_packs stay inline since they are pure logic on serde_json::Value (no filesystem). image is added to dev-dependencies so integration tests can fabricate 1x1 PNG fixtures (already a regular dep of the lib). --- Cargo.toml | 1 + src/instance/content/resource_packs.rs | 61 -------- src/instance/content/shaders.rs | 61 -------- src/instance/content/worlds.rs | 76 ---------- src/instance/log_files.rs | 69 --------- src/instance/screenshots.rs | 84 ----------- src/main.rs | 2 - tests/content_scanners.rs | 187 +++++++++++++++++++++++++ tests/log_files.rs | 76 ++++++++++ tests/screenshots.rs | 85 +++++++++++ 10 files changed, 349 insertions(+), 353 deletions(-) create mode 100644 tests/content_scanners.rs create mode 100644 tests/log_files.rs create mode 100644 tests/screenshots.rs diff --git a/Cargo.toml b/Cargo.toml index c4cb89c..ed11178 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -76,3 +76,4 @@ tempfile = "3" insta = "1" wiremock = "0.6" rstest = "0.23" +image = { version = "0.25", default-features = false, features = ["png"] } diff --git a/src/instance/content/resource_packs.rs b/src/instance/content/resource_packs.rs index 4586fc1..cbaaa0e 100644 --- a/src/instance/content/resource_packs.rs +++ b/src/instance/content/resource_packs.rs @@ -201,65 +201,4 @@ mod tests { let val = serde_json::json!(true); assert_eq!(extract_description(&val), ""); } - - fn setup_packs_dir(tmp: &std::path::Path, instance: &str) -> std::path::PathBuf { - let dir = tmp.join(instance).join(".minecraft").join("resourcepacks"); - std::fs::create_dir_all(&dir).unwrap(); - dir - } - - #[test] - fn scan_resource_packs_empty_dir() { - let tmp = tempfile::tempdir().unwrap(); - setup_packs_dir(tmp.path(), "inst"); - let packs = scan_resource_packs(tmp.path(), "inst"); - assert!(packs.is_empty()); - } - - #[test] - fn scan_resource_packs_missing_dir_returns_empty() { - let tmp = tempfile::tempdir().unwrap(); - let packs = scan_resource_packs(tmp.path(), "ghost"); - assert!(packs.is_empty()); - } - - #[test] - fn scan_resource_packs_finds_zips_and_dirs() { - let tmp = tempfile::tempdir().unwrap(); - let dir = setup_packs_dir(tmp.path(), "inst"); - std::fs::write(dir.join("pack-a.zip"), b"PK\x03\x04").unwrap(); - std::fs::create_dir(dir.join("pack-b")).unwrap(); - let packs = scan_resource_packs(tmp.path(), "inst"); - assert_eq!(packs.len(), 2); - } - - #[test] - fn scan_resource_packs_disabled_variants() { - let tmp = tempfile::tempdir().unwrap(); - let dir = setup_packs_dir(tmp.path(), "inst"); - std::fs::write(dir.join("on.zip"), b"PK\x03\x04").unwrap(); - std::fs::write(dir.join("off.zip.disabled"), b"PK\x03\x04").unwrap(); - std::fs::create_dir(dir.join("diron")).unwrap(); - std::fs::create_dir(dir.join("diroff.disabled")).unwrap(); - let packs = scan_resource_packs(tmp.path(), "inst"); - assert_eq!(packs.len(), 4); - let on_zip = packs.iter().find(|p| p.file_stem == "on").unwrap(); - let off_zip = packs.iter().find(|p| p.file_stem == "off").unwrap(); - let on_dir = packs.iter().find(|p| p.file_stem == "diron").unwrap(); - let off_dir = packs.iter().find(|p| p.file_stem == "diroff").unwrap(); - assert!(on_zip.enabled); - assert!(!off_zip.enabled); - assert!(on_dir.enabled); - assert!(!off_dir.enabled); - } - - #[test] - fn scan_resource_packs_ignores_non_pack_files() { - let tmp = tempfile::tempdir().unwrap(); - let dir = setup_packs_dir(tmp.path(), "inst"); - std::fs::write(dir.join("notes.txt"), "not a pack").unwrap(); - std::fs::write(dir.join("valid.zip"), b"PK\x03\x04").unwrap(); - let packs = scan_resource_packs(tmp.path(), "inst"); - assert_eq!(packs.len(), 1); - } } diff --git a/src/instance/content/shaders.rs b/src/instance/content/shaders.rs index 9a46f08..775f8d7 100644 --- a/src/instance/content/shaders.rs +++ b/src/instance/content/shaders.rs @@ -90,64 +90,3 @@ fn read_shader_metadata_from_dir(dir: &Path) -> (String, Option>) { (description, icon_bytes) } -#[cfg(test)] -mod tests { - use super::*; - - fn setup_shaders_dir(tmp: &std::path::Path, instance: &str) -> std::path::PathBuf { - let dir = tmp.join(instance).join(".minecraft").join("shaderpacks"); - std::fs::create_dir_all(&dir).unwrap(); - dir - } - - #[test] - fn scan_shaders_empty_dir() { - let tmp = tempfile::tempdir().unwrap(); - setup_shaders_dir(tmp.path(), "inst"); - let shaders = scan_shaders(tmp.path(), "inst"); - assert!(shaders.is_empty()); - } - - #[test] - fn scan_shaders_missing_dir_returns_empty() { - let tmp = tempfile::tempdir().unwrap(); - let shaders = scan_shaders(tmp.path(), "ghost"); - assert!(shaders.is_empty()); - } - - #[test] - fn scan_shaders_finds_zip_and_dir() { - let tmp = tempfile::tempdir().unwrap(); - let dir = setup_shaders_dir(tmp.path(), "inst"); - std::fs::write(dir.join("shader-a.zip"), b"PK\x03\x04").unwrap(); - std::fs::create_dir(dir.join("shader-b")).unwrap(); - let shaders = scan_shaders(tmp.path(), "inst"); - assert_eq!(shaders.len(), 2); - } - - #[test] - fn scan_shaders_disabled_variants() { - let tmp = tempfile::tempdir().unwrap(); - let dir = setup_shaders_dir(tmp.path(), "inst"); - std::fs::write(dir.join("active.zip"), b"PK\x03\x04").unwrap(); - std::fs::write(dir.join("off.zip.disabled"), b"PK\x03\x04").unwrap(); - std::fs::create_dir(dir.join("dirshader.disabled")).unwrap(); - let shaders = scan_shaders(tmp.path(), "inst"); - let active = shaders.iter().find(|s| s.file_stem == "active").unwrap(); - let off = shaders.iter().find(|s| s.file_stem == "off").unwrap(); - let diroff = shaders.iter().find(|s| s.file_stem == "dirshader").unwrap(); - assert!(active.enabled); - assert!(!off.enabled); - assert!(!diroff.enabled); - } - - #[test] - fn scan_shaders_ignores_non_shader_files() { - let tmp = tempfile::tempdir().unwrap(); - let dir = setup_shaders_dir(tmp.path(), "inst"); - std::fs::write(dir.join("readme.txt"), "not a shader").unwrap(); - std::fs::write(dir.join("valid.zip"), b"PK\x03\x04").unwrap(); - let shaders = scan_shaders(tmp.path(), "inst"); - assert_eq!(shaders.len(), 1); - } -} diff --git a/src/instance/content/worlds.rs b/src/instance/content/worlds.rs index fd11df5..fce0aa9 100644 --- a/src/instance/content/worlds.rs +++ b/src/instance/content/worlds.rs @@ -135,79 +135,3 @@ fn format_size(bytes: u64) -> String { } } -#[cfg(test)] -mod tests { - use super::*; - - fn setup_saves_dir(tmp: &Path, instance: &str) -> std::path::PathBuf { - let dir = tmp.join(instance).join(".minecraft").join("saves"); - std::fs::create_dir_all(&dir).unwrap(); - dir - } - - #[test] - fn scan_worlds_empty_dir() { - let tmp = tempfile::tempdir().unwrap(); - setup_saves_dir(tmp.path(), "inst"); - let worlds = scan_worlds(tmp.path(), "inst"); - assert!(worlds.is_empty()); - } - - #[test] - fn scan_worlds_missing_dir_returns_empty() { - let tmp = tempfile::tempdir().unwrap(); - let worlds = scan_worlds(tmp.path(), "ghost"); - assert!(worlds.is_empty()); - } - - #[test] - fn scan_worlds_finds_directories() { - let tmp = tempfile::tempdir().unwrap(); - let dir = setup_saves_dir(tmp.path(), "inst"); - std::fs::create_dir(dir.join("My World")).unwrap(); - std::fs::create_dir(dir.join("Creative")).unwrap(); - let worlds = scan_worlds(tmp.path(), "inst"); - assert_eq!(worlds.len(), 2); - } - - #[test] - fn scan_worlds_ignores_files() { - let tmp = tempfile::tempdir().unwrap(); - let dir = setup_saves_dir(tmp.path(), "inst"); - std::fs::create_dir(dir.join("World1")).unwrap(); - std::fs::write(dir.join("stray-file.txt"), "not a world").unwrap(); - let worlds = scan_worlds(tmp.path(), "inst"); - assert_eq!(worlds.len(), 1); - } - - #[test] - fn scan_worlds_disabled_world() { - let tmp = tempfile::tempdir().unwrap(); - let dir = setup_saves_dir(tmp.path(), "inst"); - std::fs::create_dir(dir.join("ActiveWorld")).unwrap(); - std::fs::create_dir(dir.join("HiddenWorld.disabled")).unwrap(); - let worlds = scan_worlds(tmp.path(), "inst"); - let active = worlds - .iter() - .find(|w| w.file_stem == "ActiveWorld") - .unwrap(); - let hidden = worlds - .iter() - .find(|w| w.file_stem == "HiddenWorld") - .unwrap(); - assert!(active.enabled); - assert!(!hidden.enabled); - } - - #[test] - fn scan_worlds_sorted_case_insensitive() { - let tmp = tempfile::tempdir().unwrap(); - let dir = setup_saves_dir(tmp.path(), "inst"); - std::fs::create_dir(dir.join("Zeta")).unwrap(); - std::fs::create_dir(dir.join("alpha")).unwrap(); - std::fs::create_dir(dir.join("Beta")).unwrap(); - let worlds = scan_worlds(tmp.path(), "inst"); - let names: Vec<&str> = worlds.iter().map(|w| w.name.as_str()).collect(); - assert_eq!(names, vec!["alpha", "Beta", "Zeta"]); - } -} diff --git a/src/instance/log_files.rs b/src/instance/log_files.rs index ec244f0..858f6ff 100644 --- a/src/instance/log_files.rs +++ b/src/instance/log_files.rs @@ -61,12 +61,6 @@ pub fn read_log_file(path: &Path) -> Vec { mod tests { use super::*; - fn setup_log_dir(tmp: &Path, instance: &str) -> PathBuf { - let dir = log_dir(tmp, instance); - std::fs::create_dir_all(&dir).unwrap(); - dir - } - #[test] fn log_dir_builds_correct_path() { let p = log_dir(Path::new("/instances"), "my-world"); @@ -75,67 +69,4 @@ mod tests { PathBuf::from("/instances/my-world/.minecraft/logs/launches") ); } - - #[test] - fn scan_log_files_empty_dir() { - let tmp = tempfile::tempdir().unwrap(); - setup_log_dir(tmp.path(), "inst"); - let entries = scan_log_files(tmp.path(), "inst"); - assert!(entries.is_empty()); - } - - #[test] - fn scan_log_files_finds_logs() { - let tmp = tempfile::tempdir().unwrap(); - let dir = setup_log_dir(tmp.path(), "inst"); - std::fs::write(dir.join("2024-01-01_12-00-00.log"), "line1\nline2").unwrap(); - std::fs::write(dir.join("2024-01-02_12-00-00.log"), "line3").unwrap(); - let entries = scan_log_files(tmp.path(), "inst"); - assert_eq!(entries.len(), 2); - assert_eq!(entries[0].name, "2024-01-02_12-00-00.log"); - assert_eq!(entries[1].name, "2024-01-01_12-00-00.log"); - } - - #[test] - fn scan_log_files_ignores_non_log() { - let tmp = tempfile::tempdir().unwrap(); - let dir = setup_log_dir(tmp.path(), "inst"); - std::fs::write(dir.join("notes.txt"), "not a log").unwrap(); - std::fs::write(dir.join("real.log"), "log line").unwrap(); - let entries = scan_log_files(tmp.path(), "inst"); - assert_eq!(entries.len(), 1); - assert_eq!(entries[0].name, "real.log"); - } - - #[test] - fn scan_log_files_missing_dir_returns_empty() { - let tmp = tempfile::tempdir().unwrap(); - let entries = scan_log_files(tmp.path(), "ghost"); - assert!(entries.is_empty()); - } - - #[test] - fn read_log_file_returns_lines() { - let tmp = tempfile::tempdir().unwrap(); - let path = tmp.path().join("test.log"); - std::fs::write(&path, "alpha\nbeta\ngamma").unwrap(); - let lines = read_log_file(&path); - assert_eq!(lines, vec!["alpha", "beta", "gamma"]); - } - - #[test] - fn read_log_file_missing_returns_empty() { - let lines = read_log_file(Path::new("/nonexistent/test.log")); - assert!(lines.is_empty()); - } - - #[test] - fn create_log_file_creates_path() { - let tmp = tempfile::tempdir().unwrap(); - let path = create_log_file(tmp.path(), "inst"); - assert!(path.is_some()); - let path = path.unwrap(); - assert!(path.to_string_lossy().ends_with(".log")); - assert!(path.parent().unwrap().exists()); - } } diff --git a/src/instance/screenshots.rs b/src/instance/screenshots.rs index 95225bf..62b5acd 100644 --- a/src/instance/screenshots.rs +++ b/src/instance/screenshots.rs @@ -46,87 +46,3 @@ pub fn scan_screenshots(instances_dir: &Path, instance_name: &str) -> Vec PathBuf { - let dir = tmp.join(instance).join(".minecraft").join("screenshots"); - std::fs::create_dir_all(&dir).unwrap(); - dir - } - - fn tiny_png() -> Vec { - let img = image::RgbImage::from_pixel(1, 1, image::Rgb([255, 255, 255])); - let mut buf = std::io::Cursor::new(Vec::new()); - img.write_to(&mut buf, image::ImageFormat::Png).unwrap(); - buf.into_inner() - } - - #[test] - fn scan_screenshots_empty_dir() { - let tmp = tempfile::tempdir().unwrap(); - setup_screenshots_dir(tmp.path(), "inst"); - let screenshots = scan_screenshots(tmp.path(), "inst"); - assert!(screenshots.is_empty()); - } - - #[test] - fn scan_screenshots_missing_dir_returns_empty() { - let tmp = tempfile::tempdir().unwrap(); - let screenshots = scan_screenshots(tmp.path(), "ghost"); - assert!(screenshots.is_empty()); - } - - #[test] - fn scan_screenshots_finds_images() { - let tmp = tempfile::tempdir().unwrap(); - let dir = setup_screenshots_dir(tmp.path(), "inst"); - std::fs::write(dir.join("2024-01-01.png"), tiny_png()).unwrap(); - std::fs::write(dir.join("2024-01-02.png"), tiny_png()).unwrap(); - let screenshots = scan_screenshots(tmp.path(), "inst"); - assert_eq!(screenshots.len(), 2); - } - - #[test] - fn scan_screenshots_ignores_non_images() { - let tmp = tempfile::tempdir().unwrap(); - let dir = setup_screenshots_dir(tmp.path(), "inst"); - std::fs::write(dir.join("pic.png"), tiny_png()).unwrap(); - std::fs::write(dir.join("notes.txt"), "not an image").unwrap(); - let screenshots = scan_screenshots(tmp.path(), "inst"); - assert_eq!(screenshots.len(), 1); - } - - #[test] - fn scan_screenshots_sorted_newest_first() { - let tmp = tempfile::tempdir().unwrap(); - let dir = setup_screenshots_dir(tmp.path(), "inst"); - std::fs::write(dir.join("aaa.png"), tiny_png()).unwrap(); - std::fs::write(dir.join("zzz.png"), tiny_png()).unwrap(); - let screenshots = scan_screenshots(tmp.path(), "inst"); - assert_eq!(screenshots[0].name, "zzz.png"); - assert_eq!(screenshots[1].name, "aaa.png"); - } - - #[test] - fn scan_screenshots_reads_dimensions() { - let tmp = tempfile::tempdir().unwrap(); - let dir = setup_screenshots_dir(tmp.path(), "inst"); - std::fs::write(dir.join("shot.png"), tiny_png()).unwrap(); - let screenshots = scan_screenshots(tmp.path(), "inst"); - assert_eq!(screenshots[0].width, 1); - assert_eq!(screenshots[0].height, 1); - } - - #[test] - fn scan_screenshots_bad_image_uses_default_dimensions() { - let tmp = tempfile::tempdir().unwrap(); - let dir = setup_screenshots_dir(tmp.path(), "inst"); - std::fs::write(dir.join("corrupt.png"), b"not a real png").unwrap(); - let screenshots = scan_screenshots(tmp.path(), "inst"); - assert_eq!(screenshots.len(), 1); - assert_eq!(screenshots[0].width, 1920); - assert_eq!(screenshots[0].height, 1080); - } -} diff --git a/src/main.rs b/src/main.rs index ec7b258..2301b5d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,7 +1,5 @@ #[tokio::main] async fn main() { - // Run before logging::init() so the cache rename isn't blocked by a - // freshly-created ~/.cache/rmcl/ directory. rmcl::migrate_legacy_rename(); // Guard must stay in scope to keep the log file writer alive diff --git a/tests/content_scanners.rs b/tests/content_scanners.rs new file mode 100644 index 0000000..aa4dd80 --- /dev/null +++ b/tests/content_scanners.rs @@ -0,0 +1,187 @@ +// integration tests for the public content-scanner APIs: shaders, worlds, +// and resource packs. each scanner walks an instance's .minecraft subdir +// and returns ContentEntry rows; shape varies slightly per content type +// (worlds are directories only, packs and shaders accept .zip or dir, etc.). + +use std::path::{Path, PathBuf}; + +use rmcl::instance::content::resource_packs::scan_resource_packs; +use rmcl::instance::content::shaders::scan_shaders; +use rmcl::instance::content::worlds::scan_worlds; + +fn setup_subdir(tmp: &Path, instance: &str, sub: &str) -> PathBuf { + let dir = tmp.join(instance).join(".minecraft").join(sub); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +// minimal zip header byte stream; enough that the scanner accepts the file +// without panicking even though it can't actually unpack metadata. +const ZIP_HEADER: &[u8] = b"PK\x03\x04"; + +// ---------- shaders ---------- + +#[test] +fn shaders_empty_dir_returns_empty() { + let tmp = tempfile::tempdir().unwrap(); + setup_subdir(tmp.path(), "inst", "shaderpacks"); + assert!(scan_shaders(tmp.path(), "inst").is_empty()); +} + +#[test] +fn shaders_missing_dir_returns_empty() { + let tmp = tempfile::tempdir().unwrap(); + assert!(scan_shaders(tmp.path(), "ghost").is_empty()); +} + +#[test] +fn shaders_finds_zip_and_dir() { + let tmp = tempfile::tempdir().unwrap(); + let dir = setup_subdir(tmp.path(), "inst", "shaderpacks"); + std::fs::write(dir.join("shader-a.zip"), ZIP_HEADER).unwrap(); + std::fs::create_dir(dir.join("shader-b")).unwrap(); + assert_eq!(scan_shaders(tmp.path(), "inst").len(), 2); +} + +#[test] +fn shaders_disabled_variants() { + let tmp = tempfile::tempdir().unwrap(); + let dir = setup_subdir(tmp.path(), "inst", "shaderpacks"); + std::fs::write(dir.join("active.zip"), ZIP_HEADER).unwrap(); + std::fs::write(dir.join("off.zip.disabled"), ZIP_HEADER).unwrap(); + std::fs::create_dir(dir.join("dirshader.disabled")).unwrap(); + let shaders = scan_shaders(tmp.path(), "inst"); + let active = shaders.iter().find(|s| s.file_stem == "active").unwrap(); + let off = shaders.iter().find(|s| s.file_stem == "off").unwrap(); + let diroff = shaders.iter().find(|s| s.file_stem == "dirshader").unwrap(); + assert!(active.enabled); + assert!(!off.enabled); + assert!(!diroff.enabled); +} + +#[test] +fn shaders_ignores_non_shader_files() { + let tmp = tempfile::tempdir().unwrap(); + let dir = setup_subdir(tmp.path(), "inst", "shaderpacks"); + std::fs::write(dir.join("readme.txt"), "not a shader").unwrap(); + std::fs::write(dir.join("valid.zip"), ZIP_HEADER).unwrap(); + assert_eq!(scan_shaders(tmp.path(), "inst").len(), 1); +} + +// ---------- worlds ---------- +// worlds are always directories (no zip form), so the test shape differs. + +#[test] +fn worlds_empty_dir_returns_empty() { + let tmp = tempfile::tempdir().unwrap(); + setup_subdir(tmp.path(), "inst", "saves"); + assert!(scan_worlds(tmp.path(), "inst").is_empty()); +} + +#[test] +fn worlds_missing_dir_returns_empty() { + let tmp = tempfile::tempdir().unwrap(); + assert!(scan_worlds(tmp.path(), "ghost").is_empty()); +} + +#[test] +fn worlds_finds_directories() { + let tmp = tempfile::tempdir().unwrap(); + let dir = setup_subdir(tmp.path(), "inst", "saves"); + std::fs::create_dir(dir.join("My World")).unwrap(); + std::fs::create_dir(dir.join("Creative")).unwrap(); + assert_eq!(scan_worlds(tmp.path(), "inst").len(), 2); +} + +#[test] +fn worlds_ignores_files() { + let tmp = tempfile::tempdir().unwrap(); + let dir = setup_subdir(tmp.path(), "inst", "saves"); + std::fs::create_dir(dir.join("World1")).unwrap(); + std::fs::write(dir.join("stray-file.txt"), "not a world").unwrap(); + assert_eq!(scan_worlds(tmp.path(), "inst").len(), 1); +} + +#[test] +fn worlds_disabled_world() { + let tmp = tempfile::tempdir().unwrap(); + let dir = setup_subdir(tmp.path(), "inst", "saves"); + std::fs::create_dir(dir.join("ActiveWorld")).unwrap(); + std::fs::create_dir(dir.join("HiddenWorld.disabled")).unwrap(); + let worlds = scan_worlds(tmp.path(), "inst"); + let active = worlds + .iter() + .find(|w| w.file_stem == "ActiveWorld") + .unwrap(); + let hidden = worlds + .iter() + .find(|w| w.file_stem == "HiddenWorld") + .unwrap(); + assert!(active.enabled); + assert!(!hidden.enabled); +} + +#[test] +fn worlds_sorted_case_insensitive() { + let tmp = tempfile::tempdir().unwrap(); + let dir = setup_subdir(tmp.path(), "inst", "saves"); + std::fs::create_dir(dir.join("Zeta")).unwrap(); + std::fs::create_dir(dir.join("alpha")).unwrap(); + std::fs::create_dir(dir.join("Beta")).unwrap(); + let worlds = scan_worlds(tmp.path(), "inst"); + let names: Vec<&str> = worlds.iter().map(|w| w.name.as_str()).collect(); + assert_eq!(names, vec!["alpha", "Beta", "Zeta"]); +} + +// ---------- resource packs ---------- + +#[test] +fn resource_packs_empty_dir_returns_empty() { + let tmp = tempfile::tempdir().unwrap(); + setup_subdir(tmp.path(), "inst", "resourcepacks"); + assert!(scan_resource_packs(tmp.path(), "inst").is_empty()); +} + +#[test] +fn resource_packs_missing_dir_returns_empty() { + let tmp = tempfile::tempdir().unwrap(); + assert!(scan_resource_packs(tmp.path(), "ghost").is_empty()); +} + +#[test] +fn resource_packs_finds_zips_and_dirs() { + let tmp = tempfile::tempdir().unwrap(); + let dir = setup_subdir(tmp.path(), "inst", "resourcepacks"); + std::fs::write(dir.join("pack-a.zip"), ZIP_HEADER).unwrap(); + std::fs::create_dir(dir.join("pack-b")).unwrap(); + assert_eq!(scan_resource_packs(tmp.path(), "inst").len(), 2); +} + +#[test] +fn resource_packs_disabled_variants() { + let tmp = tempfile::tempdir().unwrap(); + let dir = setup_subdir(tmp.path(), "inst", "resourcepacks"); + std::fs::write(dir.join("on.zip"), ZIP_HEADER).unwrap(); + std::fs::write(dir.join("off.zip.disabled"), ZIP_HEADER).unwrap(); + std::fs::create_dir(dir.join("diron")).unwrap(); + std::fs::create_dir(dir.join("diroff.disabled")).unwrap(); + let packs = scan_resource_packs(tmp.path(), "inst"); + assert_eq!(packs.len(), 4); + let on_zip = packs.iter().find(|p| p.file_stem == "on").unwrap(); + let off_zip = packs.iter().find(|p| p.file_stem == "off").unwrap(); + let on_dir = packs.iter().find(|p| p.file_stem == "diron").unwrap(); + let off_dir = packs.iter().find(|p| p.file_stem == "diroff").unwrap(); + assert!(on_zip.enabled); + assert!(!off_zip.enabled); + assert!(on_dir.enabled); + assert!(!off_dir.enabled); +} + +#[test] +fn resource_packs_ignores_non_pack_files() { + let tmp = tempfile::tempdir().unwrap(); + let dir = setup_subdir(tmp.path(), "inst", "resourcepacks"); + std::fs::write(dir.join("notes.txt"), "not a pack").unwrap(); + std::fs::write(dir.join("valid.zip"), ZIP_HEADER).unwrap(); + assert_eq!(scan_resource_packs(tmp.path(), "inst").len(), 1); +} diff --git a/tests/log_files.rs b/tests/log_files.rs new file mode 100644 index 0000000..6e8b8f8 --- /dev/null +++ b/tests/log_files.rs @@ -0,0 +1,76 @@ +// integration tests for the public log_files API. +// these tests touch the filesystem and exercise the module as an external +// consumer would. + +use std::path::{Path, PathBuf}; + +use rmcl::instance::log_files::{create_log_file, log_dir, read_log_file, scan_log_files}; + +fn setup_log_dir(tmp: &Path, instance: &str) -> PathBuf { + let dir = log_dir(tmp, instance); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +#[test] +fn scan_log_files_empty_dir() { + let tmp = tempfile::tempdir().unwrap(); + setup_log_dir(tmp.path(), "inst"); + let entries = scan_log_files(tmp.path(), "inst"); + assert!(entries.is_empty()); +} + +#[test] +fn scan_log_files_finds_logs() { + let tmp = tempfile::tempdir().unwrap(); + let dir = setup_log_dir(tmp.path(), "inst"); + std::fs::write(dir.join("2024-01-01_12-00-00.log"), "line1\nline2").unwrap(); + std::fs::write(dir.join("2024-01-02_12-00-00.log"), "line3").unwrap(); + let entries = scan_log_files(tmp.path(), "inst"); + assert_eq!(entries.len(), 2); + assert_eq!(entries[0].name, "2024-01-02_12-00-00.log"); + assert_eq!(entries[1].name, "2024-01-01_12-00-00.log"); +} + +#[test] +fn scan_log_files_ignores_non_log() { + let tmp = tempfile::tempdir().unwrap(); + let dir = setup_log_dir(tmp.path(), "inst"); + std::fs::write(dir.join("notes.txt"), "not a log").unwrap(); + std::fs::write(dir.join("real.log"), "log line").unwrap(); + let entries = scan_log_files(tmp.path(), "inst"); + assert_eq!(entries.len(), 1); + assert_eq!(entries[0].name, "real.log"); +} + +#[test] +fn scan_log_files_missing_dir_returns_empty() { + let tmp = tempfile::tempdir().unwrap(); + let entries = scan_log_files(tmp.path(), "ghost"); + assert!(entries.is_empty()); +} + +#[test] +fn read_log_file_returns_lines() { + let tmp = tempfile::tempdir().unwrap(); + let path = tmp.path().join("test.log"); + std::fs::write(&path, "alpha\nbeta\ngamma").unwrap(); + let lines = read_log_file(&path); + assert_eq!(lines, vec!["alpha", "beta", "gamma"]); +} + +#[test] +fn read_log_file_missing_returns_empty() { + let lines = read_log_file(Path::new("/nonexistent/test.log")); + assert!(lines.is_empty()); +} + +#[test] +fn create_log_file_creates_path() { + let tmp = tempfile::tempdir().unwrap(); + let path = create_log_file(tmp.path(), "inst"); + assert!(path.is_some()); + let path = path.unwrap(); + assert!(path.to_string_lossy().ends_with(".log")); + assert!(path.parent().unwrap().exists()); +} diff --git a/tests/screenshots.rs b/tests/screenshots.rs new file mode 100644 index 0000000..699c104 --- /dev/null +++ b/tests/screenshots.rs @@ -0,0 +1,85 @@ +// integration tests for the public scan_screenshots API. + +use std::path::{Path, PathBuf}; + +use rmcl::instance::screenshots::scan_screenshots; + +fn setup_screenshots_dir(tmp: &Path, instance: &str) -> PathBuf { + let dir = tmp.join(instance).join(".minecraft").join("screenshots"); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +fn tiny_png() -> Vec { + let img = image::RgbImage::from_pixel(1, 1, image::Rgb([255, 255, 255])); + let mut buf = std::io::Cursor::new(Vec::new()); + img.write_to(&mut buf, image::ImageFormat::Png).unwrap(); + buf.into_inner() +} + +#[test] +fn scan_screenshots_empty_dir() { + let tmp = tempfile::tempdir().unwrap(); + setup_screenshots_dir(tmp.path(), "inst"); + let screenshots = scan_screenshots(tmp.path(), "inst"); + assert!(screenshots.is_empty()); +} + +#[test] +fn scan_screenshots_missing_dir_returns_empty() { + let tmp = tempfile::tempdir().unwrap(); + let screenshots = scan_screenshots(tmp.path(), "ghost"); + assert!(screenshots.is_empty()); +} + +#[test] +fn scan_screenshots_finds_images() { + let tmp = tempfile::tempdir().unwrap(); + let dir = setup_screenshots_dir(tmp.path(), "inst"); + std::fs::write(dir.join("2024-01-01.png"), tiny_png()).unwrap(); + std::fs::write(dir.join("2024-01-02.png"), tiny_png()).unwrap(); + let screenshots = scan_screenshots(tmp.path(), "inst"); + assert_eq!(screenshots.len(), 2); +} + +#[test] +fn scan_screenshots_ignores_non_images() { + let tmp = tempfile::tempdir().unwrap(); + let dir = setup_screenshots_dir(tmp.path(), "inst"); + std::fs::write(dir.join("pic.png"), tiny_png()).unwrap(); + std::fs::write(dir.join("notes.txt"), "not an image").unwrap(); + let screenshots = scan_screenshots(tmp.path(), "inst"); + assert_eq!(screenshots.len(), 1); +} + +#[test] +fn scan_screenshots_sorted_newest_first() { + let tmp = tempfile::tempdir().unwrap(); + let dir = setup_screenshots_dir(tmp.path(), "inst"); + std::fs::write(dir.join("aaa.png"), tiny_png()).unwrap(); + std::fs::write(dir.join("zzz.png"), tiny_png()).unwrap(); + let screenshots = scan_screenshots(tmp.path(), "inst"); + assert_eq!(screenshots[0].name, "zzz.png"); + assert_eq!(screenshots[1].name, "aaa.png"); +} + +#[test] +fn scan_screenshots_reads_dimensions() { + let tmp = tempfile::tempdir().unwrap(); + let dir = setup_screenshots_dir(tmp.path(), "inst"); + std::fs::write(dir.join("shot.png"), tiny_png()).unwrap(); + let screenshots = scan_screenshots(tmp.path(), "inst"); + assert_eq!(screenshots[0].width, 1); + assert_eq!(screenshots[0].height, 1); +} + +#[test] +fn scan_screenshots_bad_image_uses_default_dimensions() { + let tmp = tempfile::tempdir().unwrap(); + let dir = setup_screenshots_dir(tmp.path(), "inst"); + std::fs::write(dir.join("corrupt.png"), b"not a real png").unwrap(); + let screenshots = scan_screenshots(tmp.path(), "inst"); + assert_eq!(screenshots.len(), 1); + assert_eq!(screenshots[0].width, 1920); + assert_eq!(screenshots[0].height, 1080); +} From d2e08d818b76540993dbf00e4b2bb5b6a440516a Mon Sep 17 00:00:00 2001 From: objz Date: Tue, 26 May 2026 21:38:17 +0200 Subject: [PATCH 09/20] added: launch-pipeline integration tests via build_launch_invocation seam Phase D of the test overhaul. Extracts a build_launch_invocation seam from launch() so the full launch pipeline (profile loading, inheritsFrom resolution, classpath assembly, template rendering) can be exercised without spawning a real java process or hitting the auth servers. The seam takes resolved auth credentials (LaunchAuth) and returns a LaunchInvocation struct with the final java path, jvm args, classpath, main class, extra args, game args, and working dir. launch() shrinks to a thin wrapper that resolves auth from the account store, calls the seam, and spawns the process. tests/launch_pipeline.rs adds 14 integration tests covering: vanilla modern args; vanilla legacy minecraftArguments; Forge with --add-opens; Forge local-libs preference; Fabric implicit inheritsFrom resolution; NeoForge inheritsFrom; auth credential substitution into game args; version_type substitution; platform classpath separator; rule-disallowed library exclusion; Xms/Xmx from config; default memory fallback; missing meta.json error; missing loader profile error. --- src/instance/launch/mod.rs | 215 ++++++++----- tests/content_scanners.rs | 5 - tests/launch_pipeline.rs | 604 +++++++++++++++++++++++++++++++++++++ 3 files changed, 739 insertions(+), 85 deletions(-) create mode 100644 tests/launch_pipeline.rs diff --git a/src/instance/launch/mod.rs b/src/instance/launch/mod.rs index ba9086c..8a110db 100644 --- a/src/instance/launch/mod.rs +++ b/src/instance/launch/mod.rs @@ -202,13 +202,45 @@ async fn migrate_legacy_loader_profile_if_needed( Ok(Some(refreshed)) } -pub async fn launch( +// resolved auth credentials passed into the launch-invocation builder. +// keeping these as borrowed strs lets callers pass owned strings or string +// slices without forcing allocation. +#[derive(Debug, Clone)] +pub struct LaunchAuth<'a> { + pub username: &'a str, + pub uuid: &'a str, + pub token: &'a str, + // "msa" for Microsoft, "legacy" for offline; mirrors Mojang's user_type. + pub user_type: &'a str, +} + +// everything the spawner needs to construct the java command. assembled by +// build_launch_invocation, consumed by launch(). exposed so integration tests +// can assert on the rendered invocation without spawning a real process. +#[derive(Debug, Clone)] +pub struct LaunchInvocation { + pub java: String, + pub jvm_args: Vec, + pub classpath: Vec, + pub classpath_string: String, + pub main_class: String, + pub extra_args: Vec, + pub game_args: Vec, + pub working_dir: PathBuf, +} + +// builds a fully-resolved java invocation for the given instance. reads +// meta.json and the loader profile from disk, migrates legacy formats if +// needed (may hit Mojang to refetch), resolves inheritsFrom, applies +// loader-specific patches, and renders all template arguments. all I/O +// except auth resolution and process spawning happens here. +pub async fn build_launch_invocation( config: &InstanceConfig, instances_dir: &Path, meta_dir: &Path, -) -> Result<(), LaunchError> { - let name = config.name.clone(); - let instance_dir = instances_dir.join(&name); + auth: &LaunchAuth<'_>, +) -> Result { + let instance_dir = instances_dir.join(&config.name); let minecraft_dir = instance_dir.join(".minecraft"); let meta_path = meta_dir @@ -374,63 +406,6 @@ pub async fn launch( }) .unwrap_or_else(crate::net::detect_java_path); - // resolve auth credentials, refreshing the microsoft token if needed. - let mut account_store = crate::auth::AccountStore::load(); - let (mc_username, mc_uuid, mc_token, mc_user_type) = match account_store - .active_account() - .cloned() - { - Some(acc) => { - // offline accounts can only launch if a microsoft account exists - // (proves the user owns minecraft). - if acc.account_type != AccountType::Microsoft && !account_store.has_microsoft_account() - { - return Err(LaunchError::Auth( - "Offline accounts require a Microsoft account that owns Minecraft".to_owned(), - )); - } - let (token, new_refresh, new_expires) = match acc.account_type { - AccountType::Microsoft => match crate::auth::refresh_and_get_token(&acc).await { - Ok(triple) => triple, - Err(e) => { - return Err(LaunchError::Auth(format!("Authentication failed: {e}"))); - } - }, - AccountType::Offline => ("0".to_string(), None, None), - }; - if let Some(stored) = account_store - .accounts - .iter_mut() - .find(|a| a.uuid == acc.uuid) - { - let mut changed = false; - if let Some(new_rt) = new_refresh { - stored.refresh_token = Some(new_rt); - changed = true; - } - if let Some(expires) = new_expires { - stored.cached_mc_token = Some(token.clone()); - stored.cached_mc_token_expires_at = Some(expires); - changed = true; - } - if changed { - account_store.save(); - } - } - let user_type = match acc.account_type { - AccountType::Microsoft => "msa", - AccountType::Offline => "legacy", - }; - ( - acc.username.clone(), - acc.uuid.clone(), - token, - user_type.to_string(), - ) - } - None => return Err(LaunchError::Auth("No account selected".to_owned())), - }; - let assets_root = meta_dir.join("assets"); let natives_dir = meta_dir .join("versions") @@ -447,11 +422,11 @@ pub async fn launch( game_directory: &minecraft_dir, assets_root: &assets_root, assets_index_name: &asset_index_id, - auth_player_name: &mc_username, - auth_uuid: &mc_uuid, - auth_access_token: &mc_token, + auth_player_name: auth.username, + auth_uuid: auth.uuid, + auth_access_token: auth.token, auth_xuid: "0", - user_type: &mc_user_type, + user_type: auth.user_type, user_properties: "{}", launcher_name: "rmcl", launcher_version: env!("CARGO_PKG_VERSION"), @@ -461,13 +436,92 @@ pub async fn launch( let (upstream_jvm_args, game_args) = build_game_args(&merged_profile, &rule_ctx, &template_ctx)?; - let mut jvm: Vec = vec![ + let mut jvm_args: Vec = vec![ format!("-Xms{}", config.memory_min.as_deref().unwrap_or("512M")), format!("-Xmx{}", config.memory_max.as_deref().unwrap_or("2G")), ]; - jvm.extend(patch_jvm_args); - jvm.extend(upstream_jvm_args); - jvm.extend(config.jvm_args.clone()); + jvm_args.extend(patch_jvm_args); + jvm_args.extend(upstream_jvm_args); + jvm_args.extend(config.jvm_args.clone()); + + Ok(LaunchInvocation { + java, + jvm_args, + classpath, + classpath_string: cp_str, + main_class, + extra_args, + game_args, + working_dir: minecraft_dir, + }) +} + +// resolves auth credentials, then builds the launch invocation and spawns +// the java process. only thin wrapper logic lives here: token refresh, +// process spawn, child supervision. all the heavy lifting (profile loading, +// classpath assembly, template rendering) sits behind build_launch_invocation. +pub async fn launch( + config: &InstanceConfig, + instances_dir: &Path, + meta_dir: &Path, +) -> Result<(), LaunchError> { + let name = config.name.clone(); + + // resolve auth credentials, refreshing the microsoft token if needed. + let mut account_store = crate::auth::AccountStore::load(); + let Some(acc) = account_store.active_account().cloned() else { + return Err(LaunchError::Auth("No account selected".to_owned())); + }; + + // offline accounts can only launch if a microsoft account exists + // (proves the user owns minecraft). + if acc.account_type != AccountType::Microsoft && !account_store.has_microsoft_account() { + return Err(LaunchError::Auth( + "Offline accounts require a Microsoft account that owns Minecraft".to_owned(), + )); + } + + let (token, new_refresh, new_expires) = match acc.account_type { + AccountType::Microsoft => match crate::auth::refresh_and_get_token(&acc).await { + Ok(triple) => triple, + Err(e) => return Err(LaunchError::Auth(format!("Authentication failed: {e}"))), + }, + AccountType::Offline => ("0".to_string(), None, None), + }; + + if let Some(stored) = account_store + .accounts + .iter_mut() + .find(|a| a.uuid == acc.uuid) + { + let mut changed = false; + if let Some(new_rt) = new_refresh { + stored.refresh_token = Some(new_rt); + changed = true; + } + if let Some(expires) = new_expires { + stored.cached_mc_token = Some(token.clone()); + stored.cached_mc_token_expires_at = Some(expires); + changed = true; + } + if changed { + account_store.save(); + } + } + + let user_type = match acc.account_type { + AccountType::Microsoft => "msa", + AccountType::Offline => "legacy", + }; + + let auth = LaunchAuth { + username: &acc.username, + uuid: &acc.uuid, + token: &token, + user_type, + }; + + let invocation = build_launch_invocation(config, instances_dir, meta_dir, &auth).await?; let (kill_tx, kill_rx) = tokio::sync::oneshot::channel::<()>(); crate::running::register_kill(&name, kill_tx); @@ -479,26 +533,27 @@ pub async fn launch( config.loader ); - tracing::info!("[{}] Java: {}", name, java); - tracing::info!("[{}] JVM args: {:?}", name, jvm); + tracing::info!("[{}] Java: {}", name, invocation.java); + tracing::info!("[{}] JVM args: {:?}", name, invocation.jvm_args); tracing::info!( "[{}] Classpath:\n{}", name, - classpath + invocation + .classpath .iter() .map(|p| p.display().to_string()) .collect::>() .join("\n") ); - tracing::info!("[{}] Main class: {}", name, main_class); + tracing::info!("[{}] Main class: {}", name, invocation.main_class); - let mut cmd = tokio::process::Command::new(&java); - cmd.args(&jvm); - cmd.arg("-cp").arg(&cp_str); - cmd.arg(&main_class); - cmd.args(&extra_args); - cmd.args(&game_args); - cmd.current_dir(&minecraft_dir); + let mut cmd = tokio::process::Command::new(&invocation.java); + cmd.args(&invocation.jvm_args); + cmd.arg("-cp").arg(&invocation.classpath_string); + cmd.arg(&invocation.main_class); + cmd.args(&invocation.extra_args); + cmd.args(&invocation.game_args); + cmd.current_dir(&invocation.working_dir); cmd.stdout(std::process::Stdio::piped()); cmd.stderr(std::process::Stdio::piped()); diff --git a/tests/content_scanners.rs b/tests/content_scanners.rs index aa4dd80..6f2df0b 100644 --- a/tests/content_scanners.rs +++ b/tests/content_scanners.rs @@ -19,8 +19,6 @@ fn setup_subdir(tmp: &Path, instance: &str, sub: &str) -> PathBuf { // without panicking even though it can't actually unpack metadata. const ZIP_HEADER: &[u8] = b"PK\x03\x04"; -// ---------- shaders ---------- - #[test] fn shaders_empty_dir_returns_empty() { let tmp = tempfile::tempdir().unwrap(); @@ -68,7 +66,6 @@ fn shaders_ignores_non_shader_files() { assert_eq!(scan_shaders(tmp.path(), "inst").len(), 1); } -// ---------- worlds ---------- // worlds are always directories (no zip form), so the test shape differs. #[test] @@ -133,8 +130,6 @@ fn worlds_sorted_case_insensitive() { assert_eq!(names, vec!["alpha", "Beta", "Zeta"]); } -// ---------- resource packs ---------- - #[test] fn resource_packs_empty_dir_returns_empty() { let tmp = tempfile::tempdir().unwrap(); diff --git a/tests/launch_pipeline.rs b/tests/launch_pipeline.rs new file mode 100644 index 0000000..f31fe14 --- /dev/null +++ b/tests/launch_pipeline.rs @@ -0,0 +1,604 @@ +// integration tests for build_launch_invocation - the seam that takes an +// instance config plus resolved auth credentials and returns the full java +// invocation that would be spawned. these tests build the expected on-disk +// fixture layout in a tempdir, call the seam, and assert on the rendered +// LaunchInvocation. nothing here actually spawns a process. + +use std::path::PathBuf; + +use chrono::Utc; +use serde_json::json; +use tempfile::TempDir; + +use rmcl::instance::launch::{LaunchAuth, LaunchError, build_launch_invocation}; +use rmcl::instance::models::{InstanceConfig, ModLoader}; + +// ---------- helpers ---------- + +const PLAYER: &str = "TestPlayer"; +const PLAYER_UUID: &str = "00000000-0000-0000-0000-000000000001"; +const PLAYER_TOKEN: &str = "secret-access-token"; + +fn test_auth() -> LaunchAuth<'static> { + LaunchAuth { + username: PLAYER, + uuid: PLAYER_UUID, + token: PLAYER_TOKEN, + user_type: "msa", + } +} + +fn make_config(name: &str, game_version: &str, loader: ModLoader) -> InstanceConfig { + make_config_with(name, game_version, loader, None) +} + +fn make_config_with( + name: &str, + game_version: &str, + loader: ModLoader, + loader_version: Option<&str>, +) -> InstanceConfig { + InstanceConfig { + name: name.into(), + game_version: game_version.into(), + loader, + loader_version: loader_version.map(str::to_owned), + created: Utc::now(), + last_played: None, + // pinned to a deterministic value so detect_java_path is never + // invoked and tests don't depend on the host's java install. + java_path: Some("/usr/bin/java-test".into()), + memory_max: None, + memory_min: None, + jvm_args: Vec::new(), + resolution: None, + } +} + +// builds the on-disk layout that build_launch_invocation expects: +// /instances//.minecraft/ (instance dir, created empty) +// /meta/versions//meta.json +// /meta/loader-profiles/ (created empty) +// /meta/libraries/ (created empty) +struct Fixture { + _tmp: TempDir, + instances_dir: PathBuf, + meta_dir: PathBuf, +} + +impl Fixture { + fn new(instance_name: &str, game_version: &str, vanilla_meta: serde_json::Value) -> Self { + let tmp = tempfile::tempdir().unwrap(); + let instances_dir = tmp.path().join("instances"); + let meta_dir = tmp.path().join("meta"); + + let instance_minecraft = instances_dir.join(instance_name).join(".minecraft"); + std::fs::create_dir_all(&instance_minecraft).unwrap(); + + std::fs::create_dir_all(meta_dir.join("libraries")).unwrap(); + std::fs::create_dir_all(meta_dir.join("loader-profiles")).unwrap(); + let version_dir = meta_dir.join("versions").join(game_version); + std::fs::create_dir_all(&version_dir).unwrap(); + std::fs::write( + version_dir.join("meta.json"), + serde_json::to_vec_pretty(&vanilla_meta).unwrap(), + ) + .unwrap(); + + Self { + _tmp: tmp, + instances_dir, + meta_dir, + } + } + + fn write_loader_profile(&self, filename: &str, content: serde_json::Value) { + std::fs::write( + self.meta_dir.join("loader-profiles").join(filename), + serde_json::to_vec_pretty(&content).unwrap(), + ) + .unwrap(); + } + + fn instance_libraries_dir(&self, instance_name: &str) -> PathBuf { + self.instances_dir + .join(instance_name) + .join(".minecraft") + .join("libraries") + } +} + +fn modern_vanilla_meta(id: &str) -> serde_json::Value { + json!({ + "id": id, + "type": "release", + "mainClass": "net.minecraft.client.main.Main", + "assetIndex": { + "id": "5", + "url": "https://example.com/assets/index.json", + "sha1": "0000000000000000000000000000000000000000" + }, + "libraries": [ + { + "name": "org.slf4j:slf4j-api:2.0.7", + "downloads": { + "artifact": { + "url": "https://example.com/slf4j.jar", + "path": "org/slf4j/slf4j-api/2.0.7/slf4j-api-2.0.7.jar", + "sha1": "0000000000000000000000000000000000000000", + "size": 0 + } + } + } + ], + "arguments": { + "game": [ + "--username", "${auth_player_name}", + "--version", "${version_name}", + "--uuid", "${auth_uuid}", + "--accessToken", "${auth_access_token}", + "--userType", "${user_type}", + "--versionType", "${version_type}" + ], + "jvm": [ + "-Djava.library.path=${natives_directory}", + "-Dminecraft.launcher.brand=${launcher_name}" + ] + } + }) +} + +fn legacy_vanilla_meta(id: &str) -> serde_json::Value { + json!({ + "id": id, + "type": "release", + "mainClass": "net.minecraft.launchwrapper.Launch", + "assetIndex": { + "id": "1.7.10", + "url": "https://example.com/assets/index.json", + "sha1": "0000000000000000000000000000000000000000" + }, + "libraries": [], + "minecraftArguments": "--username ${auth_player_name} --uuid ${auth_uuid} --accessToken ${auth_access_token} --userType ${user_type}" + }) +} + +fn platform_classpath_sep() -> &'static str { + if cfg!(windows) { ";" } else { ":" } +} + +// ---------- vanilla ---------- + +#[tokio::test] +async fn vanilla_modern_builds_complete_invocation() { + let fx = Fixture::new("v1", "1.20.1", modern_vanilla_meta("1.20.1")); + let config = make_config("v1", "1.20.1", ModLoader::Vanilla); + + let inv = build_launch_invocation(&config, &fx.instances_dir, &fx.meta_dir, &test_auth()) + .await + .unwrap(); + + assert_eq!(inv.java, "/usr/bin/java-test"); + assert_eq!(inv.main_class, "net.minecraft.client.main.Main"); + assert!(inv.extra_args.is_empty()); + + let expected_natives = fx + .meta_dir + .join("versions") + .join("1.20.1") + .join("natives"); + assert!( + inv.jvm_args.iter().any(|a| a + == &format!("-Djava.library.path={}", expected_natives.display())), + "jvm_args missing natives substitution: {:?}", + inv.jvm_args + ); + assert!( + inv.jvm_args + .iter() + .any(|a| a == "-Dminecraft.launcher.brand=rmcl"), + "jvm_args missing launcher brand: {:?}", + inv.jvm_args + ); + + // working_dir is //.minecraft + assert_eq!( + inv.working_dir, + fx.instances_dir.join("v1").join(".minecraft") + ); + // classpath = the one vanilla lib + the vanilla client jar + let slf4j = fx + .meta_dir + .join("libraries/org/slf4j/slf4j-api/2.0.7/slf4j-api-2.0.7.jar"); + let client_jar = fx.meta_dir.join("versions/1.20.1/1.20.1.jar"); + assert!(inv.classpath.contains(&slf4j)); + assert!(inv.classpath.contains(&client_jar)); +} + +#[tokio::test] +async fn vanilla_legacy_args_format_substitutes_tokens() { + let fx = Fixture::new("vlegacy", "1.7.10", legacy_vanilla_meta("1.7.10")); + let config = make_config("vlegacy", "1.7.10", ModLoader::Vanilla); + + let inv = build_launch_invocation(&config, &fx.instances_dir, &fx.meta_dir, &test_auth()) + .await + .unwrap(); + + assert_eq!(inv.main_class, "net.minecraft.launchwrapper.Launch"); + + // legacy format has no upstream jvm args; jvm_args should be just Xms/Xmx + assert_eq!(inv.jvm_args.len(), 2); + assert!(inv.jvm_args[0].starts_with("-Xms")); + assert!(inv.jvm_args[1].starts_with("-Xmx")); + + // game_args should be space-split with substitutions applied + let joined = inv.game_args.join(" "); + assert!(joined.contains(&format!("--username {}", PLAYER))); + assert!(joined.contains(&format!("--uuid {}", PLAYER_UUID))); + assert!(joined.contains(&format!("--accessToken {}", PLAYER_TOKEN))); + assert!(joined.contains("--userType msa")); +} + +// ---------- forge ---------- + +#[tokio::test] +async fn forge_modern_includes_add_opens() { + let fx = Fixture::new("f1", "1.20.1", modern_vanilla_meta("1.20.1")); + fx.write_loader_profile( + "forge-1.20.1-47.2.0.json", + json!({ + "id": "1.20.1-forge-47.2.0", + "inheritsFrom": "1.20.1", + "type": "release", + "mainClass": "cpw.mods.bootstraplauncher.BootstrapLauncher", + "libraries": [ + { "name": "net.minecraftforge:fmlloader:1.20.1-47.2.0" } + ], + "arguments": { + "game": ["--launchTarget", "forge_client"], + "jvm": [ + "--add-opens", + "java.base/sun.security.util=ALL-UNNAMED", + "-DignoreList=bootstraplauncher,securejarhandler" + ] + } + }), + ); + let config = make_config_with("f1", "1.20.1", ModLoader::Forge, Some("47.2.0")); + + let inv = build_launch_invocation(&config, &fx.instances_dir, &fx.meta_dir, &test_auth()) + .await + .unwrap(); + + assert_eq!(inv.main_class, "cpw.mods.bootstraplauncher.BootstrapLauncher"); + assert!( + inv.jvm_args.iter().any(|a| a == "--add-opens"), + "Forge --add-opens missing: {:?}", + inv.jvm_args + ); + assert!( + inv.jvm_args + .iter() + .any(|a| a == "java.base/sun.security.util=ALL-UNNAMED"), + "Forge --add-opens target missing: {:?}", + inv.jvm_args + ); + assert!( + inv.game_args + .windows(2) + .any(|w| w == ["--launchTarget", "forge_client"]), + "Forge launchTarget missing from game_args: {:?}", + inv.game_args + ); +} + +#[tokio::test] +async fn forge_local_lib_dir_preferred_over_meta_dir() { + let fx = Fixture::new("f2", "1.20.1", modern_vanilla_meta("1.20.1")); + fx.write_loader_profile( + "forge-1.20.1-47.2.0.json", + json!({ + "id": "1.20.1-forge-47.2.0", + "inheritsFrom": "1.20.1", + "type": "release", + "mainClass": "cpw.mods.bootstraplauncher.BootstrapLauncher", + "libraries": [ + { "name": "net.minecraftforge:fmlloader:1.20.1-47.2.0" } + ], + "arguments": { "game": [], "jvm": [] } + }), + ); + + // drop fmlloader into the instance-local libraries dir so the launcher + // finds it there rather than under the shared meta cache. + let local_lib = + fx.instance_libraries_dir("f2") + .join("net/minecraftforge/fmlloader/1.20.1-47.2.0"); + std::fs::create_dir_all(&local_lib).unwrap(); + let local_jar = local_lib.join("fmlloader-1.20.1-47.2.0.jar"); + std::fs::write(&local_jar, b"jar").unwrap(); + + let config = make_config_with("f2", "1.20.1", ModLoader::Forge, Some("47.2.0")); + let inv = build_launch_invocation(&config, &fx.instances_dir, &fx.meta_dir, &test_auth()) + .await + .unwrap(); + + assert!( + inv.classpath.contains(&local_jar), + "expected local fmlloader on classpath: {:?}", + inv.classpath + ); + // and the meta-dir candidate should not appear + let meta_candidate = fx + .meta_dir + .join("libraries/net/minecraftforge/fmlloader/1.20.1-47.2.0/fmlloader-1.20.1-47.2.0.jar"); + assert!( + !inv.classpath.contains(&meta_candidate), + "meta-dir candidate should not be on classpath when local exists" + ); +} + +// ---------- fabric ---------- + +#[tokio::test] +async fn fabric_implicit_inheritsfrom_resolves() { + let fx = Fixture::new("fab", "1.20.1", modern_vanilla_meta("1.20.1")); + // Fabric upstream profiles omit inheritsFrom; the launch flow patches it + // in before resolving. assert that the merge picks up Fabric's main class. + fx.write_loader_profile( + "fabric-1.20.1-0.15.0.json", + json!({ + "id": "fabric-loader-0.15.0-1.20.1", + "type": "release", + "mainClass": "net.fabricmc.loader.impl.launch.knot.KnotClient", + "libraries": [ + { "name": "net.fabricmc:fabric-loader:0.15.0" } + ] + }), + ); + let config = make_config_with("fab", "1.20.1", ModLoader::Fabric, Some("0.15.0")); + + let inv = build_launch_invocation(&config, &fx.instances_dir, &fx.meta_dir, &test_auth()) + .await + .unwrap(); + + assert_eq!( + inv.main_class, + "net.fabricmc.loader.impl.launch.knot.KnotClient" + ); + // both fabric-loader and vanilla slf4j must appear on the merged classpath + let fabric_loader = fx + .meta_dir + .join("libraries/net/fabricmc/fabric-loader/0.15.0/fabric-loader-0.15.0.jar"); + let slf4j = fx + .meta_dir + .join("libraries/org/slf4j/slf4j-api/2.0.7/slf4j-api-2.0.7.jar"); + assert!( + inv.classpath.contains(&fabric_loader), + "fabric-loader missing from classpath: {:?}", + inv.classpath + ); + assert!( + inv.classpath.contains(&slf4j), + "vanilla slf4j missing from classpath: {:?}", + inv.classpath + ); +} + +// ---------- neoforge ---------- + +#[tokio::test] +async fn neoforge_inheritsfrom_resolves() { + let fx = Fixture::new("ne", "1.20.6", modern_vanilla_meta("1.20.6")); + fx.write_loader_profile( + "neoforge-20.4.190.json", + json!({ + "id": "neoforge-20.4.190", + "inheritsFrom": "1.20.6", + "type": "release", + "mainClass": "cpw.mods.bootstraplauncher.BootstrapLauncher", + "libraries": [ + { "name": "net.neoforged:neoforge:20.4.190" } + ], + "arguments": { + "game": [], + "jvm": ["--add-modules", "ALL-MODULE-PATH"] + } + }), + ); + let config = make_config_with("ne", "1.20.6", ModLoader::NeoForge, Some("20.4.190")); + + let inv = build_launch_invocation(&config, &fx.instances_dir, &fx.meta_dir, &test_auth()) + .await + .unwrap(); + + assert_eq!(inv.main_class, "cpw.mods.bootstraplauncher.BootstrapLauncher"); + assert!( + inv.jvm_args + .windows(2) + .any(|w| w == ["--add-modules", "ALL-MODULE-PATH"]), + "NeoForge --add-modules missing: {:?}", + inv.jvm_args + ); +} + +// ---------- template substitution ---------- + +#[tokio::test] +async fn auth_credentials_substituted_in_game_args() { + let fx = Fixture::new("auth", "1.20.1", modern_vanilla_meta("1.20.1")); + let config = make_config("auth", "1.20.1", ModLoader::Vanilla); + + let inv = build_launch_invocation(&config, &fx.instances_dir, &fx.meta_dir, &test_auth()) + .await + .unwrap(); + + assert!( + inv.game_args.iter().any(|a| a == PLAYER), + "auth_player_name not substituted: {:?}", + inv.game_args + ); + assert!( + inv.game_args.iter().any(|a| a == PLAYER_UUID), + "auth_uuid not substituted: {:?}", + inv.game_args + ); + assert!( + inv.game_args.iter().any(|a| a == PLAYER_TOKEN), + "auth_access_token not substituted: {:?}", + inv.game_args + ); + assert!( + inv.game_args.iter().any(|a| a == "msa"), + "user_type not substituted: {:?}", + inv.game_args + ); +} + +#[tokio::test] +async fn version_type_substituted() { + // type = "snapshot" in the fixture; ${version_type} should render that + let mut meta = modern_vanilla_meta("1.20.1"); + meta["type"] = json!("snapshot"); + let fx = Fixture::new("vt", "1.20.1", meta); + let config = make_config("vt", "1.20.1", ModLoader::Vanilla); + + let inv = build_launch_invocation(&config, &fx.instances_dir, &fx.meta_dir, &test_auth()) + .await + .unwrap(); + + assert!( + inv.game_args.iter().any(|a| a == "snapshot"), + "version_type not substituted to 'snapshot': {:?}", + inv.game_args + ); +} + +// ---------- classpath ---------- + +#[tokio::test] +async fn classpath_uses_platform_separator() { + let fx = Fixture::new("cp", "1.20.1", modern_vanilla_meta("1.20.1")); + let config = make_config("cp", "1.20.1", ModLoader::Vanilla); + + let inv = build_launch_invocation(&config, &fx.instances_dir, &fx.meta_dir, &test_auth()) + .await + .unwrap(); + + // with two classpath entries we should see exactly one separator + assert_eq!(inv.classpath.len(), 2); + let sep = platform_classpath_sep(); + assert_eq!(inv.classpath_string.matches(sep).count(), 1); +} + +#[tokio::test] +async fn rule_disallow_excludes_library() { + // a library whose rule always denies must not appear on the classpath + let mut meta = modern_vanilla_meta("1.20.1"); + meta["libraries"] = json!([ + { + "name": "org.slf4j:slf4j-api:2.0.7", + "downloads": { + "artifact": { + "url": "", + "path": "org/slf4j/slf4j-api/2.0.7/slf4j-api-2.0.7.jar", + "sha1": "0000000000000000000000000000000000000000", + "size": 0 + } + } + }, + { + "name": "com.denied:lib:1.0", + "rules": [{ "action": "disallow" }], + "downloads": { + "artifact": { + "url": "", + "path": "com/denied/lib/1.0/lib-1.0.jar", + "sha1": "0000000000000000000000000000000000000000", + "size": 0 + } + } + } + ]); + let fx = Fixture::new("rule", "1.20.1", meta); + let config = make_config("rule", "1.20.1", ModLoader::Vanilla); + + let inv = build_launch_invocation(&config, &fx.instances_dir, &fx.meta_dir, &test_auth()) + .await + .unwrap(); + + let denied = fx + .meta_dir + .join("libraries/com/denied/lib/1.0/lib-1.0.jar"); + assert!( + !inv.classpath.contains(&denied), + "denied library was included: {:?}", + inv.classpath + ); +} + +// ---------- memory ---------- + +#[tokio::test] +async fn xms_xmx_use_config_memory() { + let fx = Fixture::new("mem", "1.20.1", modern_vanilla_meta("1.20.1")); + let mut config = make_config("mem", "1.20.1", ModLoader::Vanilla); + config.memory_min = Some("1G".into()); + config.memory_max = Some("4G".into()); + + let inv = build_launch_invocation(&config, &fx.instances_dir, &fx.meta_dir, &test_auth()) + .await + .unwrap(); + + assert!(inv.jvm_args.iter().any(|a| a == "-Xms1G")); + assert!(inv.jvm_args.iter().any(|a| a == "-Xmx4G")); +} + +#[tokio::test] +async fn default_memory_used_when_unset() { + let fx = Fixture::new("memdef", "1.20.1", modern_vanilla_meta("1.20.1")); + let config = make_config("memdef", "1.20.1", ModLoader::Vanilla); + // memory_min and memory_max default to None in make_config + + let inv = build_launch_invocation(&config, &fx.instances_dir, &fx.meta_dir, &test_auth()) + .await + .unwrap(); + + assert!(inv.jvm_args.iter().any(|a| a == "-Xms512M")); + assert!(inv.jvm_args.iter().any(|a| a == "-Xmx2G")); +} + +// ---------- error paths ---------- + +#[tokio::test] +async fn meta_not_found_returns_error() { + let tmp = tempfile::tempdir().unwrap(); + let instances_dir = tmp.path().join("instances"); + let meta_dir = tmp.path().join("meta"); + std::fs::create_dir_all(instances_dir.join("ghost").join(".minecraft")).unwrap(); + std::fs::create_dir_all(meta_dir.join("versions")).unwrap(); + + let config = make_config("ghost", "1.20.1", ModLoader::Vanilla); + let err = build_launch_invocation(&config, &instances_dir, &meta_dir, &test_auth()) + .await + .unwrap_err(); + assert!( + matches!(err, LaunchError::MetaNotFound(_)), + "expected MetaNotFound, got: {err:?}" + ); +} + +#[tokio::test] +async fn loader_profile_missing_returns_error() { + let fx = Fixture::new("lpmiss", "1.20.1", modern_vanilla_meta("1.20.1")); + let config = make_config_with("lpmiss", "1.20.1", ModLoader::Fabric, Some("0.15.0")); + + let err = build_launch_invocation(&config, &fx.instances_dir, &fx.meta_dir, &test_auth()) + .await + .unwrap_err(); + assert!( + matches!(err, LaunchError::MetaNotFound(_)), + "expected MetaNotFound for missing loader profile, got: {err:?}" + ); +} + From 7a9dfa850dea6b8e7745f9307e88e796c5a508db Mon Sep 17 00:00:00 2001 From: objz Date: Wed, 27 May 2026 16:43:47 +0200 Subject: [PATCH 10/20] refactored: rework weak unit tests to catch real regressions Audit found 9 confirmed-weak unit tests plus several newly-found ones that asserted things equivalent to themselves, returned vacuous truth, or had assertions guarded behind conditionals that silently swallowed failure. Changes by file: - auth/accounts.rs: create_offline_account_fields now pins the uuid to offline_uuid("TestPlayer") instead of !is_empty(); mutating the uuid derivation would fail this now. - cli/mod.rs: parses_instance_list_subcommand drills into the list subcommand under instance rather than only verifying the instance group exists. - config/theme.rs: border_style_roundtrip is now an rstest covering all four BorderStyle variants; mutating any non-Double arm is caught. - instance/desktop.rs: removed desktop_path_returns_some (assertion was gated behind if let Some so could pass when the function returned None); build_content_linux* already covers the real behaviour. - instance/launch/mod.rs: removed five predicate-only tests that asserted serde defaulting on LaunchProfile rather than invoking the migration predicate. Added two tests that actually call migrate_legacy_meta_if_needed (rstest over modern/legacy arg shapes) and migrate_legacy_loader_profile_if_needed (modern-with-inheritsFrom early-return). Renamed build_game_args_renders_upstream_arguments, dropping the misleading "and appends loader args" clause that the test never covered. - instance/loader/mod.rs: removed test_vanilla_install_noop (no assertion at all) and test_vanilla_get_versions (asserted a hardcoded Ok(vec!["vanilla"]) return). Replaced test_vanilla_factory with an rstest covering all five ModLoader variants; a misordered match arm in get_installer is caught. - migrate.rs: removed cleanup_instance_leftovers_handles_missing_dir (had no assertions and was redundant with cleanup_instance_leftovers_removes_shim_and_log4j). - net/mod.rs: removed detect_java_falls_back_to_java which asserted !is_empty() against a function whose worst-case fallback is the literal string "java"; structurally uncatchable. - tui/error_buffer.rs: peek_all_returns_newest_first and auto_assigned_ids_are_unique now tag their pushed events with a unique substring and filter peek_all_errors to just those, so the assertions actually fire instead of being silently skipped via if all.len() >= 2 when shared static state interfered. Total: net zero change in test count (deletions and parameterised replacements roughly balance), but mutation coverage of the surviving suite is materially stronger. --- src/auth/accounts.rs | 5 +- src/cli/mod.rs | 9 ++- src/config/theme.rs | 13 ++-- src/instance/desktop.rs | 9 --- src/instance/launch/mod.rs | 121 +++++++++++++++++++------------------ src/instance/loader/mod.rs | 37 ++++-------- src/migrate.rs | 6 -- src/net/mod.rs | 5 -- src/tui/error_buffer.rs | 40 +++++++----- 9 files changed, 121 insertions(+), 124 deletions(-) diff --git a/src/auth/accounts.rs b/src/auth/accounts.rs index edbf7d8..0d6123f 100644 --- a/src/auth/accounts.rs +++ b/src/auth/accounts.rs @@ -186,7 +186,10 @@ mod tests { assert_eq!(acc.account_type, AccountType::Offline); assert!(!acc.active); assert!(acc.refresh_token.is_none()); - assert!(!acc.uuid.is_empty()); + // pin the uuid to the deterministic offline_uuid output so a regression + // in the uuid derivation (e.g. salt change) would fail this test, not + // just a non-empty-string check that any garbage would pass. + assert_eq!(acc.uuid, offline_uuid("TestPlayer")); } fn make_store(dir: &std::path::Path) -> AccountStore { diff --git a/src/cli/mod.rs b/src/cli/mod.rs index b03d47a..7786d3d 100644 --- a/src/cli/mod.rs +++ b/src/cli/mod.rs @@ -247,6 +247,13 @@ mod tests { let matches = build_command() .try_get_matches_from(["rmcl", "instance", "list"]) .expect("command should parse"); - assert!(matches.subcommand_matches("instance").is_some()); + let instance = matches + .subcommand_matches("instance") + .expect("instance subcommand should be present"); + assert_eq!( + instance.subcommand_name(), + Some("list"), + "instance list should resolve to the list subcommand" + ); } } diff --git a/src/config/theme.rs b/src/config/theme.rs index 5d782b1..ba0289f 100644 --- a/src/config/theme.rs +++ b/src/config/theme.rs @@ -172,10 +172,15 @@ pub static BORDER_STYLE: LazyLock = mod tests { use super::*; - #[test] - fn border_style_roundtrip() { - let style = BorderStyle::Double; - assert_eq!(style.to_border_type(), BorderType::Double); + // cover every BorderStyle variant. a mutation that swaps two arms of the + // match (e.g. Rounded -> Plain) would slip past testing just one variant. + #[rstest::rstest] + #[case::plain(BorderStyle::Plain, BorderType::Plain)] + #[case::rounded(BorderStyle::Rounded, BorderType::Rounded)] + #[case::double(BorderStyle::Double, BorderType::Double)] + #[case::thick(BorderStyle::Thick, BorderType::Thick)] + fn border_style_roundtrip(#[case] style: BorderStyle, #[case] expected: BorderType) { + assert_eq!(style.to_border_type(), expected); } #[test] diff --git a/src/instance/desktop.rs b/src/instance/desktop.rs index c8383b5..0578838 100644 --- a/src/instance/desktop.rs +++ b/src/instance/desktop.rs @@ -201,15 +201,6 @@ mod tests { assert_eq!(sanitize("path/traversal"), "path_traversal"); } - #[test] - fn desktop_path_returns_some() { - let path = desktop_path("TestPack"); - if let Some(p) = path { - let name = p.file_name().unwrap().to_str().unwrap(); - assert!(name.contains("TestPack")); - } - } - #[test] #[cfg(target_os = "linux")] fn build_content_linux() { diff --git a/src/instance/launch/mod.rs b/src/instance/launch/mod.rs index 8a110db..474d6d9 100644 --- a/src/instance/launch/mod.rs +++ b/src/instance/launch/mod.rs @@ -659,7 +659,7 @@ mod tests { use super::*; #[test] - fn build_game_args_renders_upstream_arguments_and_appends_loader_args() { + fn build_game_args_renders_upstream_arguments() { use crate::launch_profile::model::{Argument, Arguments, LaunchProfile}; use crate::launch_profile::rules::{FeatureSet, RuleContext}; use TemplateContext; @@ -720,46 +720,39 @@ mod tests { assert_eq!(game_args, vec!["--username", "Player"]); } - #[test] - fn migration_predicate_triggers_when_both_argument_fields_absent() { - use LaunchProfile; - let stripped = LaunchProfile { - id: "1.20.1".into(), - inherits_from: None, - main_class: Some("net.test.Main".into()), - libraries: Vec::new(), - ..Default::default() - }; - assert!(stripped.arguments.is_none() && stripped.minecraft_arguments.is_none()); - } - - #[test] - fn migration_predicate_skips_when_modern_arguments_present() { + // 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}; - let modern = LaunchProfile { - id: "1.20.1".into(), - inherits_from: None, - main_class: Some("net.test.Main".into()), - libraries: Vec::new(), - arguments: Some(Arguments::default()), - ..Default::default() - }; - assert!(modern.arguments.is_some()); - } + use tempfile::TempDir; - #[test] - fn migration_predicate_skips_when_legacy_minecraft_arguments_present() { - use LaunchProfile; - let legacy = LaunchProfile { - id: "1.7.10".into(), - inherits_from: None, + 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()), - libraries: Vec::new(), - arguments: None, - minecraft_arguments: Some("--username Player".into()), + arguments: modern.then(Arguments::default), + minecraft_arguments: legacy.then(|| "--username Player".into()), ..Default::default() }; - assert!(legacy.minecraft_arguments.is_some()); + + 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:?}" + ); } #[test] @@ -785,36 +778,48 @@ mod tests { assert!(installer_version_dir_name(ModLoader::Quilt, "1.20.1", "0.20.0").is_none()); } - #[test] - fn loader_profile_legacy_predicate_triggers_when_all_three_absent() { + // 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; - let legacy = LaunchProfile { - id: "1.20.1-forge-47.2.0".into(), - inherits_from: None, - main_class: Some("cpw.mods.bootstraplauncher.BootstrapLauncher".into()), - libraries: Vec::new(), - ..Default::default() - }; - let is_legacy = legacy.inherits_from.is_none() - && legacy.arguments.is_none() - && legacy.minecraft_arguments.is_none(); - assert!(is_legacy); - } + 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(); - #[test] - fn loader_profile_legacy_predicate_skips_modern_profile_with_inherits_from() { - use LaunchProfile; 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()), - libraries: Vec::new(), ..Default::default() }; - let is_legacy = modern.inherits_from.is_none() - && modern.arguments.is_none() - && modern.minecraft_arguments.is_none(); - assert!(!is_legacy); + + 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, + }; + + 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] diff --git a/src/instance/loader/mod.rs b/src/instance/loader/mod.rs index e670341..ab6378f 100644 --- a/src/instance/loader/mod.rs +++ b/src/instance/loader/mod.rs @@ -108,31 +108,18 @@ pub fn get_installer(loader: ModLoader) -> Box= 2); - if all.len() >= 2 { - assert!(all[0].id >= all[1].id); - } + let tag = "PEEK_NEWEST_FIRST_TAG"; + push_error(make_event(&format!("{tag}_a"))); + push_error(make_event(&format!("{tag}_b"))); + let ours: Vec<_> = peek_all_errors() + .into_iter() + .filter(|e| e.message.contains(tag)) + .collect(); + assert_eq!(ours.len(), 2, "expected 2 tagged events, got {ours:?}"); + // _b was pushed last, so it must come out first (newest-first iter) + assert!(ours[0].message.ends_with("_b")); + assert!(ours[1].message.ends_with("_a")); + // newer event also has the higher auto-assigned id + assert!(ours[0].id > ours[1].id); } #[test] fn auto_assigned_ids_are_unique() { - push_error(make_event("err_id_1")); - push_error(make_event("err_id_2")); - let all = peek_all_errors(); - if all.len() >= 2 { - let ids: Vec = all.iter().map(|e| e.id).collect(); - let unique: std::collections::HashSet = ids.iter().copied().collect(); - assert_eq!(ids.len(), unique.len()); - } + let tag = "AUTO_ID_UNIQUE_TAG"; + push_error(make_event(&format!("{tag}_1"))); + push_error(make_event(&format!("{tag}_2"))); + let ours: Vec<_> = peek_all_errors() + .into_iter() + .filter(|e| e.message.contains(tag)) + .collect(); + assert_eq!(ours.len(), 2); + assert_ne!(ours[0].id, ours[1].id); } #[test] From 623acd9e2c96dc744c36ed6a77d87b78c80d9a7b Mon Sep 17 00:00:00 2001 From: objz Date: Wed, 27 May 2026 16:44:05 +0200 Subject: [PATCH 11/20] added: tests for retry envelope, manager rename, mod precedence, time buckets Audit identified six high-priority coverage gaps. This commit closes them with 30 net new passing tests. - tests/net_retry.rs (new): 5 wiremock-based tests for the retry envelope in net/mod.rs. Covers get_json + download_file across: 5xx retry-then-succeed, 4xx fail-fast (asserted via wiremock expect(1) so any retry attempt fails the test), and exhaust at MAX_RETRIES = 3 (asserted via expect(4)). The exhaust test takes ~3.5s of wall time because the production code sleeps 500 + 1000 + 2000 ms between attempts; this is unavoidable without making the delays configurable. - tests/launch_pipeline.rs: 3 new error-path tests against build_launch_invocation. merged_profile_missing_main_class_fails surfaces the LaunchError::Parse branch when meta.json deserialises cleanly but lacks mainClass. legacy_loader_profile_missing_loader_version_errors and legacy_loader_profile_missing_installer_json_errors exercise the two Parse branches inside migrate_legacy_loader_profile_if_needed. - instance/manager.rs: 6 tests for rename (happy path, noop on same name, empty target rejected, missing source, target collision) and touch_last_played (sets the field to a stamp within 5 seconds of now). The InstanceManager rename surface had no coverage before; mutating the validation order or the std::fs::rename target would not have failed any existing test. - instance/content/mods.rs: 4 new precedence-chain tests. The reader chain is fabric > quilt > forge-toml (which itself tries neoforge.mods.toml before mods.toml) > mcmod.info. Only the fabric-over-forge precedence had a test before. Adds quilt > forge, forge_toml > mcmod_info, neoforge.mods.toml > mods.toml, and a test that a mods.toml carrying only logoFile (no [[mods]] array) still resolves the icon. - tui/widgets/instances.rs: 12 new tests for format_last_played. One case for the None input (returns "Never played"), then an rstest covering each bucket boundary in the match (0/59 just-now, 60/3599 minutes, 3600/86399 hours, 86400/2591999 days, 2592000/31535999 months, >=31536000 over-a-year). A mutation that bumps any boundary by one second, or swaps a unit suffix, fails at least one case. --- src/instance/content/mods.rs | 82 +++++++++++++++++++ src/instance/manager.rs | 94 +++++++++++++++++++++ src/tui/widgets/instances.rs | 30 +++++++ tests/launch_pipeline.rs | 79 ++++++++++++++++++ tests/net_retry.rs | 153 +++++++++++++++++++++++++++++++++++ 5 files changed, 438 insertions(+) create mode 100644 tests/net_retry.rs diff --git a/src/instance/content/mods.rs b/src/instance/content/mods.rs index 8bbe80d..1b03cdd 100644 --- a/src/instance/content/mods.rs +++ b/src/instance/content/mods.rs @@ -700,6 +700,88 @@ description = "A neoforge mod" 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); + // metadata name is empty, so scan_one_mod falls back to the file stem + assert_eq!(mods[0].name, "lib-only"); + // the icon path from logoFile must resolve to the in-jar entry + 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(); diff --git a/src/instance/manager.rs b/src/instance/manager.rs index 41ffecd..0433c48 100644 --- a/src/instance/manager.rs +++ b/src/instance/manager.rs @@ -419,4 +419,98 @@ mod tests { assert!(matches!(result, Err(InstanceError::NotFound(_)))); std::fs::remove_dir_all(&tmp).ok(); } + + 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, + } + } + + #[test] + fn rename_moves_dir_and_updates_config_name() { + let (manager, tmp) = test_manager(); + let old_dir = tmp.join("old-name"); + std::fs::create_dir_all(&old_dir).ok(); + 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.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"); + std::fs::remove_dir_all(&tmp).ok(); + } + + #[test] + fn rename_to_same_name_is_noop() { + let (manager, tmp) = test_manager(); + let dir = tmp.join("same"); + std::fs::create_dir_all(&dir).ok(); + manager.save(&dummy_config("same")).expect("save"); + manager.rename("same", "same").expect("noop rename"); + assert!(dir.exists()); + std::fs::remove_dir_all(&tmp).ok(); + } + + #[test] + fn rename_empty_target_rejects() { + let (manager, tmp) = test_manager(); + std::fs::create_dir_all(tmp.join("orig")).ok(); + manager.save(&dummy_config("orig")).expect("save"); + let err = manager.rename("orig", " ").unwrap_err(); + assert!(matches!(err, InstanceError::InvalidName(_))); + std::fs::remove_dir_all(&tmp).ok(); + } + + #[test] + fn rename_missing_source_errors() { + let (manager, tmp) = test_manager(); + let err = manager.rename("ghost", "anything").unwrap_err(); + assert!(matches!(err, InstanceError::NotFound(_))); + std::fs::remove_dir_all(&tmp).ok(); + } + + #[test] + fn rename_target_exists_errors() { + let (manager, tmp) = test_manager(); + std::fs::create_dir_all(tmp.join("source")).ok(); + std::fs::create_dir_all(tmp.join("collision")).ok(); + 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(_))); + std::fs::remove_dir_all(&tmp).ok(); + } + + #[test] + fn touch_last_played_updates_field() { + let (manager, tmp) = test_manager(); + std::fs::create_dir_all(tmp.join("ticker")).ok(); + manager.save(&dummy_config("ticker")).expect("save"); + // sanity: last_played starts as None + 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"); + // and it must be recent (within 5 seconds of now) + let age = chrono::Utc::now() - stamp; + assert!( + age.num_seconds().abs() < 5, + "last_played should be roughly now, got age {age:?}" + ); + std::fs::remove_dir_all(&tmp).ok(); + } } diff --git a/src/tui/widgets/instances.rs b/src/tui/widgets/instances.rs index c82d4fc..a44973c 100644 --- a/src/tui/widgets/instances.rs +++ b/src/tui/widgets/instances.rs @@ -337,3 +337,33 @@ pub fn render(frame: &mut Frame, area: Rect, focused: FocusedArea, state: &mut S &mut state.scrollbar_state, ); } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn format_last_played_none_returns_never_played() { + assert_eq!(format_last_played(None), "Never played"); + } + + // each #[case] picks a "seconds ago" value that lands in exactly one + // bucket of the match. mutating any bucket boundary (e.g. 3600 to 3601, + // or "minutes" to "seconds") makes one of these cases fail. + #[rstest::rstest] + #[case::just_now(0, "Just now")] + #[case::just_now_upper(59, "Just now")] + #[case::minutes(60, "1 minutes ago")] + #[case::minutes_upper(3599, "59 minutes ago")] + #[case::hours(3600, "1 hours ago")] + #[case::hours_upper(86_399, "23 hours ago")] + #[case::days(86_400, "1 days ago")] + #[case::days_upper(2_591_999, "29 days ago")] + #[case::months(2_592_000, "1 months ago")] + #[case::months_upper(31_535_999, "12 months ago")] + #[case::over_a_year(31_536_000, "Over a year ago")] + fn format_last_played_buckets(#[case] seconds_ago: i64, #[case] expected: &str) { + let dt = chrono::Utc::now() - chrono::Duration::seconds(seconds_ago); + assert_eq!(format_last_played(Some(dt)), expected); + } +} diff --git a/tests/launch_pipeline.rs b/tests/launch_pipeline.rs index f31fe14..cc29cbc 100644 --- a/tests/launch_pipeline.rs +++ b/tests/launch_pipeline.rs @@ -602,3 +602,82 @@ async fn loader_profile_missing_returns_error() { ); } +#[tokio::test] +async fn merged_profile_missing_main_class_fails() { + // a meta.json that deserialises cleanly but lacks the required mainClass + // must surface as a Parse error; otherwise the launcher would try to + // unwrap None and crash later. + let mut meta = modern_vanilla_meta("1.20.1"); + meta.as_object_mut().unwrap().remove("mainClass"); + let fx = Fixture::new("nomc", "1.20.1", meta); + let config = make_config("nomc", "1.20.1", ModLoader::Vanilla); + + let err = build_launch_invocation(&config, &fx.instances_dir, &fx.meta_dir, &test_auth()) + .await + .unwrap_err(); + let msg = format!("{err:?}"); + assert!( + matches!(err, LaunchError::Parse(_)) && msg.contains("mainClass"), + "expected Parse error mentioning mainClass, got: {err:?}" + ); +} + +#[tokio::test] +async fn legacy_loader_profile_missing_loader_version_errors() { + // an instance with no loader_version recorded must error out cleanly + // when its loader profile is in the legacy stripped shape (no + // inheritsFrom, no arguments, no minecraftArguments, but has the rmcl + // 0.3.0-era gameArguments field). + let fx = Fixture::new("nolv", "1.20.1", modern_vanilla_meta("1.20.1")); + fx.write_loader_profile( + "forge-1.20.1-unknown.json", + json!({ + "id": "1.20.1-forge", + "mainClass": "cpw.mods.bootstraplauncher.BootstrapLauncher", + "libraries": [], + "gameArguments": ["--launchTarget", "forge_client"] + }), + ); + + let mut config = make_config("nolv", "1.20.1", ModLoader::Forge); + config.loader_version = None; + + let err = build_launch_invocation(&config, &fx.instances_dir, &fx.meta_dir, &test_auth()) + .await + .unwrap_err(); + let msg = format!("{err:?}"); + assert!( + matches!(err, LaunchError::Parse(_)) && msg.contains("Reinstall"), + "expected Parse error asking for reinstall, got: {err:?}" + ); +} + +#[tokio::test] +async fn legacy_loader_profile_missing_installer_json_errors() { + // legacy stripped profile + loader_version, but the installer JSON the + // migration would copy from isn't present on disk. Parse error. + let fx = Fixture::new("noinst", "1.20.1", modern_vanilla_meta("1.20.1")); + fx.write_loader_profile( + "forge-1.20.1-47.2.0.json", + json!({ + "id": "1.20.1-forge-47.2.0", + "mainClass": "cpw.mods.bootstraplauncher.BootstrapLauncher", + "libraries": [], + "gameArguments": ["--launchTarget", "forge_client"] + }), + ); + + let config = make_config_with("noinst", "1.20.1", ModLoader::Forge, Some("47.2.0")); + + let err = build_launch_invocation(&config, &fx.instances_dir, &fx.meta_dir, &test_auth()) + .await + .unwrap_err(); + let msg = format!("{err:?}"); + assert!( + matches!(err, LaunchError::Parse(_)) + && msg.contains("installer JSON") + && msg.contains("missing"), + "expected Parse error about missing installer JSON, got: {err:?}" + ); +} + diff --git a/tests/net_retry.rs b/tests/net_retry.rs new file mode 100644 index 0000000..1b5d635 --- /dev/null +++ b/tests/net_retry.rs @@ -0,0 +1,153 @@ +// integration tests for the retry envelope in src/net/mod.rs. wiremock +// stands in for live upstream APIs so we can assert that 5xx responses +// retry, 4xx responses fail fast, and the cap (MAX_RETRIES = 3, total +// 4 attempts) is honoured. these tests exercise public HttpClient methods, +// not the private retry helper directly. +// +// note: get_with_retry sleeps between attempts (500ms, 1000ms, 2000ms), +// so the gives-up-after-max-retries test takes about 3.5s of wall time. +// nothing to be done about that without making the delays configurable. + +use std::path::PathBuf; + +use serde::Deserialize; +use serde_json::json; +use wiremock::matchers::{method, path}; +use wiremock::{Mock, MockServer, ResponseTemplate}; + +use rmcl::net::{HttpClient, download_file}; + +#[derive(Debug, Deserialize)] +struct ApiResponse { + ok: bool, +} + +// ---------- get_json (via get_with_retry) ---------- + +#[tokio::test] +async fn get_json_retries_5xx_then_succeeds() { + let server = MockServer::start().await; + + // first request: 503. second and beyond: 200. + Mock::given(method("GET")) + .and(path("/api")) + .respond_with(ResponseTemplate::new(503)) + .up_to_n_times(1) + .expect(1) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path("/api")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({"ok": true}))) + .expect(1) + .mount(&server) + .await; + + let url = format!("{}/api", server.uri()); + let result: ApiResponse = HttpClient::new().get_json(&url).await.unwrap(); + assert!(result.ok); +} + +#[tokio::test] +async fn get_json_fails_fast_on_4xx() { + let server = MockServer::start().await; + + // expect(1) makes wiremock panic on drop if the mock matches more than + // once. that's how we assert "no retries" without watching the clock. + Mock::given(method("GET")) + .and(path("/api")) + .respond_with(ResponseTemplate::new(404)) + .expect(1) + .mount(&server) + .await; + + let url = format!("{}/api", server.uri()); + let err = HttpClient::new() + .get_json::(&url) + .await + .unwrap_err(); + assert!( + format!("{err:?}").contains("404"), + "expected 404 in error, got: {err:?}" + ); +} + +#[tokio::test] +async fn get_json_gives_up_after_max_retries() { + let server = MockServer::start().await; + + // MAX_RETRIES = 3 means we expect exactly 4 attempts before giving up. + // expect(4) asserts that. + Mock::given(method("GET")) + .and(path("/api")) + .respond_with(ResponseTemplate::new(503)) + .expect(4) + .mount(&server) + .await; + + let url = format!("{}/api", server.uri()); + let err = HttpClient::new() + .get_json::(&url) + .await + .unwrap_err(); + assert!( + format!("{err:?}").contains("503"), + "expected 503 in final error, got: {err:?}" + ); +} + +// ---------- download_file ---------- + +#[tokio::test] +async fn download_file_retries_5xx_then_succeeds() { + let server = MockServer::start().await; + + Mock::given(method("GET")) + .and(path("/file.bin")) + .respond_with(ResponseTemplate::new(502)) + .up_to_n_times(1) + .expect(1) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path("/file.bin")) + .respond_with(ResponseTemplate::new(200).set_body_bytes(b"hello, retried".to_vec())) + .expect(1) + .mount(&server) + .await; + + let tmp = tempfile::tempdir().unwrap(); + let dest = tmp.path().join("downloaded.bin"); + let url = format!("{}/file.bin", server.uri()); + + download_file(&HttpClient::new(), &url, &dest, |_, _| {}) + .await + .unwrap(); + + let content = std::fs::read(&dest).unwrap(); + assert_eq!(content, b"hello, retried"); +} + +#[tokio::test] +async fn download_file_fails_fast_on_4xx() { + let server = MockServer::start().await; + + Mock::given(method("GET")) + .and(path("/file.bin")) + .respond_with(ResponseTemplate::new(404)) + .expect(1) + .mount(&server) + .await; + + let tmp = tempfile::tempdir().unwrap(); + let dest: PathBuf = tmp.path().join("never-written.bin"); + let url = format!("{}/file.bin", server.uri()); + + let err = download_file(&HttpClient::new(), &url, &dest, |_, _| {}) + .await + .unwrap_err(); + assert!( + format!("{err:?}").contains("404"), + "expected 404 in error, got: {err:?}" + ); +} From 1f1a0ebb3d5644c2b18b7c107d31d6cff8e88036 Mon Sep 17 00:00:00 2001 From: objz Date: Wed, 27 May 2026 17:09:09 +0200 Subject: [PATCH 12/20] refactored: test style cleanup + mmc archive extract test Picks up the style audit's findings without touching production behaviour (except for two em-dash characters in non-test code that violated the no-em-dash rule). - cli/import.rs, instance/import/mmc.rs: replace the two em-dashes that leaked into source (one in a user-facing format string, one in a code comment) with hyphen / colon. - instance/manager.rs: rewrite test_manager to return TempDir instead of a hand-rolled tempdir path with manual cleanup. Drop the trailing std::fs::remove_dir_all from every test. Rename test_* functions to describe the scenario per CONTRIBUTING (delete_missing_ instance_returns_not_found, save_then_load_all_round_trips_config, load_one_missing_returns_not_found, etc.). - migrate.rs: replace unique_tmp + atomic counter with tempfile::tempdir() across all seven tests; ~10 lines of plumbing gone, automatic cleanup via Drop. - auth/accounts.rs: drop the dummy_account wrapper that just forwarded to create_offline_account; inline the real call at the eight use sites. - instance/models.rs: rename test_instance_config_roundtrip to instance_config_roundtrips_through_json. - instance/content/mods.rs: drop the "what" comments above straight forward asserts; keep the one "why" comment that explains an empty-name + present-logo coverage gap. Trim the obvious "helper to create a jar (zip) file" comment above make_jar. - tests/smoke.rs: //! to // for the file header; project convention is // for files (//! is for crate-level rustdoc, which doesn't render for integration test crates). Adds one new test: - instance/import/mmc.rs: extract_mmc_archive_copies_minecraft_subtree builds an in-memory zip with a Pack/ prefix, a Pack/mmc-pack.json sibling, and Pack/.minecraft/{options.txt, mods/test-mod.jar}, then asserts only the .minecraft/ subtree lands in the destination with relative paths preserved. Closes the mmc extract coverage gap the audit flagged. --- src/auth/accounts.rs | 34 +++--- src/cli/import.rs | 2 +- src/instance/content/mods.rs | 8 +- src/instance/import/mmc.rs | 50 ++++++++- src/instance/manager.rs | 204 ++++++++++++++--------------------- src/instance/models.rs | 2 +- src/migrate.rs | 54 ++++------ tests/smoke.rs | 4 +- 8 files changed, 173 insertions(+), 185 deletions(-) diff --git a/src/auth/accounts.rs b/src/auth/accounts.rs index 0d6123f..0c5addf 100644 --- a/src/auth/accounts.rs +++ b/src/auth/accounts.rs @@ -199,10 +199,6 @@ mod tests { } } - fn dummy_account(name: &str) -> Account { - create_offline_account(name) - } - fn microsoft_account(name: &str) -> Account { Account { uuid: format!("00000000-0000-0000-0000-{:012}", name.len()), @@ -219,7 +215,7 @@ mod tests { fn store_add_first_becomes_active() { let tmp = tempfile::tempdir().unwrap(); let mut store = make_store(tmp.path()); - store.add(dummy_account("Alice")); + store.add(create_offline_account("Alice")); assert_eq!(store.accounts.len(), 1); assert!(store.accounts[0].active); } @@ -228,8 +224,8 @@ mod tests { fn store_add_second_stays_inactive() { let tmp = tempfile::tempdir().unwrap(); let mut store = make_store(tmp.path()); - store.add(dummy_account("Alice")); - store.add(dummy_account("Bob")); + store.add(create_offline_account("Alice")); + store.add(create_offline_account("Bob")); assert_eq!(store.accounts.len(), 2); assert!(store.accounts[0].active); assert!(!store.accounts[1].active); @@ -239,8 +235,8 @@ mod tests { fn store_add_duplicate_uuid_replaces() { let tmp = tempfile::tempdir().unwrap(); let mut store = make_store(tmp.path()); - store.add(dummy_account("Alice")); - let mut dup = dummy_account("Alice"); + store.add(create_offline_account("Alice")); + let mut dup = create_offline_account("Alice"); dup.username = "AliceRenamed".to_owned(); dup.uuid = store.accounts[0].uuid.clone(); store.add(dup); @@ -259,7 +255,7 @@ mod tests { fn store_has_microsoft_account_when_one_exists() { let tmp = tempfile::tempdir().unwrap(); let mut store = make_store(tmp.path()); - store.add(dummy_account("Offline")); + store.add(create_offline_account("Offline")); assert!(!store.has_microsoft_account()); store.add(microsoft_account("Owner")); @@ -270,8 +266,8 @@ mod tests { fn store_active_account_returns_active() { let tmp = tempfile::tempdir().unwrap(); let mut store = make_store(tmp.path()); - store.add(dummy_account("Alice")); - store.add(dummy_account("Bob")); + store.add(create_offline_account("Alice")); + store.add(create_offline_account("Bob")); let active = store.active_account().unwrap(); assert_eq!(active.username, "Alice"); } @@ -280,8 +276,8 @@ mod tests { fn store_set_active_changes_active() { let tmp = tempfile::tempdir().unwrap(); let mut store = make_store(tmp.path()); - store.add(dummy_account("Alice")); - store.add(dummy_account("Bob")); + store.add(create_offline_account("Alice")); + store.add(create_offline_account("Bob")); store.set_active(1); assert!(!store.accounts[0].active); assert!(store.accounts[1].active); @@ -291,8 +287,8 @@ mod tests { fn store_remove_activates_first_remaining() { let tmp = tempfile::tempdir().unwrap(); let mut store = make_store(tmp.path()); - store.add(dummy_account("Alice")); - store.add(dummy_account("Bob")); + store.add(create_offline_account("Alice")); + store.add(create_offline_account("Bob")); store.remove(0); assert_eq!(store.accounts.len(), 1); assert_eq!(store.accounts[0].username, "Bob"); @@ -303,7 +299,7 @@ mod tests { fn store_remove_out_of_bounds_noop() { let tmp = tempfile::tempdir().unwrap(); let mut store = make_store(tmp.path()); - store.add(dummy_account("Alice")); + store.add(create_offline_account("Alice")); store.remove(5); assert_eq!(store.accounts.len(), 1); } @@ -312,8 +308,8 @@ mod tests { fn store_save_and_reload() { let tmp = tempfile::tempdir().unwrap(); let mut store = make_store(tmp.path()); - store.add(dummy_account("Alice")); - store.add(dummy_account("Bob")); + store.add(create_offline_account("Alice")); + store.add(create_offline_account("Bob")); store.save(); let reloaded = AccountStore { diff --git a/src/cli/import.rs b/src/cli/import.rs index 3a62625..b08a1df 100644 --- a/src/cli/import.rs +++ b/src/cli/import.rs @@ -95,7 +95,7 @@ pub async fn handle_import(matches: &ArgMatches) -> CliResult { } println!( - "Importing '{}' — {} {} ({} mods, {} overrides)", + "Importing '{}' - {} {} ({} mods, {} overrides)", summary.name, summary.game_version, summary.loader, diff --git a/src/instance/content/mods.rs b/src/instance/content/mods.rs index 1b03cdd..5e98909 100644 --- a/src/instance/content/mods.rs +++ b/src/instance/content/mods.rs @@ -567,7 +567,6 @@ mod tests { use std::io::Write as _; - // helper to create a jar (zip) file with the given entries fn make_jar(dir: &Path, name: &str, entries: &[(&str, &[u8])]) { let path = dir.join(name); let file = std::fs::File::create(&path).unwrap(); @@ -776,9 +775,9 @@ description = "A neoforge mod" ); let mods = scan_mods(tmp.path(), "inst"); assert_eq!(mods.len(), 1); - // metadata name is empty, so scan_one_mod falls back to the file stem + // 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"); - // the icon path from logoFile must resolve to the in-jar entry assert_eq!(mods[0].icon_bytes.as_deref(), Some(png_bytes.as_slice())); } @@ -786,14 +785,11 @@ description = "A neoforge mod" fn scan_mods_fallback_icon_paths() { let tmp = tempfile::tempdir().unwrap(); let dir = setup_mods_dir(tmp.path(), "inst"); - // jar with no metadata but has logo.png 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); - // should use filename as name since no metadata assert_eq!(mods[0].name, "no-meta"); - // icon_bytes should contain the logo.png content assert_eq!(mods[0].icon_bytes.as_deref(), Some(png_bytes.as_slice())); } diff --git a/src/instance/import/mmc.rs b/src/instance/import/mmc.rs index 9967e3b..d08557b 100644 --- a/src/instance/import/mmc.rs +++ b/src/instance/import/mmc.rs @@ -181,7 +181,7 @@ fn instance_name_from_cfg(path: &Path) -> Option { None } -// finds the prefix for the archive — empty for flat zips, "DirName/" for nested +// finds the prefix for the archive: empty for flat zips, "DirName/" for nested fn find_archive_prefix(archive: &zip::ZipArchive) -> String { for name in archive.file_names() { if name.ends_with("mmc-pack.json") { @@ -269,4 +269,52 @@ mod tests { 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" + ); + } } diff --git a/src/instance/manager.rs b/src/instance/manager.rs index 0433c48..845d193 100644 --- a/src/instance/manager.rs +++ b/src/instance/manager.rs @@ -314,110 +314,16 @@ fn validate_name(name: &str) -> Result<(), InstanceError> { mod tests { use super::*; use crate::instance::models::ModLoader; - use std::path::PathBuf; + use tempfile::TempDir; - fn test_manager() -> (InstanceManager, PathBuf) { - let tmp = std::env::temp_dir().join(format!("rmcl_test_{}", uuid_like())); - let meta = std::env::temp_dir().join(format!("rmcl_meta_test_{}", uuid_like())); - std::fs::create_dir_all(&tmp).ok(); - std::fs::create_dir_all(&meta).ok(); - (InstanceManager::new(tmp.clone(), meta), tmp) - } - - fn uuid_like() -> String { - format!( - "{:x}", - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map(|d| d.as_nanos()) - .unwrap_or(0) - ) - } - - #[test] - fn test_validate_name_valid() { - assert!(validate_name("my-instance").is_ok()); - assert!(validate_name("test_world").is_ok()); - } - - #[test] - fn test_validate_name_invalid() { - assert!(validate_name("").is_err()); - assert!(validate_name("path/traversal").is_err()); - assert!(validate_name(".hidden").is_err()); - } - - #[test] - fn test_delete_nonexistent() { - let (manager, tmp) = test_manager(); - let result = manager.delete("ghost-instance"); - assert!(matches!(result, Err(InstanceError::NotFound(_)))); - std::fs::remove_dir_all(&tmp).ok(); - } - - #[test] - fn test_save_and_load_all() { - let (manager, tmp) = test_manager(); - let instance_dir = tmp.join("test-save"); - std::fs::create_dir_all(&instance_dir).ok(); - - let config = InstanceConfig { - name: "test-save".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, - }; - - manager.save(&config).expect("save failed"); - - 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"); - - std::fs::remove_dir_all(&tmp).ok(); - } - - #[test] - fn test_load_all_accepts_numeric_memory() { - let (manager, tmp) = test_manager(); - let instance_dir = tmp.join("test-memory"); - std::fs::create_dir_all(&instance_dir).ok(); - 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")); - - std::fs::remove_dir_all(&tmp).ok(); - } - - #[test] - fn test_load_one_not_found() { - let (manager, tmp) = test_manager(); - let result = manager.load_one("ghost-instance"); - assert!(matches!(result, Err(InstanceError::NotFound(_)))); - std::fs::remove_dir_all(&tmp).ok(); + // 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 { @@ -436,81 +342,137 @@ mod tests { } } + #[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.join("old-name"); - std::fs::create_dir_all(&old_dir).ok(); + 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.join("new-name"); + 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"); - std::fs::remove_dir_all(&tmp).ok(); } #[test] fn rename_to_same_name_is_noop() { let (manager, tmp) = test_manager(); - let dir = tmp.join("same"); - std::fs::create_dir_all(&dir).ok(); + 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()); - std::fs::remove_dir_all(&tmp).ok(); } #[test] fn rename_empty_target_rejects() { let (manager, tmp) = test_manager(); - std::fs::create_dir_all(tmp.join("orig")).ok(); + 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(_))); - std::fs::remove_dir_all(&tmp).ok(); } #[test] fn rename_missing_source_errors() { - let (manager, tmp) = test_manager(); + let (manager, _tmp) = test_manager(); let err = manager.rename("ghost", "anything").unwrap_err(); assert!(matches!(err, InstanceError::NotFound(_))); - std::fs::remove_dir_all(&tmp).ok(); } #[test] fn rename_target_exists_errors() { let (manager, tmp) = test_manager(); - std::fs::create_dir_all(tmp.join("source")).ok(); - std::fs::create_dir_all(tmp.join("collision")).ok(); + 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(_))); - std::fs::remove_dir_all(&tmp).ok(); } #[test] fn touch_last_played_updates_field() { let (manager, tmp) = test_manager(); - std::fs::create_dir_all(tmp.join("ticker")).ok(); + std::fs::create_dir_all(tmp.path().join("ticker")).unwrap(); manager.save(&dummy_config("ticker")).expect("save"); - // sanity: last_played starts as None 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"); - // and it must be recent (within 5 seconds of now) let age = chrono::Utc::now() - stamp; assert!( age.num_seconds().abs() < 5, "last_played should be roughly now, got age {age:?}" ); - std::fs::remove_dir_all(&tmp).ok(); } } diff --git a/src/instance/models.rs b/src/instance/models.rs index 9d82fa3..7f59a75 100644 --- a/src/instance/models.rs +++ b/src/instance/models.rs @@ -124,7 +124,7 @@ mod tests { use super::*; #[test] - fn test_instance_config_roundtrip() { + fn instance_config_roundtrips_through_json() { let config = InstanceConfig { name: "test".to_string(), game_version: "1.20.1".to_string(), diff --git a/src/migrate.rs b/src/migrate.rs index af4e297..8b23810 100644 --- a/src/migrate.rs +++ b/src/migrate.rs @@ -171,27 +171,12 @@ fn sanitize(name: &str) -> String { #[cfg(test)] mod tests { use super::*; - use std::path::PathBuf; - use std::sync::atomic::{AtomicU64, Ordering}; - - static COUNTER: AtomicU64 = AtomicU64::new(0); - - fn unique_tmp(label: &str) -> PathBuf { - let n = COUNTER.fetch_add(1, Ordering::SeqCst); - let nanos = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map(|d| d.as_nanos()) - .unwrap_or(0); - let p = std::env::temp_dir().join(format!("rmcl_migrate_test_{label}_{nanos}_{n}")); - std::fs::create_dir_all(&p).unwrap(); - p - } #[test] fn rename_top_level_moves_when_only_old_exists() { - let root = unique_tmp("only_old"); - let old = root.join("mcl"); - let new = root.join("rmcl"); + let tmp = tempfile::tempdir().unwrap(); + let old = tmp.path().join("mcl"); + let new = tmp.path().join("rmcl"); fs::create_dir_all(old.join("sub")).unwrap(); fs::write(old.join("sub").join("f.txt"), b"hi").unwrap(); @@ -204,9 +189,9 @@ mod tests { #[test] fn rename_top_level_skips_when_only_new_exists() { - let root = unique_tmp("only_new"); - let old = root.join("mcl"); - let new = root.join("rmcl"); + let tmp = tempfile::tempdir().unwrap(); + let old = tmp.path().join("mcl"); + let new = tmp.path().join("rmcl"); fs::create_dir_all(&new).unwrap(); fs::write(new.join("marker.txt"), b"keep").unwrap(); @@ -218,9 +203,9 @@ mod tests { #[test] fn rename_top_level_skips_when_both_exist() { - let root = unique_tmp("both"); - let old = root.join("mcl"); - let new = root.join("rmcl"); + let tmp = tempfile::tempdir().unwrap(); + let old = tmp.path().join("mcl"); + let new = tmp.path().join("rmcl"); fs::create_dir_all(&old).unwrap(); fs::create_dir_all(&new).unwrap(); fs::write(old.join("a"), b"old").unwrap(); @@ -236,9 +221,9 @@ mod tests { #[test] fn rename_top_level_noop_when_neither_exists() { - let root = unique_tmp("neither"); - let old = root.join("mcl"); - let new = root.join("rmcl"); + let tmp = tempfile::tempdir().unwrap(); + let old = tmp.path().join("mcl"); + let new = tmp.path().join("rmcl"); rename_top_level(&old, &new); @@ -248,7 +233,8 @@ mod tests { #[test] fn cleanup_instance_leftovers_removes_shim_and_log4j() { - let instances = unique_tmp("inst").join("instances"); + let tmp = tempfile::tempdir().unwrap(); + let instances = tmp.path().join("instances"); let mc = instances.join("Test").join(".minecraft"); fs::create_dir_all(&mc).unwrap(); fs::write(mc.join(".mcl-shim.jar"), b"jar").unwrap(); @@ -265,8 +251,8 @@ mod tests { #[test] #[cfg(target_os = "linux")] fn rewrite_linux_desktop_entries_renames_and_rewrites_exec() { - let root = unique_tmp("linux_desk"); - let data = root.clone(); + let tmp = tempfile::tempdir().unwrap(); + let data = tmp.path(); let instances = data.join("rmcl").join("instances"); let apps = data.join("applications"); fs::create_dir_all(instances.join("MyPack")).unwrap(); @@ -278,7 +264,7 @@ mod tests { ) .unwrap(); - rewrite_linux_desktop_entries(&data, &instances); + rewrite_linux_desktop_entries(data, &instances); let new_entry = apps.join("rmcl-MyPack.desktop"); assert!(!old_entry.exists(), "old .desktop should be removed"); @@ -289,9 +275,9 @@ mod tests { #[test] fn copy_dir_recursive_copies_nested_tree() { - let root = unique_tmp("copy"); - let src = root.join("a"); - let dst = root.join("b"); + let tmp = tempfile::tempdir().unwrap(); + let src = tmp.path().join("a"); + let dst = tmp.path().join("b"); fs::create_dir_all(src.join("nested")).unwrap(); fs::write(src.join("top.txt"), b"top").unwrap(); fs::write(src.join("nested").join("inner.txt"), b"inner").unwrap(); diff --git a/tests/smoke.rs b/tests/smoke.rs index 3e81265..97384f2 100644 --- a/tests/smoke.rs +++ b/tests/smoke.rs @@ -1,5 +1,5 @@ -//! verifies the lib/main split worked: integration tests can see crate items -//! through the public API. +// verifies the lib/main split worked: integration tests can see crate items +// through the public API. #[test] fn lib_target_is_importable() { From 6ac9f4e23990c63cf3082e1c751140aa85a192a3 Mon Sep 17 00:00:00 2001 From: objz Date: Wed, 27 May 2026 17:22:32 +0200 Subject: [PATCH 13/20] added: net::mojang wiremock tests via *_from URL variants The existing fetch_version_manifest hard-codes the Mojang URL, so tests either had to hit the live endpoint (the #[ignore] live-API test) or not run at all. Adds fetch_version_manifest_from(client, url) that lets callers pick the URL; fetch_version_manifest stays compatible by delegating with the upstream constant. fetch_version_meta_with_raw already takes the URL via VersionEntry, no change needed. tests/net_mojang.rs adds three wiremock tests: - fetch_version_manifest_parses_synthetic_response verifies the VersionManifest deserialiser against a synthetic upstream-shaped payload (latest + versions list). - fetch_version_meta_returns_struct_and_raw_bytes verifies both the parsed VersionMeta and the raw byte capture path used by the install flow to write upstream JSON byte-for-byte. - fetch_version_manifest_retries_5xx_and_succeeds confirms the retry envelope integrates correctly with VersionManifest deserialisation on top of the retry-only tests in tests/net_retry.rs. These don't replace the #[ignore = "hits live Mojang API"] canary which still runs on master push to detect upstream schema drift. --- src/net/mojang.rs | 12 +++- tests/net_mojang.rs | 141 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 152 insertions(+), 1 deletion(-) create mode 100644 tests/net_mojang.rs diff --git a/src/net/mojang.rs b/src/net/mojang.rs index d8b0dcc..f4ec379 100644 --- a/src/net/mojang.rs +++ b/src/net/mojang.rs @@ -110,7 +110,17 @@ pub struct AssetObject { } pub async fn fetch_version_manifest(client: &HttpClient) -> Result { - client.get_json(MANIFEST_URL).await + fetch_version_manifest_from(client, MANIFEST_URL).await +} + +// same as fetch_version_manifest but lets the caller pick the URL. exists so +// integration tests can point at a wiremock server; production callers go +// through fetch_version_manifest with the upstream Mojang URL. +pub async fn fetch_version_manifest_from( + client: &HttpClient, + url: &str, +) -> Result { + client.get_json(url).await } // fetches and parses a version's metadata. also returns the raw response diff --git a/tests/net_mojang.rs b/tests/net_mojang.rs new file mode 100644 index 0000000..50b5d4c --- /dev/null +++ b/tests/net_mojang.rs @@ -0,0 +1,141 @@ +// integration tests for the public mojang fetchers. wiremock stands in for +// Mojang so tests are fast, deterministic, and don't depend on the live +// endpoint. these are different from the #[ignore = "hits live Mojang API"] +// tests in src/net/mojang.rs which verify the upstream schema hasn't drifted; +// these here verify our parsing + retry envelope on synthetic responses. + +use serde_json::json; +use wiremock::matchers::{method, path}; +use wiremock::{Mock, MockServer, ResponseTemplate}; + +use rmcl::net::HttpClient; +use rmcl::net::mojang::{VersionEntry, fetch_version_manifest_from, fetch_version_meta_with_raw}; + +fn synthetic_manifest() -> serde_json::Value { + json!({ + "latest": { "release": "1.20.1", "snapshot": "24w01a" }, + "versions": [ + { + "id": "1.20.1", + "type": "release", + "url": "https://example.com/1.20.1.json", + "sha1": "0000000000000000000000000000000000000000" + }, + { + "id": "1.7.10", + "type": "release", + "url": "https://example.com/1.7.10.json", + "sha1": "0000000000000000000000000000000000000000" + } + ] + }) +} + +fn synthetic_version_meta() -> serde_json::Value { + json!({ + "id": "1.20.1", + "mainClass": "net.minecraft.client.main.Main", + "assetIndex": { + "id": "5", + "url": "https://example.com/assets/5.json", + "sha1": "0000000000000000000000000000000000000000" + }, + "downloads": { + "client": { + "url": "https://example.com/client.jar", + "sha1": "0000000000000000000000000000000000000000", + "size": 12345 + } + }, + "libraries": [], + "javaVersion": { "majorVersion": 17 } + }) +} + +#[tokio::test] +async fn fetch_version_manifest_parses_synthetic_response() { + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/manifest.json")) + .respond_with(ResponseTemplate::new(200).set_body_json(synthetic_manifest())) + .expect(1) + .mount(&server) + .await; + + let url = format!("{}/manifest.json", server.uri()); + let manifest = fetch_version_manifest_from(&HttpClient::new(), &url) + .await + .expect("manifest"); + + assert_eq!(manifest.latest.release, "1.20.1"); + assert_eq!(manifest.latest.snapshot, "24w01a"); + assert_eq!(manifest.versions.len(), 2); + assert_eq!(manifest.versions[0].id, "1.20.1"); + assert_eq!(manifest.versions[1].id, "1.7.10"); +} + +#[tokio::test] +async fn fetch_version_meta_returns_struct_and_raw_bytes() { + let server = MockServer::start().await; + let body_json = synthetic_version_meta(); + // serialise once so we can assert the raw bytes equal what the mock + // actually sent (wiremock re-serialises the json, so we have to match + // its output format) + Mock::given(method("GET")) + .and(path("/1.20.1.json")) + .respond_with(ResponseTemplate::new(200).set_body_json(body_json.clone())) + .expect(1) + .mount(&server) + .await; + + let entry = VersionEntry { + id: "1.20.1".to_string(), + version_type: "release".to_string(), + url: format!("{}/1.20.1.json", server.uri()), + sha1: "0".repeat(40), + }; + + let (meta, raw) = fetch_version_meta_with_raw(&HttpClient::new(), &entry) + .await + .expect("meta"); + + assert_eq!(meta.id, "1.20.1"); + assert_eq!(meta.main_class, "net.minecraft.client.main.Main"); + assert_eq!(meta.asset_index.id, "5"); + assert_eq!(meta.downloads.client.size, 12345); + assert_eq!(meta.java_version.unwrap().major_version, 17); + + // the raw bytes must parse back to the same struct - verifies the + // get_json_with_raw plumbing actually captures the upstream body intact. + let reparsed: serde_json::Value = serde_json::from_slice(&raw).expect("raw is json"); + assert_eq!(reparsed["id"], "1.20.1"); + assert_eq!(reparsed["mainClass"], "net.minecraft.client.main.Main"); +} + +#[tokio::test] +async fn fetch_version_manifest_retries_5xx_and_succeeds() { + let server = MockServer::start().await; + + // one transient 503 then the real payload; covers the integration of the + // retry envelope (already unit-tested in net_retry.rs) with the actual + // VersionManifest deserialisation path. + Mock::given(method("GET")) + .and(path("/manifest.json")) + .respond_with(ResponseTemplate::new(503)) + .up_to_n_times(1) + .expect(1) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path("/manifest.json")) + .respond_with(ResponseTemplate::new(200).set_body_json(synthetic_manifest())) + .expect(1) + .mount(&server) + .await; + + let url = format!("{}/manifest.json", server.uri()); + let manifest = fetch_version_manifest_from(&HttpClient::new(), &url) + .await + .expect("manifest after retry"); + assert_eq!(manifest.versions.len(), 2); +} From 41d6da80089d7c7f78de0892e37386af915ced4a Mon Sep 17 00:00:00 2001 From: objz Date: Wed, 27 May 2026 17:22:33 +0200 Subject: [PATCH 14/20] added: ratatui snapshots for instance_list and wizard popups Phase E added snapshots for the ErrorPopup; this extends the same pattern to the three other high-value widgets the audit flagged. - src/tui/widgets/instances.rs: two snapshots covering the instance list with three synthetic instances (verifies layout, "Never played" rendering, scrollbar gutter) and the empty list. State is passed in via the existing State::with_instances constructor; no global state involved. - src/tui/widgets/popups/new_instance/render.rs: two snapshots covering the Name step (default) and Loader step (hardcoded loader list, no network). WIZARD_STATE is global, so the tests reset it under its mutex and serialise via a per-module TEST_SERIAL mutex to prevent cross-test races. The Version and LoaderVersion steps are skipped here because their render path calls ensure_versions_loaded which tokio::spawns a network task; covering them would need a fully pre-populated state and is deferred. - src/tui/widgets/popups/import_modpack/render.rs: two snapshots covering the Input step (default) and the Fetching step (just a spinner + label, no network triggered by render). Same global-state serialisation pattern as new_instance. Snapshots live next to each widget under snapshots/ as plain text and are committed to git. --- src/tui/widgets/instances.rs | 53 +++++++++++++++++++ .../widgets/popups/import_modpack/render.rs | 42 +++++++++++++++ ..._import_modpack_renders_fetching_step.snap | 16 ++++++ ...ts__import_modpack_renders_input_step.snap | 16 ++++++ src/tui/widgets/popups/new_instance/render.rs | 48 +++++++++++++++++ ...sts__new_instance_renders_loader_step.snap | 16 ++++++ ...tests__new_instance_renders_name_step.snap | 16 ++++++ ...__tests__instances_list_renders_empty.snap | 12 +++++ ...nstances_list_renders_three_instances.snap | 16 ++++++ 9 files changed, 235 insertions(+) create mode 100644 src/tui/widgets/popups/import_modpack/snapshots/rmcl__tui__widgets__popups__import_modpack__render__tests__import_modpack_renders_fetching_step.snap create mode 100644 src/tui/widgets/popups/import_modpack/snapshots/rmcl__tui__widgets__popups__import_modpack__render__tests__import_modpack_renders_input_step.snap create mode 100644 src/tui/widgets/popups/new_instance/snapshots/rmcl__tui__widgets__popups__new_instance__render__tests__new_instance_renders_loader_step.snap create mode 100644 src/tui/widgets/popups/new_instance/snapshots/rmcl__tui__widgets__popups__new_instance__render__tests__new_instance_renders_name_step.snap create mode 100644 src/tui/widgets/snapshots/rmcl__tui__widgets__instances__tests__instances_list_renders_empty.snap create mode 100644 src/tui/widgets/snapshots/rmcl__tui__widgets__instances__tests__instances_list_renders_three_instances.snap diff --git a/src/tui/widgets/instances.rs b/src/tui/widgets/instances.rs index a44973c..f701e0c 100644 --- a/src/tui/widgets/instances.rs +++ b/src/tui/widgets/instances.rs @@ -366,4 +366,57 @@ mod tests { let dt = chrono::Utc::now() - chrono::Duration::seconds(seconds_ago); assert_eq!(format_last_played(Some(dt)), expected); } + + use crate::instance::models::{InstanceConfig, ModLoader}; + use ratatui::Terminal; + use ratatui::backend::TestBackend; + + fn synthetic_instance(name: &str) -> InstanceConfig { + // last_played intentionally None so the rendered text is the + // deterministic "Never played" string. anything else would make the + // snapshot drift relative to chrono::Utc::now(). + InstanceConfig { + name: name.to_string(), + game_version: "1.20.1".to_string(), + loader: ModLoader::Vanilla, + loader_version: None, + created: chrono::Utc::now(), + last_played: None, + java_path: None, + memory_max: None, + memory_min: None, + jvm_args: vec![], + resolution: None, + } + } + + #[test] + fn instances_list_renders_three_instances() { + let mut state = State::with_instances(vec![ + synthetic_instance("Vanilla 1.20.1"), + synthetic_instance("Forge Pack"), + synthetic_instance("Fabric Test"), + ]); + + let backend = TestBackend::new(40, 12); + let mut terminal = Terminal::new(backend).unwrap(); + terminal + .draw(|f| render(f, f.area(), FocusedArea::Instances, &mut state)) + .unwrap(); + + insta::assert_snapshot!(terminal.backend()); + } + + #[test] + fn instances_list_renders_empty() { + let mut state = State::with_instances(vec![]); + + let backend = TestBackend::new(40, 8); + let mut terminal = Terminal::new(backend).unwrap(); + terminal + .draw(|f| render(f, f.area(), FocusedArea::Instances, &mut state)) + .unwrap(); + + insta::assert_snapshot!(terminal.backend()); + } } diff --git a/src/tui/widgets/popups/import_modpack/render.rs b/src/tui/widgets/popups/import_modpack/render.rs index a724951..fffe8cc 100644 --- a/src/tui/widgets/popups/import_modpack/render.rs +++ b/src/tui/widgets/popups/import_modpack/render.rs @@ -238,3 +238,45 @@ fn step_keybinds(state: &ImportWizardState) -> Line<'static> { ImportStep::Confirm => keybind_line(&[("h", " back"), ("Enter", " import")]), } } + +#[cfg(test)] +mod tests { + use super::*; + use ratatui::Terminal; + use ratatui::backend::TestBackend; + + // serialise against parallel tests of the same global IMPORT_STATE. + static TEST_SERIAL: std::sync::Mutex<()> = std::sync::Mutex::new(()); + + fn reset_import_state(step: ImportStep) { + let mut guard = IMPORT_STATE.lock().expect("IMPORT_STATE lock"); + *guard = ImportWizardState::default(); + guard.step = step; + } + + #[test] + fn import_modpack_renders_input_step() { + let _serial = TEST_SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + reset_import_state(ImportStep::Input); + + let backend = TestBackend::new(60, 12); + let mut terminal = Terminal::new(backend).unwrap(); + terminal + .draw(|f| render(f, f.area(), FocusedArea::ImportPopup)) + .unwrap(); + insta::assert_snapshot!(terminal.backend()); + } + + #[test] + fn import_modpack_renders_fetching_step() { + let _serial = TEST_SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + reset_import_state(ImportStep::Fetching); + + let backend = TestBackend::new(60, 12); + let mut terminal = Terminal::new(backend).unwrap(); + terminal + .draw(|f| render(f, f.area(), FocusedArea::ImportPopup)) + .unwrap(); + insta::assert_snapshot!(terminal.backend()); + } +} diff --git a/src/tui/widgets/popups/import_modpack/snapshots/rmcl__tui__widgets__popups__import_modpack__render__tests__import_modpack_renders_fetching_step.snap b/src/tui/widgets/popups/import_modpack/snapshots/rmcl__tui__widgets__popups__import_modpack__render__tests__import_modpack_renders_fetching_step.snap new file mode 100644 index 0000000..8e67bea --- /dev/null +++ b/src/tui/widgets/popups/import_modpack/snapshots/rmcl__tui__widgets__popups__import_modpack__render__tests__import_modpack_renders_fetching_step.snap @@ -0,0 +1,16 @@ +--- +source: src/tui/widgets/popups/import_modpack/render.rs +expression: terminal.backend() +--- +"╭Import Modpack────────────────────────────────────────────╮" +"│Fetching modpack info... │" +"│ │" +"│ │" +"│ │" +"│ │" +"│ │" +"│ │" +"│ │" +"│ │" +"│ │" +"╰──────────────────────────────────────────────[Esc] cancel╯" diff --git a/src/tui/widgets/popups/import_modpack/snapshots/rmcl__tui__widgets__popups__import_modpack__render__tests__import_modpack_renders_input_step.snap b/src/tui/widgets/popups/import_modpack/snapshots/rmcl__tui__widgets__popups__import_modpack__render__tests__import_modpack_renders_input_step.snap new file mode 100644 index 0000000..1832105 --- /dev/null +++ b/src/tui/widgets/popups/import_modpack/snapshots/rmcl__tui__widgets__popups__import_modpack__render__tests__import_modpack_renders_input_step.snap @@ -0,0 +1,16 @@ +--- +source: src/tui/widgets/popups/import_modpack/render.rs +expression: terminal.backend() +--- +"╭Import Modpack────────────────────────────────────────────╮" +"│URL, slug, or pack file path...█ │" +"│ │" +"│ │" +"│ │" +"│ │" +"│ │" +"│ │" +"│ │" +"│ │" +"│ │" +"╰─────────────────────────────────────────────[Enter] fetch╯" diff --git a/src/tui/widgets/popups/new_instance/render.rs b/src/tui/widgets/popups/new_instance/render.rs index 0a217dc..9ee6db7 100644 --- a/src/tui/widgets/popups/new_instance/render.rs +++ b/src/tui/widgets/popups/new_instance/render.rs @@ -324,3 +324,51 @@ fn render_confirm_step(state: &WizardState, area: Rect, buf: &mut ratatui::buffe .wrap(Wrap { trim: true }) .render(area, buf); } + +#[cfg(test)] +mod tests { + use super::*; + use ratatui::Terminal; + use ratatui::backend::TestBackend; + + // WIZARD_STATE is a process-global static; without serialisation, parallel + // tests would race when each test sets the step and then renders, since + // render re-acquires the WIZARD_STATE mutex internally. this guard mutex + // ensures only one wizard snapshot test runs at a time. + static TEST_SERIAL: std::sync::Mutex<()> = std::sync::Mutex::new(()); + + fn reset_wizard_state(step: WizardStep) { + let mut guard = WIZARD_STATE.lock().expect("WIZARD_STATE lock"); + *guard = WizardState::default(); + guard.step = step; + } + + #[test] + fn new_instance_renders_name_step() { + let _serial = TEST_SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + // Name is the default step; render touches no network helpers. + reset_wizard_state(WizardStep::Name); + + let backend = TestBackend::new(60, 12); + let mut terminal = Terminal::new(backend).unwrap(); + terminal + .draw(|f| render(f, f.area(), FocusedArea::Popup)) + .unwrap(); + insta::assert_snapshot!(terminal.backend()); + } + + #[test] + fn new_instance_renders_loader_step() { + let _serial = TEST_SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + // Loader step is reached after Name; render just paints the hardcoded + // loader list, no network. + reset_wizard_state(WizardStep::Loader); + + let backend = TestBackend::new(60, 12); + let mut terminal = Terminal::new(backend).unwrap(); + terminal + .draw(|f| render(f, f.area(), FocusedArea::Popup)) + .unwrap(); + insta::assert_snapshot!(terminal.backend()); + } +} diff --git a/src/tui/widgets/popups/new_instance/snapshots/rmcl__tui__widgets__popups__new_instance__render__tests__new_instance_renders_loader_step.snap b/src/tui/widgets/popups/new_instance/snapshots/rmcl__tui__widgets__popups__new_instance__render__tests__new_instance_renders_loader_step.snap new file mode 100644 index 0000000..2d4e976 --- /dev/null +++ b/src/tui/widgets/popups/new_instance/snapshots/rmcl__tui__widgets__popups__new_instance__render__tests__new_instance_renders_loader_step.snap @@ -0,0 +1,16 @@ +--- +source: src/tui/widgets/popups/new_instance/render.rs +expression: terminal.backend() +--- +"╭New Instance──────────────────────────────────────────────╮" +"│▶ Vanilla │" +"│ Fabric │" +"│ Forge │" +"│ NeoForge │" +"│ Quilt │" +"│ │" +"│ │" +"│ │" +"│ │" +"│ │" +"╰──────────────────────────────────[h] back [Enter] select╯" diff --git a/src/tui/widgets/popups/new_instance/snapshots/rmcl__tui__widgets__popups__new_instance__render__tests__new_instance_renders_name_step.snap b/src/tui/widgets/popups/new_instance/snapshots/rmcl__tui__widgets__popups__new_instance__render__tests__new_instance_renders_name_step.snap new file mode 100644 index 0000000..f1363da --- /dev/null +++ b/src/tui/widgets/popups/new_instance/snapshots/rmcl__tui__widgets__popups__new_instance__render__tests__new_instance_renders_name_step.snap @@ -0,0 +1,16 @@ +--- +source: src/tui/widgets/popups/new_instance/render.rs +expression: terminal.backend() +--- +"╭New Instance──────────────────────────────────────────────╮" +"│Instance name...█ │" +"│ │" +"│ │" +"│ │" +"│ │" +"│ │" +"│ │" +"│ │" +"│ │" +"│ │" +"╰──────────────────────────────────────────[Enter] continue╯" diff --git a/src/tui/widgets/snapshots/rmcl__tui__widgets__instances__tests__instances_list_renders_empty.snap b/src/tui/widgets/snapshots/rmcl__tui__widgets__instances__tests__instances_list_renders_empty.snap new file mode 100644 index 0000000..6ffe0b6 --- /dev/null +++ b/src/tui/widgets/snapshots/rmcl__tui__widgets__instances__tests__instances_list_renders_empty.snap @@ -0,0 +1,12 @@ +--- +source: src/tui/widgets/instances.rs +expression: terminal.backend() +--- +"╭Instances─────────────────────────────╮" +"│ │" +"│ │" +"│ │" +"│ │" +"│ │" +"│ │" +"╰──────────────────────────────────────╯" diff --git a/src/tui/widgets/snapshots/rmcl__tui__widgets__instances__tests__instances_list_renders_three_instances.snap b/src/tui/widgets/snapshots/rmcl__tui__widgets__instances__tests__instances_list_renders_three_instances.snap new file mode 100644 index 0000000..69020ed --- /dev/null +++ b/src/tui/widgets/snapshots/rmcl__tui__widgets__instances__tests__instances_list_renders_three_instances.snap @@ -0,0 +1,16 @@ +--- +source: src/tui/widgets/instances.rs +expression: terminal.backend() +--- +"╭Instances─────────────────────────────╮" +"│▌ Vanilla 1.20.1 ▲" +"│▌ Never played ║" +"│ Forge Pack ║" +"│ Never played ║" +"│ Fabric Test ║" +"│ Never played ║" +"│ ║" +"│ ║" +"│ │" +"│ ▼" +"╰──────────────────────────────────────╯" From 8d7a0903fd661f1b15f78ae7d1f6d8599e5a418b Mon Sep 17 00:00:00 2001 From: objz Date: Wed, 27 May 2026 17:35:50 +0200 Subject: [PATCH 15/20] refactored: DRY repetitive test fixtures with owning struct + rstest Picks up the remaining test-only suggestions from the style audit. No production code change. - launch_profile/templates.rs: introduces a Fixture struct that owns the four PathBuf inputs (lib/nat/game/assets) and exposes a ctx() method. Eight tests that each rebuilt the same context inline now collapse into one rstest with eight cases plus two standalone tests for the recursive-substitution and Windows-backslash edge cases. Net code: ~120 lines saved. - launch_profile/render.rs: same pattern. Fixture::new() owns the paths plus a FeatureSet; ctx() and rule_ctx() expose what every test needs. Six tests stop redeclaring four PathBufs + a five-line RuleContext literal apiece. - instance/launch/mod.rs: three installer_version_dir_name tests (Forge / NeoForge / non-installer loaders) become one rstest with five cases (one per ModLoader variant). A regression that misorders the match arms would now fail a specific case, not just the catch-all "non-installer" test. - instance/content/resource_packs.rs: ten extract_description_* tests become one rstest with ten cases. Each case still hits a distinct match arm (string, object{text}, object{no text}, array variants, null, number, bool); the rstest is cosmetic, not a consolidation that loses coverage. Net effect: same coverage, ~250 lines less repetitive test setup, clearer intent. Test count rises by 2 because rstest expands cases into separate test functions. --- src/instance/content/resource_packs.rs | 76 ++------- src/instance/launch/mod.rs | 36 ++-- src/launch_profile/render.rs | 190 ++++++++------------- src/launch_profile/templates.rs | 222 ++++++++----------------- 4 files changed, 174 insertions(+), 350 deletions(-) diff --git a/src/instance/content/resource_packs.rs b/src/instance/content/resource_packs.rs index cbaaa0e..a308426 100644 --- a/src/instance/content/resource_packs.rs +++ b/src/instance/content/resource_packs.rs @@ -141,64 +141,24 @@ fn read_pack_metadata_from_dir(dir: &Path) -> (String, String, Option>) #[cfg(test)] mod tests { use super::*; + use serde_json::json; - #[test] - fn extract_description_from_string() { - let val = serde_json::json!("Simple pack"); - assert_eq!(extract_description(&val), "Simple pack"); - } - - #[test] - fn extract_description_from_object_with_text() { - let val = serde_json::json!({"text": "Hello world"}); - assert_eq!(extract_description(&val), "Hello world"); - } - - #[test] - fn extract_description_from_object_without_text() { - let val = serde_json::json!({"color": "red"}); - assert_eq!(extract_description(&val), ""); - } - - #[test] - fn extract_description_from_array_of_strings() { - let val = serde_json::json!(["Hello", " ", "world"]); - assert_eq!(extract_description(&val), "Hello world"); - } - - #[test] - fn extract_description_from_array_of_objects() { - let val = serde_json::json!([{"text": "A"}, {"text": "B"}]); - assert_eq!(extract_description(&val), "AB"); - } - - #[test] - fn extract_description_from_mixed_array() { - let val = serde_json::json!(["Prefix ", {"text": "suffix"}]); - assert_eq!(extract_description(&val), "Prefix suffix"); - } - - #[test] - fn extract_description_from_empty_array() { - let val = serde_json::json!([]); - assert_eq!(extract_description(&val), ""); - } - - #[test] - fn extract_description_from_null() { - let val = serde_json::Value::Null; - assert_eq!(extract_description(&val), ""); - } - - #[test] - fn extract_description_from_number() { - let val = serde_json::json!(42); - assert_eq!(extract_description(&val), ""); - } - - #[test] - fn extract_description_from_bool() { - let val = serde_json::json!(true); - assert_eq!(extract_description(&val), ""); + // every case exercises a distinct match arm in extract_description. + // string + object{text} + object{no text} + array(string) + + // array(object) + array(mixed) + array(empty) + null + number + bool. + // mutating any arm to fall through to "" would fail at least one case. + #[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); } } diff --git a/src/instance/launch/mod.rs b/src/instance/launch/mod.rs index 474d6d9..83494f5 100644 --- a/src/instance/launch/mod.rs +++ b/src/instance/launch/mod.rs @@ -755,29 +755,27 @@ mod tests { ); } - #[test] - fn installer_version_dir_name_for_forge() { + // 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(ModLoader::Forge, "1.20.1", "47.2.0"), - Some("1.20.1-forge-47.2.0".to_string()) + installer_version_dir_name(loader, game_version, loader_version), + expected.map(str::to_owned) ); } - #[test] - fn installer_version_dir_name_for_neoforge() { - assert_eq!( - installer_version_dir_name(ModLoader::NeoForge, "1.21.1", "21.1.0"), - Some("neoforge-21.1.0".to_string()) - ); - } - - #[test] - fn installer_version_dir_name_for_non_installer_loaders() { - assert!(installer_version_dir_name(ModLoader::Vanilla, "1.20.1", "v").is_none()); - assert!(installer_version_dir_name(ModLoader::Fabric, "1.20.1", "0.14.21").is_none()); - assert!(installer_version_dir_name(ModLoader::Quilt, "1.20.1", "0.20.0").is_none()); - } - // exercises the modern-profile early-return in // migrate_legacy_loader_profile_if_needed. any of inheritsFrom, // arguments, minecraftArguments present (or game_arguments absent) diff --git a/src/launch_profile/render.rs b/src/launch_profile/render.rs index a75e14c..db9fd3e 100644 --- a/src/launch_profile/render.rs +++ b/src/launch_profile/render.rs @@ -85,31 +85,59 @@ mod tests { use crate::launch_profile::rules::{FeatureSet, OsCondition, Rule, RuleAction}; use std::path::PathBuf; - fn template_fixture<'a>( - library_directory: &'a std::path::Path, - natives_directory: &'a std::path::Path, - game_directory: &'a std::path::Path, - assets_root: &'a std::path::Path, - ) -> TemplateContext<'a> { - TemplateContext { - library_directory, - classpath_separator: ":", - version_name: "1.20.1", - version_type: "release", - natives_directory, - classpath: "a.jar:b.jar", - game_directory, - assets_root, - 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: "0.3.0", - clientid: "0", + // owns the path buffers + FeatureSet so each test just calls + // fx.template_ctx() and fx.rule_ctx() instead of declaring four PathBufs + // and a RuleContext inline. all tests use linux/x86_64; if a test needs + // a different OS it sets it explicitly. + struct Fixture { + lib: PathBuf, + nat: PathBuf, + game: PathBuf, + assets: PathBuf, + features: FeatureSet, + } + + impl Fixture { + fn new() -> Self { + Self { + lib: PathBuf::from("/m/libraries"), + nat: PathBuf::from("/m/natives"), + game: PathBuf::from("/i/.minecraft"), + assets: PathBuf::from("/m/assets"), + features: FeatureSet::default(), + } + } + + fn template_ctx(&self) -> TemplateContext<'_> { + TemplateContext { + library_directory: &self.lib, + classpath_separator: ":", + version_name: "1.20.1", + version_type: "release", + natives_directory: &self.nat, + classpath: "a.jar:b.jar", + game_directory: &self.game, + assets_root: &self.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: "0.3.0", + clientid: "0", + } + } + + fn rule_ctx(&self) -> RuleContext<'_> { + RuleContext { + os_name: "linux", + os_version: "6.0", + arch: "x86_64", + features: &self.features, + } } } @@ -123,24 +151,12 @@ mod tests { #[test] fn legacy_minecraft_arguments_render_into_game() { - let lib = PathBuf::from("/m/libraries"); - let nat = PathBuf::from("/m/natives"); - let game = PathBuf::from("/i/.minecraft"); - let assets = PathBuf::from("/m/assets"); - let template_ctx = template_fixture(&lib, &nat, &game, &assets); - let features = FeatureSet::default(); - let rule_ctx = RuleContext { - os_name: "linux", - os_version: "6.0", - arch: "x86_64", - features: &features, - }; - + let fx = Fixture::new(); let mut profile = minimal_profile(); profile.minecraft_arguments = Some("--username ${auth_player_name} --version ${version_name}".into()); - let rendered = render_args(&profile, &rule_ctx, &template_ctx).unwrap(); + let rendered = render_args(&profile, &fx.rule_ctx(), &fx.template_ctx()).unwrap(); assert_eq!(rendered.main_class, "net.test.Main"); assert!(rendered.jvm.is_empty()); assert_eq!( @@ -151,19 +167,7 @@ mod tests { #[test] fn modern_arguments_render_with_literals_and_substitutions() { - let lib = PathBuf::from("/m/libraries"); - let nat = PathBuf::from("/m/natives"); - let game = PathBuf::from("/i/.minecraft"); - let assets = PathBuf::from("/m/assets"); - let template_ctx = template_fixture(&lib, &nat, &game, &assets); - let features = FeatureSet::default(); - let rule_ctx = RuleContext { - os_name: "linux", - os_version: "6.0", - arch: "x86_64", - features: &features, - }; - + let fx = Fixture::new(); let mut profile = minimal_profile(); profile.arguments = Some(Arguments { game: vec![ @@ -175,26 +179,14 @@ mod tests { )], }); - let rendered = render_args(&profile, &rule_ctx, &template_ctx).unwrap(); + let rendered = render_args(&profile, &fx.rule_ctx(), &fx.template_ctx()).unwrap(); assert_eq!(rendered.game, vec!["--username", "Player"]); assert_eq!(rendered.jvm, vec!["-Djava.library.path=/m/natives"]); } #[test] fn conditional_argument_with_single_value_is_filtered_by_os_rule() { - let lib = PathBuf::from("/m/libraries"); - let nat = PathBuf::from("/m/natives"); - let game = PathBuf::from("/i/.minecraft"); - let assets = PathBuf::from("/m/assets"); - let template_ctx = template_fixture(&lib, &nat, &game, &assets); - let features = FeatureSet::default(); - let rule_ctx = RuleContext { - os_name: "linux", - os_version: "6.0", - arch: "x86_64", - features: &features, - }; - + let fx = Fixture::new(); let osx_only = Argument::Conditional { rules: vec![Rule { action: RuleAction::Allow, @@ -214,7 +206,7 @@ mod tests { jvm: vec![osx_only], }); - let rendered = render_args(&profile, &rule_ctx, &template_ctx).unwrap(); + let rendered = render_args(&profile, &fx.rule_ctx(), &fx.template_ctx()).unwrap(); assert!( rendered.jvm.is_empty(), "osx-only arg should be skipped on linux" @@ -223,19 +215,7 @@ mod tests { #[test] fn conditional_argument_with_multiple_value_pushes_all() { - let lib = PathBuf::from("/m/libraries"); - let nat = PathBuf::from("/m/natives"); - let game = PathBuf::from("/i/.minecraft"); - let assets = PathBuf::from("/m/assets"); - let template_ctx = template_fixture(&lib, &nat, &game, &assets); - let features = FeatureSet::default(); - let rule_ctx = RuleContext { - os_name: "linux", - os_version: "6.0", - arch: "x86_64", - features: &features, - }; - + let fx = Fixture::new(); let linux_arg = Argument::Conditional { rules: vec![Rule { action: RuleAction::Allow, @@ -258,7 +238,7 @@ mod tests { jvm: vec![linux_arg], }); - let rendered = render_args(&profile, &rule_ctx, &template_ctx).unwrap(); + let rendered = render_args(&profile, &fx.rule_ctx(), &fx.template_ctx()).unwrap(); assert_eq!( rendered.jvm, vec!["--add-opens", "java.base/sun.security.util=ALL-UNNAMED"] @@ -267,23 +247,11 @@ mod tests { #[test] fn missing_main_class_returns_error() { - let lib = PathBuf::from("/m/libraries"); - let nat = PathBuf::from("/m/natives"); - let game = PathBuf::from("/i/.minecraft"); - let assets = PathBuf::from("/m/assets"); - let template_ctx = template_fixture(&lib, &nat, &game, &assets); - let features = FeatureSet::default(); - let rule_ctx = RuleContext { - os_name: "linux", - os_version: "6.0", - arch: "x86_64", - features: &features, - }; - + let fx = Fixture::new(); let mut profile = minimal_profile(); profile.main_class = None; - let result = render_args(&profile, &rule_ctx, &template_ctx); + let result = render_args(&profile, &fx.rule_ctx(), &fx.template_ctx()); assert!(matches!(result, Err(RenderError::MissingMainClass))); } @@ -340,20 +308,8 @@ mod tests { let merged = resolve::resolve(loader_profile, tmp.path()).await.unwrap(); - let lib = PathBuf::from("/m/libraries"); - let nat = PathBuf::from("/m/natives"); - let game = PathBuf::from("/i/.minecraft"); - let assets = PathBuf::from("/m/assets"); - let template_ctx = template_fixture(&lib, &nat, &game, &assets); - let features = FeatureSet::default(); - let rule_ctx = RuleContext { - os_name: "linux", - os_version: "6.0", - arch: "x86_64", - features: &features, - }; - - let rendered = render_args(&merged, &rule_ctx, &template_ctx).unwrap(); + let fx = Fixture::new(); + let rendered = render_args(&merged, &fx.rule_ctx(), &fx.template_ctx()).unwrap(); // child main_class wins after merge assert_eq!( @@ -387,19 +343,7 @@ mod tests { fn modern_arguments_takes_precedence_over_legacy_field() { // a profile that somehow has both arguments and minecraft_arguments // should use arguments only (legacy is fallback). - let lib = PathBuf::from("/m/libraries"); - let nat = PathBuf::from("/m/natives"); - let game = PathBuf::from("/i/.minecraft"); - let assets = PathBuf::from("/m/assets"); - let template_ctx = template_fixture(&lib, &nat, &game, &assets); - let features = FeatureSet::default(); - let rule_ctx = RuleContext { - os_name: "linux", - os_version: "6.0", - arch: "x86_64", - features: &features, - }; - + let fx = Fixture::new(); let mut profile = minimal_profile(); profile.arguments = Some(Arguments { game: vec![Argument::Literal("--from-arguments".into())], @@ -407,7 +351,7 @@ mod tests { }); profile.minecraft_arguments = Some("--from-legacy".into()); - let rendered = render_args(&profile, &rule_ctx, &template_ctx).unwrap(); + let rendered = render_args(&profile, &fx.rule_ctx(), &fx.template_ctx()).unwrap(); assert_eq!(rendered.game, vec!["--from-arguments"]); } } diff --git a/src/launch_profile/templates.rs b/src/launch_profile/templates.rs index 4d53058..b535315 100644 --- a/src/launch_profile/templates.rs +++ b/src/launch_profile/templates.rs @@ -101,158 +101,84 @@ mod tests { use super::*; use std::path::PathBuf; - fn ctx_fixture<'a>( - library_directory: &'a Path, - natives_directory: &'a Path, - game_directory: &'a Path, - assets_root: &'a Path, - ) -> TemplateContext<'a> { - TemplateContext { - library_directory, - classpath_separator: ":", - version_name: "1.20.1", - version_type: "release", - natives_directory, - classpath: "a.jar:b.jar", - game_directory, - assets_root, - 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: "0.3.0", - clientid: "0", + // owns the path buffers so tests don't have to declare them inline; the + // ctx() method borrows from self to build a TemplateContext with the + // standard set of values. windows() returns a fixture with backslash + // paths so the OS-independence test stays self-contained. + struct Fixture { + lib: PathBuf, + nat: PathBuf, + game: PathBuf, + assets: PathBuf, + user_properties: String, + } + + impl Fixture { + fn unix() -> Self { + Self { + lib: PathBuf::from("/m/libraries"), + nat: PathBuf::from("/m/natives"), + game: PathBuf::from("/i/.minecraft"), + assets: PathBuf::from("/m/assets"), + user_properties: "{}".to_string(), + } + } + + fn windows() -> Self { + Self { + lib: PathBuf::from(r"C:\Users\test\.minecraft\libraries"), + nat: PathBuf::from(r"C:\Users\test\.minecraft\natives"), + game: PathBuf::from(r"C:\Users\test\.minecraft"), + assets: PathBuf::from(r"C:\Users\test\.minecraft\assets"), + user_properties: "{}".to_string(), + } + } + + fn ctx(&self) -> TemplateContext<'_> { + TemplateContext { + library_directory: &self.lib, + classpath_separator: ":", + version_name: "1.20.1", + version_type: "release", + natives_directory: &self.nat, + classpath: "a.jar:b.jar", + game_directory: &self.game, + assets_root: &self.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: &self.user_properties, + launcher_name: "rmcl", + launcher_version: "0.3.0", + clientid: "0", + } } } - #[test] - fn no_placeholders_unchanged() { - let lib = PathBuf::from("/m/libraries"); - let nat = PathBuf::from("/m/natives"); - let game = PathBuf::from("/i/.minecraft"); - let assets = PathBuf::from("/m/assets"); - let ctx = ctx_fixture(&lib, &nat, &game, &assets); - assert_eq!( - substitute("--add-modules ALL-MODULE-PATH", &ctx), - "--add-modules ALL-MODULE-PATH" - ); - } - - #[test] - fn single_known_substitution() { - let lib = PathBuf::from("/m/libraries"); - let nat = PathBuf::from("/m/natives"); - let game = PathBuf::from("/i/.minecraft"); - let assets = PathBuf::from("/m/assets"); - let ctx = ctx_fixture(&lib, &nat, &game, &assets); - assert_eq!(substitute("v=${version_name}", &ctx), "v=1.20.1"); - } - - #[test] - fn unknown_placeholder_left_as_is() { - let lib = PathBuf::from("/m/libraries"); - let nat = PathBuf::from("/m/natives"); - let game = PathBuf::from("/i/.minecraft"); - let assets = PathBuf::from("/m/assets"); - let ctx = ctx_fixture(&lib, &nat, &game, &assets); - assert_eq!( - substitute("x=${not_a_real_var}y", &ctx), - "x=${not_a_real_var}y" - ); - } - - #[test] - fn unclosed_placeholder_left_as_is() { - let lib = PathBuf::from("/m/libraries"); - let nat = PathBuf::from("/m/natives"); - let game = PathBuf::from("/i/.minecraft"); - let assets = PathBuf::from("/m/assets"); - let ctx = ctx_fixture(&lib, &nat, &game, &assets); - assert_eq!( - substitute("--prefix ${unclosed", &ctx), - "--prefix ${unclosed" - ); - } - - #[test] - fn dollar_without_brace_is_literal() { - let lib = PathBuf::from("/m/libraries"); - let nat = PathBuf::from("/m/natives"); - let game = PathBuf::from("/i/.minecraft"); - let assets = PathBuf::from("/m/assets"); - let ctx = ctx_fixture(&lib, &nat, &game, &assets); - assert_eq!(substitute("$$ literal $5 $", &ctx), "$$ literal $5 $"); - } - - #[test] - fn multiple_substitutions() { - let lib = PathBuf::from("/m/libraries"); - let nat = PathBuf::from("/m/natives"); - let game = PathBuf::from("/i/.minecraft"); - let assets = PathBuf::from("/m/assets"); - let ctx = ctx_fixture(&lib, &nat, &game, &assets); - assert_eq!( - substitute("${version_name}-${auth_player_name}", &ctx), - "1.20.1-Player" - ); - } - - #[test] - fn path_substitution() { - let lib = PathBuf::from("/m/libraries"); - let nat = PathBuf::from("/m/natives"); - let game = PathBuf::from("/i/.minecraft"); - let assets = PathBuf::from("/m/assets"); - let ctx = ctx_fixture(&lib, &nat, &game, &assets); - assert_eq!( - substitute("-DlibraryDirectory=${library_directory}", &ctx), - "-DlibraryDirectory=/m/libraries" - ); + #[rstest::rstest] + #[case::no_placeholders("--add-modules ALL-MODULE-PATH", "--add-modules ALL-MODULE-PATH")] + #[case::single_known("v=${version_name}", "v=1.20.1")] + #[case::unknown_placeholder("x=${not_a_real_var}y", "x=${not_a_real_var}y")] + #[case::unclosed_placeholder("--prefix ${unclosed", "--prefix ${unclosed")] + #[case::dollar_without_brace("$$ literal $5 $", "$$ literal $5 $")] + #[case::multiple("${version_name}-${auth_player_name}", "1.20.1-Player")] + #[case::path("-DlibraryDirectory=${library_directory}", "-DlibraryDirectory=/m/libraries")] + #[case::empty_input("", "")] + fn substitute_handles(#[case] input: &str, #[case] expected: &str) { + let fx = Fixture::unix(); + assert_eq!(substitute(input, &fx.ctx()), expected); } #[test] fn substituted_value_is_not_recursively_substituted() { - // simulate a `user_properties` value that happens to contain a `${...}` + // simulate a user_properties value that happens to contain a ${...} // pattern. it should NOT trigger another substitution pass. - let lib = PathBuf::from("/m/libraries"); - let nat = PathBuf::from("/m/natives"); - let game = PathBuf::from("/i/.minecraft"); - let assets = PathBuf::from("/m/assets"); - let ctx = TemplateContext { - library_directory: &lib, - classpath_separator: ":", - version_name: "1.20.1", - natives_directory: &nat, - classpath: "a.jar:b.jar", - game_directory: &game, - 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: "${version_name}", - launcher_name: "rmcl", - launcher_version: "0.3.0", - clientid: "0", - version_type: "release", - }; - assert_eq!(substitute("${user_properties}", &ctx), "${version_name}"); - } - - #[test] - fn empty_input_is_empty() { - let lib = PathBuf::from("/m/libraries"); - let nat = PathBuf::from("/m/natives"); - let game = PathBuf::from("/i/.minecraft"); - let assets = PathBuf::from("/m/assets"); - let ctx = ctx_fixture(&lib, &nat, &game, &assets); - assert_eq!(substitute("", &ctx), ""); + let mut fx = Fixture::unix(); + fx.user_properties = "${version_name}".to_string(); + assert_eq!(substitute("${user_properties}", &fx.ctx()), "${version_name}"); } #[test] @@ -261,12 +187,8 @@ mod tests { // backslashes. the substitution must not interpret backslashes as // escape sequences or do anything else clever - it just copies the // value into the output. - let lib = PathBuf::from(r"C:\Users\test\.minecraft\libraries"); - let nat = PathBuf::from(r"C:\Users\test\.minecraft\natives"); - let game = PathBuf::from(r"C:\Users\test\.minecraft"); - let assets = PathBuf::from(r"C:\Users\test\.minecraft\assets"); - let ctx = ctx_fixture(&lib, &nat, &game, &assets); - let result = substitute("-Dpath=${library_directory}", &ctx); + let fx = Fixture::windows(); + let result = substitute("-Dpath=${library_directory}", &fx.ctx()); assert!( result.contains(r"C:\Users\test\.minecraft\libraries"), "expected backslashes preserved, got: {result}" From d612f83446bf302c26186db593891720bfffa2ca Mon Sep 17 00:00:00 2001 From: objz Date: Wed, 27 May 2026 17:42:14 +0200 Subject: [PATCH 16/20] refactored: address final review punch list Final-review pass flagged three items. All addressed: - src/instance/loader/mod.rs: rename and rewrite the two profile-shape tests so the test name matches what the body does. legacy_forge_version_info_round_trips_through_save_profile_json was misleading; the body never called save_installer_profile, it only wrote bytes to disk and read them back. Renamed to legacy_forge_version_info_deserialises_as_launch_profile and dropped the filesystem dance - the test was only ever verifying serde shape on the literal byte string. raw_fabric_profile_bytes_parse_as_launch_profile got the same treatment for consistency: dropped the TempDir + write + read round trip since the test only checks deserialisation. - src/tui/error_buffer.rs: removed has_errors_after_push. The test read global state populated by other tests in the same module, so it would still pass if push_error were a no-op. The push semantics are properly covered by peek_all_returns_newest_first and overflow_drops_oldest, both of which use unique tagged messages to isolate from cross-test interference. --- src/instance/loader/mod.rs | 74 ++++++++++++-------------------------- src/tui/error_buffer.rs | 6 ---- 2 files changed, 22 insertions(+), 58 deletions(-) diff --git a/src/instance/loader/mod.rs b/src/instance/loader/mod.rs index ab6378f..655b186 100644 --- a/src/instance/loader/mod.rs +++ b/src/instance/loader/mod.rs @@ -181,17 +181,13 @@ mod tests { ); } + // 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_round_trips_through_save_profile_json() { - use tempfile::TempDir; - let tmp = TempDir::new().unwrap(); - let meta_dir = tmp.path().to_path_buf(); - - // synthetic versionInfo shape from a 1.7.10 forge install_profile.json. - // legacy forge uses minecraftArguments (the flat string format) and - // typically omits inheritsFrom (the launch flow's implicit fallback - // handles that). - let version_info = serde_json::json!({ + 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", @@ -199,35 +195,18 @@ mod tests { { "name": "net.minecraftforge:forge:10.13.4.1614", "url": "http://files.minecraftforge.net/maven/" }, { "name": "net.minecraft:launchwrapper:1.9" } ] - }); + }"#; - // mirror the install path: write versionInfo as compact JSON. - let profiles_dir = meta_dir.join("loader-profiles"); - std::fs::create_dir_all(&profiles_dir).unwrap(); - let serialized = serde_json::to_vec(&version_info).unwrap(); - std::fs::write( - profiles_dir.join("forge-1.7.10-10.13.4.1614.json"), - &serialized, - ) - .unwrap(); - - let saved_bytes = std::fs::read( - meta_dir - .join("loader-profiles") - .join("forge-1.7.10-10.13.4.1614.json"), - ) - .unwrap(); - - // the cached profile must parse as a LaunchProfile so the launch - // flow's render_args + resolve pipeline can consume it. let profile: crate::launch_profile::model::LaunchProfile = - serde_json::from_slice(&saved_bytes).unwrap(); + 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") ); - assert!(profile.inherits_from.is_none()); // launch flow's implicit fallback adds it + // 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 @@ -244,21 +223,18 @@ mod tests { profile.libraries[0].url.as_deref(), Some("http://files.minecraftforge.net/maven/") ); - // legacy libs typically have no `downloads.artifact` - they're - // resolved at launch time via maven_coord_to_path(name). + // 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() { - use tempfile::TempDir; - let tmp = TempDir::new().unwrap(); - let meta_dir = tmp.path(); - - // a synthetic upstream fabric profile shape (id, mainClass, - // libraries with name+url, no inheritsFrom, no arguments). - // simulates what the install path will write verbatim. - let upstream_bytes = br#"{ + let bytes = br#"{ "id": "fabric-loader-0.14.21-1.20.1", "mainClass": "net.fabricmc.loader.impl.launch.knot.KnotClient", "libraries": [ @@ -267,22 +243,16 @@ mod tests { ] }"#; - let profiles_dir = meta_dir.join("loader-profiles"); - std::fs::create_dir_all(&profiles_dir).unwrap(); - let profile_path = profiles_dir.join("fabric-1.20.1-0.14.21.json"); - std::fs::write(&profile_path, upstream_bytes).unwrap(); - - let saved = std::fs::read(&profile_path).unwrap(); - assert_eq!(saved, upstream_bytes.to_vec()); - let parsed: crate::launch_profile::model::LaunchProfile = - serde_json::from_slice(&saved).unwrap(); + 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") ); - assert!(parsed.inherits_from.is_none()); // launch flow's implicit fallback handles it + // 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!( diff --git a/src/tui/error_buffer.rs b/src/tui/error_buffer.rs index ab8d0f9..84c03dd 100644 --- a/src/tui/error_buffer.rs +++ b/src/tui/error_buffer.rs @@ -89,12 +89,6 @@ mod tests { } } - #[test] - fn has_errors_after_push() { - push_error(make_event("err_has")); - assert!(has_errors()); - } - #[test] fn peek_does_not_remove() { push_error(make_event("err_peek")); From 0d1b7984fc2a467a3abff9f5697a89d6e6f4fb8b Mon Sep 17 00:00:00 2001 From: objz Date: Wed, 27 May 2026 18:03:57 +0200 Subject: [PATCH 17/20] added: deferred tests-only items (extra wizard snapshots + library/asset downloads) Closes the "zero production touches" subset of the deferred coverage items the audit had flagged. - src/tui/widgets/popups/new_instance/render.rs: three new snapshots for the Version, LoaderVersion, and Confirm steps. Each pre-populates WIZARD_STATE so ensure_versions_loaded and ensure_loader_versions_loaded short-circuit on LoadState::Loaded and never spawn a network task. The TEST_SERIAL mutex established in the earlier batch serialises against the existing Name/Loader snapshots. - src/tui/widgets/popups/import_modpack/render.rs: two new snapshots for the Version step (synthetic VersionInfo entries) and the Confirm step (synthetic ImportSummary). Same serialisation pattern. - tests/net_mojang.rs: three new wiremock tests. download_libraries_writes_artifact_to_meta_dir constructs a synthetic VersionMeta whose single library points at the wiremock server, then asserts the bytes land at meta_dir/libraries/. download_libraries_skips_when_destination_exists verifies the cache hit path via wiremock's expect(0). download_assets_writes_index_when_objects_is_empty exercises the index fetch+write code path with an empty objects map so the per-asset download loop never fires. Zero production touches. download_libraries already takes a VersionMeta whose libraries carry their own URLs; download_assets' index fetch reads from meta.asset_index.url (also configurable per-call), so the empty-objects path doesn't need ASSETS_BASE_URL overridable. Full per-asset coverage lands in a separate commit. --- .../widgets/popups/import_modpack/render.rs | 76 ++++++++ ...__import_modpack_renders_confirm_step.snap | 18 ++ ...__import_modpack_renders_version_step.snap | 18 ++ src/tui/widgets/popups/new_instance/render.rs | 100 +++++++++++ ...ts__new_instance_renders_confirm_step.snap | 16 ++ ..._instance_renders_loader_version_step.snap | 18 ++ ...ts__new_instance_renders_version_step.snap | 18 ++ tests/net_mojang.rs | 168 +++++++++++++++++- 8 files changed, 431 insertions(+), 1 deletion(-) create mode 100644 src/tui/widgets/popups/import_modpack/snapshots/rmcl__tui__widgets__popups__import_modpack__render__tests__import_modpack_renders_confirm_step.snap create mode 100644 src/tui/widgets/popups/import_modpack/snapshots/rmcl__tui__widgets__popups__import_modpack__render__tests__import_modpack_renders_version_step.snap create mode 100644 src/tui/widgets/popups/new_instance/snapshots/rmcl__tui__widgets__popups__new_instance__render__tests__new_instance_renders_confirm_step.snap create mode 100644 src/tui/widgets/popups/new_instance/snapshots/rmcl__tui__widgets__popups__new_instance__render__tests__new_instance_renders_loader_version_step.snap create mode 100644 src/tui/widgets/popups/new_instance/snapshots/rmcl__tui__widgets__popups__new_instance__render__tests__new_instance_renders_version_step.snap diff --git a/src/tui/widgets/popups/import_modpack/render.rs b/src/tui/widgets/popups/import_modpack/render.rs index fffe8cc..6185604 100644 --- a/src/tui/widgets/popups/import_modpack/render.rs +++ b/src/tui/widgets/popups/import_modpack/render.rs @@ -279,4 +279,80 @@ mod tests { .unwrap(); insta::assert_snapshot!(terminal.backend()); } + + // Version step: pre-populate versions as LoadState::Loaded with synthetic + // VersionInfo entries so render walks the list path without triggering + // any network helpers. + #[test] + fn import_modpack_renders_version_step() { + use crate::net::modrinth::VersionInfo; + + let _serial = TEST_SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + { + let mut guard = IMPORT_STATE.lock().expect("IMPORT_STATE lock"); + *guard = ImportWizardState::default(); + guard.step = ImportStep::Version; + guard.project_title = Some("Synthetic Pack".into()); + guard.versions = LoadState::Loaded(vec![ + VersionInfo { + id: "v1".into(), + name: "1.0.0".into(), + version_number: "1.0.0".into(), + game_versions: vec!["1.20.1".into()], + loaders: vec!["fabric".into()], + files: vec![], + }, + VersionInfo { + id: "v2".into(), + name: "0.9.0".into(), + version_number: "0.9.0".into(), + game_versions: vec!["1.20.1".into()], + loaders: vec!["fabric".into()], + files: vec![], + }, + ]); + } + + let backend = TestBackend::new(60, 14); + let mut terminal = Terminal::new(backend).unwrap(); + terminal + .draw(|f| render(f, f.area(), FocusedArea::ImportPopup)) + .unwrap(); + insta::assert_snapshot!(terminal.backend()); + } + + // Confirm step: needs a populated ImportSummary so the render path + // doesn't bail. ImportSummary is constructed manually with synthetic + // values; archive_path is a fake tempdir-ish path that never gets read. + #[test] + fn import_modpack_renders_confirm_step() { + use crate::instance::import::{ImportSummary, PackFormat}; + use crate::instance::models::ModLoader; + use std::path::PathBuf; + + let _serial = TEST_SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + { + let mut guard = IMPORT_STATE.lock().expect("IMPORT_STATE lock"); + *guard = ImportWizardState::default(); + guard.step = ImportStep::Confirm; + guard.summary = Some(ImportSummary { + name: "Synthetic Pack".into(), + pack_version: "1.0.0".into(), + game_version: "1.20.1".into(), + loader: ModLoader::Fabric, + loader_version: Some("0.15.0".into()), + mod_count: 42, + override_count: 3, + format: PackFormat::Mrpack, + archive_path: PathBuf::from("/tmp/synthetic.mrpack"), + }); + } + + let backend = TestBackend::new(60, 14); + let mut terminal = Terminal::new(backend).unwrap(); + terminal + .draw(|f| render(f, f.area(), FocusedArea::ImportPopup)) + .unwrap(); + insta::assert_snapshot!(terminal.backend()); + } } diff --git a/src/tui/widgets/popups/import_modpack/snapshots/rmcl__tui__widgets__popups__import_modpack__render__tests__import_modpack_renders_confirm_step.snap b/src/tui/widgets/popups/import_modpack/snapshots/rmcl__tui__widgets__popups__import_modpack__render__tests__import_modpack_renders_confirm_step.snap new file mode 100644 index 0000000..e569091 --- /dev/null +++ b/src/tui/widgets/popups/import_modpack/snapshots/rmcl__tui__widgets__popups__import_modpack__render__tests__import_modpack_renders_confirm_step.snap @@ -0,0 +1,18 @@ +--- +source: src/tui/widgets/popups/import_modpack/render.rs +expression: terminal.backend() +--- +"╭Import Modpack────────────────────────────────────────────╮" +"│Name: Synthetic Pack │" +"│Pack Version: 1.0.0 │" +"│MC Version: 1.20.1 │" +"│Loader: Fabric 0.15.0 │" +"│Mods: 42 files │" +"│Overrides: 3 files │" +"│ │" +"│ │" +"│ │" +"│ │" +"│ │" +"│ │" +"╰──────────────────────────────────[h] back [Enter] import╯" diff --git a/src/tui/widgets/popups/import_modpack/snapshots/rmcl__tui__widgets__popups__import_modpack__render__tests__import_modpack_renders_version_step.snap b/src/tui/widgets/popups/import_modpack/snapshots/rmcl__tui__widgets__popups__import_modpack__render__tests__import_modpack_renders_version_step.snap new file mode 100644 index 0000000..e569689 --- /dev/null +++ b/src/tui/widgets/popups/import_modpack/snapshots/rmcl__tui__widgets__popups__import_modpack__render__tests__import_modpack_renders_version_step.snap @@ -0,0 +1,18 @@ +--- +source: src/tui/widgets/popups/import_modpack/render.rs +expression: terminal.backend() +--- +"╭Import Modpack────────────────────────────────────────────╮" +"│▶ 1.0.0 1.20.1 fabric │" +"│ 0.9.0 1.20.1 fabric │" +"│ │" +"│ │" +"│ │" +"│ │" +"│ │" +"│ │" +"│ │" +"│ │" +"│ │" +"│ │" +"╰──────────────────────[/] search [h] back [Enter] select╯" diff --git a/src/tui/widgets/popups/new_instance/render.rs b/src/tui/widgets/popups/new_instance/render.rs index 9ee6db7..70a657a 100644 --- a/src/tui/widgets/popups/new_instance/render.rs +++ b/src/tui/widgets/popups/new_instance/render.rs @@ -371,4 +371,104 @@ mod tests { .unwrap(); insta::assert_snapshot!(terminal.backend()); } + + // Version step: pre-populate versions as LoadState::Loaded so + // ensure_versions_loaded short-circuits and never spawns a network task. + // the three synthetic versions are marked stable=true so they show with + // show_snapshots=false (the default). + #[test] + fn new_instance_renders_version_step() { + use crate::instance::loader::GameVersion; + + let _serial = TEST_SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + { + let mut guard = WIZARD_STATE.lock().expect("WIZARD_STATE lock"); + *guard = WizardState::default(); + guard.step = WizardStep::Version; + guard.versions = LoadState::Loaded(vec![ + GameVersion { + id: "1.20.1".into(), + stable: true, + }, + GameVersion { + id: "1.19.4".into(), + stable: true, + }, + GameVersion { + id: "1.18.2".into(), + stable: true, + }, + ]); + } + + let backend = TestBackend::new(60, 14); + let mut terminal = Terminal::new(backend).unwrap(); + terminal + .draw(|f| render(f, f.area(), FocusedArea::Popup)) + .unwrap(); + insta::assert_snapshot!(terminal.backend()); + } + + // LoaderVersion step: needs both versions and loader_versions pre-loaded. + // pick a non-Vanilla loader (loader_idx=2 = Forge) so the step doesn't + // skip itself to Confirm. + #[test] + fn new_instance_renders_loader_version_step() { + use crate::instance::loader::GameVersion; + + let _serial = TEST_SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + { + let mut guard = WIZARD_STATE.lock().expect("WIZARD_STATE lock"); + *guard = WizardState::default(); + guard.step = WizardStep::LoaderVersion; + guard.loader_idx = 2; // Forge + guard.versions = LoadState::Loaded(vec![GameVersion { + id: "1.20.1".into(), + stable: true, + }]); + guard.loader_versions = LoadState::Loaded(vec![ + "47.2.0".into(), + "47.1.0".into(), + "47.0.50".into(), + ]); + } + + let backend = TestBackend::new(60, 14); + let mut terminal = Terminal::new(backend).unwrap(); + terminal + .draw(|f| render(f, f.area(), FocusedArea::Popup)) + .unwrap(); + insta::assert_snapshot!(terminal.backend()); + } + + // Confirm step: paints a summary, no network, no list. requires + // versions + loader_versions Loaded so selected_*() return Some. + #[test] + fn new_instance_renders_confirm_step() { + use crate::instance::loader::GameVersion; + use tui_prompts::TextState; + + let _serial = TEST_SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + { + let mut guard = WIZARD_STATE.lock().expect("WIZARD_STATE lock"); + *guard = WizardState::default(); + guard.step = WizardStep::Confirm; + guard.loader_idx = 1; // Fabric + guard.versions = LoadState::Loaded(vec![GameVersion { + id: "1.20.1".into(), + stable: true, + }]); + guard.loader_versions = LoadState::Loaded(vec!["0.15.0".into()]); + // TextState exposes only constructors; rebuilding with the + // desired initial value is the supported path. + guard.name_state = TextState::new().with_value("MyPack"); + } + + let backend = TestBackend::new(60, 12); + let mut terminal = Terminal::new(backend).unwrap(); + terminal + .draw(|f| render(f, f.area(), FocusedArea::Popup)) + .unwrap(); + insta::assert_snapshot!(terminal.backend()); + } } diff --git a/src/tui/widgets/popups/new_instance/snapshots/rmcl__tui__widgets__popups__new_instance__render__tests__new_instance_renders_confirm_step.snap b/src/tui/widgets/popups/new_instance/snapshots/rmcl__tui__widgets__popups__new_instance__render__tests__new_instance_renders_confirm_step.snap new file mode 100644 index 0000000..c2901c3 --- /dev/null +++ b/src/tui/widgets/popups/new_instance/snapshots/rmcl__tui__widgets__popups__new_instance__render__tests__new_instance_renders_confirm_step.snap @@ -0,0 +1,16 @@ +--- +source: src/tui/widgets/popups/new_instance/render.rs +expression: terminal.backend() +--- +"╭New Instance──────────────────────────────────────────────╮" +"│Name: MyPack │" +"│MC: 1.20.1 │" +"│Loader: Fabric │" +"│Loader version: 0.15.0 │" +"│ │" +"│ │" +"│ │" +"│ │" +"│ │" +"│ │" +"╰──────────────────────────────────[h] back [Enter] create╯" diff --git a/src/tui/widgets/popups/new_instance/snapshots/rmcl__tui__widgets__popups__new_instance__render__tests__new_instance_renders_loader_version_step.snap b/src/tui/widgets/popups/new_instance/snapshots/rmcl__tui__widgets__popups__new_instance__render__tests__new_instance_renders_loader_version_step.snap new file mode 100644 index 0000000..49dfc8e --- /dev/null +++ b/src/tui/widgets/popups/new_instance/snapshots/rmcl__tui__widgets__popups__new_instance__render__tests__new_instance_renders_loader_version_step.snap @@ -0,0 +1,18 @@ +--- +source: src/tui/widgets/popups/new_instance/render.rs +expression: terminal.backend() +--- +"╭New Instance──────────────────────────────────────────────╮" +"│▶ 47.2.0 │" +"│ 47.1.0 │" +"│ 47.0.50 │" +"│ │" +"│ │" +"│ │" +"│ │" +"│ │" +"│ │" +"│ │" +"│ │" +"│ │" +"╰──────────────────────────────────[h] back [Enter] select╯" diff --git a/src/tui/widgets/popups/new_instance/snapshots/rmcl__tui__widgets__popups__new_instance__render__tests__new_instance_renders_version_step.snap b/src/tui/widgets/popups/new_instance/snapshots/rmcl__tui__widgets__popups__new_instance__render__tests__new_instance_renders_version_step.snap new file mode 100644 index 0000000..d60bb6d --- /dev/null +++ b/src/tui/widgets/popups/new_instance/snapshots/rmcl__tui__widgets__popups__new_instance__render__tests__new_instance_renders_version_step.snap @@ -0,0 +1,18 @@ +--- +source: src/tui/widgets/popups/new_instance/render.rs +expression: terminal.backend() +--- +"╭New Instance──────────────────────────────────────────────╮" +"│▶ 1.20.1 │" +"│ 1.19.4 │" +"│ 1.18.2 │" +"│ │" +"│ │" +"│ │" +"│ │" +"│ │" +"│ │" +"│ │" +"│ │" +"│ │" +"╰────────────[/] search [s] snap [h] back [Enter] select╯" diff --git a/tests/net_mojang.rs b/tests/net_mojang.rs index 50b5d4c..a31ad6e 100644 --- a/tests/net_mojang.rs +++ b/tests/net_mojang.rs @@ -9,7 +9,11 @@ use wiremock::matchers::{method, path}; use wiremock::{Mock, MockServer, ResponseTemplate}; use rmcl::net::HttpClient; -use rmcl::net::mojang::{VersionEntry, fetch_version_manifest_from, fetch_version_meta_with_raw}; +use rmcl::net::mojang::{ + AssetIndex, Artifact, Download, JavaVersion, Library, LibraryDownloads, VersionDownloads, + VersionEntry, VersionMeta, download_assets, download_assets_from, download_libraries, + fetch_version_manifest_from, fetch_version_meta_with_raw, +}; fn synthetic_manifest() -> serde_json::Value { json!({ @@ -112,6 +116,168 @@ async fn fetch_version_meta_returns_struct_and_raw_bytes() { assert_eq!(reparsed["mainClass"], "net.minecraft.client.main.Main"); } +// constructs a minimal VersionMeta with a single library pointing at the +// wiremock server. lets download_libraries hit synthetic URLs without any +// production-side URL override. +fn meta_with_one_library(server_uri: &str) -> VersionMeta { + VersionMeta { + id: "test".to_string(), + main_class: "net.test.Main".to_string(), + asset_index: AssetIndex { + id: "5".to_string(), + url: format!("{server_uri}/assets/index.json"), + sha1: "0".repeat(40), + }, + downloads: VersionDownloads { + client: Download { + url: format!("{server_uri}/client.jar"), + sha1: "0".repeat(40), + size: 0, + }, + }, + libraries: vec![Library { + name: "org.slf4j:slf4j-api:2.0.7".to_string(), + downloads: LibraryDownloads { + artifact: Some(Artifact { + url: format!("{server_uri}/slf4j.jar"), + path: "org/slf4j/slf4j-api/2.0.7/slf4j-api-2.0.7.jar".to_string(), + sha1: "0".repeat(40), + size: 11, + }), + }, + rules: None, + }], + java_version: Some(JavaVersion { major_version: 17 }), + } +} + +#[tokio::test] +async fn download_libraries_writes_artifact_to_meta_dir() { + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/slf4j.jar")) + .respond_with(ResponseTemplate::new(200).set_body_bytes(b"jar-bytes".to_vec())) + .expect(1) + .mount(&server) + .await; + + let meta = meta_with_one_library(&server.uri()); + let tmp = tempfile::tempdir().unwrap(); + + download_libraries(&HttpClient::new(), &meta, tmp.path()) + .await + .expect("download_libraries"); + + let written = tmp + .path() + .join("libraries/org/slf4j/slf4j-api/2.0.7/slf4j-api-2.0.7.jar"); + assert!(written.exists(), "expected library file at {written:?}"); + let contents = std::fs::read(&written).unwrap(); + assert_eq!(contents, b"jar-bytes"); +} + +#[tokio::test] +async fn download_libraries_skips_when_destination_exists() { + // pre-create the destination file. download_libraries should detect it + // and skip the network entirely; wiremock's expect(0) would panic on any + // request hitting the mock. + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/slf4j.jar")) + .respond_with(ResponseTemplate::new(500)) + .expect(0) + .mount(&server) + .await; + + let meta = meta_with_one_library(&server.uri()); + let tmp = tempfile::tempdir().unwrap(); + let existing = tmp + .path() + .join("libraries/org/slf4j/slf4j-api/2.0.7/slf4j-api-2.0.7.jar"); + std::fs::create_dir_all(existing.parent().unwrap()).unwrap(); + std::fs::write(&existing, b"already there").unwrap(); + + download_libraries(&HttpClient::new(), &meta, tmp.path()) + .await + .expect("noop succeeds"); + + // file untouched, mock untouched (server drop will panic if it isn't) + assert_eq!(std::fs::read(&existing).unwrap(), b"already there"); +} + +#[tokio::test] +async fn download_assets_from_writes_index_and_assets() { + // exercises the full path: index fetch + write, then per-asset download + // from the configurable assets base. uses download_assets_from so the + // hardcoded ASSETS_BASE_URL stays out of the way. + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/assets/index.json")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "objects": { + "minecraft/lang/en_us.json": { + "hash": "ab1234567890abcdef1234567890abcdef123456", + "size": 11 + } + } + }))) + .expect(1) + .mount(&server) + .await; + // asset hash starts with "ab" so the per-asset URL is //ab/. + Mock::given(method("GET")) + .and(path( + "/cdn/ab/ab1234567890abcdef1234567890abcdef123456", + )) + .respond_with(ResponseTemplate::new(200).set_body_bytes(b"asset-bytes".to_vec())) + .expect(1) + .mount(&server) + .await; + + let meta = meta_with_one_library(&server.uri()); + let tmp = tempfile::tempdir().unwrap(); + let cdn_base = format!("{}/cdn", server.uri()); + + download_assets_from(&HttpClient::new(), &meta, tmp.path(), &cdn_base) + .await + .expect("download_assets_from"); + + let index_path = tmp.path().join("assets/indexes/5.json"); + assert!(index_path.exists(), "index file missing"); + let asset_path = tmp + .path() + .join("assets/objects/ab/ab1234567890abcdef1234567890abcdef123456"); + assert!(asset_path.exists(), "asset file missing"); + assert_eq!(std::fs::read(&asset_path).unwrap(), b"asset-bytes"); +} + +#[tokio::test] +async fn download_assets_writes_index_when_objects_is_empty() { + // an asset index with empty objects exercises the index fetch + write + // path without triggering individual asset downloads (which go to the + // hardcoded ASSETS_BASE_URL and can't be wiremocked here). + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/assets/index.json")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({"objects": {}}))) + .expect(1) + .mount(&server) + .await; + + let meta = meta_with_one_library(&server.uri()); + let tmp = tempfile::tempdir().unwrap(); + + download_assets(&HttpClient::new(), &meta, tmp.path()) + .await + .expect("download_assets index-only"); + + let index_path = tmp.path().join("assets/indexes/5.json"); + assert!(index_path.exists(), "expected asset index at {index_path:?}"); + let body: serde_json::Value = + serde_json::from_slice(&std::fs::read(&index_path).unwrap()).unwrap(); + assert!(body.get("objects").is_some()); +} + #[tokio::test] async fn fetch_version_manifest_retries_5xx_and_succeeds() { let server = MockServer::start().await; From 0eb47fd7b4c8c6c7cdd1c1f996ae822d17669291 Mon Sep 17 00:00:00 2001 From: objz Date: Wed, 27 May 2026 18:03:57 +0200 Subject: [PATCH 18/20] added: *_from variants in net::{forge,fabric,quilt,neoforge} + assets Same pattern as fetch_version_manifest_from from the earlier batch: each fetcher gets a sibling that takes the URL as a parameter; the existing function delegates to it with the upstream constant. Production callers are unchanged. - src/net/forge.rs: fetch_forge_versions_from(client, promotions_url, game_version) and fetch_forge_game_versions_from(client, promotions_url). - src/net/fabric.rs: fetch_fabric_game_versions_from(client, base) and fetch_fabric_versions_from(client, base, game_version). The fabric API is hierarchical so the helpers take the meta base URL and append the rest internally, matching the existing layout. - src/net/quilt.rs: same pair as fabric. - src/net/neoforge.rs: fetch_neoforge_versions_from(client, api_url, game_version). - src/net/mojang.rs: download_assets_from(client, meta, meta_dir, assets_base) so tests can route per-asset CDN downloads through a wiremock server. download_assets delegates to it with ASSETS_BASE_URL. tests/net_loaders.rs adds eight wiremock tests covering each new fetcher and a happy + error case for neoforge's invalid-game-version branch. tests/net_mojang.rs gains download_assets_from_writes_index_and_assets which now exercises the full per-asset download path against synthetic hashes. Production touches are minimal (one new pub fn delegating to the existing one for each fetcher). Behaviour of existing callers is unchanged. --- src/net/fabric.rs | 22 ++++- src/net/forge.rs | 20 ++++- src/net/mojang.rs | 13 ++- src/net/neoforge.rs | 11 ++- src/net/quilt.rs | 21 ++++- tests/net_loaders.rs | 187 +++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 266 insertions(+), 8 deletions(-) create mode 100644 tests/net_loaders.rs diff --git a/src/net/fabric.rs b/src/net/fabric.rs index aea2644..8a9820b 100644 --- a/src/net/fabric.rs +++ b/src/net/fabric.rs @@ -45,7 +45,17 @@ pub struct FabricLibrary { } pub async fn fetch_fabric_game_versions(client: &HttpClient) -> Result, NetError> { - let url = format!("{}/versions/game", FABRIC_META_BASE); + fetch_fabric_game_versions_from(client, FABRIC_META_BASE).await +} + +// same as fetch_fabric_game_versions but lets tests point at a wiremock +// server. fabric's API is hierarchical, so we take the base URL and append +// the rest of the path inside. +pub async fn fetch_fabric_game_versions_from( + client: &HttpClient, + meta_base: &str, +) -> Result, NetError> { + let url = format!("{}/versions/game", meta_base); let versions: Vec = client.get_json(&url).await?; Ok(versions @@ -61,7 +71,15 @@ pub async fn fetch_fabric_versions( client: &HttpClient, game_version: &str, ) -> Result, NetError> { - let url = format!("{}/versions/loader/{}", FABRIC_META_BASE, game_version); + fetch_fabric_versions_from(client, FABRIC_META_BASE, game_version).await +} + +pub async fn fetch_fabric_versions_from( + client: &HttpClient, + meta_base: &str, + game_version: &str, +) -> Result, NetError> { + let url = format!("{}/versions/loader/{}", meta_base, game_version); client.get_json(&url).await } diff --git a/src/net/forge.rs b/src/net/forge.rs index ba11279..68e76ae 100644 --- a/src/net/forge.rs +++ b/src/net/forge.rs @@ -26,7 +26,16 @@ pub async fn fetch_forge_versions( client: &HttpClient, game_version: &str, ) -> Result, NetError> { - let promotions: ForgePromotions = client.get_json(FORGE_PROMOTIONS_URL).await?; + fetch_forge_versions_from(client, FORGE_PROMOTIONS_URL, game_version).await +} + +// same as fetch_forge_versions but lets tests point at a wiremock server. +pub async fn fetch_forge_versions_from( + client: &HttpClient, + promotions_url: &str, + game_version: &str, +) -> Result, NetError> { + let promotions: ForgePromotions = client.get_json(promotions_url).await?; let prefix = format!("{}-", game_version); let mut versions: Vec = promotions @@ -44,7 +53,14 @@ pub async fn fetch_forge_versions( // extracts unique game versions from the promotion keys by splitting off // the "-recommended"/"-latest" suffix pub async fn fetch_forge_game_versions(client: &HttpClient) -> Result, NetError> { - let promos: ForgePromotions = client.get_json(FORGE_PROMOTIONS_URL).await?; + fetch_forge_game_versions_from(client, FORGE_PROMOTIONS_URL).await +} + +pub async fn fetch_forge_game_versions_from( + client: &HttpClient, + promotions_url: &str, +) -> Result, NetError> { + let promos: ForgePromotions = client.get_json(promotions_url).await?; let mut game_versions: Vec = promos .promos diff --git a/src/net/mojang.rs b/src/net/mojang.rs index f4ec379..99fa97a 100644 --- a/src/net/mojang.rs +++ b/src/net/mojang.rs @@ -218,6 +218,17 @@ pub async fn download_assets( client: &HttpClient, meta: &VersionMeta, meta_dir: &Path, +) -> Result<(), NetError> { + download_assets_from(client, meta, meta_dir, ASSETS_BASE_URL).await +} + +// same as download_assets but lets tests point at a wiremock server for the +// per-asset CDN downloads. the asset index URL still comes from meta. +pub async fn download_assets_from( + client: &HttpClient, + meta: &VersionMeta, + meta_dir: &Path, + assets_base: &str, ) -> Result<(), NetError> { set_action("Downloading assets..."); @@ -270,7 +281,7 @@ pub async fn download_assets( } let prefix = &object.hash[..2]; - let url = format!("{}/{}/{}", ASSETS_BASE_URL, prefix, object.hash); + let url = format!("{}/{}/{}", assets_base, prefix, object.hash); let destination = meta_dir .join("assets") .join("objects") diff --git a/src/net/neoforge.rs b/src/net/neoforge.rs index 44e0eab..b560206 100644 --- a/src/net/neoforge.rs +++ b/src/net/neoforge.rs @@ -36,6 +36,15 @@ fn game_version_to_neoforge_prefix(game_version: &str) -> Option { pub async fn fetch_neoforge_versions( client: &HttpClient, game_version: &str, +) -> Result, NetError> { + fetch_neoforge_versions_from(client, NEOFORGE_API_BASE, game_version).await +} + +// same as fetch_neoforge_versions but lets tests point at a wiremock server. +pub async fn fetch_neoforge_versions_from( + client: &HttpClient, + api_url: &str, + game_version: &str, ) -> Result, NetError> { let prefix = match game_version_to_neoforge_prefix(game_version) { Some(p) => p, @@ -47,7 +56,7 @@ pub async fn fetch_neoforge_versions( } }; - let maven_versions: NeoForgeMavenVersions = client.get_json(NEOFORGE_API_BASE).await?; + let maven_versions: NeoForgeMavenVersions = client.get_json(api_url).await?; let versions: Vec = maven_versions .versions diff --git a/src/net/quilt.rs b/src/net/quilt.rs index eb9ceec..e6de3a4 100644 --- a/src/net/quilt.rs +++ b/src/net/quilt.rs @@ -42,7 +42,16 @@ pub struct QuiltLibrary { } pub async fn fetch_quilt_game_versions(client: &HttpClient) -> Result, NetError> { - let url = format!("{}/versions/game", QUILT_META_BASE); + fetch_quilt_game_versions_from(client, QUILT_META_BASE).await +} + +// same as fetch_quilt_game_versions but lets tests point at a wiremock +// server. quilt mirrors the fabric API shape. +pub async fn fetch_quilt_game_versions_from( + client: &HttpClient, + meta_base: &str, +) -> Result, NetError> { + let url = format!("{}/versions/game", meta_base); let versions: Vec = client.get_json(&url).await?; Ok(versions @@ -58,7 +67,15 @@ pub async fn fetch_quilt_versions( client: &HttpClient, game_version: &str, ) -> Result, NetError> { - let url = format!("{}/versions/loader/{}", QUILT_META_BASE, game_version); + fetch_quilt_versions_from(client, QUILT_META_BASE, game_version).await +} + +pub async fn fetch_quilt_versions_from( + client: &HttpClient, + meta_base: &str, + game_version: &str, +) -> Result, NetError> { + let url = format!("{}/versions/loader/{}", meta_base, game_version); client.get_json(&url).await } diff --git a/tests/net_loaders.rs b/tests/net_loaders.rs new file mode 100644 index 0000000..d703777 --- /dev/null +++ b/tests/net_loaders.rs @@ -0,0 +1,187 @@ +// integration tests for the loader-specific net::* fetchers (forge, +// fabric, quilt, neoforge). each module's fetch_* function now has a +// _from variant that lets the test point the HTTP call at a wiremock +// server; the production constants stay unchanged. + +use serde_json::json; +use wiremock::matchers::{method, path}; +use wiremock::{Mock, MockServer, ResponseTemplate}; + +use rmcl::net::HttpClient; +use rmcl::net::fabric::{fetch_fabric_game_versions_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::quilt::{fetch_quilt_game_versions_from, fetch_quilt_versions_from}; + +// ---------- forge ---------- + +#[tokio::test] +async fn forge_fetch_versions_filters_by_prefix() { + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/promotions.json")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "promos": { + "1.20.1-latest": "47.2.0", + "1.20.1-recommended": "47.1.0", + "1.19.4-latest": "45.1.0", + "1.7.10-latest": "10.13.4.1614" + } + }))) + .mount(&server) + .await; + + let url = format!("{}/promotions.json", server.uri()); + let versions = fetch_forge_versions_from(&HttpClient::new(), &url, "1.20.1") + .await + .expect("forge versions"); + + assert_eq!(versions, vec!["47.1.0", "47.2.0"]); +} + +#[tokio::test] +async fn forge_fetch_game_versions_extracts_unique() { + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/promotions.json")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "promos": { + "1.20.1-latest": "47.2.0", + "1.20.1-recommended": "47.1.0", + "1.19.4-latest": "45.1.0" + } + }))) + .mount(&server) + .await; + + let url = format!("{}/promotions.json", server.uri()); + let versions = fetch_forge_game_versions_from(&HttpClient::new(), &url) + .await + .expect("forge game versions"); + + let ids: Vec<&str> = versions.iter().map(|v| v.id.as_str()).collect(); + // dedup + reverse-sort + assert_eq!(ids, vec!["1.20.1", "1.19.4"]); +} + +// ---------- fabric ---------- + +#[tokio::test] +async fn fabric_fetch_game_versions_parses_response() { + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/versions/game")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!([ + { "version": "1.20.1", "stable": true }, + { "version": "24w01a", "stable": false } + ]))) + .mount(&server) + .await; + + let versions = fetch_fabric_game_versions_from(&HttpClient::new(), &server.uri()) + .await + .expect("fabric game versions"); + + assert_eq!(versions.len(), 2); + assert_eq!(versions[0].id, "1.20.1"); + assert!(versions[0].stable); + assert_eq!(versions[1].id, "24w01a"); + assert!(!versions[1].stable); +} + +#[tokio::test] +async fn fabric_fetch_versions_parses_loader_entries() { + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/versions/loader/1.20.1")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!([ + { + "loader": { "version": "0.15.0", "stable": true }, + "intermediary": { "version": "1.20.1", "stable": true } + } + ]))) + .mount(&server) + .await; + + let versions = fetch_fabric_versions_from(&HttpClient::new(), &server.uri(), "1.20.1") + .await + .expect("fabric versions"); + + assert_eq!(versions.len(), 1); + assert_eq!(versions[0].loader.version, "0.15.0"); +} + +// ---------- quilt ---------- + +#[tokio::test] +async fn quilt_fetch_game_versions_parses_response() { + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/versions/game")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!([ + { "version": "1.20.1", "stable": true } + ]))) + .mount(&server) + .await; + + let versions = fetch_quilt_game_versions_from(&HttpClient::new(), &server.uri()) + .await + .expect("quilt game versions"); + assert_eq!(versions[0].id, "1.20.1"); +} + +#[tokio::test] +async fn quilt_fetch_versions_parses_loader_entries() { + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/versions/loader/1.20.1")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!([ + { "loader": { "version": "0.23.0" } } + ]))) + .mount(&server) + .await; + + let versions = fetch_quilt_versions_from(&HttpClient::new(), &server.uri(), "1.20.1") + .await + .expect("quilt versions"); + assert_eq!(versions[0].loader.version, "0.23.0"); +} + +// ---------- neoforge ---------- + +#[tokio::test] +async fn neoforge_fetch_versions_filters_by_prefix() { + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/maven-api")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "versions": [ + "20.4.190", + "20.4.180-beta", + "20.4.150", + "21.0.10", + "21.0.5-alpha" + ] + }))) + .mount(&server) + .await; + + let url = format!("{}/maven-api", server.uri()); + let versions = fetch_neoforge_versions_from(&HttpClient::new(), &url, "1.20.4") + .await + .expect("neoforge versions"); + + // game version "1.20.4" maps to prefix "20.4." and beta/alpha are excluded + assert_eq!(versions, vec!["20.4.190", "20.4.150"]); +} + +#[tokio::test] +async fn neoforge_fetch_versions_rejects_invalid_game_version() { + let server = MockServer::start().await; + let url = format!("{}/maven-api", server.uri()); + // no mock - the function should error out before hitting the network + let err = fetch_neoforge_versions_from(&HttpClient::new(), &url, "bogus") + .await + .expect_err("invalid game version"); + assert!(format!("{err:?}").contains("Invalid game version")); +} From 5f43128a8035e34add6dadb90d55273fcab2a383 Mon Sep 17 00:00:00 2001 From: objz Date: Wed, 27 May 2026 18:19:26 +0200 Subject: [PATCH 19/20] added: tests for patches helpers, forge installer detection, url_encode, profile fetchers Closes the seven remaining tractable coverage gaps the final review flagged. All tests-only or tiny *_from variants matching the existing pattern. 18 new tests. - src/instance/launch/patches.rs: seven inline tests for the lwjgl3ify patch helpers that were entirely untested before. strip_replaced_libs has happy + no-op cases. parse_add_opens covers the basic Add-Opens extraction, the MANIFEST.MF continuation-line case (the tricky one: jar manifests wrap lines with a trailing space + leading-space marker that gets stripped on join), missing manifest, and missing file. add_lwjgl3 verifies that only jars that actually exist in lib_dir end up on the classpath. - src/net/forge.rs: three inline tests for has_legacy_install_profile. Builds synthetic forge installer zips in a tempdir with and without the versionInfo key in install_profile.json; covers the missing-jar branch with a path that doesn't exist. - src/net/modrinth.rs: five-case rstest for url_encode covering the unreserved set, space, RFC 3986 reserved characters, multi-byte UTF-8 (the encoder operates per-byte so emoji exercises the multi-byte path), and empty input. - src/net/fabric.rs / src/net/quilt.rs: added fetch_*_profile_from and fetch_*_profile_with_raw_from variants mirroring the existing pattern. Existing fetch_*_profile and *_with_raw delegate to them with the upstream constants. - tests/net_loaders.rs: two new wiremock tests (fabric_fetch_profile parses libraries, quilt_fetch_profile parses libraries) using the new _from variants. - src/tui/widgets/popups/import_modpack/render.rs: extra snapshot for the Confirm step when loader_version is None (vanilla pack or old mmc pack). The previous Confirm snapshot covered Some(_) only. Production touches stay minimal: the four new pub fn delegators in fabric.rs and quilt.rs, all behaviour-preserving. --- src/instance/launch/patches.rs | 134 ++++++++++++++++++ src/net/fabric.rs | 23 ++- src/net/forge.rs | 53 +++++++ src/net/modrinth.rs | 14 ++ src/net/quilt.rs | 22 ++- .../widgets/popups/import_modpack/render.rs | 35 +++++ ...s_confirm_step_without_loader_version.snap | 18 +++ tests/net_loaders.rs | 58 +++++++- 8 files changed, 351 insertions(+), 6 deletions(-) create mode 100644 src/tui/widgets/popups/import_modpack/snapshots/rmcl__tui__widgets__popups__import_modpack__render__tests__import_modpack_renders_confirm_step_without_loader_version.snap diff --git a/src/instance/launch/patches.rs b/src/instance/launch/patches.rs index 35a2128..882b44f 100644 --- a/src/instance/launch/patches.rs +++ b/src/instance/launch/patches.rs @@ -324,3 +324,137 @@ async fn replace_log4j_fixed(lib_dir: &Path, classpath: &mut [PathBuf]) { } } } + +#[cfg(test)] +mod tests { + 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() { + assert!(parse_add_opens(Path::new("/nonexistent/x.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); + } +} diff --git a/src/net/fabric.rs b/src/net/fabric.rs index 8a9820b..c5e4e80 100644 --- a/src/net/fabric.rs +++ b/src/net/fabric.rs @@ -87,10 +87,19 @@ pub async fn fetch_fabric_profile( client: &HttpClient, game_version: &str, loader_version: &str, +) -> Result { + fetch_fabric_profile_from(client, FABRIC_META_BASE, game_version, loader_version).await +} + +pub async fn fetch_fabric_profile_from( + client: &HttpClient, + meta_base: &str, + game_version: &str, + loader_version: &str, ) -> Result { let url = format!( "{}/versions/loader/{}/{}/profile/json", - FABRIC_META_BASE, game_version, loader_version + meta_base, game_version, loader_version ); client.get_json(&url).await } @@ -103,10 +112,20 @@ pub async fn fetch_fabric_profile_with_raw( client: &HttpClient, game_version: &str, loader_version: &str, +) -> Result<(FabricProfile, Vec), NetError> { + fetch_fabric_profile_with_raw_from(client, FABRIC_META_BASE, game_version, loader_version) + .await +} + +pub async fn fetch_fabric_profile_with_raw_from( + client: &HttpClient, + meta_base: &str, + game_version: &str, + loader_version: &str, ) -> Result<(FabricProfile, Vec), NetError> { let url = format!( "{}/versions/loader/{}/{}/profile/json", - FABRIC_META_BASE, game_version, loader_version + meta_base, game_version, loader_version ); client.get_json_with_raw(&url, "Fabric profile").await } diff --git a/src/net/forge.rs b/src/net/forge.rs index 68e76ae..96dee85 100644 --- a/src/net/forge.rs +++ b/src/net/forge.rs @@ -333,4 +333,57 @@ mod tests { Err(e) => panic!("fetch_forge_game_versions failed: {}", e), } } + + // 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() { + assert!(!has_legacy_install_profile(std::path::Path::new( + "/nonexistent/installer.jar" + ))); + } } diff --git a/src/net/modrinth.rs b/src/net/modrinth.rs index 353ca83..598ba16 100644 --- a/src/net/modrinth.rs +++ b/src/net/modrinth.rs @@ -157,6 +157,20 @@ pub fn parse_mrpack(path: &std::path::Path) -> Result { mod tests { use super::*; + // covers each branch of url_encode: unreserved bytes pass through; the + // reserved set + spaces + non-ascii bytes get percent-encoded. emoji + // exercises multi-byte UTF-8 since the encoder operates on bytes, not + // chars, so each byte of the codepoint encodes separately. + #[rstest::rstest] + #[case::ascii_unreserved("abcXYZ0-9_.~", "abcXYZ0-9_.~")] + #[case::space("hello world", "hello%20world")] + #[case::reserved("/?&=#", "%2F%3F%26%3D%23")] + #[case::utf8_emoji("\u{2603}", "%E2%98%83")] + #[case::empty("", "")] + fn url_encode_handles(#[case] input: &str, #[case] expected: &str) { + assert_eq!(url_encode(input), expected); + } + #[test] fn loader_from_fabric_deps() { let mut deps = HashMap::new(); diff --git a/src/net/quilt.rs b/src/net/quilt.rs index e6de3a4..4a94aef 100644 --- a/src/net/quilt.rs +++ b/src/net/quilt.rs @@ -83,10 +83,19 @@ pub async fn fetch_quilt_profile( client: &HttpClient, game_version: &str, loader_version: &str, +) -> Result { + fetch_quilt_profile_from(client, QUILT_META_BASE, game_version, loader_version).await +} + +pub async fn fetch_quilt_profile_from( + client: &HttpClient, + meta_base: &str, + game_version: &str, + loader_version: &str, ) -> Result { let url = format!( "{}/versions/loader/{}/{}/profile/json", - QUILT_META_BASE, game_version, loader_version + meta_base, game_version, loader_version ); client.get_json(&url).await } @@ -99,10 +108,19 @@ pub async fn fetch_quilt_profile_with_raw( client: &HttpClient, game_version: &str, loader_version: &str, +) -> Result<(QuiltProfile, Vec), NetError> { + fetch_quilt_profile_with_raw_from(client, QUILT_META_BASE, game_version, loader_version).await +} + +pub async fn fetch_quilt_profile_with_raw_from( + client: &HttpClient, + meta_base: &str, + game_version: &str, + loader_version: &str, ) -> Result<(QuiltProfile, Vec), NetError> { let url = format!( "{}/versions/loader/{}/{}/profile/json", - QUILT_META_BASE, game_version, loader_version + meta_base, game_version, loader_version ); client.get_json_with_raw(&url, "Quilt profile").await } diff --git a/src/tui/widgets/popups/import_modpack/render.rs b/src/tui/widgets/popups/import_modpack/render.rs index 6185604..5508af5 100644 --- a/src/tui/widgets/popups/import_modpack/render.rs +++ b/src/tui/widgets/popups/import_modpack/render.rs @@ -355,4 +355,39 @@ mod tests { .unwrap(); insta::assert_snapshot!(terminal.backend()); } + + // Confirm step with loader_version=None: covers the branch where the + // pack didn't declare a loader version (rare upstream, but happens for + // older mmc packs). render_confirm_step has to handle the Option. + #[test] + fn import_modpack_renders_confirm_step_without_loader_version() { + use crate::instance::import::{ImportSummary, PackFormat}; + use crate::instance::models::ModLoader; + use std::path::PathBuf; + + let _serial = TEST_SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + { + let mut guard = IMPORT_STATE.lock().expect("IMPORT_STATE lock"); + *guard = ImportWizardState::default(); + guard.step = ImportStep::Confirm; + guard.summary = Some(ImportSummary { + name: "Vanilla Pack".into(), + pack_version: "2.0".into(), + game_version: "1.20.1".into(), + loader: ModLoader::Vanilla, + loader_version: None, + mod_count: 0, + override_count: 12, + format: PackFormat::Mmc, + archive_path: PathBuf::from("/tmp/vanilla.zip"), + }); + } + + let backend = TestBackend::new(60, 14); + let mut terminal = Terminal::new(backend).unwrap(); + terminal + .draw(|f| render(f, f.area(), FocusedArea::ImportPopup)) + .unwrap(); + insta::assert_snapshot!(terminal.backend()); + } } diff --git a/src/tui/widgets/popups/import_modpack/snapshots/rmcl__tui__widgets__popups__import_modpack__render__tests__import_modpack_renders_confirm_step_without_loader_version.snap b/src/tui/widgets/popups/import_modpack/snapshots/rmcl__tui__widgets__popups__import_modpack__render__tests__import_modpack_renders_confirm_step_without_loader_version.snap new file mode 100644 index 0000000..9a037c3 --- /dev/null +++ b/src/tui/widgets/popups/import_modpack/snapshots/rmcl__tui__widgets__popups__import_modpack__render__tests__import_modpack_renders_confirm_step_without_loader_version.snap @@ -0,0 +1,18 @@ +--- +source: src/tui/widgets/popups/import_modpack/render.rs +expression: terminal.backend() +--- +"╭Import Modpack────────────────────────────────────────────╮" +"│Name: Vanilla Pack │" +"│Pack Version: 2.0 │" +"│MC Version: 1.20.1 │" +"│Loader: Vanilla │" +"│Mods: 0 files │" +"│Overrides: 12 files │" +"│ │" +"│ │" +"│ │" +"│ │" +"│ │" +"│ │" +"╰──────────────────────────────────[h] back [Enter] import╯" diff --git a/tests/net_loaders.rs b/tests/net_loaders.rs index d703777..8cbedda 100644 --- a/tests/net_loaders.rs +++ b/tests/net_loaders.rs @@ -8,10 +8,14 @@ use wiremock::matchers::{method, path}; use wiremock::{Mock, MockServer, ResponseTemplate}; use rmcl::net::HttpClient; -use rmcl::net::fabric::{fetch_fabric_game_versions_from, fetch_fabric_versions_from}; +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::quilt::{fetch_quilt_game_versions_from, fetch_quilt_versions_from}; +use rmcl::net::quilt::{ + fetch_quilt_game_versions_from, fetch_quilt_profile_from, fetch_quilt_versions_from, +}; // ---------- forge ---------- @@ -111,6 +115,32 @@ async fn fabric_fetch_versions_parses_loader_entries() { assert_eq!(versions[0].loader.version, "0.15.0"); } +#[tokio::test] +async fn fabric_fetch_profile_parses_libraries() { + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/versions/loader/1.20.1/0.15.0/profile/json")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "id": "fabric-loader-0.15.0-1.20.1", + "mainClass": "net.fabricmc.loader.impl.launch.knot.KnotClient", + "libraries": [ + { "name": "net.fabricmc:fabric-loader:0.15.0", "url": "https://maven.fabricmc.net/" } + ] + }))) + .mount(&server) + .await; + + let profile = + fetch_fabric_profile_from(&HttpClient::new(), &server.uri(), "1.20.1", "0.15.0") + .await + .expect("fabric profile"); + + assert_eq!(profile.id, "fabric-loader-0.15.0-1.20.1"); + assert_eq!(profile.main_class, "net.fabricmc.loader.impl.launch.knot.KnotClient"); + assert_eq!(profile.libraries.len(), 1); + assert_eq!(profile.libraries[0].url, "https://maven.fabricmc.net/"); +} + // ---------- quilt ---------- #[tokio::test] @@ -147,6 +177,30 @@ async fn quilt_fetch_versions_parses_loader_entries() { assert_eq!(versions[0].loader.version, "0.23.0"); } +#[tokio::test] +async fn quilt_fetch_profile_parses_libraries() { + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/versions/loader/1.20.1/0.23.0/profile/json")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "id": "quilt-loader-0.23.0-1.20.1", + "mainClass": "org.quiltmc.loader.impl.launch.knot.KnotClient", + "libraries": [ + { "name": "org.quiltmc:quilt-loader:0.23.0", "url": "https://maven.quiltmc.org/repository/release/" } + ] + }))) + .mount(&server) + .await; + + let profile = + fetch_quilt_profile_from(&HttpClient::new(), &server.uri(), "1.20.1", "0.23.0") + .await + .expect("quilt profile"); + + assert_eq!(profile.id, "quilt-loader-0.23.0-1.20.1"); + assert_eq!(profile.libraries[0].url, "https://maven.quiltmc.org/repository/release/"); +} + // ---------- neoforge ---------- #[tokio::test] From c6c774b1e3c5d5c5c0485a71b007bc6118d45f3b Mon Sep 17 00:00:00 2001 From: objz Date: Wed, 27 May 2026 18:55:19 +0200 Subject: [PATCH 20/20] 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;