From 801595e24acdf8050b8d3ffa512d424147848d32 Mon Sep 17 00:00:00 2001 From: Ashley Sommer Date: Tue, 21 Jan 2020 01:00:48 +1000 Subject: [PATCH] Add server.start_serving and server.serve_forever to AsyncioServer proxy object, to match asyncio-python3.7 example doc, fixes #1754 (#1762) --- sanic/server.py | 20 ++++++++++++++++++++ tests/test_app.py | 18 +++++++++++++++++- 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/sanic/server.py b/sanic/server.py index 47ebcd95..b9e72197 100644 --- a/sanic/server.py +++ b/sanic/server.py @@ -735,6 +735,26 @@ class AsyncioServer: task = asyncio.ensure_future(coro, loop=self.loop) return task + def start_serving(self): + if self.server: + try: + return self.server.start_serving() + except AttributeError: + raise NotImplementedError( + "server.start_serving not available in this version " + "of asyncio or uvloop." + ) + + def serve_forever(self): + if self.server: + try: + return self.server.serve_forever() + except AttributeError: + raise NotImplementedError( + "server.serve_forever not available in this version " + "of asyncio or uvloop." + ) + def __await__(self): """Starts the asyncio server, returns AsyncServerCoro""" task = asyncio.ensure_future(self.serve_coro) diff --git a/tests/test_app.py b/tests/test_app.py index 7fd154ad..6f79ef22 100644 --- a/tests/test_app.py +++ b/tests/test_app.py @@ -44,7 +44,7 @@ def test_create_asyncio_server(app): @pytest.mark.skipif( sys.version_info < (3, 7), reason="requires python3.7 or higher" ) -def test_asyncio_server_start_serving(app): +def test_asyncio_server_no_start_serving(app): if not uvloop_installed(): loop = asyncio.get_event_loop() asyncio_srv_coro = app.create_server( @@ -54,6 +54,22 @@ def test_asyncio_server_start_serving(app): srv = loop.run_until_complete(asyncio_srv_coro) assert srv.is_serving() is False +@pytest.mark.skipif( + sys.version_info < (3, 7), reason="requires python3.7 or higher" +) +def test_asyncio_server_start_serving(app): + if not uvloop_installed(): + loop = asyncio.get_event_loop() + asyncio_srv_coro = app.create_server( + return_asyncio_server=True, + asyncio_server_kwargs=dict(start_serving=False), + ) + srv = loop.run_until_complete(asyncio_srv_coro) + assert srv.is_serving() is False + loop.run_until_complete(srv.start_serving()) + assert srv.is_serving() is True + srv.close() + # Looks like we can't easily test `serve_forever()` def test_app_loop_not_running(app): with pytest.raises(SanicException) as excinfo: