I'm trying to make a MagicMock instance of the mysql connector, but I need for the method fetchone() to return None.
This is what I've done so far:
with mock.patch('mysql.connector.cursor') as dbmock, \
mock.patch('mysql.connector.connect', mock.MagicMock()):
dbcursor_mock = dbmock.return_value # Get the mock for the cursor
dbcursor_mock.fetchone.return_value = None # Set the return value of fetchone
The problem is that this returns a MagicMock instance and not None.
Now, if I remove the second patch(), it does work:
with mock.patch('mysql.connector.cursor') as dbmock):
dbcursor_mock = dbmock.return_value
dbcursor_mock.fetchone.return_value = None # this does return None, Why?
But then my code will try to connect to the db and fail.
I'm using the MySQL cursor within a context manager like this:
def fetch_a_row():
# establishing the connection
with mysql.connector.connect(user='root',password='password',host='127.0.0.1',database='mydb') as conn:
# Creating a cursor object using the cursor() method
cursor = conn.cursor()
cursor.execute("SELECT * FROM mytable")
# return the fetchone() output
return cursor.fetchone()
How can I make an instance of MagicMock return None?
Use of patch.object() and side_effect
I have write a test which can be force
fetchone()to returneNoneby the use of:with mock.patch()to get the mock object which avoids the real connection to the database (exactly as in your code)with mock.path.object()to mock the method cursor()side_effectinstead ofreturn_valueto forcefetchone()to returnNoneA test adapt for your need should be the following:
In the code I have written the function
fetch_one_row()which simulate your production code.EDIT: I have edited the answer because the OP have add his code for the function
fetch_a_row().Test with the context manager
You have edited your question and add the code of the function
fetch_a_row()with the use of the context manager.When you use a context manager is called the method
__enter__()(see this link) and this method returns the objectconn. So with context manager I have to modify the test function as following: