如何为pymssql编写pytest?

how to write pytest for pymssql?

我正在尝试编写 pytest 以通过模拟数据库来测试以下方法。如何在不实际连接到真实数据库的情况下模拟数据库连接 server.I 尝试使用示例测试用例。我不确定这是否是正确的方法。如有错误请指正

//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

请帮忙。

尝试模拟一个模块很困难。模拟方法调用很简单。像这样重写你的测试:

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 本身。