From ed8725bf6c6e9392b9344da59e077c16c3123d02 Mon Sep 17 00:00:00 2001 From: Jeong YunWon Date: Mon, 6 Nov 2017 17:26:11 +0900 Subject: [PATCH] Let SanicTestClient has its own port For parallel test running, the servers must have different ports. See examples/pytest_xdist.py for example. --- examples/pytest_xdist.py | 49 ++++++++++++++++++++++++++++++++++++++++ sanic/testing.py | 7 +++--- 2 files changed, 53 insertions(+), 3 deletions(-) create mode 100644 examples/pytest_xdist.py diff --git a/examples/pytest_xdist.py b/examples/pytest_xdist.py new file mode 100644 index 00000000..06730016 --- /dev/null +++ b/examples/pytest_xdist.py @@ -0,0 +1,49 @@ +"""pytest-xdist example for sanic server + +Install testing tools: + + $ pip install pytest pytest-xdist + +Run with xdist params: + + $ pytest examples/pytest_xdist.py -n 8 # 8 workers +""" +import re +from sanic import Sanic +from sanic.response import text +from sanic.testing import PORT as PORT_BASE, SanicTestClient +import pytest + + +@pytest.fixture(scope="session") +def test_port(worker_id): + m = re.search(r'[0-9]+', worker_id) + if m: + num_id = m.group(0) + else: + num_id = 0 + port = PORT_BASE + int(num_id) + return port + + +@pytest.fixture(scope="session") +def app(): + app = Sanic() + + @app.route('/') + async def index(request): + return text('OK') + + return app + + +@pytest.fixture(scope="session") +def client(app, test_port): + return SanicTestClient(app, test_port) + + +@pytest.mark.parametrize('run_id', range(100)) +def test_index(client, run_id): + request, response = client._sanic_endpoint_test('get', '/') + assert response.status == 200 + assert response.text == 'OK' diff --git a/sanic/testing.py b/sanic/testing.py index ef54537b..873e43f7 100644 --- a/sanic/testing.py +++ b/sanic/testing.py @@ -8,8 +8,9 @@ PORT = 42101 class SanicTestClient: - def __init__(self, app): + def __init__(self, app, port=PORT): self.app = app + self.port = port async def _local_request(self, method, uri, cookies=None, *args, **kwargs): import aiohttp @@ -17,7 +18,7 @@ class SanicTestClient: url = uri else: url = 'http://{host}:{port}{uri}'.format( - host=HOST, port=PORT, uri=uri) + host=HOST, port=self.port, uri=uri) logger.info(url) conn = aiohttp.TCPConnector(verify_ssl=False) @@ -66,7 +67,7 @@ class SanicTestClient: exceptions.append(e) self.app.stop() - self.app.run(host=HOST, debug=debug, port=PORT, **server_kwargs) + self.app.run(host=HOST, debug=debug, port=self.port, **server_kwargs) self.app.listeners['after_server_start'].pop() if exceptions: