[Python] Test event handler registration using pytest

Discussão em 'Python' iniciado por Stack, Março 18, 2025.

  1. Stack

    Stack Membro Participativo

    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.

    Continue reading...

Compartilhe esta Página