This code shows how to separate test and production environments in microservices by switching database connections based on environment variables. It prevents tests from affecting live data and enables use of synthetic test data.
### Before: Shared environment with hardcoded test data
class UserService:
def get_user(self, user_id):
# Directly queries production DB
return db.query(f"SELECT * FROM users WHERE id={user_id}")
### After: Environment variable controls DB connection, uses test data setup
import os
class UserService:
def __init__(self):
env = os.getenv('ENVIRONMENT', 'production')
if env == 'test':
self.db = TestDatabaseConnection()
else:
self.db = ProductionDatabaseConnection()
def get_user(self, user_id):
return self.db.query(f"SELECT * FROM users WHERE id={user_id}")
# Test setup example
class TestDatabaseConnection:
def query(self, sql):
# Returns synthetic test data
return {'id': 1, 'name': 'Test User'}
# Explanation:
# The before code uses a hardcoded production database connection, risking data corruption during tests.
# The after code switches database connections based on environment variables, isolating test data.
# This pattern supports safe testing in microservices by separating test and production data access.