Ejemplo n.º 1
0
def test_prepare_reply_event(session):
    '''Prepare reply event.'''
    event_hub = ftrack_api.event.hub.EventHub(
        session.server_url, session.api_user, session.api_key
    )

    source_event = Event('source', source=dict(id='source-id'))
    reply_event = Event('reply')

    event_hub._prepare_reply_event(reply_event, source_event)
    assert source_event['source']['id'] in reply_event['target']
    assert reply_event['in_reply_to_event'] == source_event['id']

    event_hub._prepare_reply_event(reply_event, source_event, {'id': 'source'})
    assert reply_event['source'] == {'id': 'source'}
Ejemplo n.º 2
0
def test_stop_event(event_hub):
    '''Stop processing of subsequent local handlers when stop flag set.'''
    called = {
        'a': False,
        'b': False,
        'c': False
    }

    def callback_a(event):
        called['a'] = True

    def callback_b(event):
        called['b'] = True
        event.stop()

    def callback_c(event):
        called['c'] = True

    event_hub.subscribe('topic=test', callback_a, priority=50)
    event_hub.subscribe('topic=test', callback_b, priority=60)
    event_hub.subscribe('topic=test', callback_c, priority=70)

    event_hub.publish(Event(topic='test'))
    event_hub.wait(2)

    assert called == {
        'a': True,
        'b': True,
        'c': False
    }
Ejemplo n.º 3
0
def test_subscribe_before_connected(session):
    '''Subscribe to topic before connected.'''
    event_hub = ftrack_api.event.hub.EventHub(
        session.server_url, session.api_user, session.api_key
    )

    called = {'callback': False}

    def callback(event):
        called['callback'] = True

    identifier = 'test-subscriber'
    event_hub.subscribe(
        'topic=test-subscribe', callback, subscriber={'id': identifier}
    )
    assert event_hub.get_subscriber_by_identifier(identifier) is not None

    event_hub.connect()

    try:
        event_hub.publish(Event(topic='test-subscribe'))
        event_hub.wait(2)
    finally:
        event_hub.disconnect()

    assert called == {'callback': True}
Ejemplo n.º 4
0
def test_encode(session):
    '''Encode event data.'''
    encoded = session.event_hub._encode(
        dict(name='ftrack.event', args=[Event('test')])
    )
    assert 'inReplyToEvent' in encoded
    assert 'in_reply_to_event' not in encoded
Ejemplo n.º 5
0
def test_publish_ignoring_error(event_hub):
    '''Ignore error, when configured, on failed publish.'''
    # Note that the event hub currently only fails publish when not connected.
    # All other errors are inconsistently swallowed.
    event_hub.disconnect()
    event = Event(topic='a-topic', data=dict(status='fail'))
    event_hub.publish(event, on_error='ignore')
Ejemplo n.º 6
0
def test_publish_raising_error(event_hub):
    '''Raise error, when configured, on failed publish.'''
    # Note that the event hub currently only fails publish when not connected.
    # All other errors are inconsistently swallowed.
    event_hub.disconnect()
    event = Event(topic='a-topic', data=dict(status='fail'))

    with pytest.raises(Exception):
        event_hub.publish(event, on_error='raise')
Ejemplo n.º 7
0
def test_prepare_event(session, event_data):
    '''Prepare event.'''
    # Replace username `auto` in event data with API user.
    try:
        if event_data['source']['user']['username'] == 'auto':
            event_data['source']['user']['username'] = session.api_user
    except KeyError:
        pass

    event_hub = ftrack_api.event.hub.EventHub(
        session.server_url, session.api_user, session.api_key
    )
    event_hub.id = '1'

    event = Event('test', id='event-id', **event_data)
    expected = Event(
        'test', id='event-id', source=dict(id='1', user=dict(username=session.api_user))
    )
    event_hub._prepare_event(event)
    assert event == expected
Ejemplo n.º 8
0
def test_wait_interrupted_by_disconnect(event_hub):
    '''Interrupt wait loop with disconnect event.'''
    wait_time = 5
    start = time.time()

    # Inject event directly for test purposes.
    event = Event(topic='ftrack.meta.disconnected')
    event_hub._event_queue.put(event)

    event_hub.wait(wait_time)

    assert time.time() - start < wait_time
Ejemplo n.º 9
0
def main(arguments=None):
    '''Publish and receive heartbeat test.'''
    parser = argparse.ArgumentParser()
    parser.add_argument('mode', choices=['publish', 'subscribe'])

    namespace = parser.parse_args(arguments)
    logging.basicConfig(level=logging.INFO)

    session = ftrack_api.Session()

    message_count = 100
    sleep_time_per_message = 1

    if namespace.mode == 'publish':
        max_atempts = 100
        retry_interval = 0.1
        atempt = 0
        while not session.event_hub.connected:
            print(
                'Session is not yet connected to event hub, sleeping for 0.1s')
            time.sleep(retry_interval)

            atempt = atempt + 1
            if atempt > max_atempts:
                raise Exception(
                    'Unable to connect to server within {0} seconds'.format(
                        max_atempts * retry_interval))

        print('Sending {0} messages...'.format(message_count))

        for counter in range(1, message_count + 1):
            session.event_hub.publish(
                Event(topic=TOPIC, data=dict(counter=counter)))
            print('Sent message {0}'.format(counter))

            if counter < message_count:
                time.sleep(sleep_time_per_message)

    elif namespace.mode == 'subscribe':
        session.event_hub.subscribe('topic={0}'.format(TOPIC), callback)
        session.event_hub.wait(
            duration=(((message_count - 1) * sleep_time_per_message) + 15))

        if len(RECEIVED) != message_count:
            print('>> Failed to receive all messages. Dropped {0} <<'.format(
                message_count - len(RECEIVED)))
            return False

    # Give time to flush all buffers.
    time.sleep(5)

    return True
Ejemplo n.º 10
0
def test_publish(event_hub):
    '''Publish asynchronous event.'''
    called = {'callback': False}

    def callback(event):
        called['callback'] = True

    event_hub.subscribe('topic=test-subscribe', callback)

    event_hub.publish(Event(topic='test-subscribe'))
    event_hub.wait(2)

    assert called == {'callback': True}
Ejemplo n.º 11
0
def test_subscribe(event_hub):
    '''Subscribe to topics.'''
    called = {'a': False, 'b': False}

    def callback_a(event):
        called['a'] = True

    def callback_b(event):
        called['b'] = True

    event_hub.subscribe('topic=test-subscribe', callback_a)
    event_hub.subscribe('topic=test-subscribe-other', callback_b)

    event_hub.publish(Event(topic='test-subscribe'))
    event_hub.wait(2)

    assert called == {'a': True, 'b': False}
Ejemplo n.º 12
0
def test_synchronous_publish(event_hub):
    '''Publish event synchronously and collect results.'''
    def callback_a(event):
        return 'A'

    def callback_b(event):
        return 'B'

    def callback_c(event):
        return 'C'

    event_hub.subscribe('topic=test', callback_a, priority=50)
    event_hub.subscribe('topic=test', callback_b, priority=60)
    event_hub.subscribe('topic=test', callback_c, priority=70)

    results = event_hub.publish(Event(topic='test'), synchronous=True)
    assert results == ['A', 'B', 'C']
Ejemplo n.º 13
0
def test_wait(event_hub):
    '''Wait for event and handle as they arrive.'''
    called = {'callback': False}

    def callback(event):
        called['callback'] = True

    event_hub.subscribe('topic=test-subscribe', callback)

    event_hub.publish(Event(topic='test-subscribe'))

    # Until wait, the event should not have been processed even if received.
    time.sleep(1)
    assert called == {'callback': False}

    event_hub.wait(2)
    assert called == {'callback': True}
Ejemplo n.º 14
0
def test_publish_with_reply(event_hub):
    '''Publish asynchronous event with on reply handler.'''

    def replier(event):
        '''Replier.'''
        return 'Replied'

    event_hub.subscribe('topic=test', replier)

    called = {'callback': None}

    def on_reply(event):
        called['callback'] = event['data']

    event_hub.publish(Event(topic='test'), on_reply=on_reply)
    event_hub.wait(2)

    assert called['callback'] == 'Replied'
Ejemplo n.º 15
0
def test_publish_logs_other_errors(event_hub, caplog, mocker):
    '''Log publish errors other than connection error.'''
    # Mock connection to force error.
    mocker.patch.object(event_hub, '_connection', MockConnection())

    event = Event(topic='a-topic', data=dict(status='fail'))
    event_hub.publish(event)

    expected = 'Error sending event {0}.'.format(event)


    if not isinstance(caplog.records, list):
        records = caplog.records()
    else:
        records = caplog.records

    messages = [record.getMessage().strip() for record in records]
    assert expected in messages, 'Expected log message missing in output.'
Ejemplo n.º 16
0
def test_publish_with_multiple_replies(event_hub):
    '''Publish asynchronous event and retrieve multiple replies.'''

    def replier_one(event):
        '''Replier.'''
        return 'One'

    def replier_two(event):
        '''Replier.'''
        return 'Two'

    event_hub.subscribe('topic=test', replier_one)
    event_hub.subscribe('topic=test', replier_two)

    called = {'callback': []}

    def on_reply(event):
        called['callback'].append(event['data'])

    event_hub.publish(Event(topic='test'), on_reply=on_reply)
    event_hub.wait(2)

    assert sorted(called['callback']) == ['One', 'Two']
Ejemplo n.º 17
0
# :coding: utf-8
# :copyright: Copyright (c) 2015 ftrack

import pytest

import ftrack_api.event.subscription
from ftrack_api.event.base import Event


def test_string_representation():
    '''String representation is subscription expression.'''
    expression = 'topic=some-topic'
    subscription = ftrack_api.event.subscription.Subscription(expression)

    assert str(subscription) == expression


@pytest.mark.parametrize('expression, event, expected',
                         [('topic=test', Event(topic='test'), True),
                          ('topic=test', Event(topic='other-test'), False)],
                         ids=['match', 'no match'])
def test_includes(expression, event, expected):
    '''Subscription includes event.'''
    subscription = ftrack_api.event.subscription.Subscription(expression)
    assert subscription.includes(event) is expected