我有一个函数,根据条件将numpy数组转换为包含True或False的数组,然后将彼此相邻的True或False条目分组并计算每个组的长度.这是为了确定给定月份降水数据中干燥法术或湿法术的长度.
这是功能:
import itertools
def spell(X, kind='wet', how='mean', threshold=0.5):
if kind=='wet':
condition = X>threshold
else:
condition = X<=threshold
length = [sum(1 if x==True else nan for x in group) for key,group in itertools.groupby(condition) if key]
if not length:
res = 0
elif how=='mean':
res = np.mean(length)
else:
res = np.max(length)
return res
Run Code Online (Sandbox Code Playgroud)
因此,基本上可以选择确定湿法或干法术的平均长度或最大长度,给出一系列大量的降水数据,默认参数设置为湿法术的平均长度.
我将此函数与pandas一起应用于历史记录的每个月:
#Create example dataframe
np.random.seed(1324)
idx = pd.DatetimeIndex(start='1960-01-01', periods=100, freq='d')
values = np.random.random(100)
df = pd.DataFrame(values, index=idx)
#Apply function
df.resample('M', how=spell)
Run Code Online (Sandbox Code Playgroud)
而我得到的是:
0
1960-01-31 1.555556
1960-02-29 1.500000 …Run Code Online (Sandbox Code Playgroud) 我有这个my_module.py:
def _sub_function(do_the_thing=True):
if do_the_thing:
do_stuff()
else:
do_something_else()
def main_function():
# do some stuff
if some_condition:
return _sub_function()
else:
return _sub_function(do_the_thing=False)
Run Code Online (Sandbox Code Playgroud)
然后我有这个测试test_my_module.py:
import unittest
from unittest import mock
import my_module
class TestMyModule(unittest.TestCase):
@mock.patch.object("my_module._sub_function", "__defaults__", (False,))
def test_main_function(self):
print(my_module.main_function())
if __name__ == "__main__":
unittest.main()
Run Code Online (Sandbox Code Playgroud)
我有一个函数_sub_function,它采用默认参数来决定它是否执行某些步骤。通常,main_function计算何时需要执行这些操作并覆盖该默认参数。不幸的是,在运行测试时,我无法在通常需要时执行这些操作。
所以我的想法是在我的测试中使用默认参数_sub_function来修补函数以猴子修补该参数,以便False它在测试期间跳过这些操作。不幸的是,我无法使用这个问题中的代码,因为我正在测试main_function,而不是,所以我的测试中_sub_function没有。只能将被修补的对象作为参数,而不是包含对象导入路径的字符串(就像那样),因此上面的代码不起作用,它会引发一个on line._sub_functionmock.patch.objectmock.patchAttributeError: my_module._sub_function does not have the attribute '__defaults__'mock.patch.object()
有没有办法使用该函数的字符串导入路径来修补函数的默认参数。
或者有更好的方法来实现我想要的吗?