Django.fun

Python unittest change mock patch value on fly

I'm having trouble while dealing with patching. I'm using mock from unittest library. While testing check_codes() view I would like to set another values to db.find_one()

api.utils.py

from pymongo import MongoClient
import os

def get_share_code_collection():
    client = MongoClient(os.getenv("DB_HOST"))
    db_handle = client[os.getenv("DB_NAME")]
    return db_handle["share_codes"]

views.py

def check_codes(self, request):
    db = get_share_code_collection()
    data = db.find_one({"specialist_id": {"$exists": True}}) 

test_views.py

 from unittest import mock
 @mock.patch("api.utils.get_share_code_collection")
 def test_share_code_correct_no_share_types(
     self, mocked_collection, mocked_share_code, user_model
 ):
     mocked_collection().find_one.return_value = True
     ...

 @mock.patch("api.utils.get_share_code_collection")
 def test_share_code_no_start_time(
     self, mocked_collection, user_model
 ):
    mocked_collection().find_one.return_value = False
     ...
        

The only workaround I found is setting

mocked_collection().find_one.side_effect = [True,False]

but once it is initialized I can't add values. How can I deal with the problem?

Answers: 0