I am trying to simulate the reading of an hdf5 file in python3 for testing. The function controls, if the file contains all the required keywords. The structure of the file is:
parent
A
B
My plan is to use MagicMock object for the file object and the group object.
def test_checkInput(self):
file = MagicMock()
my_values = MagicMock()
my_values.keys.return_value = ['A', 'B']
file.keys.return_value = {'parent': my_values}
self.assertTrue(reader_class.checkInput(file))
reader_class is the module where the function checkInput(file)
is defined
def checkInput(file):
if not file.keys:
return False
if 'parent' in file.keys():
group = file['parent']
if 'A' in group.keys():
if 'B' in group.keys():
return True
else:
print(f"[ {__file__} ] : No Group: 'A'")
return False
else:
print(f"[ {__file__} ] : No Group: 'B'")
return False
else:
print(f"[ {__file__} ] : No Group: 'parent'")
return False
The problem is, that group.keys()
does not return ['A', 'B']
as expected in the checkInput function. It returns a MagicMock-Object instead. How can a get the set values?
The problem was, that the MagicMock objects in the the reader_class file are different.
file.keys()
returns another mock as file['parent']
I found a simple solution:
in the Testfile just use one MagicMock object and specify the return values
def test_checkInput(self):
file = MagicMock()
file.keys.return_value = 'parent'
file['parent'].keys.return_value = ['A', 'B']
self.assertTrue(reader_class.checkInput(file))