Skip to content

Lesson 9 of 9 · 23m

Testing and Packaging Ops Tools

Unit testing operational logic, faking external systems at the right boundary, integration smoke tests, dependency pinning, virtual environments, and safe rollout.

Ops code often skips testing because "it is just a script." Then the script becomes load-bearing, another team depends on its output, and nobody knows whether a refactor changes behavior. The fix is placing tests at the boundaries where mistakes are expensive.

Test logic, not process plumbing

If core behavior is separate from argparse and sys.exit, unit tests are straightforward:

def test_selects_oldest_backups_for_pruning(tmp_path):
    backups = [make_backup(tmp_path, f'db-{day}.sql') for day in range(10)]
    doomed = choose_prune_candidates(backups, keep=7)
    assert len(doomed) == 3

tmp_path gives every test an isolated filesystem. Use real files for filesystem logic; mocking Path usually tests the mock framework more than your code.

Fake external systems at the boundary

Do not patch ten internals. Define a narrow adapter around subprocess, SSH, or cloud APIs:

class Runner:
    def run(self, argv, timeout):
        return subprocess.run(argv, check=True, timeout=timeout, capture_output=True, text=True)

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

A fake implementing the same small interface can record commands and return controlled stdout, stderr, and exit codes. Tests verify construction, timeouts, and error handling without touching real machines. For boto3, use botocore.stub.Stubber; moto or LocalStack can support broader workflows, but neither proves IAM, throttling, or production consistency behavior.

Integration tests should be small and deliberate

A useful smoke test asks whether the installed artifact runs realistically:

python -m venv /tmp/tooltest
/tmp/tooltest/bin/pip install dist/backupctl-1.4.0-py3-none-any.whl
/tmp/tooltest/bin/backupctl --config fixtures/test.toml --dry-run

This catches missing package data, bad entry points, undeclared dependencies, and interpreter-version problems.

Package like you expect upgrades

[project]
name = "backupctl"
version = "1.4.0"
dependencies = ["boto3>=1.34,<2", "paramiko>=3.4,<4"]
[project.scripts]
backupctl = "backupctl.cli:main"

Use a virtual environment or installable package and keep the runtime away from system Python. Pin ranges wide enough for security updates but narrow enough to avoid surprise major-version upgrades. Roll out to one host, inspect logs, dry-run, apply, then expand. Rollback should mean installing the previous artifact, not editing Python on production machines.

Field notes

  • Tests that shell out to real production APIs are uncontrolled production changes.
  • Freeze time when testing retention logic; month boundaries and leap years are treacherous.
  • Include ugly fixtures: spaces in filenames, missing metadata, empty output, unicode.

Was this lesson helpful?

Sign in to rate