add a flag to skip SIGINT and SIGTERM signals registration

This commit is contained in:
Diogo Dutra 2016-12-29 19:35:41 -02:00
parent f74d44152a
commit 6d1d4ade19
3 changed files with 49 additions and 5 deletions

View File

@ -239,7 +239,7 @@ class Sanic:
def run(self, host="127.0.0.1", port=8000, debug=False, before_start=None,
after_start=None, before_stop=None, after_stop=None, sock=None,
workers=1, loop=None):
workers=1, loop=None, register_sys_signals=True):
"""
Runs the HTTP Server and listens until keyboard interrupt or term
signal. On termination, drains connections before closing.
@ -273,7 +273,8 @@ class Sanic:
'error_handler': self.error_handler,
'request_timeout': self.config.REQUEST_TIMEOUT,
'request_max_size': self.config.REQUEST_MAX_SIZE,
'loop': loop
'loop': loop,
'register_sys_signals': register_sys_signals
}
# -------------------------------------------- #

View File

@ -226,7 +226,8 @@ def trigger_events(events, loop):
def serve(host, port, request_handler, error_handler, before_start=None,
after_start=None, before_stop=None, after_stop=None,
debug=False, request_timeout=60, sock=None,
request_max_size=None, reuse_port=False, loop=None):
request_max_size=None, reuse_port=False, loop=None,
register_sys_signals=True):
"""
Starts asynchronous HTTP Server on an individual process.
:param host: Address to host on
@ -286,6 +287,7 @@ def serve(host, port, request_handler, error_handler, before_start=None,
trigger_events(after_start, loop)
# Register signals for graceful termination
if register_sys_signals:
for _signal in (SIGINT, SIGTERM):
loop.add_signal_handler(_signal, loop.stop)

41
tests/test_sanic.py Normal file
View File

@ -0,0 +1,41 @@
from sanic import Sanic
from sanic.response import HTTPResponse
from sanic.utils import HOST, PORT
from unittest.mock import MagicMock
import pytest
import asyncio
async def stop(app):
await asyncio.sleep(0.2)
app.stop()
def test_register_system_signals():
"""Test if sanic register system signals"""
app = Sanic('test_register_system_signals')
@app.route('/hello')
async def hello_route(request):
return HTTPResponse()
loop = asyncio.new_event_loop()
loop.add_signal_handler = MagicMock()
asyncio.ensure_future(stop(app), loop=loop)
app.run(HOST, PORT, loop=loop)
assert loop.add_signal_handler.called == True
def test_dont_register_system_signals():
"""Test if sanic don't register system signals"""
app = Sanic('test_register_system_signals')
@app.route('/hello')
async def hello_route(request):
return HTTPResponse()
loop = asyncio.new_event_loop()
loop.add_signal_handler = MagicMock()
asyncio.ensure_future(stop(app), loop=loop)
app.run(HOST, PORT, loop=loop, register_sys_signals=False)
assert loop.add_signal_handler.called == False