How to patch shutil.move to test some method
-
14-07-2021 - |
문제
I need to test a method that would move a file. I don't want the file move operation to actually occur, I just need to know the method under test made the right call to shutil.move
What would be the best way to patch shutil.move
so the method can call it without doing the actual file operation?
I did it this way but is ugly, I'd like to do it using mock library:
real_move = ftp2email.shutil.move
move_operations = []
def fake_move(src, dst):
move_operations.append((src, dst))
ftp2email.shutil.move = fake_move
msg_id = '/path/to/message.xml'
self.ch.mark_message(msg_id)
self.assertEqual(move_operations,
[('/path/to/message.xml', '/path/to/archived/message.xml')])
ftp2email.shutil.move = real_move
해결책 2
I've solved it using Mock library
@mock.patch('%s.ftp2email.shutil.move' % __name__)
def test_mark_message(self, move_mock):
self.ch.mark_message('/path/to/message.xml')
move_mock.assert_called_with('/path/to/message.xml',
'/path/to/archived/message.xml')
This is just one way to do it, I can also be done with a 'with statement' or calling the mock methods start and stop.
다른 팁
You could try using mox, it can do that sort of thing.
From the mox recipes.
def testFoo(self):
self.mox.StubOutWithMock(module_to_mock, 'FunctionToMock')
module_to_mock.FunctionToMock().AndReturn(foo)
self.mox.ReplayAll()
...
self.mox.VerifyAll()
제휴하지 않습니다 StackOverflow