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.

Medium Python 3.9+ Aug 9, 2026 Git + Python 12 views 0 copies

Requires third-party packages — install first
pip install GitPython

Python code

26 lines
Python 3.9+
import 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

stdout
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

  1. Use `repo.git.rev_parse('--abbrev-ref', 'HEAD')` as an alternative to `repo.active_branch`.
  2. 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

Run locally

This sample needs third-party packages, so it cannot run in the browser IDE. Copy the code above, install the packages shown at the top, then run it in your own Python environment.

More from Git + Python

Related tutorials and quizzes for this topic.