How to Mock Git Worktree Creation in Python
Create a mock Git worktree setup with parallel branch directories and state files for testing or simulation.
Python code
31 linesimport os
import tempfile
from pathlib import Path
def create_mock_worktree(base_dir: Path, branches: list[str]) -> dict[str, Path]:
"""
Mock Git worktree creation: creates parallel directories for each branch
under the base directory, simulating independent worktrees.
"""
worktrees = {}
for branch in branches:
branch_dir = base_dir / f"wt-{branch}"
branch_dir.mkdir(parents=True, exist_ok=True)
# Simulate branch-specific state file
(branch_dir / ".branch-state").write_text(f"branch: {branch}\nstatus: ready")
worktrees[branch] = branch_dir
return worktrees
if __name__ == "__main__":
# Simulate adding three parallel branches as worktrees
with tempfile.TemporaryDirectory() as tmpdir:
base = Path(tmpdir)
result = create_mock_worktree(base, ["feature-a", "feature-b", "hotfix-1"])
# Print structure to verify
for branch, path in sorted(result.items()):
state_file = path / ".branch-state"
print(f"Branch: {branch} -> {path}")
print(f" State: {state_file.read_text().strip()}")
print(f"\nTotal worktrees created: {len(result)}")
Output
Branch: feature-a -> /tmp/abc123/wt-feature-a
State: branch: feature-a
status: ready
Branch: feature-b -> /tmp/abc123/wt-feature-b
State: branch: feature-b
status: ready
Branch: hotfix-1 -> /tmp/abc123/wt-hotfix-1
State: branch: hotfix-1
status: ready
Total worktrees created: 3
How it works
This code simulates Git worktree creation without actually running Git commands. Each branch gets its own directory under the base path, named wt-<branch>. A .branch-state file inside each directory mimics branch-specific metadata. Using a TemporaryDirectory ensures cleanup after the demo. The result is a simple dict mapping branch names to directory paths — perfect for testing Git worktree logic that depends on parallel branches.
Common mistakes
- Confusing mock directories with actual `git worktree add` behavior
- Forgetting to handle branch names with slashes (e.g., 'feature/foo')
- Not cleaning up the temp directory when running in production code
- Assuming the mock captures file content from real Git state
Variations
- Use `subprocess.run` to call real Git worktree commands in integration tests
- Create a custom class-based context manager to auto-clean mock worktrees
Real-world use cases
- Test scripts that iterate over multiple parallel feature branches without touching a real repo.
- Simulate multi-worktree environments in CI to verify CI/CD logic before merging.
- Develop and validate automation that manages branch-specific build artifacts or configs.
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.