gpt4 book ai didi

python单元测试补丁模拟方法不返回返回值

转载 作者:行者123 更新时间:2023-12-05 01:37:35 24 4
gpt4 key购买 nike

我正在尝试编写一个测试用例 test_is_user_present()redshift_util.py 脚本调用另一个函数 execute_redshift_sql()

我将函数 execute_redshift_sql() 的预期返回值设置为 1 。但是我从来没有在调用函数后从结果中得到这个值!我还打印了一些值用于调试目的

你可以看看下面的测试用例

from mock import patch, Mock, MagicMock
from cia_admin_operations.redshift_util import execute_redshift_sql
@patch('cia_admin_operations.redshift_util.execute_redshift_sql')
def test_is_user_present(mock_execute_redshift_sql):
ldap_user = "dummy_user"
mock_out = Mock()

user_check_sql = "SELECT COUNT(1) FROM pg_user WHERE usename = '{}';".format(ldap_user)

mock_execute_redshift_sql.return_value = 1
print(mock_execute_redshift_sql())

result = execute_redshift_sql(mock_out, user_check_sql)
print(result)
print(result())
> assert result() == 1
E AssertionError: assert <Mock name='m...749067684720'> == 1
E -<Mock name='mock.query().getresult()()' id='139749067684720'>
E +1

test/test_cia_admin_operations.py:51: AssertionError
----------------------------- Captured stdout call -----------------------------
1
<Mock name='mock.query().getresult()' id='139749067684776'>
<Mock name='mock.query().getresult()()' id='139749067684720'>

redshift_util.py

def execute_redshift_sql(connection, sqlQuery):
"""Executes redshift query"""

logger.info("Executing following SQL query :\n %s" % sqlQuery)

try:
result = connection.query(sqlQuery)
logger.info("Redshift query is successfully executed.")
except Exception as e:
logger.error("Query not executed : %s" % e)
return None
# return only if the result has some data
if result:
logger.info("Query result :\n %s" % result)
return result.getresult()
else:
return 0

最佳答案

您必须在函数导入时对其进行修补。解决此问题的一种可能性是使用:

from mock import patch, Mock
import cia_admin_operations.redshift_util

@patch('cia_admin_operations.redshift_util.execute_redshift_sql')
def test_is_user_present(mock_execute_redshift_sql):
ldap_user = "dummy_user"
mock_out = Mock()

user_check_sql = "SELECT COUNT(1) FROM pg_user WHERE usename = '{}';".format(ldap_user)

mock_execute_redshift_sql.return_value = 1

result = cia_admin_operations.redshift_util.execute_redshift_sql(mock_out, user_check_sql)
print(result)

在你的例子中,你已经模拟了包中的函数,但使用了本地导入的模块。你总是要检查where to patch .

上面我适配了import,你也可以适配patching:

from mock import patch, Mock
from cia_admin_operations.redshift_util import execute_redshift_sql

@patch('redshift_test.execute_redshift_sql')
def test_is_user_present(mock_execute_redshift_sql):
ldap_user = "dummy_user"
mock_out = Mock()

user_check_sql = "SELECT COUNT(1) FROM pg_user WHERE usename = '{}';".format(ldap_user)

mock_execute_redshift_sql.return_value = 1

result = execute_redshift_sql(mock_out, user_check_sql)
print(result)

(您必须用 redshift_test 替换 patch 装饰器中的测试模块名称)

关于python单元测试补丁模拟方法不返回返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60882117/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com