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.
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