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:pass@host: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:pass@host: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
Tiling manager which runs on top of EWMH window managers.

PyTyle is an extremely versatile and extensible tiling manager that is meant to be used on top of EWMH window managers. Its feature set was modeled af

null 55 Jul 29, 2021
A one place destination to check whatever is trending on the top social and news websites at present.

UpTrend A one place destination to check whatever is trending on the top social and news websites at present. Explore the docs » View Demo · Report Bu

Google Developer Student Clubs - JGEC 10 Oct 3, 2021
Get a list of the top-10 rejected libraries in your WhiteSource inventory

WhiteSource Top 10 Rejected Libraries Generate a spreadsheet listing the 10 most common libraries in your WhiteSource inventory that were rejected by

WhiteSource-PS-tools 10 Mar 23, 2022
Aerial Ace is a helper bot for poketwo which provide various functionalities on top of being a pokedex.

Aerial Ace is a helper bot for poketwo which provide various functionalities on top of being a pokedex.

Devanshu Mishra 1 Dec 1, 2021
A Blender addon to align the origin to the top, center or bottom of a mesh object

Align Origin Blender Addon. Align Origin Blender Addon. What? This simple addon lets you align the origin to the top, center or bottom of a mesh objec

VA79 7 Nov 30, 2022
Ergonomic option parser on top of dataclasses, inspired by structopt.

oppapī Ergonomic option parser on top of dataclasses, inspired by structopt. Usage from typing import Optional from oppapi import from_args, oppapi @

yukinarit 4 Jul 19, 2022
Meera 2 May 12, 2022
Ikaros is a free financial library built in pure python that can be used to get information for single stocks, generate signals and build prortfolios

Ikaros is a free financial library built in pure python that can be used to get information for single stocks, generate signals and build prortfolios

Salma Saidane 64 Sep 28, 2022
Built with Python programming language and QT library and Guess the number in three easy, medium and hard rolls

guess-the-numbers Built with Python programming language and QT library and Guess the number in three easy, medium and hard rolls Number guessing game

Amir Hussein Sharifnezhad 5 Oct 9, 2021
Built with Python programming language and QT library and Guess the number in three easy, medium and hard rolls

password-generator Built with Python programming language and QT library and Guess the number in three easy, medium and hard rolls Password generator

Amir Hussein Sharifnezhad 3 Oct 9, 2021
Driving lessons made simpler. Custom scheduling API built with Python.

NOTE This is a mirror of a GitLab repository. Dryvo Dryvo is a unique solution for the driving lessons industry. Our aim is to save the teacher’s time

Adam Goldschmidt 595 Dec 5, 2022
This repository contains Python Projects for Beginners as well as for Intermediate Developers built by Contributors.

Python Projects {Open Source} Introduction The repository was built with a tree-like structure in mind, it contains collections of Python Projects. Mo

Gaurav Pandey 115 Apr 30, 2022
Choice Coin 633 Dec 23, 2022
Here, I have discuss the three methods of list reversion. The three methods are built-in method, slicing method and position changing method.

Three-different-method-for-list-reversion Here, I have discuss the three methods of list reversion. The three methods are built-in method, slicing met

Sachin Vinayak Dabhade 4 Sep 24, 2021
Dot Browser is a privacy-conscious web browser with smarts built-in for protection against trackers and advertisments online.

?? Take back your privacy with Dot Browser, the privacy-conscious web browser that protects you from being tracked and monitored online.

Dot HQ 1k Jan 7, 2023
Source-o-grapher is a tool built with the aim to investigate software resilience aspects of Open Source Software (OSS) projects.

Source-o-grapher is a tool built with the aim to investigate software resilience aspects of Open Source Software (OSS) projects.

Aristotle University 5 Jun 28, 2022
Persian Kaldi profile for Rhasspy built from open speech data

Persian Kaldi Profile A Rhasspy profile for Persian (fa). Installation Get started by first installing Vosk: # Create virtual environment python3 -m v

Rhasspy 12 Aug 8, 2022
Student Management System Built With Python

Student-Management-System Group Members 19BCE183 - Patel Sarthak 19BCE195 - Patel Jinil 19BCE220 - Rana Yash Project Description In our project Studen

Sarthak Patel 6 Oct 20, 2022
Flask-built web application that simulates a time and cost calculator for charging Electric Vehicles.

ev_charging_calculator Flask-built web application that simulates a time and cost calculator for charging Electric Vehicles. The project aims to simul

null 1 Nov 3, 2021