How to Mock Git Cherry-Pick in Python for Tests

Mock the `repo.git.cherry_pick` method with `unittest.mock` to test a Git cherry-pick helper without a real repository.

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

Python code

29 lines
Python 3.9+
from unittest.mock import patch, MagicMock

class GitCherryPicker:
    def __init__(self):
        self.applied_commits = []
    
    def cherry_pick(self, commit_hash, repo):
        try:
            result = repo.git.cherry_pick(commit_hash)
            self.applied_commits.append(commit_hash)
            return f"Applied commit {commit_hash}"
        except Exception as e:
            return f"Conflict: {commit_hash} - {str(e)}"
    
    def list_applied(self):
        return self.applied_commits

def apply_mock_cherry_pick():
    with patch('unittest.mock.MagicMock') as mock_repo:
        mock_repo.git.cherry_pick.return_value = "Success"
        cherry_picker = GitCherryPicker()
        result = cherry_picker.cherry_pick("abc123", mock_repo)
        applied = cherry_picker.list_applied()
        return result, applied

if __name__ == "__main__":
    result, applied = apply_mock_cherry_pick()
    print(f"Result: {result}")
    print(f"Applied commits: {applied}")

Output

stdout
Result: Applied commit abc123
Applied commits: ['abc123']

How it works

The GitCherryPicker class wraps a git repository object and calls repo.git.cherry_pick to apply a commit. The test uses MagicMock to create a fake repository where cherry_pick returns "Success", simulating a clean cherry-pick. patch replaces the mock's return_value, and the captured result is appended to the class's tracking list. This isolates the unit under test from real git operations, making tests fast and deterministic. The with block ensures the mock is properly cleaned up after the test.

Common mistakes

  • Mocking the wrong object, e.g., patching `repo.git` instead of `repo.git.cherry_pick`
  • Forgetting to assert that the mock was called with the correct commit hash
  • Not resetting mock state between tests, leading to unexpected side effects
  • Assuming the real `repo.git` object exists instead of creating a MagicMock

Variations

  1. Use `patch.object(repo, 'cherry_pick')` if the method exists directly on the repo object
  2. Use `patch('git.Repo')` to mock the entire Repo class constructor

Real-world use cases

  • Testing a CLI tool that automates cherry-picking commits between branches without touching a real git repo.
  • Unit-testing a Git release script that applies hotfix commits, using mocks to avoid modifying the team's shared repository.
  • Verifying commit-application logic in CI automation that needs deterministic behavior for pipeline testing.

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.