Listeners for main server process (#2018)

* Initial POC

* Add test case

* Resolve create_server and Gunicorn serve)

* add testr coverage
This commit is contained in:
Adam Hopkins
2021-03-01 15:03:26 +02:00
committed by GitHub
parent 170177feb0
commit 4b968dc611
6 changed files with 99 additions and 3 deletions

View File

@@ -70,6 +70,20 @@ def test_asyncio_server_start_serving(app):
# Looks like we can't easily test `serve_forever()`
def test_create_server_main(app, caplog):
app.listener("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

@@ -1,3 +1,4 @@
import logging
import multiprocessing
import pickle
import random
@@ -8,6 +9,7 @@ import pytest
from sanic_testing.testing import HOST, PORT
from sanic import Blueprint
from sanic.log import logger
from sanic.response import text
@@ -108,3 +110,35 @@ def test_pickle_app_with_static(app, protocol):
assert up_p_app
request, response = up_p_app.test_client.get("/static/missing.txt")
assert response.status == 404
def test_main_process_event(app, caplog):
# Selects a number at random so we can spot check
num_workers = random.choice(range(2, multiprocessing.cpu_count() * 2 + 1))
def stop_on_alarm(*args):
for process in multiprocessing.active_children():
process.terminate()
signal.signal(signal.SIGALRM, stop_on_alarm)
signal.alarm(1)
@app.listener("main_process_start")
def main_process_start(app, loop):
logger.info("main_process_start")
@app.listener("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
)
assert (
caplog.record_tuples.count(("sanic.root", 20, "main_process_stop"))
== 1
)