python - 模拟 psycopg2 连接以测试是否插入了数据
问题描述
class Test_Postgres(unittest.TestCase):
def setUp(self):
#mock connection
conx = Mock()
#mock cursor
cursor = MagicMock()
cursor.__enter__.return_value = MagicMock()
cursor.__exit__ = MagicMock()
#define cursor as output of connection cursor
conx.cursor.return_value = cursor
#add conx to set-up for use across tests
self.conx = conx
@patch('__main__.psycopg2')
def testWriteStats(self, mock_postgres_sql):
#Test that the mocked library matches the library itself
self.assertIs(psycopg2, mock_postgres_sql)
#set mock library connection as mock connection
mock_postgres_sql.connect.return_value = self.conx
print(mock_postgres_sql.connect.return_value)
db = Statistics()
db.insert(statistics_data)
# self.assertTrue(mock_result.execute.called)
self.assertTrue(mock_postgres_sql.connect.cursor().called)
上面的代码试图对 psycopg2 连接/游标进行建模,以便可以独立于连接依赖项测试另一个函数(其中插入到数据库方法)。
我真的很挣扎,因为我是修补/模拟的新手。
目前我的代码失败了:
Traceback (most recent call last):
File "c:\program files (x86)\python38-32\lib\unittest\mock.py", line 1342, in patched
return func(*newargs, **newkeywargs)
File "test.py", line 44, in testWriteStats
self.assertTrue(mock_postgres_sql.connect.cursor().called)
AssertionError: False is not true
我正在调用的附加函数可以在以下行的第一个代码片段中看到:
...
db = Statistics()
db.insert(statistics_data)
...
本节调用以下内容:
def insert(self, row):
#magic variables
field_names = row.keys()
number_of_fields = len(
field_names
)
# Produces string in the form: `(Field_1, Field_2, Field_3 ...etc)`
specified_fields_string = self.list_to_query_string(
field_names
)
#Produces string in the form: `(%s, %s, %s ... etc)`
values_placeholder_format = self.list_to_query_string(
["%s"] * number_of_fields
)
query_string = f"INSERT INTO {self.table_name} {specified_fields_string} VALUES {values_placeholder_format}"
#Define the values to be used within the query string
params = list(row.values())
# Execute query
connection = psycopg2.connect(**database_settings)
cursor = connection.cursor()
cursor.execute(query_string, params)
我真的需要一些指导,通过对我的设置的反馈或对可以对上述代码片段进行更改的想法,使 psycopg2 的测试进展到有用的东西。
解决方案
推荐阅读
- x86 - 操作码 1 中的 8086 d 位:更常见的值是 0 还是 1?
- c++ - 有像“pthread_getcancelstate”这样的函数吗?
- java - 如何在 JAVA 中实现瓦片无缝算法?
- windows - 批量连接视频对
- c# - AcquireTokenByAuthorizationCode 在使用 Azure Active Directory 的 ASP.NET MVC 的单租户应用程序中引发新异常
- knockout.js - Knockout Sortables、Draggables 和 Droppables - 在 droppables 之间移动的问题
- javascript - 格式化 hAxis 到日期 - Google Chart
- azure-data-factory - 是否存在数据工厂需要成为 Azure 订阅所有者的情况?
- postgresql - 将 psql 转储恢复到另一个(新)数据库名称 -d/--dbname 和 -f/--file 不能一起使用
- jquery - 如何通过ajax将JQuery Datatable与列表绑定