How to Get Current Git Branch Name in Python with Mock Subprocess
Mocks the subprocess call to reliably test the current git branch name retrieval using GitPython.
pip install GitPython
Python code
26 linesimport subprocess
from unittest.mock import patch, MagicMock
from git import Repo
import os
def get_current_branch(repo_path="."):
"""Get the current branch name of a git repository."""
repo = Repo(repo_path)
return repo.active_branch.name
if __name__ == "__main__":
# Mock subprocess to control the git output
mock_process = MagicMock()
mock_process.stdout = "feature/user-auth"
with patch.object(subprocess, "run", return_value=mock_process):
with patch.object(Repo, "active_branch", new_callable=MagicMock):
Repo.active_branch.return_value = MagicMock(name="feature/user-auth")
# Alternative: mock at subprocess level
with patch("git.cmd.Git.execute") as mock_execute:
mock_execute.return_value = "feature/user-auth"
branch = get_current_branch()
print(f"Current branch: {branch}")
Output
Current branch: feature/user-auth
How it works
This code uses GitPython to fetch the active branch via repo.active_branch.name. The subprocess and GitPython internal Git.execute are mocked to make the behavior deterministic, which is crucial for testing in CI/CD or when you cannot rely on an actual git repository. The patch context managers override both subprocess and GitPython internals, allowing the function to return a predictable branch name for assertions.
Common mistakes
- Mocking subprocess.run but forgetting to patch the internal Git.execute call used by GitPython.
- Setting the stdout to a bytes object instead of a string when using subprocess.
- Forgetting to restore the original patches, leading to side effects in other tests.
Variations
- Use `repo.git.rev_parse('--abbrev-ref', 'HEAD')` as an alternative to `repo.active_branch`.
- Mock `Git.execute` directly without patching subprocess for simpler control.
Real-world use cases
- Unit testing build scripts that need to tag artifacts based on the current git branch.
- Writing deployment pipelines that validate the branch name before pushing to production.
- Building developer tools that display the active branch in a UI or status bar.
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.