pytest-subprocess

1.5.4 · active · verified Sun Apr 12

pytest-subprocess is a pytest plugin that allows faking the behavior of `subprocess` calls within tests, eliminating the need to rely on actual external processes. It hooks into `subprocess.Popen()` and consequently handles `subprocess.run()`, `subprocess.call()`, `subprocess.check_call()`, and `subprocess.check_output()` methods. The library is actively maintained with regular releases, ensuring compatibility and new features.

Warnings

Install

Imports

Quickstart

This example demonstrates how to use the `fp` (alias for `fake_process`) fixture to register a command and define its `stdout`. When `subprocess.run()` is called with the registered command, `pytest-subprocess` intercepts it and provides the faked output and return code.

import subprocess
import pytest

def test_process_command(fp):
    # Register a fake command and its expected output
    fp.register(['fake-command'], stdout='Hello from fake-command')

    # Run the command using subprocess (it will be faked by pytest-subprocess)
    process = subprocess.run(['fake-command'], capture_output=True, text=True)

    # Assert on the faked process's behavior
    assert process.returncode == 0
    assert process.stdout.strip() == 'Hello from fake-command'

def test_command_with_args(fp):
    fp.register(['greet', 'world'], stdout='Greeting world!')
    process = subprocess.run(['greet', 'world'], capture_output=True, text=True)
    assert process.returncode == 0
    assert process.stdout.strip() == 'Greeting world!'

view raw JSON →