【问题标题】:Mocking return type for an external function in Python在 Python 中模拟外部函数的返回类型
【发布时间】:2015-08-11 01:17:19
【问题描述】:
假设我们有以下 Python 函数:
def lookup_current_prices_dict(stocks):
prices = {}
for stock in stocks:
prices[stock] = stock_price_toolkit.get_current_price(stock)
return prices
我想为此函数编写一个单元测试,但我不想依赖使用stock_price_toolkit 模块查找的价格。实际上,我想告诉stock_price_toolkit 在调用get_current_price() 时始终返回1.00,以便我可以测试函数的其余部分。
我知道这可以使用模拟来完成,但我找不到任何关于如何完成这个特定任务的好的文档。
【问题讨论】:
标签:
python
unit-testing
testing
mocking
【解决方案1】:
您可以使用mock.patch 执行此操作,如下所示:
with patch('sock_price_toolkit.get_current_price') as m:
m.return_value = '1.00'
prices = lookup_current_prices_dict(stocks)
查看官方documentation
【解决方案2】:
使用mock.patch,并设置返回的模拟对象的return_value:
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_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
}
【解决方案3】:
确切的方法将稍微取决于您使用的测试模块,但这应该为您指明正确的方向:
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