gpt4 book ai didi

python - 修补一个方法而不改变该方法的工作方式?

转载 作者:行者123 更新时间:2023-11-30 23:21:06 24 4
gpt4 key购买 nike

我正在尝试测试是否使用某些值调用 pandas 方法。

但是,仅通过应用 @patch 装饰器就会导致修补的方法在 pandas 中抛出 ValueError,而实际方法不会。我只是想测试 Stock.calc_sma 是否正在调用底层 pandas.rolling_mean 函数。

我假设@patch装饰器基本上向我正在修补的东西添加了一些“神奇”方法,这些方法允许我检查函数是否被调用。如果是这种情况,为什么无论修补与未修补,pandas.rolling_mean 函数的行为都不相同?

应用程序/models.py

import pandas as pd
class Stock: # i've excluded a bunch of class methods, including the one that sets self.data, which is a DataFrame of stock prices.
def calc_sma(self, num_days)
if self.data.shape[0] > num_days: # Stock.data holds a DataFrame of stock prices
column_title = 'sma' + str(num_days)
self.data[column_title] = pd.rolling_mean(self.data['Adj Close'], num_days)

应用程序/测试/TestStockModel.py

def setUp(self):
self.stock = MagicMock(Stock)
self.stock.ticker = "AAPL"
self.stock.data = DataFrame(aapl_test_data.data)

@patch('app.models.pd.rolling_mean')
def test_calc_sma(self, patched_rolling_mean):
Stock.calc_sma(self.stock, 3)
assert(isinstance(self.stock.data['sma3'], Series))
patched_rolling_mean.assert_any_call()

错误:test_calc_sma(TestStockModel.TestStockModel)

Traceback (most recent call last):
File "/Users/grant/Code/python/chartflux/env/lib/python2.7/site-packages/mock.py", line 1201, in patched
return func(*args, **keywargs)
File "/Users/grant/Code/python/chartflux/app/tests/TestStockModel.py", line 26, in test_calc_sma
Stock.calc_sma(self.stock, 3)
File "/Users/grant/Code/python/chartflux/app/models.py", line 27, in calc_sma
self.data[column_title] = pd.rolling_mean(self.data['Adj Close'], num_days)
File "/Users/grant/Code/python/chartflux/env/lib/python2.7/site-packages/pandas/core/frame.py", line 1887, in __setitem__
self._set_item(key, value)
File "/Users/grant/Code/python/chartflux/env/lib/python2.7/site-packages/pandas/core/frame.py", line 1967, in _set_item
value = self._sanitize_column(key, value)
File "/Users/grant/Code/python/chartflux/env/lib/python2.7/site-packages/pandas/core/frame.py", line 2017, in _sanitize_column
raise ValueError('Length of values does not match length of '
ValueError: Length of values does not match length of index

最佳答案

>>> import os
>>> os.getcwd()
'/'
>>> from unittest.mock import patch
>>> with patch('os.getcwd'):
... print(os.getcwd)
... print(os.getcwd())
... print(len(os.getcwd()))
...
<MagicMock name='getcwd' id='4472112296'>
<MagicMock name='getcwd()' id='4472136928'>
0

默认情况下,patch 用真正通用的模拟对象替换内容。如您所见,调用模拟只会返回另一个模拟。即使替换的对象没有 len,它的 len 也为 0。它的属性也是通用模拟。

因此,要模拟行为需要额外的参数,例如:

>>> with patch('os.getcwd', return_value='/a/wonderful/place'):
... os.getcwd()
...
'/a/wonderful/place'

或者“通过”:

>>> _cwd = os.getcwd
>>> with patch('os.getcwd') as p:
... p.side_effect = lambda: _cwd()
... print(os.getcwd())
...
/

https://docs.python.org/3.5/library/unittest.mock-examples.html中有一个类似的例子

关于python - 修补一个方法而不改变该方法的工作方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25097061/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com