DEV Community

Cover image for How to test method call order with unittest in Python
pikoTutorial
pikoTutorial

Posted on • Originally published at pikotutorial.com

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:

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)
Enter fullscreen mode Exit fullscreen mode

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

def function(obj):
    obj.say_goodbye()
    obj.say_hello()
Enter fullscreen mode Exit fullscreen mode

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()]
Enter fullscreen mode Exit fullscreen mode

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Heroku

This site is powered by Heroku

Heroku was created by developers, for developers. Get started today and find out why Heroku has been the platform of choice for brands like DEV for over a decade.

Sign Up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay