I have the following class in Python:
# lib/filesum.py
class FileSum(object):
def __init__(self, path1, path2, path3):
self.path1 = path1
self.path2 = path2
self.path3 = path3
self.a = int(open(self.path1).read().strip())
self.b = int(open(self.path2).read().strip())
def save_sum(self):
s = self.a + self.b
open(self.path3, mode='w').write(str(s))
I want to write a unit test to test the save_sum()
method. How can I mock the two calls to open and one to write for different files without having to have actual files there when the test is run? I would like to ignore (not mock) any interactions with any other files besides these 3.
EDIT:
My attempt was:
def mock_file_open(filename, mode='r'):
if filename == "a.txt":
content = "3"
elif filename == 'b.txt':
content = "2"
else:
# I want to leave all other file interactions alone but
#this causes infinite resursion
return open(filename, mode=mode)
file_object = mock.mock_open(read_data=content).return_value
file_object.__iter__.return_value = content
return file_object
...
with mock.patch('builtins.open', new=mock_file_open):
...