2017-11-06 08:26:11 +00:00
|
|
|
"""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
|
2021-03-10 09:19:38 +00:00
|
|
|
|
|
|
|
import pytest
|
|
|
|
from sanic_testing import SanicTestClient
|
|
|
|
from sanic_testing.testing import PORT as PORT_BASE
|
|
|
|
|
2017-11-06 08:26:11 +00:00
|
|
|
from sanic import Sanic
|
|
|
|
from sanic.response import text
|
|
|
|
|
|
|
|
|
|
|
|
@pytest.fixture(scope="session")
|
|
|
|
def test_port(worker_id):
|
2021-03-10 09:19:38 +00:00
|
|
|
m = re.search(r"[0-9]+", worker_id)
|
2017-11-06 08:26:11 +00:00
|
|
|
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():
|
2021-12-23 22:30:27 +00:00
|
|
|
app = Sanic("Example")
|
2017-11-06 08:26:11 +00:00
|
|
|
|
2021-03-10 09:19:38 +00:00
|
|
|
@app.route("/")
|
2017-11-06 08:26:11 +00:00
|
|
|
async def index(request):
|
2021-03-10 09:19:38 +00:00
|
|
|
return text("OK")
|
2017-11-06 08:26:11 +00:00
|
|
|
|
|
|
|
return app
|
|
|
|
|
|
|
|
|
|
|
|
@pytest.fixture(scope="session")
|
|
|
|
def client(app, test_port):
|
|
|
|
return SanicTestClient(app, test_port)
|
|
|
|
|
|
|
|
|
2021-03-10 09:19:38 +00:00
|
|
|
@pytest.mark.parametrize("run_id", range(100))
|
2017-11-06 08:26:11 +00:00
|
|
|
def test_index(client, run_id):
|
2021-03-10 09:19:38 +00:00
|
|
|
request, response = client._sanic_endpoint_test("get", "/")
|
2017-11-06 08:26:11 +00:00
|
|
|
assert response.status == 200
|
2021-03-10 09:19:38 +00:00
|
|
|
assert response.text == "OK"
|