jeudi 11 octobre 2018

How to mock decorated function

How to mock a function if it is decorated? I want to make sure that handle_message function is being called in process_event function. I try to run this test and handle_message function is actually being called, but test says that it called 0 times.

Code I want to test:

class EventDistributor:
    def __init__(self):
        self.event_handlers = {}

    def on_event(self, event_type):
        def decorator(func):
            self.event_handlers[event_type] = func
            return func

        return decorator

    def process_event(self, event):
        body = event['event']
        body_type = body['type']

        if 'subtype' in body:
            return

        event_handler = self.event_handlers.get(body_type)
        if event_handler:
            event_handler(event, body)

Tests:

@app.on_event('message')
def handle_message(event, body):
    return True

class EventDistributorTests(TestCase):
    def test_process_event(self):
        message_event = {'event': {'type': 'message', 'text': 'hello'}}

        with mock.patch('tests.test_event_distributor.handle_message') as mocked:
            app.process_event(message_event)
            mocked.handle_message.assert_called_once()

Aucun commentaire:

Enregistrer un commentaire