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
Mpis-ex7 - Implementation of tasks 1, 2, 3 for Metody Probabilistyczne i Statystyka Lista 7

Implementations of task 1, 2 and 3 from here Author: Maciej Bazela Index: 261743 Each task was implemented in Python 3. I've used Cython to speed up e

Maciej Bazela 1 Feb 27, 2022
This is an API to get user details for competitive coding platforms - Codeforces, Codechef, SPOJ, Interviewbit. More Platform will be Added Soon.

Competitive-Programming-Score-API An API to get user details for competitive coding platforms - Codeforces, Codechef, SPOJ, Interviewbit Platforms Ava

Aaditya Prakash 3 Jan 17, 2022
API wrapper for VCS hosting system.

PythonVCS API wrapper for VCS hosting system. Supported platforms Gitea Github, Gitlab, Bitbucket support will not, until that packages is not updated

MisileLaboratory 1 Apr 02, 2022
The program converts Swiss notes into American notes

Informatik-Programmieren Einleitung: Das Programm rechnet Schweizer Noten in das Amerikanische Noten um. Der Benutzer kann seine Note eingeben und der

2 Dec 16, 2021
🟥This is an overview of how to set up and use DataStore3 in your Roblox experiences

Welcome to DataStore3 👋 This is an overview of how to set up and use DataStore3 in your Roblox experiences What is it? 🤔 DataStore3 is a service tha

Reece Harris 7 Aug 19, 2022
WordlistPasswordGenerator - Shuhfab Basheer

WordlistPasswordGenerator - Shuhfab Basheer Python wordlist generator MAINTAINER

1 Dec 31, 2021
Thumbor-bootcamp - learning and contribution experience with ❤️ and 🤗 from the thumbor team

Thumbor-bootcamp - learning and contribution experience with ❤️ and 🤗 from the thumbor team

Thumbor (by @globocom) 9 Jul 11, 2022
Mannaggia is a python application to praise or more likely to curse the saints

Mannaggia-py 👼 Remember Mannaggia? This is a Python remake of it, with new features. mannaggia is a python application to praise or more likely to cu

Christian Visintin 9 Aug 12, 2022
Neptune client library - integrate your Python scripts with Neptune

Lightweight experiment tracking tool for AI/ML individuals and teams. Fits any workflow. Neptune is a lightweight experiment logging/tracking tool tha

neptune.ai 353 Jan 04, 2023
A bunch of codes for procedurally modeling and texturing futuristic cities.

Procedural Futuristic City This is our final project for CPSC 479. We created a procedural futuristic city complete with Worley noise procedural textu

1 Dec 22, 2021
The official Repository wherein newbies into Open Source can Contribute during the Hacktoberfest 2021

Hacktoberfest 2021 Get Started With your first Contrinution/Pull Request : Fork/Copy the repo by clicking the right most button on top of the page. Go

HacOkars 25 Aug 20, 2022
Create beautiful diagrams just by typing mathematical notation in plain text.

Penrose Penrose is an early-stage system that is still in development. Our system is not ready for contributions or public use yet, but hopefully will

Penrose 5.6k Jan 08, 2023
A system for assigning and grading notebooks

nbgrader Linux: Windows: Forum: Coverage: Cite: A system for assigning and grading Jupyter notebooks. Documentation can be found on Read the Docs. Hig

Project Jupyter 1.2k Dec 26, 2022
samples of neat code

NEAT-samples Some samples of code and config files for use with the NEAT-Python package These samples are largely copy and pasted, so if you

Harrison 50 Sep 28, 2022
Coronavirus Tracker API

Coronavirus Tracker API Provides up-to-date data about Coronavirus outbreak. Includes numbers about confirmed cases, deaths and recovered. Support mul

Francisco Laguna 1 Oct 31, 2020
Use Fofa、shodan、zoomeye、360quake to collect information(e.g:domain,IP,CMS,OS)同时调用Fofa、shodan、zoomeye、360quake四个网络空间测绘API完成红队信息收集

Cyberspace Map API English/中文 Development fofaAPI Completed zoomeyeAPI shodanAPI regular 360 quakeAPI Completed Difficulty APIs uses different inputs

Xc1Ym 61 Oct 08, 2022
To lazy to read your homework ? Get it done with LOL

LOL To lazy to read your homework ? Get it done with LOL Needs python 3.x L:::::::::L OO:::::::::OO L:::::::::L L:::::::

KorryKatti 4 Dec 08, 2022
Python implementation of Newton's Fractal

Newton's Fractal Animates Newton's fractal between two polynomials of the same order. Inspired by this video by 3Blue1Brown. Example fractals can be f

Jaime Liew 10 Aug 04, 2022
Programmatic interface to Synapse services for Python

A Python client for Sage Bionetworks' Synapse, a collaborative, open-source research platform that allows teams to share data, track analyses, and collaborate

Sage Bionetworks 54 Dec 23, 2022
Demo of connecting Rasa with Zalo

Demo of connecting Rasa with Zalo

6 Jul 25, 2022