@@ patch模拟到mysqldb连接不起作用

问题描述 投票:0回答:1

我正在编写使用MySQLdb连接到Mysql的Python应用程序的单元测试。有一个函数可以连接到Mysql db并返回连接对象。

def connect_to_database():
    conn = MySQLdb.connect(host=db_pb2['mysql_host'],
                          user=db_pb2['mysql_user'],
                          passwd=db_pb2['mysql_password'],
                          db=db_pb2['mysql_db'])
    return conn

还有一个使用上述连接执行查询的功能

def execute_query():
    cur = connect_to_database().cursor()
    a = cur.execute("query")
    if a > 0:
        result = cur.fetchall()
    return result

我写了@patch来模拟cur.fetchall()和cur.execute()方法的返回值

@patch('application.module1.data_adapters.connect_to_database')
def test_daily_test_failures(self, db_connection):
    db_connection.cursor().execute.return_value = 1
    db_connection.cursor().fetchall. \
        return_value = ((1,5,6),)
    self.assertEqual((execute_query(),
                       ((1,5,6),))

我收到以下错误:

if a > 0:
TypeError: '<=' not supported between instances of 'MagicMock' and 'int'

似乎补丁函数中的返回值未按预期工作

python unit-testing mocking mysql-python patch
1个回答
0
投票

您的修补需要更多的精力。

@patch('application.module1.data_adapters.connect_to_database')
def test_daily_test_failures(self, connect_to_database):
    db_connection = MagicMock()
    connect_to_database.return_value = db_connection  # 1.
    mock_cursor = MagicMock()
    db_connection.cursor.return_value = mock_cursor   # 2.
    mock_cursor.fetchall.return_value = ((1,5,6),)
    self.assertEqual((execute_query(),
                       ((1,5,6),))
  1. 您正在修补符号connect_to_database-不会模拟对该函数的调用。您需要指定“调用该符号时,请执行此操作”
  2. [当调用模拟函数时,您不能像这样:db_connection.cursor().-您需要使db_connection.cursor返回一个模拟,然后为该模拟对象指定.return_value
© www.soinside.com 2019 - 2024. All rights reserved.