Extract league client and ring test modules (#102)

This commit is contained in:
nessar committed 2026-11-22 16:32:09 +01:00
1 parent 40e8f88a98
commit fb9c2b3cf7
4 files changed
+484 -486

No files matched your search

+1 -114
View File
@@ -490,117 +490,4 @@ impl Render for Ring {
}
#[cfg(test)]
mod tests {
use arena_tracker_core::{Champion, ChampionRow, ChampionState};
use gpui_kit::{px, size};
use super::{Geometry, Tick, ticks};
use crate::champion_table::tests::row;
fn champion(id: u32, name: &str, state: ChampionState, points: Option<u64>) -> ChampionRow {
ChampionRow {
champion: Champion {
id,
..row(name).champion
},
state: Some(state),
mastery_points: points,
..row(name)
}
}
fn order(ticks: &[Tick]) -> Vec<(u32, ChampionState)> {
ticks.iter().map(|tick| (tick.id, tick.state)).collect()
}
#[test]
fn completed_by_first_top_1_then_played_then_never_played_by_mastery() {
use ChampionState::*;
// A to Z, as the statistics give them.
let rows = [
champion(1, "Ahri", NeverPlayed, Some(10)),
champion(2, "Brand", Completed, Some(5)),
champion(3, "Garen", InProgress, Some(100)),
champion(4, "Jinx", Completed, Some(900)),
champion(5, "Lux", InProgress, Some(700)),
champion(6, "Zed", NeverPlayed, Some(800)),
];
assert_eq!(
order(&ticks(&rows, &[2, 4])),
[
(2, Completed),
(4, Completed),
(5, InProgress),
(3, InProgress),
(6, NeverPlayed),
(1, NeverPlayed),
]
);
// Unknown points: A to Z, as the cards. An id the rows do not know is skipped.
let unknown: Vec<_> = rows
.iter()
.cloned()
.map(|row| ChampionRow {
mastery_points: None,
..row
})
.collect();
assert_eq!(
order(&ticks(&unknown, &[4, 99, 2])),
[
(4, Completed),
(2, Completed),
(3, InProgress),
(5, InProgress),
(1, NeverPlayed),
(6, NeverPlayed),
]
);
}
/// Which shapes the ring paints: per state, bright or dimmed.
fn painted(ticks: &[Tick], anvil: Option<&[u32]>) -> Vec<(ChampionState, bool)> {
Geometry::new(size(px(200.), px(200.)), ticks, anvil)
.ticks
.iter()
.map(|(state, dim, _)| (*state, *dim))
.collect()
}
#[test]
fn only_the_anvil_champions_ticks_stay_bright() {
use ChampionState::*;
let tick = |id, state| Tick { id, state };
let ring = [
tick(1, Completed),
tick(2, Completed),
tick(3, InProgress),
tick(4, NeverPlayed),
];
// At home, and in a champ select whose list the client did not send: nothing dimmed.
assert_eq!(
painted(&ring, None),
[
(Completed, false),
(InProgress, false),
(NeverPlayed, false)
]
);
// The hand is 1 and 4: 2 and 3 fade.
assert_eq!(
painted(&ring, Some(&[1, 4])),
[
(Completed, false),
(Completed, true),
(InProgress, true),
(NeverPlayed, false),
]
);
// An empty hand: every tick fades.
assert_eq!(
painted(&ring, Some(&[])),
[(Completed, true), (InProgress, true), (NeverPlayed, true)]
);
}
}
mod tests;
+112
View File
@@ -0,0 +1,112 @@
use arena_tracker_core::{Champion, ChampionRow, ChampionState};
use gpui_kit::{px, size};
use super::{Geometry, Tick, ticks};
use crate::champion_table::tests::row;
fn champion(id: u32, name: &str, state: ChampionState, points: Option<u64>) -> ChampionRow {
ChampionRow {
champion: Champion {
id,
..row(name).champion
},
state: Some(state),
mastery_points: points,
..row(name)
}
}
fn order(ticks: &[Tick]) -> Vec<(u32, ChampionState)> {
ticks.iter().map(|tick| (tick.id, tick.state)).collect()
}
#[test]
fn completed_by_first_top_1_then_played_then_never_played_by_mastery() {
use ChampionState::*;
// A to Z, as the statistics give them.
let rows = [
champion(1, "Ahri", NeverPlayed, Some(10)),
champion(2, "Brand", Completed, Some(5)),
champion(3, "Garen", InProgress, Some(100)),
champion(4, "Jinx", Completed, Some(900)),
champion(5, "Lux", InProgress, Some(700)),
champion(6, "Zed", NeverPlayed, Some(800)),
];
assert_eq!(
order(&ticks(&rows, &[2, 4])),
[
(2, Completed),
(4, Completed),
(5, InProgress),
(3, InProgress),
(6, NeverPlayed),
(1, NeverPlayed),
]
);
// Unknown points: A to Z, as the cards. An id the rows do not know is skipped.
let unknown: Vec<_> = rows
.iter()
.cloned()
.map(|row| ChampionRow {
mastery_points: None,
..row
})
.collect();
assert_eq!(
order(&ticks(&unknown, &[4, 99, 2])),
[
(4, Completed),
(2, Completed),
(3, InProgress),
(5, InProgress),
(1, NeverPlayed),
(6, NeverPlayed),
]
);
}
/// Which shapes the ring paints: per state, bright or dimmed.
fn painted(ticks: &[Tick], anvil: Option<&[u32]>) -> Vec<(ChampionState, bool)> {
Geometry::new(size(px(200.), px(200.)), ticks, anvil)
.ticks
.iter()
.map(|(state, dim, _)| (*state, *dim))
.collect()
}
#[test]
fn only_the_anvil_champions_ticks_stay_bright() {
use ChampionState::*;
let tick = |id, state| Tick { id, state };
let ring = [
tick(1, Completed),
tick(2, Completed),
tick(3, InProgress),
tick(4, NeverPlayed),
];
// At home, and in a champ select whose list the client did not send: nothing dimmed.
assert_eq!(
painted(&ring, None),
[
(Completed, false),
(InProgress, false),
(NeverPlayed, false)
]
);
// The hand is 1 and 4: 2 and 3 fade.
assert_eq!(
painted(&ring, Some(&[1, 4])),
[
(Completed, false),
(Completed, true),
(InProgress, true),
(NeverPlayed, false),
]
);
// An empty hand: every tick fades.
assert_eq!(
painted(&ring, Some(&[])),
[(Completed, true), (InProgress, true), (NeverPlayed, true)]
);
}
+1 -372
View File
@@ -428,375 +428,4 @@ fn decode_counter(body: &str, counter_id: Option<&str>) -> Result<Option<u32>, C
}
#[cfg(test)]
mod tests {
use super::*;
const SUMMONER: &str = include_str!("../tests/fixtures/client/current_summoner.json");
const NO_SESSION: &str = include_str!("../tests/fixtures/client/gameflow_session_absent.json");
const GROUPS: &str =
include_str!("../tests/fixtures/client/progression_groups_configuration.json");
const INSTANCE: &str = include_str!("../tests/fixtures/client/progression_instance_data.json");
const SEASON_2: &str = "2026 Season 2 Champs Completed Track";
const ARENA_GAME: &str = include_str!("../tests/fixtures/client/gameflow_session_in_game.json");
#[test]
fn reads_the_port_and_password_of_a_lockfile() {
let sample = "LeagueClient:4242:51234:fake-password_1:https";
assert_eq!(
parse_lockfile(sample),
Some((51234, "fake-password_1".into()))
);
assert_eq!(
parse_lockfile(&format!("{sample}\r\n")),
Some((51234, "fake-password_1".into()))
);
}
#[test]
fn a_malformed_lockfile_is_ignored() {
for bad in [
"",
"LeagueClient",
"LeagueClient:4242:51234:fake-password",
"LeagueClient:4242:notaport:fake-password:https",
"LeagueClient:4242:99999:fake-password:https",
"LeagueClient:4242:51234::https",
"LeagueClient:4242:51234:fake-password:http",
"LeagueClient:4242:51234:fake:password:https",
] {
assert_eq!(parse_lockfile(bad), None, "{bad:?}");
}
}
#[test]
fn reads_the_install_directory_from_the_product_settings() {
let yaml = "auto_patching_enabled_by_player: false\n\
product_install_full_path: \"C:/Riot Games/League of Legends\"\n\
settings:\n locale: \"fr_FR\"\n";
assert_eq!(
install_dir_from_settings(yaml),
Some(PathBuf::from("C:/Riot Games/League of Legends"))
);
assert_eq!(install_dir_from_settings("settings:\n locale: x\n"), None);
assert_eq!(
install_dir_from_settings("product_install_full_path: \"\""),
None
);
}
#[test]
fn basic_authorization_uses_the_riot_user() {
// base64("riot:fake-password")
assert_eq!(
authorization("fake-password"),
"Basic cmlvdDpmYWtlLXBhc3N3b3Jk"
);
}
#[test]
fn the_embedded_root_certificate_builds_a_tls_config() {
assert!(tls_config().is_ok());
}
#[test]
fn reads_the_signed_in_riot_id() {
assert_eq!(
decode_signed_in(SUMMONER),
Ok(("Joueur".into(), "EUW".into()))
);
}
#[test]
fn nobody_signed_in_yet_is_absent() {
for body in [
r#"{"gameName": "Joueur"}"#,
r#"{"gameName": "", "tagLine": "EUW"}"#,
r#"{"gameName": "Joueur", "tagLine": ""}"#,
r#"{"gameName": null, "tagLine": null}"#,
"{}",
] {
assert_eq!(decode_signed_in(body), Err(ClientError::Absent), "{body}");
}
assert!(matches!(
decode_signed_in("<html>"),
Err(ClientError::Other(_))
));
}
#[test]
fn no_gameflow_session_means_idle() {
assert_eq!(
decode_gameflow(404, NO_SESSION),
Ok(Gameflow {
phase: GamePhase::Idle,
arena: false,
game_id: None
})
);
}
#[test]
fn an_arena_game_in_progress_is_in_game_and_arena() {
assert_eq!(
decode_gameflow(200, ARENA_GAME),
Ok(Gameflow {
phase: GamePhase::InGame,
arena: true,
game_id: Some(9000000099)
})
);
let classic = r#"{"phase": "InProgress", "gameData": {"queue": {"gameMode": "CLASSIC"}}}"#;
assert_eq!(
decode_gameflow(200, classic),
Ok(Gameflow {
phase: GamePhase::InGame,
arena: false,
game_id: None
})
);
}
#[test]
fn unknown_and_missing_gameflow_fields_are_not_errors() {
let extra = r#"{"phase": "ChampSelect", "somethingNew": {"a": [1, 2]}, "map": null,
"gameData": {"queue": null}}"#;
assert_eq!(
decode_gameflow(200, extra),
Ok(Gameflow {
phase: GamePhase::ChampSelect,
arena: false,
game_id: None
})
);
assert_eq!(decode_gameflow(200, "{}"), decode_gameflow(404, ""));
// The map alone says Arena when the queue is missing.
let map_only = r#"{"phase": "EndOfGame", "map": {"gameMode": "CHERRY"}}"#;
assert_eq!(
decode_gameflow(200, map_only),
Ok(Gameflow {
phase: GamePhase::Ended,
arena: true,
game_id: None
})
);
// An id of 0 means no game; one that is not a number is ignored.
for id in ["0", "\"x\"", "null", "-1"] {
let body = format!(r#"{{"phase": "InProgress", "gameData": {{"gameId": {id}}}}}"#);
assert_eq!(decode_gameflow(200, &body).unwrap().game_id, None, "{id}");
}
assert_eq!(
decode_gameflow(503, ""),
Err(ClientError::Other("HTTP 503".into()))
);
}
#[test]
fn finds_the_champs_completed_tracks_by_exact_name() {
for (name, group, counter) in [
(
SEASON_2,
"01030e0d-e3e3-4034-93dc-44a88bcb8401",
"d64a3f04-2ba0-475a-9a33-782cb12e6467",
),
(
"2026 Season 1 Champs Completed Track",
"7d0ef399-dd59-4005-bf1d-e0b98cda8acb",
"be96f5dc-d65c-4ea4-9a23-0b2c1bb6880f",
),
(
"Cherry 2025 Champs Completed Track",
"e5d45c5c-a035-4e0a-9c9d-c02a3604a3b9",
"ae1d0604-8841-4640-987e-29696c18caca",
),
] {
assert_eq!(
find_track(GROUPS, name),
Ok(Some((group.into(), Some(counter.into())))),
"{name}"
);
}
for unknown in ["2026 Season 3 Champs Completed Track", "2026 Season 2", ""] {
assert_eq!(find_track(GROUPS, unknown), Ok(None), "{unknown:?}");
}
assert_eq!(find_track("[]", SEASON_2), Ok(None));
}
#[test]
fn reads_the_counter_of_the_track() {
let counter = "d64a3f04-2ba0-475a-9a33-782cb12e6467";
assert_eq!(decode_counter(INSTANCE, Some(counter)), Ok(Some(52)));
// Without a usable counter id, the first counter is read.
assert_eq!(decode_counter(INSTANCE, None), Ok(Some(52)));
assert_eq!(decode_counter(INSTANCE, Some("other")), Ok(Some(52)));
assert_eq!(decode_counter(r#"{"counters": []}"#, None), Ok(None));
assert_eq!(decode_counter("{}", Some(counter)), Ok(None));
}
#[test]
fn reads_the_topic_and_data_of_an_event_frame() {
let (topic, data) = decode_event(&frame(
SESSION_EVENT,
"Update",
r#"{"localPlayerCellId":16}"#,
))
.unwrap();
assert_eq!(topic, SESSION_EVENT);
assert_eq!(data["localPlayerCellId"], 16);
let (_, data) = decode_event(&frame(SESSION_EVENT, "Delete", "null")).unwrap();
assert!(data.is_null());
assert!(decode_event("not json").is_none());
assert!(decode_event("[]").is_none());
}
/// A frame as the client sends it: the resource sits in the envelope's `data`.
fn frame(topic: &str, event_type: &str, data: &str) -> String {
format!(r#"[8,"{topic}",{{"data":{data},"eventType":"{event_type}","uri":"/x"}}]"#)
}
/// A session body the reader can assemble, with this local pick.
fn session(current: u32) -> String {
format!(
r#"{{"localPlayerCellId":16,"myTeam":[{{"cellId":16,"championId":{current},
"championPickIntent":0}},{{"cellId":17,"championId":0,
"championPickIntent":0}}],"actions":[],
"bans":{{"myTeamBans":[],"theirTeamBans":[]}}}}"#
)
}
#[test]
fn a_raw_event_frame_updates_the_cached_session_and_lists() {
let client = LeagueClient::in_dir(PathBuf::new());
client
.champ_select_reader
.read(
|| Ok(session(0)),
|| Ok(("[1,2]".into(), "[]".into(), Some("[]".into()))),
)
.unwrap();
let apply = |topic, event_type, data: &str| {
let (topic, data) = decode_event(&frame(topic, event_type, data)).unwrap();
client.apply_event(&topic, data)
};
assert_eq!(
apply(SESSION_EVENT, "Update", &session(16)),
Some(ClientEvent::ChampSelect)
);
assert_eq!(
apply(ANVIL_EVENT, "Update", "[9,8]"),
Some(ClientEvent::ChampSelect)
);
assert_eq!(
apply(PICKABLE_EVENT, "Update", "[2]"),
Some(ClientEvent::ChampSelect)
);
// A deleted session carries nothing: it costs no request. Other Deletes change nothing
// either, but still wake the follower.
assert_eq!(apply(SESSION_EVENT, "Delete", "null"), None);
assert_eq!(
apply(ANVIL_EVENT, "Delete", "null"),
Some(ClientEvent::ChampSelect)
);
assert_eq!(
apply(PICKABLE_EVENT, "Delete", "null"),
Some(ClientEvent::ChampSelect)
);
// The event session replaces the request and the updated lists are used.
let pick = client
.champ_select_reader
.read(
|| panic!("the event session must be used"),
|| panic!("the lists must stay cached"),
)
.unwrap();
assert_eq!(pick.current, Some(16));
assert_eq!(pick.anvil_champions, Some(vec![9, 8]));
assert!(!pick.can_pick(1));
assert!(pick.can_pick(2));
}
#[test]
fn only_a_client_that_is_gone_is_absent() {
let io = |kind| ureq::Error::Io(std::io::Error::from(kind));
assert_eq!(
transport_error(io(ErrorKind::ConnectionRefused)),
ClientError::Absent
);
for transient in [
ureq::Error::Timeout(ureq::Timeout::Global),
io(ErrorKind::TimedOut),
io(ErrorKind::ConnectionReset),
] {
assert!(matches!(transport_error(transient), ClientError::Other(_)));
}
}
#[test]
fn events_update_only_the_list_they_concern() {
use serde_json::json;
let client = LeagueClient::in_dir(PathBuf::new());
client
.champ_select_reader
.read(
|| Ok(session(0)),
|| Ok(("[1,2]".into(), "[2]".into(), Some("[9]".into()))),
)
.unwrap();
// A gameflow event leaves the champion lists alone; the old code cleared them all.
assert_eq!(
client.apply_event("OnJsonApiEvent_lol-gameflow_v1_session", json!({})),
Some(ClientEvent::Other)
);
let read = || {
client
.champ_select_reader
.read(|| Ok(session(0)), || panic!("the lists must stay cached"))
.unwrap()
};
let pick = read();
assert_eq!(pick.anvil_champions, Some(vec![9]));
assert!(pick.can_pick(1));
assert!(!pick.can_pick(2));
assert_eq!(
client.apply_event(PICKABLE_EVENT, json!([1, 3])),
Some(ClientEvent::ChampSelect)
);
let pick = read();
assert!(pick.can_pick(1));
assert!(pick.can_pick(3));
assert!(!pick.can_pick(2));
// A session event is kept for the next read instead of a request.
assert_eq!(
client.apply_event(SESSION_EVENT, serde_json::from_str(&session(16)).unwrap()),
Some(ClientEvent::ChampSelect)
);
assert!(
client
.champ_select_reader
.read(
|| panic!("the event session must be used"),
|| panic!("the lists must stay cached"),
)
.is_ok()
);
}
#[test]
fn without_a_lockfile_the_client_is_absent() {
let dir = tempfile::tempdir().unwrap();
let client = LeagueClient::in_dir(dir.path().into());
assert_eq!(client.signed_in(), Err(ClientError::Absent));
assert_eq!(client.gameflow(), Err(ClientError::Absent));
assert_eq!(client.official_progress(SEASON_2), Err(ClientError::Absent));
let started = Instant::now();
assert_eq!(
client.wait_for_event(Duration::from_millis(50)),
ClientEvent::Other
);
assert!(started.elapsed() >= Duration::from_millis(50));
assert!(started.elapsed() < TIMEOUT);
}
}
mod tests;
+370
View File
@@ -0,0 +1,370 @@
use super::*;
const SUMMONER: &str = include_str!("../../tests/fixtures/client/current_summoner.json");
const NO_SESSION: &str = include_str!("../../tests/fixtures/client/gameflow_session_absent.json");
const GROUPS: &str =
include_str!("../../tests/fixtures/client/progression_groups_configuration.json");
const INSTANCE: &str = include_str!("../../tests/fixtures/client/progression_instance_data.json");
const SEASON_2: &str = "2026 Season 2 Champs Completed Track";
const ARENA_GAME: &str = include_str!("../../tests/fixtures/client/gameflow_session_in_game.json");
#[test]
fn reads_the_port_and_password_of_a_lockfile() {
let sample = "LeagueClient:4242:51234:fake-password_1:https";
assert_eq!(
parse_lockfile(sample),
Some((51234, "fake-password_1".into()))
);
assert_eq!(
parse_lockfile(&format!("{sample}\r\n")),
Some((51234, "fake-password_1".into()))
);
}
#[test]
fn a_malformed_lockfile_is_ignored() {
for bad in [
"",
"LeagueClient",
"LeagueClient:4242:51234:fake-password",
"LeagueClient:4242:notaport:fake-password:https",
"LeagueClient:4242:99999:fake-password:https",
"LeagueClient:4242:51234::https",
"LeagueClient:4242:51234:fake-password:http",
"LeagueClient:4242:51234:fake:password:https",
] {
assert_eq!(parse_lockfile(bad), None, "{bad:?}");
}
}
#[test]
fn reads_the_install_directory_from_the_product_settings() {
let yaml = "auto_patching_enabled_by_player: false\n\
product_install_full_path: \"C:/Riot Games/League of Legends\"\n\
settings:\n locale: \"fr_FR\"\n";
assert_eq!(
install_dir_from_settings(yaml),
Some(PathBuf::from("C:/Riot Games/League of Legends"))
);
assert_eq!(install_dir_from_settings("settings:\n locale: x\n"), None);
assert_eq!(
install_dir_from_settings("product_install_full_path: \"\""),
None
);
}
#[test]
fn basic_authorization_uses_the_riot_user() {
// base64("riot:fake-password")
assert_eq!(
authorization("fake-password"),
"Basic cmlvdDpmYWtlLXBhc3N3b3Jk"
);
}
#[test]
fn the_embedded_root_certificate_builds_a_tls_config() {
assert!(tls_config().is_ok());
}
#[test]
fn reads_the_signed_in_riot_id() {
assert_eq!(
decode_signed_in(SUMMONER),
Ok(("Joueur".into(), "EUW".into()))
);
}
#[test]
fn nobody_signed_in_yet_is_absent() {
for body in [
r#"{"gameName": "Joueur"}"#,
r#"{"gameName": "", "tagLine": "EUW"}"#,
r#"{"gameName": "Joueur", "tagLine": ""}"#,
r#"{"gameName": null, "tagLine": null}"#,
"{}",
] {
assert_eq!(decode_signed_in(body), Err(ClientError::Absent), "{body}");
}
assert!(matches!(
decode_signed_in("<html>"),
Err(ClientError::Other(_))
));
}
#[test]
fn no_gameflow_session_means_idle() {
assert_eq!(
decode_gameflow(404, NO_SESSION),
Ok(Gameflow {
phase: GamePhase::Idle,
arena: false,
game_id: None
})
);
}
#[test]
fn an_arena_game_in_progress_is_in_game_and_arena() {
assert_eq!(
decode_gameflow(200, ARENA_GAME),
Ok(Gameflow {
phase: GamePhase::InGame,
arena: true,
game_id: Some(9000000099)
})
);
let classic = r#"{"phase": "InProgress", "gameData": {"queue": {"gameMode": "CLASSIC"}}}"#;
assert_eq!(
decode_gameflow(200, classic),
Ok(Gameflow {
phase: GamePhase::InGame,
arena: false,
game_id: None
})
);
}
#[test]
fn unknown_and_missing_gameflow_fields_are_not_errors() {
let extra = r#"{"phase": "ChampSelect", "somethingNew": {"a": [1, 2]}, "map": null,
"gameData": {"queue": null}}"#;
assert_eq!(
decode_gameflow(200, extra),
Ok(Gameflow {
phase: GamePhase::ChampSelect,
arena: false,
game_id: None
})
);
assert_eq!(decode_gameflow(200, "{}"), decode_gameflow(404, ""));
// The map alone says Arena when the queue is missing.
let map_only = r#"{"phase": "EndOfGame", "map": {"gameMode": "CHERRY"}}"#;
assert_eq!(
decode_gameflow(200, map_only),
Ok(Gameflow {
phase: GamePhase::Ended,
arena: true,
game_id: None
})
);
// An id of 0 means no game; one that is not a number is ignored.
for id in ["0", "\"x\"", "null", "-1"] {
let body = format!(r#"{{"phase": "InProgress", "gameData": {{"gameId": {id}}}}}"#);
assert_eq!(decode_gameflow(200, &body).unwrap().game_id, None, "{id}");
}
assert_eq!(
decode_gameflow(503, ""),
Err(ClientError::Other("HTTP 503".into()))
);
}
#[test]
fn finds_the_champs_completed_tracks_by_exact_name() {
for (name, group, counter) in [
(
SEASON_2,
"01030e0d-e3e3-4034-93dc-44a88bcb8401",
"d64a3f04-2ba0-475a-9a33-782cb12e6467",
),
(
"2026 Season 1 Champs Completed Track",
"7d0ef399-dd59-4005-bf1d-e0b98cda8acb",
"be96f5dc-d65c-4ea4-9a23-0b2c1bb6880f",
),
(
"Cherry 2025 Champs Completed Track",
"e5d45c5c-a035-4e0a-9c9d-c02a3604a3b9",
"ae1d0604-8841-4640-987e-29696c18caca",
),
] {
assert_eq!(
find_track(GROUPS, name),
Ok(Some((group.into(), Some(counter.into())))),
"{name}"
);
}
for unknown in ["2026 Season 3 Champs Completed Track", "2026 Season 2", ""] {
assert_eq!(find_track(GROUPS, unknown), Ok(None), "{unknown:?}");
}
assert_eq!(find_track("[]", SEASON_2), Ok(None));
}
#[test]
fn reads_the_counter_of_the_track() {
let counter = "d64a3f04-2ba0-475a-9a33-782cb12e6467";
assert_eq!(decode_counter(INSTANCE, Some(counter)), Ok(Some(52)));
// Without a usable counter id, the first counter is read.
assert_eq!(decode_counter(INSTANCE, None), Ok(Some(52)));
assert_eq!(decode_counter(INSTANCE, Some("other")), Ok(Some(52)));
assert_eq!(decode_counter(r#"{"counters": []}"#, None), Ok(None));
assert_eq!(decode_counter("{}", Some(counter)), Ok(None));
}
#[test]
fn reads_the_topic_and_data_of_an_event_frame() {
let (topic, data) = decode_event(&frame(
SESSION_EVENT,
"Update",
r#"{"localPlayerCellId":16}"#,
))
.unwrap();
assert_eq!(topic, SESSION_EVENT);
assert_eq!(data["localPlayerCellId"], 16);
let (_, data) = decode_event(&frame(SESSION_EVENT, "Delete", "null")).unwrap();
assert!(data.is_null());
assert!(decode_event("not json").is_none());
assert!(decode_event("[]").is_none());
}
/// A frame as the client sends it: the resource sits in the envelope's `data`.
fn frame(topic: &str, event_type: &str, data: &str) -> String {
format!(r#"[8,"{topic}",{{"data":{data},"eventType":"{event_type}","uri":"/x"}}]"#)
}
/// A session body the reader can assemble, with this local pick.
fn session(current: u32) -> String {
format!(
r#"{{"localPlayerCellId":16,"myTeam":[{{"cellId":16,"championId":{current},
"championPickIntent":0}},{{"cellId":17,"championId":0,
"championPickIntent":0}}],"actions":[],
"bans":{{"myTeamBans":[],"theirTeamBans":[]}}}}"#
)
}
#[test]
fn a_raw_event_frame_updates_the_cached_session_and_lists() {
let client = LeagueClient::in_dir(PathBuf::new());
client
.champ_select_reader
.read(
|| Ok(session(0)),
|| Ok(("[1,2]".into(), "[]".into(), Some("[]".into()))),
)
.unwrap();
let apply = |topic, event_type, data: &str| {
let (topic, data) = decode_event(&frame(topic, event_type, data)).unwrap();
client.apply_event(&topic, data)
};
assert_eq!(
apply(SESSION_EVENT, "Update", &session(16)),
Some(ClientEvent::ChampSelect)
);
assert_eq!(
apply(ANVIL_EVENT, "Update", "[9,8]"),
Some(ClientEvent::ChampSelect)
);
assert_eq!(
apply(PICKABLE_EVENT, "Update", "[2]"),
Some(ClientEvent::ChampSelect)
);
// A deleted session carries nothing: it costs no request. Other Deletes change nothing
// either, but still wake the follower.
assert_eq!(apply(SESSION_EVENT, "Delete", "null"), None);
assert_eq!(
apply(ANVIL_EVENT, "Delete", "null"),
Some(ClientEvent::ChampSelect)
);
assert_eq!(
apply(PICKABLE_EVENT, "Delete", "null"),
Some(ClientEvent::ChampSelect)
);
// The event session replaces the request and the updated lists are used.
let pick = client
.champ_select_reader
.read(
|| panic!("the event session must be used"),
|| panic!("the lists must stay cached"),
)
.unwrap();
assert_eq!(pick.current, Some(16));
assert_eq!(pick.anvil_champions, Some(vec![9, 8]));
assert!(!pick.can_pick(1));
assert!(pick.can_pick(2));
}
#[test]
fn only_a_client_that_is_gone_is_absent() {
let io = |kind| ureq::Error::Io(std::io::Error::from(kind));
assert_eq!(
transport_error(io(ErrorKind::ConnectionRefused)),
ClientError::Absent
);
for transient in [
ureq::Error::Timeout(ureq::Timeout::Global),
io(ErrorKind::TimedOut),
io(ErrorKind::ConnectionReset),
] {
assert!(matches!(transport_error(transient), ClientError::Other(_)));
}
}
#[test]
fn events_update_only_the_list_they_concern() {
use serde_json::json;
let client = LeagueClient::in_dir(PathBuf::new());
client
.champ_select_reader
.read(
|| Ok(session(0)),
|| Ok(("[1,2]".into(), "[2]".into(), Some("[9]".into()))),
)
.unwrap();
// A gameflow event leaves the champion lists alone; the old code cleared them all.
assert_eq!(
client.apply_event("OnJsonApiEvent_lol-gameflow_v1_session", json!({})),
Some(ClientEvent::Other)
);
let read = || {
client
.champ_select_reader
.read(|| Ok(session(0)), || panic!("the lists must stay cached"))
.unwrap()
};
let pick = read();
assert_eq!(pick.anvil_champions, Some(vec![9]));
assert!(pick.can_pick(1));
assert!(!pick.can_pick(2));
assert_eq!(
client.apply_event(PICKABLE_EVENT, json!([1, 3])),
Some(ClientEvent::ChampSelect)
);
let pick = read();
assert!(pick.can_pick(1));
assert!(pick.can_pick(3));
assert!(!pick.can_pick(2));
// A session event is kept for the next read instead of a request.
assert_eq!(
client.apply_event(SESSION_EVENT, serde_json::from_str(&session(16)).unwrap()),
Some(ClientEvent::ChampSelect)
);
assert!(
client
.champ_select_reader
.read(
|| panic!("the event session must be used"),
|| panic!("the lists must stay cached"),
)
.is_ok()
);
}
#[test]
fn without_a_lockfile_the_client_is_absent() {
let dir = tempfile::tempdir().unwrap();
let client = LeagueClient::in_dir(dir.path().into());
assert_eq!(client.signed_in(), Err(ClientError::Absent));
assert_eq!(client.gameflow(), Err(ClientError::Absent));
assert_eq!(client.official_progress(SEASON_2), Err(ClientError::Absent));
let started = Instant::now();
assert_eq!(
client.wait_for_event(Duration::from_millis(50)),
ClientEvent::Other
);
assert!(started.elapsed() >= Duration::from_millis(50));
assert!(started.elapsed() < TIMEOUT);
}