我试图通过模拟数据库来编写pytest来测试以下方法。如何模拟数据库连接,而不实际连接到真正的数据库服务器。我尝试了用样例测试用例。我不知道这样做是否正确。如果我错了,请纠正我。
//fetch.py
import pymssql
def cur_fetch(query):
with pymssql.connect('host', 'username', 'password') as conn:
with conn.cursor(as_dict=True) as cursor:
cursor.execute(query)
response = cursor.fetchall()
return response
//test_fetch.py
import mock
from unittest.mock import MagicMock, patch
from .fetch import cur_fetch
def test_cur_fetch():
with patch('fetch.pymssql', autospec=True) as mock_pymssql:
mock_cursor = mock.MagicMock()
test_data = [{'password': 'secret', 'id': 1}]
mock_cursor.fetchall.return_value = MagicMock(return_value=test_data)
mock_pymssql.connect.return_value.cursor.return_value.__enter__.return_value = mock_cursor
x = cur_fetch({})
assert x == None结果是:
AssertionError: assert <MagicMock name='pymssql.connect().__enter__().cursor().__enter__().fetchall()' id='2250972950288'> == None请帮帮忙。
发布于 2021-11-24 19:27:51
试图模拟一个模块是很困难的。模拟方法调用很简单。像这样重写您的测试:
import unittest.mock as mock
import fetch
def test_cur_tech():
with mock.patch('fetch.pymssql.connect') as mock_connect:
mock_conn = mock.MagicMock()
mock_cursor = mock.MagicMock()
mock_connect.return_value.__enter__.return_value = mock_conn
mock_conn.cursor.return_value.__enter__.return_value = mock_cursor
mock_cursor.fetchall.return_value = [{}]
res = fetch.cur_fetch('select * from table')
assert mock_cursor.execute.call_args.args[0] == 'select * from table'
assert res == [{}]在上面的代码中,我们显式地模拟pymyssql.connect,并提供适当的假上下文管理器,以使cur_fetch中的代码高兴。
如果cur_fetch将连接作为参数来接收,而不是调用pymssql.connect本身,您可以简化一些事情。
https://stackoverflow.com/questions/70101555
复制相似问题