mongomock-motor

0.0.36 · active · verified Mon Apr 13

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

Install

Imports

Quickstart

This quickstart demonstrates how to initialize `AsyncMongoMockClient` and perform basic asynchronous MongoDB operations (insert, find, update) against it, mimicking the API of `motor.motor_asyncio.AsyncIOMotorClient`.

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())

view raw JSON →