我正在嘗試撰寫 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
請幫忙。
uj5u.com熱心網友回復:
試圖模擬一個模塊很困難。模擬方法呼叫很簡單。像這樣重寫你的測驗:
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://www.uj5u.com/ruanti/366157.html
上一篇:無法使用記憶體中的MassTransit從單元測驗發送訊息
下一篇:如何測驗Laravel登錄事件
