Group core integration tests by behavior (#102)

This commit is contained in:
nessar committed 2026-11-22 16:49:32 +01:00
1 parent 4548b6ac64
commit c716c2c759
32 files changed
+4504 -4410

No files matched your search

+8 -536
View File
@@ -37,162 +37,6 @@ fn reopen(dir: &std::path::Path, champions: FakeChampions) -> Tracker {
.with_champions(Box::new(champions), dir.join("portraits"))
}
#[test]
fn the_catalog_is_fetched_once_while_the_game_version_is_unchanged() {
let dir = tempfile::tempdir().unwrap();
let first = FakeChampions::new("1.0", &CATALOG);
let first_calls = first.catalog_counter();
let tracker = reopen(dir.path(), first);
tracker.refresh_champions().unwrap();
tracker.refresh_champions().unwrap();
assert_eq!(first_calls.load(Ordering::SeqCst), 1);
assert_eq!(statistics(&tracker).challenge.unwrap().total, 6);
drop(tracker);
let same_version = FakeChampions::new("1.0", &CATALOG);
let same_calls = same_version.catalog_counter();
reopen(dir.path(), same_version)
.refresh_champions()
.unwrap();
assert_eq!(same_calls.load(Ordering::SeqCst), 0);
let mut grown = CATALOG.to_vec();
grown.push((777, "Newcomer", "Nouveau"));
let new_version = FakeChampions::new("2.0", &grown);
let new_calls = new_version.catalog_counter();
let tracker = reopen(dir.path(), new_version);
tracker.refresh_champions().unwrap();
assert_eq!(new_calls.load(Ordering::SeqCst), 1);
assert_eq!(statistics(&tracker).challenge.unwrap().total, 7);
}
#[test]
fn a_failing_source_leaves_the_cached_catalog_usable() {
let dir = tempfile::tempdir().unwrap();
reopen(dir.path(), FakeChampions::new("1.0", &CATALOG))
.refresh_champions()
.unwrap();
let offline = reopen(dir.path(), FakeChampions::new("2.0", &CATALOG).failing());
assert!(matches!(offline.refresh_champions(), Err(Error::Source(_))));
assert_eq!(statistics(&offline).challenge.unwrap().total, 6);
}
#[test]
fn without_any_catalog_the_page_shows_the_champions_played() {
let dir = tempfile::tempdir().unwrap();
let tracker = open_tracker(dir.path(), &[played_match(1, 3, jan_2026(2, 0))]).with_champions(
Box::new(FakeChampions::new("1.0", &CATALOG).failing()),
dir.path().join("portraits"),
);
assert!(tracker.refresh_champions().is_err());
tracker.sync(common::RIOT_ID, &mut |_| {}).unwrap();
let stats = statistics(&tracker);
assert_eq!(row_names(&stats), ["Annie"]);
assert_eq!(stats.challenge.unwrap().total, 1);
}
#[test]
fn a_champion_played_but_absent_from_the_catalog_still_gets_a_row() {
let dir = tempfile::tempdir().unwrap();
let tracker = open_tracker(dir.path(), &[played_match(1, 3, jan_2026(2, 0))]).with_champions(
Box::new(FakeChampions::new("1.0", &CATALOG[1..])),
dir.path().join("portraits"),
);
tracker.refresh_champions().unwrap();
tracker.sync(common::RIOT_ID, &mut |_| {}).unwrap();
let stats = statistics(&tracker);
assert_eq!(stats.rows.len(), 6);
let annie = stats.rows.iter().find(|r| r.champion.id == 1).unwrap();
assert_eq!(
(annie.champion.key.as_str(), annie.champion.name.as_str()),
("Annie", "Annie")
);
assert_eq!(annie.state, Some(ChampionState::InProgress));
assert_eq!(stats.challenge.unwrap().total, 6);
}
#[test]
fn rows_are_ordered_by_champion_name_in_french_order() {
let dir = tempfile::tempdir().unwrap();
let champions = [
(1, "Zoe", "Zoé"),
(2, "Zed", "Zed"),
(11, "MasterYi", "Maître Yi"),
(3, "Nami", "Nami"),
];
let tracker = reopen(dir.path(), FakeChampions::new("1.0", &champions));
tracker.refresh_champions().unwrap();
assert_eq!(
row_names(&statistics(&tracker)),
["Maître Yi", "Nami", "Zed", "Zoé"]
);
}
#[test]
fn portraits_are_downloaded_and_exposed_and_a_failed_one_is_left_out() {
let dir = tempfile::tempdir().unwrap();
let tracker = reopen(
dir.path(),
FakeChampions::new("1.0", &CATALOG).without_portrait("Jinx"),
);
assert!(
statistics(&tracker)
.rows
.iter()
.all(|r| r.portrait.is_none())
);
tracker.refresh_champions().unwrap();
let stats = statistics(&tracker);
let portraits = dir.path().join("portraits");
for row in &stats.rows {
if row.champion.key == "Jinx" {
assert_eq!(row.portrait, None);
} else {
let path = portraits.join(format!("{}.png", row.champion.key));
assert_eq!(row.portrait.as_ref(), Some(&path));
assert_eq!(
std::fs::read(&path).unwrap(),
format!("png of {}", row.champion.key).into_bytes()
);
}
}
assert!(!portraits.join("Jinx.part").exists());
}
#[test]
fn only_files_count_as_portraits() {
let dir = tempfile::tempdir().unwrap();
let tracker = reopen(dir.path(), FakeChampions::new("1.0", &CATALOG));
tracker.refresh_champions().unwrap();
let portraits = dir.path().join("portraits");
std::fs::remove_file(portraits.join("Jinx.png")).unwrap();
std::fs::create_dir(portraits.join("Jinx.png")).unwrap();
let stats = statistics(&tracker);
let jinx = stats
.rows
.iter()
.find(|r| r.champion.key == "Jinx")
.unwrap();
assert_eq!(jinx.portrait, None);
assert_eq!(
stats.rows.iter().filter(|r| r.portrait.is_some()).count(),
5
);
}
fn cards_dir(dir: &std::path::Path) -> std::path::PathBuf {
dir.join("portraits").join("cards")
}
@@ -206,383 +50,11 @@ fn card_files(dir: &std::path::Path) -> Vec<String> {
names
}
#[test]
fn a_missing_card_portrait_is_downloaded_once_then_read_from_disk() {
let dir = tempfile::tempdir().unwrap();
let source = FakeChampions::new("1.0", &CATALOG);
let calls = source.card_counter();
let tracker = reopen(dir.path(), source);
tracker.refresh_champions().unwrap();
assert!(
statistics(&tracker)
.rows
.iter()
.all(|r| r.card_portrait.is_none())
);
let mut saved = 0;
tracker
.refresh_card_portraits(&mut |ok| saved += usize::from(ok))
.unwrap();
assert_eq!((saved, calls.load(Ordering::SeqCst)), (6, 6));
let stats = statistics(&tracker);
for row in &stats.rows {
let path = cards_dir(dir.path()).join(format!("{}.jpg", row.champion.key));
assert_eq!(row.card_portrait.as_ref(), Some(&path));
let card = image::open(&path).unwrap();
// The 40 x 60 art is smaller than a card: cropped to the card's shape, not enlarged.
assert_eq!((card.width(), card.height()), (40, 59));
}
let mut saved_again = 0;
tracker
.refresh_card_portraits(&mut |ok| saved_again += usize::from(ok))
.unwrap();
assert_eq!((saved_again, calls.load(Ordering::SeqCst)), (0, 6));
}
#[test]
fn a_failed_card_download_leaves_no_file_and_the_next_pass_resumes() {
let dir = tempfile::tempdir().unwrap();
let source = FakeChampions::new("1.0", &CATALOG);
let failure = source.card_failure();
let calls = source.card_counter();
let tracker = reopen(dir.path(), source);
tracker.refresh_champions().unwrap();
failure.store(true, Ordering::SeqCst);
let mut saved = 0;
tracker
.refresh_card_portraits(&mut |ok| saved += usize::from(ok))
.unwrap();
assert_eq!(saved, 0);
assert!(card_files(dir.path()).is_empty());
assert!(
statistics(&tracker)
.rows
.iter()
.all(|r| r.card_portrait.is_none())
);
failure.store(false, Ordering::SeqCst);
tracker
.refresh_card_portraits(&mut |ok| saved += usize::from(ok))
.unwrap();
assert_eq!(saved, 6);
assert_eq!(card_files(dir.path()).len(), 6);
// One request failed the first pass; the second asked for the six.
assert_eq!(calls.load(Ordering::SeqCst), 7);
assert!(
statistics(&tracker)
.rows
.iter()
.all(|r| r.card_portrait.is_some())
);
}
#[test]
fn a_network_error_stops_the_card_pass_after_one_request() {
let dir = tempfile::tempdir().unwrap();
let source = FakeChampions::new("1.0", &CATALOG);
let failure = source.card_failure();
let calls = source.card_counter();
let tracker = reopen(dir.path(), source);
tracker.refresh_champions().unwrap();
failure.store(true, Ordering::SeqCst);
let mut attempts = Vec::new();
tracker
.refresh_card_portraits(&mut |ok| attempts.push(ok))
.unwrap();
assert_eq!(calls.load(Ordering::SeqCst), 1);
assert_eq!(attempts, [false]);
}
#[test]
fn each_card_attempt_tells_whether_a_portrait_was_saved() {
let dir = tempfile::tempdir().unwrap();
let tracker = reopen(
dir.path(),
FakeChampions::new("1.0", &CATALOG).without_portrait("Jinx"),
);
tracker.refresh_champions().unwrap();
let mut attempts = Vec::new();
tracker
.refresh_card_portraits(&mut |ok| attempts.push(ok))
.unwrap();
assert_eq!(attempts.len(), 6);
assert_eq!(attempts.iter().filter(|ok| **ok).count(), 5);
}
#[test]
fn a_card_portrait_that_cannot_be_read_is_skipped_without_a_file() {
let dir = tempfile::tempdir().unwrap();
let tracker = reopen(
dir.path(),
FakeChampions::new("1.0", &CATALOG).with_card_art(b"<html>erreur</html>".to_vec()),
);
tracker.refresh_champions().unwrap();
let mut saved = 0;
tracker
.refresh_card_portraits(&mut |ok| saved += usize::from(ok))
.unwrap();
assert_eq!(saved, 0);
assert!(card_files(dir.path()).is_empty());
}
#[test]
fn one_failed_card_portrait_does_not_stop_the_others() {
let dir = tempfile::tempdir().unwrap();
let tracker = reopen(
dir.path(),
FakeChampions::new("1.0", &CATALOG).without_portrait("Jinx"),
);
tracker.refresh_champions().unwrap();
let mut saved = 0;
tracker
.refresh_card_portraits(&mut |ok| saved += usize::from(ok))
.unwrap();
assert_eq!(saved, 5);
assert!(!card_files(dir.path()).contains(&"Jinx.jpg".to_string()));
let stats = statistics(&tracker);
let jinx = stats
.rows
.iter()
.find(|r| r.champion.key == "Jinx")
.unwrap();
assert_eq!(jinx.card_portrait, None);
}
#[test]
fn refreshing_card_portraits_without_a_champion_source_does_nothing() {
let dir = tempfile::tempdir().unwrap();
let tracker = open_tracker(dir.path(), &[]);
tracker.refresh_card_portraits(&mut |_| {}).unwrap();
assert!(!dir.path().join("portraits").exists());
}
#[test]
fn refreshing_without_a_champion_source_does_nothing() {
let dir = tempfile::tempdir().unwrap();
let tracker = open_tracker(dir.path(), &[]);
tracker.refresh_champions().unwrap();
assert!(!dir.path().join("portraits").exists());
}
#[test]
fn splash_downloads_resume_after_a_network_error_and_only_fetch_new_champions() {
let dir = tempfile::tempdir().unwrap();
let source = FakeChampions::new("1", &CATALOG[..3]);
let failure = source.card_failure();
let splash_calls = source.splash_calls.clone();
let loading_calls = source.card_counter();
let tracker = reopen(dir.path(), source);
let mut attempts = Vec::new();
tracker
.refresh_champion_art(|| {}, &mut |saved| {
attempts.push(saved);
// Three cards, then one splash. The next splash loses the network.
if attempts.len() == 4 {
failure.store(true, Ordering::SeqCst);
}
})
.unwrap();
assert_eq!(attempts, [true, true, true, true, false]);
assert_eq!(splash_calls.load(Ordering::SeqCst), 2);
assert_eq!(loading_calls.load(Ordering::SeqCst), 3);
let first = statistics(&tracker)
.rows
.into_iter()
.filter_map(|r| r.splash)
.collect::<Vec<_>>();
assert_eq!(first.len(), 1);
// (59 + 40/2, 6 + 0.30*60) in a 112 x 75 splash.
assert!(
first[0].focus.x.abs_diff(71) <= 1 && first[0].focus.y.abs_diff(32) <= 1,
"{:?}",
first[0].focus
);
assert_eq!(std::fs::read(&first[0].path).unwrap(), common::splash_art());
drop(tracker);
let next = FakeChampions::new("2", &CATALOG[..4]);
let calls = next.splash_calls.clone();
let loading_calls = next.card_counter();
let tracker = reopen(dir.path(), next);
tracker
.refresh_champion_art(|| {}, &mut |ok| assert!(ok))
.unwrap();
let splashes = statistics(&tracker)
.rows
.into_iter()
.filter_map(|r| r.splash)
.collect::<Vec<_>>();
assert_eq!(splashes.len(), 4);
assert!(splashes.contains(&first[0]));
tracker
.refresh_champion_art(|| {}, &mut |_| panic!("already cached"))
.unwrap();
assert_eq!(calls.load(Ordering::SeqCst), 3);
assert_eq!(loading_calls.load(Ordering::SeqCst), 3);
}
#[test]
fn missing_loading_art_still_saves_the_original_splash_once_with_fixed_focus() {
for cached_card in [false, true] {
let dir = tempfile::tempdir().unwrap();
let catalog = &CATALOG[..1];
if cached_card {
let tracker = reopen(dir.path(), FakeChampions::new("1", catalog));
tracker.refresh_champions().unwrap();
tracker.refresh_card_portraits(&mut |_| {}).unwrap();
}
let source = FakeChampions::new("1", catalog).without_portrait("Annie");
let calls = source.splash_calls.clone();
let tracker = reopen(dir.path(), source);
tracker.refresh_champion_art(|| {}, &mut |_| {}).unwrap();
let splash = statistics(&tracker).rows.remove(0).splash.unwrap();
assert_eq!((splash.focus.x, splash.focus.y), (50, 30));
assert_eq!(std::fs::read(splash.path).unwrap(), common::splash_art());
tracker.refresh_champion_art(|| {}, &mut |_| {}).unwrap();
assert_eq!(calls.load(Ordering::SeqCst), 1);
}
}
#[test]
fn a_temporarily_unreadable_loading_image_is_retried_before_caching_the_splash() {
let dir = tempfile::tempdir().unwrap();
let source = FakeChampions::new("1", &CATALOG[..1]).with_card_art(b"not a JPEG".to_vec());
let splash_calls = source.splash_calls.clone();
let tracker = reopen(dir.path(), source);
tracker.refresh_champion_art(|| {}, &mut |_| {}).unwrap();
assert!(statistics(&tracker).rows.iter().all(|r| r.splash.is_none()));
assert_eq!(splash_calls.load(Ordering::SeqCst), 0);
let tracker = reopen(dir.path(), FakeChampions::new("1", &CATALOG[..1]));
tracker
.refresh_champion_art(|| {}, &mut |saved| assert!(saved))
.unwrap();
assert!(statistics(&tracker).rows.iter().all(|r| r.splash.is_some()));
}
#[test]
fn an_offline_launch_keeps_the_cached_catalog_and_makes_no_art_requests() {
let dir = tempfile::tempdir().unwrap();
reopen(dir.path(), FakeChampions::new("1", &CATALOG))
.refresh_champions()
.unwrap();
let source = FakeChampions::new("1", &CATALOG).failing();
let cards = source.card_counter();
let splashes = source.splash_calls.clone();
let tracker = reopen(dir.path(), source);
let mut notified = false;
assert!(
tracker
.refresh_champion_art(|| notified = true, &mut |_| panic!("offline art attempt"))
.is_err()
);
assert!(notified);
assert_eq!(statistics(&tracker).rows.len(), CATALOG.len());
assert_eq!(cards.load(Ordering::SeqCst), 0);
assert_eq!(splashes.load(Ordering::SeqCst), 0);
}
#[test]
fn losing_the_network_during_cards_skips_all_splashes() {
let dir = tempfile::tempdir().unwrap();
let source = FakeChampions::new("1", &CATALOG);
source.card_failure().store(true, Ordering::SeqCst);
let calls = source.splash_calls.clone();
let tracker = reopen(dir.path(), source);
let mut attempts = Vec::new();
tracker
.refresh_champion_art(|| {}, &mut |saved| attempts.push(saved))
.unwrap();
assert_eq!(attempts, [false]);
assert_eq!(calls.load(Ordering::SeqCst), 0);
open_tracker(dir.path(), &[])
.refresh_champion_art(|| {}, &mut |_| panic!("no source"))
.unwrap();
}
#[test]
fn load_seasons_writes_the_shipped_table_when_the_file_is_missing() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("sub").join("seasons.toml");
let seasons = load_seasons(&path).unwrap();
assert_eq!(seasons, default_seasons());
assert!(
std::fs::read_to_string(&path)
.unwrap()
.contains("[[season]]")
);
assert_eq!(load_seasons(&path).unwrap(), seasons);
}
#[test]
fn load_seasons_reads_the_edited_file_sorted_by_start() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("seasons.toml");
std::fs::write(
&path,
"[[season]]\nname = \"Plus tard\"\nstart = 2027-02-01\nofficial_track = \"Piste X\"\n\n[[season]]\nname = \"Avant\"\nstart = 2026-12-31\n",
)
.unwrap();
let seasons = load_seasons(&path).unwrap();
let summary: Vec<_> = seasons
.iter()
.map(|s| (s.name.as_str(), s.start.to_string()))
.collect();
assert_eq!(
summary,
[
("Avant", "31/12/2026".to_string()),
("Plus tard", "01/02/2027".to_string())
]
);
let tracks: Vec<_> = seasons
.iter()
.map(|s| s.official_track.as_deref())
.collect();
assert_eq!(tracks, [None, Some("Piste X")]);
}
#[test]
fn load_seasons_rejects_invalid_files() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("seasons.toml");
for bad in [
"pas du toml",
"",
"[[season]]\nname = \"X\"\nstart = 2026-01-01T10:00:00\n",
"[[season]]\nname = \"X\"\nstart = 2026-01-01T10:00:00Z\n",
"[[season]]\nname = \"X\"\nstart = \"2026-01-01\"\n",
"[[season]]\nname = \"X\"\n",
"[[season]]\nstart = 2026-01-01\n",
] {
std::fs::write(&path, bad).unwrap();
assert!(
matches!(load_seasons(&path), Err(Error::Config(_))),
"{bad:?}"
);
}
}
#[path = "champions/cards.rs"]
mod cards;
#[path = "champions/catalog.rs"]
mod catalog;
#[path = "champions/seasons.rs"]
mod seasons;
#[path = "champions/splashes.rs"]
mod splashes;
+186
View File
@@ -0,0 +1,186 @@
use super::*;
#[test]
fn a_missing_card_portrait_is_downloaded_once_then_read_from_disk() {
let dir = tempfile::tempdir().unwrap();
let source = FakeChampions::new("1.0", &CATALOG);
let calls = source.card_counter();
let tracker = reopen(dir.path(), source);
tracker.refresh_champions().unwrap();
assert!(
statistics(&tracker)
.rows
.iter()
.all(|r| r.card_portrait.is_none())
);
let mut saved = 0;
tracker
.refresh_card_portraits(&mut |ok| saved += usize::from(ok))
.unwrap();
assert_eq!((saved, calls.load(Ordering::SeqCst)), (6, 6));
let stats = statistics(&tracker);
for row in &stats.rows {
let path = cards_dir(dir.path()).join(format!("{}.jpg", row.champion.key));
assert_eq!(row.card_portrait.as_ref(), Some(&path));
let card = image::open(&path).unwrap();
// The 40 x 60 art is smaller than a card: cropped to the card's shape, not enlarged.
assert_eq!((card.width(), card.height()), (40, 59));
}
let mut saved_again = 0;
tracker
.refresh_card_portraits(&mut |ok| saved_again += usize::from(ok))
.unwrap();
assert_eq!((saved_again, calls.load(Ordering::SeqCst)), (0, 6));
}
#[test]
fn a_failed_card_download_leaves_no_file_and_the_next_pass_resumes() {
let dir = tempfile::tempdir().unwrap();
let source = FakeChampions::new("1.0", &CATALOG);
let failure = source.card_failure();
let calls = source.card_counter();
let tracker = reopen(dir.path(), source);
tracker.refresh_champions().unwrap();
failure.store(true, Ordering::SeqCst);
let mut saved = 0;
tracker
.refresh_card_portraits(&mut |ok| saved += usize::from(ok))
.unwrap();
assert_eq!(saved, 0);
assert!(card_files(dir.path()).is_empty());
assert!(
statistics(&tracker)
.rows
.iter()
.all(|r| r.card_portrait.is_none())
);
failure.store(false, Ordering::SeqCst);
tracker
.refresh_card_portraits(&mut |ok| saved += usize::from(ok))
.unwrap();
assert_eq!(saved, 6);
assert_eq!(card_files(dir.path()).len(), 6);
// One request failed the first pass; the second asked for the six.
assert_eq!(calls.load(Ordering::SeqCst), 7);
assert!(
statistics(&tracker)
.rows
.iter()
.all(|r| r.card_portrait.is_some())
);
}
#[test]
fn a_network_error_stops_the_card_pass_after_one_request() {
let dir = tempfile::tempdir().unwrap();
let source = FakeChampions::new("1.0", &CATALOG);
let failure = source.card_failure();
let calls = source.card_counter();
let tracker = reopen(dir.path(), source);
tracker.refresh_champions().unwrap();
failure.store(true, Ordering::SeqCst);
let mut attempts = Vec::new();
tracker
.refresh_card_portraits(&mut |ok| attempts.push(ok))
.unwrap();
assert_eq!(calls.load(Ordering::SeqCst), 1);
assert_eq!(attempts, [false]);
}
#[test]
fn each_card_attempt_tells_whether_a_portrait_was_saved() {
let dir = tempfile::tempdir().unwrap();
let tracker = reopen(
dir.path(),
FakeChampions::new("1.0", &CATALOG).without_portrait("Jinx"),
);
tracker.refresh_champions().unwrap();
let mut attempts = Vec::new();
tracker
.refresh_card_portraits(&mut |ok| attempts.push(ok))
.unwrap();
assert_eq!(attempts.len(), 6);
assert_eq!(attempts.iter().filter(|ok| **ok).count(), 5);
}
#[test]
fn a_card_portrait_that_cannot_be_read_is_skipped_without_a_file() {
let dir = tempfile::tempdir().unwrap();
let tracker = reopen(
dir.path(),
FakeChampions::new("1.0", &CATALOG).with_card_art(b"<html>erreur</html>".to_vec()),
);
tracker.refresh_champions().unwrap();
let mut saved = 0;
tracker
.refresh_card_portraits(&mut |ok| saved += usize::from(ok))
.unwrap();
assert_eq!(saved, 0);
assert!(card_files(dir.path()).is_empty());
}
#[test]
fn one_failed_card_portrait_does_not_stop_the_others() {
let dir = tempfile::tempdir().unwrap();
let tracker = reopen(
dir.path(),
FakeChampions::new("1.0", &CATALOG).without_portrait("Jinx"),
);
tracker.refresh_champions().unwrap();
let mut saved = 0;
tracker
.refresh_card_portraits(&mut |ok| saved += usize::from(ok))
.unwrap();
assert_eq!(saved, 5);
assert!(!card_files(dir.path()).contains(&"Jinx.jpg".to_string()));
let stats = statistics(&tracker);
let jinx = stats
.rows
.iter()
.find(|r| r.champion.key == "Jinx")
.unwrap();
assert_eq!(jinx.card_portrait, None);
}
#[test]
fn refreshing_card_portraits_without_a_champion_source_does_nothing() {
let dir = tempfile::tempdir().unwrap();
let tracker = open_tracker(dir.path(), &[]);
tracker.refresh_card_portraits(&mut |_| {}).unwrap();
assert!(!dir.path().join("portraits").exists());
}
#[test]
fn losing_the_network_during_cards_skips_all_splashes() {
let dir = tempfile::tempdir().unwrap();
let source = FakeChampions::new("1", &CATALOG);
source.card_failure().store(true, Ordering::SeqCst);
let calls = source.splash_calls.clone();
let tracker = reopen(dir.path(), source);
let mut attempts = Vec::new();
tracker
.refresh_champion_art(|| {}, &mut |saved| attempts.push(saved))
.unwrap();
assert_eq!(attempts, [false]);
assert_eq!(calls.load(Ordering::SeqCst), 0);
open_tracker(dir.path(), &[])
.refresh_champion_art(|| {}, &mut |_| panic!("no source"))
.unwrap();
}
+189
View File
@@ -0,0 +1,189 @@
use super::*;
#[test]
fn the_catalog_is_fetched_once_while_the_game_version_is_unchanged() {
let dir = tempfile::tempdir().unwrap();
let first = FakeChampions::new("1.0", &CATALOG);
let first_calls = first.catalog_counter();
let tracker = reopen(dir.path(), first);
tracker.refresh_champions().unwrap();
tracker.refresh_champions().unwrap();
assert_eq!(first_calls.load(Ordering::SeqCst), 1);
assert_eq!(statistics(&tracker).challenge.unwrap().total, 6);
drop(tracker);
let same_version = FakeChampions::new("1.0", &CATALOG);
let same_calls = same_version.catalog_counter();
reopen(dir.path(), same_version)
.refresh_champions()
.unwrap();
assert_eq!(same_calls.load(Ordering::SeqCst), 0);
let mut grown = CATALOG.to_vec();
grown.push((777, "Newcomer", "Nouveau"));
let new_version = FakeChampions::new("2.0", &grown);
let new_calls = new_version.catalog_counter();
let tracker = reopen(dir.path(), new_version);
tracker.refresh_champions().unwrap();
assert_eq!(new_calls.load(Ordering::SeqCst), 1);
assert_eq!(statistics(&tracker).challenge.unwrap().total, 7);
}
#[test]
fn a_failing_source_leaves_the_cached_catalog_usable() {
let dir = tempfile::tempdir().unwrap();
reopen(dir.path(), FakeChampions::new("1.0", &CATALOG))
.refresh_champions()
.unwrap();
let offline = reopen(dir.path(), FakeChampions::new("2.0", &CATALOG).failing());
assert!(matches!(offline.refresh_champions(), Err(Error::Source(_))));
assert_eq!(statistics(&offline).challenge.unwrap().total, 6);
}
#[test]
fn without_any_catalog_the_page_shows_the_champions_played() {
let dir = tempfile::tempdir().unwrap();
let tracker = open_tracker(dir.path(), &[played_match(1, 3, jan_2026(2, 0))]).with_champions(
Box::new(FakeChampions::new("1.0", &CATALOG).failing()),
dir.path().join("portraits"),
);
assert!(tracker.refresh_champions().is_err());
tracker.sync(common::RIOT_ID, &mut |_| {}).unwrap();
let stats = statistics(&tracker);
assert_eq!(row_names(&stats), ["Annie"]);
assert_eq!(stats.challenge.unwrap().total, 1);
}
#[test]
fn a_champion_played_but_absent_from_the_catalog_still_gets_a_row() {
let dir = tempfile::tempdir().unwrap();
let tracker = open_tracker(dir.path(), &[played_match(1, 3, jan_2026(2, 0))]).with_champions(
Box::new(FakeChampions::new("1.0", &CATALOG[1..])),
dir.path().join("portraits"),
);
tracker.refresh_champions().unwrap();
tracker.sync(common::RIOT_ID, &mut |_| {}).unwrap();
let stats = statistics(&tracker);
assert_eq!(stats.rows.len(), 6);
let annie = stats.rows.iter().find(|r| r.champion.id == 1).unwrap();
assert_eq!(
(annie.champion.key.as_str(), annie.champion.name.as_str()),
("Annie", "Annie")
);
assert_eq!(annie.state, Some(ChampionState::InProgress));
assert_eq!(stats.challenge.unwrap().total, 6);
}
#[test]
fn rows_are_ordered_by_champion_name_in_french_order() {
let dir = tempfile::tempdir().unwrap();
let champions = [
(1, "Zoe", "Zoé"),
(2, "Zed", "Zed"),
(11, "MasterYi", "Maître Yi"),
(3, "Nami", "Nami"),
];
let tracker = reopen(dir.path(), FakeChampions::new("1.0", &champions));
tracker.refresh_champions().unwrap();
assert_eq!(
row_names(&statistics(&tracker)),
["Maître Yi", "Nami", "Zed", "Zoé"]
);
}
#[test]
fn portraits_are_downloaded_and_exposed_and_a_failed_one_is_left_out() {
let dir = tempfile::tempdir().unwrap();
let tracker = reopen(
dir.path(),
FakeChampions::new("1.0", &CATALOG).without_portrait("Jinx"),
);
assert!(
statistics(&tracker)
.rows
.iter()
.all(|r| r.portrait.is_none())
);
tracker.refresh_champions().unwrap();
let stats = statistics(&tracker);
let portraits = dir.path().join("portraits");
for row in &stats.rows {
if row.champion.key == "Jinx" {
assert_eq!(row.portrait, None);
} else {
let path = portraits.join(format!("{}.png", row.champion.key));
assert_eq!(row.portrait.as_ref(), Some(&path));
assert_eq!(
std::fs::read(&path).unwrap(),
format!("png of {}", row.champion.key).into_bytes()
);
}
}
assert!(!portraits.join("Jinx.part").exists());
}
#[test]
fn only_files_count_as_portraits() {
let dir = tempfile::tempdir().unwrap();
let tracker = reopen(dir.path(), FakeChampions::new("1.0", &CATALOG));
tracker.refresh_champions().unwrap();
let portraits = dir.path().join("portraits");
std::fs::remove_file(portraits.join("Jinx.png")).unwrap();
std::fs::create_dir(portraits.join("Jinx.png")).unwrap();
let stats = statistics(&tracker);
let jinx = stats
.rows
.iter()
.find(|r| r.champion.key == "Jinx")
.unwrap();
assert_eq!(jinx.portrait, None);
assert_eq!(
stats.rows.iter().filter(|r| r.portrait.is_some()).count(),
5
);
}
#[test]
fn refreshing_without_a_champion_source_does_nothing() {
let dir = tempfile::tempdir().unwrap();
let tracker = open_tracker(dir.path(), &[]);
tracker.refresh_champions().unwrap();
assert!(!dir.path().join("portraits").exists());
}
#[test]
fn an_offline_launch_keeps_the_cached_catalog_and_makes_no_art_requests() {
let dir = tempfile::tempdir().unwrap();
reopen(dir.path(), FakeChampions::new("1", &CATALOG))
.refresh_champions()
.unwrap();
let source = FakeChampions::new("1", &CATALOG).failing();
let cards = source.card_counter();
let splashes = source.splash_calls.clone();
let tracker = reopen(dir.path(), source);
let mut notified = false;
assert!(
tracker
.refresh_champion_art(|| notified = true, &mut |_| panic!("offline art attempt"))
.is_err()
);
assert!(notified);
assert_eq!(statistics(&tracker).rows.len(), CATALOG.len());
assert_eq!(cards.load(Ordering::SeqCst), 0);
assert_eq!(splashes.load(Ordering::SeqCst), 0);
}
+68
View File
@@ -0,0 +1,68 @@
use super::*;
#[test]
fn load_seasons_writes_the_shipped_table_when_the_file_is_missing() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("sub").join("seasons.toml");
let seasons = load_seasons(&path).unwrap();
assert_eq!(seasons, default_seasons());
assert!(
std::fs::read_to_string(&path)
.unwrap()
.contains("[[season]]")
);
assert_eq!(load_seasons(&path).unwrap(), seasons);
}
#[test]
fn load_seasons_reads_the_edited_file_sorted_by_start() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("seasons.toml");
std::fs::write(
&path,
"[[season]]\nname = \"Plus tard\"\nstart = 2027-02-01\nofficial_track = \"Piste X\"\n\n[[season]]\nname = \"Avant\"\nstart = 2026-12-31\n",
)
.unwrap();
let seasons = load_seasons(&path).unwrap();
let summary: Vec<_> = seasons
.iter()
.map(|s| (s.name.as_str(), s.start.to_string()))
.collect();
assert_eq!(
summary,
[
("Avant", "31/12/2026".to_string()),
("Plus tard", "01/02/2027".to_string())
]
);
let tracks: Vec<_> = seasons
.iter()
.map(|s| s.official_track.as_deref())
.collect();
assert_eq!(tracks, [None, Some("Piste X")]);
}
#[test]
fn load_seasons_rejects_invalid_files() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("seasons.toml");
for bad in [
"pas du toml",
"",
"[[season]]\nname = \"X\"\nstart = 2026-01-01T10:00:00\n",
"[[season]]\nname = \"X\"\nstart = 2026-01-01T10:00:00Z\n",
"[[season]]\nname = \"X\"\nstart = \"2026-01-01\"\n",
"[[season]]\nname = \"X\"\n",
"[[season]]\nstart = 2026-01-01\n",
] {
std::fs::write(&path, bad).unwrap();
assert!(
matches!(load_seasons(&path), Err(Error::Config(_))),
"{bad:?}"
);
}
}
+98
View File
@@ -0,0 +1,98 @@
use super::*;
#[test]
fn splash_downloads_resume_after_a_network_error_and_only_fetch_new_champions() {
let dir = tempfile::tempdir().unwrap();
let source = FakeChampions::new("1", &CATALOG[..3]);
let failure = source.card_failure();
let splash_calls = source.splash_calls.clone();
let loading_calls = source.card_counter();
let tracker = reopen(dir.path(), source);
let mut attempts = Vec::new();
tracker
.refresh_champion_art(|| {}, &mut |saved| {
attempts.push(saved);
// Three cards, then one splash. The next splash loses the network.
if attempts.len() == 4 {
failure.store(true, Ordering::SeqCst);
}
})
.unwrap();
assert_eq!(attempts, [true, true, true, true, false]);
assert_eq!(splash_calls.load(Ordering::SeqCst), 2);
assert_eq!(loading_calls.load(Ordering::SeqCst), 3);
let first = statistics(&tracker)
.rows
.into_iter()
.filter_map(|r| r.splash)
.collect::<Vec<_>>();
assert_eq!(first.len(), 1);
// (59 + 40/2, 6 + 0.30*60) in a 112 x 75 splash.
assert!(
first[0].focus.x.abs_diff(71) <= 1 && first[0].focus.y.abs_diff(32) <= 1,
"{:?}",
first[0].focus
);
assert_eq!(std::fs::read(&first[0].path).unwrap(), common::splash_art());
drop(tracker);
let next = FakeChampions::new("2", &CATALOG[..4]);
let calls = next.splash_calls.clone();
let loading_calls = next.card_counter();
let tracker = reopen(dir.path(), next);
tracker
.refresh_champion_art(|| {}, &mut |ok| assert!(ok))
.unwrap();
let splashes = statistics(&tracker)
.rows
.into_iter()
.filter_map(|r| r.splash)
.collect::<Vec<_>>();
assert_eq!(splashes.len(), 4);
assert!(splashes.contains(&first[0]));
tracker
.refresh_champion_art(|| {}, &mut |_| panic!("already cached"))
.unwrap();
assert_eq!(calls.load(Ordering::SeqCst), 3);
assert_eq!(loading_calls.load(Ordering::SeqCst), 3);
}
#[test]
fn missing_loading_art_still_saves_the_original_splash_once_with_fixed_focus() {
for cached_card in [false, true] {
let dir = tempfile::tempdir().unwrap();
let catalog = &CATALOG[..1];
if cached_card {
let tracker = reopen(dir.path(), FakeChampions::new("1", catalog));
tracker.refresh_champions().unwrap();
tracker.refresh_card_portraits(&mut |_| {}).unwrap();
}
let source = FakeChampions::new("1", catalog).without_portrait("Annie");
let calls = source.splash_calls.clone();
let tracker = reopen(dir.path(), source);
tracker.refresh_champion_art(|| {}, &mut |_| {}).unwrap();
let splash = statistics(&tracker).rows.remove(0).splash.unwrap();
assert_eq!((splash.focus.x, splash.focus.y), (50, 30));
assert_eq!(std::fs::read(splash.path).unwrap(), common::splash_art());
tracker.refresh_champion_art(|| {}, &mut |_| {}).unwrap();
assert_eq!(calls.load(Ordering::SeqCst), 1);
}
}
#[test]
fn a_temporarily_unreadable_loading_image_is_retried_before_caching_the_splash() {
let dir = tempfile::tempdir().unwrap();
let source = FakeChampions::new("1", &CATALOG[..1]).with_card_art(b"not a JPEG".to_vec());
let splash_calls = source.splash_calls.clone();
let tracker = reopen(dir.path(), source);
tracker.refresh_champion_art(|| {}, &mut |_| {}).unwrap();
assert!(statistics(&tracker).rows.iter().all(|r| r.splash.is_none()));
assert_eq!(splash_calls.load(Ordering::SeqCst), 0);
let tracker = reopen(dir.path(), FakeChampions::new("1", &CATALOG[..1]));
tracker
.refresh_champion_art(|| {}, &mut |saved| assert!(saved))
.unwrap();
assert!(statistics(&tracker).rows.iter().all(|r| r.splash.is_some()));
}
+147
View File
@@ -0,0 +1,147 @@
use super::*;
/// Champion reference data served from memory.
pub struct FakeChampions {
version: String,
champions: Vec<Champion>,
failing: bool,
no_portrait: Vec<String>,
catalog_calls: Arc<AtomicUsize>,
/// What every card portrait download delivers.
card_art: Vec<u8>,
/// The card portrait downloads fail with a network error while this is set.
card_failure: Arc<AtomicBool>,
card_calls: Arc<AtomicUsize>,
pub splash_calls: Arc<AtomicUsize>,
}
/// A small valid JPEG, tall like the loading art (40 x 60 px).
pub fn card_art() -> Vec<u8> {
let img = image::RgbImage::from_fn(40, 60, |x, y| image::Rgb([x as u8 * 6, y as u8 * 4, 90]));
let mut out = Vec::new();
image::codecs::jpeg::JpegEncoder::new(&mut out)
.encode(img.as_raw(), 40, 60, image::ExtendedColorType::Rgb8)
.unwrap();
out
}
/// The loading art at (59, 6) in a landscape JPEG.
pub fn splash_art() -> Vec<u8> {
let card = image::load_from_memory(&card_art()).unwrap().into_rgb8();
let mut splash = image::RgbImage::new(112, 75);
image::imageops::replace(&mut splash, &card, 59, 6);
let mut out = Vec::new();
image::codecs::jpeg::JpegEncoder::new(&mut out)
.encode_image(&splash)
.unwrap();
out
}
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(),
card_art: card_art(),
card_failure: Arc::default(),
card_calls: Arc::default(),
splash_calls: Arc::default(),
}
}
/// Every card portrait download delivers these bytes.
pub fn with_card_art(mut self, bytes: Vec<u8>) -> FakeChampions {
self.card_art = bytes;
self
}
/// Set it to make the card portrait downloads fail (and clear it to let them succeed).
pub fn card_failure(&self) -> Arc<AtomicBool> {
self.card_failure.clone()
}
/// Card portrait downloads attempted.
pub fn card_counter(&self) -> Arc<AtomicUsize> {
self.card_calls.clone()
}
/// 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<AtomicUsize> {
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<String, SourceError> {
self.check()?;
Ok(self.version.clone())
}
fn catalog(&self, version: &str) -> Result<ChampionCatalog, SourceError> {
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<Vec<u8>, SourceError> {
self.check()?;
if self.no_portrait.iter().any(|k| k == key) {
return Err(SourceError::NotFound);
}
Ok(format!("png of {key}").into_bytes())
}
fn card_portrait(&self, key: &str) -> Result<Vec<u8>, SourceError> {
self.card_calls.fetch_add(1, Ordering::SeqCst);
self.check()?;
if self.card_failure.load(Ordering::SeqCst) {
return Err(SourceError::Network("coupé".into()));
}
if self.no_portrait.iter().any(|k| k == key) {
return Err(SourceError::NotFound);
}
Ok(self.card_art.clone())
}
fn splash(&self, _: &str) -> Result<Vec<u8>, SourceError> {
self.splash_calls.fetch_add(1, Ordering::SeqCst);
self.check()?;
if self.card_failure.load(Ordering::SeqCst) {
return Err(SourceError::Network("coupé".into()));
}
Ok(splash_art())
}
}
+222
View File
@@ -0,0 +1,222 @@
use super::*;
/// 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<Mutex<ClientState>>,
/// Session and champion-list bodies the fake's champ select reader asked for.
session_reads: Arc<AtomicUsize>,
list_reads: Arc<AtomicUsize>,
}
#[derive(Default)]
struct ClientState {
signed_in: Option<(String, String)>,
gameflow: Gameflow,
tracks: HashMap<String, u32>,
waits: Vec<Duration>,
/// The raw bodies the client answers for the current champ select.
champ_select: Option<RawChampSelect>,
/// Reads the champ select the one way the live client does.
champ_select_reader: ChampSelectReader,
/// Session bodies the client reports as events, applied before `wait_for_event` returns.
events: VecDeque<Value>,
/// A raw gameflow body, replayed through the same parser as the live client.
raw_gameflow: Option<String>,
gameflow_error: Option<ClientError>,
champ_select_error: Option<ClientError>,
}
/// The raw client responses of a champ select, replayed through the same reader as the live
/// client.
#[derive(Clone)]
pub struct RawChampSelect {
pub pickable: String,
pub disabled: String,
/// `None` when the client's anvil list request fails.
pub anvil: Option<String>,
pub session: String,
}
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<Value> = 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.raw_gameflow = None;
state.gameflow = Gameflow {
phase: GamePhase::from_client(phase),
arena,
..state.gameflow.clone()
};
}
/// Replays a captured gameflow body through the live client's parser.
pub fn set_gameflow(&self, body: &str) {
self.state.lock().unwrap().raw_gameflow = Some(body.into());
}
/// The client's id of the game being played (kept across phases until changed).
pub fn set_game_id(&self, game_id: Option<u64>) {
self.state.lock().unwrap().gameflow.game_id = game_id;
}
pub fn set_champ_select(&self, raw: RawChampSelect) {
self.state.lock().unwrap().champ_select = Some(raw);
}
/// Reports one of the captured session bodies as the client's champ select event.
pub fn send_champ_select_event(&self, session: &str) {
let session = serde_json::from_str(session).unwrap_or(Value::Null);
self.state.lock().unwrap().events.push_back(session);
}
/// How many session and champion-list bodies the champ select reader asked the client for.
pub fn champ_select_reads(&self) -> (usize, usize) {
(
self.session_reads.load(Ordering::SeqCst),
self.list_reads.load(Ordering::SeqCst),
)
}
/// The next gameflow or champ select read fails with this, until cleared.
pub fn fail_gameflow(&self, error: Option<ClientError>) {
self.state.lock().unwrap().gameflow_error = error;
}
pub fn fail_champ_select(&self, error: Option<ClientError>) {
self.state.lock().unwrap().champ_select_error = error;
}
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<Duration> {
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<Gameflow, ClientError> {
let state = self.state.lock().unwrap();
state.signed_in.as_ref().ok_or(ClientError::Absent)?;
if let Some(error) = &state.gameflow_error {
return Err(error.clone());
}
let flow = match &state.raw_gameflow {
Some(body) => decode_gameflow(200, body)?,
None => state.gameflow.clone(),
};
state
.champ_select_reader
.reset_unless_arena_champ_select(&flow);
Ok(flow)
}
fn champ_select(&self) -> Result<ChampSelect, ClientError> {
let state = self.state.lock().unwrap();
if let Some(error) = &state.champ_select_error {
return Err(error.clone());
}
let raw = state.champ_select.as_ref().ok_or(ClientError::Absent)?;
let sessions = self.session_reads.clone();
let lists = self.list_reads.clone();
state.champ_select_reader.read(
|| {
sessions.fetch_add(1, Ordering::SeqCst);
Ok(raw.session.clone())
},
|| {
lists.fetch_add(1, Ordering::SeqCst);
Ok((
raw.pickable.clone(),
raw.disabled.clone(),
raw.anvil.clone(),
))
},
)
}
fn official_progress(&self, track_name: &str) -> Result<Option<u32>, 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_event(&self, timeout: Duration) -> ClientEvent {
let mut state = self.state.lock().unwrap();
state.waits.push(timeout);
match state.events.pop_front() {
Some(session) => {
state.champ_select_reader.set_session(session);
ClientEvent::ChampSelect
}
None => ClientEvent::Other,
}
}
}
+311
View File
@@ -0,0 +1,311 @@
use super::*;
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<String>,
/// 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<Account>,
listings: Mutex<Vec<Listing>>,
/// Every call fails with this until it is cleared.
failure: Mutex<Option<SourceError>>,
fail_after: Option<usize>,
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<Receiver<()>>)>,
fetches: Arc<AtomicUsize>,
listed: Arc<AtomicUsize>,
calls: Arc<AtomicUsize>,
/// Mastery Points by puuid, as Riot lists them (champions with points only).
mastery: Mutex<HashMap<String, Vec<(u32, u64)>>>,
/// Mastery requests fail with this until it is cleared.
mastery_failure: Mutex<Option<SourceError>>,
mastery_calls: Arc<AtomicUsize>,
}
impl FakeHistory {
pub fn new(account: Account, payloads: Vec<String>) -> 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(),
mastery: Mutex::default(),
mastery_failure: Mutex::default(),
mastery_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<String>) -> 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<String>) {
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<SourceError>) {
*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<AtomicUsize> {
self.fetches.clone()
}
/// Match ids returned by `match_ids`.
pub fn listed_counter(&self) -> Arc<AtomicUsize> {
self.listed.clone()
}
/// Calls of any kind made to the source.
pub fn call_counter(&self) -> Arc<AtomicUsize> {
self.calls.clone()
}
/// The Mastery Points Riot lists for this Account (without any, its mastery request
/// answers "not found").
pub fn with_mastery(self, puuid: &str, points: &[(u32, u64)]) -> FakeHistory {
self.set_mastery(puuid, points);
self
}
/// Replaces the Mastery Points Riot lists for this Account.
pub fn set_mastery(&self, puuid: &str, points: &[(u32, u64)]) {
self.mastery
.lock()
.unwrap()
.insert(puuid.into(), points.to_vec());
}
/// Every mastery request fails with this error until `None` is set (a sync is not affected).
pub fn fail_mastery_with(&self, error: Option<SourceError>) {
*self.mastery_failure.lock().unwrap() = error;
}
/// Mastery requests made, failed ones included. They are not counted by `call_counter`.
pub fn mastery_counter(&self) -> Arc<AtomicUsize> {
self.mastery_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<Account, SourceError> {
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<i64>,
) -> Result<Vec<String>, 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<String> = 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<String, SourceError> {
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)
}
fn champion_mastery(
&self,
_platform: &str,
puuid: &str,
) -> Result<Vec<(u32, u64)>, SourceError> {
self.mastery_calls.fetch_add(1, Ordering::SeqCst);
if let Some(error) = &*self.mastery_failure.lock().unwrap() {
return Err(error.clone());
}
self.mastery
.lock()
.unwrap()
.get(puuid)
.cloned()
.ok_or(SourceError::NotFound)
}
}
+16 -868
View File
@@ -16,875 +16,23 @@ use arena_tracker_core::{
};
use serde_json::Value;
pub const SELF_PUUID: &str = "fixture-puuid-self";
mod champions;
mod client;
mod history;
mod payloads;
mod scenarios;
const BASE: &str = include_str!("../fixtures/riot/match_1750_EUW1_9000000006.json");
/// The six recorded Riot payloads.
pub fn recorded_matches() -> Vec<String> {
[
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<String>,
/// 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<Account>,
listings: Mutex<Vec<Listing>>,
/// Every call fails with this until it is cleared.
failure: Mutex<Option<SourceError>>,
fail_after: Option<usize>,
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<Receiver<()>>)>,
fetches: Arc<AtomicUsize>,
listed: Arc<AtomicUsize>,
calls: Arc<AtomicUsize>,
/// Mastery Points by puuid, as Riot lists them (champions with points only).
mastery: Mutex<HashMap<String, Vec<(u32, u64)>>>,
/// Mastery requests fail with this until it is cleared.
mastery_failure: Mutex<Option<SourceError>>,
mastery_calls: Arc<AtomicUsize>,
}
impl FakeHistory {
pub fn new(account: Account, payloads: Vec<String>) -> 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(),
mastery: Mutex::default(),
mastery_failure: Mutex::default(),
mastery_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<String>) -> 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<String>) {
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<SourceError>) {
*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<AtomicUsize> {
self.fetches.clone()
}
/// Match ids returned by `match_ids`.
pub fn listed_counter(&self) -> Arc<AtomicUsize> {
self.listed.clone()
}
/// Calls of any kind made to the source.
pub fn call_counter(&self) -> Arc<AtomicUsize> {
self.calls.clone()
}
/// The Mastery Points Riot lists for this Account (without any, its mastery request
/// answers "not found").
pub fn with_mastery(self, puuid: &str, points: &[(u32, u64)]) -> FakeHistory {
self.set_mastery(puuid, points);
self
}
/// Replaces the Mastery Points Riot lists for this Account.
pub fn set_mastery(&self, puuid: &str, points: &[(u32, u64)]) {
self.mastery
.lock()
.unwrap()
.insert(puuid.into(), points.to_vec());
}
/// Every mastery request fails with this error until `None` is set (a sync is not affected).
pub fn fail_mastery_with(&self, error: Option<SourceError>) {
*self.mastery_failure.lock().unwrap() = error;
}
/// Mastery requests made, failed ones included. They are not counted by `call_counter`.
pub fn mastery_counter(&self) -> Arc<AtomicUsize> {
self.mastery_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<Account, SourceError> {
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<i64>,
) -> Result<Vec<String>, 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<String> = 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<String, SourceError> {
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)
}
fn champion_mastery(
&self,
_platform: &str,
puuid: &str,
) -> Result<Vec<(u32, u64)>, SourceError> {
self.mastery_calls.fetch_add(1, Ordering::SeqCst);
if let Some(error) = &*self.mastery_failure.lock().unwrap() {
return Err(error.clone());
}
self.mastery
.lock()
.unwrap()
.get(puuid)
.cloned()
.ok_or(SourceError::NotFound)
}
}
/// Champion reference data served from memory.
pub struct FakeChampions {
version: String,
champions: Vec<Champion>,
failing: bool,
no_portrait: Vec<String>,
catalog_calls: Arc<AtomicUsize>,
/// What every card portrait download delivers.
card_art: Vec<u8>,
/// The card portrait downloads fail with a network error while this is set.
card_failure: Arc<AtomicBool>,
card_calls: Arc<AtomicUsize>,
pub splash_calls: Arc<AtomicUsize>,
}
/// A small valid JPEG, tall like the loading art (40 x 60 px).
pub fn card_art() -> Vec<u8> {
let img = image::RgbImage::from_fn(40, 60, |x, y| image::Rgb([x as u8 * 6, y as u8 * 4, 90]));
let mut out = Vec::new();
image::codecs::jpeg::JpegEncoder::new(&mut out)
.encode(img.as_raw(), 40, 60, image::ExtendedColorType::Rgb8)
.unwrap();
out
}
/// The loading art at (59, 6) in a landscape JPEG.
pub fn splash_art() -> Vec<u8> {
let card = image::load_from_memory(&card_art()).unwrap().into_rgb8();
let mut splash = image::RgbImage::new(112, 75);
image::imageops::replace(&mut splash, &card, 59, 6);
let mut out = Vec::new();
image::codecs::jpeg::JpegEncoder::new(&mut out)
.encode_image(&splash)
.unwrap();
out
}
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(),
card_art: card_art(),
card_failure: Arc::default(),
card_calls: Arc::default(),
splash_calls: Arc::default(),
}
}
/// Every card portrait download delivers these bytes.
pub fn with_card_art(mut self, bytes: Vec<u8>) -> FakeChampions {
self.card_art = bytes;
self
}
/// Set it to make the card portrait downloads fail (and clear it to let them succeed).
pub fn card_failure(&self) -> Arc<AtomicBool> {
self.card_failure.clone()
}
/// Card portrait downloads attempted.
pub fn card_counter(&self) -> Arc<AtomicUsize> {
self.card_calls.clone()
}
/// 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<AtomicUsize> {
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<String, SourceError> {
self.check()?;
Ok(self.version.clone())
}
fn catalog(&self, version: &str) -> Result<ChampionCatalog, SourceError> {
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<Vec<u8>, SourceError> {
self.check()?;
if self.no_portrait.iter().any(|k| k == key) {
return Err(SourceError::NotFound);
}
Ok(format!("png of {key}").into_bytes())
}
fn card_portrait(&self, key: &str) -> Result<Vec<u8>, SourceError> {
self.card_calls.fetch_add(1, Ordering::SeqCst);
self.check()?;
if self.card_failure.load(Ordering::SeqCst) {
return Err(SourceError::Network("coupé".into()));
}
if self.no_portrait.iter().any(|k| k == key) {
return Err(SourceError::NotFound);
}
Ok(self.card_art.clone())
}
fn splash(&self, _: &str) -> Result<Vec<u8>, SourceError> {
self.splash_calls.fetch_add(1, Ordering::SeqCst);
self.check()?;
if self.card_failure.load(Ordering::SeqCst) {
return Err(SourceError::Network("coupé".into()));
}
Ok(splash_art())
}
}
// 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<Season> {
vec![
Season {
name: S1.into(),
start: date(2026, 1, 1),
official_track: None,
#[allow(unused_imports)]
pub use {
champions::{FakeChampions, card_art, splash_art},
client::{FakeClient, RawChampSelect, recorded_game_id},
history::FakeHistory,
payloads::{
SELF_PUUID, payload, played_by, recorded_account, recorded_matches, with_game_mode,
without_fields_for_others,
},
Season {
name: S2.into(),
start: date(2026, 4, 1),
official_track: Some(S2_TRACK.into()),
scenarios::{
CATALOG, HOUR_MS, PlayedMatch, RIOT_ID, S1, S2, S2_TRACK, at, date, imported_tracker,
jan_2026, open_tracker, payloads, played_match, run, seasons,
},
]
}
#[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<PlayedMatch> {
(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<String> {
(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<Mutex<ClientState>>,
/// Session and champion-list bodies the fake's champ select reader asked for.
session_reads: Arc<AtomicUsize>,
list_reads: Arc<AtomicUsize>,
}
#[derive(Default)]
struct ClientState {
signed_in: Option<(String, String)>,
gameflow: Gameflow,
tracks: HashMap<String, u32>,
waits: Vec<Duration>,
/// The raw bodies the client answers for the current champ select.
champ_select: Option<RawChampSelect>,
/// Reads the champ select the one way the live client does.
champ_select_reader: ChampSelectReader,
/// Session bodies the client reports as events, applied before `wait_for_event` returns.
events: VecDeque<Value>,
/// A raw gameflow body, replayed through the same parser as the live client.
raw_gameflow: Option<String>,
gameflow_error: Option<ClientError>,
champ_select_error: Option<ClientError>,
}
/// The raw client responses of a champ select, replayed through the same reader as the live
/// client.
#[derive(Clone)]
pub struct RawChampSelect {
pub pickable: String,
pub disabled: String,
/// `None` when the client's anvil list request fails.
pub anvil: Option<String>,
pub session: String,
}
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<Value> = 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.raw_gameflow = None;
state.gameflow = Gameflow {
phase: GamePhase::from_client(phase),
arena,
..state.gameflow.clone()
};
}
/// Replays a captured gameflow body through the live client's parser.
pub fn set_gameflow(&self, body: &str) {
self.state.lock().unwrap().raw_gameflow = Some(body.into());
}
/// The client's id of the game being played (kept across phases until changed).
pub fn set_game_id(&self, game_id: Option<u64>) {
self.state.lock().unwrap().gameflow.game_id = game_id;
}
pub fn set_champ_select(&self, raw: RawChampSelect) {
self.state.lock().unwrap().champ_select = Some(raw);
}
/// Reports one of the captured session bodies as the client's champ select event.
pub fn send_champ_select_event(&self, session: &str) {
let session = serde_json::from_str(session).unwrap_or(Value::Null);
self.state.lock().unwrap().events.push_back(session);
}
/// How many session and champion-list bodies the champ select reader asked the client for.
pub fn champ_select_reads(&self) -> (usize, usize) {
(
self.session_reads.load(Ordering::SeqCst),
self.list_reads.load(Ordering::SeqCst),
)
}
/// The next gameflow or champ select read fails with this, until cleared.
pub fn fail_gameflow(&self, error: Option<ClientError>) {
self.state.lock().unwrap().gameflow_error = error;
}
pub fn fail_champ_select(&self, error: Option<ClientError>) {
self.state.lock().unwrap().champ_select_error = error;
}
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<Duration> {
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<Gameflow, ClientError> {
let state = self.state.lock().unwrap();
state.signed_in.as_ref().ok_or(ClientError::Absent)?;
if let Some(error) = &state.gameflow_error {
return Err(error.clone());
}
let flow = match &state.raw_gameflow {
Some(body) => decode_gameflow(200, body)?,
None => state.gameflow.clone(),
};
state
.champ_select_reader
.reset_unless_arena_champ_select(&flow);
Ok(flow)
}
fn champ_select(&self) -> Result<ChampSelect, ClientError> {
let state = self.state.lock().unwrap();
if let Some(error) = &state.champ_select_error {
return Err(error.clone());
}
let raw = state.champ_select.as_ref().ok_or(ClientError::Absent)?;
let sessions = self.session_reads.clone();
let lists = self.list_reads.clone();
state.champ_select_reader.read(
|| {
sessions.fetch_add(1, Ordering::SeqCst);
Ok(raw.session.clone())
},
|| {
lists.fetch_add(1, Ordering::SeqCst);
Ok((
raw.pickable.clone(),
raw.disabled.clone(),
raw.anvil.clone(),
))
},
)
}
fn official_progress(&self, track_name: &str) -> Result<Option<u32>, 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_event(&self, timeout: Duration) -> ClientEvent {
let mut state = self.state.lock().unwrap();
state.waits.push(timeout);
match state.events.pop_front() {
Some(session) => {
state.champ_select_reader.set_session(session);
ClientEvent::ChampSelect
}
None => ClientEvent::Other,
}
}
}
+73
View File
@@ -0,0 +1,73 @@
use super::*;
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<String> {
[
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)
}
+125
View File
@@ -0,0 +1,125 @@
use super::*;
// 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<Season> {
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<PlayedMatch> {
(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<String> {
(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
}
File diff suppressed because it is too large. Load diff
+344
View File
@@ -0,0 +1,344 @@
use super::*;
#[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);
}
#[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 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);
}
+199
View File
@@ -0,0 +1,199 @@
use super::*;
#[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));
}
+290
View File
@@ -0,0 +1,290 @@
use super::*;
#[test]
fn only_a_live_insert_reports_what_the_match_brought_to_the_challenge() {
use arena_tracker_core::MatchEnd::*;
let world = World::new(&s2_matches());
let tracker = world.tracker();
let follow = || reported_round(&tracker);
assert!(follow().is_empty(), "history import");
for (i, (placement, expected)) in [
(6, Mark),
(2, Mark),
(3, Nothing),
(1, Completed),
(1, Nothing),
]
.into_iter()
.enumerate()
{
let id = common::recorded_game_id() + i as u64;
world.client.set_game_id(Some(id));
world.client.set_phase("InProgress", true);
assert!(follow().is_empty());
world.history.add_unlisted(payload(
&format!("EUW1_{id}"),
1750,
222,
"Jinx",
placement,
placement <= 3,
at(date(2026, 4, 5), i as i64),
));
world.client.set_phase("EndOfGame", true);
let events = follow();
assert_eq!(events.len(), 1);
assert_eq!((events[0].champion_id, events[0].end), (222, expected));
assert_eq!(events[0].puuid, SELF_PUUID);
assert_eq!(events[0].season, S2);
assert!(follow().is_empty());
}
}
#[test]
fn a_game_the_client_gave_no_id_for_is_reported_when_a_sync_stores_it() {
let world = World::new(&s2_matches());
let tracker = world.tracker();
assert!(reported_round(&tracker).is_empty(), "history import");
world.client.set_game_id(None);
world.client.set_phase("InProgress", true);
assert!(reported_round(&tracker).is_empty());
world.history.add(payload(
"EUW1_900",
1750,
222,
"Jinx",
6,
false,
now() + 60_000,
));
world.client.set_phase("EndOfGame", true);
let events = reported_round(&tracker);
assert_eq!(
events
.iter()
.map(|e| (e.champion_id, e.end))
.collect::<Vec<_>>(),
[(222, MatchEnd::Mark)]
);
assert!(reported_round(&tracker).is_empty());
}
#[test]
fn an_older_match_a_sync_brings_is_history_and_the_game_without_an_id_still_waits() {
let world = World::new(&s2_matches());
let tracker = world.tracker();
assert!(reported_round(&tracker).is_empty(), "history import");
world.client.set_game_id(None);
world.client.set_phase("InProgress", true);
assert!(reported_round(&tracker).is_empty());
// A game played before this one, newer than every Match stored, that Riot lists only now.
world.history.add(payload(
"EUW1_earlier",
1750,
11,
"Ahri",
2,
true,
now() - 30 * 60_000,
));
world.client.set_phase("EndOfGame", true);
assert!(reported_round(&tracker).is_empty());
assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 3);
// The followed game's Match, published later, is the one reported.
world.history.add(new_match("EUW1_followed", 1));
let events = reported_round(&tracker);
assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 4);
assert_eq!(
events
.iter()
.map(|e| (e.champion_id, e.end))
.collect::<Vec<_>>(),
[(222, MatchEnd::Completed)]
);
assert_eq!(tracker.status().problem, None);
let calls = world.source_calls();
assert!(reported_round(&tracker).is_empty());
assert_eq!(world.source_calls(), calls, "the wait is over");
}
#[test]
fn without_a_platform_the_first_import_reports_only_the_game_the_client_named() {
let world = World::new(&[]);
let tracker = world.tracker();
assert!(reported_round(&tracker).is_empty());
world.client.set_game_id(Some(common::recorded_game_id()));
world.client.set_phase("InProgress", true);
assert!(reported_round(&tracker).is_empty());
world.history.add(payload(
"EUW1_1",
1750,
11,
"Ahri",
3,
true,
at(date(2026, 4, 4), 1),
));
world.history.add(finished_match(1750));
world.client.set_phase("EndOfGame", true);
let events = reported_round(&tracker);
assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 2);
assert_eq!(
events
.iter()
.map(|e| (e.champion_id, e.end))
.collect::<Vec<_>>(),
[(222, MatchEnd::Completed)]
);
assert!(reported_round(&tracker).is_empty(), "already stored");
}
#[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);
}
+174
View File
@@ -0,0 +1,174 @@
use super::*;
#[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);
}
#[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)]);
}
+190
View File
@@ -0,0 +1,190 @@
use super::*;
#[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)
);
}
#[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"));
}
}
+8 -527
View File
@@ -76,301 +76,11 @@ fn started_at(matches: &[Match]) -> Vec<i64> {
matches.iter().map(|m| m.started_at_ms).collect()
}
#[test]
fn tracker_can_be_shared_between_threads() {
fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<Tracker>();
}
#[test]
fn imports_the_recorded_matches() {
let dir = tempfile::tempdir().unwrap();
let tracker = open(
&dir.path().join("arena.db"),
FakeHistory::new(recorded_account(), recorded_matches()),
);
let report = sync(&tracker);
assert_eq!(report.account, recorded_account());
assert_eq!((report.added, report.stored), (6, 6));
let mut want: Vec<Match> = recorded_matches().iter().map(|raw| expected(raw)).collect();
want.sort_by_key(|m| m.started_at_ms);
assert_eq!(tracker.matches(SELF_PUUID).unwrap(), want);
assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 6);
assert_eq!(tracker.accounts().unwrap(), [recorded_account()]);
}
#[test]
fn importing_twice_changes_nothing_and_fetches_nothing() {
let dir = tempfile::tempdir().unwrap();
let fake = FakeHistory::new(recorded_account(), recorded_matches());
let fetches = fake.fetch_counter();
let tracker = open(&dir.path().join("arena.db"), fake);
sync(&tracker);
let first = tracker.matches(SELF_PUUID).unwrap();
let report = sync(&tracker);
assert_eq!((report.added, report.stored), (0, 6));
assert_eq!(fetches.load(Ordering::SeqCst), 6);
assert_eq!(tracker.matches(SELF_PUUID).unwrap(), first);
}
#[test]
fn interrupted_import_keeps_what_was_stored_and_resumes_with_the_rest() {
let dir = tempfile::tempdir().unwrap();
let db = dir.path().join("arena.db");
let flaky = open(
&db,
FakeHistory::new(recorded_account(), five_matches(1_000_000)).failing_after(2),
);
let err = flaky.sync(RIOT_ID, &mut |_| {}).unwrap_err();
assert!(matches!(err, Error::Source(SourceError::Network(_))));
assert_eq!(flaky.match_count(SELF_PUUID).unwrap(), 2);
drop(flaky);
let healthy = FakeHistory::new(recorded_account(), five_matches(1_000_000));
let fetches = healthy.fetch_counter();
let tracker = open(&db, healthy);
assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 2);
let report = sync(&tracker);
// The two stored are the newest ones: the missing older ones are still found.
assert_eq!((report.added, report.stored), (3, 5));
assert_eq!(fetches.load(Ordering::SeqCst), 3);
assert_eq!(tracker.matches(SELF_PUUID).unwrap().len(), 5);
}
#[test]
fn later_sync_fetches_only_newer_matches() {
let dir = tempfile::tempdir().unwrap();
let db = dir.path().join("arena.db");
let days_apart = |from_s| five_matches_every(from_s, 10 * 24 * 3600);
sync(&open(
&db,
FakeHistory::new(recorded_account(), days_apart(1_000_000)),
));
let mut now_on_riot = days_apart(1_000_000);
now_on_riot.push(payload(
"EUW1_new1",
1750,
1,
"Annie",
1,
true,
4_500_000_000,
));
now_on_riot.push(payload(
"EUW1_new2",
1740,
2,
"Olaf",
3,
true,
4_501_000_000,
));
let fake = FakeHistory::new(recorded_account(), now_on_riot);
let (fetches, listed) = (fake.fetch_counter(), fake.listed_counter());
let tracker = open(&db, fake);
let report = sync(&tracker);
assert_eq!((report.added, report.stored), (2, 7));
assert_eq!(fetches.load(Ordering::SeqCst), 2);
// Riot is only asked for recent Matches: the newest stored one (listed again) and the new ones.
assert_eq!(listed.load(Ordering::SeqCst), 3);
}
#[test]
fn matches_are_returned_oldest_first_whatever_the_delivery_order() {
let dir = tempfile::tempdir().unwrap();
let mut payloads = five_matches(1_000_000);
payloads.swap(0, 3);
payloads.swap(1, 4);
let delivered: Vec<i64> = payloads.iter().map(|p| started_ms(p)).collect();
assert!(!delivered.is_sorted() && !delivered.iter().rev().is_sorted());
let tracker = open(
&dir.path().join("arena.db"),
FakeHistory::new(recorded_account(), payloads).delivered_as_given(),
);
sync(&tracker);
let started = started_at(&tracker.matches(SELF_PUUID).unwrap());
assert_eq!(started.len(), 5);
assert!(started.is_sorted());
}
fn started_ms(payload: &str) -> i64 {
let v: Value = serde_json::from_str(payload).unwrap();
v["info"]["gameStartTimestamp"].as_i64().unwrap()
}
#[test]
fn a_catch_up_cut_short_fetches_the_older_matches_next_time() {
let dir = tempfile::tempdir().unwrap();
let db = dir.path().join("arena.db");
let at = |hours: i64| (1_000_000 + hours * 3600) * 1000;
let known = payload("EUW1_1", 1750, 1, "A", 4, false, at(0));
sync(&open(
&db,
FakeHistory::new(recorded_account(), vec![known.clone()]),
));
// Three Matches played while the app was closed.
let mut on_riot = vec![known];
for i in 2..=4 {
let id = format!("EUW1_{i}");
on_riot.push(payload(&id, 1750, i, "B", 4, false, at(i64::from(i))));
}
// The catch-up stores the newest one, then dies.
let cut = open(
&db,
FakeHistory::new(recorded_account(), on_riot.clone()).failing_after(1),
);
assert!(cut.sync(RIOT_ID, &mut |_| {}).is_err());
assert_eq!(cut.match_count(SELF_PUUID).unwrap(), 2);
drop(cut);
let report = sync(&open(&db, FakeHistory::new(recorded_account(), on_riot)));
assert_eq!((report.added, report.stored), (2, 4));
}
#[test]
fn a_match_that_started_earlier_but_was_published_later_is_still_imported() {
let dir = tempfile::tempdir().unwrap();
let db = dir.path().join("arena.db");
let at = |hours: i64| (1_000_000 + hours * 3600) * 1000;
let first = payload("EUW1_1", 1750, 1, "A", 4, false, at(0));
let newest = payload("EUW1_2", 1750, 2, "B", 4, false, at(30));
let fake = FakeHistory::new(recorded_account(), vec![first, newest]);
let tracker = open(&db, fake);
sync(&tracker);
// A game that began before the newest stored one ends only now.
let late = FakeHistory::new(
recorded_account(),
vec![
payload("EUW1_1", 1750, 1, "A", 4, false, at(0)),
payload("EUW1_2", 1750, 2, "B", 4, false, at(30)),
payload("EUW1_3", 1750, 3, "C", 1, true, at(10)),
],
);
drop(tracker);
let report = sync(&open(&db, late));
assert_eq!((report.added, report.stored), (1, 3));
}
#[test]
fn a_match_that_cannot_be_delivered_or_read_does_not_block_the_others() {
let dir = tempfile::tempdir().unwrap();
let at = |hours: i64| (1_000_000 + hours * 3600) * 1000;
let fake = FakeHistory::new(
recorded_account(),
vec![
payload("EUW1_1", 1750, 1, "A", 4, false, at(1)),
payload("EUW1_2", 1750, 2, "B", 2, true, at(3)),
],
);
fake.add_missing("EUW1_gone", at(4));
fake.add_unreadable("EUW1_garbled", at(2), "<html>pas du JSON</html>");
fake.add_unreadable("EUW1_empty_object", at(0), "{}");
let tracker = open(&dir.path().join("arena.db"), fake);
let mut progress = Vec::new();
let report = tracker.sync(RIOT_ID, &mut |p| progress.push(p)).unwrap();
assert_eq!((report.added, report.stored), (2, 2));
assert_eq!(
progress.last(),
Some(&SyncProgress {
fetched: 5,
to_fetch: 5
})
);
let again = sync(&tracker);
assert_eq!((again.added, again.stored), (0, 2));
}
#[test]
fn other_participants_may_lack_any_field() {
let dir = tempfile::tempdir().unwrap();
let thin = common::without_fields_for_others(
&payload("EUW1_1", 1750, 7, "Zed", 2, true, 1_000_000_000),
&["placement", "win", "championId", "championName", "teamId"],
);
let tracker = open(
&dir.path().join("arena.db"),
FakeHistory::new(recorded_account(), vec![thin]),
);
let report = sync(&tracker);
assert_eq!(report.added, 1);
let stored = tracker.matches(SELF_PUUID).unwrap();
assert_eq!((stored[0].champion_id, stored[0].placement), (7, 2));
}
#[test]
fn an_account_resolved_to_another_puuid_is_a_second_account() {
let dir = tempfile::tempdir().unwrap();
let db = dir.path().join("arena.db");
let at = |hours: i64| (1_000_000 + hours * 3600) * 1000;
let build = |puuid: &str, ids: &[u32]| -> Vec<String> {
ids.iter()
.map(|&i| {
let raw = payload(
&format!("EUW1_{i}"),
1750,
i,
"A",
1,
true,
at(i64::from(i)),
);
played_by(&raw, puuid)
})
.collect()
};
// Under the development key, Joueur#EUW is P1.
let account = |puuid: &str| Account {
puuid: puuid.into(),
..recorded_account()
};
let first = open(&db, FakeHistory::new(account("P1"), build("P1", &[1, 2])));
sync(&first);
let before = first.matches("P1").unwrap();
drop(first);
// Under the personal key it is P2: nothing proves it is the same Account.
let tracker = open(
&db,
FakeHistory::new(account("P2"), build("P2", &[1, 2, 3])),
);
let report = sync(&tracker);
assert_eq!(report.account.puuid, "P2");
assert_eq!((report.added, report.stored), (3, 3));
assert_eq!(tracker.matches("P1").unwrap(), before);
let mut puuids: Vec<String> = tracker
.accounts()
.unwrap()
.into_iter()
.map(|a| a.puuid)
.collect();
puuids.sort();
assert_eq!(puuids, ["P1", "P2"]);
}
const LEGACY_SCHEMA: &str = "
CREATE TABLE accounts (
puuid TEXT PRIMARY KEY, game_name TEXT NOT NULL, tag_line TEXT NOT NULL,
@@ -385,240 +95,11 @@ CREATE TABLE matches (
INSERT INTO accounts VALUES ('fixture-puuid-self', 'Joueur', 'EUW', 1);
INSERT INTO matches VALUES ('fixture-puuid-self', 'EUW1_1', 1750, 1, 'A', 4, 0, 1000000000, '{}');";
#[test]
fn a_database_written_before_the_sync_mark_keeps_working() {
let dir = tempfile::tempdir().unwrap();
let db = dir.path().join("arena.db");
rusqlite::Connection::open(&db)
.unwrap()
.execute_batch(LEGACY_SCHEMA)
.unwrap();
let other = Account {
puuid: "fixture-puuid-other".into(),
game_name: "Autre".into(),
tag_line: "FIX".into(),
};
let theirs = vec![played_by(
&payload("EUW1_9", 1750, 9, "I", 1, true, 1_000_005_000),
&other.puuid,
)];
let tracker = open(
&db,
FakeHistory::new(
recorded_account(),
vec![
payload("EUW1_1", 1750, 1, "A", 4, false, 1_000_000_000),
payload("EUW1_2", 1750, 2, "B", 1, true, 1_000_003_000),
],
)
.with_account(other.clone(), theirs),
);
// No mark yet: everything is listed, what is stored is not fetched again.
let report = sync(&tracker);
assert_eq!((report.added, report.stored), (1, 2));
// A new Account can be added to the old table.
let report = tracker.sync("Autre#FIX", &mut |_| {}).unwrap();
assert_eq!((report.added, report.stored), (1, 1));
assert_eq!(tracker.accounts().unwrap().len(), 2);
}
#[test]
fn queues_map_to_formats_and_non_matches_are_skipped() {
let dir = tempfile::tempdir().unwrap();
let at = |i: i64| (1_000_000 + i) * 1000;
let fake = FakeHistory::new(
recorded_account(),
vec![
payload("EUW1_1", 1750, 1, "A", 1, true, at(1)),
payload("EUW1_2", 1740, 2, "B", 2, true, at(2)),
payload("EUW1_3", 1700, 3, "C", 3, true, at(3)),
payload("EUW1_4", 1710, 4, "D", 4, true, at(4)),
],
)
.listed_under(1700, payload("EUW1_5", 1704, 5, "E", 1, true, at(5)))
.listed_under(1700, payload("EUW1_6", 9999, 6, "F", 5, false, at(6)))
.listed_under(
1700,
with_game_mode(&payload("EUW1_7", 1700, 7, "G", 1, true, at(7)), "ARAM"),
);
let tracker = open(&dir.path().join("arena.db"), fake);
let report = sync(&tracker);
assert_eq!((report.added, report.stored), (5, 5));
let formats: Vec<_> = tracker
.matches(SELF_PUUID)
.unwrap()
.into_iter()
.map(|m| (m.match_id, m.format))
.collect();
assert_eq!(
formats,
[
("EUW1_1".into(), Format::Arena3x6),
("EUW1_2".into(), Format::BraveryArena),
("EUW1_3".into(), Format::Arena16),
("EUW1_4".into(), Format::Arena16),
("EUW1_6".into(), Format::Other(9999)),
]
);
}
#[test]
fn a_rate_limit_is_waited_out_and_the_import_completes() {
let dir = tempfile::tempdir().unwrap();
let tracker = open(
&dir.path().join("arena.db"),
FakeHistory::new(recorded_account(), recorded_matches()).rate_limited_once(),
);
let report = sync(&tracker);
assert_eq!((report.added, report.stored), (6, 6));
}
#[test]
fn progress_goes_from_nothing_fetched_to_everything_fetched() {
let dir = tempfile::tempdir().unwrap();
let tracker = open(
&dir.path().join("arena.db"),
FakeHistory::new(recorded_account(), recorded_matches()),
);
let mut progress = Vec::new();
tracker.sync(RIOT_ID, &mut |p| progress.push(p)).unwrap();
let want: Vec<_> = (0..=6)
.map(|fetched| SyncProgress {
fetched,
to_fetch: 6,
})
.collect();
assert_eq!(progress, want);
progress.clear();
tracker.sync(RIOT_ID, &mut |p| progress.push(p)).unwrap();
assert_eq!(
progress,
[SyncProgress {
fetched: 0,
to_fetch: 0
}]
);
}
#[test]
fn two_accounts_keep_separate_matches() {
let dir = tempfile::tempdir().unwrap();
let db = dir.path().join("arena.db");
sync(&open(
&db,
FakeHistory::new(recorded_account(), five_matches(1_000_000)),
));
let other = Account {
puuid: "fixture-puuid-other".into(),
game_name: "Autre".into(),
tag_line: "FIX".into(),
};
let theirs: Vec<String> = five_matches(5_000_000)[..2]
.iter()
.map(|raw| played_by(raw, &other.puuid))
.collect();
let tracker = open(&db, FakeHistory::new(other.clone(), theirs));
let report = tracker.sync("Autre#FIX", &mut |_| {}).unwrap();
assert_eq!((report.added, report.stored), (2, 2));
assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 5);
assert_eq!(tracker.match_count(&other.puuid).unwrap(), 2);
assert!(
tracker
.matches(&other.puuid)
.unwrap()
.iter()
.all(|m| m.started_at_ms >= 5_000_000_000)
);
assert_eq!(tracker.accounts().unwrap().len(), 2);
}
#[test]
fn matches_without_the_account_are_skipped() {
let dir = tempfile::tempdir().unwrap();
let stranger = Account {
puuid: "fixture-puuid-stranger".into(),
game_name: "Joueur".into(),
tag_line: "EUW".into(),
};
let tracker = open(
&dir.path().join("arena.db"),
FakeHistory::new(stranger, recorded_matches()),
);
let report = sync(&tracker);
assert_eq!((report.added, report.stored), (0, 0));
}
#[test]
fn riot_ids_are_validated_and_must_exist() {
let dir = tempfile::tempdir().unwrap();
let tracker = open(
&dir.path().join("arena.db"),
FakeHistory::new(recorded_account(), recorded_matches()),
);
for bad in ["Joueur", "#EUW", "Joueur#"] {
let err = tracker.sync(bad, &mut |_| {}).unwrap_err();
assert!(matches!(err, Error::InvalidRiotId(_)), "{bad}");
}
let err = tracker.sync("Inconnu#EUW", &mut |_| {}).unwrap_err();
assert!(matches!(err, Error::Source(SourceError::NotFound)));
}
#[test]
fn readers_are_not_blocked_while_a_fetch_is_in_flight() {
let dir = tempfile::tempdir().unwrap();
let (entered_tx, entered_rx) = mpsc::channel();
let (release_tx, release_rx) = mpsc::channel();
let fake = FakeHistory::new(recorded_account(), recorded_matches()[..1].to_vec())
.gated(entered_tx, release_rx);
let tracker = open(&dir.path().join("arena.db"), fake);
thread::scope(|scope| {
let import = scope.spawn(|| sync(&tracker));
entered_rx.recv().unwrap();
// The import is now waiting on the source; the UI thread must still get answers.
assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 0);
assert_eq!(tracker.accounts().unwrap().len(), 1);
release_tx.send(()).unwrap();
assert_eq!(import.join().unwrap().added, 1);
});
}
#[test]
fn concurrent_syncs_run_one_after_the_other_and_fetch_each_match_once() {
let dir = tempfile::tempdir().unwrap();
let (entered_tx, entered_rx) = mpsc::channel();
let (release_tx, release_rx) = mpsc::channel();
let fake = FakeHistory::new(recorded_account(), recorded_matches()[..1].to_vec())
.gated(entered_tx, release_rx);
let fetches = fake.fetch_counter();
let tracker = open(&dir.path().join("arena.db"), fake);
let (overlapped, added) = thread::scope(|scope| {
let first = scope.spawn(|| sync(&tracker));
entered_rx.recv().unwrap();
let second = scope.spawn(|| sync(&tracker));
// Without the lock, the second sync would reach the source while the first waits there.
let overlapped = entered_rx.recv_timeout(Duration::from_millis(300)).is_ok();
release_tx.send(()).unwrap();
release_tx.send(()).unwrap();
let added = (first.join().unwrap().added, second.join().unwrap().added);
(overlapped, added)
});
assert!(!overlapped);
assert_eq!(added, (1, 0));
assert_eq!(fetches.load(Ordering::SeqCst), 1);
}
#[path = "import/accounts.rs"]
mod accounts;
#[path = "import/compatibility.rs"]
mod compatibility;
#[path = "import/concurrency.rs"]
mod concurrency;
#[path = "import/sync.rs"]
mod sync;
+140
View File
@@ -0,0 +1,140 @@
use super::*;
#[test]
fn other_participants_may_lack_any_field() {
let dir = tempfile::tempdir().unwrap();
let thin = common::without_fields_for_others(
&payload("EUW1_1", 1750, 7, "Zed", 2, true, 1_000_000_000),
&["placement", "win", "championId", "championName", "teamId"],
);
let tracker = open(
&dir.path().join("arena.db"),
FakeHistory::new(recorded_account(), vec![thin]),
);
let report = sync(&tracker);
assert_eq!(report.added, 1);
let stored = tracker.matches(SELF_PUUID).unwrap();
assert_eq!((stored[0].champion_id, stored[0].placement), (7, 2));
}
#[test]
fn an_account_resolved_to_another_puuid_is_a_second_account() {
let dir = tempfile::tempdir().unwrap();
let db = dir.path().join("arena.db");
let at = |hours: i64| (1_000_000 + hours * 3600) * 1000;
let build = |puuid: &str, ids: &[u32]| -> Vec<String> {
ids.iter()
.map(|&i| {
let raw = payload(
&format!("EUW1_{i}"),
1750,
i,
"A",
1,
true,
at(i64::from(i)),
);
played_by(&raw, puuid)
})
.collect()
};
// Under the development key, Joueur#EUW is P1.
let account = |puuid: &str| Account {
puuid: puuid.into(),
..recorded_account()
};
let first = open(&db, FakeHistory::new(account("P1"), build("P1", &[1, 2])));
sync(&first);
let before = first.matches("P1").unwrap();
drop(first);
// Under the personal key it is P2: nothing proves it is the same Account.
let tracker = open(
&db,
FakeHistory::new(account("P2"), build("P2", &[1, 2, 3])),
);
let report = sync(&tracker);
assert_eq!(report.account.puuid, "P2");
assert_eq!((report.added, report.stored), (3, 3));
assert_eq!(tracker.matches("P1").unwrap(), before);
let mut puuids: Vec<String> = tracker
.accounts()
.unwrap()
.into_iter()
.map(|a| a.puuid)
.collect();
puuids.sort();
assert_eq!(puuids, ["P1", "P2"]);
}
#[test]
fn two_accounts_keep_separate_matches() {
let dir = tempfile::tempdir().unwrap();
let db = dir.path().join("arena.db");
sync(&open(
&db,
FakeHistory::new(recorded_account(), five_matches(1_000_000)),
));
let other = Account {
puuid: "fixture-puuid-other".into(),
game_name: "Autre".into(),
tag_line: "FIX".into(),
};
let theirs: Vec<String> = five_matches(5_000_000)[..2]
.iter()
.map(|raw| played_by(raw, &other.puuid))
.collect();
let tracker = open(&db, FakeHistory::new(other.clone(), theirs));
let report = tracker.sync("Autre#FIX", &mut |_| {}).unwrap();
assert_eq!((report.added, report.stored), (2, 2));
assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 5);
assert_eq!(tracker.match_count(&other.puuid).unwrap(), 2);
assert!(
tracker
.matches(&other.puuid)
.unwrap()
.iter()
.all(|m| m.started_at_ms >= 5_000_000_000)
);
assert_eq!(tracker.accounts().unwrap().len(), 2);
}
#[test]
fn matches_without_the_account_are_skipped() {
let dir = tempfile::tempdir().unwrap();
let stranger = Account {
puuid: "fixture-puuid-stranger".into(),
game_name: "Joueur".into(),
tag_line: "EUW".into(),
};
let tracker = open(
&dir.path().join("arena.db"),
FakeHistory::new(stranger, recorded_matches()),
);
let report = sync(&tracker);
assert_eq!((report.added, report.stored), (0, 0));
}
#[test]
fn riot_ids_are_validated_and_must_exist() {
let dir = tempfile::tempdir().unwrap();
let tracker = open(
&dir.path().join("arena.db"),
FakeHistory::new(recorded_account(), recorded_matches()),
);
for bad in ["Joueur", "#EUW", "Joueur#"] {
let err = tracker.sync(bad, &mut |_| {}).unwrap_err();
assert!(matches!(err, Error::InvalidRiotId(_)), "{bad}");
}
let err = tracker.sync("Inconnu#EUW", &mut |_| {}).unwrap_err();
assert!(matches!(err, Error::Source(SourceError::NotFound)));
}
+81
View File
@@ -0,0 +1,81 @@
use super::*;
#[test]
fn a_database_written_before_the_sync_mark_keeps_working() {
let dir = tempfile::tempdir().unwrap();
let db = dir.path().join("arena.db");
rusqlite::Connection::open(&db)
.unwrap()
.execute_batch(LEGACY_SCHEMA)
.unwrap();
let other = Account {
puuid: "fixture-puuid-other".into(),
game_name: "Autre".into(),
tag_line: "FIX".into(),
};
let theirs = vec![played_by(
&payload("EUW1_9", 1750, 9, "I", 1, true, 1_000_005_000),
&other.puuid,
)];
let tracker = open(
&db,
FakeHistory::new(
recorded_account(),
vec![
payload("EUW1_1", 1750, 1, "A", 4, false, 1_000_000_000),
payload("EUW1_2", 1750, 2, "B", 1, true, 1_000_003_000),
],
)
.with_account(other.clone(), theirs),
);
// No mark yet: everything is listed, what is stored is not fetched again.
let report = sync(&tracker);
assert_eq!((report.added, report.stored), (1, 2));
// A new Account can be added to the old table.
let report = tracker.sync("Autre#FIX", &mut |_| {}).unwrap();
assert_eq!((report.added, report.stored), (1, 1));
assert_eq!(tracker.accounts().unwrap().len(), 2);
}
#[test]
fn queues_map_to_formats_and_non_matches_are_skipped() {
let dir = tempfile::tempdir().unwrap();
let at = |i: i64| (1_000_000 + i) * 1000;
let fake = FakeHistory::new(
recorded_account(),
vec![
payload("EUW1_1", 1750, 1, "A", 1, true, at(1)),
payload("EUW1_2", 1740, 2, "B", 2, true, at(2)),
payload("EUW1_3", 1700, 3, "C", 3, true, at(3)),
payload("EUW1_4", 1710, 4, "D", 4, true, at(4)),
],
)
.listed_under(1700, payload("EUW1_5", 1704, 5, "E", 1, true, at(5)))
.listed_under(1700, payload("EUW1_6", 9999, 6, "F", 5, false, at(6)))
.listed_under(
1700,
with_game_mode(&payload("EUW1_7", 1700, 7, "G", 1, true, at(7)), "ARAM"),
);
let tracker = open(&dir.path().join("arena.db"), fake);
let report = sync(&tracker);
assert_eq!((report.added, report.stored), (5, 5));
let formats: Vec<_> = tracker
.matches(SELF_PUUID)
.unwrap()
.into_iter()
.map(|m| (m.match_id, m.format))
.collect();
assert_eq!(
formats,
[
("EUW1_1".into(), Format::Arena3x6),
("EUW1_2".into(), Format::BraveryArena),
("EUW1_3".into(), Format::Arena16),
("EUW1_4".into(), Format::Arena16),
("EUW1_6".into(), Format::Other(9999)),
]
);
}
+48
View File
@@ -0,0 +1,48 @@
use super::*;
#[test]
fn readers_are_not_blocked_while_a_fetch_is_in_flight() {
let dir = tempfile::tempdir().unwrap();
let (entered_tx, entered_rx) = mpsc::channel();
let (release_tx, release_rx) = mpsc::channel();
let fake = FakeHistory::new(recorded_account(), recorded_matches()[..1].to_vec())
.gated(entered_tx, release_rx);
let tracker = open(&dir.path().join("arena.db"), fake);
thread::scope(|scope| {
let import = scope.spawn(|| sync(&tracker));
entered_rx.recv().unwrap();
// The import is now waiting on the source; the UI thread must still get answers.
assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 0);
assert_eq!(tracker.accounts().unwrap().len(), 1);
release_tx.send(()).unwrap();
assert_eq!(import.join().unwrap().added, 1);
});
}
#[test]
fn concurrent_syncs_run_one_after_the_other_and_fetch_each_match_once() {
let dir = tempfile::tempdir().unwrap();
let (entered_tx, entered_rx) = mpsc::channel();
let (release_tx, release_rx) = mpsc::channel();
let fake = FakeHistory::new(recorded_account(), recorded_matches()[..1].to_vec())
.gated(entered_tx, release_rx);
let fetches = fake.fetch_counter();
let tracker = open(&dir.path().join("arena.db"), fake);
let (overlapped, added) = thread::scope(|scope| {
let first = scope.spawn(|| sync(&tracker));
entered_rx.recv().unwrap();
let second = scope.spawn(|| sync(&tracker));
// Without the lock, the second sync would reach the source while the first waits there.
let overlapped = entered_rx.recv_timeout(Duration::from_millis(300)).is_ok();
release_tx.send(()).unwrap();
release_tx.send(()).unwrap();
let added = (first.join().unwrap().added, second.join().unwrap().added);
(overlapped, added)
});
assert!(!overlapped);
assert_eq!(added, (1, 0));
assert_eq!(fetches.load(Ordering::SeqCst), 1);
}
+263
View File
@@ -0,0 +1,263 @@
use super::*;
#[test]
fn tracker_can_be_shared_between_threads() {
fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<Tracker>();
}
#[test]
fn imports_the_recorded_matches() {
let dir = tempfile::tempdir().unwrap();
let tracker = open(
&dir.path().join("arena.db"),
FakeHistory::new(recorded_account(), recorded_matches()),
);
let report = sync(&tracker);
assert_eq!(report.account, recorded_account());
assert_eq!((report.added, report.stored), (6, 6));
let mut want: Vec<Match> = recorded_matches().iter().map(|raw| expected(raw)).collect();
want.sort_by_key(|m| m.started_at_ms);
assert_eq!(tracker.matches(SELF_PUUID).unwrap(), want);
assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 6);
assert_eq!(tracker.accounts().unwrap(), [recorded_account()]);
}
#[test]
fn importing_twice_changes_nothing_and_fetches_nothing() {
let dir = tempfile::tempdir().unwrap();
let fake = FakeHistory::new(recorded_account(), recorded_matches());
let fetches = fake.fetch_counter();
let tracker = open(&dir.path().join("arena.db"), fake);
sync(&tracker);
let first = tracker.matches(SELF_PUUID).unwrap();
let report = sync(&tracker);
assert_eq!((report.added, report.stored), (0, 6));
assert_eq!(fetches.load(Ordering::SeqCst), 6);
assert_eq!(tracker.matches(SELF_PUUID).unwrap(), first);
}
#[test]
fn interrupted_import_keeps_what_was_stored_and_resumes_with_the_rest() {
let dir = tempfile::tempdir().unwrap();
let db = dir.path().join("arena.db");
let flaky = open(
&db,
FakeHistory::new(recorded_account(), five_matches(1_000_000)).failing_after(2),
);
let err = flaky.sync(RIOT_ID, &mut |_| {}).unwrap_err();
assert!(matches!(err, Error::Source(SourceError::Network(_))));
assert_eq!(flaky.match_count(SELF_PUUID).unwrap(), 2);
drop(flaky);
let healthy = FakeHistory::new(recorded_account(), five_matches(1_000_000));
let fetches = healthy.fetch_counter();
let tracker = open(&db, healthy);
assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 2);
let report = sync(&tracker);
// The two stored are the newest ones: the missing older ones are still found.
assert_eq!((report.added, report.stored), (3, 5));
assert_eq!(fetches.load(Ordering::SeqCst), 3);
assert_eq!(tracker.matches(SELF_PUUID).unwrap().len(), 5);
}
#[test]
fn later_sync_fetches_only_newer_matches() {
let dir = tempfile::tempdir().unwrap();
let db = dir.path().join("arena.db");
let days_apart = |from_s| five_matches_every(from_s, 10 * 24 * 3600);
sync(&open(
&db,
FakeHistory::new(recorded_account(), days_apart(1_000_000)),
));
let mut now_on_riot = days_apart(1_000_000);
now_on_riot.push(payload(
"EUW1_new1",
1750,
1,
"Annie",
1,
true,
4_500_000_000,
));
now_on_riot.push(payload(
"EUW1_new2",
1740,
2,
"Olaf",
3,
true,
4_501_000_000,
));
let fake = FakeHistory::new(recorded_account(), now_on_riot);
let (fetches, listed) = (fake.fetch_counter(), fake.listed_counter());
let tracker = open(&db, fake);
let report = sync(&tracker);
assert_eq!((report.added, report.stored), (2, 7));
assert_eq!(fetches.load(Ordering::SeqCst), 2);
// Riot is only asked for recent Matches: the newest stored one (listed again) and the new ones.
assert_eq!(listed.load(Ordering::SeqCst), 3);
}
#[test]
fn matches_are_returned_oldest_first_whatever_the_delivery_order() {
let dir = tempfile::tempdir().unwrap();
let mut payloads = five_matches(1_000_000);
payloads.swap(0, 3);
payloads.swap(1, 4);
let delivered: Vec<i64> = payloads.iter().map(|p| started_ms(p)).collect();
assert!(!delivered.is_sorted() && !delivered.iter().rev().is_sorted());
let tracker = open(
&dir.path().join("arena.db"),
FakeHistory::new(recorded_account(), payloads).delivered_as_given(),
);
sync(&tracker);
let started = started_at(&tracker.matches(SELF_PUUID).unwrap());
assert_eq!(started.len(), 5);
assert!(started.is_sorted());
}
#[test]
fn a_catch_up_cut_short_fetches_the_older_matches_next_time() {
let dir = tempfile::tempdir().unwrap();
let db = dir.path().join("arena.db");
let at = |hours: i64| (1_000_000 + hours * 3600) * 1000;
let known = payload("EUW1_1", 1750, 1, "A", 4, false, at(0));
sync(&open(
&db,
FakeHistory::new(recorded_account(), vec![known.clone()]),
));
// Three Matches played while the app was closed.
let mut on_riot = vec![known];
for i in 2..=4 {
let id = format!("EUW1_{i}");
on_riot.push(payload(&id, 1750, i, "B", 4, false, at(i64::from(i))));
}
// The catch-up stores the newest one, then dies.
let cut = open(
&db,
FakeHistory::new(recorded_account(), on_riot.clone()).failing_after(1),
);
assert!(cut.sync(RIOT_ID, &mut |_| {}).is_err());
assert_eq!(cut.match_count(SELF_PUUID).unwrap(), 2);
drop(cut);
let report = sync(&open(&db, FakeHistory::new(recorded_account(), on_riot)));
assert_eq!((report.added, report.stored), (2, 4));
}
#[test]
fn a_match_that_started_earlier_but_was_published_later_is_still_imported() {
let dir = tempfile::tempdir().unwrap();
let db = dir.path().join("arena.db");
let at = |hours: i64| (1_000_000 + hours * 3600) * 1000;
let first = payload("EUW1_1", 1750, 1, "A", 4, false, at(0));
let newest = payload("EUW1_2", 1750, 2, "B", 4, false, at(30));
let fake = FakeHistory::new(recorded_account(), vec![first, newest]);
let tracker = open(&db, fake);
sync(&tracker);
// A game that began before the newest stored one ends only now.
let late = FakeHistory::new(
recorded_account(),
vec![
payload("EUW1_1", 1750, 1, "A", 4, false, at(0)),
payload("EUW1_2", 1750, 2, "B", 4, false, at(30)),
payload("EUW1_3", 1750, 3, "C", 1, true, at(10)),
],
);
drop(tracker);
let report = sync(&open(&db, late));
assert_eq!((report.added, report.stored), (1, 3));
}
#[test]
fn a_match_that_cannot_be_delivered_or_read_does_not_block_the_others() {
let dir = tempfile::tempdir().unwrap();
let at = |hours: i64| (1_000_000 + hours * 3600) * 1000;
let fake = FakeHistory::new(
recorded_account(),
vec![
payload("EUW1_1", 1750, 1, "A", 4, false, at(1)),
payload("EUW1_2", 1750, 2, "B", 2, true, at(3)),
],
);
fake.add_missing("EUW1_gone", at(4));
fake.add_unreadable("EUW1_garbled", at(2), "<html>pas du JSON</html>");
fake.add_unreadable("EUW1_empty_object", at(0), "{}");
let tracker = open(&dir.path().join("arena.db"), fake);
let mut progress = Vec::new();
let report = tracker.sync(RIOT_ID, &mut |p| progress.push(p)).unwrap();
assert_eq!((report.added, report.stored), (2, 2));
assert_eq!(
progress.last(),
Some(&SyncProgress {
fetched: 5,
to_fetch: 5
})
);
let again = sync(&tracker);
assert_eq!((again.added, again.stored), (0, 2));
}
#[test]
fn a_rate_limit_is_waited_out_and_the_import_completes() {
let dir = tempfile::tempdir().unwrap();
let tracker = open(
&dir.path().join("arena.db"),
FakeHistory::new(recorded_account(), recorded_matches()).rate_limited_once(),
);
let report = sync(&tracker);
assert_eq!((report.added, report.stored), (6, 6));
}
#[test]
fn progress_goes_from_nothing_fetched_to_everything_fetched() {
let dir = tempfile::tempdir().unwrap();
let tracker = open(
&dir.path().join("arena.db"),
FakeHistory::new(recorded_account(), recorded_matches()),
);
let mut progress = Vec::new();
tracker.sync(RIOT_ID, &mut |p| progress.push(p)).unwrap();
let want: Vec<_> = (0..=6)
.map(|fetched| SyncProgress {
fetched,
to_fetch: 6,
})
.collect();
assert_eq!(progress, want);
progress.clear();
tracker.sync(RIOT_ID, &mut |p| progress.push(p)).unwrap();
assert_eq!(
progress,
[SyncProgress {
fetched: 0,
to_fetch: 0
}]
);
}
+11 -902
View File
@@ -36,569 +36,6 @@ fn row(stats: &Statistics, champion_id: u32) -> &ChampionRow {
.unwrap()
}
#[test]
fn attempts_run_up_to_the_first_top_1_and_no_further() {
let dir = tempfile::tempdir().unwrap();
let tracker = imported_tracker(dir.path(), &run(11, &[5, 4, 1, 3], jan(2, 0)));
let stats = stats(&tracker, S1, None);
let yi = row(&stats, 11);
assert_eq!(yi.state, Some(ChampionState::Completed));
assert_eq!(yi.attempts, Some(3));
assert_eq!(yi.matches, 4);
let challenge = stats.challenge.unwrap();
assert_eq!((challenge.completed, challenge.first_tries), (1, 0));
assert_eq!(challenge.attempts, 3);
}
#[test]
fn champion_states() {
let dir = tempfile::tempdir().unwrap();
let matches = [run(222, &[1], jan(2, 0)), run(103, &[3, 5], jan(2, 0))].concat();
let tracker = imported_tracker(dir.path(), &matches);
let stats = stats(&tracker, S1, None);
let first_try = row(&stats, 222);
assert_eq!(first_try.state, Some(ChampionState::Completed));
assert_eq!(first_try.attempts, Some(1));
let in_progress = row(&stats, 103);
assert_eq!(in_progress.state, Some(ChampionState::InProgress));
assert_eq!(in_progress.attempts, Some(2));
let never_played = row(&stats, 8);
assert_eq!(never_played.state, Some(ChampionState::NeverPlayed));
assert_eq!(never_played.attempts, Some(0));
assert_eq!(stats.challenge.unwrap().first_tries, 1);
}
#[test]
fn challenge_totals_count_every_attempt_but_average_only_completed_champions() {
let dir = tempfile::tempdir().unwrap();
let matches = [
run(11, &[5, 4, 1, 3], jan(2, 0)), // Completed in 3
run(222, &[1], jan(3, 0)), // First Try
run(103, &[3, 5], jan(4, 0)), // in progress, 2 Attempts so far
]
.concat();
let tracker = imported_tracker(dir.path(), &matches);
let challenge = stats(&tracker, S1, None).challenge.unwrap();
assert_eq!(challenge.completed, 2);
assert_eq!(challenge.total, CATALOG.len());
assert_eq!(challenge.attempts, 3 + 1 + 2);
assert_eq!(challenge.average_attempts, Some(2.0));
assert_eq!(challenge.first_tries, 1);
}
#[test]
fn average_attempts_is_none_when_nothing_is_completed() {
let dir = tempfile::tempdir().unwrap();
let tracker = imported_tracker(dir.path(), &run(103, &[3, 5], jan(2, 0)));
let challenge = stats(&tracker, S1, None).challenge.unwrap();
assert_eq!(challenge.completed, 0);
assert_eq!(challenge.average_attempts, None);
assert_eq!(challenge.attempts, 2);
}
#[test]
fn a_top_1_in_any_format_completes_the_champion() {
let dir = tempfile::tempdir().unwrap();
let matches = [
played_match(11, 5, jan(2, 0)).in_format(1740),
played_match(11, 1, jan(2, 1)).in_format(1700),
]
.to_vec();
let tracker = imported_tracker(dir.path(), &matches);
let stats = stats(&tracker, S1, Some(Format::BraveryArena));
// Only the Bravery Arena Match is in scope, yet the Challenge still sees both.
assert_eq!(row(&stats, 11).matches, 1);
assert_eq!(row(&stats, 11).state, Some(ChampionState::Completed));
assert_eq!(row(&stats, 11).attempts, Some(2));
assert_eq!(stats.challenge.unwrap().completed, 1);
}
#[test]
fn the_format_filter_changes_statistics_and_never_the_challenge() {
let dir = tempfile::tempdir().unwrap();
let matches = vec![
played_match(11, 5, jan(2, 0)),
played_match(11, 1, jan(2, 1)).in_format(1740),
played_match(11, 3, jan(2, 2)),
played_match(11, 6, jan(2, 4)).in_format(1740),
played_match(222, 2, jan(3, 0)).in_format(1740),
];
let tracker = imported_tracker(dir.path(), &matches);
let everything = stats(&tracker, S1, None);
let filtered = stats(&tracker, S1, Some(Format::Arena3x6));
let (all, only) = (row(&everything, 11), row(&filtered, 11));
assert_eq!(
(all.matches, all.top1, all.wins, all.best_placement),
(4, 1, 2, Some(1))
);
assert_eq!(all.average_placement, Some(3.75));
assert_eq!(all.last_match_ms, Some(jan(2, 4)));
assert_eq!(
(only.matches, only.top1, only.wins, only.best_placement),
(2, 0, 1, Some(3))
);
assert_eq!(only.average_placement, Some(4.0));
assert_eq!(only.last_match_ms, Some(jan(2, 2)));
assert_eq!(row(&filtered, 222).matches, 0);
assert_eq!(row(&filtered, 222).last_match_ms, None);
assert_eq!(
everything.charts.placements,
[(1, 1), (2, 1), (3, 1), (4, 0), (5, 1), (6, 1)]
);
assert_eq!(
filtered.charts.placements,
[(1, 0), (2, 0), (3, 1), (4, 0), (5, 1)]
);
// Unchanged: the Challenge, every state and Attempts count, the two Challenge charts.
assert_eq!(everything.challenge, filtered.challenge);
for (a, b) in everything.rows.iter().zip(&filtered.rows) {
assert_eq!(
(a.state, a.attempts),
(b.state, b.attempts),
"{}",
a.champion.name
);
}
assert_eq!(
everything.charts.completed_over_time,
filtered.charts.completed_over_time
);
assert_eq!(
everything.charts.attempts_to_complete,
filtered.charts.attempts_to_complete
);
assert_eq!(everything.formats, [Format::Arena3x6, Format::BraveryArena]);
assert_eq!(filtered.formats, everything.formats);
}
#[test]
fn a_season_starts_at_its_first_millisecond() {
let dir = tempfile::tempdir().unwrap();
let s1_start = date(2026, 1, 1).start_ms();
let s2_start = date(2026, 4, 1).start_ms();
let matches = vec![
played_match(1, 4, s1_start - 1), // before the first Season
played_match(8, 4, s1_start), // first instant of S1
played_match(11, 4, s2_start - 1), // last millisecond of S1
played_match(19, 4, s2_start), // first instant of S2
];
let tracker = imported_tracker(dir.path(), &matches);
let in_season = |name| -> Vec<u32> {
let stats = stats(&tracker, name, None);
let mut ids: Vec<u32> = stats
.rows
.iter()
.filter(|r| r.matches > 0)
.map(|r| r.champion.id)
.collect();
ids.sort();
ids
};
assert_eq!(in_season(S1), [8, 11]);
assert_eq!(in_season(S2), [19]);
let everything = all_seasons(&tracker);
assert_eq!(everything.rows.iter().filter(|r| r.matches > 0).count(), 4);
assert_eq!(row(&everything, 1).matches, 1);
}
#[test]
fn each_season_has_its_own_challenge_and_the_current_one_is_found_by_date() {
let dir = tempfile::tempdir().unwrap();
let matches = [
run(11, &[1], jan(2, 0)),
run(11, &[4], at(date(2026, 4, 2), 0)),
]
.concat();
let tracker = imported_tracker(dir.path(), &matches);
let past = stats(&tracker, S1, None);
let current = stats(&tracker, S2, None);
assert_eq!(past.challenge.unwrap().completed, 1);
let challenge = current.challenge.clone().unwrap();
assert_eq!((challenge.completed, challenge.attempts), (0, 1));
assert_eq!(row(&current, 11).state, Some(ChampionState::InProgress));
let name = |ms| tracker.current_season(ms).map(|s| s.name);
assert_eq!(name(date(2026, 1, 1).start_ms() - 1), None);
assert_eq!(name(date(2026, 1, 1).start_ms()), Some(S1.into()));
assert_eq!(name(date(2026, 4, 1).start_ms() - 1), Some(S1.into()));
assert_eq!(name(date(2026, 4, 1).start_ms()), Some(S2.into()));
assert_eq!(name(date(2100, 1, 1).start_ms()), Some(S2.into()));
assert_eq!(tracker.seasons(), seasons());
}
#[test]
fn the_all_seasons_view_has_no_challenge() {
let dir = tempfile::tempdir().unwrap();
let matches = [
run(11, &[1], jan(2, 0)),
run(11, &[4], at(date(2026, 4, 2), 0)),
run(222, &[3], at(date(2025, 6, 1), 0)),
]
.concat();
let tracker = imported_tracker(dir.path(), &matches);
let stats = all_seasons(&tracker);
assert_eq!(stats.challenge, None);
let yi = row(&stats, 11);
assert_eq!((yi.matches, yi.top1, yi.best_placement), (2, 1, Some(1)));
assert_eq!(yi.average_placement, Some(2.5));
assert_eq!((yi.attempts, yi.state), (None, None));
assert_eq!(
(row(&stats, 222).attempts, row(&stats, 222).state),
(None, None)
);
assert_eq!(row(&stats, 8).state, Some(ChampionState::NeverPlayed));
assert_eq!(row(&stats, 8).attempts, None);
assert!(stats.charts.completed_over_time.is_empty());
assert_eq!(stats.charts.attempts_to_complete, [0; 5]);
assert_eq!(stats.charts.placements, [(1, 1), (2, 0), (3, 1), (4, 1)]);
}
#[test]
fn an_unknown_season_is_an_error() {
let dir = tempfile::tempdir().unwrap();
let tracker = imported_tracker(dir.path(), &[]);
let scope = Scope {
season: SeasonScope::Season("Saison Z".into()),
format: None,
};
let err = tracker.statistics(SELF_PUUID, &scope).unwrap_err();
assert!(matches!(err, Error::UnknownSeason(name) if name == "Saison Z"));
}
#[test]
fn an_edited_season_table_reassigns_stored_matches_without_importing_again() {
let dir = tempfile::tempdir().unwrap();
let matches = [run(11, &[4], jan(1, 1)), run(19, &[4], jan(3, 1))].concat();
drop(imported_tracker(dir.path(), &matches));
let history = FakeHistory::new(recorded_account(), payloads(&matches));
let fetches = history.fetch_counter();
let tracker = Tracker::open(&dir.path().join("arena.db"), Box::new(history))
.unwrap()
.with_seasons(vec![
Season {
name: "Début".into(),
start: date(2026, 1, 1),
official_track: None,
},
Season {
name: "Suite".into(),
start: date(2026, 1, 2),
official_track: None,
},
]);
let report = tracker.sync(RIOT_ID, &mut |_| {}).unwrap();
assert_eq!((report.added, fetches.load(Ordering::SeqCst)), (0, 0));
let played = |name| -> Vec<u32> {
stats(&tracker, name, None)
.rows
.iter()
.filter(|r| r.matches > 0)
.map(|r| r.champion.id)
.collect()
};
assert_eq!(played("Début"), [11]);
assert_eq!(played("Suite"), [19]);
assert!(
tracker
.statistics(
SELF_PUUID,
&Scope {
season: SeasonScope::Season(S1.into()),
format: None
}
)
.is_err()
);
}
#[test]
fn row_values_for_one_champion() {
let dir = tempfile::tempdir().unwrap();
let matches = vec![
played_match(11, 4, jan(2, 1)),
played_match(11, 1, jan(2, 2)).in_format(1740),
played_match(11, 2, jan(2, 3)).in_format(1700),
];
let tracker = imported_tracker(dir.path(), &matches);
let stats = stats(&tracker, S1, None);
let yi = row(&stats, 11);
assert_eq!(
yi.champion,
Champion {
id: 11,
key: "MasterYi".into(),
name: "Maître Yi".into()
}
);
assert_eq!(yi.matches, 3);
assert_eq!(yi.best_placement, Some(1));
assert_eq!(yi.top1, 1);
assert_eq!(yi.wins, 2);
assert_eq!(yi.average_placement, Some(7.0 / 3.0));
assert_eq!(yi.last_match_ms, Some(jan(2, 3)));
let unplayed = row(&stats, 8);
assert_eq!(unplayed.matches, 0);
assert_eq!(
(
unplayed.best_placement,
unplayed.average_placement,
unplayed.last_match_ms
),
(None, None, None)
);
}
#[test]
fn the_chart_series_are_empty_without_matches() {
let dir = tempfile::tempdir().unwrap();
let tracker = imported_tracker(dir.path(), &[]);
let charts = stats(&tracker, S1, None).charts;
assert!(charts.placements.is_empty());
assert!(charts.completed_over_time.is_empty());
assert_eq!(charts.attempts_to_complete, [0; 5]);
}
#[test]
fn the_chart_series_follow_the_completions() {
let dir = tempfile::tempdir().unwrap();
let matches = [
run(1, &[1], jan(2, 1)),
run(8, &[1], jan(2, 5)),
run(11, &[4, 1], jan(5, 0)),
run(19, &[3, 3, 3, 3, 1], jan(6, 0)),
run(103, &[6, 6, 6, 6, 6, 6, 1], jan(6, 8)),
run(222, &[2, 2, 1], jan(10, 0)),
]
.concat();
let tracker = imported_tracker(dir.path(), &matches);
let charts = stats(&tracker, S1, None).charts;
assert_eq!(
charts.completed_over_time,
[
(date(2026, 1, 2), 2),
(date(2026, 1, 5), 3),
(date(2026, 1, 6), 5),
(date(2026, 1, 10), 6),
]
);
// 1 Attempt: Annie and Vladimir; 2: Maître Yi; 3: Jinx; 5 or more: Warwick and Ahri.
assert_eq!(charts.attempts_to_complete, [2, 1, 1, 0, 2]);
}
fn bare_row(name: &str, id: u32) -> ChampionRow {
ChampionRow {
champion: Champion {
id,
key: name.into(),
name: name.into(),
},
portrait: None,
card_portrait: None,
splash: None,
matches: 0,
best_placement: None,
top1: 0,
wins: 0,
average_placement: None,
last_match_ms: None,
attempts: None,
state: None,
challenge: None,
mastery_points: None,
}
}
fn names(rows: &[ChampionRow]) -> Vec<&str> {
rows.iter().map(|r| r.champion.name.as_str()).collect()
}
#[test]
fn rows_sort_by_column_with_missing_values_last_and_ties_by_name() {
let with_attempts = |name, id, attempts| ChampionRow {
attempts,
..bare_row(name, id)
};
let mut rows = vec![
with_attempts("Bard", 3, Some(3)),
with_attempts("Zed", 4, None),
with_attempts("Annie", 1, Some(3)),
with_attempts("Ahri", 2, Some(1)),
with_attempts("Jinx", 5, Some(0)),
];
sort_rows(&mut rows, Column::Attempts, true);
assert_eq!(names(&rows), ["Annie", "Bard", "Ahri", "Jinx", "Zed"]);
sort_rows(&mut rows, Column::Attempts, false);
assert_eq!(names(&rows), ["Jinx", "Ahri", "Annie", "Bard", "Zed"]);
}
#[test]
fn rows_sort_by_name_ignoring_case_and_accents() {
let mut rows: Vec<_> = ["Zoé", "Zed", "Maître Yi", "Nami", "ahri"]
.iter()
.zip(1..)
.map(|(name, id)| bare_row(name, id))
.collect();
sort_rows(&mut rows, Column::Champion, false);
assert_eq!(names(&rows), ["ahri", "Maître Yi", "Nami", "Zed", "Zoé"]);
sort_rows(&mut rows, Column::Champion, true);
assert_eq!(names(&rows), ["Zoé", "Zed", "Nami", "Maître Yi", "ahri"]);
}
#[test]
fn rows_sort_by_numbers_and_dates() {
let rows = vec![
ChampionRow {
average_placement: Some(2.5),
last_match_ms: Some(10),
matches: 1,
..bare_row("A", 1)
},
ChampionRow {
average_placement: Some(1.5),
last_match_ms: Some(30),
matches: 3,
..bare_row("B", 2)
},
bare_row("C", 3),
];
let order = |column, descending| {
let mut sorted = rows.clone();
sort_rows(&mut sorted, column, descending);
sorted
.iter()
.map(|r| r.champion.name.clone())
.collect::<Vec<_>>()
.concat()
};
assert_eq!(order(Column::AveragePlacement, false), "BAC");
assert_eq!(order(Column::AveragePlacement, true), "ABC");
assert_eq!(order(Column::LastMatch, true), "BAC");
assert_eq!(order(Column::Matches, true), "BAC");
assert_eq!(order(Column::Wins, false), "ABC"); // all zero: by name
}
#[test]
fn state_filters_keep_the_expected_rows() {
let with_state = |state| ChampionRow {
state,
..bare_row("A", 1)
};
let completed = with_state(Some(ChampionState::Completed));
let in_progress = with_state(Some(ChampionState::InProgress));
let never = with_state(Some(ChampionState::NeverPlayed));
let unknown = with_state(None);
let kept = |filter: StateFilter| -> Vec<bool> {
[&completed, &in_progress, &never, &unknown]
.iter()
.map(|r| filter.keeps(r))
.collect()
};
assert_eq!(kept(StateFilter::All), [true, true, true, true]);
assert_eq!(kept(StateFilter::Completed), [true, false, false, false]);
assert_eq!(kept(StateFilter::Remaining), [false, true, true, false]);
assert_eq!(kept(StateFilter::NeverPlayed), [false, false, true, false]);
}
#[test]
fn open_tracker_alone_uses_the_shipped_seasons() {
let dir = tempfile::tempdir().unwrap();
let tracker = Tracker::open(
&dir.path().join("arena.db"),
Box::new(FakeHistory::new(recorded_account(), vec![])),
)
.unwrap();
assert_eq!(tracker.seasons(), arena_tracker_core::default_seasons());
}
#[test]
fn rows_sort_by_state_with_unknown_states_last() {
let with_state = |name, id, state| ChampionRow {
state,
..bare_row(name, id)
};
let mut rows = vec![
with_state("Zed", 1, Some(ChampionState::NeverPlayed)),
with_state("Bard", 2, None),
with_state("Nami", 3, Some(ChampionState::InProgress)),
with_state("Jinx", 4, Some(ChampionState::Completed)),
with_state("Ahri", 5, Some(ChampionState::NeverPlayed)),
with_state("Annie", 6, Some(ChampionState::Completed)),
];
sort_rows(&mut rows, Column::State, false);
assert_eq!(
names(&rows),
["Annie", "Jinx", "Nami", "Ahri", "Zed", "Bard"]
);
sort_rows(&mut rows, Column::State, true);
assert_eq!(
names(&rows),
["Ahri", "Zed", "Nami", "Annie", "Jinx", "Bard"]
);
}
#[test]
fn attempts_follow_start_times_not_the_order_matches_were_stored_in() {
let dir = tempfile::tempdir().unwrap();
// Riot hands the newest Match over first: the top 1 is stored before the two failures.
let matches = [
played_match(11, 1, jan(5, 0)),
played_match(11, 4, jan(3, 0)),
played_match(11, 6, jan(2, 0)),
];
let tracker = Tracker::open(
&dir.path().join("arena.db"),
Box::new(FakeHistory::new(recorded_account(), payloads(&matches)).delivered_as_given()),
)
.unwrap()
.with_seasons(seasons());
tracker.sync(RIOT_ID, &mut |_| {}).unwrap();
let stats = stats(&tracker, S1, None);
let yi = row(&stats, 11);
assert_eq!(
(yi.state, yi.attempts),
(Some(ChampionState::Completed), Some(3))
);
assert_eq!(stats.challenge.unwrap().average_attempts, Some(3.0));
}
const NO_MARKS: Marks = Marks {
played: false,
won: false,
@@ -609,346 +46,18 @@ fn challenge(stats: &Statistics, champion_id: u32) -> ChampionChallenge {
row(stats, champion_id).challenge.unwrap()
}
#[test]
fn a_2nd_place_is_a_win_that_leaves_the_champion_remaining() {
let dir = tempfile::tempdir().unwrap();
let tracker = imported_tracker(dir.path(), &[played_match(11, 2, jan(2, 0))]);
let stats = stats(&tracker, S1, None);
let yi = row(&stats, 11);
assert_eq!(yi.state, Some(ChampionState::InProgress));
let challenge = yi.challenge.unwrap();
assert_eq!(
(challenge.matches, challenge.wins, challenge.best_placement),
(1, 1, Some(2))
);
assert_eq!(challenge.completed_on, None);
assert_eq!(
challenge.marks(),
Marks {
played: true,
won: true,
completed: false
}
);
}
#[test]
fn a_single_top_1_earns_the_three_marks() {
let dir = tempfile::tempdir().unwrap();
let tracker = imported_tracker(dir.path(), &[played_match(11, 1, jan(2, 5))]);
let stats = stats(&tracker, S1, None);
let yi = row(&stats, 11);
assert_eq!(yi.state, Some(ChampionState::Completed));
assert_eq!(yi.attempts, Some(1));
let challenge = yi.challenge.unwrap();
assert_eq!(challenge.completed_on, Some(date(2026, 1, 2)));
assert_eq!(
challenge.marks(),
Marks {
played: true,
won: true,
completed: true
}
);
}
#[test]
fn a_played_champion_without_a_win_has_only_the_first_mark() {
let dir = tempfile::tempdir().unwrap();
let tracker = imported_tracker(dir.path(), &run(11, &[5, 4], jan(2, 0)));
let stats = stats(&tracker, S1, None);
let challenge = challenge(&stats, 11);
assert_eq!((challenge.matches, challenge.wins), (2, 0));
assert_eq!(challenge.best_placement, Some(4));
assert_eq!(
challenge.marks(),
Marks {
played: true,
won: false,
completed: false
}
);
}
#[test]
fn a_never_played_champion_has_a_zeroed_challenge_and_no_marks() {
let dir = tempfile::tempdir().unwrap();
let tracker = imported_tracker(dir.path(), &run(11, &[1], jan(2, 0)));
let stats = stats(&tracker, S1, None);
let unplayed = challenge(&stats, 8);
assert_eq!(
unplayed,
ChampionChallenge {
matches: 0,
wins: 0,
best_placement: None,
completed_on: None
}
);
assert_eq!(unplayed.marks(), NO_MARKS);
}
#[test]
fn the_all_seasons_view_has_no_champion_challenge() {
let dir = tempfile::tempdir().unwrap();
let tracker = imported_tracker(dir.path(), &run(11, &[1], jan(2, 0)));
let stats = all_seasons(&tracker);
assert!(stats.rows.iter().all(|r| r.challenge.is_none()));
}
#[test]
fn the_format_filter_changes_the_columns_but_not_the_champion_challenge() {
let dir = tempfile::tempdir().unwrap();
let matches = vec![
played_match(11, 4, jan(2, 1)),
played_match(11, 1, jan(2, 2)).in_format(1740),
played_match(11, 2, jan(2, 3)),
played_match(222, 3, jan(2, 4)).in_format(1740),
];
let tracker = imported_tracker(dir.path(), &matches);
let everything = stats(&tracker, S1, None);
let only_3x6 = stats(&tracker, S1, Some(Format::from_queue(1750).unwrap()));
let challenges =
|stats: &Statistics| -> Vec<_> { stats.rows.iter().map(|r| r.challenge).collect() };
assert_eq!(challenges(&everything), challenges(&only_3x6));
let yi = challenge(&only_3x6, 11);
assert_eq!((yi.matches, yi.wins, yi.best_placement), (3, 2, Some(1)));
assert_eq!(yi.completed_on, Some(date(2026, 1, 2)));
assert_eq!(challenge(&only_3x6, 222).matches, 1);
// The Format-scoped columns do change.
assert_eq!(row(&everything, 11).matches, 3);
assert_eq!(row(&only_3x6, 11).matches, 2);
assert_eq!(row(&only_3x6, 11).best_placement, Some(2));
assert_eq!(row(&only_3x6, 222).matches, 0);
}
#[test]
fn the_champion_challenge_follows_the_season() {
let dir = tempfile::tempdir().unwrap();
let matches = [
run(11, &[1, 2], jan(2, 0)),
run(11, &[6], at(date(2026, 4, 2), 0)),
]
.concat();
let tracker = imported_tracker(dir.path(), &matches);
let past = challenge(&stats(&tracker, S1, None), 11);
let current = challenge(&stats(&tracker, S2, None), 11);
assert_eq!((past.matches, past.wins), (2, 2));
assert_eq!(past.completed_on, Some(date(2026, 1, 2)));
assert_eq!(
current,
ChampionChallenge {
matches: 1,
wins: 0,
best_placement: Some(6),
completed_on: None
}
);
assert!(!current.marks().won);
}
#[test]
fn the_champion_challenge_follows_the_account() {
const OTHER_PUUID: &str = "fixture-puuid-other";
let dir = tempfile::tempdir().unwrap();
let other = Account {
puuid: OTHER_PUUID.into(),
game_name: "Autre".into(),
tag_line: "FIX".into(),
};
let theirs = played_by(
&payload("EUW1_theirs", 1750, 11, "MasterYi", 1, true, jan(3, 0)),
OTHER_PUUID,
);
let history = FakeHistory::new(
recorded_account(),
payloads(&[played_match(11, 4, jan(2, 0))]),
)
.with_account(other, vec![theirs]);
let tracker = Tracker::open(&dir.path().join("arena.db"), Box::new(history))
.unwrap()
.with_seasons(seasons())
.with_champions(
Box::new(FakeChampions::new("1.0", &CATALOG)),
dir.path().join("portraits"),
);
tracker.refresh_champions().unwrap();
tracker.sync(RIOT_ID, &mut |_| {}).unwrap();
tracker.sync("Autre#FIX", &mut |_| {}).unwrap();
let scope = Scope {
season: SeasonScope::Season(S1.into()),
format: None,
};
let mine = tracker.statistics(SELF_PUUID, &scope).unwrap();
let theirs = tracker.statistics(OTHER_PUUID, &scope).unwrap();
let mine = challenge(&mine, 11);
assert_eq!((mine.matches, mine.wins, mine.completed_on), (1, 0, None));
let theirs = challenge(&theirs, 11);
assert_eq!(theirs.matches, 1);
assert_eq!(theirs.completed_on, Some(date(2026, 1, 3)));
}
#[test]
fn two_top_1_imported_out_of_order_keep_the_earlier_day_and_one_completion() {
let dir = tempfile::tempdir().unwrap();
// Riot hands the newest Match over first: the later top 1 is stored before everything else.
let matches = [
played_match(11, 1, jan(9, 0)),
played_match(11, 1, jan(5, 22)),
played_match(11, 3, jan(4, 0)),
];
let tracker = Tracker::open(
&dir.path().join("arena.db"),
Box::new(FakeHistory::new(recorded_account(), payloads(&matches)).delivered_as_given()),
)
.unwrap()
.with_seasons(seasons());
tracker.sync(RIOT_ID, &mut |_| {}).unwrap();
let stats = stats(&tracker, S1, None);
let yi = row(&stats, 11);
assert_eq!(yi.state, Some(ChampionState::Completed));
assert_eq!(yi.attempts, Some(2)); // the Win, then the first top 1
let challenge = yi.challenge.unwrap();
assert_eq!(challenge.completed_on, Some(date(2026, 1, 5)));
assert_eq!((challenge.matches, challenge.wins), (3, 3));
let summary = stats.challenge.unwrap();
assert_eq!((summary.completed, summary.attempts), (1, 2));
assert_eq!(stats.charts.completed_over_time, [(date(2026, 1, 5), 1)]);
}
#[test]
fn the_first_top_1_day_matches_the_progress_curve() {
let dir = tempfile::tempdir().unwrap();
// The first top 1 of Maitre Yi is late in the evening: the day convention must agree.
let matches = [
run(1, &[1], jan(2, 1)),
run(11, &[4, 1, 1], jan(5, 23)),
run(222, &[1], jan(7, 0)),
]
.concat();
let tracker = imported_tracker(dir.path(), &matches);
let stats = stats(&tracker, S1, None);
let mut days: Vec<_> = stats
.rows
.iter()
.filter_map(|r| r.challenge?.completed_on)
.collect();
days.sort();
let curve: Vec<_> = stats
.charts
.completed_over_time
.iter()
.map(|(d, _)| *d)
.collect();
assert_eq!(days, curve);
assert_eq!(challenge(&stats, 11).completed_on, Some(date(2026, 1, 6)));
}
#[test]
fn the_completions_keep_the_order_of_their_first_top_1() {
let dir = tempfile::tempdir().unwrap();
let matches = [
run(222, &[3, 1], jan(2, 0)), // Completed second, on its 2nd Attempt
run(11, &[1, 1], jan(2, 0)), // Completed first: the later top 1 changes nothing
run(103, &[1], jan(4, 0)),
run(1, &[4], jan(5, 0)), // played, never Completed
]
.concat();
let tracker = imported_tracker(dir.path(), &matches);
let challenge = stats(&tracker, S1, None).challenge.unwrap();
assert_eq!(challenge.completion_order, [11, 222, 103]);
}
#[test]
fn the_last_match_says_what_it_did_to_its_champion() {
let last = |matches: &[PlayedMatch], format: Option<Format>| {
let dir = tempfile::tempdir().unwrap();
let tracker = imported_tracker(dir.path(), matches);
stats(&tracker, S1, format).challenge.unwrap().last_match
};
let outcome = |champion_id, placement, outcome| {
Some(LastMatch {
champion_id,
placement,
outcome,
})
};
// Not yet Completed: its 3rd Attempt.
assert_eq!(
last(&run(11, &[5, 4, 4], jan(2, 0)), None),
outcome(11, 4, MatchOutcome::Attempt(3))
);
// The Match that completes it, here on the 3rd Attempt, or on the first.
assert_eq!(
last(&run(11, &[5, 4, 1], jan(2, 0)), None),
outcome(11, 1, MatchOutcome::Completed(3))
);
assert_eq!(
last(&run(222, &[1], jan(2, 0)), None),
outcome(222, 1, MatchOutcome::Completed(1))
);
// Already Completed: not an Attempt.
assert_eq!(
last(&run(11, &[1, 4], jan(2, 0)), None),
outcome(11, 4, MatchOutcome::AfterCompletion)
);
// The latest by start time, whatever the champion, and all Formats whatever the filter.
let matches = [
played_match(103, 2, jan(3, 0)),
played_match(11, 6, jan(4, 0)).in_format(1740),
played_match(222, 3, jan(2, 0)),
];
assert_eq!(
last(&matches, Some(Format::Arena3x6)),
outcome(11, 6, MatchOutcome::Attempt(1))
);
// Only the Season's Matches: one of the next Season is not the last of this one.
assert_eq!(
last(
&[
played_match(103, 2, jan(3, 0)),
played_match(11, 1, april(2))
],
None
),
outcome(103, 2, MatchOutcome::Attempt(1))
);
}
#[test]
fn a_season_without_any_match_has_no_last_match_nor_completion() {
let dir = tempfile::tempdir().unwrap();
let tracker = imported_tracker(dir.path(), &run(11, &[1], jan(2, 0)));
let challenge = stats(&tracker, S2, None).challenge.unwrap();
assert_eq!(challenge.last_match, None);
assert!(challenge.completion_order.is_empty());
}
/// A day of April 2026, in the second Season.
fn april(day: u8) -> i64 {
at(date(2026, 4, day), 0)
}
#[path = "statistics/champion_challenge.rs"]
mod champion_challenge;
#[path = "statistics/completions.rs"]
mod completions;
#[path = "statistics/rows_and_charts.rs"]
mod rows_and_charts;
#[path = "statistics/seasons_and_challenge.rs"]
mod seasons_and_challenge;
#[path = "statistics/sorting_and_filters.rs"]
mod sorting_and_filters;
@@ -0,0 +1,196 @@
use super::*;
#[test]
fn a_2nd_place_is_a_win_that_leaves_the_champion_remaining() {
let dir = tempfile::tempdir().unwrap();
let tracker = imported_tracker(dir.path(), &[played_match(11, 2, jan(2, 0))]);
let stats = stats(&tracker, S1, None);
let yi = row(&stats, 11);
assert_eq!(yi.state, Some(ChampionState::InProgress));
let challenge = yi.challenge.unwrap();
assert_eq!(
(challenge.matches, challenge.wins, challenge.best_placement),
(1, 1, Some(2))
);
assert_eq!(challenge.completed_on, None);
assert_eq!(
challenge.marks(),
Marks {
played: true,
won: true,
completed: false
}
);
}
#[test]
fn a_single_top_1_earns_the_three_marks() {
let dir = tempfile::tempdir().unwrap();
let tracker = imported_tracker(dir.path(), &[played_match(11, 1, jan(2, 5))]);
let stats = stats(&tracker, S1, None);
let yi = row(&stats, 11);
assert_eq!(yi.state, Some(ChampionState::Completed));
assert_eq!(yi.attempts, Some(1));
let challenge = yi.challenge.unwrap();
assert_eq!(challenge.completed_on, Some(date(2026, 1, 2)));
assert_eq!(
challenge.marks(),
Marks {
played: true,
won: true,
completed: true
}
);
}
#[test]
fn a_played_champion_without_a_win_has_only_the_first_mark() {
let dir = tempfile::tempdir().unwrap();
let tracker = imported_tracker(dir.path(), &run(11, &[5, 4], jan(2, 0)));
let stats = stats(&tracker, S1, None);
let challenge = challenge(&stats, 11);
assert_eq!((challenge.matches, challenge.wins), (2, 0));
assert_eq!(challenge.best_placement, Some(4));
assert_eq!(
challenge.marks(),
Marks {
played: true,
won: false,
completed: false
}
);
}
#[test]
fn a_never_played_champion_has_a_zeroed_challenge_and_no_marks() {
let dir = tempfile::tempdir().unwrap();
let tracker = imported_tracker(dir.path(), &run(11, &[1], jan(2, 0)));
let stats = stats(&tracker, S1, None);
let unplayed = challenge(&stats, 8);
assert_eq!(
unplayed,
ChampionChallenge {
matches: 0,
wins: 0,
best_placement: None,
completed_on: None
}
);
assert_eq!(unplayed.marks(), NO_MARKS);
}
#[test]
fn the_all_seasons_view_has_no_champion_challenge() {
let dir = tempfile::tempdir().unwrap();
let tracker = imported_tracker(dir.path(), &run(11, &[1], jan(2, 0)));
let stats = all_seasons(&tracker);
assert!(stats.rows.iter().all(|r| r.challenge.is_none()));
}
#[test]
fn the_format_filter_changes_the_columns_but_not_the_champion_challenge() {
let dir = tempfile::tempdir().unwrap();
let matches = vec![
played_match(11, 4, jan(2, 1)),
played_match(11, 1, jan(2, 2)).in_format(1740),
played_match(11, 2, jan(2, 3)),
played_match(222, 3, jan(2, 4)).in_format(1740),
];
let tracker = imported_tracker(dir.path(), &matches);
let everything = stats(&tracker, S1, None);
let only_3x6 = stats(&tracker, S1, Some(Format::from_queue(1750).unwrap()));
let challenges =
|stats: &Statistics| -> Vec<_> { stats.rows.iter().map(|r| r.challenge).collect() };
assert_eq!(challenges(&everything), challenges(&only_3x6));
let yi = challenge(&only_3x6, 11);
assert_eq!((yi.matches, yi.wins, yi.best_placement), (3, 2, Some(1)));
assert_eq!(yi.completed_on, Some(date(2026, 1, 2)));
assert_eq!(challenge(&only_3x6, 222).matches, 1);
// The Format-scoped columns do change.
assert_eq!(row(&everything, 11).matches, 3);
assert_eq!(row(&only_3x6, 11).matches, 2);
assert_eq!(row(&only_3x6, 11).best_placement, Some(2));
assert_eq!(row(&only_3x6, 222).matches, 0);
}
#[test]
fn the_champion_challenge_follows_the_season() {
let dir = tempfile::tempdir().unwrap();
let matches = [
run(11, &[1, 2], jan(2, 0)),
run(11, &[6], at(date(2026, 4, 2), 0)),
]
.concat();
let tracker = imported_tracker(dir.path(), &matches);
let past = challenge(&stats(&tracker, S1, None), 11);
let current = challenge(&stats(&tracker, S2, None), 11);
assert_eq!((past.matches, past.wins), (2, 2));
assert_eq!(past.completed_on, Some(date(2026, 1, 2)));
assert_eq!(
current,
ChampionChallenge {
matches: 1,
wins: 0,
best_placement: Some(6),
completed_on: None
}
);
assert!(!current.marks().won);
}
#[test]
fn the_champion_challenge_follows_the_account() {
const OTHER_PUUID: &str = "fixture-puuid-other";
let dir = tempfile::tempdir().unwrap();
let other = Account {
puuid: OTHER_PUUID.into(),
game_name: "Autre".into(),
tag_line: "FIX".into(),
};
let theirs = played_by(
&payload("EUW1_theirs", 1750, 11, "MasterYi", 1, true, jan(3, 0)),
OTHER_PUUID,
);
let history = FakeHistory::new(
recorded_account(),
payloads(&[played_match(11, 4, jan(2, 0))]),
)
.with_account(other, vec![theirs]);
let tracker = Tracker::open(&dir.path().join("arena.db"), Box::new(history))
.unwrap()
.with_seasons(seasons())
.with_champions(
Box::new(FakeChampions::new("1.0", &CATALOG)),
dir.path().join("portraits"),
);
tracker.refresh_champions().unwrap();
tracker.sync(RIOT_ID, &mut |_| {}).unwrap();
tracker.sync("Autre#FIX", &mut |_| {}).unwrap();
let scope = Scope {
season: SeasonScope::Season(S1.into()),
format: None,
};
let mine = tracker.statistics(SELF_PUUID, &scope).unwrap();
let theirs = tracker.statistics(OTHER_PUUID, &scope).unwrap();
let mine = challenge(&mine, 11);
assert_eq!((mine.matches, mine.wins, mine.completed_on), (1, 0, None));
let theirs = challenge(&theirs, 11);
assert_eq!(theirs.matches, 1);
assert_eq!(theirs.completed_on, Some(date(2026, 1, 3)));
}
+145
View File
@@ -0,0 +1,145 @@
use super::*;
#[test]
fn two_top_1_imported_out_of_order_keep_the_earlier_day_and_one_completion() {
let dir = tempfile::tempdir().unwrap();
// Riot hands the newest Match over first: the later top 1 is stored before everything else.
let matches = [
played_match(11, 1, jan(9, 0)),
played_match(11, 1, jan(5, 22)),
played_match(11, 3, jan(4, 0)),
];
let tracker = Tracker::open(
&dir.path().join("arena.db"),
Box::new(FakeHistory::new(recorded_account(), payloads(&matches)).delivered_as_given()),
)
.unwrap()
.with_seasons(seasons());
tracker.sync(RIOT_ID, &mut |_| {}).unwrap();
let stats = stats(&tracker, S1, None);
let yi = row(&stats, 11);
assert_eq!(yi.state, Some(ChampionState::Completed));
assert_eq!(yi.attempts, Some(2)); // the Win, then the first top 1
let challenge = yi.challenge.unwrap();
assert_eq!(challenge.completed_on, Some(date(2026, 1, 5)));
assert_eq!((challenge.matches, challenge.wins), (3, 3));
let summary = stats.challenge.unwrap();
assert_eq!((summary.completed, summary.attempts), (1, 2));
assert_eq!(stats.charts.completed_over_time, [(date(2026, 1, 5), 1)]);
}
#[test]
fn the_first_top_1_day_matches_the_progress_curve() {
let dir = tempfile::tempdir().unwrap();
// The first top 1 of Maitre Yi is late in the evening: the day convention must agree.
let matches = [
run(1, &[1], jan(2, 1)),
run(11, &[4, 1, 1], jan(5, 23)),
run(222, &[1], jan(7, 0)),
]
.concat();
let tracker = imported_tracker(dir.path(), &matches);
let stats = stats(&tracker, S1, None);
let mut days: Vec<_> = stats
.rows
.iter()
.filter_map(|r| r.challenge?.completed_on)
.collect();
days.sort();
let curve: Vec<_> = stats
.charts
.completed_over_time
.iter()
.map(|(d, _)| *d)
.collect();
assert_eq!(days, curve);
assert_eq!(challenge(&stats, 11).completed_on, Some(date(2026, 1, 6)));
}
#[test]
fn the_completions_keep_the_order_of_their_first_top_1() {
let dir = tempfile::tempdir().unwrap();
let matches = [
run(222, &[3, 1], jan(2, 0)), // Completed second, on its 2nd Attempt
run(11, &[1, 1], jan(2, 0)), // Completed first: the later top 1 changes nothing
run(103, &[1], jan(4, 0)),
run(1, &[4], jan(5, 0)), // played, never Completed
]
.concat();
let tracker = imported_tracker(dir.path(), &matches);
let challenge = stats(&tracker, S1, None).challenge.unwrap();
assert_eq!(challenge.completion_order, [11, 222, 103]);
}
#[test]
fn the_last_match_says_what_it_did_to_its_champion() {
let last = |matches: &[PlayedMatch], format: Option<Format>| {
let dir = tempfile::tempdir().unwrap();
let tracker = imported_tracker(dir.path(), matches);
stats(&tracker, S1, format).challenge.unwrap().last_match
};
let outcome = |champion_id, placement, outcome| {
Some(LastMatch {
champion_id,
placement,
outcome,
})
};
// Not yet Completed: its 3rd Attempt.
assert_eq!(
last(&run(11, &[5, 4, 4], jan(2, 0)), None),
outcome(11, 4, MatchOutcome::Attempt(3))
);
// The Match that completes it, here on the 3rd Attempt, or on the first.
assert_eq!(
last(&run(11, &[5, 4, 1], jan(2, 0)), None),
outcome(11, 1, MatchOutcome::Completed(3))
);
assert_eq!(
last(&run(222, &[1], jan(2, 0)), None),
outcome(222, 1, MatchOutcome::Completed(1))
);
// Already Completed: not an Attempt.
assert_eq!(
last(&run(11, &[1, 4], jan(2, 0)), None),
outcome(11, 4, MatchOutcome::AfterCompletion)
);
// The latest by start time, whatever the champion, and all Formats whatever the filter.
let matches = [
played_match(103, 2, jan(3, 0)),
played_match(11, 6, jan(4, 0)).in_format(1740),
played_match(222, 3, jan(2, 0)),
];
assert_eq!(
last(&matches, Some(Format::Arena3x6)),
outcome(11, 6, MatchOutcome::Attempt(1))
);
// Only the Season's Matches: one of the next Season is not the last of this one.
assert_eq!(
last(
&[
played_match(103, 2, jan(3, 0)),
played_match(11, 1, april(2))
],
None
),
outcome(103, 2, MatchOutcome::Attempt(1))
);
}
#[test]
fn a_season_without_any_match_has_no_last_match_nor_completion() {
let dir = tempfile::tempdir().unwrap();
let tracker = imported_tracker(dir.path(), &run(11, &[1], jan(2, 0)));
let challenge = stats(&tracker, S2, None).challenge.unwrap();
assert_eq!(challenge.last_match, None);
assert!(challenge.completion_order.is_empty());
}
@@ -0,0 +1,108 @@
use super::*;
#[test]
fn row_values_for_one_champion() {
let dir = tempfile::tempdir().unwrap();
let matches = vec![
played_match(11, 4, jan(2, 1)),
played_match(11, 1, jan(2, 2)).in_format(1740),
played_match(11, 2, jan(2, 3)).in_format(1700),
];
let tracker = imported_tracker(dir.path(), &matches);
let stats = stats(&tracker, S1, None);
let yi = row(&stats, 11);
assert_eq!(
yi.champion,
Champion {
id: 11,
key: "MasterYi".into(),
name: "Maître Yi".into()
}
);
assert_eq!(yi.matches, 3);
assert_eq!(yi.best_placement, Some(1));
assert_eq!(yi.top1, 1);
assert_eq!(yi.wins, 2);
assert_eq!(yi.average_placement, Some(7.0 / 3.0));
assert_eq!(yi.last_match_ms, Some(jan(2, 3)));
let unplayed = row(&stats, 8);
assert_eq!(unplayed.matches, 0);
assert_eq!(
(
unplayed.best_placement,
unplayed.average_placement,
unplayed.last_match_ms
),
(None, None, None)
);
}
#[test]
fn the_chart_series_are_empty_without_matches() {
let dir = tempfile::tempdir().unwrap();
let tracker = imported_tracker(dir.path(), &[]);
let charts = stats(&tracker, S1, None).charts;
assert!(charts.placements.is_empty());
assert!(charts.completed_over_time.is_empty());
assert_eq!(charts.attempts_to_complete, [0; 5]);
}
#[test]
fn the_chart_series_follow_the_completions() {
let dir = tempfile::tempdir().unwrap();
let matches = [
run(1, &[1], jan(2, 1)),
run(8, &[1], jan(2, 5)),
run(11, &[4, 1], jan(5, 0)),
run(19, &[3, 3, 3, 3, 1], jan(6, 0)),
run(103, &[6, 6, 6, 6, 6, 6, 1], jan(6, 8)),
run(222, &[2, 2, 1], jan(10, 0)),
]
.concat();
let tracker = imported_tracker(dir.path(), &matches);
let charts = stats(&tracker, S1, None).charts;
assert_eq!(
charts.completed_over_time,
[
(date(2026, 1, 2), 2),
(date(2026, 1, 5), 3),
(date(2026, 1, 6), 5),
(date(2026, 1, 10), 6),
]
);
// 1 Attempt: Annie and Vladimir; 2: Maître Yi; 3: Jinx; 5 or more: Warwick and Ahri.
assert_eq!(charts.attempts_to_complete, [2, 1, 1, 0, 2]);
}
#[test]
fn attempts_follow_start_times_not_the_order_matches_were_stored_in() {
let dir = tempfile::tempdir().unwrap();
// Riot hands the newest Match over first: the top 1 is stored before the two failures.
let matches = [
played_match(11, 1, jan(5, 0)),
played_match(11, 4, jan(3, 0)),
played_match(11, 6, jan(2, 0)),
];
let tracker = Tracker::open(
&dir.path().join("arena.db"),
Box::new(FakeHistory::new(recorded_account(), payloads(&matches)).delivered_as_given()),
)
.unwrap()
.with_seasons(seasons());
tracker.sync(RIOT_ID, &mut |_| {}).unwrap();
let stats = stats(&tracker, S1, None);
let yi = row(&stats, 11);
assert_eq!(
(yi.state, yi.attempts),
(Some(ChampionState::Completed), Some(3))
);
assert_eq!(stats.challenge.unwrap().average_attempts, Some(3.0));
}
@@ -0,0 +1,300 @@
use super::*;
#[test]
fn attempts_run_up_to_the_first_top_1_and_no_further() {
let dir = tempfile::tempdir().unwrap();
let tracker = imported_tracker(dir.path(), &run(11, &[5, 4, 1, 3], jan(2, 0)));
let stats = stats(&tracker, S1, None);
let yi = row(&stats, 11);
assert_eq!(yi.state, Some(ChampionState::Completed));
assert_eq!(yi.attempts, Some(3));
assert_eq!(yi.matches, 4);
let challenge = stats.challenge.unwrap();
assert_eq!((challenge.completed, challenge.first_tries), (1, 0));
assert_eq!(challenge.attempts, 3);
}
#[test]
fn champion_states() {
let dir = tempfile::tempdir().unwrap();
let matches = [run(222, &[1], jan(2, 0)), run(103, &[3, 5], jan(2, 0))].concat();
let tracker = imported_tracker(dir.path(), &matches);
let stats = stats(&tracker, S1, None);
let first_try = row(&stats, 222);
assert_eq!(first_try.state, Some(ChampionState::Completed));
assert_eq!(first_try.attempts, Some(1));
let in_progress = row(&stats, 103);
assert_eq!(in_progress.state, Some(ChampionState::InProgress));
assert_eq!(in_progress.attempts, Some(2));
let never_played = row(&stats, 8);
assert_eq!(never_played.state, Some(ChampionState::NeverPlayed));
assert_eq!(never_played.attempts, Some(0));
assert_eq!(stats.challenge.unwrap().first_tries, 1);
}
#[test]
fn challenge_totals_count_every_attempt_but_average_only_completed_champions() {
let dir = tempfile::tempdir().unwrap();
let matches = [
run(11, &[5, 4, 1, 3], jan(2, 0)), // Completed in 3
run(222, &[1], jan(3, 0)), // First Try
run(103, &[3, 5], jan(4, 0)), // in progress, 2 Attempts so far
]
.concat();
let tracker = imported_tracker(dir.path(), &matches);
let challenge = stats(&tracker, S1, None).challenge.unwrap();
assert_eq!(challenge.completed, 2);
assert_eq!(challenge.total, CATALOG.len());
assert_eq!(challenge.attempts, 3 + 1 + 2);
assert_eq!(challenge.average_attempts, Some(2.0));
assert_eq!(challenge.first_tries, 1);
}
#[test]
fn average_attempts_is_none_when_nothing_is_completed() {
let dir = tempfile::tempdir().unwrap();
let tracker = imported_tracker(dir.path(), &run(103, &[3, 5], jan(2, 0)));
let challenge = stats(&tracker, S1, None).challenge.unwrap();
assert_eq!(challenge.completed, 0);
assert_eq!(challenge.average_attempts, None);
assert_eq!(challenge.attempts, 2);
}
#[test]
fn a_top_1_in_any_format_completes_the_champion() {
let dir = tempfile::tempdir().unwrap();
let matches = [
played_match(11, 5, jan(2, 0)).in_format(1740),
played_match(11, 1, jan(2, 1)).in_format(1700),
]
.to_vec();
let tracker = imported_tracker(dir.path(), &matches);
let stats = stats(&tracker, S1, Some(Format::BraveryArena));
// Only the Bravery Arena Match is in scope, yet the Challenge still sees both.
assert_eq!(row(&stats, 11).matches, 1);
assert_eq!(row(&stats, 11).state, Some(ChampionState::Completed));
assert_eq!(row(&stats, 11).attempts, Some(2));
assert_eq!(stats.challenge.unwrap().completed, 1);
}
#[test]
fn the_format_filter_changes_statistics_and_never_the_challenge() {
let dir = tempfile::tempdir().unwrap();
let matches = vec![
played_match(11, 5, jan(2, 0)),
played_match(11, 1, jan(2, 1)).in_format(1740),
played_match(11, 3, jan(2, 2)),
played_match(11, 6, jan(2, 4)).in_format(1740),
played_match(222, 2, jan(3, 0)).in_format(1740),
];
let tracker = imported_tracker(dir.path(), &matches);
let everything = stats(&tracker, S1, None);
let filtered = stats(&tracker, S1, Some(Format::Arena3x6));
let (all, only) = (row(&everything, 11), row(&filtered, 11));
assert_eq!(
(all.matches, all.top1, all.wins, all.best_placement),
(4, 1, 2, Some(1))
);
assert_eq!(all.average_placement, Some(3.75));
assert_eq!(all.last_match_ms, Some(jan(2, 4)));
assert_eq!(
(only.matches, only.top1, only.wins, only.best_placement),
(2, 0, 1, Some(3))
);
assert_eq!(only.average_placement, Some(4.0));
assert_eq!(only.last_match_ms, Some(jan(2, 2)));
assert_eq!(row(&filtered, 222).matches, 0);
assert_eq!(row(&filtered, 222).last_match_ms, None);
assert_eq!(
everything.charts.placements,
[(1, 1), (2, 1), (3, 1), (4, 0), (5, 1), (6, 1)]
);
assert_eq!(
filtered.charts.placements,
[(1, 0), (2, 0), (3, 1), (4, 0), (5, 1)]
);
// Unchanged: the Challenge, every state and Attempts count, the two Challenge charts.
assert_eq!(everything.challenge, filtered.challenge);
for (a, b) in everything.rows.iter().zip(&filtered.rows) {
assert_eq!(
(a.state, a.attempts),
(b.state, b.attempts),
"{}",
a.champion.name
);
}
assert_eq!(
everything.charts.completed_over_time,
filtered.charts.completed_over_time
);
assert_eq!(
everything.charts.attempts_to_complete,
filtered.charts.attempts_to_complete
);
assert_eq!(everything.formats, [Format::Arena3x6, Format::BraveryArena]);
assert_eq!(filtered.formats, everything.formats);
}
#[test]
fn a_season_starts_at_its_first_millisecond() {
let dir = tempfile::tempdir().unwrap();
let s1_start = date(2026, 1, 1).start_ms();
let s2_start = date(2026, 4, 1).start_ms();
let matches = vec![
played_match(1, 4, s1_start - 1), // before the first Season
played_match(8, 4, s1_start), // first instant of S1
played_match(11, 4, s2_start - 1), // last millisecond of S1
played_match(19, 4, s2_start), // first instant of S2
];
let tracker = imported_tracker(dir.path(), &matches);
let in_season = |name| -> Vec<u32> {
let stats = stats(&tracker, name, None);
let mut ids: Vec<u32> = stats
.rows
.iter()
.filter(|r| r.matches > 0)
.map(|r| r.champion.id)
.collect();
ids.sort();
ids
};
assert_eq!(in_season(S1), [8, 11]);
assert_eq!(in_season(S2), [19]);
let everything = all_seasons(&tracker);
assert_eq!(everything.rows.iter().filter(|r| r.matches > 0).count(), 4);
assert_eq!(row(&everything, 1).matches, 1);
}
#[test]
fn each_season_has_its_own_challenge_and_the_current_one_is_found_by_date() {
let dir = tempfile::tempdir().unwrap();
let matches = [
run(11, &[1], jan(2, 0)),
run(11, &[4], at(date(2026, 4, 2), 0)),
]
.concat();
let tracker = imported_tracker(dir.path(), &matches);
let past = stats(&tracker, S1, None);
let current = stats(&tracker, S2, None);
assert_eq!(past.challenge.unwrap().completed, 1);
let challenge = current.challenge.clone().unwrap();
assert_eq!((challenge.completed, challenge.attempts), (0, 1));
assert_eq!(row(&current, 11).state, Some(ChampionState::InProgress));
let name = |ms| tracker.current_season(ms).map(|s| s.name);
assert_eq!(name(date(2026, 1, 1).start_ms() - 1), None);
assert_eq!(name(date(2026, 1, 1).start_ms()), Some(S1.into()));
assert_eq!(name(date(2026, 4, 1).start_ms() - 1), Some(S1.into()));
assert_eq!(name(date(2026, 4, 1).start_ms()), Some(S2.into()));
assert_eq!(name(date(2100, 1, 1).start_ms()), Some(S2.into()));
assert_eq!(tracker.seasons(), seasons());
}
#[test]
fn the_all_seasons_view_has_no_challenge() {
let dir = tempfile::tempdir().unwrap();
let matches = [
run(11, &[1], jan(2, 0)),
run(11, &[4], at(date(2026, 4, 2), 0)),
run(222, &[3], at(date(2025, 6, 1), 0)),
]
.concat();
let tracker = imported_tracker(dir.path(), &matches);
let stats = all_seasons(&tracker);
assert_eq!(stats.challenge, None);
let yi = row(&stats, 11);
assert_eq!((yi.matches, yi.top1, yi.best_placement), (2, 1, Some(1)));
assert_eq!(yi.average_placement, Some(2.5));
assert_eq!((yi.attempts, yi.state), (None, None));
assert_eq!(
(row(&stats, 222).attempts, row(&stats, 222).state),
(None, None)
);
assert_eq!(row(&stats, 8).state, Some(ChampionState::NeverPlayed));
assert_eq!(row(&stats, 8).attempts, None);
assert!(stats.charts.completed_over_time.is_empty());
assert_eq!(stats.charts.attempts_to_complete, [0; 5]);
assert_eq!(stats.charts.placements, [(1, 1), (2, 0), (3, 1), (4, 1)]);
}
#[test]
fn an_unknown_season_is_an_error() {
let dir = tempfile::tempdir().unwrap();
let tracker = imported_tracker(dir.path(), &[]);
let scope = Scope {
season: SeasonScope::Season("Saison Z".into()),
format: None,
};
let err = tracker.statistics(SELF_PUUID, &scope).unwrap_err();
assert!(matches!(err, Error::UnknownSeason(name) if name == "Saison Z"));
}
#[test]
fn an_edited_season_table_reassigns_stored_matches_without_importing_again() {
let dir = tempfile::tempdir().unwrap();
let matches = [run(11, &[4], jan(1, 1)), run(19, &[4], jan(3, 1))].concat();
drop(imported_tracker(dir.path(), &matches));
let history = FakeHistory::new(recorded_account(), payloads(&matches));
let fetches = history.fetch_counter();
let tracker = Tracker::open(&dir.path().join("arena.db"), Box::new(history))
.unwrap()
.with_seasons(vec![
Season {
name: "Début".into(),
start: date(2026, 1, 1),
official_track: None,
},
Season {
name: "Suite".into(),
start: date(2026, 1, 2),
official_track: None,
},
]);
let report = tracker.sync(RIOT_ID, &mut |_| {}).unwrap();
assert_eq!((report.added, fetches.load(Ordering::SeqCst)), (0, 0));
let played = |name| -> Vec<u32> {
stats(&tracker, name, None)
.rows
.iter()
.filter(|r| r.matches > 0)
.map(|r| r.champion.id)
.collect()
};
assert_eq!(played("Début"), [11]);
assert_eq!(played("Suite"), [19]);
assert!(
tracker
.statistics(
SELF_PUUID,
&Scope {
season: SeasonScope::Season(S1.into()),
format: None
}
)
.is_err()
);
}
@@ -0,0 +1,158 @@
use super::*;
fn bare_row(name: &str, id: u32) -> ChampionRow {
ChampionRow {
champion: Champion {
id,
key: name.into(),
name: name.into(),
},
portrait: None,
card_portrait: None,
splash: None,
matches: 0,
best_placement: None,
top1: 0,
wins: 0,
average_placement: None,
last_match_ms: None,
attempts: None,
state: None,
challenge: None,
mastery_points: None,
}
}
fn names(rows: &[ChampionRow]) -> Vec<&str> {
rows.iter().map(|r| r.champion.name.as_str()).collect()
}
#[test]
fn rows_sort_by_column_with_missing_values_last_and_ties_by_name() {
let with_attempts = |name, id, attempts| ChampionRow {
attempts,
..bare_row(name, id)
};
let mut rows = vec![
with_attempts("Bard", 3, Some(3)),
with_attempts("Zed", 4, None),
with_attempts("Annie", 1, Some(3)),
with_attempts("Ahri", 2, Some(1)),
with_attempts("Jinx", 5, Some(0)),
];
sort_rows(&mut rows, Column::Attempts, true);
assert_eq!(names(&rows), ["Annie", "Bard", "Ahri", "Jinx", "Zed"]);
sort_rows(&mut rows, Column::Attempts, false);
assert_eq!(names(&rows), ["Jinx", "Ahri", "Annie", "Bard", "Zed"]);
}
#[test]
fn rows_sort_by_name_ignoring_case_and_accents() {
let mut rows: Vec<_> = ["Zoé", "Zed", "Maître Yi", "Nami", "ahri"]
.iter()
.zip(1..)
.map(|(name, id)| bare_row(name, id))
.collect();
sort_rows(&mut rows, Column::Champion, false);
assert_eq!(names(&rows), ["ahri", "Maître Yi", "Nami", "Zed", "Zoé"]);
sort_rows(&mut rows, Column::Champion, true);
assert_eq!(names(&rows), ["Zoé", "Zed", "Nami", "Maître Yi", "ahri"]);
}
#[test]
fn rows_sort_by_numbers_and_dates() {
let rows = vec![
ChampionRow {
average_placement: Some(2.5),
last_match_ms: Some(10),
matches: 1,
..bare_row("A", 1)
},
ChampionRow {
average_placement: Some(1.5),
last_match_ms: Some(30),
matches: 3,
..bare_row("B", 2)
},
bare_row("C", 3),
];
let order = |column, descending| {
let mut sorted = rows.clone();
sort_rows(&mut sorted, column, descending);
sorted
.iter()
.map(|r| r.champion.name.clone())
.collect::<Vec<_>>()
.concat()
};
assert_eq!(order(Column::AveragePlacement, false), "BAC");
assert_eq!(order(Column::AveragePlacement, true), "ABC");
assert_eq!(order(Column::LastMatch, true), "BAC");
assert_eq!(order(Column::Matches, true), "BAC");
assert_eq!(order(Column::Wins, false), "ABC"); // all zero: by name
}
#[test]
fn state_filters_keep_the_expected_rows() {
let with_state = |state| ChampionRow {
state,
..bare_row("A", 1)
};
let completed = with_state(Some(ChampionState::Completed));
let in_progress = with_state(Some(ChampionState::InProgress));
let never = with_state(Some(ChampionState::NeverPlayed));
let unknown = with_state(None);
let kept = |filter: StateFilter| -> Vec<bool> {
[&completed, &in_progress, &never, &unknown]
.iter()
.map(|r| filter.keeps(r))
.collect()
};
assert_eq!(kept(StateFilter::All), [true, true, true, true]);
assert_eq!(kept(StateFilter::Completed), [true, false, false, false]);
assert_eq!(kept(StateFilter::Remaining), [false, true, true, false]);
assert_eq!(kept(StateFilter::NeverPlayed), [false, false, true, false]);
}
#[test]
fn open_tracker_alone_uses_the_shipped_seasons() {
let dir = tempfile::tempdir().unwrap();
let tracker = Tracker::open(
&dir.path().join("arena.db"),
Box::new(FakeHistory::new(recorded_account(), vec![])),
)
.unwrap();
assert_eq!(tracker.seasons(), arena_tracker_core::default_seasons());
}
#[test]
fn rows_sort_by_state_with_unknown_states_last() {
let with_state = |name, id, state| ChampionRow {
state,
..bare_row(name, id)
};
let mut rows = vec![
with_state("Zed", 1, Some(ChampionState::NeverPlayed)),
with_state("Bard", 2, None),
with_state("Nami", 3, Some(ChampionState::InProgress)),
with_state("Jinx", 4, Some(ChampionState::Completed)),
with_state("Ahri", 5, Some(ChampionState::NeverPlayed)),
with_state("Annie", 6, Some(ChampionState::Completed)),
];
sort_rows(&mut rows, Column::State, false);
assert_eq!(
names(&rows),
["Annie", "Jinx", "Nami", "Ahri", "Zed", "Bard"]
);
sort_rows(&mut rows, Column::State, true);
assert_eq!(
names(&rows),
["Ahri", "Zed", "Nami", "Annie", "Jinx", "Bard"]
);
}
+6 -386
View File
@@ -29,65 +29,6 @@ fn release(manifest: &[u8], signature: Option<&[u8]>, package: &[u8]) -> TempDir
dir
}
#[test]
fn only_the_signed_full_package_for_the_expected_release_is_accepted() {
let key = Ed25519KeyPair::from_seed_unchecked(&[7; 32]).unwrap();
let manifest = json!({
"app": "ArenaTracker", "target": "win-x64", "channel": "stable", "version": "1.0.0",
"commit": "c".repeat(40), "package": PACKAGE,
"sha256": "ungWv48Bz+pBQUDeXa4iI7ADYaOWF3qctBD/YfIAFa0="
});
let check = |dir: &TempDir, channel: &str, version: &str| {
verify_release(dir.path(), key.public_key().as_ref(), channel, version)
};
let refused =
|dir: TempDir| matches!(check(&dir, "stable", "1.0.0"), Err(Error::InvalidUpdate(_)));
let doc = serde_json::to_vec(&manifest).unwrap();
let sig = key.sign(&doc);
let good = release(&doc, Some(sig.as_ref()), b"abc");
assert_eq!(check(&good, "stable", "1.0.0").unwrap(), "c".repeat(40));
assert!(check(&good, "beta", "1.0.0").is_err());
assert!(check(&good, "stable", "1.1.0").is_err());
assert!(refused(release(&doc, Some(sig.as_ref()), b"abd")));
assert!(refused(release(&doc, None, b"abc")));
assert!(refused(release(&doc, Some(&[]), b"abc")));
assert!(refused(release(&doc, Some(&[0; 64]), b"abc")));
let missing_package = release(&doc, Some(sig.as_ref()), b"abc");
fs::remove_file(missing_package.path().join(PACKAGE)).unwrap();
assert!(refused(missing_package));
let mut padded = doc.clone();
padded.resize(4097, b' ');
assert!(refused(release(
&padded,
Some(key.sign(&padded).as_ref()),
b"abc"
)));
for (field, wrong) in [
("app", "Other"),
("target", "win-arm64"),
("channel", "beta"),
("version", "1.1.0"),
("package", "different.nupkg"),
("sha256", ""),
] {
let mut other: Value = manifest.clone();
other[field] = wrong.into();
let other = serde_json::to_vec(&other).unwrap();
assert!(
refused(release(&other, Some(sig.as_ref()), b"abc")),
"{field}"
);
assert!(
refused(release(&other, Some(key.sign(&other).as_ref()), b"abc")),
"{field}"
);
}
}
/// The files of one Release: (name, bytes). Betas are published as pre-releases.
struct Published {
prerelease: bool,
@@ -195,182 +136,6 @@ fn kept(dir: &Path) -> Vec<String> {
names
}
#[test]
fn each_channel_gets_its_newest_release_above_the_installed_version() {
let key = key();
let (url, _) = serve(
vec![
publish(&key, "stable", "1.0.0"),
publish(&key, "beta", "1.2.0-beta.10"),
publish(&key, "stable", "1.1.0"),
publish(&key, "beta", "1.2.0-beta.2"),
publish(&key, "stable", "1.0.1"),
publish(&key, "stable", "2.0"),
],
false,
);
let dir = tempfile::tempdir().unwrap();
let public = key.public_key().as_ref();
let check =
|channel, installed| download_update(&url, dir.path(), public, channel, installed).unwrap();
assert_eq!(
check(UpdateChannel::Stable, "1.0.0").as_deref(),
Some("1.1.0")
);
assert_eq!(kept(dir.path()), ["stable-1.1.0"]);
let ready = dir.path().join("stable-1.1.0");
assert!(verify_release(&ready, public, "stable", "1.1.0").is_ok());
// The same version or an older one is ignored, and nothing stays pending.
assert_eq!(check(UpdateChannel::Stable, "1.1.0"), None);
assert_eq!(check(UpdateChannel::Stable, "1.2.0"), None);
assert!(kept(dir.path()).is_empty());
// beta.10 comes after beta.2, and the beta channel never takes a stable.
assert_eq!(
check(UpdateChannel::Beta, "1.1.0-beta.1").as_deref(),
Some("1.2.0-beta.10")
);
assert_eq!(
check(UpdateChannel::Beta, "1.0.0").as_deref(),
Some("1.2.0-beta.10")
);
assert_eq!(kept(dir.path()), ["beta-1.2.0-beta.10"]);
assert_eq!(check(UpdateChannel::Beta, "1.2.0-beta.10"), None);
assert!(kept(dir.path()).is_empty());
}
#[test]
fn back_to_stable_from_a_newer_beta_waits_for_a_newer_stable() {
let key = key();
let dir = tempfile::tempdir().unwrap();
let public = key.public_key().as_ref();
let check = |url: &str| {
download_update(
url,
dir.path(),
public,
UpdateChannel::Stable,
"1.2.0-beta.3",
)
.unwrap()
};
let older = vec![
publish(&key, "stable", "1.1.0"),
publish(&key, "beta", "1.2.0-beta.4"),
];
assert_eq!(check(&serve(older, false).0), None);
let newer = vec![
publish(&key, "stable", "1.1.0"),
publish(&key, "stable", "1.2.0"),
];
assert_eq!(check(&serve(newer, false).0).as_deref(), Some("1.2.0"));
}
#[test]
fn a_kept_package_is_verified_again_and_downloaded_again_once_altered() {
let key = key();
let (url, downloads) = serve(vec![publish(&key, "stable", "1.1.0")], false);
let dir = tempfile::tempdir().unwrap();
let public = key.public_key().as_ref();
let check = || download_update(&url, dir.path(), public, UpdateChannel::Stable, "1.0.0");
assert_eq!(check().unwrap().as_deref(), Some("1.1.0"));
assert_eq!(check().unwrap().as_deref(), Some("1.1.0"));
assert_eq!(downloads.load(Ordering::SeqCst), 1);
let package = dir
.path()
.join("stable-1.1.0/ArenaTracker-1.1.0-stable-full.nupkg");
fs::write(&package, b"altered").unwrap();
assert_eq!(check().unwrap().as_deref(), Some("1.1.0"));
assert_eq!(downloads.load(Ordering::SeqCst), 2);
assert_eq!(fs::read(&package).unwrap(), b"package 1.1.0");
}
#[test]
fn a_channel_change_discards_the_other_channels_package_even_offline() {
let key = key();
let (url, _) = serve(
vec![
publish(&key, "stable", "1.1.0"),
publish(&key, "beta", "1.2.0-beta.1"),
],
false,
);
let dir = tempfile::tempdir().unwrap();
let public = key.public_key().as_ref();
let check = |url: &str, channel| download_update(url, dir.path(), public, channel, "1.0.0");
assert!(check(&url, UpdateChannel::Stable).unwrap().is_some());
// A late stable package goes as soon as a beta check starts, before any network access.
let offline = unreachable();
assert!(matches!(
check(&offline, UpdateChannel::Beta),
Err(Error::Source(_))
));
assert!(kept(dir.path()).is_empty());
assert_eq!(
check(&url, UpdateChannel::Beta).unwrap().as_deref(),
Some("1.2.0-beta.1")
);
// Offline, the channel's own pending package stays for a later launch.
assert!(check(&offline, UpdateChannel::Beta).is_err());
assert_eq!(kept(dir.path()), ["beta-1.2.0-beta.1"]);
}
#[test]
fn a_failed_newer_download_keeps_the_older_pending_package() {
let key = key();
let dir = tempfile::tempdir().unwrap();
let public = key.public_key().as_ref();
let check = |url: &str| download_update(url, dir.path(), public, UpdateChannel::Beta, "1.0.0");
let first = vec![publish(&key, "beta", "1.1.0-beta.1")];
assert!(check(&serve(first, false).0).is_ok());
let newer = || {
vec![
publish(&key, "beta", "1.1.0-beta.1"),
publish(&key, "beta", "1.1.0-beta.2"),
]
};
assert!(check(&serve(newer(), true).0).is_err());
assert_eq!(kept(dir.path()), ["beta-1.1.0-beta.1"]);
let ready = check(&serve(newer(), false).0).unwrap();
assert_eq!(ready.as_deref(), Some("1.1.0-beta.2"));
assert_eq!(kept(dir.path()), ["beta-1.1.0-beta.2"]);
}
#[test]
fn network_and_signature_failures_leave_no_update_ready() {
let key = key();
let other = Ed25519KeyPair::from_seed_unchecked(&[8; 32]).unwrap();
let dir = tempfile::tempdir().unwrap();
let public = key.public_key().as_ref();
let check =
|url: &str| download_update(url, dir.path(), public, UpdateChannel::Stable, "1.0.0");
assert!(matches!(check(&unreachable()), Err(Error::Source(_))));
let (cut, _) = serve(vec![publish(&key, "stable", "1.1.0")], true);
assert!(check(&cut).is_err());
assert!(kept(dir.path()).is_empty());
let (forged, _) = serve(vec![publish(&other, "stable", "1.1.0")], false);
assert!(matches!(check(&forged), Err(Error::InvalidUpdate(_))));
assert!(kept(dir.path()).is_empty());
let mut altered = publish(&key, "stable", "1.1.0");
altered.files[2].1 = b"package 6.6.6".to_vec();
assert!(matches!(
check(&serve(vec![altered], false).0),
Err(Error::InvalidUpdate(_))
));
assert!(kept(dir.path()).is_empty());
// A release without its signature is not offered at all.
let mut unsigned = publish(&key, "stable", "1.1.0");
unsigned.files.remove(0);
assert_eq!(check(&serve(vec![unsigned], false).0).unwrap(), None);
}
/// Keeps `version` of `channel` in `dir` as a finished download would, and returns its package.
fn keep(dir: &Path, key: &Ed25519KeyPair, channel: &str, version: &str) -> PathBuf {
let folder = dir.join(format!("{channel}-{version}"));
@@ -415,154 +180,9 @@ fn reports_failed(launch: &Launch, version: &str) -> bool {
matches!(launch, ControlFlow::Continue(Some(Error::UpdateFailed(failed))) if failed == version)
}
#[test]
fn a_launch_hands_the_chosen_channels_package_to_the_installer_once() {
let key = key();
let dir = tempfile::tempdir().unwrap();
let public = key.public_key().as_ref();
let stable = keep(dir.path(), &key, "stable", "1.1.0");
keep(dir.path(), &key, "stable", "1.0.1");
// Left from before a change to Stable, until the next check removes it.
let beta = keep(dir.path(), &key, "beta", "1.2.0-beta.1");
let launch = |channel, installed, start: Start, outcome: Outcome| {
update_at_launch(dir.path(), public, channel, installed, start, outcome)
};
let stable_launch =
|start: Start, outcome: Outcome| launch(UpdateChannel::Stable, "1.0.0", start, outcome);
let mut started = Vec::new();
let first = stable_launch(&mut recording(&mut started, 42), &mut no_installer);
assert!(applying(&first), "{first:?}");
assert_eq!(started, [stable]);
// A launch while the installer runs waits for it and leaves the app to the version it opens.
let succeeded = stable_launch(&mut never_started, &mut |pid| (pid == 42).then_some(0));
assert!(applying(&succeeded), "{succeeded:?}");
// After a failure the version in place loads and says so once, then never retries on its own.
let failed = stable_launch(&mut never_started, &mut |_| Some(1));
assert!(reports_failed(&failed, "1.1.0"), "{failed:?}");
let next = stable_launch(&mut never_started, &mut no_installer);
assert!(loads_quietly(&next), "{next:?}");
// « Redémarrer » retries it; an installer that is gone counts as failed.
let restart = restart_to_update(dir.path(), public, UpdateChannel::Stable, "1.0.0", |_| {
Ok(43)
});
assert!(restart.is_ok());
let gone = stable_launch(&mut never_started, &mut |pid| (pid != 43).then_some(0));
assert!(reports_failed(&gone, "1.1.0"), "{gone:?}");
// Once the new version is installed, nothing is left to apply.
let installed = launch(
UpdateChannel::Stable,
"1.1.0",
&mut never_started,
&mut no_installer,
);
assert!(loads_quietly(&installed), "{installed:?}");
// The Bêta channel takes only its own package.
let mut started = Vec::new();
let beta_launch = launch(
UpdateChannel::Beta,
"1.1.0",
&mut recording(&mut started, 44),
&mut no_installer,
);
assert!(applying(&beta_launch), "{beta_launch:?}");
assert_eq!(started, [beta]);
}
#[test]
fn an_altered_package_or_an_installer_that_cannot_start_leaves_the_installed_version() {
let key = key();
let dir = tempfile::tempdir().unwrap();
let public = key.public_key().as_ref();
let package = keep(dir.path(), &key, "stable", "1.1.0");
let launch = |start: Start| {
update_at_launch(
dir.path(),
public,
UpdateChannel::Stable,
"1.0.0",
start,
no_installer,
)
};
// Altered between the download and this launch: refused before the installer sees it.
fs::write(&package, b"altered").unwrap();
let refused = launch(&mut never_started);
assert!(
matches!(
refused,
ControlFlow::Continue(Some(Error::InvalidUpdate(_)))
),
"{refused:?}"
);
let restart = restart_to_update(
dir.path(),
public,
UpdateChannel::Stable,
"1.0.0",
never_started,
);
assert!(matches!(restart, Err(Error::InvalidUpdate(_))));
// Downloaded again, then the installer cannot start: reported, and no launch loops on it.
fs::write(&package, b"package 1.1.0").unwrap();
let failed = launch(&mut |_| Err(std::io::ErrorKind::NotFound.into()));
assert!(reports_failed(&failed, "1.1.0"), "{failed:?}");
let next = launch(&mut never_started);
assert!(loads_quietly(&next), "{next:?}");
}
#[test]
fn a_failed_version_is_not_retried_at_launch_but_a_newer_release_is() {
let key = key();
let (url, downloads) = serve(vec![publish(&key, "stable", "1.1.0")], false);
let dir = tempfile::tempdir().unwrap();
let public = key.public_key().as_ref();
let check = || download_update(&url, dir.path(), public, UpdateChannel::Stable, "1.0.0");
let launch = |start: Start, outcome: Outcome| {
update_at_launch(
dir.path(),
public,
UpdateChannel::Stable,
"1.0.0",
start,
outcome,
)
};
assert_eq!(check().unwrap().as_deref(), Some("1.1.0"));
assert!(applying(&launch(&mut |_| Ok(42), &mut no_installer)));
// Velopack deletes a package it cannot open, then reopens the version in place.
let package = dir
.path()
.join("stable-1.1.0/ArenaTracker-1.1.0-stable-full.nupkg");
fs::remove_file(&package).unwrap();
let failed = launch(&mut never_started, &mut |_| Some(1));
assert!(reports_failed(&failed, "1.1.0"), "{failed:?}");
assert_eq!(check().unwrap().as_deref(), Some("1.1.0"));
assert_eq!(downloads.load(Ordering::SeqCst), 2);
let next = launch(&mut never_started, &mut no_installer);
assert!(loads_quietly(&next), "{next:?}");
// The next release gets its own attempt: the app never stays on the version in place.
let newer = vec![
publish(&key, "stable", "1.1.0"),
publish(&key, "stable", "1.2.0"),
publish(&key, "stable", "1.3.0"),
];
let (url, _) = serve(newer, false);
let ready = download_update(&url, dir.path(), public, UpdateChannel::Stable, "1.0.0");
assert_eq!(ready.unwrap().as_deref(), Some("1.3.0"));
assert_eq!(kept(dir.path()), ["stable-1.3.0"]);
let mut started = Vec::new();
let newest = launch(&mut recording(&mut started, 43), &mut no_installer);
assert!(applying(&newest), "{newest:?}");
let package = dir
.path()
.join("stable-1.3.0/ArenaTracker-1.3.0-stable-full.nupkg");
assert_eq!(started, [package]);
}
#[path = "update_package/downloads.rs"]
mod downloads;
#[path = "update_package/launch.rs"]
mod launch;
#[path = "update_package/verification.rs"]
mod verification;
@@ -0,0 +1,177 @@
use super::*;
#[test]
fn each_channel_gets_its_newest_release_above_the_installed_version() {
let key = key();
let (url, _) = serve(
vec![
publish(&key, "stable", "1.0.0"),
publish(&key, "beta", "1.2.0-beta.10"),
publish(&key, "stable", "1.1.0"),
publish(&key, "beta", "1.2.0-beta.2"),
publish(&key, "stable", "1.0.1"),
publish(&key, "stable", "2.0"),
],
false,
);
let dir = tempfile::tempdir().unwrap();
let public = key.public_key().as_ref();
let check =
|channel, installed| download_update(&url, dir.path(), public, channel, installed).unwrap();
assert_eq!(
check(UpdateChannel::Stable, "1.0.0").as_deref(),
Some("1.1.0")
);
assert_eq!(kept(dir.path()), ["stable-1.1.0"]);
let ready = dir.path().join("stable-1.1.0");
assert!(verify_release(&ready, public, "stable", "1.1.0").is_ok());
// The same version or an older one is ignored, and nothing stays pending.
assert_eq!(check(UpdateChannel::Stable, "1.1.0"), None);
assert_eq!(check(UpdateChannel::Stable, "1.2.0"), None);
assert!(kept(dir.path()).is_empty());
// beta.10 comes after beta.2, and the beta channel never takes a stable.
assert_eq!(
check(UpdateChannel::Beta, "1.1.0-beta.1").as_deref(),
Some("1.2.0-beta.10")
);
assert_eq!(
check(UpdateChannel::Beta, "1.0.0").as_deref(),
Some("1.2.0-beta.10")
);
assert_eq!(kept(dir.path()), ["beta-1.2.0-beta.10"]);
assert_eq!(check(UpdateChannel::Beta, "1.2.0-beta.10"), None);
assert!(kept(dir.path()).is_empty());
}
#[test]
fn back_to_stable_from_a_newer_beta_waits_for_a_newer_stable() {
let key = key();
let dir = tempfile::tempdir().unwrap();
let public = key.public_key().as_ref();
let check = |url: &str| {
download_update(
url,
dir.path(),
public,
UpdateChannel::Stable,
"1.2.0-beta.3",
)
.unwrap()
};
let older = vec![
publish(&key, "stable", "1.1.0"),
publish(&key, "beta", "1.2.0-beta.4"),
];
assert_eq!(check(&serve(older, false).0), None);
let newer = vec![
publish(&key, "stable", "1.1.0"),
publish(&key, "stable", "1.2.0"),
];
assert_eq!(check(&serve(newer, false).0).as_deref(), Some("1.2.0"));
}
#[test]
fn a_kept_package_is_verified_again_and_downloaded_again_once_altered() {
let key = key();
let (url, downloads) = serve(vec![publish(&key, "stable", "1.1.0")], false);
let dir = tempfile::tempdir().unwrap();
let public = key.public_key().as_ref();
let check = || download_update(&url, dir.path(), public, UpdateChannel::Stable, "1.0.0");
assert_eq!(check().unwrap().as_deref(), Some("1.1.0"));
assert_eq!(check().unwrap().as_deref(), Some("1.1.0"));
assert_eq!(downloads.load(Ordering::SeqCst), 1);
let package = dir
.path()
.join("stable-1.1.0/ArenaTracker-1.1.0-stable-full.nupkg");
fs::write(&package, b"altered").unwrap();
assert_eq!(check().unwrap().as_deref(), Some("1.1.0"));
assert_eq!(downloads.load(Ordering::SeqCst), 2);
assert_eq!(fs::read(&package).unwrap(), b"package 1.1.0");
}
#[test]
fn a_channel_change_discards_the_other_channels_package_even_offline() {
let key = key();
let (url, _) = serve(
vec![
publish(&key, "stable", "1.1.0"),
publish(&key, "beta", "1.2.0-beta.1"),
],
false,
);
let dir = tempfile::tempdir().unwrap();
let public = key.public_key().as_ref();
let check = |url: &str, channel| download_update(url, dir.path(), public, channel, "1.0.0");
assert!(check(&url, UpdateChannel::Stable).unwrap().is_some());
// A late stable package goes as soon as a beta check starts, before any network access.
let offline = unreachable();
assert!(matches!(
check(&offline, UpdateChannel::Beta),
Err(Error::Source(_))
));
assert!(kept(dir.path()).is_empty());
assert_eq!(
check(&url, UpdateChannel::Beta).unwrap().as_deref(),
Some("1.2.0-beta.1")
);
// Offline, the channel's own pending package stays for a later launch.
assert!(check(&offline, UpdateChannel::Beta).is_err());
assert_eq!(kept(dir.path()), ["beta-1.2.0-beta.1"]);
}
#[test]
fn a_failed_newer_download_keeps_the_older_pending_package() {
let key = key();
let dir = tempfile::tempdir().unwrap();
let public = key.public_key().as_ref();
let check = |url: &str| download_update(url, dir.path(), public, UpdateChannel::Beta, "1.0.0");
let first = vec![publish(&key, "beta", "1.1.0-beta.1")];
assert!(check(&serve(first, false).0).is_ok());
let newer = || {
vec![
publish(&key, "beta", "1.1.0-beta.1"),
publish(&key, "beta", "1.1.0-beta.2"),
]
};
assert!(check(&serve(newer(), true).0).is_err());
assert_eq!(kept(dir.path()), ["beta-1.1.0-beta.1"]);
let ready = check(&serve(newer(), false).0).unwrap();
assert_eq!(ready.as_deref(), Some("1.1.0-beta.2"));
assert_eq!(kept(dir.path()), ["beta-1.1.0-beta.2"]);
}
#[test]
fn network_and_signature_failures_leave_no_update_ready() {
let key = key();
let other = Ed25519KeyPair::from_seed_unchecked(&[8; 32]).unwrap();
let dir = tempfile::tempdir().unwrap();
let public = key.public_key().as_ref();
let check =
|url: &str| download_update(url, dir.path(), public, UpdateChannel::Stable, "1.0.0");
assert!(matches!(check(&unreachable()), Err(Error::Source(_))));
let (cut, _) = serve(vec![publish(&key, "stable", "1.1.0")], true);
assert!(check(&cut).is_err());
assert!(kept(dir.path()).is_empty());
let (forged, _) = serve(vec![publish(&other, "stable", "1.1.0")], false);
assert!(matches!(check(&forged), Err(Error::InvalidUpdate(_))));
assert!(kept(dir.path()).is_empty());
let mut altered = publish(&key, "stable", "1.1.0");
altered.files[2].1 = b"package 6.6.6".to_vec();
assert!(matches!(
check(&serve(vec![altered], false).0),
Err(Error::InvalidUpdate(_))
));
assert!(kept(dir.path()).is_empty());
// A release without its signature is not offered at all.
let mut unsigned = publish(&key, "stable", "1.1.0");
unsigned.files.remove(0);
assert_eq!(check(&serve(vec![unsigned], false).0).unwrap(), None);
}
+153
View File
@@ -0,0 +1,153 @@
use super::*;
#[test]
fn a_launch_hands_the_chosen_channels_package_to_the_installer_once() {
let key = key();
let dir = tempfile::tempdir().unwrap();
let public = key.public_key().as_ref();
let stable = keep(dir.path(), &key, "stable", "1.1.0");
keep(dir.path(), &key, "stable", "1.0.1");
// Left from before a change to Stable, until the next check removes it.
let beta = keep(dir.path(), &key, "beta", "1.2.0-beta.1");
let launch = |channel, installed, start: Start, outcome: Outcome| {
update_at_launch(dir.path(), public, channel, installed, start, outcome)
};
let stable_launch =
|start: Start, outcome: Outcome| launch(UpdateChannel::Stable, "1.0.0", start, outcome);
let mut started = Vec::new();
let first = stable_launch(&mut recording(&mut started, 42), &mut no_installer);
assert!(applying(&first), "{first:?}");
assert_eq!(started, [stable]);
// A launch while the installer runs waits for it and leaves the app to the version it opens.
let succeeded = stable_launch(&mut never_started, &mut |pid| (pid == 42).then_some(0));
assert!(applying(&succeeded), "{succeeded:?}");
// After a failure the version in place loads and says so once, then never retries on its own.
let failed = stable_launch(&mut never_started, &mut |_| Some(1));
assert!(reports_failed(&failed, "1.1.0"), "{failed:?}");
let next = stable_launch(&mut never_started, &mut no_installer);
assert!(loads_quietly(&next), "{next:?}");
// « Redémarrer » retries it; an installer that is gone counts as failed.
let restart = restart_to_update(dir.path(), public, UpdateChannel::Stable, "1.0.0", |_| {
Ok(43)
});
assert!(restart.is_ok());
let gone = stable_launch(&mut never_started, &mut |pid| (pid != 43).then_some(0));
assert!(reports_failed(&gone, "1.1.0"), "{gone:?}");
// Once the new version is installed, nothing is left to apply.
let installed = launch(
UpdateChannel::Stable,
"1.1.0",
&mut never_started,
&mut no_installer,
);
assert!(loads_quietly(&installed), "{installed:?}");
// The Bêta channel takes only its own package.
let mut started = Vec::new();
let beta_launch = launch(
UpdateChannel::Beta,
"1.1.0",
&mut recording(&mut started, 44),
&mut no_installer,
);
assert!(applying(&beta_launch), "{beta_launch:?}");
assert_eq!(started, [beta]);
}
#[test]
fn an_altered_package_or_an_installer_that_cannot_start_leaves_the_installed_version() {
let key = key();
let dir = tempfile::tempdir().unwrap();
let public = key.public_key().as_ref();
let package = keep(dir.path(), &key, "stable", "1.1.0");
let launch = |start: Start| {
update_at_launch(
dir.path(),
public,
UpdateChannel::Stable,
"1.0.0",
start,
no_installer,
)
};
// Altered between the download and this launch: refused before the installer sees it.
fs::write(&package, b"altered").unwrap();
let refused = launch(&mut never_started);
assert!(
matches!(
refused,
ControlFlow::Continue(Some(Error::InvalidUpdate(_)))
),
"{refused:?}"
);
let restart = restart_to_update(
dir.path(),
public,
UpdateChannel::Stable,
"1.0.0",
never_started,
);
assert!(matches!(restart, Err(Error::InvalidUpdate(_))));
// Downloaded again, then the installer cannot start: reported, and no launch loops on it.
fs::write(&package, b"package 1.1.0").unwrap();
let failed = launch(&mut |_| Err(std::io::ErrorKind::NotFound.into()));
assert!(reports_failed(&failed, "1.1.0"), "{failed:?}");
let next = launch(&mut never_started);
assert!(loads_quietly(&next), "{next:?}");
}
#[test]
fn a_failed_version_is_not_retried_at_launch_but_a_newer_release_is() {
let key = key();
let (url, downloads) = serve(vec![publish(&key, "stable", "1.1.0")], false);
let dir = tempfile::tempdir().unwrap();
let public = key.public_key().as_ref();
let check = || download_update(&url, dir.path(), public, UpdateChannel::Stable, "1.0.0");
let launch = |start: Start, outcome: Outcome| {
update_at_launch(
dir.path(),
public,
UpdateChannel::Stable,
"1.0.0",
start,
outcome,
)
};
assert_eq!(check().unwrap().as_deref(), Some("1.1.0"));
assert!(applying(&launch(&mut |_| Ok(42), &mut no_installer)));
// Velopack deletes a package it cannot open, then reopens the version in place.
let package = dir
.path()
.join("stable-1.1.0/ArenaTracker-1.1.0-stable-full.nupkg");
fs::remove_file(&package).unwrap();
let failed = launch(&mut never_started, &mut |_| Some(1));
assert!(reports_failed(&failed, "1.1.0"), "{failed:?}");
assert_eq!(check().unwrap().as_deref(), Some("1.1.0"));
assert_eq!(downloads.load(Ordering::SeqCst), 2);
let next = launch(&mut never_started, &mut no_installer);
assert!(loads_quietly(&next), "{next:?}");
// The next release gets its own attempt: the app never stays on the version in place.
let newer = vec![
publish(&key, "stable", "1.1.0"),
publish(&key, "stable", "1.2.0"),
publish(&key, "stable", "1.3.0"),
];
let (url, _) = serve(newer, false);
let ready = download_update(&url, dir.path(), public, UpdateChannel::Stable, "1.0.0");
assert_eq!(ready.unwrap().as_deref(), Some("1.3.0"));
assert_eq!(kept(dir.path()), ["stable-1.3.0"]);
let mut started = Vec::new();
let newest = launch(&mut recording(&mut started, 43), &mut no_installer);
assert!(applying(&newest), "{newest:?}");
let package = dir
.path()
.join("stable-1.3.0/ArenaTracker-1.3.0-stable-full.nupkg");
assert_eq!(started, [package]);
}
@@ -0,0 +1,60 @@
use super::*;
#[test]
fn only_the_signed_full_package_for_the_expected_release_is_accepted() {
let key = Ed25519KeyPair::from_seed_unchecked(&[7; 32]).unwrap();
let manifest = json!({
"app": "ArenaTracker", "target": "win-x64", "channel": "stable", "version": "1.0.0",
"commit": "c".repeat(40), "package": PACKAGE,
"sha256": "ungWv48Bz+pBQUDeXa4iI7ADYaOWF3qctBD/YfIAFa0="
});
let check = |dir: &TempDir, channel: &str, version: &str| {
verify_release(dir.path(), key.public_key().as_ref(), channel, version)
};
let refused =
|dir: TempDir| matches!(check(&dir, "stable", "1.0.0"), Err(Error::InvalidUpdate(_)));
let doc = serde_json::to_vec(&manifest).unwrap();
let sig = key.sign(&doc);
let good = release(&doc, Some(sig.as_ref()), b"abc");
assert_eq!(check(&good, "stable", "1.0.0").unwrap(), "c".repeat(40));
assert!(check(&good, "beta", "1.0.0").is_err());
assert!(check(&good, "stable", "1.1.0").is_err());
assert!(refused(release(&doc, Some(sig.as_ref()), b"abd")));
assert!(refused(release(&doc, None, b"abc")));
assert!(refused(release(&doc, Some(&[]), b"abc")));
assert!(refused(release(&doc, Some(&[0; 64]), b"abc")));
let missing_package = release(&doc, Some(sig.as_ref()), b"abc");
fs::remove_file(missing_package.path().join(PACKAGE)).unwrap();
assert!(refused(missing_package));
let mut padded = doc.clone();
padded.resize(4097, b' ');
assert!(refused(release(
&padded,
Some(key.sign(&padded).as_ref()),
b"abc"
)));
for (field, wrong) in [
("app", "Other"),
("target", "win-arm64"),
("channel", "beta"),
("version", "1.1.0"),
("package", "different.nupkg"),
("sha256", ""),
] {
let mut other: Value = manifest.clone();
other[field] = wrong.into();
let other = serde_json::to_vec(&other).unwrap();
assert!(
refused(release(&other, Some(sig.as_ref()), b"abc")),
"{field}"
);
assert!(
refused(release(&other, Some(key.sign(&other).as_ref()), b"abc")),
"{field}"
);
}
}