Library for mocking AsyncIOMotorClient built on top of mongomock.

Overview

mongomock-motor

PyPI version

Best effort mock for AsyncIOMotorClient (Database, Collection, e.t.c) built on top of mongomock library.

Example / Showcase

from mongomock_motor import AsyncMongoMockClient


async def test_mock_client():
    collection = AsyncMongoMockClient()['tests']['test-1']

    assert await collection.find({}).to_list(None) == []

    result = await collection.insert_one({'a': 1})
    assert result.inserted_id

    assert len(await collection.find({}).to_list(None)) == 1
Comments
  • AttributeError: 'UpdateResult' object has no attribute '_UpdateResult__acknowledged'

    AttributeError: 'UpdateResult' object has no attribute '_UpdateResult__acknowledged'

    i believe there is a regression in version 0.0.9 which causes our mocks in the tests to fail on the following:

    Traceback (most recent call last):
    File "/Users/itaykeren/.vscode/extensions/ms-python.python-2022.6.2/pythonFiles/lib/python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_resolver.py", line 192, in _get_py_dictionary
    attr = getattr(var, name)
    AttributeError: \'UpdateResult\' object has no attribute \'_UpdateResult__acknowledged\
    

    in our tests, we are mocking update_one to return UpdateResult({}, False) in order to mock an upsert failure - meaning result.acknowledged is set to False

    this worked fine with previous versions, but breaks on 0.0.9

    i suspect its related to the changes introduced in https://github.com/michaelkryukov/mongomock_motor/pull/13

    can you please look into it?

    opened by Itay4 6
  • It is impossible to use database methods

    It is impossible to use database methods

    Hi, thank you for a great project!

    We tried to use it in a real project and found out that it is impossible to use database methods due to a wrapper that thinks that every attribute is a collection name. Is it difficult to implement methods support in Database wrapper? We are trying to use list_collection_names method to access collections without knowing their names.

    opened by ArchiDevil 5
  • New Beanie `Link` directive fails with mongomock harness

    New Beanie `Link` directive fails with mongomock harness

    Hey Michael, I was referred to your library by the guys at mongomock who think my issue is probably with mongomock-motor. This is the ticket I raised with them. Does this make any sense? Do you agree with them?

    opened by cypherlou 4
  • masquerade and more async methods

    masquerade and more async methods

    Changes:

    • Added masquerading mock classes as motor's original, so checks like isinstance(collection, AsyncIOMotorCollection) won't fail. It's possible there will still be issues if you expected to use tornado classes instead of asyncio, but I will wait for actual cases to somehow solve this.
    • Added some async methods for collection.
    • Added test that checks basic compatibility with beanie ODM.

    Notes:

    • Inspired by #1.
    opened by michaelkryukov 4
  • Fix patches when fields are enum members

    Fix patches when fields are enum members

    The current implementation of _normalize_strings transforms enum members into their representation, when it should give their value instead.

    For example, with such an enum

    class Importance(str, Enum):
        HIGH = "high"
        LOW = "low"
    

    a cursor like Cursor({"importance": Importance.HIGH}) would see its filter transformed to {"importance": "Importance.HIGH"} instead of {"importance": "high"}, which will most likely not fetch anything.

    opened by ramnes 2
  • Add support for Mongo-Thingy

    Add support for Mongo-Thingy

    Hey there, thanks for the great library!

    Mongo-Thingy is a sync + async ODM that already has Mongomock and Motor as supported backends, so I really would love to add mongomock-motor to the list. :)

    This PR fixes the errors that are raised by our test suite when adding mongomock-motor to the list of tested backends (see here if you're curious).

    Basically, we just handle a few more things that should be interesting in other situations too:

    • AsyncCursor.clone() and AsyncCursor.distinct() that are missing;
    • AsyncMongoMockCollection.database that doesn't return an AsyncMongoMockDatabase but the underlying class instead;
    • as well as AsyncMongoMockCollection.__eq__ and AsyncMongoMockDatabase.__eq__ that are missing.

    It also adds a test file for Mongo-Thingy, inspired by test_umongo.py, in case you want to keep the compatibility alive.

    opened by ramnes 1
  • Add support for AsyncIOMotorLatentCommandCursor

    Add support for AsyncIOMotorLatentCommandCursor

    aggregate() actually returns an AsyncIOMotorLatentCommandCursor instace, which is similar to AsyncIOMotorCursor but without the bells and whistles like sort(), limit() etc.

    opened by jyggen 1
  • Beanie Query Syntax Not Recognized

    Beanie Query Syntax Not Recognized

    The Beanie .find(), .find_many() and .find_one() methods, when used with the Beanie search criteria syntax always return every document, regardless of the search criteria.

    Using your test as an example and adjusting slightly, if we create two documents and then make a query that should only return one, we still get both documents returned. Example below:

    @pytest.mark.anyio
    async def test_beanie():
        client = AsyncMongoMockClient('mongodb://user:[email protected]:27017', connectTimeoutMS=250)
    
        await init_beanie(database=client.beanie_test, document_models=[Product])
    
        chocolate = Category(name='Chocolate', description='A preparation of roasted and ground cacao seeds.')
        tonybar = Product(name="Tony's", price=5.95, category=chocolate)
        newbar = Product(name="Test", price=5.95, category=chocolate)
        await tonybar.insert()
        await newbar.insert()
        
        find_many = Product.find_many(Product.name == "Test")
        assert find_many.motor_cursor
        assert await find_many.count() == 1 # This assert fails: 2 != 1
    

    Additionally, you can see this happening in your test as it stands because of a typo. Line 37, there's a typo; "Chocolade" instead of "Chocolate". This query should return no documents, but your asserts on 38 and 39 still pass because the beanie syntax is essentially ignored.

    I've found that these methods still work with pymongo syntax. For instance, modifying the search in my example above:

    @pytest.mark.anyio
    async def test_beanie():
        client = AsyncMongoMockClient('mongodb://user:[email protected]:27017', connectTimeoutMS=250)
    
        await init_beanie(database=client.beanie_test, document_models=[Product])
    
        chocolate = Category(name='Chocolate', description='A preparation of roasted and ground cacao seeds.')
        tonybar = Product(name="Tony's", price=5.95, category=chocolate)
        newbar = Product(name="Test", price=5.95, category=chocolate)
        await tonybar.insert()
        await newbar.insert()
        
        find_many = Product.find_many({"name": "Test"}) # using pymongo syntax here
        assert find_many.motor_cursor
        assert await find_many.count() == 1 # This now works with the pymongo syntax.
    

    This test will pass because it uses pymongo syntax.

    In short, it seems that the native beanie search syntax is essentially omitted and all documents are always returned in the case of .find() and the first document is always returned in the case of .find_one(). I may try and poke around a bit to see if I can work something out myself. Let me know your thoughts!

    opened by liamptiernan 1
  • tz_aware option was not working (among other)

    tz_aware option was not working (among other)

    Hi, the thing is that MongoClient was not being initialized correctly. I discovered it while trying to use tz_aware parameter and queries always returned naive datetime instances.

    I passed *args and **kwargs to the MongoClient initializer so all the MongoClient options can be used, but I haven't written tests for all options, just one for the tz_aware case, by the way.

    opened by cperezabo 1
  • Add index_information to mocked methods

    Add index_information to mocked methods

    This mocked method is required by the beanie ODM. This PR by itself isn't enough to make this new mock fully compatible, we will also need to patch Beanie to support the runtime type checking of mocked objects.

    https://github.com/roman-right/beanie/ https://github.com/roman-right/beanie/blob/2e104ee9602624b7c5e694e3f0a5f56a8a39d924/beanie/odm/settings/collection.py#L71

    opened by tclasen 1
  • Package is installed with

    Package is installed with "tests" folder

    When installing the package the tests folder is installed as well as a separate package.

    When uninstalling with pip the following appears:

    Uninstalling mongomock-motor-0.0.15:
      Would remove:
        .pyenv/versions/3.9.13/envs/venv_tb_web_server/lib/python3.9/site-packages/mongomock_motor-0.0.15.dist-info/*
       .pyenv/versions/3.9.13/envs/venv_tb_web_server/lib/python3.9/site-packages/mongomock_motor/*
        .pyenv/versions/3.9.13/envs/venv_tb_web_server/lib/python3.9/site-packages/tests/
    

    This causes problems when I want to import from my tests folder.

    A good solution would be to change setup.py

    opened by JPDevelop 0
  • The fetch_links=True in beanie queries doesn't work

    The fetch_links=True in beanie queries doesn't work

    So after getting a document calling fetch_all_links() works however when using the keyword argument it doesn't. Thus you can't do queries comparing the linked document properties. For example the below would not work:

    doc = await House.find_one(House.front_door.color == 'Blue', fetch_links=True)

    opened by nemrok 2
Releases(v0.0.17)
  • v0.0.17(Jan 2, 2023)

    What's Changed

    • feat: implemented 'next' for cursors; tweaked testing process by @michaelkryukov in https://github.com/michaelkryukov/mongomock_motor/pull/28

    Full Changelog: https://github.com/michaelkryukov/mongomock_motor/compare/v0.0.16...v0.0.17

    Source code(tar.gz)
    Source code(zip)
  • v0.0.16(Jan 1, 2023)

    What's Changed

    • fix: do not install tests as module by @michaelkryukov in https://github.com/michaelkryukov/mongomock_motor/pull/25

    Full Changelog: https://github.com/michaelkryukov/mongomock_motor/compare/v0.0.15...v0.0.16

    Source code(tar.gz)
    Source code(zip)
  • v0.0.15(Dec 31, 2022)

    What's Changed

    • fix: avoid issues with ExpressionField and proper str-like classes (thanks @ramnes) by @michaelkryukov in https://github.com/michaelkryukov/mongomock_motor/pull/23

    Full Changelog: https://github.com/michaelkryukov/mongomock_motor/compare/v0.0.14...v0.0.15

    Source code(tar.gz)
    Source code(zip)
  • v0.0.14(Dec 16, 2022)

    What's Changed

    • Add support for Mongo-Thingy by @ramnes in https://github.com/michaelkryukov/mongomock_motor/pull/21

    New Contributors

    • @ramnes made their first contribution in https://github.com/michaelkryukov/mongomock_motor/pull/21

    Full Changelog: https://github.com/michaelkryukov/mongomock_motor/compare/v0.0.13...v0.0.14

    Source code(tar.gz)
    Source code(zip)
  • v0.0.13(Oct 8, 2022)

    What's Changed

    • Add support for AsyncIOMotorLatentCommandCursor by @jyggen in https://github.com/michaelkryukov/mongomock_motor/pull/19

    New Contributors

    • @jyggen made their first contribution in https://github.com/michaelkryukov/mongomock_motor/pull/19

    Full Changelog: https://github.com/michaelkryukov/mongomock_motor/compare/v0.0.12...v0.0.13

    Source code(tar.gz)
    Source code(zip)
  • v0.0.12(Jul 3, 2022)

    What's Changed

    • fix: added string normalization to _iter_documents so beanie works by @michaelkryukov in https://github.com/michaelkryukov/mongomock_motor/pull/18

    Full Changelog: https://github.com/michaelkryukov/mongomock_motor/compare/v0.0.11...v0.0.12

    Source code(tar.gz)
    Source code(zip)
  • v0.0.11(Jun 9, 2022)

    What's Changed

    • [IMP] support distinct as async by @oerp-odoo in https://github.com/michaelkryukov/mongomock_motor/pull/16

    New Contributors

    • @oerp-odoo made their first contribution in https://github.com/michaelkryukov/mongomock_motor/pull/16

    Full Changelog: https://github.com/michaelkryukov/mongomock_motor/compare/v0.0.10...v0.0.11

    Source code(tar.gz)
    Source code(zip)
  • v0.0.10(Jun 1, 2022)

    What's Changed

    • feat: refactored code to be better compatible with mocking; added tests by @michaelkryukov in https://github.com/michaelkryukov/mongomock_motor/pull/15

    Full Changelog: https://github.com/michaelkryukov/mongomock_motor/compare/v0.0.9...v0.0.10

    Source code(tar.gz)
    Source code(zip)
  • v0.0.9(May 24, 2022)

    What's Changed

    • BulkWriteResult couldn't be awaited by @cperezabo in https://github.com/michaelkryukov/mongomock_motor/pull/11
    • Refactored interaction with get_database and get_collection, extended async (and sync) methods list by @michaelkryukov in https://github.com/michaelkryukov/mongomock_motor/pull/13

    Full Changelog: https://github.com/michaelkryukov/mongomock_motor/compare/v0.0.8...v0.0.9

    Source code(tar.gz)
    Source code(zip)
  • v0.0.8(May 10, 2022)

    What's Changed

    • Support for umongo + more tests by @michaelkryukov in https://github.com/michaelkryukov/mongomock_motor/pull/10

    Full Changelog: https://github.com/michaelkryukov/mongomock_motor/compare/v0.0.7...v0.0.8

    Source code(tar.gz)
    Source code(zip)
  • v0.0.7(Apr 27, 2022)

    What's Changed

    • tz_aware option was not working (among other) by @cperezabo in https://github.com/michaelkryukov/mongomock_motor/pull/8

    New Contributors

    • @cperezabo made their first contribution in https://github.com/michaelkryukov/mongomock_motor/pull/8

    Full Changelog: https://github.com/michaelkryukov/mongomock_motor/compare/v0.0.6...v0.0.7

    Source code(tar.gz)
    Source code(zip)
  • v0.0.6(Apr 23, 2022)

    What's Changed

    • Set required mongomock version by @Itay4 in https://github.com/michaelkryukov/mongomock_motor/pull/7

    New Contributors

    • @Itay4 made their first contribution in https://github.com/michaelkryukov/mongomock_motor/pull/7

    Full Changelog: https://github.com/michaelkryukov/mongomock_motor/compare/v0.0.5...v0.0.6

    Source code(tar.gz)
    Source code(zip)
  • v0.0.5(Mar 27, 2022)

    • Make AsyncCursor more similar to AsyncIOMotorCursor (add support for limit, skip, sort, e.t.c.) + tests.
    • Add limited support for {buildInfo: 1} command.
    • Add attributes proxying for collections.
    • Add tests for links (limited).
    • Bump version for beanie, mongomock
    Source code(tar.gz)
    Source code(zip)
  • v0.0.3(Feb 25, 2022)

  • v0.0.2(Nov 17, 2021)

    Changes:

    • Added masquerading mock classes as motor's original, so checks like isinstance(collection, AsyncIOMotorCollection) won't fail. It's possible there will still be issues if you expected to use tornado classes instead of asyncio, but I will wait for actual cases to somehow solve this.
    • Added some async methods for collection.
    • Added test that checks basic compatibility with beanie ODM.
    Source code(tar.gz)
    Source code(zip)
  • v0.0.1(Nov 11, 2021)

Owner
Michael Kryukov
🐘 Coding many things 📝 Python, Go, JavaScript, Java, Kotlin, PHP
Michael Kryukov
In this project, we'll be creating a virtual personal assistant for ourselves using our favorite programming language

In this project, we'll be creating a virtual personal assistant for ourselves using our favorite programming language, Python. We can perform several offline as well as online operations using the bo

Ashutosh Krishna 188 Jan 03, 2023
Мой первый калькулятор!!!!!!

my_first_calculator Первый калькулятор созданный мною на питоне Версия калькулятора: 0.0.4 Как скачать? TERMUX Для скрипта нужен питон, скачиваем pkg

Lesha Russkiyov 2 Dec 29, 2021
SciPy library main repository

SciPy SciPy (pronounced "Sigh Pie") is an open-source software for mathematics, science, and engineering. It includes modules for statistics, optimiza

SciPy 10.7k Jan 09, 2023
Social reading and reviewing, decentralized with ActivityPub

BookWyrm Social reading and reviewing, decentralized with ActivityPub Contents Joining BookWyrm Contributing About BookWyrm What it is and isn't The r

BookWyrm 1.4k Jan 08, 2023
Painel de consulta

⚙ FullP 1.1 Instalação 💻 git clone https://github.com/gav1x/FullP.git cd FullP pip3 install -r requirements.txt python3 main.py Um pequeno

gav1x 26 Oct 11, 2022
Collection of functions for working with interlaced content in VapourSynth.

vsfieldkit Collection of functions for working with interlaced content in VapourSynth. It does not have any hard dependencies outside of VapourSynth.

Justin Turner Arthur 11 May 27, 2022
A basic notes app to store your notes.

Notes Webapp A basic notes webapp to keep your notes.You can add, edit and delete notes after signing up. To add a note type your note in the text box

2 Oct 23, 2021
a pull switch (or BYO button) that gets you out of video calls, quick

zoomout a pull switch (or BYO button) that gets you out of video calls, quick. As seen on Twitter System compatibility Tested on macOS Catalina (10.15

Brian Moore 422 Dec 30, 2022
This is the improvised version of Dobot Magician which can be implemented for Dobot M1

pydobotM1 This is the edited driver for Dobot M1 version of the original pydobot library intended for use with the Dobot Magician. Here's what you nee

Shaik Abdullah 2 Jul 11, 2022
Restaurant-finder - Restaurant finder With Python

restaurant-finder APIs /restaurants query-params: a. filter: column based on whi

Kumar saurav 1 Feb 22, 2022
Python-Course-V1 - This Repo contains a series of Python Jupyter Notebooks and assignments

This Repo contains a series of Python Jupyter Notebooks and assignments. The assignments are taken from Python Crash Course book by Eric Matthes.

2 Nov 15, 2022
The tool helps to find hidden parameters that can be vulnerable or can reveal interesting functionality that other hunters miss.

The tool helps to find hidden parameters that can be vulnerable or can reveal interesting functionality that other hunters miss. Greater accuracy is achieved thanks to the line-by-line comparison of

197 Nov 14, 2022
Time python - Códigos para auxiliar e mostrar formas de como fazer um relógio e manipular o seu tempo

Time_python Códigos para auxiliar e mostrar formas de como fazer um relógio e manipular o seu tempo. Bibliotecas Nestes foram usadas bibliotecas nativ

Eduardo Henrique 1 Jan 03, 2022
TimeWizard - A script that generates every single Time Wizard EDOPRO lflist possible

EDOPRO F&L list generator This project is just a script that generates every sin

Diamond Dude 2 Sep 28, 2022
Do you need a screensaver for CircuitPython? Of course you do

circuitpython_screensaver Do you need a screensaver for CircuitPython? Of course you do Demo video of dvdlogo screensaver: screensaver_dvdlogo.mp4 Dem

Tod E. Kurt 8 Sep 02, 2021
Генератор отчетов на Python с использованием библиотеки docx для работы с word-файлами и запросов к сервису

Генератор отчетов на Python с использованием библиотеки docx для работы с word-файлами и запросов к сервису

Semyon Esaev 2 Jun 24, 2022
A web-based chat application that enables multiple users to interact with one another

A web-based chat application that enables multiple users to interact with one another, in the same chat room or different ones according to their choosing.

3 Apr 22, 2022
mrcal is a generic toolkit to solve calibration and SFM-like problems originating at NASA/JPL

mrcal is a generic toolkit to solve calibration and SFM-like problems originating at NASA/JPL. Functionality related to these problems is exposed as a set of C and Python libraries and some commandli

Dima Kogan 102 Dec 23, 2022
Release for Improved Denoising Diffusion Probabilistic Models

improved-diffusion This is the codebase for Improved Denoising Diffusion Probabilistic Models. Usage This section of the README walks through how to t

OpenAI 1.2k Dec 30, 2022
peace-performance (Rust) binding for python. To calculate star ratings and performance points for all osu! gamemodes

peace-performance-python Fast, To calculate star ratings and performance points for all osu! gamemodes peace-performance (Rust) binding for python bas

9 Sep 19, 2022