【发布时间】:2019-08-20 05:26:32
【问题描述】:
我试图模拟 pandas 应用函数的返回值,但似乎无法让它工作。
我正在尝试创建一个模拟返回对象(在这种情况下,我的函数返回一个 dict),然后从我在 pandas.apply 中调用的函数中获得该返回。我将该值放在单元测试的 @patch 装饰器中,但它仍然最终调用了真正的函数
def pandas_function():
data = {'one thing': {0: 1, 1: 2, 2: 3, 3: 4},'second thing': {0: 0.1, 1: 0.2, 2: 1.0, 3: 2.0}}
df = pd.DataFrame(data)
val = df.apply(real_function, axis=1)
return val
def real_function(row):
return dict("foo": row['one thing'])
Unit test class:
def stub_foo():
foo="test"
return dict("foo":foo)
Unit test class:
@patch('package.module.real_function',return_value=stub_foo())
def pandas_test(self, stub_foo)
expected = pd.Series(data={0: {'foo': "test"}, 1: {'foo': "test"}, 2: {'foo': "test"}, 3: {'foo': "test"}})
real = class.pandas_function()
assert_series_equal(expected, real)
运行测试时的响应:
AssertionError: Series are different
Series values are different (100.0 %)
[left]: [{'foo': 'test'}, {'foo': 'test'}, {'foo': 'test'}, {'foo': 'test'}]
[right]: [{'foo': 1.0}, {'foo': 2.0}, {'foo': 3.0}, {'foo': 4.0}]
如何让 unittest 模拟来自 apply 函数的响应对象?
【问题讨论】: