Add convenience decorators for new listeners (#2064)

This commit is contained in:
Adam Hopkins 2021-03-16 11:21:05 +02:00 committed by GitHub
parent 2fea954dcf
commit 7bed5a5c3c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 30 additions and 2 deletions

View File

@ -63,6 +63,12 @@ class ListenerMixin:
else:
return partial(register_listener, event=listener_or_event)
def main_process_start(self, listener):
return self.listener(listener, "main_process_start")
def main_process_stop(self, listener):
return self.listener(listener, "main_process_stop")
def before_server_start(self, listener):
return self.listener(listener, "before_server_start")

View File

@ -89,6 +89,20 @@ def test_create_server_main(app, caplog):
) in caplog.record_tuples
def test_create_server_main_convenience(app, caplog):
app.main_process_start(lambda *_: ...)
loop = asyncio.get_event_loop()
with caplog.at_level(logging.INFO):
asyncio_srv_coro = app.create_server(return_asyncio_server=True)
loop.run_until_complete(asyncio_srv_coro)
assert (
"sanic.root",
30,
"Listener events for the main process are not available with "
"create_server()",
) in caplog.record_tuples
def test_app_loop_not_running(app):
with pytest.raises(SanicException) as excinfo:
app.loop

View File

@ -131,14 +131,22 @@ def test_main_process_event(app, caplog):
def main_process_stop(app, loop):
logger.info("main_process_stop")
@app.main_process_start
def main_process_start(app, loop):
logger.info("main_process_start")
@app.main_process_stop
def main_process_stop(app, loop):
logger.info("main_process_stop")
with caplog.at_level(logging.INFO):
app.run(HOST, PORT, workers=num_workers)
assert (
caplog.record_tuples.count(("sanic.root", 20, "main_process_start"))
== 1
== 2
)
assert (
caplog.record_tuples.count(("sanic.root", 20, "main_process_stop"))
== 1
== 2
)