How to Mock subprocess.run in Python Tests

Mock subprocess.run to test a Git submodule update command without executing it in your test suite.

Easy Python 3.9+ Aug 9, 2026 Git + Python 13 views 0 copies

Python code

14 lines
Python 3.9+
import subprocess
from unittest.mock import Mock, patch

def update_submodules():
    subprocess.run(["git", "submodule", "update", "--init", "--recursive"], check=True)

with patch("subprocess.run") as mock_run:
    mock_run.return_value = Mock(returncode=0)
    update_submodules()
    mock_run.assert_called_once_with(
        ["git", "submodule", "update", "--init", "--recursive"],
        check=True
    )
    print("Submodule update command executed successfully")

Output

stdout
Submodule update command executed successfully

How it works

The patch context manager replaces subprocess.run with a Mock object, so the real command is never executed. The mock's return_value is set to a Mock with returncode=0 to simulate a successful run. assert_called_once_with verifies the exact command and arguments were passed, ensuring your function behaves correctly. This approach isolates the test from the actual Git repository state and avoids side effects.

Common mistakes

  • Forgetting to include `check=True` in the assertion if the original call uses it.
  • Patching `subprocess.run` without a context manager, which can leave the mock active for other tests.
  • Assuming the mock's return value provides a `returncode` attribute without setting it.

Variations

  1. Use `unittest.mock.patch` as a decorator on the test function instead of a context manager.
  2. Set `mock_run.side_effect = subprocess.CalledProcessError(1, cmd)` to test failure handling.

Real-world use cases

  • Unit testing a deployment script that runs Git commands without modifying a real repository.
  • Verifying that a CI pipeline step calls the correct subprocess with expected arguments.
  • Simulating Git submodule behavior in a test environment where Git is not installed.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Git + Python

Related tutorials and quizzes for this topic.