pytest-xprocess: Pytest Plugin for External Process Management

1.0.2 · active · verified Thu Apr 16

pytest-xprocess is a pytest plugin designed for robust management of external processes across test runs. It ensures that essential external processes, upon which an application depends, are started and properly terminated during pytest execution. The current version is 1.0.2, and the project maintains an active release cadence, with several updates per year, often coinciding with new Python or pytest versions.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a process fixture using `pytest-xprocess` in a `conftest.py` file. It sets up a simple dummy server, waits for a specific pattern in its output to confirm readiness, and then allows tests to run against it. The `xprocess.ensure()` method guarantees the process is started and managed, including automatic cleanup after the test session.

import pytest
import os
import time

# This content would typically be in conftest.py
# For demonstration, we'll create a dummy server script
# and then use it in the quickstart.

dummy_server_script = """
# dummy_server.py
import time
import sys

if __name__ == '__main__':
    print("Dummy server starting...")
    sys.stdout.flush()
    time.sleep(1) # Simulate startup time
    print("Dummy server ready on port 12345")
    sys.stdout.flush()
    try:
        while True:
            time.sleep(0.5)
    except KeyboardInterrupt:
        print("Dummy server shutting down.")
        sys.stdout.flush()
"""

# Ensure the dummy server script exists for the quickstart to run
with open("dummy_server.py", "w") as f:
    f.write(dummy_server_script)

@pytest.fixture(scope="session")
def dummy_server(xprocess):
    class Starter(xprocess.ProcessStarter):
        # Path to the dummy server script
        # Use absolute path to ensure it's found regardless of cwd
        script_path = os.path.abspath("dummy_server.py")
        pattern = "Dummy server ready on port 12345"
        args = ["python", script_path]

        # Optional: increase timeout if the server takes longer to start
        # timeout = 5 # Default is 120 seconds

    # Ensure the process is running; get its logfile and info object
    logfile = xprocess.ensure("dummy_server", Starter)
    
    # You can interact with the server here if needed, e.g., check its status
    # process_info = xprocess.getinfo("dummy_server")
    # assert process_info.isrunning()
    
    print(f"\nDummy server log: {logfile.name}")
    
    # Yield control to the tests that depend on this fixture
    yield logfile

    # xprocess automatically handles termination after tests, but you can
    # also get the info object and terminate manually if needed.
    # xprocess.getinfo("dummy_server").terminate()

def test_server_is_up(dummy_server):
    # The dummy_server fixture ensures the server is running.
    # You can read its log for verification or perform other checks.
    with open(dummy_server.name, "r") as f:
        logs = f.read()
    assert "Dummy server ready on port 12345" in logs
    print("Test: Dummy server is confirmed ready!")

# To run this, save as a .py file (e.g., test_quickstart.py) and run `pytest -s`
# The -s flag is important to see print statements from the fixture and tests.

view raw JSON →