SeaBattle/sea_battle_backend/src/test/invite_mode.rs

85 lines
2.7 KiB
Rust
Raw Normal View History

2022-09-24 09:46:12 +00:00
use std::error::Error;
use tokio::sync::mpsc;
use tokio::sync::mpsc::Sender;
use tokio::task;
use crate::args::Args;
use crate::human_player_ws::ServerMessage;
use crate::server::start_server;
use crate::test::bot_client::{ClientEndResult, RunMode};
use crate::test::network_utils::wait_for_port;
use crate::test::{bot_client, TestPort};
#[tokio::test]
async fn invalid_accept_code() {
let _ = env_logger::builder().is_test(true).try_init();
let local_set = task::LocalSet::new();
local_set
.run_until(async move {
task::spawn_local(start_server(Args::for_test(
TestPort::InviteModeInvalidCode,
)));
wait_for_port(TestPort::InviteModeInvalidCode.port()).await;
let res = bot_client::BotClient::new(TestPort::InviteModeInvalidCode.as_url())
.with_run_mode(RunMode::AcceptInvite {
code: "BadCode".to_string(),
})
.run_client()
.await
.unwrap();
assert_eq!(res, ClientEndResult::InvalidInviteCode)
})
.await;
}
async fn run_other_invite_side(
sender: Sender<Result<ClientEndResult, Box<dyn Error>>>,
port: TestPort,
code: String,
) {
let res = bot_client::BotClient::new(port.as_url())
.with_run_mode(RunMode::AcceptInvite { code })
.run_client()
.await;
sender.send(res).await.unwrap()
}
#[tokio::test]
async fn full_game() {
let _ = env_logger::builder().is_test(true).try_init();
let local_set = task::LocalSet::new();
local_set
.run_until(async move {
task::spawn_local(start_server(Args::for_test(TestPort::InviteModeFullGame)));
wait_for_port(TestPort::InviteModeFullGame.port()).await;
let (sender, mut receiver) = mpsc::channel(1);
let res = bot_client::BotClient::new(TestPort::InviteModeFullGame.as_url())
.with_run_mode(RunMode::CreateInvite)
.with_server_msg_callback(move |msg| {
if let ServerMessage::SetInviteCode { code } = msg {
task::spawn_local(run_other_invite_side(
sender.clone(),
TestPort::InviteModeFullGame,
code.clone(),
));
}
})
.run_client()
.await
.unwrap();
assert!(matches!(res, ClientEndResult::Finished { .. }));
let other_side_res = receiver.recv().await.unwrap().unwrap();
assert!(matches!(other_side_res, ClientEndResult::Finished { .. }));
})
.await;
}