Search code examples
pythonpython-mock

python mock unittest: 'self' parameter lacking default value


I am trying to test a class method that calls another class method. I have seen this question, but I think this is slightly different. I tried the answer to that question, but it was not working. I continue to get this error:

AssertionError: Expected call: run(autocommit=False, parameters=None, sql='SELECT')
Actual call: run(<plugins.bigsql.hooks.bigsql_hook.BigSqlHook object at 0x10b201050>, 'SELECT', False, parameters=None)
'self' parameter lacking default value

Here is the code for the test:

import mock

from plugins.bigsql.hooks import BigSqlHook
from plugins.bigsql.operators import BigSqlOperator


@mock.patch.object(BigSqlHook, 'run', autospec=True)
def test_bigsql_hook(mock_hook_object):
    """Test BigSqlOperator connection is formed correctly."""
    operator = BigSqlOperator(task_id='test', jdbc_conn_id='sqlite_default', sql='SELECT')
    operator.execute(context={})

    mock_hook_object.assert_called_with(sql="SELECT", autocommit=False, parameters=None)

Here is the code for the class method I am trying to test:

import logging

from airflow.operators.jdbc_operator import JdbcOperator

from plugins.bigsql.hooks import BigSqlHook


class BigSqlOperator(JdbcOperator):
    """Extends py:class:`airflow.hooks.jdbc_operator.JdbcOperator` to connect to IBM BigSQL.

    Notes:
        Works the same as JdbcOperator, just uses the BigSqlHook instead
    """

    def execute(self, context):
        """Execute SQL statement on IBM BigSQL."""
        logging.info('Executing: {0}'.format(str(self.sql)))
        hook = BigSqlHook(jdbc_conn_id=self.jdbc_conn_id)
        hook.run(self.sql, self.autocommit, parameters=self.parameters)

Thanks in advance!


Solution

  • I solved it. I had to remove the auto_spec=True and not pass in key word arguments.

    This worked:

    import mock
    
    from plugins.bigsql.hooks import BigSqlHook
    from plugins.bigsql.operators import BigSqlOperator
    
    
    @mock.patch.object(BigSqlHook, 'run')
    def test_bigsql_hook(mock_hook_object):
        """Test BigSqlOperator connection is formed correctly."""
        operator = BigSqlOperator(task_id='test', jdbc_conn_id='sqlite_default', sql='SELECT')
        operator.execute(context={})
    
        mock_hook_object.assert_called_with("SELECT", False, parameters=None)