您好我在继承类中模拟游标对象时遇到了麻烦。 以下是我的代码的一部分:
# classa.py
class ClassA(ClassB):
def __init__(self, params):
ClassB.__init__(params)
# other params
def get_current_attr(self):
sql = "SELECT max(attr) FROM {};".format(self.table_name)
self.rs_cursor.execute(sql)
current_attr = self.rs_cursor.fetchone()[0]
return current_attr
# classb.py
import psycopg2
class ClassB:
def __init__(self, params):
self.redshift_conn = self.open_redshift_connection()
self.redshift_conn.set_isolation_level(
psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
self.rs_cursor = self.redshift_conn.cursor()
现在我想在ClassA的get_current_attr()函数中模拟psycopg2游标。我试着这样做:
@mock.patch("mypackage.classa.classb.psycopg2.connect")
def test_get_current_attr(self, mock_connect):
mock_con = mock_connect.return_value
mock_cur = mock_con.cursor.return_value
mock_cur.fetch_one.return_value = 1
result = self.gap_load_instance.get_current_batch_id()
mock_cur.execute.assert_called_with(
"SELECT max(attr) FROM tablename"
)
我得到了:
引发AssertionError('预期调用:%s \ n不称为'%(期望))
任何人都可以帮我吗?
答案 0 :(得分:0)
模拟整个psycopg2最简单。我为您缺少的功能添加了存根,但是类似的东西应该可以工作:
# classa.py
class ClassA(ClassB):
def __init__(self, params):
super().__init__(params)
# other params
def get_current_attr(self):
sql = "SELECT max(attr) FROM {};".format(self.table_name)
self.rs_cursor.execute(sql)
current_attr = self.rs_cursor.fetchone()[0]
return current_attr
# classb.py
import psycopg2
class ClassB:
def __init__(self, params):
self.redshift_conn = self.open_redshift_connection()
self.redshift_conn.set_isolation_level(
psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
self.rs_cursor = self.redshift_conn.cursor()
self.table_name = "atablename"
def open_redshift_connection(self):
return psycopg2.connect()
然后
from unittest import TestCase, mock
from classa import ClassA
class Tester(TestCase):
@mock.patch("classb.psycopg2")
def test_get_current_attr(self, mock_psycopg2):
mock_cur = mock_psycopg2.connect().cursor()
mock_cur.fetch_one.return_value = 1
a = ClassA({})
result = a.get_current_attr()
mock_cur.execute.assert_called_with(
"SELECT max(attr) FROM {};".format(a.table_name)
)