Reference library

Cloud + Python

Cloud SDK patterns — storage, serverless handlers, secrets, and deployment helpers.

42 matches
Cloud + Python medium

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.

boto3 s3 aws
Python
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=…
13 0 Open
Cloud + Python medium

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.

boto3 s3 mocking
Python
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…
12 0 Open
Cloud + Python easy

How to plan reserved capacity from a CSV in Python

Read a CSV of workloads with csv.DictReader and compute a mock reserved capacity plan with headroom per service.

csv capacity-planning cloud
Python
import csv
import io


def plan_reserved_capacity(workloads_csv: str) -> list[dict]:
    """Read a CSV of workloads and return a plan for reserved capacity per service."""
    reader = csv.DictReader(io.StringIO(workloads_csv))
    plan = []
    for row in reader:
        service = row["service"]
        avg_load = fl…
11 0 Open
Cloud + Python easy

Mock AWS Spot Instance Interruption Handler in Python

A Python class that simulates AWS Spot instance interruption checks, handling the 10% chance of termination, logging state-saving, and storing notice details.

aws spot-instances simulation
Python
import time
import random

class SpotInstanceHandler:
    def __init__(self, instance_id):
        self.instance_id = instance_id
        self.interruption_notices = []

    def start(self):
        print(f"Spot instance {self.instance_id} started")

    def check_interruption(self):
        # Simulate random interrup…
13 0 Open
Cloud + Python easy

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.

azure mock testing
Python
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, …
14 0 Open
Cloud + Python medium

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.

aws cdk cloudformation
Python
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",
              …
12 0 Open
Cloud + Python easy

Mock CloudWatch put_metric_data in Python

Simulate AWS CloudWatch put_metric_data with validation and formatted output for local testing without AWS.

cloudwatch aws mock
Python
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 …
15 0 Open
Cloud + Python easy

Mock ECS Task Run Stop Status Dict in Python

Build a mock ECS task status dictionary with RUNNING/STOPPED states using the standard library.

aws ecs mocking
Python
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…
15 0 Open
Cloud + Python easy

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.

gcp secret-manager mock
Python
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:
        …
15 0 Open
Cloud + Python medium

Mock GCP storage bucket blob upload in Python

Simulate uploading a blob to a GCP Storage bucket for testing without hitting the cloud.

gcp mock storage
Python
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):
    …
14 0 Open
Cloud + Python medium

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.

pubsub gcp testing
Python
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:
 …
15 0 Open
Cloud + Python easy

Mock Lambda handler event context dict in Python

Simulates an AWS Lambda invocation by passing a mock event dict and context object to a handler, then prints the response.

lambda aws mock
Python
import json


def lambda_handler(event, context):
    """
    A mock AWS Lambda handler that processes an event dict and context object.
    Demonstrates the typical Lambda function signature and basic event/context usage.
    """
    print("Received event:", json.dumps(event, indent=2))
    print("Function name:", co…
14 0 Open
Cloud + Python medium

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.

aws route53 boto3
Python
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…
14 0 Open
Cloud + Python medium

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.

s3 mock paginator
Python
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…
13 0 Open
Cloud + Python medium

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.

storage abstraction testing
Python
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…
14 0 Open
Cloud + Python easy

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.

aws sns pub-sub
Python
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…
13 0 Open
Cloud + Python easy

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.

aws ssm parameter-store
Python
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):
                   …
16 0 Open
Cloud + Python easy

Pick a Random Region with Mock Carbon Intensity in Python

Selects a random region from a list and generates a mock carbon intensity value using Python's random module.

random mock-data cloud
Python
import random

def pick_region_intensity(regions, seed=42):
    random.seed(seed)
    selected = random.choice(regions)
    intensity = random.randint(1, 10)
    return selected, intensity

if __name__ == "__main__":
    regions = ["North", "South", "East", "West"]
    selected, intensity = pick_region_intensity(regio…
14 0 Open

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.