mercredi 18 février 2015

How to mock method if it is getting called multiple times with different attributes?

I am writing unit tests for my Python and Fabric based code. I have following method which in turn calls sudo method of Fabric API multiple times with different arguments. I would like to know how to call assert on mock sudo object. Can anyone please help me here?



**main_file.py**

from fabric.api import sudo

def do_something(path_to_file_to_be_copied, destination_path):
# remove file if already exists
sudo('rm ' + path_to_file_to_be_copied, warn_only=True)
sudo('cp ' + path_to_file_to_be_copied + ' ' + destination_path)


I have written test file as below :



**test_main_file.py**

import main_file

class MainFileTest(unittest.TestCase):

@mock.patch('main_file.sudo')
def test_do_something(self, mock_sudo):
file_path = '/dummy/file/path.txt'
dest_dir = '/path/to/dest/dir'
main_file.do_something(file_path, dest_dir)
mock_sudo.assert_called_with('rm ' + file_path)


Above test fails because mocked object remembers only last call. that is, if I write mock_sudo.assert_called_with(cp + file_path + ' ' + dest_dir) then test fails.


Can anyone please tell how can I assert both the calls to sudo?


Aucun commentaire:

Enregistrer un commentaire