pythonevent-handlingpytestfunction-call

Test event handler registration using pytest


Consider a module that allows to register event handlers and fires them at some condition:

# mymodule/myfile.py
_event_handlers = []
def register_event_handler(handler):
    _event_handlers.append(handler)

def fire_event_handlers():
    for handler in _event_handlers:
        handler()

I now want to test that the registration of an event handler works:

# tests/test_mymodule.py
from mymodule.myfile import register_event_handler, fire_event_handlers

def test_event_handler():
    def example_handler():
        pass

    register_event_handler(example_handler)
    fire_event_handlers()
    # assert example_handler was called

How do I test if my function example_handler is called?

There are some similar test cases that use unittest.mock (e.g. How to assert that nested function called pytest), but as I do not want to mock any existing function of the module, I do not see how to use it here.


Solution

  • You can use unittest.mock.Mock to track whether example_handler was called without mocking any existing function

    from mymodule.myfile import register_event_handler, fire_event_handlers
    from unittest.mock import Mock
    
    def test_event_handler():
        mock_handler = Mock()  
    
        register_event_handler(mock_handler)  
        fire_event_handlers() 
    
        mock_handler.assert_called_once() 
    
    #Mock() acts like a function and tracks calls.
    #assert_called_once() ensures the function was invoked exactly once.