我在 python 中有一个 SnowflakeApi 类,它只是作为 SnowflakeConnection 类之上的包装器。我的 SnowflakeApi 是
import logging
import os
from snowflake.connector import connect
class SnowflakeApi(object):
"""
Wrapper to handle snowflake connection
"""
def __init__(self, account, warehouse, database, user, pwd):
"""
Handles snowflake connection. Connection must be closed once it is no longer needed
:param account:
:param warehouse:
:param database:
"""
self.__acct = self._account_url(account)
self.__wh = warehouse
self.__db = database
self.__connection = None
self.__user = user
self.__pwd = pwd
def __create_connection(self):
try:
# set the proxy here
conn = connect(
account=self.__acct
, user=self.__user
, password=self.__pwd
, warehouse=self.__wh
, database=self.__db
)
return conn
except:
raise Exception(
"Unable to connect to snowflake for user: '{0}', warehouse: '{1}', database: '{2}'".format(
self.__user, self.__wh, self.__db))
def get_connection(self):
"""
Gets a snowflake connection. If the connection has already been initialised it is returned
otherwise a new connection is created
:param credentials_func: method to get database credentials.
:return:
"""
try:
if self.__connection is None:
self.__connection = self.__create_connection()
return self.__connection
except:
raise Exception("Unable to initalise Snowflake connection")
def close_connection(self):
"""
Closes snowflake connection.
:return:
"""
self.__connection.close()
SnowflakeApi 的命名空间是 connection.snowflake_connection.SnowflakeApi(即我在名为 connections 的文件夹中有 snowflake_connection.py)
我想使用 pytest 和 unittest.mock 为这个类编写单元测试。问题是我想模拟“连接”,以便返回一个 MagicMock 对象并且不进行数据库调用。到目前为止,我已经尝试过:
- monkeypatch.setattr(connections.snowflake_connection,"connect",return_value = "")
- 将我原来的课程改为只导入雪花。然后我创建了一个模拟对象并使用了 monkeypatch.setattr(snowflake_connection,"snowflake",my_mock_snowflake)。那也没用
简而言之,我尝试了其他一些方法,但没有任何效果。我想做的只是模拟雪花连接,因此不会进行实际的数据库调用。