0

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):
   ...
nickponline
  • 25,354
  • 32
  • 99
  • 167
  • Does this answer your question? [Getting an actual return value for a mocked file.read()](https://stackoverflow.com/questions/8746586/getting-an-actual-return-value-for-a-mocked-file-read) – itprorh66 Oct 10 '21 at 16:24
  • @itprorh66 No i don't think so because there are two files. So I can't just mock read and open right? - I updated question to reflect that. – nickponline Oct 10 '21 at 16:31

0 Answers0