Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not able to mock a method

I have this code i want to test in isolation in some_module.py

import tarfile
def function_to_test(path_to_tar):
    tar_file = tarfile.open(path_to_tar)
    for tar_info in tar_file.getmembers():
        #some logic to test
        pass

And i can't get to effectively mock tarfile methods so i can mimic a tar file without having to read from actual file, my current attempt looks as follows

from unittest.mock import patch, Mock

def test_DeepLabModel_unexistent_error():
    tar_path = "/path/to/nowhere"

    import tarfile

    with patch.object(tarfile, 'open', autospec=True) as open_mock:
        open_mock.getmembers = Mock()
        open_mock.getmembers.return_value = ['a','b']

        from some_module import function_to_test
        function_to_test(tar_path)
        pass

This doesn't work, the call to "getmembers" in the test method just returns another MagicMock object and not the list of strings i'm providing, thus not iterating as it should. I've achieved my purpose using similar behavior in the past, but i can't understand why that doesn't work here.

like image 741
macebalp Avatar asked Jun 28 '26 01:06

macebalp


1 Answers

You're missing a return_value between open_mock and getmembers. After you've defined your mock, you need to say what that mocked method is going to return. That is what you're going to be calling getmembers on in the method you're testing. Your test would look like this:

import tarfile
from unittest.mock import patch, Mock
from some_module import function_to_test

def test_DeepLabModel_unexistent_error():
    tar_path = "/path/to/nowhere"

    with patch.object(tarfile, 'open', autospec=True) as open_mock:
        open_mock.return_value.getmembers.return_value = ['a','b']
        get_members(tar_path)

Note that I've moved the imports to the top as well.

like image 170
wholevinski Avatar answered Jun 29 '26 13:06

wholevinski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!