Search code examples
pythonpandasdataframeassertmagicmock

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:

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.

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:

enter image description here

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. Use a.empty, a.bool(), a.item(), a.any() or a.all().

From reading other issues I think it is because the MagicMock tries to call == but Pandas require .equals() to check for equality. Does anyone know of an alternative approach?


Solution

  • So I did some more digging and came across call_args which captures all of the parameters that were passed.

    Even more useful for me was call_args_list as my method can be called multiple times.

    The call_args_list provides a lit of all the calls that were made in the form of tuples.

    In my example I captured the call_args_list with the following:

    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.