在Python中模拟外部函数的返回类型
假设我们有以下Python函数:在Python中模拟外部函数的返回类型,python,unit-testing,testing,mocking,Python,Unit Testing,Testing,Mocking,假设我们有以下Python函数: def lookup_current_prices_dict(stocks): prices = {} for stock in stocks: prices[stock] = stock_price_toolkit.get_current_price(stock) return prices 我想为这个函数编写一个单元测试,但我不想依赖于使用stock\u price\u toolkit模块查找的价格。实际上,我想
def lookup_current_prices_dict(stocks):
prices = {}
for stock in stocks:
prices[stock] = stock_price_toolkit.get_current_price(stock)
return prices
我想为这个函数编写一个单元测试,但我不想依赖于使用stock\u price\u toolkit
模块查找的价格。实际上,我想告诉stock\u price\u toolkit
在调用get\u current\u price()
时始终返回1.00
,这样我就可以测试函数的其余部分了
我知道这可以使用mock来完成,但我找不到任何关于如何完成这项特定任务的好文档。使用,并返回mock对象集:
import stock_price_toolkit
def lookup_current_prices_dict(stocks):
prices = {}
for stock in stocks:
prices[stock] = stock_price_toolkit.get_current_price(stock)
return prices
#####
import mock
# from unittest import mock # If you're using Python 3.x
with mock.patch('stock_price_toolkit.get_current_price') as m:
m.return_value = 1.0
assert lookup_current_prices_dict(['stock1', 'stock2']) == {
'stock1': 1.0, 'stock2': 1.0
}
或者,您可以指定return\u value
作为mock.patch
的关键字参数:
with mock.patch('stock_price_toolkit.get_current_price', return_value=1.0) as m:
assert lookup_current_prices_dict(['stock1', 'stock2']) == {
'stock1': 1.0, 'stock2': 1.0
}
您可以使用
mock.patch
执行此操作,如下所示:
with patch('sock_price_toolkit.get_current_price') as m:
m.return_value = '1.00'
prices = lookup_current_prices_dict(stocks)
检查官方确切的方法将略微取决于您使用的测试模块,但这将为您指明正确的方向:
try:
from unittest import mock # Python 3
except ImportError:
import mock # Third-party module in Python 2
with mock.patch('stock_price_toolkit.get_current_price') as mock_price:
mock_price.return_value = 1.0
expected = {'STOC': 1.0, 'STOK': 1.0}
assert lookup_current_prices(['STOC', 'STOK']) == expected