Backend - Add match logic (#38)
* add method to update server state * add draft test match unit test class * add join response message class * add lobby state message class * add spectator raw type * add start match json schema * add start match message class * add test client manager class * change client to return server responses as python classes * add start match test method * adapt old unit tests to use python message classes * shortcut two players join and ready protocol * fix wrong imports * add message to assertion * make broadcast function send message provided as argument * add match state message class * add match state json schema * add match utility class * add match state message class * extend test function with match state check * remove print statement * add missing match schemas to frontend and add id properties * make state keys unique * fix MockSocket * add basic match history funtionality * use Prettier formatter * fix typehint error
This commit is contained in:
1 parent
db3781c11d
commit
72e6cb10ed
21 files changed
+465
-126
No files matched your search
@@ -0,0 +1,77 @@
|
||||
from autobeerpong.types.raw import MessageRaw_T
|
||||
|
||||
|
||||
class Team:
|
||||
def __init__(self) -> None:
|
||||
self.formation = [1, 2, 3]
|
||||
self.cups = [True, True, True]
|
||||
|
||||
def rotate(self) -> None:
|
||||
self.formation.insert(0, self.formation.pop())
|
||||
|
||||
def hit_cup(self) -> None:
|
||||
for _ in range(len(self.cups)):
|
||||
pass
|
||||
|
||||
|
||||
class Match:
|
||||
def __init__(self) -> None:
|
||||
self.turn = True
|
||||
self.team_a = Team()
|
||||
self.team_b = Team()
|
||||
self.history: list[MessageRaw_T] = []
|
||||
|
||||
def get_table_state(self) -> MessageRaw_T:
|
||||
return {
|
||||
"cupsA": self.team_a.cups.copy(),
|
||||
"cupsB": self.team_b.cups.copy(),
|
||||
"teamA": self.team_a.formation.copy(),
|
||||
"teamB": self.team_b.formation.copy(),
|
||||
}
|
||||
|
||||
def get_action(self) -> MessageRaw_T:
|
||||
turn = "a" if self.turn else "b"
|
||||
x_pos = -150 if self.turn else 150
|
||||
x_vel = 250 if self.turn else -250
|
||||
|
||||
# determine if hit
|
||||
# is_hit = True if random.random() >= 0.5 else False
|
||||
|
||||
return {
|
||||
"turn": turn,
|
||||
"parabola": {
|
||||
"startPosition": [x_pos, -200],
|
||||
"startVelocity": [x_vel, -300],
|
||||
"stopTime": 900,
|
||||
},
|
||||
}
|
||||
|
||||
def match_not_over(self) -> bool:
|
||||
return any(self.team_a.cups) and any(self.team_b.cups)
|
||||
|
||||
def resolve(self) -> None:
|
||||
# first send table state
|
||||
self.history.append(self.get_table_state())
|
||||
|
||||
while self.match_not_over():
|
||||
# action
|
||||
active_team = self.team_a if self.turn else self.team_b
|
||||
other_team = self.team_a if not self.turn else self.team_b
|
||||
|
||||
self.history.append(self.get_action())
|
||||
|
||||
for i in range(len(other_team.cups)):
|
||||
if other_team.cups[i]:
|
||||
other_team.cups[i] = False
|
||||
break
|
||||
|
||||
active_team.rotate()
|
||||
# table state
|
||||
self.history.append(self.get_table_state())
|
||||
self.turn = not self.turn
|
||||
|
||||
def to_raw(self) -> MessageRaw_T:
|
||||
return {
|
||||
"messageType": "matchState",
|
||||
"messageContent": {"history": self.history},
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
from autobeerpong.messages.message import Message, MessageRaw_T
|
||||
from autobeerpong.messages.message import Message
|
||||
from autobeerpong.messages.lobby.join_response import JoinResponseMessage
|
||||
from autobeerpong.types.raw import MessageRaw_T
|
||||
from autobeerpong.client import Client
|
||||
from autobeerpong.contexts.server import ServerContext
|
||||
from autobeerpong.contexts.client import ClientContext
|
||||
@@ -42,11 +44,11 @@ class JoinMessage(Message):
|
||||
client_context.has_joined = True
|
||||
client_context.client_id = client_id
|
||||
|
||||
join_message_raw: MessageRaw_T = {
|
||||
join_message = JoinResponseMessage(
|
||||
{
|
||||
"messageType": "joinResponse",
|
||||
"messageContent": {"client": client.as_raw()},
|
||||
}
|
||||
)
|
||||
|
||||
Message.validate(join_message_raw)
|
||||
|
||||
await client.send(join_message_raw)
|
||||
await client.send(join_message.to_raw())
|
||||
@@ -0,0 +1,17 @@
|
||||
from autobeerpong.messages.message import Message
|
||||
from autobeerpong.types.raw import MessageRaw_T, ClientRaw_T
|
||||
|
||||
|
||||
class JoinResponseMessage(Message):
|
||||
has_direct_response = False
|
||||
|
||||
def _contents_from_raw(self, message_raw: MessageRaw_T):
|
||||
self.client_raw: ClientRaw_T = message_raw["messageContent"]["client"]
|
||||
|
||||
def to_raw(self) -> MessageRaw_T:
|
||||
msg_raw = super().to_raw()
|
||||
msg_raw["messageContent"].update({"client": self.client_raw})
|
||||
|
||||
self.validate(msg_raw)
|
||||
|
||||
return msg_raw
|
||||
@@ -0,0 +1,21 @@
|
||||
from autobeerpong.messages.message import Message
|
||||
from autobeerpong.types.raw import MessageRaw_T, PlayerRaw_T, SpectatorRaw_T
|
||||
|
||||
|
||||
class LobbyStateMessage(Message):
|
||||
has_direct_response = False
|
||||
|
||||
def _contents_from_raw(self, message_raw: MessageRaw_T):
|
||||
self.players: list[PlayerRaw_T] = message_raw["messageContent"]["players"]
|
||||
self.spectators: list[SpectatorRaw_T] = message_raw["messageContent"][
|
||||
"spectators"
|
||||
]
|
||||
|
||||
def to_raw(self) -> MessageRaw_T:
|
||||
msg_raw = super().to_raw()
|
||||
msg_raw["messageContent"].update({"players": self.players})
|
||||
msg_raw["messageContent"].update({"spectators": self.spectators})
|
||||
|
||||
self.validate(msg_raw)
|
||||
|
||||
return msg_raw
|
||||
Whitespace-only changes.
@@ -0,0 +1,17 @@
|
||||
from autobeerpong.messages.message import Message
|
||||
from autobeerpong.types.raw import MessageRaw_T
|
||||
|
||||
|
||||
class MatchStateMessage(Message):
|
||||
has_direct_response = False
|
||||
|
||||
def _contents_from_raw(self, message_raw: MessageRaw_T) -> None:
|
||||
self.history = message_raw["messageContent"]["history"]
|
||||
|
||||
def to_raw(self) -> MessageRaw_T:
|
||||
msg_raw = super().to_raw()
|
||||
msg_raw["messageContent"].update({"history": self.history})
|
||||
|
||||
self.validate(msg_raw)
|
||||
|
||||
return msg_raw
|
||||
@@ -0,0 +1,16 @@
|
||||
from autobeerpong.messages.message import Message
|
||||
from autobeerpong.types.raw import MessageRaw_T
|
||||
|
||||
|
||||
class StartMatchMessage(Message):
|
||||
has_direct_response = False
|
||||
|
||||
def _contents_from_raw(self, message_raw: MessageRaw_T) -> None:
|
||||
pass
|
||||
|
||||
def to_raw(self) -> MessageRaw_T:
|
||||
msg_raw = super().to_raw()
|
||||
|
||||
self.validate(msg_raw)
|
||||
|
||||
return msg_raw
|
||||
@@ -7,26 +7,76 @@ from websockets.exceptions import ConnectionClosedOK
|
||||
import autobeerpong.config as config
|
||||
from autobeerpong.messages.message import Message, MessageRaw_T
|
||||
from autobeerpong.messages.lobby.join import JoinMessage
|
||||
from autobeerpong.messages.lobby.join_response import JoinResponseMessage
|
||||
from autobeerpong.messages.lobby.rejoin import RejoinMessage
|
||||
from autobeerpong.messages.lobby.toggle_ready import ToggleReadyMessage
|
||||
from autobeerpong.messages.lobby.toggle_role import ToggleRoleMessage
|
||||
from autobeerpong.messages.lobby.state import LobbyStateMessage
|
||||
from autobeerpong.messages.match.start_match import StartMatchMessage
|
||||
from autobeerpong.messages.match.match_state import MatchStateMessage
|
||||
from autobeerpong.contexts.server import ServerContext
|
||||
from autobeerpong.contexts.client import ClientContext
|
||||
from autobeerpong.states.client import ClientState
|
||||
from autobeerpong.states.server import ServerState
|
||||
from autobeerpong.match import Match
|
||||
|
||||
|
||||
class AutobeerpongServer:
|
||||
message_map: dict[str, type[Message]] = {
|
||||
# LOBBY
|
||||
"join": JoinMessage,
|
||||
"joinResponse": JoinResponseMessage,
|
||||
"rejoin": RejoinMessage,
|
||||
"toggleReady": ToggleReadyMessage,
|
||||
"toggleRole": ToggleRoleMessage,
|
||||
"lobbyState": LobbyStateMessage,
|
||||
# MATCH
|
||||
"startMatch": StartMatchMessage,
|
||||
"matchState": MatchStateMessage,
|
||||
}
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.context = ServerContext()
|
||||
|
||||
async def broadcast(self):
|
||||
async def broadcast(self, msg_raw: MessageRaw_T) -> None:
|
||||
connected_clients = list(
|
||||
filter(
|
||||
lambda x: x.state is not ClientState.DISCONNECTED,
|
||||
self.context.clients.values(),
|
||||
)
|
||||
)
|
||||
|
||||
for client in connected_clients:
|
||||
await client.send(msg_raw)
|
||||
|
||||
async def update_server_state(self) -> None:
|
||||
if self.context.state is ServerState.LOBBY:
|
||||
players = list(
|
||||
filter(
|
||||
lambda x: x.state is ClientState.PLAYER,
|
||||
self.context.clients.values(),
|
||||
)
|
||||
)
|
||||
|
||||
if all([player.ready for player in players]):
|
||||
# all players are ready, advance server state to match
|
||||
self.context.state = ServerState.MATCH
|
||||
# send match start message to all connected clients
|
||||
start_match = StartMatchMessage(
|
||||
{"messageType": "startMatch", "messageContent": {}}
|
||||
)
|
||||
|
||||
await self.broadcast(start_match.to_raw())
|
||||
|
||||
match = Match()
|
||||
match.resolve()
|
||||
|
||||
await self.broadcast(match.to_raw())
|
||||
|
||||
elif self.context.state is ServerState.MATCH:
|
||||
pass
|
||||
|
||||
def get_lobby_state(self) -> LobbyStateMessage:
|
||||
players = list(
|
||||
filter(
|
||||
lambda x: x.state is ClientState.PLAYER,
|
||||
@@ -40,33 +90,22 @@ class AutobeerpongServer:
|
||||
)
|
||||
)
|
||||
|
||||
lobby_state_raw: MessageRaw_T = {
|
||||
return LobbyStateMessage(
|
||||
{
|
||||
"messageType": "lobbyState",
|
||||
"messageContent": {
|
||||
"players": [player.as_raw_player() for player in players],
|
||||
"spectators": [spectator.as_raw() for spectator in spectators],
|
||||
},
|
||||
}
|
||||
|
||||
# for validation
|
||||
Message.validate(lobby_state_raw)
|
||||
|
||||
connected_clients = list(
|
||||
filter(
|
||||
lambda x: x.state is not ClientState.DISCONNECTED,
|
||||
self.context.clients.values(),
|
||||
)
|
||||
)
|
||||
|
||||
for client in connected_clients:
|
||||
await client.send(lobby_state_raw)
|
||||
|
||||
async def handler(self, websocket: ServerConnection) -> None:
|
||||
client_context = ClientContext(websocket)
|
||||
|
||||
async for msg in websocket:
|
||||
message_raw: MessageRaw_T = json.loads(msg)
|
||||
message_type: str = message_raw.get("messageType")
|
||||
message_type = str(message_raw.get("messageType"))
|
||||
|
||||
if message_type is None:
|
||||
raise Exception("Message has no messageType property.")
|
||||
@@ -83,12 +122,13 @@ class AutobeerpongServer:
|
||||
client_context=client_context,
|
||||
)
|
||||
|
||||
await self.broadcast()
|
||||
await self.broadcast(self.get_lobby_state().to_raw())
|
||||
await self.update_server_state()
|
||||
|
||||
if client_context.has_joined:
|
||||
self.context.clients[client_context.get_client_id()].disconnect()
|
||||
try:
|
||||
await self.broadcast()
|
||||
await self.broadcast(self.get_lobby_state().to_raw())
|
||||
except ConnectionClosedOK:
|
||||
pass
|
||||
|
||||
|
||||
@@ -4,3 +4,4 @@ _Raw_T = dict[str, Any]
|
||||
MessageRaw_T = _Raw_T
|
||||
ClientRaw_T = _Raw_T
|
||||
PlayerRaw_T = _Raw_T
|
||||
SpectatorRaw_T = _Raw_T
|
||||
@@ -1,9 +1,11 @@
|
||||
from unittest import IsolatedAsyncioTestCase
|
||||
|
||||
from autobeerpong.messages.lobby.join import JoinMessage
|
||||
from autobeerpong.messages.lobby.join_response import JoinResponseMessage
|
||||
from autobeerpong.messages.lobby.rejoin import RejoinMessage
|
||||
from autobeerpong.messages.lobby.toggle_ready import ToggleReadyMessage
|
||||
from autobeerpong.messages.lobby.toggle_role import ToggleRoleMessage
|
||||
from autobeerpong.messages.lobby.state import LobbyStateMessage
|
||||
from autobeerpong.contexts.lobby import MAX_PLAYERS_IN_LOBBY
|
||||
from tests.utils.server import manage_server
|
||||
from tests.utils.client import TestClient
|
||||
@@ -27,26 +29,31 @@ class TestLobby(IsolatedAsyncioTestCase):
|
||||
self.assertEqual(len(client_b_responses), 2)
|
||||
|
||||
response = client_a_responses[0]
|
||||
self.assertEqual(response["messageType"], "joinResponse")
|
||||
self.assertEqual(response["messageContent"]["client"]["name"], "Ruedi")
|
||||
self.assertEqual(response.type, "joinResponse")
|
||||
assert type(response) is JoinResponseMessage
|
||||
self.assertEqual(response.client_raw["name"], "Ruedi")
|
||||
|
||||
response = client_b_responses[0]
|
||||
self.assertEqual(response["messageType"], "joinResponse")
|
||||
self.assertEqual(response["messageContent"]["client"]["name"], "Hansi")
|
||||
self.assertEqual(response.type, "joinResponse")
|
||||
assert type(response) is JoinResponseMessage
|
||||
self.assertEqual(response.client_raw["name"], "Hansi")
|
||||
|
||||
response = client_a_responses[1]
|
||||
self.assertEqual(response["messageType"], "lobbyState")
|
||||
self.assertEqual(len(response["messageContent"]["players"]), 1)
|
||||
self.assertEqual(response.type, "lobbyState")
|
||||
assert type(response) is LobbyStateMessage
|
||||
self.assertEqual(len(response.players), 1)
|
||||
|
||||
response = client_b_responses[1]
|
||||
self.assertEqual(response["messageType"], "lobbyState")
|
||||
self.assertEqual(len(response["messageContent"]["players"]), 2)
|
||||
self.assertEqual(response.type, "lobbyState")
|
||||
assert type(response) is LobbyStateMessage
|
||||
self.assertEqual(len(response.players), 2)
|
||||
|
||||
response = client_a_responses[2]
|
||||
self.assertEqual(response["messageType"], "lobbyState")
|
||||
self.assertEqual(len(response["messageContent"]["players"]), 2)
|
||||
self.assertEqual(response.type, "lobbyState")
|
||||
assert type(response) is LobbyStateMessage
|
||||
self.assertEqual(len(response.players), 2)
|
||||
|
||||
player_names = [p["client"]["name"] for p in response["messageContent"]["players"]]
|
||||
player_names = [p["client"]["name"] for p in response.players]
|
||||
|
||||
self.assertIn("Ruedi", player_names)
|
||||
self.assertIn("Hansi", player_names)
|
||||
@@ -88,8 +95,9 @@ class TestLobby(IsolatedAsyncioTestCase):
|
||||
client_a_responses.append(await client_a.get_response())
|
||||
|
||||
response = client_a_responses[3]
|
||||
self.assertEqual(response["messageType"], "lobbyState")
|
||||
players = response["messageContent"]["players"]
|
||||
self.assertEqual(response.type, "lobbyState")
|
||||
assert type(response) is LobbyStateMessage
|
||||
players = response.players
|
||||
|
||||
for player in players:
|
||||
if player["client"]["name"] == "Ruedi":
|
||||
@@ -97,11 +105,12 @@ class TestLobby(IsolatedAsyncioTestCase):
|
||||
elif player["client"]["name"] == "Hansi":
|
||||
self.assertEqual(player["ready"], False)
|
||||
|
||||
self.assertEqual(client_a_responses[3], client_b_responses[2])
|
||||
self.assertEqual(client_a_responses[3].to_raw(), client_b_responses[2].to_raw())
|
||||
|
||||
response = client_a_responses[4]
|
||||
self.assertEqual(response["messageType"], "lobbyState")
|
||||
players = response["messageContent"]["players"]
|
||||
self.assertEqual(response.type, "lobbyState")
|
||||
assert type(response) is LobbyStateMessage
|
||||
players = response.players
|
||||
|
||||
for player in players:
|
||||
if player["client"]["name"] == "Ruedi":
|
||||
@@ -109,7 +118,7 @@ class TestLobby(IsolatedAsyncioTestCase):
|
||||
elif player["client"]["name"] == "Hansi":
|
||||
self.assertEqual(player["ready"], True)
|
||||
|
||||
self.assertEqual(client_a_responses[4], client_b_responses[3])
|
||||
self.assertEqual(client_a_responses[4].to_raw(), client_b_responses[3].to_raw())
|
||||
|
||||
client_a.shutdown()
|
||||
client_b.shutdown()
|
||||
@@ -154,20 +163,23 @@ class TestLobby(IsolatedAsyncioTestCase):
|
||||
client_a_responses.append(await client_a.get_response())
|
||||
|
||||
response = client_a_responses[2]
|
||||
self.assertEqual(response["messageType"], "lobbyState")
|
||||
self.assertEqual(response, client_b_responses[1])
|
||||
self.assertEqual(len(response["messageContent"]["players"]), 2)
|
||||
self.assertEqual(response.type, "lobbyState")
|
||||
assert type(response) is LobbyStateMessage
|
||||
self.assertEqual(response.to_raw(), client_b_responses[1].to_raw())
|
||||
self.assertEqual(len(response.players), 2)
|
||||
|
||||
response = client_a_responses[3]
|
||||
self.assertEqual(response, client_b_responses[2])
|
||||
self.assertEqual(len(response["messageContent"]["players"]), 1)
|
||||
self.assertEqual(len(response["messageContent"]["spectators"]), 1)
|
||||
self.assertEqual(response["messageContent"]["spectators"][0]["name"], "Ruedi")
|
||||
assert type(response) is LobbyStateMessage
|
||||
self.assertEqual(response.to_raw(), client_b_responses[2].to_raw())
|
||||
self.assertEqual(len(response.players), 1)
|
||||
self.assertEqual(len(response.spectators), 1)
|
||||
self.assertEqual(response.spectators[0]["name"], "Ruedi")
|
||||
|
||||
response = client_a_responses[4]
|
||||
self.assertEqual(response, client_b_responses[3])
|
||||
self.assertEqual(len(response["messageContent"]["players"]), 0)
|
||||
self.assertEqual(len(response["messageContent"]["spectators"]), 2)
|
||||
assert type(response) is LobbyStateMessage
|
||||
self.assertEqual(response.to_raw(), client_b_responses[3].to_raw())
|
||||
self.assertEqual(len(response.players), 0)
|
||||
self.assertEqual(len(response.spectators), 2)
|
||||
|
||||
client_a.shutdown()
|
||||
client_b.shutdown()
|
||||
@@ -192,13 +204,12 @@ class TestLobby(IsolatedAsyncioTestCase):
|
||||
client_b_responses.append(await client_b.get_response())
|
||||
|
||||
response = client_a_responses[3]
|
||||
self.assertEqual(response["messageType"], "lobbyState")
|
||||
self.assertEqual(response, client_b_responses[2])
|
||||
self.assertEqual(response, client_c_responses[1])
|
||||
self.assertLessEqual(
|
||||
len(response["messageContent"]["players"]), MAX_PLAYERS_IN_LOBBY
|
||||
)
|
||||
self.assertEqual(response["messageContent"]["spectators"][0]["name"], "Fredi")
|
||||
self.assertEqual(response.type, "lobbyState")
|
||||
assert type(response) is LobbyStateMessage
|
||||
self.assertEqual(response.to_raw(), client_b_responses[2].to_raw())
|
||||
self.assertEqual(response.to_raw(), client_c_responses[1].to_raw())
|
||||
self.assertLessEqual(len(response.players), MAX_PLAYERS_IN_LOBBY)
|
||||
self.assertEqual(response.spectators[0]["name"], "Fredi")
|
||||
|
||||
client_c_responses.extend(
|
||||
await client_c.send_messages(
|
||||
@@ -209,14 +220,13 @@ class TestLobby(IsolatedAsyncioTestCase):
|
||||
client_b_responses.append(await client_b.get_response())
|
||||
|
||||
response = client_a_responses[-1]
|
||||
self.assertEqual(response["messageType"], "lobbyState")
|
||||
self.assertEqual(response, client_b_responses[-1])
|
||||
self.assertEqual(response, client_c_responses[-1])
|
||||
self.assertEqual(response.type, "lobbyState")
|
||||
assert type(response) is LobbyStateMessage
|
||||
self.assertEqual(response.to_raw(), client_b_responses[-1].to_raw())
|
||||
self.assertEqual(response.to_raw(), client_c_responses[-1].to_raw())
|
||||
|
||||
self.assertLessEqual(
|
||||
len(response["messageContent"]["players"]), MAX_PLAYERS_IN_LOBBY
|
||||
)
|
||||
self.assertEqual(response["messageContent"]["spectators"][0]["name"], "Fredi")
|
||||
self.assertLessEqual(len(response.players), MAX_PLAYERS_IN_LOBBY)
|
||||
self.assertEqual(response.spectators[0]["name"], "Fredi")
|
||||
|
||||
client_a.shutdown()
|
||||
client_b.shutdown()
|
||||
@@ -235,7 +245,9 @@ class TestLobby(IsolatedAsyncioTestCase):
|
||||
)
|
||||
client_a_responses.append(await client_a.get_response())
|
||||
|
||||
client_b_id = client_b_responses[0]["messageContent"]["client"]["id"]
|
||||
response = client_b_responses[0]
|
||||
assert type(response) is JoinResponseMessage
|
||||
client_b_id = response.client_raw["id"]
|
||||
client_b.shutdown()
|
||||
|
||||
client_a_responses.append(await client_a.get_response())
|
||||
@@ -261,14 +273,11 @@ class TestLobby(IsolatedAsyncioTestCase):
|
||||
)
|
||||
client_a_responses.append(await client_a.get_response())
|
||||
|
||||
self.assertEqual(client_a_responses[-1], client_b_responses[-1])
|
||||
|
||||
self.assertEqual(
|
||||
client_a_responses[-1]["messageContent"]["players"][0]["ready"], False
|
||||
)
|
||||
self.assertEqual(
|
||||
client_a_responses[-1]["messageContent"]["players"][1]["ready"], True
|
||||
)
|
||||
response = client_a_responses[-1]
|
||||
assert type(response) is LobbyStateMessage
|
||||
self.assertEqual(response.to_raw(), client_b_responses[-1].to_raw())
|
||||
self.assertEqual(response.players[0]["ready"], False)
|
||||
self.assertEqual(response.players[1]["ready"], True)
|
||||
|
||||
client_a_responses.extend(
|
||||
await client_a.send_messages(
|
||||
@@ -281,14 +290,12 @@ class TestLobby(IsolatedAsyncioTestCase):
|
||||
)
|
||||
client_b_responses.append(await client_b.get_response())
|
||||
|
||||
self.assertEqual(client_a_responses[-1], client_b_responses[-1])
|
||||
response = client_a_responses[-1]
|
||||
assert type(response) is LobbyStateMessage
|
||||
self.assertEqual(response.to_raw(), client_b_responses[-1].to_raw())
|
||||
|
||||
self.assertEqual(
|
||||
client_a_responses[-1]["messageContent"]["players"][0]["ready"], True
|
||||
)
|
||||
self.assertEqual(
|
||||
client_a_responses[-1]["messageContent"]["players"][1]["ready"], True
|
||||
)
|
||||
self.assertEqual(response.players[0]["ready"], True)
|
||||
self.assertEqual(response.players[1]["ready"], True)
|
||||
|
||||
client_a.shutdown()
|
||||
client_b.shutdown()
|
||||
@@ -0,0 +1,59 @@
|
||||
from unittest import IsolatedAsyncioTestCase
|
||||
|
||||
from autobeerpong.messages.message import Message
|
||||
from autobeerpong.messages.lobby.join import JoinMessage
|
||||
from autobeerpong.messages.lobby.toggle_ready import ToggleReadyMessage
|
||||
from tests.utils.server import manage_server
|
||||
from tests.utils.client import TestClient
|
||||
from tests.utils.manager import TestClientManager
|
||||
|
||||
|
||||
def get_two_players_join_and_ready(
|
||||
client_a: TestClient, client_b: TestClient
|
||||
) -> list[tuple[TestClient, Message]]:
|
||||
return [
|
||||
(
|
||||
client_a,
|
||||
JoinMessage({"messageType": "join", "messageContent": {"name": "Ruedi"}}),
|
||||
),
|
||||
(
|
||||
client_b,
|
||||
JoinMessage({"messageType": "join", "messageContent": {"name": "Ueli"}}),
|
||||
),
|
||||
(
|
||||
client_a,
|
||||
ToggleReadyMessage({"messageType": "toggleReady", "messageContent": {}}),
|
||||
),
|
||||
(
|
||||
client_b,
|
||||
ToggleReadyMessage({"messageType": "toggleReady", "messageContent": {}}),
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
class TestMatch(IsolatedAsyncioTestCase):
|
||||
@manage_server
|
||||
async def test_match(self) -> None:
|
||||
client_a = TestClient()
|
||||
client_b = TestClient()
|
||||
|
||||
client_manager = TestClientManager()
|
||||
client_manager.register_test_client(client_a)
|
||||
client_manager.register_test_client(client_b)
|
||||
|
||||
await client_manager.send_messages(
|
||||
get_two_players_join_and_ready(client_a, client_b)
|
||||
)
|
||||
|
||||
await client_manager.collect_broadcast_messages()
|
||||
|
||||
self.assertEqual(client_manager.response_map[client_a][-1].type, "startMatch")
|
||||
self.assertEqual(client_manager.response_map[client_b][-1].type, "startMatch")
|
||||
|
||||
await client_manager.collect_broadcast_messages()
|
||||
|
||||
self.assertEqual(client_manager.response_map[client_a][-1].type, "matchState")
|
||||
self.assertEqual(client_manager.response_map[client_b][-1].type, "matchState")
|
||||
|
||||
client_a.shutdown()
|
||||
client_b.shutdown()
|
||||
@@ -1,11 +1,11 @@
|
||||
import json
|
||||
import asyncio
|
||||
from typing import Any
|
||||
|
||||
from websockets.asyncio.client import connect
|
||||
|
||||
import autobeerpong.config as config
|
||||
from autobeerpong.messages.message import MessageRaw_T, Message
|
||||
from autobeerpong.server import AutobeerpongServer
|
||||
from tests.utils.task import ClientTask, SendMessageToServer, GetResponseFromServer
|
||||
from tests.utils.server import SERVER_RESPONSE_TIMEOUT
|
||||
|
||||
@@ -13,7 +13,7 @@ from tests.utils.server import SERVER_RESPONSE_TIMEOUT
|
||||
class TestClient:
|
||||
def __init__(self) -> None:
|
||||
self.queue_send: asyncio.Queue[ClientTask] = asyncio.Queue()
|
||||
self.queue_recv: asyncio.Queue[MessageRaw_T] = asyncio.Queue()
|
||||
self.queue_recv: asyncio.Queue[Message] = asyncio.Queue()
|
||||
self._task = asyncio.create_task(self._client_task())
|
||||
|
||||
async def _client_task(self) -> None:
|
||||
@@ -30,7 +30,18 @@ class TestClient:
|
||||
response_raw = await asyncio.wait_for(
|
||||
websocket.recv(), timeout=SERVER_RESPONSE_TIMEOUT
|
||||
)
|
||||
await self.queue_recv.put(json.loads(response_raw))
|
||||
|
||||
message_raw: MessageRaw_T = json.loads(response_raw)
|
||||
|
||||
assert (
|
||||
message_raw["messageType"] in AutobeerpongServer.message_map
|
||||
), f"Message type {message_raw['messageType']} not in message map!"
|
||||
|
||||
MessageClass = AutobeerpongServer.message_map[
|
||||
message_raw["messageType"]
|
||||
]
|
||||
|
||||
await self.queue_recv.put(MessageClass(message_raw))
|
||||
|
||||
else:
|
||||
raise Exception(
|
||||
@@ -39,23 +50,23 @@ class TestClient:
|
||||
|
||||
self.queue_send.task_done()
|
||||
|
||||
async def send_message(self, message: Message):
|
||||
async def send_message(self, message: Message) -> None:
|
||||
await self.queue_send.put(SendMessageToServer(message))
|
||||
|
||||
async def get_response(self) -> dict[str, Any]:
|
||||
async def get_response(self) -> Message:
|
||||
await self.queue_send.put(GetResponseFromServer())
|
||||
|
||||
response_raw = await asyncio.wait_for(
|
||||
response = await asyncio.wait_for(
|
||||
self.queue_recv.get(),
|
||||
timeout=SERVER_RESPONSE_TIMEOUT,
|
||||
)
|
||||
|
||||
self.queue_recv.task_done()
|
||||
|
||||
return response_raw
|
||||
return response
|
||||
|
||||
async def send_messages(self, messages: list[Message]) -> list[MessageRaw_T]:
|
||||
responses: list[MessageRaw_T] = []
|
||||
async def send_messages(self, messages: list[Message]) -> list[Message]:
|
||||
responses: list[Message] = []
|
||||
|
||||
for message in messages:
|
||||
await self.send_message(message)
|
||||
@@ -70,7 +81,7 @@ class TestClient:
|
||||
|
||||
return responses
|
||||
|
||||
def shutdown(self):
|
||||
def shutdown(self) -> None:
|
||||
self.queue_send.shutdown()
|
||||
self.queue_recv.shutdown()
|
||||
self._task.cancel()
|
||||
@@ -0,0 +1,42 @@
|
||||
from tests.utils.client import TestClient
|
||||
|
||||
from autobeerpong.messages.message import Message
|
||||
|
||||
|
||||
class TestClientManager:
|
||||
def __init__(self) -> None:
|
||||
self.response_map: dict[TestClient, list[Message]] = {}
|
||||
self.joined_map: dict[TestClient, bool] = {}
|
||||
|
||||
def register_test_client(
|
||||
self,
|
||||
test_client: TestClient,
|
||||
):
|
||||
self.response_map[test_client]: list[Message] = []
|
||||
self.joined_map[test_client] = False
|
||||
|
||||
async def collect_broadcast_messages(self) -> None:
|
||||
for broadcast_client in self.response_map:
|
||||
if not self.joined_map[broadcast_client]:
|
||||
continue
|
||||
|
||||
response = await broadcast_client.get_response()
|
||||
self.response_map[broadcast_client].append(response)
|
||||
|
||||
async def send_messages(
|
||||
self, client_messages: list[tuple[TestClient, Message]]
|
||||
) -> None:
|
||||
for client, message in client_messages:
|
||||
assert client in self.response_map
|
||||
|
||||
await client.send_message(message)
|
||||
|
||||
if message.has_direct_response:
|
||||
response = await client.get_response()
|
||||
self.response_map[client].append(response)
|
||||
|
||||
if response.type == "joinResponse":
|
||||
self.joined_map[client] = True
|
||||
|
||||
# collect broadcast responses
|
||||
await self.collect_broadcast_messages()
|
||||
@@ -119,7 +119,7 @@ export class MatchScene extends BaseScene {
|
||||
(resolve) => (resolver = resolve),
|
||||
);
|
||||
|
||||
for (const actionOrTable of state.matchStateRaw.history) {
|
||||
for (const actionOrTable of state.matchStateRaw.messageContent.history) {
|
||||
if ("cupsA" in actionOrTable) {
|
||||
this._updateFromTableState(actionOrTable);
|
||||
await this._matchClock.startAndWait(2000);
|
||||
|
||||
@@ -14,9 +14,10 @@ import lobbyStateSchemaFile from "../../schema/lobby/state.json";
|
||||
import toggleReadySchemaFile from "../../schema/lobby/toggle_ready.json";
|
||||
import toggleRoleSchemaFile from "../../schema/lobby/toggle_role.json";
|
||||
|
||||
// import matchStateSchemaFile from "../../schema//match/state.json";
|
||||
// import actionSchemaFile from "../../schema/match/action.json";
|
||||
// import tableSchemaFile from "../../schema/match/table_schema.json";
|
||||
import startMatchSchemaFile from "../../schema/match/start_match.json";
|
||||
import matchStateSchemaFile from "../../schema/match/state.json";
|
||||
import actionSchemaFile from "../../schema/match/action.json";
|
||||
import tableSchemaFile from "../../schema/match/table.json";
|
||||
|
||||
const ajv = new Ajv({ strict: true });
|
||||
|
||||
@@ -26,11 +27,14 @@ ajv.addSchema(playerSchemaFile, "player.json");
|
||||
ajv.addSchema(joinSchemaFile, "join.json");
|
||||
ajv.addSchema(joinResponseSchemaFile, "join_response.json");
|
||||
ajv.addSchema(rejoinSchemaFile, "rejoin.json");
|
||||
ajv.addSchema(lobbyStateSchemaFile, "state.json");
|
||||
ajv.addSchema(lobbyStateSchemaFile, "lobby_state.json");
|
||||
ajv.addSchema(toggleReadySchemaFile, "toggle_ready.json");
|
||||
ajv.addSchema(toggleRoleSchemaFile, "toggle_role.json");
|
||||
|
||||
// TODO: Match schemas
|
||||
ajv.addSchema(startMatchSchemaFile, "start_match.json");
|
||||
ajv.addSchema(matchStateSchemaFile, "match_state.json");
|
||||
ajv.addSchema(actionSchemaFile, "action.json");
|
||||
ajv.addSchema(tableSchemaFile, "table.json");
|
||||
|
||||
const validateMessage = ajv.compile(messageSchemaFile);
|
||||
const validateClient = ajv.compile(clientSchemaFile);
|
||||
|
||||
@@ -1,29 +0,0 @@
|
||||
{
|
||||
"title": "MatchState",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"stateType": {
|
||||
"enum": [
|
||||
"match"
|
||||
]
|
||||
},
|
||||
"history": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"anyOf": [
|
||||
{
|
||||
"$ref": "./table_schema.json"
|
||||
},
|
||||
{
|
||||
"$ref": "./action_schema.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"stateType",
|
||||
"history"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
{
|
||||
"title": "Action",
|
||||
"$id": "http://localhost/match/action.json",
|
||||
"type": "object",
|
||||
"title": "Action",
|
||||
"properties": {
|
||||
"parabola": {
|
||||
"$ref": "#/$defs/parabola"
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"$id": "http://localhost/match/start_match.json",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"messageType": {
|
||||
"const": "startMatch"
|
||||
},
|
||||
"messageContent": {
|
||||
"type": "object",
|
||||
"properties": {},
|
||||
"required": [],
|
||||
"additionalProperties": false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
{
|
||||
"$id": "http://localhost/match/state.json",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"messageType": {
|
||||
"const": "matchState"
|
||||
},
|
||||
"messageContent": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"history": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"anyOf": [
|
||||
{
|
||||
"$ref": "./table.json"
|
||||
},
|
||||
{
|
||||
"$ref": "./action.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"history"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
{
|
||||
"title": "Table",
|
||||
"$id": "http://localhost/match/table.json",
|
||||
"type": "object",
|
||||
"title": "Table",
|
||||
"properties": {
|
||||
"cupsA": {
|
||||
"$ref": "#/$defs/cups"
|
||||
@@ -29,6 +29,12 @@
|
||||
},
|
||||
{
|
||||
"$ref": "./lobby/toggle_role.json"
|
||||
},
|
||||
{
|
||||
"$ref": "./match/start_match.json"
|
||||
},
|
||||
{
|
||||
"$ref": "./match/state.json"
|
||||
}
|
||||
],
|
||||
"required": [
|
||||
|
||||
Reference in new issue
Block a user