Skip to content

Commit

Permalink
Add convenience decorators for new listeners
Browse files Browse the repository at this point in the history
  • Loading branch information
ahopkins committed Mar 16, 2021
1 parent 2fea954 commit 0abe640
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 2 deletions.
6 changes: 6 additions & 0 deletions sanic/mixins/listeners.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,12 @@ def register_listener(listener, event):
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")

Expand Down
14 changes: 14 additions & 0 deletions tests/test_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 10 additions & 2 deletions tests/test_multiprocessing.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,14 +131,22 @@ def main_process_start(app, loop):
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
)

0 comments on commit 0abe640

Please sign in to comment.