I am trying to mock the fetchall()
from dbconnection
cursor object. I am trying the following code with expected return value. However, it was not returning the value. I have the answer now and edited the unit test to include the answer also
db.py
def query_db(db_connection, query):
"""
:param db_connection: dbconnection object
:param query: query to be executed
:return:
"""
cur = db_connection.cursor()
try:
logging.info(f"Query to be executed : {query}")
cur.execute(query)
results = cur.fetchall()
logging.info(f"Query Results : {results}")
except Exception:
logging.exception("Exception while executing \'query_db\' function")
raise Exception(f"Error while executing query : {query}. Please check the logs for details")
return results
Test Case:
def test_get_client_object(self):
dbconnection = Mock(name="dbconnection")
mycursor = Mock(name="mycursor")
mycursor.fetchall.return_value = "testing_return_value"
dbconnection.cursor.return_value = mycursor # I was doing dbconnection.cursor = mycursor . ... which caused the error
self.assertEqual("testing_return_value", utils.query_db(dbconnection, 12345))
I got the follwing assertion error. It returned a mock object instead of expected return value.
<Mock name='mycursor().fetchall()' id='4443879760'> != testing_return_value
Expected :testing_return_value
Actual :<Mock name='mycursor().fetchall()' id='4443879760'>
<Click to see difference>