Fake pymongo stub for testing simple MongoDB-dependent code
npx @tessl/cli install tessl/pypi-mongomock@4.3.00
# Mongomock
1
2
A comprehensive MongoDB mocking library that provides a complete fake implementation of PyMongo's API for testing Python applications. Mongomock enables developers to test MongoDB-dependent code without requiring an actual MongoDB instance, offering full compatibility with PyMongo interfaces including collections, databases, queries, aggregation pipelines, and GridFS functionality.
3
4
## Package Information
5
6
- **Package Name**: mongomock
7
- **Language**: Python
8
- **Installation**: `pip install mongomock`
9
10
## Core Imports
11
12
```python
13
import mongomock
14
```
15
16
Main classes and functions:
17
18
```python
19
from mongomock import MongoClient, Database, Collection, ObjectId
20
from mongomock import patch, ignore_feature, warn_on_feature
21
```
22
23
Error classes:
24
25
```python
26
from mongomock import (
27
OperationFailure, DuplicateKeyError,
28
CollectionInvalid, InvalidName
29
)
30
```
31
32
Configuration classes:
33
34
```python
35
from mongomock import WriteConcern
36
```
37
38
## Basic Usage
39
40
```python
41
import mongomock
42
43
# Create a mock MongoDB client
44
client = mongomock.MongoClient()
45
46
# Get a database
47
db = client.test_database
48
49
# Get a collection
50
collection = db.test_collection
51
52
# Insert documents
53
collection.insert_one({"name": "Alice", "age": 30})
54
collection.insert_many([
55
{"name": "Bob", "age": 25},
56
{"name": "Charlie", "age": 35}
57
])
58
59
# Query documents
60
user = collection.find_one({"name": "Alice"})
61
all_users = list(collection.find({"age": {"$gte": 25}}))
62
63
# Update documents
64
collection.update_one({"name": "Alice"}, {"$set": {"age": 31}})
65
collection.update_many({"age": {"$lt": 30}}, {"$set": {"status": "young"}})
66
67
# Delete documents
68
collection.delete_one({"name": "Bob"})
69
collection.delete_many({"age": {"$gt": 40}})
70
71
# Count documents
72
count = collection.count_documents({"age": {"$gte": 25}})
73
```
74
75
## Architecture
76
77
Mongomock mirrors PyMongo's architecture while providing in-memory storage and mock behavior:
78
79
- **MongoClient**: Main entry point that manages connections and provides access to databases
80
- **Database**: Container for collections with database-level operations
81
- **Collection**: Primary interface for CRUD operations, indexing, and aggregation
82
- **Store**: Internal in-memory storage system that maintains data persistence across operations
83
- **Result Objects**: Structured responses that match PyMongo's result interfaces
84
- **Error System**: Complete exception hierarchy mirroring PyMongo's error classes
85
86
This architecture ensures drop-in compatibility with PyMongo while providing predictable, controllable behavior for testing scenarios.
87
88
## Capabilities
89
90
### Client and Connection Management
91
92
Core client functionality for establishing mock connections and managing database access with configuration options and server information.
93
94
```python { .api }
95
class MongoClient:
96
def __init__(self, host=None, port=None, document_class=dict,
97
tz_aware=False, connect=True, **kwargs): ...
98
def get_database(self, name=None, **kwargs): ...
99
def list_database_names(self): ...
100
def server_info(self): ...
101
def close(self): ...
102
```
103
104
[Client and Connection Management](./client.md)
105
106
### Database Operations
107
108
Database-level operations including collection management, database commands, and configuration with support for read/write concerns and codec options.
109
110
```python { .api }
111
class Database:
112
def get_collection(self, name, **kwargs): ...
113
def list_collection_names(self, filter=None, session=None): ...
114
def create_collection(self, name, **kwargs): ...
115
def drop_collection(self, name_or_collection, session=None): ...
116
def command(self, command, **kwargs): ...
117
```
118
119
[Database Operations](./database.md)
120
121
### Collection CRUD Operations
122
123
Complete Create, Read, Update, Delete operations with support for bulk operations, complex queries, and MongoDB-compatible filtering and sorting.
124
125
```python { .api }
126
class Collection:
127
def insert_one(self, document, **kwargs): ...
128
def insert_many(self, documents, **kwargs): ...
129
def find(self, filter=None, **kwargs): ...
130
def find_one(self, filter=None, **kwargs): ...
131
def update_one(self, filter, update, **kwargs): ...
132
def update_many(self, filter, update, **kwargs): ...
133
def delete_one(self, filter, **kwargs): ...
134
def delete_many(self, filter, **kwargs): ...
135
```
136
137
[Collection CRUD Operations](./collection-crud.md)
138
139
### Indexing and Performance
140
141
Index management operations including creation, deletion, and inspection of indexes with support for compound indexes, text indexes, and index options.
142
143
```python { .api }
144
def create_index(self, key_or_list, **kwargs): ...
145
def create_indexes(self, indexes, session=None): ...
146
def drop_index(self, index_or_name, session=None): ...
147
def list_indexes(self, session=None): ...
148
def index_information(self, session=None): ...
149
```
150
151
[Indexing and Performance](./indexing.md)
152
153
### Aggregation and Analysis
154
155
Aggregation pipeline operations and data analysis functions including pipeline stages, aggregation operators, and distinct value queries.
156
157
```python { .api }
158
def aggregate(self, pipeline, session=None, **kwargs): ...
159
def distinct(self, key, filter=None, session=None): ...
160
def count_documents(self, filter, **kwargs): ...
161
def estimated_document_count(self, **kwargs): ...
162
```
163
164
[Aggregation and Analysis](./aggregation.md)
165
166
### Cursors and Result Iteration
167
168
Cursor management for query results with support for sorting, limiting, skipping, and batch processing of result sets.
169
170
```python { .api }
171
class Cursor:
172
def sort(self, key_or_list, direction=None): ...
173
def skip(self, count): ...
174
def limit(self, count): ...
175
def batch_size(self, count): ...
176
def hint(self, hint): ...
177
```
178
179
[Cursors and Result Iteration](./cursors.md)
180
181
### Configuration and Options
182
183
Configuration classes for controlling read/write behavior, codec options, and database connection parameters.
184
185
```python { .api }
186
class WriteConcern:
187
def __init__(self, w=None, wtimeout=None, j=None, fsync=None): ...
188
189
class ReadConcern:
190
def __init__(self, level=None): ...
191
192
class CodecOptions:
193
def __init__(self, document_class=dict, tz_aware=False, **kwargs): ...
194
```
195
196
[Configuration and Options](./configuration.md)
197
198
### Error Handling and Exceptions
199
200
Complete exception hierarchy mirroring PyMongo's error system with support for operation failures, write errors, and configuration errors.
201
202
```python { .api }
203
class OperationFailure(PyMongoError): ...
204
class WriteError(OperationFailure): ...
205
class DuplicateKeyError(WriteError): ...
206
class BulkWriteError(OperationFailure): ...
207
class CollectionInvalid(PyMongoError): ...
208
```
209
210
[Error Handling and Exceptions](./errors.md)
211
212
### Testing and Integration Utilities
213
214
Utilities for test integration including patching, feature management, and development helpers for seamless testing workflows.
215
216
```python { .api }
217
def patch(servers='localhost', on_new='error'): ...
218
def ignore_feature(feature): ...
219
def warn_on_feature(feature): ...
220
def enable_gridfs_integration(): ...
221
```
222
223
[Testing and Integration Utilities](./testing-utilities.md)
224
225
## Common Types
226
227
```python { .api }
228
from typing import Any, Dict, List, Optional, Union
229
230
# Document types
231
Document = Dict[str, Any]
232
Filter = Dict[str, Any]
233
Update = Dict[str, Any]
234
Projection = Union[Dict[str, Any], List[str]]
235
236
# Sort specification
237
SortSpec = Union[str, List[tuple]]
238
239
# Index specification
240
IndexSpec = Union[str, List[tuple]]
241
242
# Session type (placeholder for compatibility)
243
ClientSession = Any
244
245
# Result document
246
ResultDocument = Dict[str, Any]
247
```