test(net): make retry and loader coverage deterministic

This commit is contained in:
objz committed 2026-07-27 01:10:04 +02:00
1 parent 45ce7ef84b
commit dc13746841
5 files changed
+96 -53

No files matched your search

+1 -1
View File
@@ -46,7 +46,7 @@ toml = "1.1.2"
tachyonfx = "0.25" tachyonfx = "0.25"
throbber-widgets-tui = "0.11" throbber-widgets-tui = "0.11"
thiserror = "2" thiserror = "2"
tokio = { version = "1", features = ["full"] } tokio = { version = "1", features = ["full", "test-util"] }
tracing = "0.1" tracing = "0.1"
tracing-appender = "0.2" tracing-appender = "0.2"
tracing-subscriber = { version = "0.3", features = ["env-filter"] } tracing-subscriber = { version = "0.3", features = ["env-filter"] }
+49 -8
View File
@@ -20,14 +20,7 @@ impl ModLoaderInstaller for VanillaInstaller {
async fn get_game_versions(&self, client: &HttpClient) -> Result<Vec<GameVersion>, NetError> { async fn get_game_versions(&self, client: &HttpClient) -> Result<Vec<GameVersion>, NetError> {
let manifest = mojang::fetch_version_manifest(client).await?; let manifest = mojang::fetch_version_manifest(client).await?;
Ok(manifest Ok(game_versions_from_manifest(manifest))
.versions
.into_iter()
.map(|v| GameVersion {
id: v.id,
stable: v.version_type == "release",
})
.collect())
} }
async fn get_versions( async fn get_versions(
@@ -49,3 +42,51 @@ impl ModLoaderInstaller for VanillaInstaller {
Ok(()) Ok(())
} }
} }
fn game_versions_from_manifest(manifest: mojang::VersionManifest) -> Vec<GameVersion> {
manifest
.versions
.into_iter()
.map(|version| GameVersion {
id: version.id,
stable: version.version_type == "release",
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::net::mojang::{LatestVersions, VersionEntry, VersionManifest};
#[test]
fn manifest_types_map_to_stable_game_versions() {
let manifest = VersionManifest {
latest: LatestVersions {
release: "1.21.1".to_owned(),
snapshot: "24w01a".to_owned(),
},
versions: vec![
VersionEntry {
id: "1.21.1".to_owned(),
version_type: "release".to_owned(),
url: String::new(),
sha1: String::new(),
},
VersionEntry {
id: "24w01a".to_owned(),
version_type: "snapshot".to_owned(),
url: String::new(),
sha1: String::new(),
},
],
};
let versions = game_versions_from_manifest(manifest);
assert_eq!(versions[0].id, "1.21.1");
assert!(versions[0].stable);
assert_eq!(versions[1].id, "24w01a");
assert!(!versions[1].stable);
}
}
+6
View File
@@ -39,6 +39,12 @@ impl Default for HttpClient {
} }
} }
impl From<Client> for HttpClient {
fn from(inner: Client) -> Self {
Self { inner }
}
}
impl NetError { impl NetError {
pub(crate) fn is_retryable(&self) -> bool { pub(crate) fn is_retryable(&self) -> bool {
matches!(self, Self::StatusError { status: 429, .. }) || is_retryable(self) matches!(self, Self::StatusError { status: 429, .. }) || is_retryable(self)
+5 -16
View File
@@ -88,21 +88,6 @@ async fn neoforge_game_versions_are_available() {
assert!(versions.iter().any(|version| version.id == "1.21")); assert!(versions.iter().any(|version| version.id == "1.21"));
} }
#[tokio::test]
#[ignore = "hits live Mojang API"]
async fn mojang_manifest_contains_a_known_release() {
let manifest = net::mojang::fetch_version_manifest(&HttpClient::new())
.await
.unwrap();
assert!(
manifest
.versions
.iter()
.any(|version| version.id == "1.20.1")
);
}
#[tokio::test] #[tokio::test]
#[ignore = "hits live Mojang API"] #[ignore = "hits live Mojang API"]
async fn vanilla_installer_lists_game_versions() { async fn vanilla_installer_lists_game_versions() {
@@ -113,7 +98,11 @@ async fn vanilla_installer_lists_game_versions() {
.await .await
.unwrap(); .unwrap();
assert!(versions.iter().any(|version| version.id == "1.20.1")); assert!(
versions
.iter()
.any(|version| version.id == "1.20.1" && version.stable)
);
} }
#[tokio::test] #[tokio::test]
+35 -28
View File
@@ -4,11 +4,14 @@
// 4 attempts) is honoured. these tests exercise public HttpClient methods, // 4 attempts) is honoured. these tests exercise public HttpClient methods,
// not the private retry helper directly. // not the private retry helper directly.
// //
// note: get_with_retry sleeps between attempts (500ms, 1000ms, 2000ms), // Tokio time is paused in retrying tests so the production backoff remains
// so the gives-up-after-max-retries test takes about 3.5s of wall time. // covered without adding wall-clock delay to the suite.
// nothing to be done about that without making the delays configurable.
use std::path::PathBuf; use std::path::PathBuf;
use std::sync::{
Arc,
atomic::{AtomicUsize, Ordering},
};
use serde::Deserialize; use serde::Deserialize;
use serde_json::json; use serde_json::json;
@@ -22,29 +25,33 @@ struct ApiResponse {
ok: bool, ok: bool,
} }
fn client_without_timeout() -> HttpClient {
reqwest::Client::builder().build().unwrap().into()
}
// ---------- get_json (via get_with_retry) ---------- // ---------- get_json (via get_with_retry) ----------
#[tokio::test] #[tokio::test(start_paused = true)]
async fn get_json_retries_5xx_then_succeeds() { async fn get_json_retries_5xx_then_succeeds() {
let server = MockServer::start().await; let server = MockServer::start().await;
let attempts = Arc::new(AtomicUsize::new(0));
// first request: 503. second and beyond: 200. // first request: 503. second request: 200.
Mock::given(method("GET")) Mock::given(method("GET"))
.and(path("/api")) .and(path("/api"))
.respond_with(ResponseTemplate::new(503)) .respond_with(move |_: &wiremock::Request| {
.up_to_n_times(1) if attempts.fetch_add(1, Ordering::SeqCst) == 0 {
.expect(1) ResponseTemplate::new(503)
.mount(&server) } else {
.await; ResponseTemplate::new(200).set_body_json(json!({"ok": true}))
Mock::given(method("GET")) }
.and(path("/api")) })
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"ok": true}))) .expect(2)
.expect(1)
.mount(&server) .mount(&server)
.await; .await;
let url = format!("{}/api", server.uri()); let url = format!("{}/api", server.uri());
let result: ApiResponse = HttpClient::new().get_json(&url).await.unwrap(); let result: ApiResponse = client_without_timeout().get_json(&url).await.unwrap();
assert!(result.ok); assert!(result.ok);
} }
@@ -72,7 +79,7 @@ async fn get_json_fails_fast_on_4xx() {
); );
} }
#[tokio::test] #[tokio::test(start_paused = true)]
async fn get_json_gives_up_after_max_retries() { async fn get_json_gives_up_after_max_retries() {
let server = MockServer::start().await; let server = MockServer::start().await;
@@ -86,7 +93,7 @@ async fn get_json_gives_up_after_max_retries() {
.await; .await;
let url = format!("{}/api", server.uri()); let url = format!("{}/api", server.uri());
let err = HttpClient::new() let err = client_without_timeout()
.get_json::<ApiResponse>(&url) .get_json::<ApiResponse>(&url)
.await .await
.unwrap_err(); .unwrap_err();
@@ -98,21 +105,21 @@ async fn get_json_gives_up_after_max_retries() {
// ---------- download_file ---------- // ---------- download_file ----------
#[tokio::test] #[tokio::test(start_paused = true)]
async fn download_file_retries_5xx_then_succeeds() { async fn download_file_retries_5xx_then_succeeds() {
let server = MockServer::start().await; let server = MockServer::start().await;
let attempts = Arc::new(AtomicUsize::new(0));
Mock::given(method("GET")) Mock::given(method("GET"))
.and(path("/file.bin")) .and(path("/file.bin"))
.respond_with(ResponseTemplate::new(502)) .respond_with(move |_: &wiremock::Request| {
.up_to_n_times(1) if attempts.fetch_add(1, Ordering::SeqCst) == 0 {
.expect(1) ResponseTemplate::new(502)
.mount(&server) } else {
.await; ResponseTemplate::new(200).set_body_bytes(b"hello, retried".to_vec())
Mock::given(method("GET")) }
.and(path("/file.bin")) })
.respond_with(ResponseTemplate::new(200).set_body_bytes(b"hello, retried".to_vec())) .expect(2)
.expect(1)
.mount(&server) .mount(&server)
.await; .await;
@@ -120,7 +127,7 @@ async fn download_file_retries_5xx_then_succeeds() {
let dest = tmp.path().join("downloaded.bin"); let dest = tmp.path().join("downloaded.bin");
let url = format!("{}/file.bin", server.uri()); let url = format!("{}/file.bin", server.uri());
download_file(&HttpClient::new(), &url, &dest, |_, _| {}) download_file(&client_without_timeout(), &url, &dest, |_, _| {})
.await .await
.unwrap(); .unwrap();