added tests

This commit is contained in:
Jan Felix Wiebe 2025-07-09 22:18:21 +02:00
parent 4e359cf3ef
commit cbe9369712
9 changed files with 960 additions and 150 deletions

View file

@ -0,0 +1,74 @@
from fastapi import WebSocket
from typing import List, Dict, Any
import json
import asyncio
from datetime import datetime
class WebSocketManager:
def __init__(self):
self.active_connections: List[WebSocket] = []
async def connect(self, websocket: WebSocket):
"""Neue WebSocket-Verbindung hinzufügen."""
await websocket.accept()
self.active_connections.append(websocket)
print(f"WebSocket verbunden. Aktive Verbindungen: {len(self.active_connections)}")
def disconnect(self, websocket: WebSocket):
"""WebSocket-Verbindung entfernen."""
if websocket in self.active_connections:
self.active_connections.remove(websocket)
print(f"WebSocket getrennt. Aktive Verbindungen: {len(self.active_connections)}")
async def broadcast(self, message: Dict[str, Any]):
"""Nachricht an alle verbundenen Clients senden."""
if not self.active_connections:
return
# Nachricht als JSON serialisieren
message_json = json.dumps(message, default=str)
# An alle verbundenen Clients senden
disconnected = []
for connection in self.active_connections:
try:
await connection.send_text(message_json)
except Exception as e:
print(f"Fehler beim Senden an WebSocket: {e}")
disconnected.append(connection)
# Getrennte Verbindungen entfernen
for connection in disconnected:
self.disconnect(connection)
async def broadcast_order_created(self, order: Dict[str, Any]):
"""Broadcast für neue Bestellung."""
message = {
"type": "order_created",
"timestamp": datetime.now().isoformat(),
"order": order
}
await self.broadcast(message)
async def broadcast_order_deleted(self, order_id: str):
"""Broadcast für gelöschte Bestellung."""
message = {
"type": "order_deleted",
"timestamp": datetime.now().isoformat(),
"order_id": order_id
}
await self.broadcast(message)
async def broadcast_all_orders(self, orders: List[Dict[str, Any]]):
"""Broadcast für alle Bestellungen (z.B. bei initialer Verbindung)."""
message = {
"type": "all_orders",
"timestamp": datetime.now().isoformat(),
"orders": orders
}
await self.broadcast(message)
# Globale WebSocket-Manager-Instanz
websocket_manager = WebSocketManager()