Cloud + Python
Cloud SDK patterns — storage, serverless handlers, secrets, and deployment helpers.
Generate an Idempotency-Key header mock with UUID in Python
This code provides a mock idempotency service that generates a UUID-based Idempotency-Key header token and validates it, useful for simulating production API behavior in tests.
import uuid
class MockIdempotencyService:
def __init__(self):
self._tokens = {}
def get_token(self, header_name="Idempotency-Key"):
token = str(uuid.uuid4())
self._tokens[header_name] = token
return token
def validate(self, header_name="Idempotency-Key"):
return s…
How to Create a Mock STS AssumeRole Credentials Dict in Python
Build a realistic AWS STS AssumeRole response dict with temporary credentials, expiry time, and assumed role ARN for local testing.
import json
from datetime import datetime, timedelta, timezone
def mock_sts_credentials(role_arn, session_name, duration=3600):
now = datetime.now(timezone.utc)
expiration = now + timedelta(seconds=duration)
credentials = {
"Credentials": {
"AccessKeyId": "ASIAEXAMPLEACCESSKEY",
…
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 AWS Secrets Manager in Python
Create a lightweight mock of AWS Secrets Manager's get_secret_value API to test secret retrieval without cloud dependencies.
import json
from typing import Optional
class MockSecretsManager:
"""A simple mock of AWS Secrets Manager's get_secret_value API."""
def __init__(self):
self._secrets: dict[str, str] = {}
def create_secret(self, secret_id: str, secret_value: str) -> None:
"""Store a secret value under a…
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 Azure Service Bus Queue in Python
A lightweight in-memory mock of the Azure Service Bus queue API for local testing without cloud dependencies.
import json
import time
from collections import deque
class ServiceBusQueueMock:
def __init__(self, queue_name):
self.queue_name = queue_name
self._messages = deque()
self._dead_letter_queue = deque()
self._message_counter = 0
def send_message(self, body, message_id=None, prop…
How to Mock DynamoDB with a Simple Dict Store in Python
A lightweight in-memory DynamoDB mock that stores items in a dict and supports put, get, and query-by-value operations for local testing.
import json
from typing import Any, Dict, Optional
class MockDynamoDB:
def __init__(self) -> None:
self._store: Dict[str, Dict[str, Any]] = {}
def put_item(self, table_name: str, item: Dict[str, Any]) -> None:
key = str(item.get("id"))
if table_name not in self._store:
se…
How to Mock GCP Cloud Functions HTTP Events in Python
Simulate a GCP Cloud Functions HTTP event with a Python mock handler that constructs a realistic event payload and returns a JSON response.
import json
from datetime import datetime, timezone
def mock_http_event(data):
"""Simulate a GCP Cloud Function HTTP event."""
event = {
"event_id": "mock-event-12345",
"timestamp": datetime.now(timezone.utc).isoformat(),
"event_type": "google.cloud.functions.http",
"resource"…
How to Mock Pulumi Stack Outputs in Python
Create a dict-like mock of Pulumi stack outputs for local testing and scripts without running pulumi.
from collections import defaultdict
class StackOutputMock:
def __init__(self, outputs: dict):
self.outputs = dict(outputs)
def export(self):
return self.outputs
def get(self, key: str, default=None):
return self.outputs.get(key, default)
def keys(self):
r…
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 Azure Blob Upload and Download in Python
Simulate Azure Blob Storage upload and download operations with a lightweight in-memory mock class for testing.
import io
import json
from datetime import datetime, timezone
class MockBlob:
def __init__(self, name):
self.name = name
self.content = b""
self.properties = {
"last_modified": datetime.now(timezone.utc).isoformat(),
"size": 0,
}
def upload(self, data, …
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 CloudWatch put_metric_data in Python
Simulate AWS CloudWatch put_metric_data with validation and formatted output for local testing without AWS.
import json
from datetime import datetime, timezone
def put_metric_data(namespace, metric_data_list):
"""
Mock AWS CloudWatch put_metric_data.
Validates and prints the metrics that would be sent.
"""
timestamp = datetime.now(timezone.utc).isoformat()
print(f"[MockCloudWatch] Received request …
Mock ECS Task Run Stop Status Dict in Python
Build a mock ECS task status dictionary with RUNNING/STOPPED states using the standard library.
from datetime import datetime, timezone
def mock_ecs_task_status(task_id: str, state: str = "RUNNING") -> dict:
"""Return a mock ECS task status dictionary."""
return {
"taskArn": f"arn:aws:ecs:us-east-1:123456789012:task/cluster/{task_id}",
"taskDefinition": "arn:aws:ecs:us-east-1:1234567890…
Mock GCP Secret Manager access version in Python
A minimal mock of GCP Secret Manager that stores secret versions, retrieves payloads by version, and logs access timestamps.
import json
import time
from datetime import datetime, timezone
class MockSecretManager:
"""Minimal mock of GCP Secret Manager access/version behavior."""
def __init__(self):
self._secrets = {}
self._access_log = []
def create_secret(self, secret_id: str, payload: str) -> dict:
…
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 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…
Mock SNS publish subscribe fanout in Python
Simulates AWS SNS publish/subscribe with an in-memory topic-to-endpoints dict that fans out messages to all subscribers.
class SNSMock:
def __init__(self):
self.topics = {}
def create_topic(self, name):
if name not in self.topics:
self.topics[name] = []
return f"arn:aws:sns:us-east-1:123456789012:{name}"
def subscribe(self, topic_name, endpoint):
self.topics.setdefault(topic_name…
Mock SSM Parameter Store Get Parameters by Path in Python
This code implements a simple mock of the AWS SSM Parameter Store get_parameters_by_path API, returning parameters under a given path with recursive and non-recursive options.
import json
class MockSSM:
def __init__(self, parameters):
self.parameters = parameters
def get_parameters_by_path(self, path, recursive=True):
result = []
for key, value in self.parameters.items():
if recursive:
if key.startswith(path):
…
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.