Closed maxupp closed 1 month ago
I found a really stupid way to accomplish this by abusing the yield mechanism in pytest-asyncio:
@pytest.fixture
async def server():
...
dispatcher = Dispatcher(engine_config, dialog_history_manager, logger)
async with websockets.serve(dispatcher.start, 'localhost', 1337):
try:
yield None
finally:
print('Destroying server')
and using it like this:
@pytest.mark.asyncio
async def test_run_server(server):
async for x in server:
async with connect('ws://localhost:1337') as ws:
await ws.send(json.dumps({'type': 'clientTurn', 'ask': 'What is my age again?'}))
while True:
r = await ws.recv()
print(r)
But I'm sure there must be a better way, right?
Hello, sorry for getting to your question so late — I was unable to find time for this project during the first half of the year.
Your question is half about pytest and half about websockets.
I was never a proficient pytest hacker so I won't be able to help much on that front.
About websockets, here's how I'm testing against a real websockets server in websockets' own test suite:
And here's the implementation of the run_server
context manager:
This looks very similar to what you're trying to implement. Your solution appears similar too, even if the async for x in server:
leaves me a bit puzzled.
Hope this helps!
On thing that could help: if you connect to port 0, the OS will allocate a random available port. This can help isolating tests from one another. Then you need to find which port was allocated so you can connect to it. Here's how I'm doing it:
Sorry if this is a trivial question, but I've spend a lot of time on it by now.
I wrote a server that does wesocket connection and session management, and I am struggling to find a way to test it properly.
I'm starting the server like this:
"Dispatcher" handles a few things like extracting locale and session ID from the HTTP Request, and then retrieves a session, and attaches it to a Manager object:
Now I want to test the Dispatcher by setting up a server in an async fixture and test it with a few edge cases like reconnect handling etc.
I've been through a couple iterations, currently on this:
When running a test against it, I get [WinError 1225] The remote computer refused the network connection:
Is there something I'm doing wrong (well, probably), is there a best practice to do testing like this?
Do I have to wrap the server into an asyncio task and dispatch it like that?