title: How to mock mongodb when it is called from another function?
body: <p>I need help while mocking mongodb. I am using <a href="https://github.com/mongomock/mongomock" rel="nofollow noreferrer">mongomock</a> to mock mongodb.</p>
  
  <p>My project structure is:</p>
  
  <blockquote>
    <p>-- my_mongo.py<br>
    -- code.py<br>
    -- my_test.py</p>
  </blockquote>
  
  <p><strong>my_mongo.py</strong> has :        </p>
  
  <pre><code>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
  </code></pre>
  
  <p>and <strong>code.py</strong> has</p>
  
  <pre><code>import my_mongo
  
  def action():
      #do somethings
      my_mongo.insert(id, data)
  </code></pre>
  
  <p>and <strong>my_test.py</strong> has</p>
  
  <pre><code>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()
  </code></pre>
  
  <p>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.</p>
  
  <p>What am I missing?</p>