How to test method call order with unittest in Python?


Welcome to the next pikoTutorial!

Sometimes when writing unit test it is necessary to check not only if certain function has been called, but also the order in which functions have been called. To do that with unittest in Python, use the following code:

Python
import unittest from unittest.mock import MagicMock, call # function to be tested def function(obj):  obj.say_hello()  obj.say_goodbye() # unit test class TestFunctionCallOrder(unittest.TestCase):  def test_function_call_order(self):  # create a mock object  mock_obj = MagicMock()  # call the function with the mock object  function(mock_obj)  # define the expected call order  expected_calls = [call.say_hello(), call.say_goodbye()]  # check if the actual call order matches the expected call order  mock_obj.assert_has_calls(expected_calls)

If you change the order of function calls, e.g. like this:

Python
def function(obj):  obj.say_goodbye()  obj.say_hello()

The above test will immediately catch such regression:

AssertionError: Calls not found. Expected: [call.say_hello(), call.say_goodbye()]  Actual: [call.say_goodbye(), call.say_hello()]