Backend - Add jsonschema module (#32)
* add jsonschema module * remove unused files * small refactoring * remove hardcoded host and port arguments * remove hardcoded host and server arguments * add direct response flag and to raw methods * fix config lookup * fix is players full method * use config singleton for server host and port arguments * add join message schema * move testclient module * move client tast module * add python typehint module * rename as_dict method to as_raw * delete message_raw file * add client state module * add more type modules * update json schemas * add support for json schema validation * add ready property to client * add client getter and adder methods * add repr dunder method * fix client context not being updated with new client id * add support for toggle ready message * only toggle ready if client is player * add toggle role message * add rejoin message * remove old files * fix import * remove unused import * update unit tests to work with new message classes * make schema dir not user configurable * add config template * rename client id getter method * make client id none-ed
This commit is contained in:
1 parent
4069f3df3b
commit
b63f2da22c
54 files changed
+869
-544
No files matched your search
@@ -1,3 +1,4 @@
|
||||
.venv
|
||||
__pycache__/
|
||||
upgrade_toolchain.sh
|
||||
config.toml
|
||||
@@ -1,47 +0,0 @@
|
||||
from typing import Any
|
||||
|
||||
|
||||
ActionDict_T = dict[str, Any]
|
||||
|
||||
|
||||
class Action:
|
||||
def __init__(self, action: str, has_direct_response: bool) -> None:
|
||||
self.action = action
|
||||
self.has_direct_response = has_direct_response
|
||||
|
||||
def as_dict(self) -> ActionDict_T:
|
||||
return {"action": self.action}
|
||||
|
||||
|
||||
class JoinAction(Action):
|
||||
def __init__(self, name: str) -> None:
|
||||
super().__init__(action="join", has_direct_response=True)
|
||||
self.name = name
|
||||
|
||||
def as_dict(self) -> ActionDict_T:
|
||||
adict = super().as_dict()
|
||||
adict.update(name=self.name)
|
||||
|
||||
return adict
|
||||
|
||||
|
||||
class RejoinAction(Action):
|
||||
def __init__(self, client_id: int) -> None:
|
||||
super().__init__(action="rejoin", has_direct_response=True)
|
||||
self.client_id = client_id
|
||||
|
||||
def as_dict(self) -> ActionDict_T:
|
||||
adict = super().as_dict()
|
||||
adict.update(client_id=self.client_id)
|
||||
|
||||
return adict
|
||||
|
||||
|
||||
class ToggleRoleAction(Action):
|
||||
def __init__(self) -> None:
|
||||
super().__init__(action="toggleRole", has_direct_response=False)
|
||||
|
||||
|
||||
class ToggleReadyAction(Action):
|
||||
def __init__(self) -> None:
|
||||
super().__init__(action="toggleReady", has_direct_response=False)
|
||||
@@ -1,9 +0,0 @@
|
||||
from typing import Any
|
||||
from action import JoinAction
|
||||
|
||||
|
||||
def produce_action(raw_action: dict[Any]) -> JoinAction:
|
||||
if raw_action["action"] == "join":
|
||||
return JoinAction(raw_action["name"])
|
||||
else:
|
||||
raise Exception(f"Unknown action: {raw_action['action']}")
|
||||
@@ -1,26 +0,0 @@
|
||||
import asyncio
|
||||
import socket
|
||||
|
||||
|
||||
async def handle(reader, writer):
|
||||
addr = writer.get_extra_info("peername")
|
||||
print("Connected by", addr)
|
||||
try:
|
||||
while True:
|
||||
data = await reader.read(1024)
|
||||
if not data:
|
||||
break
|
||||
writer.write(data)
|
||||
await writer.drain()
|
||||
finally:
|
||||
writer.close()
|
||||
await writer.wait_closed()
|
||||
|
||||
|
||||
async def main():
|
||||
server = await asyncio.start_server(handle, "0.0.0.0", 15555)
|
||||
async with server:
|
||||
await server.serve_forever()
|
||||
|
||||
|
||||
asyncio.run(main())
|
||||
@@ -1,15 +1,9 @@
|
||||
import json
|
||||
|
||||
from enum import Enum, auto
|
||||
from websockets.asyncio.server import ServerConnection
|
||||
|
||||
from autobeerpong.action import ActionDict_T
|
||||
|
||||
|
||||
class ClientRole(Enum):
|
||||
PLAYER = auto()
|
||||
SPECTATOR = auto()
|
||||
DISCONNECTED = auto()
|
||||
from autobeerpong.types.raw import MessageRaw_T, ClientRaw_T
|
||||
from autobeerpong.states.client import ClientState
|
||||
|
||||
|
||||
class Client:
|
||||
@@ -17,19 +11,23 @@ class Client:
|
||||
self.id = client_id
|
||||
self.websocket = websocket
|
||||
self.name = name
|
||||
self.role = ClientRole.PLAYER
|
||||
self.state = ClientState.PLAYER
|
||||
self.ready = False
|
||||
|
||||
def as_dict(self) -> dict[str, int | str]:
|
||||
def __repr__(self) -> str:
|
||||
return f"Client({self.id}, {self.name}, {self.state.name}, {self.ready})"
|
||||
|
||||
def as_raw(self) -> ClientRaw_T:
|
||||
return {
|
||||
"id": self.id,
|
||||
"name": self.name,
|
||||
"ready": self.ready,
|
||||
}
|
||||
|
||||
def disconnect(self):
|
||||
self.role = ClientRole.DISCONNECTED
|
||||
self.state = ClientState.DISCONNECTED
|
||||
self.websocket = None
|
||||
|
||||
async def send(self, msg_dict: ActionDict_T) -> None:
|
||||
if self.websocket is not None:
|
||||
async def send(self, msg_dict: MessageRaw_T) -> None:
|
||||
assert self.websocket is not None
|
||||
await self.websocket.send(json.dumps(msg_dict))
|
||||
@@ -0,0 +1,12 @@
|
||||
import tomllib
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
CONFIG_FILE = Path(f"{Path(__file__).parent.parent}") / "config.toml"
|
||||
|
||||
with open(CONFIG_FILE, "rb") as fp:
|
||||
config_raw = tomllib.load(fp)
|
||||
|
||||
SCHEMA_DIR = Path(__file__).parent.parent.parent / "schema"
|
||||
SERVER_PORT = int(config_raw["server_port"])
|
||||
SERVER_HOST = str(config_raw["server_host"])
|
||||
Whitespace-only changes.
@@ -0,0 +1,13 @@
|
||||
from websockets.asyncio.server import ServerConnection
|
||||
|
||||
|
||||
class ClientContext:
|
||||
def __init__(self, websocket: ServerConnection) -> None:
|
||||
self.websocket = websocket
|
||||
|
||||
self.has_joined = False
|
||||
self.client_id = None
|
||||
|
||||
def get_client_id(self) -> int:
|
||||
assert self.client_id is not None
|
||||
return self.client_id
|
||||
@@ -0,0 +1,23 @@
|
||||
from autobeerpong.states.client import ClientState
|
||||
from autobeerpong.types.client_map import ClientMap_T
|
||||
|
||||
MAX_PLAYERS_IN_LOBBY = 2
|
||||
|
||||
|
||||
class LobbyContext:
|
||||
MAX_PLAYERS = MAX_PLAYERS_IN_LOBBY
|
||||
|
||||
def __init__(self, clients: ClientMap_T) -> None:
|
||||
self._clients = clients
|
||||
|
||||
def is_players_full(self) -> bool:
|
||||
return (
|
||||
len(
|
||||
list(
|
||||
filter(
|
||||
lambda x: x.state is ClientState.PLAYER, self._clients.values()
|
||||
)
|
||||
)
|
||||
)
|
||||
== self.MAX_PLAYERS
|
||||
)
|
||||
@@ -0,0 +1,2 @@
|
||||
class MatchContext:
|
||||
pass
|
||||
@@ -0,0 +1,28 @@
|
||||
from itertools import count
|
||||
|
||||
|
||||
from autobeerpong.states.server import ServerState
|
||||
from autobeerpong.contexts.lobby import LobbyContext
|
||||
from autobeerpong.types.client_map import ClientMap_T
|
||||
from autobeerpong.client import Client
|
||||
|
||||
|
||||
class ServerContext:
|
||||
def __init__(self) -> None:
|
||||
self.clients: ClientMap_T = {}
|
||||
self.client_id_counter = count()
|
||||
|
||||
self.state = ServerState.LOBBY
|
||||
self.lobby = LobbyContext(self.clients)
|
||||
# self.match = MatchContext()
|
||||
|
||||
def get_free_client_id(self) -> int:
|
||||
return next(self.client_id_counter)
|
||||
|
||||
def add_client(self, client_id: int, client: Client) -> None:
|
||||
assert client_id not in self.clients
|
||||
self.clients[client_id] = client
|
||||
|
||||
def get_client(self, client_id: int) -> Client:
|
||||
assert client_id in self.clients
|
||||
return self.clients[client_id]
|
||||
@@ -1,41 +0,0 @@
|
||||
import json
|
||||
import time
|
||||
|
||||
from pprint import pprint
|
||||
from websockets.sync.client import connect
|
||||
|
||||
|
||||
actions = [
|
||||
({"action": "join", "name": "ruedi"}, True),
|
||||
({"action": "toggleReady"}, False),
|
||||
]
|
||||
|
||||
|
||||
def hello():
|
||||
with connect("ws://localhost:8888") as websocket:
|
||||
for action, direct_response in actions:
|
||||
websocket.send(json.dumps(action))
|
||||
if direct_response:
|
||||
message = json.loads(websocket.recv())
|
||||
player_id = int(message["player"]["id"])
|
||||
pprint(message)
|
||||
|
||||
message = json.loads(websocket.recv())
|
||||
pprint(message)
|
||||
|
||||
time.sleep(2)
|
||||
|
||||
with connect("ws://localhost:8888") as websocket:
|
||||
websocket.send(json.dumps({"action": "rejoin", "id": player_id}))
|
||||
message = json.loads(websocket.recv())
|
||||
pprint(message)
|
||||
message = json.loads(websocket.recv())
|
||||
pprint(message)
|
||||
|
||||
# websocket.send(json.dumps({"action": "toggleReady"}))
|
||||
# message = json.loads(websocket.recv())
|
||||
# pprint(message)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
hello()
|
||||
@@ -1,108 +0,0 @@
|
||||
from typing import Any, Callable
|
||||
from websockets.asyncio.server import ServerConnection
|
||||
|
||||
from autobeerpong.client import Client, ClientRole
|
||||
from autobeerpong.action import JoinAction, RejoinAction
|
||||
|
||||
|
||||
MAX_PLAYERS_IN_LOBBY = 2
|
||||
|
||||
|
||||
class AutobeerpongLobby:
|
||||
MAX_PLAYERS = MAX_PLAYERS_IN_LOBBY
|
||||
|
||||
def __init__(self):
|
||||
self.clients: dict[int, Client] = {}
|
||||
|
||||
async def broadcast(self) -> None:
|
||||
for client in filter(
|
||||
lambda c: c.role is not ClientRole.DISCONNECTED, self.clients.values()
|
||||
):
|
||||
await client.send(self.as_dict())
|
||||
|
||||
async def process_join(
|
||||
self, client_id: int, websocket: ServerConnection, action: JoinAction
|
||||
) -> None:
|
||||
client = Client(client_id=client_id, websocket=websocket, name=action.name)
|
||||
|
||||
if self.is_players_full():
|
||||
client.role = ClientRole.SPECTATOR
|
||||
|
||||
self.add_client(client)
|
||||
|
||||
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:
|
||||
if client.role is ClientRole.SPECTATOR and not self.is_players_full():
|
||||
client.role = ClientRole.PLAYER
|
||||
elif client.role is ClientRole.PLAYER:
|
||||
client.role = ClientRole.SPECTATOR
|
||||
|
||||
async def process_toggle_ready(self, client: Client) -> None:
|
||||
if client.role is ClientRole.PLAYER:
|
||||
client.ready = not client.ready
|
||||
|
||||
async def process(self, client_id: int, action_dict: dict[str, Any]) -> None:
|
||||
action_name = action_dict["action"]
|
||||
|
||||
client = self.clients.get(client_id)
|
||||
|
||||
if client is None:
|
||||
raise Exception("Client has not joined.")
|
||||
|
||||
if action_name == "toggleRole":
|
||||
await self.process_toggle_role(client)
|
||||
elif action_name == "toggleReady":
|
||||
await self.process_toggle_ready(client)
|
||||
|
||||
def add_client(self, client: Client):
|
||||
self.clients[client.id] = client
|
||||
|
||||
def filter_clients(self, rule: Callable[[Client], bool]) -> list[Client]:
|
||||
return list(filter(lambda x: rule(x), self.clients.values()))
|
||||
|
||||
def get_players(self) -> list[Client]:
|
||||
return self.filter_clients(lambda x: x.role is ClientRole.PLAYER)
|
||||
|
||||
def get_num_players(self) -> int:
|
||||
return len(self.get_players())
|
||||
|
||||
def get_spectators(self) -> list[Client]:
|
||||
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]:
|
||||
players = self.get_players()
|
||||
spectators = self.get_spectators()
|
||||
|
||||
return {
|
||||
"gamestate": {
|
||||
"players": [
|
||||
{"player": player.as_dict(), "ready": player.ready}
|
||||
for player in players
|
||||
],
|
||||
"spectators": [
|
||||
{"player": spectator.as_dict()} for spectator in spectators
|
||||
],
|
||||
}
|
||||
}
|
||||
Whitespace-only changes.
@@ -0,0 +1 @@
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
from autobeerpong.messages.message import Message, MessageRaw_T
|
||||
from autobeerpong.client import Client
|
||||
from autobeerpong.contexts.server import ServerContext
|
||||
from autobeerpong.contexts.client import ClientContext
|
||||
from autobeerpong.states.server import ServerState
|
||||
from autobeerpong.states.client import ClientState
|
||||
|
||||
|
||||
class JoinMessage(Message):
|
||||
has_direct_response = True
|
||||
|
||||
def _contents_from_raw(self, message_raw: MessageRaw_T):
|
||||
self.name = str(message_raw["messageContent"]["name"])
|
||||
|
||||
def to_raw(self) -> MessageRaw_T:
|
||||
msg_raw = super().to_raw()
|
||||
msg_raw["messageContent"].update({"name": self.name})
|
||||
|
||||
self.validate(msg_raw)
|
||||
|
||||
return msg_raw
|
||||
|
||||
async def execute(
|
||||
self, server_context: ServerContext, client_context: ClientContext
|
||||
) -> None:
|
||||
|
||||
assert server_context.state is ServerState.LOBBY
|
||||
assert client_context.has_joined is False
|
||||
|
||||
client_id = server_context.get_free_client_id()
|
||||
|
||||
client = Client(
|
||||
client_id=client_id,
|
||||
websocket=client_context.websocket,
|
||||
name=self.name,
|
||||
)
|
||||
|
||||
if server_context.lobby.is_players_full():
|
||||
client.state = ClientState.SPECTATOR
|
||||
|
||||
server_context.add_client(client_id, client)
|
||||
client_context.has_joined = True
|
||||
client_context.client_id = client_id
|
||||
|
||||
join_message_raw: MessageRaw_T = {
|
||||
"messageType": "joinResponse",
|
||||
"messageContent": {"client": client.as_raw()},
|
||||
}
|
||||
|
||||
Message.validate(join_message_raw)
|
||||
|
||||
await client.send(join_message_raw)
|
||||
@@ -0,0 +1,47 @@
|
||||
from autobeerpong.messages.message import Message, MessageRaw_T
|
||||
from autobeerpong.contexts.server import ServerContext
|
||||
from autobeerpong.contexts.client import ClientContext
|
||||
from autobeerpong.states.server import ServerState
|
||||
from autobeerpong.states.client import ClientState
|
||||
|
||||
|
||||
class RejoinMessage(Message):
|
||||
has_direct_response = True
|
||||
|
||||
def _contents_from_raw(self, message_raw: MessageRaw_T):
|
||||
self.id = int(message_raw["messageContent"]["id"])
|
||||
|
||||
def to_raw(self) -> MessageRaw_T:
|
||||
msg_raw = super().to_raw()
|
||||
msg_raw["messageContent"].update({"id": self.id})
|
||||
|
||||
self.validate(msg_raw)
|
||||
|
||||
return msg_raw
|
||||
|
||||
async def execute(
|
||||
self, server_context: ServerContext, client_context: ClientContext
|
||||
) -> None:
|
||||
|
||||
assert server_context.state is ServerState.LOBBY
|
||||
assert client_context.has_joined is False
|
||||
|
||||
client = server_context.get_client(self.id)
|
||||
client.websocket = client_context.websocket
|
||||
|
||||
if server_context.lobby.is_players_full():
|
||||
client.state = ClientState.SPECTATOR
|
||||
else:
|
||||
client.state = ClientState.PLAYER
|
||||
|
||||
client_context.client_id = self.id
|
||||
client_context.has_joined = True
|
||||
|
||||
join_message_raw: MessageRaw_T = {
|
||||
"messageType": "joinResponse",
|
||||
"messageContent": {"client": client.as_raw()},
|
||||
}
|
||||
|
||||
Message.validate(join_message_raw)
|
||||
|
||||
await client.send(join_message_raw)
|
||||
@@ -0,0 +1,30 @@
|
||||
from autobeerpong.messages.message import Message, MessageRaw_T
|
||||
from autobeerpong.contexts.server import ServerContext
|
||||
from autobeerpong.contexts.client import ClientContext
|
||||
from autobeerpong.states.server import ServerState
|
||||
from autobeerpong.states.client import ClientState
|
||||
|
||||
|
||||
class ToggleReadyMessage(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
|
||||
|
||||
async def execute(
|
||||
self, server_context: ServerContext, client_context: ClientContext
|
||||
) -> None:
|
||||
assert server_context.state is ServerState.LOBBY
|
||||
assert client_context.has_joined is True
|
||||
|
||||
client = server_context.get_client(client_context.get_client_id())
|
||||
|
||||
if client.state is ClientState.PLAYER:
|
||||
client.ready = not client.ready
|
||||
@@ -0,0 +1,35 @@
|
||||
from autobeerpong.messages.message import Message, MessageRaw_T
|
||||
from autobeerpong.contexts.server import ServerContext
|
||||
from autobeerpong.contexts.client import ClientContext
|
||||
from autobeerpong.states.server import ServerState
|
||||
from autobeerpong.states.client import ClientState
|
||||
|
||||
|
||||
class ToggleRoleMessage(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
|
||||
|
||||
async def execute(
|
||||
self, server_context: ServerContext, client_context: ClientContext
|
||||
) -> None:
|
||||
assert server_context.state is ServerState.LOBBY
|
||||
assert client_context.has_joined is True
|
||||
|
||||
client = server_context.get_client(client_context.get_client_id())
|
||||
|
||||
if (
|
||||
client.state is ClientState.SPECTATOR
|
||||
and not server_context.lobby.is_players_full()
|
||||
):
|
||||
client.state = ClientState.PLAYER
|
||||
elif client.state is ClientState.PLAYER:
|
||||
client.state = ClientState.SPECTATOR
|
||||
@@ -0,0 +1,51 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import jsonschema
|
||||
import jsonschema.protocols
|
||||
|
||||
from pathlib import Path
|
||||
from referencing import Registry, Resource
|
||||
from referencing.jsonschema import DRAFT202012
|
||||
|
||||
import autobeerpong.config as config
|
||||
from autobeerpong.contexts.server import ServerContext
|
||||
from autobeerpong.contexts.client import ClientContext
|
||||
from autobeerpong.types.raw import MessageRaw_T
|
||||
|
||||
|
||||
def _retrieve_from_filesystem(uri: str):
|
||||
# if not uri.startswith("http://localhost/"):
|
||||
# raise NoSuchResource(ref=uri)
|
||||
path = config.SCHEMA_DIR / Path(uri.removeprefix("http://localhost/"))
|
||||
contents = json.loads(path.read_text())
|
||||
return Resource.from_contents(contents, default_specification=DRAFT202012)
|
||||
|
||||
|
||||
class Message:
|
||||
has_direct_response = False
|
||||
registry = Registry(retrieve=_retrieve_from_filesystem)
|
||||
validator: jsonschema.protocols.Validator = jsonschema.Draft202012Validator(
|
||||
json.loads((config.SCHEMA_DIR / Path("message.json")).read_text()),
|
||||
registry=registry,
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def validate(cls, message_raw: MessageRaw_T) -> None:
|
||||
cls.validator.validate(message_raw)
|
||||
|
||||
def __init__(self, message_raw: MessageRaw_T) -> None:
|
||||
self.validate(message_raw)
|
||||
self.type = message_raw["messageType"]
|
||||
self._contents_from_raw(message_raw)
|
||||
|
||||
def _contents_from_raw(self, message_raw: MessageRaw_T) -> None:
|
||||
raise NotImplementedError()
|
||||
|
||||
def to_raw(self) -> MessageRaw_T:
|
||||
return {"messageType": self.type, "messageContent": {}}
|
||||
|
||||
async def execute(
|
||||
self, server_context: ServerContext, client_context: ClientContext
|
||||
) -> None:
|
||||
raise NotImplementedError()
|
||||
@@ -1,3 +0,0 @@
|
||||
class Protocol:
|
||||
def __init__(self):
|
||||
pass
|
||||
@@ -1,83 +1,101 @@
|
||||
import websockets
|
||||
from autobeerpong.action import JoinAction, RejoinAction
|
||||
import json
|
||||
import asyncio
|
||||
|
||||
from enum import Enum, auto
|
||||
from itertools import count
|
||||
from websockets.asyncio.server import serve, ServerConnection
|
||||
from websockets.asyncio.server import ServerConnection, serve
|
||||
from websockets.exceptions import ConnectionClosedOK
|
||||
|
||||
from autobeerpong.lobby import AutobeerpongLobby
|
||||
|
||||
|
||||
class ServerState(Enum):
|
||||
LOBBY = auto()
|
||||
MATCH = auto()
|
||||
import autobeerpong.config as config
|
||||
from autobeerpong.messages.message import Message, MessageRaw_T
|
||||
from autobeerpong.messages.lobby.join import JoinMessage
|
||||
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.contexts.server import ServerContext
|
||||
from autobeerpong.contexts.client import ClientContext
|
||||
from autobeerpong.states.client import ClientState
|
||||
|
||||
|
||||
class AutobeerpongServer:
|
||||
message_map: dict[str, type[Message]] = {
|
||||
"join": JoinMessage,
|
||||
"rejoin": RejoinMessage,
|
||||
"toggleReady": ToggleReadyMessage,
|
||||
"toggleRole": ToggleRoleMessage,
|
||||
}
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.client_ids = count()
|
||||
self.server_state = ServerState.LOBBY
|
||||
self.lobby = AutobeerpongLobby()
|
||||
self.context = ServerContext()
|
||||
|
||||
async def handler(self, websocket: ServerConnection):
|
||||
client_id = None
|
||||
async def broadcast(self):
|
||||
players = list(
|
||||
filter(
|
||||
lambda x: x.state is ClientState.PLAYER,
|
||||
self.context.lobby._clients.values(),
|
||||
)
|
||||
)
|
||||
spectators = list(
|
||||
filter(
|
||||
lambda x: x.state is ClientState.SPECTATOR,
|
||||
self.context.lobby._clients.values(),
|
||||
)
|
||||
)
|
||||
|
||||
lobby_state_raw: MessageRaw_T = {
|
||||
"messageType": "lobbyState",
|
||||
"messageContent": {
|
||||
"players": [player.as_raw() 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)
|
||||
|
||||
try:
|
||||
async for msg in websocket:
|
||||
action_dict = json.loads(msg)
|
||||
message_raw: MessageRaw_T = json.loads(msg)
|
||||
message_type: str = message_raw.get("messageType")
|
||||
|
||||
if self.server_state is ServerState.LOBBY:
|
||||
action_name = action_dict["action"]
|
||||
if message_type is None:
|
||||
raise Exception("Message has no messageType property.")
|
||||
|
||||
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"]),
|
||||
MessageClass = self.message_map.get(message_type)
|
||||
|
||||
if MessageClass is None:
|
||||
raise Exception(f"Unknown messageType: {message_type}.")
|
||||
|
||||
message = MessageClass(message_raw)
|
||||
|
||||
await message.execute(
|
||||
server_context=self.context,
|
||||
client_context=client_context,
|
||||
)
|
||||
|
||||
elif action_name == "rejoin":
|
||||
client_id = action_dict["client_id"]
|
||||
await self.lobby.process_rejoin(
|
||||
websocket=websocket, action=RejoinAction(client_id)
|
||||
)
|
||||
await self.broadcast()
|
||||
|
||||
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:
|
||||
pass
|
||||
|
||||
except Exception as exception:
|
||||
print(str(exception))
|
||||
await websocket.close(1011)
|
||||
else:
|
||||
if client_id is not None:
|
||||
client = self.lobby.clients.get(client_id)
|
||||
|
||||
if client is not None:
|
||||
client.disconnect()
|
||||
|
||||
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.
|
||||
if client_context.has_joined:
|
||||
self.context.clients[client_context.get_client_id()].disconnect()
|
||||
try:
|
||||
await self.lobby.broadcast()
|
||||
except websockets.exceptions.ConnectionClosedOK:
|
||||
await self.broadcast()
|
||||
except ConnectionClosedOK:
|
||||
pass
|
||||
except Exception as exception:
|
||||
raise (exception)
|
||||
|
||||
async def _start(self) -> None:
|
||||
async with serve(self.handler, "localhost", 8888) as server:
|
||||
async with serve(
|
||||
self.handler, config.SERVER_HOST, config.SERVER_PORT
|
||||
) as server:
|
||||
await server.serve_forever()
|
||||
|
||||
def start(self) -> None:
|
||||
|
||||
@@ -1,41 +0,0 @@
|
||||
from enum import Enum, auto
|
||||
|
||||
|
||||
class State(Enum):
|
||||
ONE = auto()
|
||||
TWO = auto()
|
||||
THREE = auto()
|
||||
FOUR = auto()
|
||||
|
||||
|
||||
class StateMachine:
|
||||
def __init__(self) -> None:
|
||||
self.reset_state = State.ONE
|
||||
self.state = self.reset_state
|
||||
|
||||
def update(self) -> None:
|
||||
print(self.state.name)
|
||||
|
||||
if self.state is State.ONE:
|
||||
self.state = State.TWO
|
||||
elif self.state is State.TWO:
|
||||
self.state = State.THREE
|
||||
elif self.state is State.THREE:
|
||||
self.state = State.FOUR
|
||||
elif self.state is State.FOUR:
|
||||
self.state = State.ONE
|
||||
else:
|
||||
raise Exception(f"Unknown state: {self.state}")
|
||||
|
||||
def reset(self) -> None:
|
||||
print("RESET!")
|
||||
self.state = self.reset_state
|
||||
|
||||
|
||||
fsm = StateMachine()
|
||||
|
||||
for i in range(10):
|
||||
if i == 6:
|
||||
fsm.reset()
|
||||
|
||||
fsm.update()
|
||||
Whitespace-only changes.
@@ -0,0 +1,7 @@
|
||||
from enum import Enum, auto
|
||||
|
||||
|
||||
class ClientState(Enum):
|
||||
PLAYER = auto()
|
||||
SPECTATOR = auto()
|
||||
DISCONNECTED = auto()
|
||||
@@ -0,0 +1,6 @@
|
||||
from enum import Enum, auto
|
||||
|
||||
|
||||
class ServerState(Enum):
|
||||
LOBBY = auto()
|
||||
MATCH = auto()
|
||||
Whitespace-only changes.
@@ -0,0 +1,3 @@
|
||||
from autobeerpong.client import Client
|
||||
|
||||
ClientMap_T = dict[int, Client]
|
||||
@@ -0,0 +1,5 @@
|
||||
from typing import Any
|
||||
|
||||
_Raw_T = dict[str, Any]
|
||||
MessageRaw_T = _Raw_T
|
||||
ClientRaw_T = _Raw_T
|
||||
@@ -0,0 +1,2 @@
|
||||
server_port = 8888
|
||||
server_host = "localhost"
|
||||
@@ -1 +1,2 @@
|
||||
websockets==15.0.1
|
||||
jsonschema==4.26.0
|
||||
+148
-152
@@ -1,99 +1,12 @@
|
||||
import json
|
||||
import asyncio
|
||||
|
||||
from typing import Any
|
||||
from unittest import IsolatedAsyncioTestCase
|
||||
from websockets.asyncio.client import connect
|
||||
|
||||
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
|
||||
|
||||
|
||||
SERVER_RESPONSE_TIMEOUT = 5.0
|
||||
|
||||
|
||||
class ClientTask:
|
||||
pass
|
||||
|
||||
|
||||
class SendActionToServer(ClientTask):
|
||||
def __init__(self, action: Action) -> None:
|
||||
self.action = action
|
||||
|
||||
|
||||
class GetResponseFromServer(ClientTask):
|
||||
pass
|
||||
|
||||
|
||||
class TestClient:
|
||||
def __init__(self) -> None:
|
||||
self.queue_send: asyncio.Queue[ClientTask] = asyncio.Queue()
|
||||
self.queue_recv: asyncio.Queue[dict[str, Any]] = asyncio.Queue()
|
||||
self._task = asyncio.create_task(self._client_task())
|
||||
|
||||
async def _client_task(self):
|
||||
async with connect(f"ws://{SERVER_ADDRESS}:{SERVER_PORT}") as websocket:
|
||||
while True:
|
||||
client_task = await self.queue_send.get()
|
||||
|
||||
if isinstance(client_task, SendActionToServer):
|
||||
await websocket.send(json.dumps(client_task.action.as_dict()))
|
||||
|
||||
elif isinstance(client_task, GetResponseFromServer):
|
||||
response_raw = await asyncio.wait_for(
|
||||
websocket.recv(), timeout=SERVER_RESPONSE_TIMEOUT
|
||||
)
|
||||
await self.queue_recv.put(json.loads(response_raw))
|
||||
|
||||
else:
|
||||
raise Exception(
|
||||
f"Unknown type of ClientTask received: {type(ClientTask)}"
|
||||
)
|
||||
|
||||
self.queue_send.task_done()
|
||||
|
||||
async def send_action(self, action: Action):
|
||||
await self.queue_send.put(SendActionToServer(action))
|
||||
|
||||
async def get_response(self) -> dict[str, Any]:
|
||||
await self.queue_send.put(GetResponseFromServer())
|
||||
|
||||
response_raw = await asyncio.wait_for(
|
||||
self.queue_recv.get(),
|
||||
timeout=SERVER_RESPONSE_TIMEOUT,
|
||||
)
|
||||
|
||||
self.queue_recv.task_done()
|
||||
|
||||
return response_raw
|
||||
|
||||
async def send_actions(self, actions: list[Action]) -> list[dict[str, Any]]:
|
||||
responses: list[dict[str, Any]] = []
|
||||
|
||||
for action in actions:
|
||||
await self.send_action(action)
|
||||
|
||||
if action.has_direct_response:
|
||||
num_responses = 2
|
||||
else:
|
||||
num_responses = 1
|
||||
|
||||
for _ in range(num_responses):
|
||||
responses.append(await self.get_response())
|
||||
|
||||
return responses
|
||||
|
||||
def shutdown(self):
|
||||
self.queue_send.shutdown()
|
||||
self.queue_recv.shutdown()
|
||||
self._task.cancel()
|
||||
from autobeerpong.messages.lobby.join import JoinMessage
|
||||
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.contexts.lobby import MAX_PLAYERS_IN_LOBBY
|
||||
from tests.utils.server import manage_server
|
||||
from tests.utils.client import TestClient
|
||||
|
||||
|
||||
class TestLobby(IsolatedAsyncioTestCase):
|
||||
@@ -102,29 +15,38 @@ class TestLobby(IsolatedAsyncioTestCase):
|
||||
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 = await client_a.send_messages(
|
||||
[JoinMessage({"messageType": "join", "messageContent": {"name": "Ruedi"}})]
|
||||
)
|
||||
client_b_responses = await client_b.send_messages(
|
||||
[JoinMessage({"messageType": "join", "messageContent": {"name": "Hansi"}})]
|
||||
)
|
||||
client_a_responses.append(await client_a.get_response())
|
||||
|
||||
self.assertEqual(len(client_a_responses), 3)
|
||||
self.assertEqual(len(client_b_responses), 2)
|
||||
|
||||
response = client_a_responses[0]
|
||||
self.assertEqual(response["player"]["name"], "Ruedi")
|
||||
self.assertEqual(response["messageType"], "joinResponse")
|
||||
self.assertEqual(response["messageContent"]["client"]["name"], "Ruedi")
|
||||
|
||||
response = client_b_responses[0]
|
||||
self.assertEqual(response["player"]["name"], "Hansi")
|
||||
self.assertEqual(response["messageType"], "joinResponse")
|
||||
self.assertEqual(response["messageContent"]["client"]["name"], "Hansi")
|
||||
|
||||
response = client_a_responses[1]
|
||||
self.assertEqual(len(response["gamestate"]["players"]), 1)
|
||||
self.assertEqual(response["messageType"], "lobbyState")
|
||||
self.assertEqual(len(response["messageContent"]["players"]), 1)
|
||||
|
||||
response = client_b_responses[1]
|
||||
self.assertEqual(len(response["gamestate"]["players"]), 2)
|
||||
self.assertEqual(response["messageType"], "lobbyState")
|
||||
self.assertEqual(len(response["messageContent"]["players"]), 2)
|
||||
|
||||
response = client_a_responses[2]
|
||||
self.assertEqual(len(response["gamestate"]["players"]), 2)
|
||||
self.assertEqual(response["messageType"], "lobbyState")
|
||||
self.assertEqual(len(response["messageContent"]["players"]), 2)
|
||||
|
||||
player_names = [p["player"]["name"] for p in response["gamestate"]["players"]]
|
||||
player_names = [p["name"] for p in response["messageContent"]["players"]]
|
||||
|
||||
self.assertIn("Ruedi", player_names)
|
||||
self.assertIn("Hansi", player_names)
|
||||
@@ -137,32 +59,54 @@ class TestLobby(IsolatedAsyncioTestCase):
|
||||
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 = await client_a.send_messages(
|
||||
[JoinMessage({"messageType": "join", "messageContent": {"name": "Ruedi"}})]
|
||||
)
|
||||
client_b_responses = await client_b.send_messages(
|
||||
[JoinMessage({"messageType": "join", "messageContent": {"name": "Hansi"}})]
|
||||
)
|
||||
client_a_responses.append(await client_a.get_response())
|
||||
client_a_responses.extend(await client_a.send_actions([ToggleReadyAction()]))
|
||||
client_a_responses.extend(
|
||||
await client_a.send_messages(
|
||||
[
|
||||
ToggleReadyMessage(
|
||||
{"messageType": "toggleReady", "messageContent": {}}
|
||||
)
|
||||
]
|
||||
)
|
||||
)
|
||||
client_b_responses.append(await client_b.get_response())
|
||||
client_b_responses.extend(await client_b.send_actions([ToggleReadyAction()]))
|
||||
client_b_responses.extend(
|
||||
await client_b.send_messages(
|
||||
[
|
||||
ToggleReadyMessage(
|
||||
{"messageType": "toggleReady", "messageContent": {}}
|
||||
)
|
||||
]
|
||||
)
|
||||
)
|
||||
client_a_responses.append(await client_a.get_response())
|
||||
|
||||
response = client_a_responses[3]
|
||||
players = response["gamestate"]["players"]
|
||||
self.assertEqual(response["messageType"], "lobbyState")
|
||||
players = response["messageContent"]["players"]
|
||||
|
||||
for player in players:
|
||||
if player["player"]["name"] == "Ruedi":
|
||||
if player["name"] == "Ruedi":
|
||||
self.assertEqual(player["ready"], True)
|
||||
elif player["player"]["name"] == "Hansi":
|
||||
elif player["name"] == "Hansi":
|
||||
self.assertEqual(player["ready"], False)
|
||||
|
||||
self.assertEqual(client_a_responses[3], client_b_responses[2])
|
||||
|
||||
response = client_a_responses[4]
|
||||
players = response["gamestate"]["players"]
|
||||
self.assertEqual(response["messageType"], "lobbyState")
|
||||
players = response["messageContent"]["players"]
|
||||
|
||||
for player in players:
|
||||
if player["player"]["name"] == "Ruedi":
|
||||
if player["name"] == "Ruedi":
|
||||
self.assertEqual(player["ready"], True)
|
||||
elif player["player"]["name"] == "Hansi":
|
||||
elif player["name"] == "Hansi":
|
||||
self.assertEqual(player["ready"], True)
|
||||
|
||||
self.assertEqual(client_a_responses[4], client_b_responses[3])
|
||||
@@ -175,33 +119,55 @@ class TestLobby(IsolatedAsyncioTestCase):
|
||||
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 = await client_a.send_messages(
|
||||
[JoinMessage({"messageType": "join", "messageContent": {"name": "Ruedi"}})]
|
||||
)
|
||||
client_b_responses = await client_b.send_messages(
|
||||
[JoinMessage({"messageType": "join", "messageContent": {"name": "Hansi"}})]
|
||||
)
|
||||
client_a_responses.append(await client_a.get_response())
|
||||
client_a_responses.extend(await client_a.send_actions([ToggleRoleAction()]))
|
||||
client_a_responses.extend(
|
||||
await client_a.send_messages(
|
||||
[
|
||||
ToggleRoleMessage(
|
||||
{
|
||||
"messageType": "toggleRole",
|
||||
"messageContent": {},
|
||||
}
|
||||
)
|
||||
]
|
||||
)
|
||||
)
|
||||
client_b_responses.append(await client_b.get_response())
|
||||
client_b_responses.extend(await client_b.send_actions([ToggleRoleAction()]))
|
||||
client_b_responses.extend(
|
||||
await client_b.send_messages(
|
||||
[
|
||||
ToggleRoleMessage(
|
||||
{
|
||||
"messageType": "toggleRole",
|
||||
"messageContent": {},
|
||||
}
|
||||
)
|
||||
]
|
||||
)
|
||||
)
|
||||
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["gamestate"]["players"]), 2)
|
||||
self.assertEqual(len(response["messageContent"]["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"
|
||||
)
|
||||
self.assertEqual(len(response["messageContent"]["players"]), 1)
|
||||
self.assertEqual(len(response["messageContent"]["spectators"]), 1)
|
||||
self.assertEqual(response["messageContent"]["spectators"][0]["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)
|
||||
self.assertEqual(len(response["messageContent"]["players"]), 0)
|
||||
self.assertEqual(len(response["messageContent"]["spectators"]), 2)
|
||||
|
||||
client_a.shutdown()
|
||||
client_b.shutdown()
|
||||
@@ -212,38 +178,45 @@ class TestLobby(IsolatedAsyncioTestCase):
|
||||
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 = await client_a.send_messages(
|
||||
[JoinMessage({"messageType": "join", "messageContent": {"name": "Ruedi"}})]
|
||||
)
|
||||
client_b_responses = await client_b.send_messages(
|
||||
[JoinMessage({"messageType": "join", "messageContent": {"name": "Hansi"}})]
|
||||
)
|
||||
client_a_responses.append(await client_a.get_response())
|
||||
client_c_responses = await client_c.send_actions([JoinAction("Fredi")])
|
||||
client_c_responses = await client_c.send_messages(
|
||||
[JoinMessage({"messageType": "join", "messageContent": {"name": "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["messageType"], "lobbyState")
|
||||
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"
|
||||
len(response["messageContent"]["players"]), MAX_PLAYERS_IN_LOBBY
|
||||
)
|
||||
self.assertEqual(response["messageContent"]["spectators"][0]["name"], "Fredi")
|
||||
|
||||
client_c_responses.extend(await client_c.send_actions([ToggleRoleAction()]))
|
||||
client_c_responses.extend(
|
||||
await client_c.send_messages(
|
||||
[ToggleRoleMessage({"messageType": "toggleRole", "messageContent": {}})]
|
||||
)
|
||||
)
|
||||
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["messageType"], "lobbyState")
|
||||
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"
|
||||
len(response["messageContent"]["players"]), MAX_PLAYERS_IN_LOBBY
|
||||
)
|
||||
self.assertEqual(response["messageContent"]["spectators"][0]["name"], "Fredi")
|
||||
|
||||
client_a.shutdown()
|
||||
client_b.shutdown()
|
||||
@@ -254,44 +227,67 @@ class TestLobby(IsolatedAsyncioTestCase):
|
||||
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 = await client_a.send_messages(
|
||||
[JoinMessage({"messageType": "join", "messageContent": {"name": "Ruedi"}})]
|
||||
)
|
||||
client_b_responses = await client_b.send_messages(
|
||||
[JoinMessage({"messageType": "join", "messageContent": {"name": "Hansi"}})]
|
||||
)
|
||||
client_a_responses.append(await client_a.get_response())
|
||||
|
||||
client_b_id = client_b_responses[0]["player"]["id"]
|
||||
|
||||
client_b_id = client_b_responses[0]["messageContent"]["client"]["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_b_responses = await client_b.send_messages(
|
||||
[
|
||||
RejoinMessage(
|
||||
{"messageType": "rejoin", "messageContent": {"id": client_b_id}}
|
||||
)
|
||||
]
|
||||
)
|
||||
client_a_responses.append(await client_a.get_response())
|
||||
|
||||
client_b_responses.extend(await client_b.send_actions([ToggleReadyAction()]))
|
||||
client_b_responses.extend(
|
||||
await client_b.send_messages(
|
||||
[
|
||||
ToggleReadyMessage(
|
||||
{"messageType": "toggleReady", "messageContent": {}}
|
||||
)
|
||||
]
|
||||
)
|
||||
)
|
||||
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
|
||||
client_a_responses[-1]["messageContent"]["players"][0]["ready"], False
|
||||
)
|
||||
self.assertEqual(
|
||||
client_a_responses[-1]["gamestate"]["players"][1]["ready"], True
|
||||
client_a_responses[-1]["messageContent"]["players"][1]["ready"], True
|
||||
)
|
||||
|
||||
client_a_responses.extend(await client_a.send_actions([ToggleReadyAction()]))
|
||||
client_a_responses.extend(
|
||||
await client_a.send_messages(
|
||||
[
|
||||
ToggleReadyMessage(
|
||||
{"messageType": "toggleReady", "messageContent": {}}
|
||||
)
|
||||
]
|
||||
)
|
||||
)
|
||||
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
|
||||
client_a_responses[-1]["messageContent"]["players"][0]["ready"], True
|
||||
)
|
||||
self.assertEqual(
|
||||
client_a_responses[-1]["gamestate"]["players"][1]["ready"], True
|
||||
client_a_responses[-1]["messageContent"]["players"][1]["ready"], True
|
||||
)
|
||||
|
||||
client_a.shutdown()
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
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 tests.utils.task import ClientTask, SendMessageToServer, GetResponseFromServer
|
||||
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._task = asyncio.create_task(self._client_task())
|
||||
|
||||
async def _client_task(self) -> None:
|
||||
async with connect(
|
||||
f"ws://{config.SERVER_HOST}:{config.SERVER_PORT}"
|
||||
) as websocket:
|
||||
while True:
|
||||
client_task = await self.queue_send.get()
|
||||
|
||||
if isinstance(client_task, SendMessageToServer):
|
||||
await websocket.send(json.dumps(client_task.message.to_raw()))
|
||||
|
||||
elif isinstance(client_task, GetResponseFromServer):
|
||||
response_raw = await asyncio.wait_for(
|
||||
websocket.recv(), timeout=SERVER_RESPONSE_TIMEOUT
|
||||
)
|
||||
await self.queue_recv.put(json.loads(response_raw))
|
||||
|
||||
else:
|
||||
raise Exception(
|
||||
f"Unknown type of ClientTask received: {type(ClientTask)}"
|
||||
)
|
||||
|
||||
self.queue_send.task_done()
|
||||
|
||||
async def send_message(self, message: Message):
|
||||
await self.queue_send.put(SendMessageToServer(message))
|
||||
|
||||
async def get_response(self) -> dict[str, Any]:
|
||||
await self.queue_send.put(GetResponseFromServer())
|
||||
|
||||
response_raw = await asyncio.wait_for(
|
||||
self.queue_recv.get(),
|
||||
timeout=SERVER_RESPONSE_TIMEOUT,
|
||||
)
|
||||
|
||||
self.queue_recv.task_done()
|
||||
|
||||
return response_raw
|
||||
|
||||
async def send_messages(self, messages: list[Message]) -> list[MessageRaw_T]:
|
||||
responses: list[MessageRaw_T] = []
|
||||
|
||||
for message in messages:
|
||||
await self.send_message(message)
|
||||
|
||||
if message.has_direct_response:
|
||||
num_responses = 2
|
||||
else:
|
||||
num_responses = 1
|
||||
|
||||
for _ in range(num_responses):
|
||||
responses.append(await self.get_response())
|
||||
|
||||
return responses
|
||||
|
||||
def shutdown(self):
|
||||
self.queue_send.shutdown()
|
||||
self.queue_recv.shutdown()
|
||||
self._task.cancel()
|
||||
@@ -1,23 +0,0 @@
|
||||
import json
|
||||
|
||||
from autobeerpong.player import Player
|
||||
|
||||
|
||||
class Response:
|
||||
def __init__(self, response_raw: str | bytes) -> None:
|
||||
self._response_dict = json.loads(response_raw)
|
||||
|
||||
|
||||
class PlayerDirectResponse(Response):
|
||||
def __init__(self, response_raw: str | bytes) -> None:
|
||||
super().__init__(response_raw)
|
||||
self.player = Player.from_dict(
|
||||
player_dict=self._response_dict["player"],
|
||||
is_ready=False,
|
||||
is_spectator=False,
|
||||
)
|
||||
|
||||
|
||||
class GameStateBroadcastResponse(Response):
|
||||
def __init__(self, response_raw: str | bytes) -> None:
|
||||
super().__init__(response_raw)
|
||||
@@ -3,17 +3,17 @@ import functools
|
||||
from websockets.asyncio.server import serve
|
||||
|
||||
from autobeerpong.server import AutobeerpongServer
|
||||
import autobeerpong.config as config
|
||||
|
||||
|
||||
SERVER_ADDRESS = "localhost"
|
||||
SERVER_PORT = 8888
|
||||
SERVER_RESPONSE_TIMEOUT = 0.5
|
||||
|
||||
|
||||
def manage_server(func):
|
||||
@functools.wraps(func)
|
||||
async def _wrapper(obj):
|
||||
server = AutobeerpongServer()
|
||||
async with serve(server.handler, SERVER_ADDRESS, SERVER_PORT):
|
||||
async with serve(server.handler, config.SERVER_HOST, config.SERVER_PORT):
|
||||
await func(obj)
|
||||
|
||||
return _wrapper
|
||||
@@ -0,0 +1,14 @@
|
||||
from autobeerpong.messages.message import Message
|
||||
|
||||
|
||||
class ClientTask:
|
||||
pass
|
||||
|
||||
|
||||
class SendMessageToServer(ClientTask):
|
||||
def __init__(self, message: Message) -> None:
|
||||
self.message = message
|
||||
|
||||
|
||||
class GetResponseFromServer(ClientTask):
|
||||
pass
|
||||
File renamed without changes.
@@ -10,6 +10,9 @@
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": ["id", "name"],
|
||||
"required": [
|
||||
"id",
|
||||
"name"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"title": "JoinMessage",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"type": {
|
||||
"type": "string"
|
||||
},
|
||||
"name": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"type",
|
||||
"name"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
@@ -2,11 +2,15 @@
|
||||
"title": "LobbyState",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"stateType": { "enum": ["lobby"] },
|
||||
"stateType": {
|
||||
"enum": [
|
||||
"lobby"
|
||||
]
|
||||
},
|
||||
"players": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "./player_schema.json"
|
||||
"$ref": "file://localhost/./player_schema.json"
|
||||
}
|
||||
},
|
||||
"spectators": {
|
||||
@@ -16,6 +20,10 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": ["stateType", "players", "spectators"],
|
||||
"required": [
|
||||
"stateType",
|
||||
"players",
|
||||
"spectators"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
File renamed without changes.
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"title": "Message",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"state": {
|
||||
"anyOf": [
|
||||
{
|
||||
"$ref": "./lobby_state_schema.json"
|
||||
},
|
||||
{
|
||||
"$ref": "./match_state_schema.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"state"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "schema:client",
|
||||
"title": "Client",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "number",
|
||||
"minimum": 0
|
||||
},
|
||||
"name": {
|
||||
"type": "string"
|
||||
},
|
||||
"ready": {
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id",
|
||||
"name",
|
||||
"ready"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"properties": {
|
||||
"messageType": {
|
||||
"const": "join"
|
||||
},
|
||||
"messageContent": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"name": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"name"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"properties": {
|
||||
"messageType": {
|
||||
"const": "joinResponse"
|
||||
},
|
||||
"messageContent": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"client": {
|
||||
"$ref": "../common/client.json"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"client"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"properties": {
|
||||
"messageType": {
|
||||
"const": "rejoin"
|
||||
},
|
||||
"messageContent": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "number",
|
||||
"minimum": 0
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"properties": {
|
||||
"messageType": {
|
||||
"const": "lobbyState"
|
||||
},
|
||||
"messageContent": {
|
||||
"players": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "../common/client.json"
|
||||
}
|
||||
},
|
||||
"spectators": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "../common/client.json"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"properties": {
|
||||
"messageType": {
|
||||
"const": "toggleReady"
|
||||
},
|
||||
"messageContent": {
|
||||
"type": "object",
|
||||
"properties": {},
|
||||
"required": [],
|
||||
"additionalProperties": false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"properties": {
|
||||
"messageType": {
|
||||
"const": "toggleRole"
|
||||
},
|
||||
"messageContent": {
|
||||
"type": "object",
|
||||
"properties": {},
|
||||
"required": [],
|
||||
"additionalProperties": false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "schema:message",
|
||||
"title": "Message",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"messageType": {
|
||||
"type": "string"
|
||||
},
|
||||
"messageContent": {
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"anyOf": [
|
||||
{
|
||||
"$ref": "./lobby/join.json"
|
||||
},
|
||||
{
|
||||
"$ref": "./lobby/join_response.json"
|
||||
},
|
||||
{
|
||||
"$ref": "./lobby/rejoin.json"
|
||||
},
|
||||
{
|
||||
"$ref": "./lobby/state.json"
|
||||
},
|
||||
{
|
||||
"$ref": "./lobby/toggle_ready.json"
|
||||
},
|
||||
{
|
||||
"$ref": "./lobby/toggle_role.json"
|
||||
}
|
||||
],
|
||||
"required": [
|
||||
"messageType",
|
||||
"messageContent"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
{
|
||||
"title": "Message",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"state": {
|
||||
"anyOf": [
|
||||
{ "$ref": "./lobby_state_schema.json"},
|
||||
{ "$ref": "./match_state_schema.json"}
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": ["state"],
|
||||
"additionalProperties": false
|
||||
}
|
||||
Reference in new issue
Block a user