首页 > 解决方案 > 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)

为简洁起见,并未显示所有代码。任何帮助,将不胜感激。谢谢!

标签: pythonpython-3.xunit-testingtestingmonkeypatching

解决方案


Stock(ticker)将返回某个类的对象,假设该类是A. 然后,调用Stock(ticker).get_price将调用方法A.get_price。这是你必须修补的。


推荐阅读