Skip to content

Add test helper for running a specific test in an isolated subprocess #2412

Description

@mdboom

There are 4 places in the code base that run an individual test in an isolated subprocess (to avoid the side effects that test would cause to other tests).

We should refactor that out into a helper. Probably after #2384 which organizes the test helpers.

Here is an agent-generated rough start to such a helper:

import os
import subprocess
import sys
import pytest

# Define an environment variable key to prevent infinite subprocess loops
SUBPROCESS_ENV_KEY = "PYTEST_RUNNING_IN_SUBPROCESS"

@pytest.fixture
def run_in_subprocess(request):
    """
    Reruns the current test inside an isolated python subprocess.
    Skips original in-process execution if triggered.
    """
    # If this token is set, we are already inside the subprocess. Proceed with test logic.
    if os.environ.get(SUBPROCESS_ENV_KEY) == "1":
        yield
        return

    # Build the exact command to re-run only this specific test node
    cmd = [
        sys.executable,  # Current Python interpreter path
        "-m", "pytest",
        request.node.nodeid,  # Specific ID of the active test case
        "-s"  # Allow output to display
    ]

    # Inject the loop prevention variable into the environment
    env = os.environ.copy()
    env[SUBPROCESS_ENV_KEY] = "1"

    # Spawn the subprocess and block until completion
    result = subprocess.run(cmd, env=env)

    # Propagate the subprocess exit status back to the main pytest suite
    if result.returncode != 0:
        pytest.fail(f"Test failed in subprocess with exit code {result.returncode}")

    # Skip standard in-process execution since it has completed externally
    pytest.skip("Test executed successfully inside subprocess.")

Metadata

Metadata

Assignees

Labels

P1Medium priority - Should docuda.coreEverything related to the cuda.core module

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions