Mock ConfigMap Mount Environment Variables in Python
Simulate reading environment variables from a Kubernetes ConfigMap-mounted directory and test it with mocks.
Python code
47 linesimport os
import tempfile
from unittest.mock import patch
def load_config_from_mount(mount_path):
"""Simulate reading environment variables from a ConfigMap-mounted directory."""
config = {}
for filename in os.listdir(mount_path):
file_path = os.path.join(mount_path, filename)
if os.path.isfile(file_path):
with open(file_path, "r") as f:
config[filename] = f.read().strip()
return config
def create_env_from_config(config):
"""Set environment variables from the loaded config."""
for key, value in config.items():
os.environ[key] = value
return {key: os.environ[key] for key in config}
if __name__ == "__main__":
# Create a temporary directory to simulate a ConfigMap mount
with tempfile.TemporaryDirectory() as tmpdir:
with open(os.path.join(tmpdir, "DATABASE_URL"), "w") as f:
f.write("postgres://user:pass@localhost:5432/db")
with open(os.path.join(tmpdir, "LOG_LEVEL"), "w") as f:
f.write("INFO")
with open(os.path.join(tmpdir, "MAX_RETRIES"), "w") as f:
f.write("5")
# Load config and set environment variables
config = load_config_from_mount(tmpdir)
env_vars = create_env_from_config(config)
print("Environment variables set from ConfigMap mount:")
for key, value in sorted(env_vars.items()):
print(f" {key}={value}")
# Example of mocking for testing (without actual mount)
with patch.dict(os.environ, {}, clear=True):
with patch.object(os, "listdir", return_value=["TEST_KEY"]):
with patch("builtins.open") as mock_open:
mock_open.return_value.__enter__.return_value.read.return_value = "mock_value"
fake_config = load_config_from_mount("/fake/mount")
print("\nMocked ConfigMap mount result:")
print(f" {fake_config}")
Output
Environment variables set from ConfigMap mount:
DATABASE_URL=postgres://user:pass@localhost:5432/db
LOG_LEVEL=INFO
MAX_RETRIES=5
Mocked ConfigMap mount result:
{'TEST_KEY': 'mock_value'}
How it works
The code first creates a temporary directory to mimic a Kubernetes ConfigMap mount, writing files that represent environment variables. load_config_from_mount reads each file's content as a string value, and create_env_from_config sets them into os.environ. The with patch.dict(os.environ, {}, clear=True) isolates the environment to avoid side effects. patch.object and patch('builtins.open') replace filesystem operations, returning a fake config without needing a real mount. This pattern lets you test ConfigMap loading logic in CI without Kubernetes infrastructure.
Common mistakes
- Forgetting to clear `os.environ` before mocking, causing test pollution.
- Mocking `open` without setting up the `__enter__` context manager correctly.
- Assuming file order matters when reading directory contents — sort explicitly if needed.
Variations
- Use `pytest` fixtures with `tmp_path` to create temporary dirs more elegantly.
- Load config directly from a JSON or YAML file mounted at a known path instead of individual files.
Real-world use cases
- Testing application startup routines that read Kubernetes ConfigMap mounts in staging environments.
- Unit-testing service bootstrap code that sets env vars from mounted secrets without real clusters.
- Simulating config loading for local development when cloud mounts are not available.
Sponsored
More from Production deployment patterns
- Auto Rollback on Error Rate Exceeded in Python medium
- Automate Semantic Versioning with Conventional Commits in Python medium
- Design a Data Helper for Beginners in Python easy
- Docker healthcheck CMD mock in Python easy
- Generate a Mock Artifact Version Tag in Python easy
- Generate a docker-compose.yml with mock services in Python easy
Keep learning
Related tutorials and quizzes for this topic.