How to Mock Fabric Connections in Python for Task Testing

Create a lightweight MockConnection class to replace fabric.Connection and test task functions without SSH.

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

Requires third-party packages — install first
pip install fabric

Python code

34 lines
Python 3.9+
from fabric import Connection


class MockConnection:
    """Minimal mock of fabric.Connection for task testing."""

    def __init__(self):
        self.commands = []

    def run(self, command, **kwargs):
        self.commands.append(command)
        return f"OK: {command}"


def deploy(conn):
    """Deploy the app: install deps, migrate, restart."""
    conn.run("pip install -r requirements.txt")
    conn.run("python manage.py migrate")
    conn.run("systemctl restart app")


def healthcheck(conn):
    """Check basic system health metrics."""
    conn.run("free -m")
    conn.run("df -h /")


if __name__ == "__main__":
    mock = MockConnection()
    deploy(mock)
    healthcheck(mock)

    for cmd in mock.commands:
        print(cmd)

Output

stdout
pip install -r requirements.txt
python manage.py migrate
systemctl restart app
free -m
df -h /

How it works

This example defines a MockConnection class that mimics the run() method of fabric's Connection. It records each command to a list instead of executing it, allowing you to verify the sequence of calls without needing a real server. The task functions deploy() and healthcheck() accept any object with a run() method, making them easy to swap between mock and real connections. This is a common pattern for unit testing infrastructure automation code.

Common mistakes

  • Mocking only `run` but forgetting `put` or `get` if used.
  • Not capturing `sudo` or `with` context manager calls in your mock.
  • Forgetting to assert the command order when using a real connection in tests.

Variations

  1. Use `unittest.mock.patch('fabric.Connection')` to replace the real class in tests.
  2. Implement a fake response object that returns structured output for your commands.

Real-world use cases

  • Unit testing deployment scripts before running them against production servers.
  • Validating the order of commands in a CI/CD pipeline without SSH access.
  • Simulating remote execution for integration tests in a sandboxed environment.

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 Modern tooling

Related tutorials and quizzes for this topic.