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.
Python code
29 linesfrom 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
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
- Use `patch.object(repo, 'cherry_pick')` if the method exists directly on the repo object
- 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
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.