Ni3dzwi3dz
Ni3dzwi3dz

Reputation: 197

MagickMock() assert_called not recognizing calls

i have a function like this, stored in file example.py:

def my_func(file):
    conn = get_connection()
    conn.upload_file(file)
    conn.execute_file(file)

Now, i want to test it, so i`m using MagicMock in test_example.py like:

@mock.patch("example.get_connection")
def test_my_func(mock_conn):
    mock_conn = MagickMock()
    mock_conn.upload_file = MagickMock(return_value=True)
    
    result= my_func("file.zip")
    mock_conn.upload_file.assert_called()

Now, the test fails with error:

        if self.call_count == 0:
            msg = ("Expected '%s' to have been called." %
                   (self._mock_name or 'mock'))
>           raise AssertionError(msg)
E           AssertionError: Expected 'upload_file' to have been called.

When i debug the test, in example.py, MagickMocks attribute called` is set to True after the call, but back in test_example.py it is False, and the test fails. What am i doing wrong?

Upvotes: 1

Views: 118

Answers (2)

OlafdeL
OlafdeL

Reputation: 290

I would do it like this:

@mock.patch("example.get_connection")
def test_my_func(mock_get_connection):
    mock_connection = MagicMock()
    mock_get_connection.return_value = mock_connection

    my_func("file.zip")
    mock_get_connection.assert_called_once()
    mock_connection.upload_file.assert_called_once_with("file.zip")
    mock_get_connection.execute_file.assert_called_once_with("file.zip")

So, I create a Mock object for the connection. The get_connector function is patched, and returns the Mock connector. Then you can easily assert whether the execute and upload methods are called.

Note, you have a typo in MagicMock, an extra "k"

Upvotes: 0

Vijay Kumar Prajapat
Vijay Kumar Prajapat

Reputation: 59

You can try by replacing

mock_conn.upload_file.assert_called()

with below line

mock_conn.return_value.upload_file.assert_called()

Upvotes: 1

Related Questions