简体   繁体   English

如何验证使用包括数据帧在内的参数调用了 Python 方法?

[英]How can I verify a Python method was called with parameters including a DataFrames?

I'm using MagicMock to verify that a method was called with specific arguments:我正在使用 MagicMock 来验证是否使用特定参数调用了一个方法:

ClassToMock.method_to_mock = MagicMock(name='method_to_mock')
ClassToMock.method_that_creates_data_frame_and_passes_to_mocking_method()
ClassToMock.method_to_mock.assert_called_with('test_parameter_value', self.get_test_data_frame())

Where self.get_test_data_frame() is a pre-defined DataFrame that is the expected result of the call.其中self.get_test_data_frame()是一个预定义的 DataFrame,它是调用的预期结果。

When I print out the DataFrame passed to the mocking method and the the test DataFrame I can see that they look equal when printed:当我打印出传递给模拟方法的 DataFrame 和测试 DataFrame 时,我可以看到它们在打印时看起来相等:

在此处输入图片说明

but the test output does not think they are equal:但测试输出认为它们不相等:

File "C:\\python3.6\\lib\\unittest\\mock.py", line 812, in assert_called_with if expected != actual: File "C:\\python3.6\\lib\\unittest\\mock.py", line 2055, in eq return (other_args, other_kwargs) == (self_args, self_kwargs) File "C:\\python3.6\\lib\\site-packages\\pandas\\core\\generic.py", line 1330, in nonzero f"The truth value of a {type(self). name } is ambiguous. " ValueError: The truth value of a DataFrame is ambiguous.文件“C:\\python3.6\\lib\\unittest\\mock.py”,第 812 行,在 assert_Called_with 中,如果预期!= 实际:文件“C:\\python3.6\\lib\\unittest\\mock.py”,第 2055 行,在eq return (other_args, other_kwargs) == (self_args, self_kwargs) 文件 "C:\\python3.6\\lib\\site-packages\\pandas\\core\\generic.py",第 1330 行,在非零f"中的真值一个{式(个体)名称}不明确“ValueError异常:一个数据帧的真值是不明确的。 Use a.empty, a.bool(), a.item(), a.any() or a.all().使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。

From reading other issues I think it is because the MagicMock tries to call == but Pandas require .equals() to check for equality.通过阅读其他问题,我认为这是因为 MagicMock 尝试调用 == 但 Pandas 需要 .equals() 来检查相等性。 Does anyone know of an alternative approach?有谁知道另一种方法?

So I did some more digging and came across call_args which captures all of the parameters that were passed.所以我做了更多的挖掘,发现call_args捕获了所有传递的参数。

Even more useful for me was call_args_list as my method can be called multiple times.对我来说更有用的是call_args_list因为我的方法可以被多次调用。

The call_args_list provides a lit of all the calls that were made in the form of tuples. call_args_list提供了所有以元组形式进行的调用。

In my example I captured the call_args_list with the following:在我的示例中,我使用以下内容捕获了call_args_list

call_list = ClassToMock.method_to_mock.call_args_list

I then unpacked the tuples to get the DataFrame and was able to check equality with the .equals() method.然后我解压元组以获取 DataFrame 并能够使用 .equals() 方法检查相等性。

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

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