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.

Easy Python 3.9+ Aug 9, 2026 Cloud + Python 14 views 0 copies

Python code

52 lines
Python 3.9+
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, overwrite=False):
        if not overwrite and self.content:
            raise ValueError("Blob already exists; set overwrite=True")
        self.content = bytes(data)
        self.properties["size"] = len(self.content)
        self.properties["last_modified"] = datetime.now(timezone.utc).isoformat()

    def download(self):
        return io.BytesIO(self.content)

    def to_dict(self):
        return {
            "name": self.name,
            "size": self.properties["size"],
            "last_modified": self.properties["last_modified"],
        }

class MockBlobServiceClient:
    def __init__(self):
        self._blobs = {}

    def get_blob_client(self, container, blob_name):
        key = f"{container}/{blob_name}"
        if key not in self._blobs:
            blob = MockBlob(blob_name)
            blob._container = container
            self._blobs[key] = blob
        return self._blobs[key]

if __name__ == "__main__":
    service = MockBlobServiceClient()
    blob = service.get_blob_client("data", "sample.json")

    payload = {"task": "mock-azure", "count": 3}
    blob.upload(json.dumps(payload).encode("utf-8"), overwrite=True)

    downloaded = json.loads(blob.download().read().decode("utf-8"))
    print("Uploaded metadata:", blob.to_dict())
    print("Downloaded content:", downloaded)

Output

stdout
Uploaded metadata: {'name': 'sample.json', 'size': 31, 'last_modified': '2025-01-01T12:00:00+00:00'}
Downloaded content: {'task': 'mock-azure', 'count': 3}

How it works

The MockBlob class mimics the core Azure SDK interface by storing content as bytes and tracking size and last-modified time. The upload method enforces an overwrite flag, raising an error if the blob already exists and overwrite is false, matching Azure's behavior. download returns a BytesIO stream, so callers can read the content as they would with a real StorageStreamDownloader. The MockBlobServiceClient maintains a dictionary of blobs keyed by container and blob name, recreating the client-side behavior of the Azure SDK. This lets you write unit tests without network calls, making tests fast and deterministic.

Common mistakes

  • Forgetting to set `overwrite=True` when uploading to an existing blob in the mock, causing a ValueError.
  • Not encoding string data to bytes before calling `upload`, leading to a TypeError.
  • Assuming `download()` returns a string instead of a BytesIO stream, requiring `.read()` and `.decode()`.
  • Using a global time in tests without mocking `datetime.now`, making snapshot comparisons flaky.

Variations

  1. Use `unittest.mock` to patch `azure.storage.blob.BlobClient` and return a mock object with side effects.
  2. Implement a mock using pytest fixtures that reset the blob store between tests.

Real-world use cases

  • Unit testing scripts that process files from blob storage without incurring cloud costs or network latency.
  • Writing local integration tests for serverless functions that trigger on blob upload events.
  • Simulating blob storage in CI/CD pipelines where Azure credentials are not available.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Cloud + Python

Related tutorials and quizzes for this topic.