我正在尝试使用mock在以下代码中删除cursor.execute(),以便我可以使用格式正确的查询调用execute:
// Module ABC
def buildAndExecuteQuery( tablesAndColumnsToSelect ):
'''Build and execute a query.
Args: tablesAndColumnsToSelect (dict)
- keys are table names, values are columns
'''
query = ..... < logic to build query > ....
from django.db import connections
cursor = connections[ 'mydb' ].cursor()
cursor.execute( query )
如何使用模拟库在python2.7中完成这种类型的模拟?
答案 0 :(得分:1)
由于我不知道你的查询逻辑是什么,我修改了query
以直接通过tables_and_columns_to_select
参数接受一个标记值。
# b_and_ex_q.py
def build_and_execute_query(tables_and_columns_to_select):
"""Build and execute a query.
Args: tablesAndColumnsToSelect (dict)
- keys are table names, values are columns
"""
query = tables_and_columns_to_select # ..... < logic to build query > ....
from django.db import connections
cursor = connections['mydb'].cursor()
cursor.execute(query)
import unittest
from mock import patch, sentinel
from b_and_ex_q import build_and_execute_query
class TestCursorExecute(unittest.TestCase):
@patch('django.db.connections')
def test_build_and_execute_query(self, mock_connections):
# Arrange
mock_cursor = mock_connections.__getitem__('mydb').cursor.return_value
# Act
build_and_execute_query(sentinel.t_and_c)
# Assert
mock_cursor.execute.assert_called_once_with(sentinel.t_and_c)
if __name__ == '__main__':
unittest.main()
答案 1 :(得分:0)
由于有两个异议,我将用示例扩展@G_M答案:
mock
时,我们不应在定义了对象的地方打补丁:基本原理是,您修补在其中查找对象的位置, 它不一定与定义的位置相同。一种 几个例子将有助于澄清这一点。
参考:https://docs.python.org/3/library/unittest.mock.html#where-to-patch
示例:
我们要测试的功能:
# foooo_bar.py
from typing import Optional
from django.db import DEFAULT_DB_ALIAS, connections
def some_function(some_arg: str, db_alias: Optional[str] = DEFAULT_DB_ALIAS):
with connections[db_alias].cursor() as cursor:
cursor.execute('SOME SQL FROM %s;', [some_arg])
测试:
# test_foooo_bar.py
from unittest import mock
from django.db import DEFAULT_DB_ALIAS
from django.test import SimpleTestCase
from core.db_utils.xx import some_function
class ExampleSimpleTestCase(SimpleTestCase):
@mock.patch('foooo_bar.connections')
def test_some_function_executes_some_sql(self, mock_connections):
mock_cursor = mock_connections.__getitem__(DEFAULT_DB_ALIAS).cursor.return_value.__enter__.return_value
some_function('fooo')
# Demonstrating assert_* options:
mock_cursor.execute.assert_called_once()
mock_cursor.execute.assert_called()
mock_cursor.execute.assert_called_once_with('SOME SQL FROM %s;', ['fooo'])