//! Test doubles and payload builders shared by the integration tests. // Each test binary uses its own subset of these helpers. #![allow(dead_code)] use std::collections::HashMap; use std::path::Path; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::mpsc::{Receiver, Sender}; use std::sync::{Arc, Mutex}; use std::time::Duration; use arena_tracker_core::{ Account, Champion, ChampionCatalog, ChampionSource, ClientError, Date, GameClientSource, GamePhase, Gameflow, MatchHistorySource, Season, SourceError, Tracker, }; use serde_json::Value; pub const SELF_PUUID: &str = "fixture-puuid-self"; const BASE: &str = include_str!("../fixtures/riot/match_1750_EUW1_9000000006.json"); /// The six recorded Riot payloads. pub fn recorded_matches() -> Vec { [ include_str!("../fixtures/riot/match_1700_EUW1_9000000001.json"), include_str!("../fixtures/riot/match_1700_EUW1_9000000002.json"), include_str!("../fixtures/riot/match_1740_EUW1_9000000004.json"), include_str!("../fixtures/riot/match_1740_EUW1_9000000005.json"), include_str!("../fixtures/riot/match_1750_EUW1_9000000003.json"), include_str!("../fixtures/riot/match_1750_EUW1_9000000006.json"), ] .map(String::from) .to_vec() } pub fn recorded_account() -> Account { serde_json::from_str(include_str!("../fixtures/riot/account.json")).unwrap() } /// A payload cloned from a recorded one, with the self participant patched. pub fn payload( match_id: &str, queue_id: u32, champion_id: u32, champion_name: &str, placement: u8, win: bool, started_at_ms: i64, ) -> String { let mut v: Value = serde_json::from_str(BASE).unwrap(); v["metadata"]["matchId"] = match_id.into(); v["info"]["queueId"] = queue_id.into(); v["info"]["gameStartTimestamp"] = started_at_ms.into(); let me = v["info"]["participants"] .as_array_mut() .unwrap() .iter_mut() .find(|p| p["puuid"] == SELF_PUUID) .unwrap(); me["championId"] = champion_id.into(); me["championName"] = champion_name.into(); me["placement"] = placement.into(); me["win"] = win.into(); v.to_string() } pub fn with_game_mode(payload: &str, game_mode: &str) -> String { let mut v: Value = serde_json::from_str(payload).unwrap(); v["info"]["gameMode"] = game_mode.into(); v.to_string() } /// The payload with these fields missing from every participant but the Account. pub fn without_fields_for_others(payload: &str, fields: &[&str]) -> String { let mut v: Value = serde_json::from_str(payload).unwrap(); for p in v["info"]["participants"].as_array_mut().unwrap() { if p["puuid"] != SELF_PUUID { for field in fields { p.as_object_mut().unwrap().remove(*field); } } } v.to_string() } pub fn played_by(payload: &str, puuid: &str) -> String { payload.replace(SELF_PUUID, puuid) } fn queue_and_start(raw: &str) -> (u32, i64) { let v: Value = serde_json::from_str(raw).unwrap(); ( v["info"]["queueId"].as_u64().unwrap() as u32, v["info"]["gameStartTimestamp"].as_i64().unwrap(), ) } fn match_id(raw: &str) -> String { let v: Value = serde_json::from_str(raw).unwrap(); v["metadata"]["matchId"].as_str().unwrap().to_string() } struct Listing { owner: String, /// The queue the id is listed under. queue_id: u32, match_id: String, started_ms: i64, /// `None`: Riot lists the id but answers "not found" when asked for it. raw: Option, /// Unlisted Matches can only be fetched by their id. listed: bool, } impl Listing { fn of(owner: &str, raw: String) -> Listing { let (queue_id, started_ms) = queue_and_start(&raw); Listing { owner: owner.into(), queue_id, match_id: match_id(&raw), started_ms, raw: Some(raw), listed: true, } } } /// In-memory Match history that behaves like Riot's (newest first, paged, filtered by queue). pub struct FakeHistory { accounts: Vec, listings: Mutex>, /// Every call fails with this until it is cleared. failure: Mutex>, fail_after: Option, rate_limit_once: AtomicBool, /// Lists in the order the Matches were added instead of newest first. as_given: bool, /// Called at the start of every fetch: announces it, then waits to be released. gate: Option<(Sender<()>, Mutex>)>, fetches: Arc, listed: Arc, calls: Arc, } impl FakeHistory { pub fn new(account: Account, payloads: Vec) -> FakeHistory { FakeHistory { accounts: Vec::new(), listings: Mutex::default(), failure: Mutex::default(), fail_after: None, rate_limit_once: AtomicBool::new(false), as_given: false, gate: None, fetches: Arc::default(), listed: Arc::default(), calls: Arc::default(), } .with_account(account, payloads) } /// Another Account Riot can resolve; its payloads must have been built for its puuid. pub fn with_account(mut self, account: Account, payloads: Vec) -> FakeHistory { for raw in payloads { self.add_for(&account.puuid, raw); } self.accounts.push(account); self } /// Lists a payload under a queue other than its own: a sync only asks for Arena queues. pub fn listed_under(self, queue_id: u32, payload: String) -> FakeHistory { let owner = self.accounts[0].puuid.clone(); self.listings.lock().unwrap().push(Listing { queue_id, ..Listing::of(&owner, payload) }); self } /// A Match that appears for the first Account (e.g. one that has just been played). pub fn add(&self, payload: String) { self.add_for(&self.accounts[0].puuid, payload); } pub fn add_for(&self, puuid: &str, raw: String) { self.listings.lock().unwrap().push(Listing::of(puuid, raw)); } /// A Match Riot has but does not list, like one of a queue the app does not know. pub fn add_unlisted(&self, payload: String) { let owner = self.accounts[0].puuid.clone(); self.listings.lock().unwrap().push(Listing { listed: false, ..Listing::of(&owner, payload) }); } /// An id Riot lists (Arena 3x6) but cannot deliver. pub fn add_missing(&self, match_id: &str, started_ms: i64) { self.add_broken(match_id, started_ms, None); } /// An id Riot lists (Arena 3x6) whose payload is not a readable Match. pub fn add_unreadable(&self, match_id: &str, started_ms: i64, text: &str) { self.add_broken(match_id, started_ms, Some(text.into())); } fn add_broken(&self, match_id: &str, started_ms: i64, raw: Option) { let owner = self.accounts[0].puuid.clone(); self.listings.lock().unwrap().push(Listing { owner, queue_id: 1750, match_id: match_id.into(), started_ms, raw, listed: true, }); } /// Lists Matches in the order they were added, however old they are. pub fn delivered_as_given(mut self) -> FakeHistory { self.as_given = true; self } /// Every call fails with this error until `None` is set. pub fn fail_with(&self, error: Option) { *self.failure.lock().unwrap() = error; } /// Every fetch after the first `n` fails with a network error. pub fn failing_after(mut self, n: usize) -> FakeHistory { self.fail_after = Some(n); self } /// The first fetch answers "rate limited" once. pub fn rate_limited_once(mut self) -> FakeHistory { self.rate_limit_once = AtomicBool::new(true); self } /// Each fetch sends on `entered`, then blocks until `release` delivers. pub fn gated(mut self, entered: Sender<()>, release: Receiver<()>) -> FakeHistory { self.gate = Some((entered, Mutex::new(release))); self } /// Payloads delivered by `fetch_match`, still readable after the fake is boxed. pub fn fetch_counter(&self) -> Arc { self.fetches.clone() } /// Match ids returned by `match_ids`. pub fn listed_counter(&self) -> Arc { self.listed.clone() } /// Calls of any kind made to the source. pub fn call_counter(&self) -> Arc { self.calls.clone() } fn enter(&self) -> Result<(), SourceError> { self.calls.fetch_add(1, Ordering::SeqCst); match &*self.failure.lock().unwrap() { Some(error) => Err(error.clone()), None => Ok(()), } } } impl MatchHistorySource for FakeHistory { fn resolve_account(&self, game_name: &str, tag_line: &str) -> Result { self.enter()?; // Riot IDs are case-insensitive for Riot, too. self.accounts .iter() .find(|a| { a.game_name.eq_ignore_ascii_case(game_name) && a.tag_line.eq_ignore_ascii_case(tag_line) }) .cloned() .ok_or(SourceError::NotFound) } fn match_ids( &self, puuid: &str, queue_id: u32, start: usize, count: usize, start_time_s: Option, ) -> Result, SourceError> { self.enter()?; let mut found: Vec<_> = self .listings .lock() .unwrap() .iter() .filter(|l| l.listed && l.owner == puuid && l.queue_id == queue_id) .filter(|l| start_time_s.is_none_or(|t| l.started_ms / 1000 >= t)) .map(|l| (l.started_ms, l.match_id.clone())) .collect(); if !self.as_given { found.sort_by_key(|(started_ms, _)| std::cmp::Reverse(*started_ms)); } let page: Vec = found .into_iter() .skip(start) .take(count) .map(|(_, id)| id) .collect(); self.listed.fetch_add(page.len(), Ordering::SeqCst); Ok(page) } fn fetch_match(&self, id: &str) -> Result { self.enter()?; if let Some((entered, release)) = &self.gate { entered.send(()).unwrap(); release.lock().unwrap().recv().unwrap(); } if self.rate_limit_once.swap(false, Ordering::SeqCst) { return Err(SourceError::RateLimited { retry_after: Duration::ZERO, }); } if self .fail_after .is_some_and(|n| self.fetches.load(Ordering::SeqCst) >= n) { return Err(SourceError::Network("connexion perdue".into())); } let raw = self .listings .lock() .unwrap() .iter() .find(|l| l.match_id == id) .and_then(|l| l.raw.clone()) .ok_or(SourceError::NotFound)?; self.fetches.fetch_add(1, Ordering::SeqCst); Ok(raw) } } /// Champion reference data served from memory. pub struct FakeChampions { version: String, champions: Vec, failing: bool, no_portrait: Vec, catalog_calls: Arc, } impl FakeChampions { /// `champions`: (id, key, display name). pub fn new(version: &str, champions: &[(u32, &str, &str)]) -> FakeChampions { FakeChampions { version: version.into(), champions: champions .iter() .map(|&(id, key, name)| Champion { id, key: key.into(), name: name.into(), }) .collect(), failing: false, no_portrait: Vec::new(), catalog_calls: Arc::default(), } } /// Every call fails with a network error. pub fn failing(mut self) -> FakeChampions { self.failing = true; self } /// The portrait download of this champion key fails. pub fn without_portrait(mut self, key: &str) -> FakeChampions { self.no_portrait.push(key.into()); self } pub fn catalog_counter(&self) -> Arc { self.catalog_calls.clone() } fn check(&self) -> Result<(), SourceError> { if self.failing { Err(SourceError::Network("hors ligne".into())) } else { Ok(()) } } } impl ChampionSource for FakeChampions { fn latest_version(&self) -> Result { self.check()?; Ok(self.version.clone()) } fn catalog(&self, version: &str) -> Result { self.catalog_calls.fetch_add(1, Ordering::SeqCst); self.check()?; Ok(ChampionCatalog { version: version.into(), champions: self.champions.clone(), }) } fn portrait(&self, _version: &str, key: &str) -> Result, SourceError> { self.check()?; if self.no_portrait.iter().any(|k| k == key) { return Err(SourceError::NotFound); } Ok(format!("png of {key}").into_bytes()) } } // Statistics scenarios: a small catalog, two Seasons and Matches described by champion and Placement. pub const RIOT_ID: &str = "Joueur#EUW"; pub const HOUR_MS: i64 = 3_600_000; pub const S1: &str = "Saison A"; pub const S2: &str = "Saison B"; /// The name of the progression track recorded from the real client for the Season 2 2026. pub const S2_TRACK: &str = "2026 Season 2 Champs Completed Track"; /// (id, key, French name) pub const CATALOG: [(u32, &str, &str); 6] = [ (1, "Annie", "Annie"), (8, "Vladimir", "Vladimir"), (11, "MasterYi", "MaƮtre Yi"), (19, "Warwick", "Warwick"), (103, "Ahri", "Ahri"), (222, "Jinx", "Jinx"), ]; pub fn date(year: i32, month: u8, day: u8) -> Date { Date { year, month, day } } /// `hours` after 00:00 UTC of `date`. pub fn at(date: Date, hours: i64) -> i64 { date.start_ms() + hours * HOUR_MS } /// `hours` after 00:00 UTC on a day of January 2026 (inside S1). pub fn jan_2026(day: u8, hours: i64) -> i64 { at(date(2026, 1, day), hours) } /// S1 starts on 2026-01-01 and S2 on 2026-04-01; only S2 has an official track. pub fn seasons() -> Vec { vec![ Season { name: S1.into(), start: date(2026, 1, 1), official_track: None, }, Season { name: S2.into(), start: date(2026, 4, 1), official_track: Some(S2_TRACK.into()), }, ] } #[derive(Clone)] pub struct PlayedMatch { pub champion: u32, pub placement: u8, pub queue_id: u32, pub started_at_ms: i64, } /// An Arena 3x6 Match. pub fn played_match(champion: u32, placement: u8, started_at_ms: i64) -> PlayedMatch { PlayedMatch { champion, placement, queue_id: 1750, started_at_ms, } } impl PlayedMatch { pub fn in_format(mut self, queue_id: u32) -> PlayedMatch { self.queue_id = queue_id; self } } /// One Match per Placement, an hour apart from `from_ms`. pub fn run(champion: u32, placements: &[u8], from_ms: i64) -> Vec { (0..) .zip(placements) .map(|(i, &p)| played_match(champion, p, from_ms + i * HOUR_MS)) .collect() } /// The payloads of the Matches, as the Riot API would serve them (win = top 3). pub fn payloads(matches: &[PlayedMatch]) -> Vec { (0..) .zip(matches) .map(|(i, m)| { let key = CATALOG .iter() .find(|(id, _, _)| *id == m.champion) .map_or("Unknown", |(_, key, _)| key); payload( &format!("EUW1_{i}"), m.queue_id, m.champion, key, m.placement, m.placement <= 3, m.started_at_ms, ) }) .collect() } pub fn open_tracker(dir: &Path, matches: &[PlayedMatch]) -> Tracker { Tracker::open( &dir.join("arena.db"), Box::new(FakeHistory::new(recorded_account(), payloads(matches))), ) .unwrap() .with_seasons(seasons()) } /// A tracker with the six-champion catalog cached and the Matches imported. pub fn imported_tracker(dir: &Path, matches: &[PlayedMatch]) -> Tracker { let tracker = open_tracker(dir, matches).with_champions( Box::new(FakeChampions::new("1.0", &CATALOG)), dir.join("portraits"), ); tracker.refresh_champions().unwrap(); tracker.sync(RIOT_ID, &mut |_| {}).unwrap(); tracker } /// The id of the Arena game in the recorded in-game session of the client. pub fn recorded_game_id() -> u64 { let session: Value = serde_json::from_str(include_str!( "../fixtures/client/gameflow_session_in_game.json" )) .unwrap(); session["gameData"]["gameId"].as_u64().unwrap() } /// The game client, driven by the test between rounds. #[derive(Clone, Default)] pub struct FakeClient { state: Arc>, } #[derive(Default)] struct ClientState { signed_in: Option<(String, String)>, gameflow: Gameflow, tracks: HashMap, waits: Vec, } impl FakeClient { /// A client that is not running. pub fn absent() -> FakeClient { FakeClient::default() } /// Signed in as the recorded Account, with what the real client answered. pub fn recorded() -> FakeClient { let client = FakeClient::default(); let summoner: Value = serde_json::from_str(include_str!("../fixtures/client/current_summoner.json")).unwrap(); client.sign_in( summoner["gameName"].as_str().unwrap(), summoner["tagLine"].as_str().unwrap(), ); let phase: String = serde_json::from_str(include_str!("../fixtures/client/gameflow_phase_none.json")) .unwrap(); client.set_phase(&phase, false); let groups: Vec = serde_json::from_str(include_str!( "../fixtures/client/progression_groups_configuration.json" )) .unwrap(); let instance: Value = serde_json::from_str(include_str!( "../fixtures/client/progression_instance_data.json" )) .unwrap(); let group = groups .iter() .find(|g| g["id"] == instance["groupId"]) .unwrap(); client.set_track( group["name"].as_str().unwrap(), instance["counters"][0]["counterValue"].as_u64().unwrap() as u32, ); client } pub fn sign_in(&self, game_name: &str, tag_line: &str) { self.state.lock().unwrap().signed_in = Some((game_name.into(), tag_line.into())); } /// The client closes. pub fn sign_out(&self) { self.state.lock().unwrap().signed_in = None; } /// `phase` is the client's own name for it, e.g. "InProgress". pub fn set_phase(&self, phase: &str, arena: bool) { let mut state = self.state.lock().unwrap(); state.gameflow = Gameflow { phase: GamePhase::from_client(phase), arena, ..state.gameflow.clone() }; } /// The client's id of the game being played (kept across phases until changed). pub fn set_game_id(&self, game_id: Option) { self.state.lock().unwrap().gameflow.game_id = game_id; } pub fn set_track(&self, name: &str, value: u32) { self.state.lock().unwrap().tracks.insert(name.into(), value); } pub fn remove_track(&self, name: &str) { self.state.lock().unwrap().tracks.remove(name); } /// The timeouts the tracker asked to wait for. pub fn waits(&self) -> Vec { self.state.lock().unwrap().waits.clone() } } impl GameClientSource for FakeClient { fn signed_in(&self) -> Result<(String, String), ClientError> { let state = self.state.lock().unwrap(); state.signed_in.clone().ok_or(ClientError::Absent) } fn gameflow(&self) -> Result { let state = self.state.lock().unwrap(); state.signed_in.as_ref().ok_or(ClientError::Absent)?; Ok(state.gameflow.clone()) } fn official_progress(&self, track_name: &str) -> Result, ClientError> { let state = self.state.lock().unwrap(); state.signed_in.as_ref().ok_or(ClientError::Absent)?; Ok(state.tracks.get(track_name).copied()) } fn wait_for_change(&self, timeout: Duration) { self.state.lock().unwrap().waits.push(timeout); } }