python mock unittest:'self'参数缺少默认值

时间:2017-01-31 03:51:26

标签: python python-mock

我正在尝试测试一个调用另一个类方法的类方法。我已经看到了这个问题,但我认为这有点不同。我尝试了question的答案,但它没有用。我继续得到这个错误:

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

以下是测试的代码:

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)

以下是我要测试的类方法的代码:

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)

提前致谢!

1 个答案:

答案 0 :(得分:1)

我解决了。我不得不删除auto_spec=True而不传递关键字参数。

这有效:

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)