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.

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

Python code

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

stdout
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

  1. Use `subprocess.run` to call real Git worktree commands in integration tests
  2. 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

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.