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,
basicConfigin 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.
More on Testing, services & metrics
Why should automation scripts have tests at all?BeginnerHow does pytest discover and run tests?BeginnerWhy does pytest use plain `assert` instead of `assertEqual`?BeginnerWhat are pytest fixtures, and what scopes exist?IntermediateWhat built-in fixtures do you use most?IntermediateHow does `@pytest.mark.parametrize` work?Beginner