Search code examples
pythonunit-testingmockingpython-unittestpatch

python unittest : mock cursor.fetchall() to return a dummy value inside a function


#file utils.py 
def update_configuration(configuration, mysql_client):

    query = "SELECT * from some database"

    cursor = mysql_client.execute_query(query)

    function_mapping = cursor.fetchall()

    cursor.close()

    configuration["mapping"] = {}
    for (display_name, formula_name) in function_mapping:
        configuration["formula_mapping"][formula_name] = display_name


#main.py 
def main_func(configuration): 
    mysql_client = get_mysql_connection() 
    ut.update_configuration(configuration, mysql_client) #ut means utils.py

#test.py
@mock.patch("src.utils.cursor.fetchall",return_value = [1,2,3,4])  
@mock.patch("src.main.get_sql_connection", return_value = mock.Mock()) 
def test_initiate_calc(self, dummy1): 
    # perform integration testing on "main_func"

The project structure is as shown below

--project 
  --src 
    --tests 
      --test_main.py 
    --main.py 
    --utils.py

When I try to mock the cursor.fetchall() to return some value I get an error saying "ModuleNotFoundError: No module named 'src.utils.cursor'; 'src.utils' is not a package"

Need help in finding a way to get the function_mapping = cursor.fetchall() value some return value


Solution

  • You can also try cursor.fetchall.side_effect = "some-value"

    Something like this:

      @patch('connector')
      def test_create_table(self, connector):
            connection = Mock()
            cursor = Mock()
    
            connector.connect.return_value = connection
            connection.cursor.return_value = cursor
            cursor.fetchall.side_effect = "List of tuple"
            connector.connect.assert_called_with("creds")
            cursor.execute.assert_called_with("statements - you - are - trying - to - execute")
    

    For multiple statements use assert_has_calls.