From 571b5b544d2c9533f63beaee95550b4567fe218a Mon Sep 17 00:00:00 2001 From: Stephan Fitzpatrick Date: Fri, 9 Feb 2018 14:01:17 -0800 Subject: [PATCH] added app.register_listener method w/test --- sanic/app.py | 15 +++++++++++++++ tests/test_server_events.py | 17 +++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/sanic/app.py b/sanic/app.py index 6e8377f5..42206b36 100644 --- a/sanic/app.py +++ b/sanic/app.py @@ -117,6 +117,21 @@ class Sanic: return decorator + def register_listener(self, listener, event): + """ + Register the listener for a given event. + + Args: + listener: callable i.e. setup_db(app, loop) + + event: when to register listener i.e. 'before_server_start' + + Returns: listener + + """ + + return self.listener(event)(listener) + # Decorator def route(self, uri, methods=frozenset({'GET'}), host=None, strict_slashes=None, stream=False, version=None, name=None): diff --git a/tests/test_server_events.py b/tests/test_server_events.py index ab0a1fb1..9c0d99eb 100644 --- a/tests/test_server_events.py +++ b/tests/test_server_events.py @@ -49,6 +49,23 @@ def test_single_listener(listener_name): assert random_name_app.name + listener_name == output.pop() +@pytest.mark.parametrize('listener_name', AVAILABLE_LISTENERS) +def test_register_listener(listener_name): + """ + Test that listeners on their own work with + app.register_listener method + """ + random_name_app = Sanic(''.join( + [choice(ascii_letters) for _ in range(choice(range(5, 10)))])) + output = list() + # Register listener + listener = create_listener(listener_name, output) + random_name_app.register_listener(listener, + event=listener_name) + start_stop_app(random_name_app) + assert random_name_app.name + listener_name == output.pop() + + def test_all_listeners(): random_name_app = Sanic(''.join( [choice(ascii_letters) for _ in range(choice(range(5, 10)))]))