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.