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.
Python code
14 linesimport 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
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
- Use `unittest.mock.patch` as a decorator on the test function instead of a context manager.
- 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
More from Git + Python
- Amend Last Commit Message in Python easy
- Bisect Good Bad Automation Script in Python easy
- Build a Simple Log Graph in Python easy
- Bump Semantic Version Git Tag in Python easy
- Count Unique Contributors from Git Shortlog in Python easy
- Create a Mock GitHub Release API in Python for Testing gh CLI easy
Keep learning
Related tutorials and quizzes for this topic.