#!/usr/bin/env python3
import asyncio
import sys
from amicus.websocket_client import SynapseWebSocketClient
async def main():
# Command to run the server from the 'amicus' module
server_command = [sys.executable, '-m', 'amicus.websocket_server']
# Environment with PYTHONPATH to ensure the module is found
env = {'PYTHONPATH': 'src'}
# Start the server as a background process
process = await asyncio.create_subprocess_exec(
*server_command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
env=env
)
print(f"WebSocket server starting in background with PID: {process.pid}")
# Give the server a moment to start up
await asyncio.sleep(2)
test_successful = asyncio.Event()
received_event_data = None
def on_event(msg):
nonlocal received_event_data
print(f"Client received event: {msg}")
received_event_data = msg.get('data')
if received_event_data == {'test_key': 'test_value'}:
test_successful.set()
client = SynapseWebSocketClient(node_id="test-client")
try:
# Connect the client
connected = await client.connect()
print(f"Client connection status: {connected}")
if not connected:
print("Test FAILED: Client could not connect.")
stdout, stderr = await process.communicate()
print("--- Server STDOUT ---")
print(stdout.decode())
print("--- Server STDERR ---")
print(stderr.decode())
return
# Run the test logic
print("Client subscribing to 'test_event'...")
client.subscribe('test_event', on_event)
print("Client subscribed.")
await asyncio.sleep(0.5)
print("Client publishing event...")
await client.publish('test_event', {'test_key': 'test_value'})
print("Client event published.")
# Wait for the test to complete or time out
print("Waiting for event to be received...")
await asyncio.wait_for(test_successful.wait(), timeout=5.0)
print("Test PASSED")
except asyncio.TimeoutError:
print("Test FAILED: Did not receive event in time.")
print(f"Received data: {received_event_data}")
stdout, stderr = await process.communicate()
print("--- Server STDOUT ---")
print(stdout.decode())
print("--- Server STDERR ---")
print(stderr.decode())
except Exception as e:
print(f"An unexpected error occurred: {e}")
stdout, stderr = await process.communicate()
print("--- Server STDOUT ---")
print(stdout.decode())
print("--- Server STDERR ---")
print(stderr.decode())
finally:
# Clean up
if client.connected:
await client.disconnect()
if process.returncode is None:
print(f"Terminating server process (PID: {process.pid})")
process.terminate()
await process.wait()
print("Test finished.")
if __name__ == "__main__":
asyncio.run(main())