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.
pip install fabric
Python code
34 linesfrom 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
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
- Use `unittest.mock.patch('fabric.Connection')` to replace the real class in tests.
- 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
More from Modern tooling
- Build a Recipe Runner Mock in Python easy
- Build a Textual TUI App Skeleton in Python easy
- Configure ruff linter rules in pyproject.toml with Python easy
- Data Conversion Helper Functions in Python easy
- How to Bind and Mock structlog Context in Python medium
- How to Build a Chainable Filter Helper in Python easy
Keep learning
Related tutorials and quizzes for this topic.