如何在 python 中对数据库连接 pymysql 进行单元测试?
how to unit test the database connection pymysql in python?
我正在尝试编写单元测试用例,通过模拟数据库来测试以下方法。如何在不实际连接到真实数据库的情况下模拟数据库连接 server.I 尝试使用示例测试用例。我不确定这是否是正确的方法。如有错误请指正
//MySQL.py
class MySQL():
retry_interval = 20000
def link(self, server,port):
try:
return pymysql.connect(server, username='name', passwd='pwd', db='demo', int(port))
sys.stdout.write('Connected to database at {}:{}\n'.format(server,port))
except:
sys.stderr.write('Retry database connection in {} ms...\n'.format(self.retry_interval))
sleep(self.retry_interval/1000.0)
continue
//test.py
from unittest.mock import Mock, MagicMock
from unittest.mock import patch
import MySQL
@patch('MySQL.pymysql')
def testLink(self, mysql_mock):
mock_cursor = Mock.MagicMock()
mysql_mock.connect.return_value.cursor.return_value.__enter__.return_value = mock_cursor
您可以在 MySQL.pymysql
中真正测试的唯一有用的东西是 connect
方法,所以您最好直接修补它:
//test.py
from unittest.mock import Mock, MagicMock
from unittest.mock import patch, call
import MySQL
@patch('MySQL.pymysql.connect')
def testLink(self, connect_mock):
# You can configure a return value for the connection if you need to...
connect_mock.return_value = MagicMock(name='connection_return', return_value=...)
# You can now test that your connection is being called...
self.assertEqual(1, connect_mock.call_count)
# You can also check the call parameters...
self.assertEqual(connect_mock.call_args_list[0], call(server, username='name', passwd='pwd',...))
我正在尝试编写单元测试用例,通过模拟数据库来测试以下方法。如何在不实际连接到真实数据库的情况下模拟数据库连接 server.I 尝试使用示例测试用例。我不确定这是否是正确的方法。如有错误请指正
//MySQL.py
class MySQL():
retry_interval = 20000
def link(self, server,port):
try:
return pymysql.connect(server, username='name', passwd='pwd', db='demo', int(port))
sys.stdout.write('Connected to database at {}:{}\n'.format(server,port))
except:
sys.stderr.write('Retry database connection in {} ms...\n'.format(self.retry_interval))
sleep(self.retry_interval/1000.0)
continue
//test.py
from unittest.mock import Mock, MagicMock
from unittest.mock import patch
import MySQL
@patch('MySQL.pymysql')
def testLink(self, mysql_mock):
mock_cursor = Mock.MagicMock()
mysql_mock.connect.return_value.cursor.return_value.__enter__.return_value = mock_cursor
您可以在 MySQL.pymysql
中真正测试的唯一有用的东西是 connect
方法,所以您最好直接修补它:
//test.py
from unittest.mock import Mock, MagicMock
from unittest.mock import patch, call
import MySQL
@patch('MySQL.pymysql.connect')
def testLink(self, connect_mock):
# You can configure a return value for the connection if you need to...
connect_mock.return_value = MagicMock(name='connection_return', return_value=...)
# You can now test that your connection is being called...
self.assertEqual(1, connect_mock.call_count)
# You can also check the call parameters...
self.assertEqual(connect_mock.call_args_list[0], call(server, username='name', passwd='pwd',...))