From 7bed5a5c3c002a2d099b9d95fe86b6d21bd1ac59 Mon Sep 17 00:00:00 2001 From: Adam Hopkins Date: Tue, 16 Mar 2021 11:21:05 +0200 Subject: [PATCH] Add convenience decorators for new listeners (#2064) --- sanic/mixins/listeners.py | 6 ++++++ tests/test_app.py | 14 ++++++++++++++ tests/test_multiprocessing.py | 12 ++++++++++-- 3 files changed, 30 insertions(+), 2 deletions(-) diff --git a/sanic/mixins/listeners.py b/sanic/mixins/listeners.py index bcb56988..90e4895b 100644 --- a/sanic/mixins/listeners.py +++ b/sanic/mixins/listeners.py @@ -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") diff --git a/tests/test_app.py b/tests/test_app.py index 84a41bae..941556ea 100644 --- a/tests/test_app.py +++ b/tests/test_app.py @@ -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 diff --git a/tests/test_multiprocessing.py b/tests/test_multiprocessing.py index ec29b3ae..066b89ac 100644 --- a/tests/test_multiprocessing.py +++ b/tests/test_multiprocessing.py @@ -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 )