Files
arena-tracker/crates/core/tests/follow.rs
T
nessarandClaude Opus 5.5 4612d89a3d Keep a whole row in "Autres champions" and tidy the cards code (#75)
- "Autres champions" grid is never shorter than one card row.
- A Format change keeps the home's statistics (#71); the home cards
  are built when "Defi" is shown again; hidden grids give back their
  decoded portraits; the card holds its portrait as Arc<Path>.
- Unavailability becomes Unpickable (glossary), "selection" becomes
  "champ select" in comments (#74); the statistics error is shown by
  the banner only during a champ select.
- Column breakpoints follow the mockup's max-width rules, the home
  tools row is search, filters, sort; stale comments fixed.
- Tests: whole row, hidden grids, stats scopes, error shown once, and
  the capture's reasons end to end in the open section.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 02:26:14 +01:00

1230 lines
40 KiB
Rust

mod common;
use std::cell::Cell;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, mpsc};
use std::thread;
use std::time::{Duration, Instant};
use arena_tracker_core::{
Account, ChampSelect, ChampionRow, ChampionState, ClientError, ClientEvent, Format,
MATCH_RETRIES, ProgressCheck, RETRY_EVERY_MS, Scope, SeasonScope, SourceError, Tracker,
Unpickable, UpdateProblem,
};
use common::{
FakeClient, FakeHistory, PlayedMatch, RawChampSelect, S2, S2_TRACK, SELF_PUUID, at, date,
payload, payloads, played_by, played_match, recorded_account, run, seasons,
};
const OTHER_PUUID: &str = "fixture-puuid-other";
/// A moment inside the second test Season.
fn now() -> i64 {
at(date(2026, 4, 10), 12)
}
fn other_account() -> Account {
Account {
puuid: OTHER_PUUID.into(),
game_name: "Autre".into(),
tag_line: "FIX".into(),
}
}
/// One Arena 3x6 Match of the recorded Account, placed first with Jinx.
fn new_match(id: &str, hours: i64) -> String {
payload(id, 1750, 222, "Jinx", 1, true, at(date(2026, 4, 5), hours))
}
struct World {
dir: tempfile::TempDir,
history: Arc<FakeHistory>,
client: FakeClient,
calls: Arc<AtomicUsize>,
}
impl World {
/// The recorded Account has played `matches`; the client runs and is signed in as them.
fn new(matches: &[PlayedMatch]) -> World {
World::with_history(FakeHistory::new(recorded_account(), payloads(matches)))
}
fn with_history(history: FakeHistory) -> World {
let calls = history.call_counter();
World {
dir: tempfile::tempdir().unwrap(),
history: Arc::new(history),
client: FakeClient::recorded(),
calls,
}
}
fn tracker(&self) -> Tracker {
self.open().with_client(Box::new(self.client.clone()))
}
fn open(&self) -> Tracker {
Tracker::open(
&self.dir.path().join("arena.db"),
Box::new(self.history.clone()),
)
.unwrap()
.with_seasons(seasons())
}
fn source_calls(&self) -> usize {
self.calls.load(Ordering::SeqCst)
}
}
thread_local! {
/// The time of the latest round (each test runs on its own thread).
static CLOCK: Cell<i64> = Cell::new(now());
}
/// A round `ms` after the previous one.
fn round_after(tracker: &Tracker, ms: i64) -> bool {
let now_ms = CLOCK.with(|clock| clock.replace(clock.get() + ms) + ms);
tracker.follow_client(now_ms, None, &mut |_| {})
}
/// A round one retry interval after the previous one.
fn round(tracker: &Tracker) -> bool {
round_after(tracker, RETRY_EVERY_MS)
}
/// The live champ select the page would show, read once at this instant.
fn shown(tracker: &Tracker) -> Result<Option<(String, ChampSelect)>, ClientError> {
tracker.champ_select_with(&tracker.client_snapshot())
}
fn completed(tracker: &Tracker, puuid: &str) -> usize {
let scope = Scope {
season: SeasonScope::Season(S2.into()),
format: None,
};
let stats = tracker.statistics(puuid, &scope).unwrap();
stats.challenge.unwrap().completed
}
/// A Match won with each of `n` different champions.
fn top1_matches(n: u32) -> Vec<PlayedMatch> {
(0..n)
.map(|i| played_match(1000 + i, 1, at(date(2026, 4, 2), i64::from(i))))
.collect()
}
fn s2_matches() -> Vec<PlayedMatch> {
run(11, &[4, 1], at(date(2026, 4, 2), 0))
}
#[test]
fn the_first_round_syncs_the_signed_in_account_and_makes_it_active() {
let world = World::new(&s2_matches());
let tracker = world.tracker();
assert_eq!(tracker.status().updating, None);
assert!(!tracker.status().client_running);
assert!(round(&tracker));
let status = tracker.status();
assert!(status.client_running);
assert_eq!(status.updating, Some(recorded_account()));
assert_eq!(status.problem, None);
assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 2);
// Nothing changed: no visible change and no call to Riot, even if the client spells the
// Riot ID differently.
world.client.sign_in("joueur", "euw");
let calls = world.source_calls();
assert!(!round(&tracker));
assert_eq!(world.source_calls(), calls);
}
/// The recorded Account and another one, who has one Match.
fn two_accounts() -> FakeHistory {
let theirs = payload(
"EUW1_theirs",
1750,
222,
"Jinx",
3,
true,
at(date(2026, 4, 3), 0),
);
FakeHistory::new(recorded_account(), payloads(&s2_matches()))
.with_account(other_account(), vec![played_by(&theirs, OTHER_PUUID)])
}
#[test]
fn signing_in_to_another_account_switches_the_active_account() {
let world = World::with_history(two_accounts());
let tracker = world.tracker();
round(&tracker);
assert_eq!(tracker.status().updating, Some(recorded_account()));
world.client.sign_in("Autre", "FIX");
assert!(round(&tracker));
assert_eq!(tracker.status().updating, Some(other_account()));
assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 2);
assert_eq!(tracker.match_count(OTHER_PUUID).unwrap(), 1);
assert_eq!(completed(&tracker, SELF_PUUID), 1);
assert_eq!(completed(&tracker, OTHER_PUUID), 0);
world.client.sign_in("Joueur", "EUW");
round(&tracker);
assert_eq!(tracker.status().updating, Some(recorded_account()));
}
#[test]
fn without_the_client_the_first_round_catches_up_on_the_last_active_account() {
let world = World::new(&s2_matches());
round(&world.tracker());
world.client.sign_out();
world.history.add(new_match("EUW1_while_closed", 3));
let tracker = world.tracker();
assert_eq!(
tracker.last_active_account().unwrap(),
Some(recorded_account())
);
assert!(round(&tracker));
let status = tracker.status();
assert!(!status.client_running);
assert_eq!(status.updating, Some(recorded_account()));
assert_eq!(status.problem, None);
assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 3);
}
#[test]
fn without_the_client_nor_any_known_account_there_is_nothing_to_update() {
let world = World::new(&s2_matches());
world.client.sign_out();
let tracker = world.tracker();
assert!(round(&tracker));
let status = tracker.status();
assert_eq!(
(status.updating, status.problem),
(None, Some(UpdateProblem::NoAccount))
);
assert_eq!(world.source_calls(), 0);
// An empty Riot ID from the settings is no Riot ID.
tracker.follow_client(now(), Some(" "), &mut |_| {});
assert_eq!(tracker.status().problem, Some(UpdateProblem::NoAccount));
}
#[test]
fn the_configured_riot_id_is_the_fallback_when_nothing_else_is_known() {
let world = World::new(&s2_matches());
world.client.sign_out();
let tracker = world.tracker();
assert!(tracker.follow_client(now(), Some("Joueur#EUW"), &mut |_| {}));
let status = tracker.status();
assert_eq!(
(status.updating, status.problem),
(Some(recorded_account()), None)
);
assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 2);
assert_eq!(
world.open().last_active_account().unwrap(),
Some(recorded_account())
);
}
#[test]
fn rounds_work_without_any_client() {
let world = World::new(&s2_matches());
let tracker = world.open();
tracker.follow_client(now(), Some("Joueur#EUW"), &mut |_| {});
assert!(!tracker.status().client_running);
assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 2);
}
#[test]
fn when_the_client_stops_the_active_account_and_its_data_stay() {
let world = World::new(&s2_matches());
let tracker = world.tracker();
round(&tracker);
world.client.sign_out();
let calls = world.source_calls();
assert!(round(&tracker));
let status = tracker.status();
assert!(!status.client_running);
assert_eq!(status.updating, Some(recorded_account()));
assert_eq!(status.official_progress, ProgressCheck::Absent);
assert_eq!(world.source_calls(), calls);
assert_eq!(completed(&tracker, SELF_PUUID), 1);
}
#[test]
fn an_unknown_riot_id_in_the_client_is_a_problem_not_a_crash() {
let world = World::new(&s2_matches());
world.client.sign_in("Inconnu", "XX");
let tracker = world.tracker();
round(&tracker);
assert!(matches!(
tracker.status().problem,
Some(UpdateProblem::Other(_))
));
assert_eq!(tracker.status().updating, None);
}
#[test]
fn the_match_of_an_arena_game_that_just_ended_is_stored() {
let world = World::new(&s2_matches());
let tracker = world.tracker();
round(&tracker);
let calls = world.source_calls();
world.client.set_phase("ChampSelect", false);
round(&tracker);
world.client.set_phase("InProgress", true);
assert!(!round(&tracker));
assert_eq!(
world.source_calls(),
calls,
"nothing to fetch while the game runs"
);
world.history.add(new_match("EUW1_just_played", 1));
world.client.set_phase("EndOfGame", true);
assert!(round(&tracker));
assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 3);
assert_eq!(tracker.status().problem, None);
let calls = world.source_calls();
world.client.set_phase("None", false);
assert!(!round(&tracker));
assert_eq!(world.source_calls(), calls, "a stored Match ends the wait");
let report = tracker.refresh(&mut |_| {}).unwrap();
assert_eq!((report.added, report.stored), (0, 3));
}
#[test]
fn a_match_that_shows_up_late_is_still_stored_without_leaving_a_problem() {
let world = World::new(&s2_matches());
let tracker = world.tracker();
round(&tracker);
world.client.set_phase("Reconnect", true);
round(&tracker);
world.client.set_phase("WaitingForStats", true);
round(&tracker);
round(&tracker);
assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 2);
world.history.add(new_match("EUW1_late", 1));
round(&tracker);
tracker.wait_for_client();
assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 3);
assert_eq!(tracker.status().problem, None);
assert_eq!(world.client.waits(), [Duration::from_secs(60)]);
}
#[test]
fn while_a_match_is_pending_client_events_still_end_the_wait() {
let world = World::new(&s2_matches());
let tracker = world.tracker();
round(&tracker);
world.client.set_phase("InProgress", true);
round(&tracker);
world.client.set_phase("EndOfGame", true);
round(&tracker);
let started = Instant::now();
tracker.wait_for_client();
assert!(started.elapsed() < Duration::from_secs(1), "no sleep");
assert_eq!(world.client.waits(), [Duration::from_secs(20)]);
}
#[test]
fn a_burst_of_client_events_makes_one_request_per_retry_interval() {
let world = World::new(&s2_matches());
let tracker = world.tracker();
round(&tracker);
play_arena_game(&world, &tracker);
let calls = world.source_calls();
round(&tracker);
for _ in 0..5 {
round_after(&tracker, 0);
}
assert_eq!(world.source_calls(), calls + 1);
round_after(&tracker, RETRY_EVERY_MS - 1);
assert_eq!(world.source_calls(), calls + 1);
round_after(&tracker, 1);
assert_eq!(world.source_calls(), calls + 2);
}
/// The Match of a game the client gave this id, as Riot has it.
fn match_of_game(game_id: u64) -> String {
let id = format!("EUW1_{game_id}");
payload(&id, 1750, 103, "Ahri", 2, true, at(date(2026, 4, 5), 2))
}
/// Eliminated early from the recorded game A, the player queues again and game B ends before
/// A's lobby has finished: no Match is published yet.
fn two_games_in_a_row(world: &World, tracker: &Tracker) -> u64 {
round(tracker);
play_arena_game(world, tracker);
round(tracker);
let game_b = common::recorded_game_id() + 1;
world.client.set_game_id(Some(game_b));
world.client.set_phase("InProgress", true);
round(tracker);
world.client.set_phase("EndOfGame", true);
game_b
}
#[test]
fn the_matches_of_two_games_ended_in_a_row_are_both_stored() {
let world = World::new(&s2_matches());
let tracker = world.tracker();
let game_b = two_games_in_a_row(&world, &tracker);
world.history.add_unlisted(match_of_game(game_b));
round(&tracker);
assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 3);
world.history.add_unlisted(finished_match(1750));
round(&tracker);
assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 4);
assert_eq!(tracker.status().problem, None);
let calls = world.source_calls();
round(&tracker);
assert_eq!(world.source_calls(), calls, "nothing left to wait for");
}
#[test]
fn the_first_of_two_games_is_pending_after_its_own_tries_once_the_second_is_stored() {
let world = World::new(&s2_matches());
let tracker = world.tracker();
let game_b = two_games_in_a_row(&world, &tracker);
world.history.add_unlisted(match_of_game(game_b));
// Game A was tried twice already.
for _ in 2..MATCH_RETRIES - 1 {
round(&tracker);
assert_eq!(tracker.status().problem, None);
}
assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 3);
round(&tracker);
assert_eq!(tracker.status().problem, Some(UpdateProblem::MatchPending));
}
#[test]
fn a_match_that_never_shows_up_is_reported_pending_until_a_refresh_finds_it() {
let world = World::new(&s2_matches());
let tracker = world.tracker();
round(&tracker);
world.client.set_phase("InProgress", true);
round(&tracker);
world.client.set_phase("EndOfGame", true);
for _ in 1..MATCH_RETRIES {
round(&tracker);
assert_eq!(tracker.status().problem, None);
}
assert!(round(&tracker));
assert_eq!(tracker.status().problem, Some(UpdateProblem::MatchPending));
tracker.wait_for_client();
assert_eq!(world.client.waits(), [Duration::from_secs(60)]);
let calls = world.source_calls();
assert!(!round(&tracker));
assert_eq!(world.source_calls(), calls, "the round gave up");
world.history.add(new_match("EUW1_finally", 1));
let report = tracker.refresh(&mut |_| {}).unwrap();
assert_eq!(report.added, 1);
assert_eq!(tracker.status().problem, None);
}
#[test]
fn a_game_that_is_not_arena_triggers_nothing() {
let world = World::new(&s2_matches());
let tracker = world.tracker();
round(&tracker);
let calls = world.source_calls();
world.client.set_phase("InProgress", false);
round(&tracker);
world.client.set_phase("EndOfGame", false);
assert!(!round(&tracker));
assert_eq!(world.source_calls(), calls);
assert_eq!(tracker.status().problem, None);
tracker.wait_for_client();
assert_eq!(world.client.waits(), [Duration::from_secs(60)]);
}
fn failures() -> [(SourceError, UpdateProblem); 4] {
[
(SourceError::MissingKey, UpdateProblem::MissingKey),
(SourceError::InvalidKey, UpdateProblem::InvalidKey),
(SourceError::Network("coupé".into()), UpdateProblem::Network),
(
SourceError::RateLimited {
retry_after: Duration::ZERO,
},
UpdateProblem::RateLimited,
),
]
}
#[test]
fn failures_during_a_round_are_recorded_and_stored_data_stays_readable() {
for (error, problem) in failures() {
let world = World::new(&s2_matches());
let tracker = world.tracker();
round(&tracker);
world.client.set_phase("InProgress", true);
round(&tracker);
world.history.fail_with(Some(error));
world.client.set_phase("EndOfGame", true);
assert!(round(&tracker), "{problem:?}");
assert_eq!(tracker.status().problem, Some(problem));
assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 2);
assert_eq!(completed(&tracker, SELF_PUUID), 1);
world.history.fail_with(None);
round(&tracker);
assert_eq!(tracker.status().problem, None);
}
}
#[test]
fn failures_during_a_refresh_are_returned_and_recorded() {
for (error, problem) in failures() {
let world = World::new(&s2_matches());
let tracker = world.tracker();
round(&tracker);
world.history.fail_with(Some(error));
let failed = tracker.refresh(&mut |_| {});
assert_eq!(failed.unwrap_err(), problem);
assert_eq!(tracker.status().problem, Some(problem));
assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 2);
assert_eq!(completed(&tracker, SELF_PUUID), 1);
world.history.fail_with(None);
assert!(tracker.refresh(&mut |_| {}).is_ok());
assert_eq!(tracker.status().problem, None);
}
}
#[test]
fn a_first_sync_that_failed_is_tried_again_a_minute_later() {
let world = World::new(&s2_matches());
world.history.fail_with(Some(SourceError::InvalidKey));
let tracker = world.tracker();
round(&tracker);
assert_eq!(tracker.status().problem, Some(UpdateProblem::InvalidKey));
assert_eq!(tracker.status().updating, None);
world.history.fail_with(None);
assert!(round_after(&tracker, 60_000));
assert_eq!(tracker.status().problem, None);
assert_eq!(tracker.status().updating, Some(recorded_account()));
assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 2);
}
#[test]
fn refreshing_with_no_account_known_is_a_problem() {
let world = World::new(&s2_matches());
let tracker = world.open();
assert_eq!(
tracker.refresh(&mut |_| {}).unwrap_err(),
UpdateProblem::NoAccount
);
assert_eq!(tracker.status().problem, Some(UpdateProblem::NoAccount));
}
#[test]
fn refreshing_at_launch_updates_the_last_active_account() {
let world = World::new(&s2_matches());
round(&world.tracker());
world.history.add(new_match("EUW1_next", 1));
let tracker = world.open();
let report = tracker.refresh(&mut |_| {}).unwrap();
assert_eq!((report.added, report.stored), (1, 3));
assert_eq!(tracker.status().updating, Some(recorded_account()));
}
#[test]
fn official_progress_agrees_when_the_counts_are_equal() {
let world = World::new(&top1_matches(52));
let tracker = world.tracker();
round(&tracker);
// 52 is what the real client reported.
assert_eq!(
tracker.status().official_progress,
ProgressCheck::Agrees(52)
);
}
#[test]
fn official_progress_differs_with_both_numbers_and_follows_later_syncs() {
let world = World::new(&top1_matches(50));
let tracker = world.tracker();
round(&tracker);
let differs = ProgressCheck::Differs {
app: 50,
official: 52,
};
assert_eq!(tracker.status().official_progress, differs);
world
.history
.add(new_match("EUW1_a", 1).replace("\"championId\":222", "\"championId\":2001"));
world
.history
.add(new_match("EUW1_b", 2).replace("\"championId\":222", "\"championId\":2002"));
tracker.refresh(&mut |_| {}).unwrap();
assert_eq!(
tracker.status().official_progress,
ProgressCheck::Agrees(52)
);
}
#[test]
fn official_progress_is_absent_without_a_reading() {
let world = World::new(&top1_matches(52));
let tracker = world.tracker();
round(&tracker);
assert_ne!(tracker.status().official_progress, ProgressCheck::Absent);
world.client.remove_track(S2_TRACK);
round(&tracker);
assert_eq!(tracker.status().official_progress, ProgressCheck::Absent);
world.client.set_track(S2_TRACK, 52);
round(&tracker);
assert_eq!(
tracker.status().official_progress,
ProgressCheck::Agrees(52)
);
world.client.sign_out();
round(&tracker);
assert_eq!(tracker.status().official_progress, ProgressCheck::Absent);
}
#[test]
fn official_progress_is_absent_when_the_season_has_no_track_or_there_is_no_season() {
let world = World::new(&top1_matches(52));
let tracker = world.tracker();
tracker.follow_client(at(date(2026, 1, 15), 0), None, &mut |_| {});
assert_eq!(tracker.status().official_progress, ProgressCheck::Absent);
tracker.follow_client(at(date(2025, 6, 1), 0), None, &mut |_| {});
assert_eq!(tracker.status().official_progress, ProgressCheck::Absent);
tracker.follow_client(now(), None, &mut |_| {});
assert_eq!(
tracker.status().official_progress,
ProgressCheck::Agrees(52)
);
}
/// The Match of the game the recorded client session is playing, as Riot has it.
fn finished_match(queue_id: u32) -> String {
let id = format!("EUW1_{}", common::recorded_game_id());
payload(&id, queue_id, 222, "Jinx", 1, true, at(date(2026, 4, 5), 1))
}
/// Plays an Arena game up to its end: the next round sees it ended.
fn play_arena_game(world: &World, tracker: &Tracker) {
world.client.set_game_id(Some(common::recorded_game_id()));
world.client.set_phase("InProgress", true);
round(tracker);
world.client.set_phase("EndOfGame", true);
}
#[test]
fn a_finished_game_is_fetched_by_its_id_even_in_a_queue_nobody_lists() {
let world = World::new(&s2_matches());
let tracker = world.tracker();
round(&tracker);
play_arena_game(&world, &tracker);
world.history.add_unlisted(finished_match(1800));
let (calls, listed) = (world.source_calls(), world.history.listed_counter());
let listed_before = listed.load(Ordering::SeqCst);
assert!(round(&tracker));
assert_eq!(world.source_calls(), calls + 1, "one request, no listing");
assert_eq!(listed.load(Ordering::SeqCst), listed_before);
let matches = tracker.matches(SELF_PUUID).unwrap();
assert_eq!(matches.len(), 3);
assert_eq!(matches.last().unwrap().format, Format::Other(1800));
assert_eq!(tracker.status().problem, None);
world.client.set_phase("None", false);
assert!(!round(&tracker));
assert_eq!(
world.source_calls(),
calls + 1,
"a stored Match ends the wait"
);
}
#[test]
fn a_match_riot_publishes_late_is_stored_once_it_appears() {
let world = World::new(&s2_matches());
let tracker = world.tracker();
round(&tracker);
play_arena_game(&world, &tracker);
for _ in 0..5 {
let calls = world.source_calls();
round(&tracker);
assert_eq!(world.source_calls(), calls + 1, "one request per round");
assert_eq!(tracker.status().problem, None);
}
assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 2);
world.history.add_unlisted(finished_match(1750));
assert!(round(&tracker));
assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 3);
assert_eq!(tracker.status().problem, None);
}
#[test]
fn a_match_that_never_appears_is_pending_and_an_empty_refresh_keeps_it_so() {
let world = World::new(&s2_matches());
let tracker = world.tracker();
round(&tracker);
play_arena_game(&world, &tracker);
let calls = world.source_calls();
for _ in 0..MATCH_RETRIES {
round(&tracker);
}
assert_eq!(world.source_calls(), calls + MATCH_RETRIES);
assert_eq!(tracker.status().problem, Some(UpdateProblem::MatchPending));
assert!(!round(&tracker));
assert_eq!(
world.source_calls(),
calls + MATCH_RETRIES,
"the wait is over"
);
let report = tracker.refresh(&mut |_| {}).unwrap();
assert_eq!(report.added, 0);
assert_eq!(tracker.status().problem, Some(UpdateProblem::MatchPending));
world.history.add(finished_match(1750));
assert_eq!(tracker.refresh(&mut |_| {}).unwrap().added, 1);
assert_eq!(tracker.status().problem, None);
}
#[test]
fn a_match_fetched_by_its_id_is_never_stored_twice() {
let world = World::new(&s2_matches());
let tracker = world.tracker();
round(&tracker);
play_arena_game(&world, &tracker);
world.history.add(finished_match(1750));
round(&tracker);
assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 3);
let report = tracker.refresh(&mut |_| {}).unwrap();
assert_eq!((report.added, report.stored), (0, 3));
}
#[test]
fn a_finished_game_that_is_not_an_arena_match_ends_the_wait_without_storing_it() {
let world = World::new(&s2_matches());
let tracker = world.tracker();
round(&tracker);
play_arena_game(&world, &tracker);
world.history.add_unlisted(finished_match(1704));
round(&tracker);
let calls = world.source_calls();
round(&tracker);
assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 2);
assert_eq!(world.source_calls(), calls, "nothing left to wait for");
}
#[test]
fn a_failed_fetch_by_id_is_recorded_and_tried_again() {
let world = World::new(&s2_matches());
let tracker = world.tracker();
round(&tracker);
play_arena_game(&world, &tracker);
world.history.add_unlisted(finished_match(1750));
world
.history
.fail_with(Some(SourceError::Network("coupé".into())));
round(&tracker);
assert_eq!(tracker.status().problem, Some(UpdateProblem::Network));
assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 2);
world.history.fail_with(None);
round(&tracker);
assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 3);
assert_eq!(tracker.status().problem, None);
}
#[test]
fn without_a_stored_match_to_give_the_platform_a_normal_sync_looks_for_the_game() {
let world = World::new(&[]);
let tracker = world.tracker();
round(&tracker);
play_arena_game(&world, &tracker);
world.history.add(finished_match(1750));
round(&tracker);
assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 1);
}
#[test]
fn a_failed_first_sight_of_another_account_does_not_keep_the_previous_one() {
let world = World::with_history(
FakeHistory::new(recorded_account(), payloads(&s2_matches()))
.with_account(other_account(), vec![]),
);
let tracker = world.tracker();
round(&tracker);
assert_eq!(tracker.status().updating, Some(recorded_account()));
// Never seen before, and Riot is down.
world
.history
.fail_with(Some(SourceError::Network("coupé".into())));
world.client.sign_in("Autre", "FIX");
round(&tracker);
assert_eq!(tracker.status().updating, None);
assert_eq!(tracker.status().problem, Some(UpdateProblem::Network));
play_arena_game(&world, &tracker);
round(&tracker);
assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 2);
// Once seen, the stored Account stays shown while Riot is down.
world.history.fail_with(None);
world.client.set_phase("None", false);
world.client.sign_in("Autre", "FIX");
round(&tracker);
assert_eq!(tracker.status().updating, Some(other_account()));
world.client.sign_in("Joueur", "EUW");
round(&tracker);
world
.history
.fail_with(Some(SourceError::Network("coupé".into())));
world.client.sign_in("Autre", "FIX");
round(&tracker);
assert_eq!(tracker.status().updating, Some(other_account()));
assert_eq!(tracker.status().problem, Some(UpdateProblem::Network));
}
#[test]
fn signing_back_in_after_a_failed_switch_shows_that_account_again() {
let world = World::with_history(two_accounts());
let tracker = world.tracker();
round(&tracker);
world
.history
.fail_with(Some(SourceError::Network("coupé".into())));
world.client.sign_in("Autre", "FIX");
round(&tracker);
assert_eq!(tracker.status().updating, None);
world.client.sign_in("Joueur", "EUW");
round(&tracker);
assert_eq!(tracker.status().updating, Some(recorded_account()));
}
#[test]
fn a_failing_adoption_is_tried_again_once_a_minute_not_on_every_client_event() {
let world = World::new(&s2_matches());
world.history.fail_with(Some(SourceError::InvalidKey));
let tracker = world.tracker();
round(&tracker);
for _ in 0..9 {
round_after(&tracker, 0);
}
assert_eq!(world.source_calls(), 1);
// The refresh button is not held back.
let refreshed = tracker.refresh(&mut |_| {});
assert_eq!(refreshed.unwrap_err(), UpdateProblem::InvalidKey);
assert_eq!(world.source_calls(), 2);
round_after(&tracker, 59_999);
assert_eq!(world.source_calls(), 2);
round_after(&tracker, 1);
assert_eq!(world.source_calls(), 3);
}
#[test]
fn a_refresh_after_a_failed_first_sight_adopts_the_signed_in_account() {
let world = World::with_history(two_accounts());
let tracker = world.tracker();
round(&tracker);
world.history.fail_with(Some(SourceError::InvalidKey));
world.client.sign_in("Autre", "FIX");
round(&tracker);
assert_eq!(tracker.status().updating, None);
world.history.fail_with(None);
let report = tracker.refresh(&mut |_| {}).unwrap();
assert_eq!(report.account, other_account());
assert_eq!(tracker.status().updating, Some(other_account()));
assert_eq!(
tracker.last_active_account().unwrap(),
Some(other_account())
);
}
#[test]
fn a_refresh_after_a_failed_first_round_adopts_the_account_signed_in_to_the_client() {
let world = World::new(&s2_matches());
world.history.fail_with(Some(SourceError::InvalidKey));
let tracker = world.tracker();
round(&tracker);
world.history.fail_with(None);
let report = tracker.refresh(&mut |_| {}).unwrap();
assert_eq!((report.added, report.stored), (2, 2));
assert_eq!(tracker.status().updating, Some(recorded_account()));
assert_eq!(tracker.status().problem, None);
}
#[test]
fn a_refresh_during_the_first_import_of_a_new_account_keeps_that_account_active() {
let (entered_tx, entered) = mpsc::channel();
let (release, release_rx) = mpsc::channel();
let world = World::with_history(two_accounts().gated(entered_tx, release_rx));
let tracker = world.tracker();
// The two Matches of the recorded Account go through.
release.send(()).unwrap();
release.send(()).unwrap();
round(&tracker);
assert_eq!(entered.try_iter().count(), 2);
world.client.sign_in("Autre", "FIX");
thread::scope(|scope| {
let follower = scope.spawn(|| round(&tracker));
// The import of the other Account now waits on Riot.
entered.recv().unwrap();
let refresh = scope.spawn(|| tracker.refresh(&mut |_| {}));
thread::sleep(Duration::from_millis(200));
release.send(()).unwrap();
follower.join().unwrap();
refresh.join().unwrap().unwrap();
});
assert_eq!(tracker.status().updating, Some(other_account()));
assert_eq!(
tracker.last_active_account().unwrap(),
Some(other_account())
);
}
#[test]
fn a_fallback_whose_first_sync_failed_is_tried_again_by_later_rounds() {
let world = World::new(&s2_matches());
world.client.sign_out();
world.history.fail_with(Some(SourceError::InvalidKey));
let tracker = world.tracker();
tracker.follow_client(now(), Some("Joueur#EUW"), &mut |_| {});
assert_eq!(tracker.status().problem, Some(UpdateProblem::InvalidKey));
assert_eq!(tracker.status().updating, None);
world.history.fail_with(None);
assert!(round_after(&tracker, 60_000));
assert_eq!(tracker.status().updating, Some(recorded_account()));
assert_eq!(tracker.status().problem, None);
assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 2);
}
#[test]
fn a_refresh_after_a_failed_first_round_uses_the_fallback() {
let world = World::new(&s2_matches());
world.client.sign_out();
world.history.fail_with(Some(SourceError::InvalidKey));
let tracker = world.tracker();
tracker.follow_client(now(), Some("Joueur#EUW"), &mut |_| {});
world.history.fail_with(None);
let report = tracker.refresh(&mut |_| {}).unwrap();
assert_eq!((report.added, report.stored), (2, 2));
assert_eq!(tracker.status().updating, Some(recorded_account()));
assert_eq!(tracker.status().problem, None);
}
#[test]
fn a_fallback_given_after_a_round_without_any_account_is_used() {
let world = World::new(&s2_matches());
world.client.sign_out();
let tracker = world.tracker();
round(&tracker);
assert_eq!(tracker.status().problem, Some(UpdateProblem::NoAccount));
tracker.follow_client(now(), Some("Joueur#EUW"), &mut |_| {});
assert_eq!(tracker.status().updating, Some(recorded_account()));
assert_eq!(tracker.status().problem, None);
}
#[test]
fn banners_point_to_the_parametres_screen_and_never_to_a_missing_field() {
let text = |p: UpdateProblem| p.message();
for problem in [UpdateProblem::MissingKey, UpdateProblem::InvalidKey] {
assert!(text(problem.clone()).contains("Paramètres"), "{problem:?}");
}
let no_account = text(UpdateProblem::NoAccount);
assert!(no_account.contains("League of Legends"), "{no_account}");
assert!(!no_account.contains("Riot ID"), "{no_account}");
for problem in [
UpdateProblem::MissingKey,
UpdateProblem::InvalidKey,
UpdateProblem::Network,
UpdateProblem::RateLimited,
UpdateProblem::NoAccount,
UpdateProblem::MatchPending,
UpdateProblem::Other("x".into()),
] {
assert!(!text(problem).contains("réglages"));
}
}
#[test]
fn arena_champ_select_replays_bans_hovers_and_lock_in_for_the_current_challenge() {
use serde_json::Value;
fn assert_pick(
pick: &ChampSelect,
rows: &[ChampionRow],
current: Option<(u32, ChampionState)>,
remaining: &[u32],
) {
assert_eq!(pick.anvil_champions, Some(vec![233, 64, 5, 16, 68]));
let row_of = |id: u32| rows.iter().find(|r| r.champion.id == id);
assert_eq!(
pick.current
.and_then(row_of)
.map(|r| (r.champion.id, r.attempts, r.state)),
current.map(|(id, state)| (id, Some(1), Some(state)))
);
// Pickable and not Completed: the player's own hovered or locked champion stays in
// while not Completed.
let mut ids: Vec<_> = rows
.iter()
.filter(|r| {
r.state.is_some_and(|s| s != ChampionState::Completed)
&& pick.can_pick(r.champion.id)
})
.map(|r| r.champion.id)
.collect();
ids.sort_unstable();
assert_eq!(ids, remaining);
}
// The reasons the champ select gives for the champions of the capture. The anvil champions
// 64, 5 and 68 are not in the client's pickable list. The player's own pick is never
// unpickable, whatever the bans and allies say.
fn assert_reasons(pick: &ChampSelect, banned: &[u32], taken: &[u32]) {
for id in [12, 16, 25, 50, 64, 5, 68, 103, 233] {
let expected = if pick.current == Some(id) {
Unpickable::default()
} else {
Unpickable {
banned: banned.contains(&id),
taken_by_ally: taken.contains(&id),
not_offered: [64, 5, 68].contains(&id),
}
};
assert_eq!(pick.unpickable(id), expected, "champion {id}");
}
}
let capture: Value =
serde_json::from_str(include_str!("fixtures/client/arena_champ_select.json")).unwrap();
let world = World::new(
&[12, 16, 25, 50, 103, 233].map(|id| played_match(id, if id == 16 { 1 } else { 4 }, now())),
);
let tracker = world.tracker();
// The fake replays the captured raw responses through the same reader as the live client.
let set_frame = |frame: usize| {
world.client.set_champ_select(RawChampSelect {
pickable: capture["pickableChampionIds"].to_string(),
disabled: capture["disabledChampionIds"].to_string(),
anvil: Some(capture["crowdFavoriteChampionIds"].to_string()),
session: capture["sessions"][frame].to_string(),
});
};
set_frame(0);
world.client.set_phase("ChampSelect", false);
round(&tracker);
assert_eq!(shown(&tracker), Ok(None));
// The captured gameflow body goes through the live client's parser too.
world.client.set_gameflow(&capture["gameflow"].to_string());
let rows = tracker
.statistics(
SELF_PUUID,
&Scope {
season: SeasonScope::Season(S2.into()),
format: None,
},
)
.unwrap()
.rows;
// The first read fetches the session and the champion lists once.
let (account, pick) = shown(&tracker).unwrap().unwrap();
assert_eq!(account, "Joueur#EUW");
assert_pick(&pick, &rows, None, &[12, 25, 50, 103, 233]);
assert_reasons(&pick, &[], &[]);
assert_eq!(world.client.champ_select_reads(), (1, 1));
// Every later change arrives as the client's session event: neither the session nor the
// lists are read again.
// The ban of 12 is completed in frame 1 and the ban of 50 in frame 2. The ally's pre-pick of
// 25 (frame 1) leaves it as it is; the confirmed pick (frame 3) takes it.
for (frame, current, remaining, banned, taken) in [
(1, None, vec![25, 50, 103, 233], vec![12], vec![]),
(
2,
Some((233, ChampionState::InProgress)),
vec![25, 103, 233],
vec![12, 50],
vec![],
),
(
3,
Some((16, ChampionState::Completed)),
vec![103, 233],
vec![12, 50],
vec![25],
),
(
4,
Some((16, ChampionState::Completed)),
vec![103, 233],
vec![12, 50],
vec![25],
),
] {
world
.client
.send_champ_select_event(&capture["sessions"][frame].to_string());
assert_eq!(tracker.wait_for_client(), ClientEvent::ChampSelect);
let (_, pick) = shown(&tracker).unwrap().unwrap();
assert_pick(&pick, &rows, current, &remaining);
assert_reasons(&pick, &banned, &taken);
assert_eq!(world.client.champ_select_reads(), (1, 1));
}
// Leaving the champ select ends it and drops its lists; the next one reads them again.
world.client.set_phase("InProgress", true);
assert_eq!(shown(&tracker), Ok(None));
set_frame(0);
world.client.set_gameflow(&capture["gameflow"].to_string());
// Bans and ally picks expired with the first champ select.
let (_, pick) = shown(&tracker).unwrap().unwrap();
assert_reasons(&pick, &[], &[]);
assert_eq!(world.client.champ_select_reads(), (2, 2));
}
#[test]
fn the_anvil_list_is_unknown_when_the_client_fails_to_give_it_and_empty_when_it_says_so() {
use serde_json::Value;
let capture: Value =
serde_json::from_str(include_str!("fixtures/client/arena_champ_select.json")).unwrap();
let anvil_champions = |anvil: Option<&str>| {
let world = World::new(&[]);
let tracker = world.tracker();
world.client.set_champ_select(RawChampSelect {
pickable: capture["pickableChampionIds"].to_string(),
disabled: capture["disabledChampionIds"].to_string(),
anvil: anvil.map(str::to_string),
session: capture["sessions"][0].to_string(),
});
world.client.set_gameflow(&capture["gameflow"].to_string());
shown(&tracker).unwrap().unwrap().1.anvil_champions
};
assert_eq!(anvil_champions(None), None);
assert_eq!(anvil_champions(Some("not json")), None);
assert_eq!(anvil_champions(Some("[]")), Some(vec![]));
assert_eq!(anvil_champions(Some("[3,1,2]")), Some(vec![3, 1, 2]));
}
#[test]
fn a_failed_champ_select_read_keeps_the_pick_until_the_champ_select_really_ends() {
use serde_json::Value;
let capture: Value =
serde_json::from_str(include_str!("fixtures/client/arena_champ_select.json")).unwrap();
let world = World::new(&[]);
let tracker = world.tracker();
world.client.set_champ_select(RawChampSelect {
pickable: capture["pickableChampionIds"].to_string(),
disabled: capture["disabledChampionIds"].to_string(),
anvil: Some(capture["crowdFavoriteChampionIds"].to_string()),
session: capture["sessions"][0].to_string(),
});
world.client.set_gameflow(&capture["gameflow"].to_string());
let live = shown(&tracker).unwrap();
assert!(live.is_some());
// A failed gameflow or session request is not an answer that the champ select is over.
world
.client
.fail_gameflow(Some(ClientError::Other("HTTP 500".into())));
assert_eq!(shown(&tracker), Err(ClientError::Other("HTTP 500".into())));
world.client.fail_gameflow(None);
world
.client
.fail_champ_select(Some(ClientError::Other("HTTP 500".into())));
assert_eq!(shown(&tracker), Err(ClientError::Other("HTTP 500".into())));
world.client.fail_champ_select(None);
assert_eq!(shown(&tracker).unwrap(), live);
// Leaving champ select, or the client going away, does end it.
world.client.set_phase("InProgress", true);
assert_eq!(shown(&tracker), Ok(None));
world.client.sign_out();
assert_eq!(shown(&tracker), Ok(None));
}