'Pytest - Test for database connection using object Mocking

I have class MySQL contains methods to fetch all databases user has access to. Which uses decorator for database connection. I don't want to do the actual database call so I want to mock.

I want to write test case for this, may be I want to check if fetchall() is called.

class_file.py
def decorator(class_method):
    @retry(exception_list=(DatabaseConnectionException))
    def with_connection_(class_object):
        try:
            class_object.connection = connect(host=class_object.host, port=class_object.port, user=class_object.username, password=class_object.password)
            result = class_method(class_object)
        except mysql.connector.Error as err:
            if err.errno in [errorcode.CR_CONN_HOST_ERROR, errorcode.CR_CONN_HOST_ERROR]:
                raise DatabaseConnectionException(err.errno, err.msg)
        return result
    return with_connection_


class MySQL:
    """This class encapsulates all module logic."""
    def __init__(self, config, logger):
        self.logger = logger
        self.retry_count = int(config.get_value("retry_count"))
        self.host = config.get_value("mysql.host_name")
        self.port = config.get_value("mysql.port_name")
        self.username = config.get_value("mysql.user_name")
        self.password = config.get_value("mysql.user_password")

    @decorator
    def get_databases(self):
        """Fire SQL query to fetch all the databases, it's size in MB and Created Time
           of each database authenticated user has access to.
           Returns:
                Generator object contains database information.
        """
        self.logger.info("Going for fetch all")

        self.cursor = self.connection.cursor()
        query = """SELECT table_schema 'DB Name',
                  ROUND(SUM(data_length + index_length) / 1024 / 1024, 1) 'DB Size in MB',
                  create_time 'Created At'
                  FROM information_schema.tables
                  WHERE table_schema not in ('mysql','sys','information_schema','performance_schema')
                  GROUP BY table_schema,create_time"""
        self.cursor.execute(query)
        data = self.cursor.fetchall()
        yield data

I am new at pytest and trying to test is like below but it's not working for me.

def test_get_databases():
    with mock.patch(target='mysql.connector.connect') as m:
        object = create_mysql_object()
        object.connection = m.return_value
        object.cursor = object.connection.cursor.return_value
        object.cursor = object.cursor.execute.return_value
        print("object.cursor-->",object.cursor)
        result =  object.cursor.fetchall.return_value
        print ("result-->",result)
        object.cursor.execute.fetchall.assert_called()

I am getting an error

FAILED tests\test_mysql_client.py::test_get_databases - AssertionError: Expected 'fetchall' to have been called.

Blockquote



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source