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()
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top