Cloud + Python
Cloud SDK patterns — storage, serverless handlers, secrets, and deployment helpers.
Cross Account Role Chaining Mock Credentials in Python
Simulate AWS STS AssumeRole with mock credentials for cross-account role chaining in Python.
import json
class CredentialChain:
def __init__(self, account_id, role_name):
self.account_id = account_id
self.role_name = role_name
self.credentials = {}
def assume_role(self, session_name="mock_session"):
"""Simulate STS AssumeRole, returning mock credentials with expiry.""…
Generate a Mock Presigned URL in Python with HMAC
Build a mock AWS S3 presigned URL using an HMAC-SHA256 signature, mimicking the core SigV4 pattern without cloud SDK dependencies.
import hashlib
import hmac
import time
import base64
def generate_presigned_url_mock(secret_key, bucket, object_key, expires_in=3600):
# Build the canonical request string (simplified AWS SigV4 style)
timestamp = str(int(time.time()))
expiry = str(int(time.time()) + expires_in)
payload = f"GET\n/{buck…
How to Mock AWS SQS Send Receive Delete in Python
Build an in-memory mock of the SQS send, receive, and delete message flow for local testing.
import json
from collections import deque
from uuid import uuid4
class MockSQSQueue:
def __init__(self, name):
self.name = name
self._messages = deque()
self._in_flight = {}
def send_message(self, body, attributes=None):
message_id = str(uuid4())
message = {
…
How to Mock Azure Key Vault Secret Get in Python
Mock an Azure Key Vault client's get_secret method with unittest.mock to test functions that retrieve secret values without hitting the real service.
import unittest
from unittest.mock import MagicMock, patch
def get_secret(key_vault_client, secret_name):
"""Retrieve a secret value from an Azure Key Vault client."""
secret = key_vault_client.get_secret(secret_name)
return secret.value
class TestKeyVaultSecretGet(unittest.TestCase):
def test_get_…
How to Mock RDS Snapshot Create and Restore in Python
Mock AWS RDS snapshot creation and restore operations in Python tests using moto and boto3 without hitting real AWS services.
import boto3
from moto import mock_rds
@mock_rds
def create_and_restore_snapshot():
client = boto3.client("rds", region_name="us-east-1")
client.create_db_instance(
DBInstanceIdentifier="my-db",
DBInstanceClass="db.t3.micro",
Engine="postgres",
AllocatedStorage=20,
Mas…
How to mock boto3 S3 upload file wrapper in Python
Wrap an S3 put_object call in a testable function that returns metadata, and mock boto3 to verify the upload without touching AWS.
import boto3
import io
def upload_file_to_s3(file_obj, bucket, key, object_metadata=None):
"""Upload a file-like object to S3 and return a metadata dict."""
s3 = boto3.client("s3")
content = file_obj.read()
s3.put_object(
Bucket=bucket,
Key=key,
Body=content,
Metadata=…
How to mock boto3 S3 upload in Python
Shows how to mock the boto3 S3 client with unit tests and wrap an upload function to return a dictionary with status details.
import boto3
from unittest.mock import Mock, patch
class S3Uploader:
def __init__(self, bucket_name):
self.bucket_name = bucket_name
self.s3 = boto3.client("s3", region_name="us-east-1")
def upload_file(self, local_path, s3_key):
self.s3.upload_file(local_path, self.bucket_name, s3_ke…
Mock CDK Synth Output in Python for Template Testing
Simulate AWS CDK synth output with MagicMock to test or preview CloudFormation templates without running a real CDK app.
import json
from unittest.mock import MagicMock
def mock_cdk_synth() -> dict:
"""Simulate AWS CDK synth output for a simple S3 bucket."""
cdk_app = MagicMock()
cdk_app.synth.return_value.template = {
"Resources": {
"MyBucket": {
"Type": "AWS::S3::Bucket",
…
Mock GCP storage bucket blob upload in Python
Simulate uploading a blob to a GCP Storage bucket for testing without hitting the cloud.
import io
from datetime import datetime
from unittest.mock import MagicMock, patch
class MockBlob:
"""Simulates a GCP storage blob for unit testing."""
def __init__(self, name):
self.name = name
self.uploaded_at = None
self.content = b""
def upload_from_file(self, file_obj):
…
Mock Google Pub/Sub publish and pull in Python
A lightweight in-memory mock of Google Pub/Sub with publisher/subscriber classes to test topic-based fan-out and message pulling without real infrastructure.
import json
import time
from collections import deque
from dataclasses import dataclass, field
from typing import Any, Callable
@dataclass
class Message:
data: str
attributes: dict[str, str] = field(default_factory=dict)
message_id: str | None = None
ack_id: str | None = None
class MockPublisher:
…
Mock Route53 change_resource_record_sets in Python
This code demonstrates how to mock AWS Route53 change_resource_record_sets API calls using the botocore Stubber, allowing you to test DNS update logic without touching real infrastructure.
import boto3
from botocore.exceptions import ClientError
def mock_change_resource_record_sets():
"""Demonstrates Route53 change_resource_record_sets with a mock client."""
# Create a mock Route53 client
route53 = boto3.client('route53', region_name='us-east-1',
aws_access_key_id…
Mock S3 List Objects Paginator in Python
This code implements a mock S3 paginator that yields pages of object keys, mimicking the behavior of boto3's list_objects_v2 paginator for local testing.
import json
from datetime import datetime, timezone
class MockS3Paginator:
"""A mock S3 list_objects_v2 paginator returning pages of keys."""
def __init__(self, bucket, all_keys, page_size=1000):
self.bucket = bucket
self.all_keys = all_keys
self.page_size = page_size
def pagina…
Mock S3, GCS, and Azure storage with a Python abstract interface
Define an abstract Storage interface and implement a local, filesystem-backed mock so S3, GCS, and Azure code can be tested without cloud dependencies.
from abc import ABC, abstractmethod
from pathlib import Path
class Storage(ABC):
@abstractmethod
def put(self, name: str, data: bytes) -> None:
pass
@abstractmethod
def get(self, name: str) -> bytes:
pass
class LocalStorage(Storage):
def __init__(self, base_dir: str = "mock_sto…
Browse by section
Each section groups closely related Python snippets.
Cloud + Python — Python code examples
What you will find here
This page collects cloud + python snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.