Interview Prep/Python for DevOps/Testing, services & metrics

How do you structure code so it is easy to test?

AdvancedConceptTesting, services & metrics
Answer
  • Dependency injection: pass clients, clocks and config into functions instead of creating them inside (def old_snapshots(ec2, now, max_age)).
  • Separate pure logic (decide what is non-compliant) from I/O (fetch and act).
  • Keep the CLI layer thin: parse args, build clients, call functions, render, exit.
  • Avoid module-level side effects (clients created at import, basicConfig in modules).
  • Return data instead of printing.

Code written this way can be tested with plain dicts in milliseconds, and moto covers the thin I/O layer.

All Python for DevOps questions Roadmap: Python for automation

More on Testing, services & metrics