add more unit tests (#28)

* add test method for toggle role action

* add max player detection in lobby during join

* add test method for max players check

* remove unused player module

* add missing client shutdown statements

* add process rejoin action method

* move client id logic to server class

* add test method for rejoin action

* extend test rejoin action method

* add comment to hacky solution
This commit is contained in:
Denis authored and GitHub committed 2026-02-02 20:59:57 +01:00
1 parent 01211f6243
commit 523d933ffd
4 files changed
+219 -83

No files matched your search

+38 -20
View File
@@ -2,32 +2,56 @@ from typing import Any, Callable
from websockets.asyncio.server import ServerConnection from websockets.asyncio.server import ServerConnection
from autobeerpong.client import Client, ClientRole from autobeerpong.client import Client, ClientRole
from autobeerpong.action import JoinAction from autobeerpong.action import JoinAction, RejoinAction
MAX_PLAYERS_IN_LOBBY = 2
class AutobeerpongLobby: class AutobeerpongLobby:
MAX_PLAYERS = 2 MAX_PLAYERS = MAX_PLAYERS_IN_LOBBY
def __init__(self): def __init__(self):
self.clients: dict[int, Client] = {} self.clients: dict[int, Client] = {}
async def broadcast(self) -> None: async def broadcast(self) -> None:
for client in self.clients.values(): for client in filter(
lambda c: c.role is not ClientRole.DISCONNECTED, self.clients.values()
):
await client.send(self.as_dict()) await client.send(self.as_dict())
async def process_join( async def process_join(
self, websocket: ServerConnection, action: JoinAction self, client_id: int, websocket: ServerConnection, action: JoinAction
) -> None: ) -> None:
client = Client(websocket.id.int, websocket, action.name) client = Client(client_id=client_id, websocket=websocket, name=action.name)
if self.is_players_full():
client.role = ClientRole.SPECTATOR
self.add_client(client) self.add_client(client)
await client.send({"player": client.as_dict()}) await client.send({"player": client.as_dict()})
async def process_rejoin(
self, websocket: ServerConnection, action: RejoinAction
) -> None:
client = self.clients.get(action.client_id)
if client is None:
print(f"No client found for id {action.client_id}")
return
if self.is_players_full():
client.role = ClientRole.SPECTATOR
else:
client.role = ClientRole.PLAYER
client.websocket = websocket
await client.send({"player": client.as_dict()})
async def process_toggle_role(self, client: Client) -> None: async def process_toggle_role(self, client: Client) -> None:
if ( if client.role is ClientRole.SPECTATOR and not self.is_players_full():
client.role is ClientRole.SPECTATOR
and self.get_num_players() < self.MAX_PLAYERS
):
client.role = ClientRole.PLAYER client.role = ClientRole.PLAYER
elif client.role is ClientRole.PLAYER: elif client.role is ClientRole.PLAYER:
client.role = ClientRole.SPECTATOR client.role = ClientRole.SPECTATOR
@@ -36,17 +60,10 @@ class AutobeerpongLobby:
if client.role is ClientRole.PLAYER: if client.role is ClientRole.PLAYER:
client.ready = not client.ready client.ready = not client.ready
async def process( async def process(self, client_id: int, action_dict: dict[str, Any]) -> None:
self, websocket: ServerConnection, action_dict: dict[str, Any]
) -> None:
action_name = action_dict["action"] action_name = action_dict["action"]
if action_name == "join": client = self.clients.get(client_id)
await self.process_join(websocket, JoinAction(name=action_dict["name"]))
elif action_name == "rejoin":
pass
else:
client = self.clients.get(websocket.id.int)
if client is None: if client is None:
raise Exception("Client has not joined.") raise Exception("Client has not joined.")
@@ -56,8 +73,6 @@ class AutobeerpongLobby:
elif action_name == "toggleReady": elif action_name == "toggleReady":
await self.process_toggle_ready(client) await self.process_toggle_ready(client)
await self.broadcast()
def add_client(self, client: Client): def add_client(self, client: Client):
self.clients[client.id] = client self.clients[client.id] = client
@@ -73,6 +88,9 @@ class AutobeerpongLobby:
def get_spectators(self) -> list[Client]: def get_spectators(self) -> list[Client]:
return self.filter_clients(lambda x: x.role is ClientRole.SPECTATOR) return self.filter_clients(lambda x: x.role is ClientRole.SPECTATOR)
def is_players_full(self) -> bool:
return self.get_num_players() >= self.MAX_PLAYERS
def as_dict(self) -> dict[str, Any]: def as_dict(self) -> dict[str, Any]:
players = self.get_players() players = self.get_players()
spectators = self.get_spectators() spectators = self.get_spectators()
-58
View File
@@ -1,58 +0,0 @@
from __future__ import annotations
import json
from typing import Any
from websockets.asyncio.server import ServerConnection
T_PlayerDict = dict[str, str | int]
class Player:
def __init__(
self,
websocket: ServerConnection | None,
player_id: int,
name: str,
is_spectator: bool,
is_ready: bool = False,
) -> None:
self.id = player_id
self.name = name
self.websocket: ServerConnection | None = websocket
self.is_spectator = is_spectator
self.is_ready = is_ready
self.is_disconnected = False
def disconnect(self) -> None:
self.is_disconnected = True
self.is_spectator = True
self.is_ready = False
self.websocket = None
def reconnect(self, websocket: ServerConnection) -> None:
self.is_disconnected = False
self.websocket = websocket
async def send_message(self, message) -> None:
if not self.is_disconnected and self.websocket is not None:
await self.websocket.send(json.dumps(message))
def as_dict(self) -> T_PlayerDict:
return {"id": self.id, "name": self.name}
@classmethod
def from_dict(
cls, player_dict: dict[str, Any], is_ready: bool, is_spectator: bool
) -> Player:
player_id: int = player_dict["id"]
name: str = player_dict["name"]
return Player(
websocket=None,
player_id=player_id,
name=name,
is_spectator=is_spectator,
is_ready=is_ready,
)
+40 -3
View File
@@ -1,8 +1,10 @@
import websockets
from autobeerpong.action import JoinAction, RejoinAction
import json import json
import asyncio import asyncio
from enum import Enum, auto from enum import Enum, auto
from itertools import count
from websockets.asyncio.server import serve, ServerConnection from websockets.asyncio.server import serve, ServerConnection
from autobeerpong.lobby import AutobeerpongLobby from autobeerpong.lobby import AutobeerpongLobby
@@ -15,16 +17,40 @@ class ServerState(Enum):
class AutobeerpongServer: class AutobeerpongServer:
def __init__(self) -> None: def __init__(self) -> None:
self.client_ids = count()
self.server_state = ServerState.LOBBY self.server_state = ServerState.LOBBY
self.lobby = AutobeerpongLobby() self.lobby = AutobeerpongLobby()
async def handler(self, websocket: ServerConnection): async def handler(self, websocket: ServerConnection):
client_id = None
try: try:
async for msg in websocket: async for msg in websocket:
action_dict = json.loads(msg) action_dict = json.loads(msg)
if self.server_state is ServerState.LOBBY: if self.server_state is ServerState.LOBBY:
await self.lobby.process(websocket, action_dict) action_name = action_dict["action"]
if action_name == "join":
client_id = next(self.client_ids)
await self.lobby.process_join(
client_id=client_id,
websocket=websocket,
action=JoinAction(action_dict["name"]),
)
elif action_name == "rejoin":
client_id = action_dict["client_id"]
await self.lobby.process_rejoin(
websocket=websocket, action=RejoinAction(client_id)
)
else:
if client_id is not None:
await self.lobby.process(client_id, action_dict)
await self.lobby.broadcast()
elif self.server_state is ServerState.MATCH: elif self.server_state is ServerState.MATCH:
pass pass
@@ -32,13 +58,24 @@ class AutobeerpongServer:
print(str(exception)) print(str(exception))
await websocket.close(1011) await websocket.close(1011)
else: else:
client = self.lobby.clients.get(websocket.id.int) if client_id is not None:
client = self.lobby.clients.get(client_id)
if client is not None: if client is not None:
client.disconnect() client.disconnect()
await websocket.close(1000) await websocket.close(1000)
if self.server_state is ServerState.LOBBY:
# Hacky solution to keep test cases from failing gracefully
# at the end of the tests, when all clients disconnect.
try:
await self.lobby.broadcast()
except websockets.exceptions.ConnectionClosedOK:
pass
except Exception as exception:
raise (exception)
async def _start(self) -> None: async def _start(self) -> None:
async with serve(self.handler, "localhost", 8888) as server: async with serve(self.handler, "localhost", 8888) as server:
await server.serve_forever() await server.serve_forever()
+141 -2
View File
@@ -5,7 +5,14 @@ from typing import Any
from unittest import IsolatedAsyncioTestCase from unittest import IsolatedAsyncioTestCase
from websockets.asyncio.client import connect from websockets.asyncio.client import connect
from autobeerpong.action import Action, JoinAction, ToggleReadyAction, ToggleRoleAction from autobeerpong.action import (
Action,
JoinAction,
RejoinAction,
ToggleReadyAction,
ToggleRoleAction,
)
from autobeerpong.lobby import MAX_PLAYERS_IN_LOBBY
from tests.utils.server import manage_server, SERVER_ADDRESS, SERVER_PORT from tests.utils.server import manage_server, SERVER_ADDRESS, SERVER_PORT
@@ -57,7 +64,12 @@ class TestClient:
async def get_response(self) -> dict[str, Any]: async def get_response(self) -> dict[str, Any]:
await self.queue_send.put(GetResponseFromServer()) await self.queue_send.put(GetResponseFromServer())
response_raw = await self.queue_recv.get()
response_raw = await asyncio.wait_for(
self.queue_recv.get(),
timeout=SERVER_RESPONSE_TIMEOUT,
)
self.queue_recv.task_done() self.queue_recv.task_done()
return response_raw return response_raw
@@ -157,3 +169,130 @@ class TestLobby(IsolatedAsyncioTestCase):
client_a.shutdown() client_a.shutdown()
client_b.shutdown() client_b.shutdown()
@manage_server
async def test_toggle_role(self):
client_a = TestClient()
client_b = TestClient()
client_a_responses = await client_a.send_actions([JoinAction("Ruedi")])
client_b_responses = await client_b.send_actions([JoinAction("Hansi")])
client_a_responses.append(await client_a.get_response())
client_a_responses.extend(await client_a.send_actions([ToggleRoleAction()]))
client_b_responses.append(await client_b.get_response())
client_b_responses.extend(await client_b.send_actions([ToggleRoleAction()]))
client_a_responses.append(await client_a.get_response())
response = client_a_responses[2]
self.assertEqual(response, client_b_responses[1])
self.assertEqual(len(response["gamestate"]["players"]), 2)
response = client_a_responses[3]
self.assertEqual(response, client_b_responses[2])
self.assertEqual(len(response["gamestate"]["players"]), 1)
self.assertEqual(len(response["gamestate"]["spectators"]), 1)
self.assertEqual(
response["gamestate"]["spectators"][0]["player"]["name"], "Ruedi"
)
response = client_a_responses[4]
self.assertEqual(response, client_b_responses[3])
self.assertEqual(len(response["gamestate"]["players"]), 0)
self.assertEqual(len(response["gamestate"]["spectators"]), 2)
client_a.shutdown()
client_b.shutdown()
@manage_server
async def test_toggle_role_max_players(self):
client_a = TestClient()
client_b = TestClient()
client_c = TestClient()
client_a_responses = await client_a.send_actions([JoinAction("Ruedi")])
client_b_responses = await client_b.send_actions([JoinAction("Hansi")])
client_a_responses.append(await client_a.get_response())
client_c_responses = await client_c.send_actions([JoinAction("Fredi")])
client_a_responses.append(await client_a.get_response())
client_b_responses.append(await client_b.get_response())
response = client_a_responses[3]
self.assertEqual(response, client_b_responses[2])
self.assertEqual(response, client_c_responses[1])
self.assertLessEqual(
len(response["gamestate"]["players"]), MAX_PLAYERS_IN_LOBBY
)
self.assertEqual(
response["gamestate"]["spectators"][0]["player"]["name"], "Fredi"
)
client_c_responses.extend(await client_c.send_actions([ToggleRoleAction()]))
client_a_responses.append(await client_a.get_response())
client_b_responses.append(await client_b.get_response())
response = client_a_responses[-1]
self.assertEqual(response, client_b_responses[-1])
self.assertEqual(response, client_c_responses[-1])
self.assertLessEqual(
len(response["gamestate"]["players"]), MAX_PLAYERS_IN_LOBBY
)
self.assertEqual(
response["gamestate"]["spectators"][0]["player"]["name"], "Fredi"
)
client_a.shutdown()
client_b.shutdown()
client_c.shutdown()
@manage_server
async def test_rejoin(self):
client_a = TestClient()
client_b = TestClient()
client_a_responses = await client_a.send_actions([JoinAction("Ruedi")])
client_b_responses = await client_b.send_actions([JoinAction("Hansi")])
client_a_responses.append(await client_a.get_response())
client_b_id = client_b_responses[0]["player"]["id"]
client_b.shutdown()
client_a_responses.append(await client_a.get_response())
client_b = TestClient()
client_b_responses = await client_b.send_actions(
[RejoinAction(client_id=client_b_id)]
)
client_a_responses.append(await client_a.get_response())
client_b_responses.extend(await client_b.send_actions([ToggleReadyAction()]))
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]["gamestate"]["players"][0]["ready"], False
)
self.assertEqual(
client_a_responses[-1]["gamestate"]["players"][1]["ready"], True
)
client_a_responses.extend(await client_a.send_actions([ToggleReadyAction()]))
client_b_responses.append(await client_b.get_response())
self.assertEqual(client_a_responses[-1], client_b_responses[-1])
self.assertEqual(
client_a_responses[-1]["gamestate"]["players"][0]["ready"], True
)
self.assertEqual(
client_a_responses[-1]["gamestate"]["players"][1]["ready"], True
)
client_a.shutdown()
client_b.shutdown()