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
FantasyBballHelper - Espn Fantasy Basketball Helper

ESPN FANTASY BASKETBALL HELPER The simple goal of this project is to allow fanta

1 Jan 18, 2022
Airbrake Python

airbrake-python Note. Python 3.4+ are advised to use new Airbrake Python notifier which supports async API and code hunks. Python 2.7 users should con

Airbrake 51 Dec 22, 2022
pyForgeCert is a Python equivalent of the original ForgeCert written in C#.

pyForgeCert is a Python equivalent of the original ForgeCert written in C#.

Evi1cg 47 Oct 08, 2022
Persistent/Immutable/Functional data structures for Python

Pyrsistent Pyrsistent is a number of persistent collections (by some referred to as functional data structures). Persistent in the sense that they are

Tobias Gustafsson 1.8k Dec 31, 2022
An html wrapper for python

MessySoup What is it? MessySoup is a python wrapper for html elements. While still a ways away, the main goal is to be able to build a wesbite straigh

4 Jan 05, 2022
北大选课网2021年春季验证码识别

北大选课网验证码识别 2021 年春季学期 Powered by Elector Quartet (@Rabbit, @xmcp, @SpiritedAwayCN, @gzz) 数据集描述 最初的数据集为 5130 张人工标记的验证码,之后利用早期训练好的模型在选课网上进行自动验证 (自举),又收集

Rabbit 27 Sep 17, 2022
Osu statistics right on your desktop, made with pyqt

Osu!Stat Osu statistics right on your desktop, made with Qt5 Credits Would like to thank these creators for their projects and contributions. ppy, osu

Aditya Gupta 21 Jul 13, 2022
【幼盾】个性化图片徽章服务!

【幼盾】个性化图片徽章服务! 你对方形的徽章感到无聊了吗?想要定制属于自己的开源项目徽章了吗? 快来使用unv-shield吧! unv-shield提供包含自定义图片的徽章服务,可以让你的项目主页更加个性化!

黄巍 130 Dec 23, 2022
🤞 Website-Survival-Detection

- 🤞 Website-Survival-Detection It can help you to detect the survival status of the website in batches and return the status code! - 📜 Instructions

B0kd1 4 Nov 14, 2022
Check is a integer is even

Is Even Check if interger is even using isevenapi. https://isevenapi.xyz/ Main features: cache memoization api retry handler hide ads Install pip inst

Rosiney Gomes Pereira 45 Dec 19, 2022
A python package to adjust the bias of probabilistic forecasts/hindcasts using "Mean and Variance Adjustment" method.

Documentation A python package to adjust the bias of probabilistic forecasts/hindcasts using "Mean and Variance Adjustment" method. Read documentation

1 Feb 02, 2022
Demo of a WAM Prolog implementation in Python

Prol: WAM demo This is a simplified Warren Abstract Machine (WAM) implementation for Prolog, that showcases the main instructions, compiling, register

Bruno Kim Medeiros Cesar 62 Dec 26, 2022
tox-gh is a tox plugin which helps running tox on GitHub Actions with multiple different Python versions on multiple workers in parallel

tox-gh is a tox plugin which helps running tox on GitHub Actions with multiple different Python versions on multiple workers in parallel. This project is inspired by tox-travis.

tox development team 19 Dec 26, 2022
Percolation simulation using python

PythonPercolation Percolation simulation using python Exemple de percolation : Etude statistique sur le pourcentage de remplissage jusqu'à percolation

Tony Chouteau 1 Sep 08, 2022
This is a spamming selfbot that has custom spammed message and @everyone spam.

This is a spamming selfbot that has custom spammed message and @everyone spam.

astro1212 1 Jul 31, 2022
A Non profit app built on top of Frappe framework & ERPNext

Non Profit A Non profit app built on top of Frappe framework & ERPNext. People who change the world need the tools to do it! The Non Profit Modules of

Frappe 16 Nov 17, 2022
A Python application that helps users determine their calorie intake, and automatically generates customized weekly meal and workout plans based on metrics computed using their physical parameters

A Python application that helps users determine their calorie intake, and automatically generates customized weekly meal and workout plans based on metrics computed using their physical parameters

Anam Iqbal 1 Jan 13, 2022
A novel dual model approach for categorization of unbalanced skin lesion image classes (Presented technical paper 📃)

A novel dual model approach for categorization of unbalanced skin lesion image classes (Presented technical paper 📃)

1 Jan 19, 2022
A domonic-like wrapper around selectolax

A domonic-like wrapper around selectolax

byteface 3 Jun 23, 2022