I want to test interactions between a server MyServer
and client MyClient
using pytest. The server is async, and has an async start()
method. Here is my setup:
import pytest
from .server import MyServer
from .client import MyClient
PORT = 8765
HOST = "127.0.0.1"
async def run_server():
await MyServer().start(host=HOST, port=PORT)
@pytest.fixture
def client():
return MyClient(host=HOST, port=PORT)
@pytest.mark.asyncio
async def test_can_get_response(client):
response = await client.call_server()
assert response is not None
I need the server to be booted up and run in the background when the tests run. There is a very simple solution here: before running pytest, just run a python file that calls run_server()
, but it would be neater if I could boot up the server in this test file, so the server gets destroyed at the end.
My first instinct is to use threading:
from threading import Thread
Thread(target=run_server).start()
However, the tests get run before the thread has time to start:
Task was destroyed but it is pending!
task: <Task pending name='Task-2' coro=<run_server() running at /path/to/file> wait_for=<_GatheringFuture pending cb=[<TaskWakeupMethWrapper object at 0x105fc90a0>()]>>
Task was destroyed but it is pending!
Adding a time.sleep()
so the server has time to boot doesn't make a difference, the tests run immediately.
I believe another alternative is to use a fixture, i.e. booting up the server for the course of each test. I attempted the following:
@pytest.fixture
async def run_server():
await MyServer().start(host=HOST, port=PORT)
@pytest.fixture
def client():
return MyClient(host=HOST, port=PORT)
@pytest.mark.asyncio
async def test_can_get_response(client, run_server):
await run_server # Not run_server() because the fixture is already a coroutine
response = await client.call_server()
assert response is not None
This boots up the server as expected, but not in the background: MyServer().start()
runs forever and blocks the tests from running.
How can I start my server in the background and run it over the course of the tests?