Files
arena-tracker/crates/core/tests/common/client.rs
T

223 lines
7.6 KiB
Rust

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,
}
}
}