Fake pymongo stub for testing simple MongoDB-dependent code
—
Configuration classes for controlling read/write behavior, codec options, and database connection parameters. These classes provide fine-grained control over MongoDB operations and data handling.
Control write operation acknowledgment and durability requirements.
class WriteConcern:
def __init__(self, w=None, wtimeout=None, j=None, fsync=None):
"""
Create a write concern specification.
Parameters:
- w: int or str, write acknowledgment requirement
- int: number of replica set members to acknowledge
- str: 'majority' for majority acknowledgment
- wtimeout: int, timeout in milliseconds for write concern
- j: bool, require journal acknowledgment
- fsync: bool, require fsync before acknowledgment
Returns:
WriteConcern instance
"""
@property
def acknowledged(self):
"""bool: whether write operations are acknowledged"""
@property
def document(self):
"""dict: write concern as document"""
@property
def is_server_default(self):
"""bool: whether this is the server default write concern"""Usage Example:
from mongomock import WriteConcern
# Default acknowledged write
wc_default = WriteConcern()
# Require acknowledgment from majority of replica set
wc_majority = WriteConcern(w='majority')
# Require acknowledgment from specific number of members
wc_three = WriteConcern(w=3, wtimeout=5000)
# Require journal acknowledgment
wc_journal = WriteConcern(j=True)
# Use with collection operations
collection = mongomock.MongoClient().db.collection.with_options(
write_concern=wc_majority
)
result = collection.insert_one({'data': 'value'})
print(f"Acknowledged: {result.acknowledged}")Specify read isolation and consistency requirements.
class ReadConcern:
def __init__(self, level=None):
"""
Create a read concern specification.
Parameters:
- level: str, read concern level
- 'local': return most recent data (default)
- 'available': return available data without consistency guarantee
- 'majority': return data acknowledged by majority
- 'linearizable': return data that reflects all writes
- 'snapshot': return consistent snapshot
Returns:
ReadConcern instance
"""
@property
def level(self):
"""str: read concern level"""
@property
def ok_for_legacy(self):
"""bool: whether compatible with legacy servers"""
@property
def document(self):
"""dict: read concern as document"""Usage Example:
from mongomock import ReadConcern
# Default local read concern
rc_local = ReadConcern()
rc_local = ReadConcern(level='local')
# Majority read concern for consistency
rc_majority = ReadConcern(level='majority')
# Linearizable read concern for strongest consistency
rc_linear = ReadConcern(level='linearizable')
# Use with database/collection operations
db = mongomock.MongoClient().get_database('test', read_concern=rc_majority)
collection = db.collection
# Query with read concern
documents = list(collection.find({'status': 'active'}))Configure document encoding, decoding, and type handling.
class CodecOptions:
def __init__(self, document_class=dict, tz_aware=False,
uuid_representation=0, unicode_decode_error_handler="strict",
tzinfo=None, type_registry=None, datetime_conversion=None):
"""
Create codec options for BSON encoding/decoding.
Parameters:
- document_class: type, class to use for documents (default: dict)
- tz_aware: bool, decode dates as timezone-aware datetimes
- uuid_representation: int, UUID representation format
- unicode_decode_error_handler: str, unicode error handling
- tzinfo: timezone, timezone for datetime objects
- type_registry: TypeRegistry, custom type registry
- datetime_conversion: DatetimeConversion, datetime conversion mode
Returns:
CodecOptions instance
"""
def with_options(self, **kwargs):
"""
Create new CodecOptions with updated options.
Parameters:
- **kwargs: options to update
Returns:
CodecOptions: new instance with updated options
"""
@property
def document_class(self):
"""type: document class"""
@property
def tz_aware(self):
"""bool: timezone awareness setting"""
@property
def uuid_representation(self):
"""int: UUID representation format"""Usage Example:
from mongomock import CodecOptions
from collections import OrderedDict
import pytz
# Default codec options (dict documents)
codec_default = CodecOptions()
# Use OrderedDict to preserve field order
codec_ordered = CodecOptions(document_class=OrderedDict)
# Timezone-aware datetime handling
codec_tz = CodecOptions(tz_aware=True, tzinfo=pytz.UTC)
# Custom unicode error handling
codec_unicode = CodecOptions(unicode_decode_error_handler='ignore')
# Combine options
codec_custom = CodecOptions(
document_class=OrderedDict,
tz_aware=True,
tzinfo=pytz.timezone('US/Eastern'),
unicode_decode_error_handler='replace'
)
# Use with client/database/collection
client = mongomock.MongoClient()
db = client.get_database('test', codec_options=codec_custom)
# Update codec options
new_codec = codec_custom.with_options(tz_aware=False)
updated_db = db.with_options(codec_options=new_codec)Control read routing and server selection behavior.
# Read preference constants (from mongomock.read_preferences)
PRIMARY = 0 # Read from primary only
PRIMARY_PREFERRED = 1 # Prefer primary, fallback to secondary
SECONDARY = 2 # Read from secondary only
SECONDARY_PREFERRED = 3 # Prefer secondary, fallback to primary
NEAREST = 4 # Read from nearest serverUsage Example:
from mongomock import read_preferences
# Use read preferences with client
client = mongomock.MongoClient(read_preference=read_preferences.SECONDARY)
# Use with database
db = client.get_database('test',
read_preference=read_preferences.PRIMARY_PREFERRED
)
# Use with collection
collection = db.get_collection('users',
read_preference=read_preferences.NEAREST
)
# Query with specific read preference
primary_results = list(collection.with_options(
read_preference=read_preferences.PRIMARY
).find({'status': 'active'}))Configure client connection behavior and options.
Client Configuration Options:
# Connection string parsing
client = mongomock.MongoClient('mongodb://localhost:27017/testdb')
# Individual parameters
client = mongomock.MongoClient(
host='localhost',
port=27017,
document_class=OrderedDict,
tz_aware=True,
connect=True
)
# Advanced configuration
client = mongomock.MongoClient(
host=['server1:27017', 'server2:27017'], # Multiple hosts
read_preference=read_preferences.SECONDARY_PREFERRED,
write_concern=WriteConcern(w='majority'),
read_concern=ReadConcern(level='majority')
)Database and Collection Configuration:
# Database with options
db = client.get_database('mydb',
codec_options=CodecOptions(tz_aware=True),
read_preference=read_preferences.SECONDARY,
write_concern=WriteConcern(w=2),
read_concern=ReadConcern(level='majority')
)
# Collection with options
collection = db.get_collection('mycol',
codec_options=CodecOptions(document_class=OrderedDict),
read_preference=read_preferences.PRIMARY
)
# Chain configuration
configured_collection = (
client
.get_database('mydb', read_concern=ReadConcern(level='majority'))
.get_collection('mycol', write_concern=WriteConcern(w='majority'))
)Understand how configuration options are inherited through the hierarchy.
Configuration Hierarchy:
MongoClient
↓ (inherits client options)
Database
↓ (inherits database options, can override)
Collection
↓ (inherits collection options, can override)
OperationUsage Example:
from mongomock import MongoClient, WriteConcern, ReadConcern, CodecOptions
# Client-level configuration
client = MongoClient(
tz_aware=True,
read_preference=read_preferences.SECONDARY_PREFERRED
)
# Database inherits client config, adds write concern
db = client.get_database('mydb',
write_concern=WriteConcern(w='majority')
)
# Collection inherits db config, overrides read preference
collection = db.get_collection('mycol',
read_preference=read_preferences.PRIMARY
)
# Operation-level override
result = collection.with_options(
write_concern=WriteConcern(w=1)
).insert_one({'data': 'value'})Configure behavior through environment variables and global settings.
# Server version configuration
SERVER_VERSION = '5.0.5' # Default MongoDB version to simulate
# Environment variable support
import os
server_version = os.getenv('MONGODB', '5.0.5')Usage Example:
import os
import mongomock
# Set server version via environment
os.environ['MONGODB'] = '6.0.0'
# Create client with environment settings
client = mongomock.MongoClient()
# Check server info
info = client.server_info()
print(f"Simulated MongoDB version: {info.get('version')}")
# Global server version setting
mongomock.SERVER_VERSION = '4.4.0'
# All new clients will use this version
new_client = mongomock.MongoClient()Production-Like Testing:
# Mirror production configuration in tests
production_config = {
'write_concern': WriteConcern(w='majority', j=True),
'read_concern': ReadConcern(level='majority'),
'read_preference': read_preferences.SECONDARY_PREFERRED
}
# Test client with production settings
test_client = mongomock.MongoClient(**production_config)
test_db = test_client.testdb
# Verify behavior with production-like settings
collection = test_db.users
result = collection.insert_one({'test': 'data'})
assert result.acknowledgedEnvironment-Specific Configuration:
# Development settings
dev_config = CodecOptions(document_class=dict, tz_aware=False)
# Production settings
prod_config = CodecOptions(
document_class=OrderedDict,
tz_aware=True,
tzinfo=pytz.UTC
)
# Use appropriate config based on environment
config = prod_config if os.getenv('ENV') == 'production' else dev_config
client = mongomock.MongoClient()
db = client.get_database('myapp', codec_options=config)Install with Tessl CLI
npx tessl i tessl/pypi-mongomock