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

What is moto, and how do you use it with pytest?

IntermediateConceptTesting, services & metrics
Answer

moto mocks AWS services in-process by intercepting botocore's HTTP layer, keeping a fake in-memory backend that behaves like the real API. In moto 5, a single mock_aws decorator or context manager covers all services.

from moto import mock_aws

@pytest.fixture
def s3():
    with mock_aws():
        c = boto3.client("s3", region_name="us-east-1")
        c.create_bucket(Bucket="test")
        yield c

def test_upload(s3):
    upload_report(s3, "test", "r.json", b"{}")
    assert s3.get_object(Bucket="test", Key="r.json")["Body"].read() == b"{}"

Always set fake credentials in env (AWS_ACCESS_KEY_ID=testing) so a bug can never reach a real account.

All Python for DevOps questions Roadmap: Python for automation

More on Testing, services & metrics