[Python] How to mock mongodb when it is called from another function?

Discussão em 'Python' iniciado por Stack, Fevereiro 13, 2025.

  1. Stack

    Stack Membro Participativo

    I need help while mocking mongodb. I am using mongomock to mock mongodb.

    My project structure is:


    -- my_mongo.py
    -- code.py
    -- my_test.py
    ​

    my_mongo.py has :

    from pymongo import MongoClient

    def get_db():
    client = MongoClient(os.environ['MONGODB_URI'])
    db = client['my_db']
    return db

    def insert(id, data):
    return get_db().results.insert_one(
    {
    "id": id,
    "data":df.to_json(),
    }).id


    and code.py has

    import my_mongo

    def action():
    #do somethings
    my_mongo.insert(id, data)


    and my_test.py has

    import mongomock
    import my_mongo
    from unittest import mock


    with patch.object(my_mongo.get_db().client, "client", mongomock.MongoClient()):
    import code

    def test_action_1():
    my_mongo.insert = mock.Mock(return_value=1)
    code.action()

    def test_action_2():
    with patch.object(my_mongo.get_db(), "get_db", mongomock.MongoClient().db):
    code.action()


    It throws pymongo.errors.ServerSelectionTimeoutError for both tests. So, It still goes into the insert_one() method in my_mongo.py. I expect in test_action_1 my_mongo.insert returns 1, but it doesn't.

    What am I missing?

    Continue reading...

Compartilhe esta Página