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.
This commit is contained in:
objz committed 2026-05-27 16:44:05 +02:00
1 parent 7a9dfa850d
commit 623acd9e2c
5 files changed
+438

No files matched your search

+82
View File
@@ -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();
+94
View File
@@ -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();
}
}
+30
View File
@@ -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);
}
}
+79
View File
@@ -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:?}"
);
}
+153
View File
@@ -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::<ApiResponse>(&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::<ApiResponse>(&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:?}"
);
}