繁体   English   中英

Python Unittest 使用参数模拟函数

[英]Python Unittest mocking a function with an argument

我正在尝试模拟一个具有调用另一个方法的参数的函数。

我知道在没有参数的情况下修补函数你这样做

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM