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?