python - Python Unittest 用参数模拟函数
问题描述
我正在尝试模拟一个具有调用另一个方法的参数的函数。
我承认在没有参数的情况下修补函数你这样做
def monthly_schedule(self, month):
response = requests.get(f'http://company.com/{self.last}/{month}')
if response.ok:
return response.text
else:
return 'Bad Response!'
def test_monthly_schedule(self):
with patch('employee.requests.get') as mocked_get:
mocked_get.return_value.ok = True
mocked_get.return_value.text = 'Success'
schedule = self.emp_1.monthly_schedule('May')
mocked_get.assert_called_with('http://company.com/Schafer/May')
self.assertEqual(schedule, 'Success')
如何模拟具有如下所示语法的函数?
Stock(ticker) 是导入的,与“Stocks”类不同。
from iexfinance.stocks import Stock
class Stocks:
def price(self, ticker):
price = Stock(ticker).get_price()
self.myStockData.at["price", ticker] = price
具有这种性质的测试似乎会在每个变体上抛出“ModuleNotFoundError”
with patch('stocks.Stock(ticker).get_price') as mock:
with patch('Stock(ticker).get_price') as mock:
with patch('stocks.get_price') as mock:
import unittest
from unittest.mock import patch
from stocks import Stocks
class MyTestCase(unittest.TestCase):
def test_price(self):
with patch('stocks.Stock(ticker).get_price') as mock:
mock = 300.00
self.test.price('AAPL')
self.assertEqual(self.test.myStockData.at["price", 'AAPL'], 300)
为简洁起见,并未显示所有代码。任何帮助,将不胜感激。谢谢!
解决方案
Stock(ticker)
将返回某个类的对象,假设该类是A
. 然后,调用Stock(ticker).get_price
将调用方法A.get_price
。这是你必须修补的。
推荐阅读
- python - *args in recursion: TypeError: unsupported operand type(s) for +: 'int' and 'tuple'
- java - 传递默认值时,@Value 注释不会从应用程序属性中读取任何值
- animation - 如何使 Jetpack Compose Image 动画无限
- kotlin - 在集合中查找元素并将其连同其索引一起返回
- mysql - 禁用mysql查询无法禁用外键约束
- wordpress - WP - add_filter() 没有从古腾堡块回调传递值
- python - 如何匹配两个数据框列并在 Python 中的单独列上返回匹配值?
- flutter - 如何在颤振 modal_bottom_sheet 中添加嵌套滚动?
- java - Cordova:当应用程序关闭时,从 JAVA 调用 JS 方法
- java - 图形 2D 不在 Java 中绘制图像