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。这是你必须修补的。

最新更新