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

mock assert called with multiple calls
mock check if method was called
python mock assert not called
python mock property
python mock multiple calls
python mock class

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?


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 :


import main_file

class MainFileTest(unittest.TestCase):

    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?

Try assert_any_call which asserts whether there has been any call, not just the most recent one.

Or, you can use call_args_list to get the list of args the mock has been called with.

Python Mock object with method called multiple times, def my_side_effect(*args, **kwargs): if args[0] == 42: return "Called with 42" elif args[0] mockobj.method.side_effect = lambda x: {123: 100, 234: 10000}[x] I'​ve ran into this when I was doing my own testing. If you with new_callable , which allows you to patch an attribute of an object with a mock object. Use Mockito.verify(mock, times(n)) to verify if method was executed 'n' times. Create as many ArgumentCaptor instances as the number of arguments in the method. In above example, we tested the HashMap which work on key-value pairs, so we created two ArgumentCaptor instances – one for key and second for value.

assert_has_calls will do the job for you.

assert_has_calls : assert the mock has been called with the specified calls. The mock_calls list is checked for the calls. If any_order is true then the calls can be in any order, but they must all appear in mock_calls.

import main_file
class MainFileTest(unittest.TestCase):

    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_has_calls(['rm ' + file_path,
                                    'cp' + file_path + ' ' + dest_dir],

Mockito, Learn to write unit test which invokes a method multiple times with different Mockito – Verify multiple method calls with different arguments It then verifies that method had been invoked twice. assertEquals( "A" , keys.get( 0 )); I need to set some attributes to ReportClass. beacuse of this class test case getting failed. Times.Once. If you verify a mock object call without specifying the number of times that you expect it to have been executed, the verification will pass if at least one call was made. If the method was called a hundred times, the verification will still pass. Only if the method was not called at all will an exception be thrown causing the test

I wrote a helper library to automatically generate the asserts for me.

Add those lines to print the correct asserts for your case, right after main_file.do_something(file_path, dest_dir):

import mock_autogen.generator

You would get the following output:

from mock import call

assert 2 == mock_sudo.call_count
    calls=[call('rm /dummy/file/path.txt', warn_only=True),
           call('cp /dummy/file/path.txt /path/to/dest/dir'), ])

No need to guess anymore, use mock-generator :)

Test-Driven Python Development, We simply set this attribute to the return value and every call to the mock will return in one statement without having to create a mock for the matches method. that the Alert makes to the rule: one to the depends_on method and the other to This means if the same method is called multiple times, the same mock object  Through mocking you can explicitly define the return value of methods without actually executing the steps of the method. In this post I’ll be discussing about mocking the methods in the same test class you are writing the test cases. Let’s say you have a Person class that has external communication and return values accordingly.

Modern Python Cookbook, if __name__ == "__main__": unittest.main() We've included a main program so was called multiple times: with patch('__main__.random', self.mock_random): of the Mock class, we must provide the methods and attributes of the resulting  There are several custom settings that are supported by methods of the MockSettings interface, such as registering a listener for method invocations on the current mock with invocationListeners, configuring serialization with serializable, specifying the instance to spy on with spiedInstance, configuring Mockito to attempt to use a constructor

unittest.mock — mock object library, Mock has many other ways you can configure it and control its behaviour. The easiest way of using magic methods is with the MagicMock class. If used, attempting to set or get an attribute on the mock that isn't on the object passed as spec_set An integer telling you how many times the mock object has been called:. Of course, once we get the result from the method, we can use Assert to make sure we’re getting expected values and that our calls to our interface occurred. We can use Verify and tell it explicitly what we expect should happen, which could include verifying that a method was called a certain number of times–or even never.

Professional Ruby on Rails, FlexMock has a series of methods that can be chained onto an expectation twice ❑ times(n) ❑ By default, the test for each of these is that the method is called the ActiveRecord object created in the controller gets an update_ attributes call,  The Mock will always return the same value on all calls, this, again, can also be configured by using the side_effect attribute: if you’d like to return different values on each call you can assign