I am trying to write some unit tests using mock for some code that looks like this:
# Write some text to edit to a file
with tempfile.NamedTemporaryFile(delete=False) as tf:
tfName = tf.name
tf.write(text_to_edit)
# Edit the text with vim
edit_file(tfName)
# Read edited text
with open(tfName, 'r') as f:
text = f.read()
# Delete the file
os.remove(tfName)
# ... do stuff with text ...
This was my initial attempt at creating mock objects for that code:
@pytest.fixture
def mock_tempfile(mocker):
new_tfile_obj = mock.MagicMock()
tfile_instance = mock.MagicMock()
tfile_instance.name.return_value = 'mockTemporaryFile'
mocker.patch('tempfile.NamedTemporaryFile', new_tfile_obj)
new_open = mock.MagicMock()
fake_file = mock.MagicMock(spec=file)
new_open.return_value = fake_file
new_tfile_obj.return_value = tfile_instance
mocker.patch('__builtin__.open', new_open)
return (new_tfile_obj, tfile_instance, new_open, fake_file)
# ... Code to mock edit_file/modify the temp file are in the actual test ...
However, I don't expect that to be anywhere near what should be used. I'm totally lost on how I would mock something like that.
Aucun commentaire:
Enregistrer un commentaire