mongomock-motor
mongomock-motor is a Python library that provides a best-effort mock for the AsyncIOMotorClient, built on top of the `mongomock` library. It enables developers to test asynchronous MongoDB applications that use `motor` without requiring a running MongoDB instance. The library is currently active, with frequent patch and minor feature releases.
Warnings
- gotcha mongomock-motor provides a 'best effort mock' and may not perfectly replicate all corner cases, complex query behaviors, or newer features of a real MongoDB instance or the `motor` driver. Discrepancies may arise in highly specific scenarios.
- deprecated The underlying `motor` library is scheduled for deprecation on May 14, 2026, with critical bug fixes ending May 14, 2027. Users are recommended to migrate to the `PyMongo Async driver`. This will affect the long-term relevance and maintenance of `mongomock-motor` as `motor` itself is phased out.
- gotcha Specific BSON type handling, such as `uuidRepresentation` settings, might not behave identically in `mongomock-motor` compared to a real `motor` connection. This can lead to unexpected errors or data mismatches when dealing with UUIDs or other complex BSON types.
- breaking Compatibility with `mongomock`, `motor`, and `pymongo` versions is crucial. Upgrades in any of these underlying libraries (e.g., `mongomock` dropping Python 2 support or `motor` requiring `PyMongo 4.0+`) can introduce breaking changes that might not be immediately reflected or supported by `mongomock-motor`.
- gotcha This library is intended for unit and integration testing purposes only. It should never be used as a substitute for a real MongoDB connection in production environments.
Install
-
pip install mongomock-motor
Imports
- AsyncMongoMockClient
from mongomock_motor import AsyncMongoMockClient
- AsyncIOMotorClient
from motor.motor_asyncio import AsyncIOMotorClient
Quickstart
import asyncio
from mongomock_motor import AsyncMongoMockClient
async def main():
client = AsyncMongoMockClient() # Create a mock client
db = client['mydatabase']
collection = db['mycollection']
# Insert a document
insert_result = await collection.insert_one({"name": "Test Document", "value": 123})
print(f"Inserted document with ID: {insert_result.inserted_id}")
# Find a document
found_doc = await collection.find_one({"name": "Test Document"})
print(f"Found document: {found_doc}")
assert found_doc['value'] == 123
# Update a document
update_result = await collection.update_one(
{"name": "Test Document"},
{"$set": {"value": 456}}
)
print(f"Modified {update_result.modified_count} document(s).")
updated_doc = await collection.find_one({"name": "Test Document"})
print(f"Updated document: {updated_doc}")
assert updated_doc['value'] == 456
# Close the mock client (good practice, though not strictly necessary for mock)
await client.close()
if __name__ == '__main__':
asyncio.run(main())