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.

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

Python code

40 lines
Python 3.9+
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 given ID."""
        self._secrets[secret_id] = secret_value

    def get_secret_value(self, secret_id: str) -> Optional[str]:
        """Fetch a secret's string value by ID, or None if not found."""
        return self._secrets.get(secret_id)


if __name__ == "__main__":
    mock_client = MockSecretsManager()

    # Seed with sample data
    mock_client.create_secret("prod/db/password", "s3cr3t-p@ssw0rd")
    mock_client.create_secret("dev/api/key", "dev_key_12345")

    # Fetch and display results
    db_secret = mock_client.get_secret_value("prod/db/password")
    api_secret = mock_client.get_secret_value("dev/api/key")
    missing_secret = mock_client.get_secret_value("nonexistent/secret")

    print(f"DB password: {db_secret}")
    print(f"API key: {api_secret}")
    print(f"Missing secret: {missing_secret}")

    # Demonstrate parsing as JSON
    mock_client.create_secret("service/config", json.dumps({"timeout": 30, "retries": 3}))
    config_raw = mock_client.get_secret_value("service/config")
    config = json.loads(config_raw) if config_raw else {}
    print(f"Config timeout: {config.get('timeout')}")

Output

stdout
DB password: s3cr3t-p@ssw0rd
API key: dev_key_12345
Missing secret: None
Config timeout: 30

How it works

The MockSecretsManager class stores secrets in an internal dictionary keyed by secret ID, mirroring how Secrets Manager organizes data. The get_secret_value method uses .get() to safely return None for missing secrets instead of raising an exception. The if __name__ == '__main__' block seeds sample secrets and demonstrates both direct string retrieval and JSON parsing. This approach lets you test code that depends on Secrets Manager without making real AWS calls or mocking the boto3 client. The mock maintains the same method signature as the real AWS SDK, making it a drop-in replacement for unit tests.

Common mistakes

  • Forgetting that real Secrets Manager returns bytes, not strings
  • Not handling None when a secret ID doesn't exist
  • Hardcoding secret values instead of seeding them via create_secret

Variations

  1. Use unittest.mock.patch to replace boto3 client methods instead of a custom class
  2. Extend the mock to support get_secret_value with version_id parameters

Real-world use cases

  • Unit testing application code that fetches database credentials from Secrets Manager in CI/CD pipelines.
  • Developing locally against a microservice that requires secret retrieval without AWS credentials.
  • Writing integration tests that simulate secret rotation scenarios for production deployment validation.

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.