Tyler R
Tyler R

Reputation: 504

Python Mocking assert_called not working

I am able to successfully mock a function, and I am sure that the original is not called. I added a huge print statement to the original function and when I mock it, this print is not called. When I turn the mock back on, the print statement is not called.

However, my assert_called is failing saying it was never called. Has anyone ever experienced something like this?

class FooTestCase(unittest.TestCase):

    @mock.patch('MyObj.helper_function')
    def test_simple(self, mock_hf):

        my_obj = MyObj()

        # internally, this class imports HelperModule 
        # and the method calls helper_function
        my_obj.do_something()

        mock_hf.helper_function.assert_called()

        return

My error response

AssertionError: Expected 'helper_function' to have been called.

Update I just added the following lines right before the assertion

    print mock_cw.method_calls
    print mock_cw.mock_calls

method_calls is an empty list, while mock_calls is a list with 1 item which is

[call(arg1_expected_for_helper_fn, arg2_expected_for_helper_fn)]

Yet the assert still fails

Upvotes: 6

Views: 9855

Answers (3)

Remotec
Remotec

Reputation: 10772

I see the original poster has done this, but for anyone else stumbling on this as I did...

Don't forget you need to wrap your expected calls in a call object e.g.

mock_logger.assert_has_calls([call(expected_log_message_1), call(expected_log_message_2)])

If you don't do that, it will complain that the expected call did not happen and you will spend ages comparing the output to try and work out why (as I did!).

Upvotes: -1

Tyler R
Tyler R

Reputation: 504

The issue is that I was checking to see if mock_hf.helper_function was called, but mock_hf is already mapped to the helper_function. I was more or less checking that helper_function.helper_function was called rather than just helper_function.

The assert line needed to be mock_hf.assert_called()

Upvotes: 4

user8791728
user8791728

Reputation:

Usually an error like this is a result of not patching the correct location. Try to patch the object itself with this:

@patch.object(MyObj, "helper_function")
def test_simple(mock_hf):
    ...

Since MyObj is (assumed to be) imported at the top of the test file, this patches the method on that object directly.

Upvotes: 4

Related Questions