Fixes "after_server_start" when using return_asyncio_server. (#1676)

* Fixes ability to trigger "after_server_start", "before_server_stop", "after_server_stop" server events when using app.create_server to start your own asyncio_server
See example file run_async_advanced for a full example

* Fix a missing method on AsyncServer that some tests need
Add a tiny bit more documentation in-code
Change name of AsyncServerCoro to AsyncioServer
This commit is contained in:
Ashley Sommer
2019-09-17 03:59:16 +10:00
committed by 7
parent e13f42c17b
commit 7674e917e4
4 changed files with 201 additions and 1 deletions

View File

@@ -1,3 +1,4 @@
import asyncio
import signal
import pytest
@@ -89,3 +90,52 @@ async def test_trigger_before_events_create_server(app):
assert hasattr(app, "db")
assert isinstance(app.db, MySanicDb)
def test_create_server_trigger_events(app):
"""Test if create_server can trigger server events"""
flag1 = False
flag2 = False
flag3 = False
async def stop(app, loop):
nonlocal flag1
flag1 = True
await asyncio.sleep(0.1)
app.stop()
async def before_stop(app, loop):
nonlocal flag2
flag2 = True
async def after_stop(app, loop):
nonlocal flag3
flag3 = True
app.listener("after_server_start")(stop)
app.listener("before_server_stop")(before_stop)
app.listener("after_server_stop")(after_stop)
loop = asyncio.get_event_loop()
serv_coro = app.create_server(return_asyncio_server=True)
serv_task = asyncio.ensure_future(serv_coro, loop=loop)
server = loop.run_until_complete(serv_task)
server.after_start()
try:
loop.run_forever()
except KeyboardInterrupt as e:
loop.stop()
finally:
# Run the on_stop function if provided
server.before_stop()
# Wait for server to close
close_task = server.close()
loop.run_until_complete(close_task)
# Complete all tasks on the loop
signal.stopped = True
for connection in server.connections:
connection.close_if_idle()
server.after_stop()
assert flag1 and flag2 and flag3