我有下面的unittest,它需要测试烧瓶路线。
@unittest.mock.patch('flask_login.utils._get_user')
@unittest.mock.patch('flask_sqlalchemy.SQLAlchemy')
def test_attendances_management(self, SQLAlchemy, current_user):
user = MagicMock()
sqlalchemy = SQLAlchemy()
sqlalchemy.engine.return_value = MagicMock()
sqlalchemy.engine.raw_connection.return_value = MagicMock()
sqlalchemy.engine.raw_connection.cursor.return_value = MagicMock()
sqlalchemy.engine.raw_connection.cursor.callproc("get_project_members", [3, 9, 2020]).return_value = ((1, 3, 4),)
current_user.return_value = user
current_user.return_value.role.name = 'Administrator'
current_user.return_value.id = 1
response = self.client.get('attendances/management/3/2020/11')
self.assertEqual(response.status_code, 200)
一切都很好(模拟数据库引擎、raw_connection和游标(,但我有一个问题,即get_project_members不存在。我需要模拟flask-sqlalchemy
或MySQLdb
库的哪一部分,以假装某个过程实际上存在,因为我使用flask-testing
来创建例如某个表`ExampleTabletable.create(db.session.bind(,我不知道如何创建存储过程,也不知道如何使用mock来模拟该过程。
异常日志:
File "C:my_appappattendancesviews.py", line 169, in management
cursor.callproc("get_project_members", [project_id, month, year])
File "c:my_appflaskvenvlibsite-packagesMySQLdbcursors.py", line 365, in callproc
self._query(q)
File "c:my_appflaskvenvlibsite-packagesMySQLdbcursors.py", line 411, in _query
rowcount = self._do_query(q)
File "c:my_appflaskvenvlibsite-packagesMySQLdbcursors.py", line 374, in _do_query
db.query(q)
File "c:my_appflaskvenvlibsite-packagesMySQLdbconnections.py", line 277, in query
_mysql.connection.query(self, query)
_mysql_exceptions.OperationalError: (1305, 'PROCEDURE my_app_test_db.get_project_members does not exist')
我刚刚通过使用cursor.execute
方法解决了这个问题,该方法使用原始查询来创建MySQL过程。此外,我已经有数据库作为SQLAlchemy的实例,所以我不需要模拟已经定义的连接。
@unittest.mock.patch('flask_login.utils._get_user')
def test_attendances_management(self, current_user):
user = MagicMock()
q = "CREATE PROCEDURE `get_project_members` (IN `project_id` INT, IN `month` INT, IN `year` INT) BEGIN END"
connection = db.engine.raw_connection()
cursor = connection.cursor()
cursor.execute(q)
current_user.return_value = user
current_user.return_value.role.name = 'Administrator'
current_user.return_value.id = 1
response = self.client.get('attendances/management/3/2020/11')
self.assertEqual(response.status_code, 200)
类似的答案:使用SQLAlchemy创建存储过程