Change all files to use open() instead of files, allowing for better unittests by mocking the open() call
Some old classes used the f = file(s) f.write()/f.read() f.close() way of accessing files, it has been replaced by with open(s) as f: ...
Then, it can be mocked in unittests with: moduleName = "ILCDIRAC.Core.Utilities.PrepareOptionFiles" file_contents = ["a line here", "the second line", "another line in the file"] text_file_data = '\n'.join(file_contents) with patch('%s.open' % moduleName, mock_open(read_data=text_file_data), create=True) as file_mocker: # mock_open doesn't properly handle iterating over the open file with for line in file: # but if we set the return value like this, it works. file_mocker.return_value.iter.return_value = text_file_data.splitlines() from ILCDIRAC.Core.Utilities import PrepareOptionFiles PrepareOptionFiles.test_me_please()
the iter assignment is necessary in case the file is read with the for line in file: expression. To make assumptions on the file use (Note that lines are terminated by \n): file_mocker.assert_any_call('testfile.txt', 'r') file_mocker.assert_any_call('testfile2.txt', 'w') mocker_handle = file_mocker() print "Writecalls : %s" % mocker_handle.write.mock_calls