Exemplo n.º 1
0
async def test_consume_on_done(consumer: InternalConsumer):
    calls = 0

    async def fn(command):
        nonlocal calls
        calls += 1

    # Setup our handler and wait for the consumer to be ready
    consumer.start(fn)

    # Add some commands
    command1 = SendEventCommand(message=None)
    on_done1 = asyncio.Event()
    command2 = SendEventCommand(message=None)
    on_done2 = asyncio.Event()

    consumer.queue.put_nowait((command1, on_done1))
    consumer.queue.put_nowait((command2, on_done2))

    await asyncio.sleep(0.05)

    assert on_done1.is_set()
    assert on_done2.is_set()

    assert calls == 2
    assert len(consumer._running_commands) == 0
    assert consumer.queue.qsize() == 0
Exemplo n.º 2
0
def test_mock_result_event_names_fired(mock_result: testing.MockResult, property_name):
    event1 = EventMessage(api_name="api1", event_name="event1")
    event2 = EventMessage(api_name="api2", event_name="event2")
    # fmt: off
    mock_result.mocker_context.event.to_transport.put_items = [
        (
            SendEventCommand(message=event1, options={}),
            None,
        ), (
            SendEventCommand(message=event2, options={}),
            None,
        ),
    ]
    # fmt: on
    assert getattr(mock_result, property_name) == ["api1.event1", "api2.event2"]
Exemplo n.º 3
0
def test_mock_result_get_event_messages_filtered(mock_result: testing.MockResult, method_name):
    get_event_messages = getattr(mock_result, method_name)

    event1 = EventMessage(api_name="api", event_name="event1")
    event2 = EventMessage(api_name="api", event_name="event2")
    # fmt: off
    mock_result.mocker_context.event.to_transport.put_items = [
        (
            SendEventCommand(message=event1, options={}),
            None,
        ), (
            SendEventCommand(message=event2, options={}),
            None,
        ),
    ]
    # fmt: on

    assert get_event_messages("api.event2") == [event2]
Exemplo n.º 4
0
def test_mock_result_assert_events_fired_times(mock_result: testing.MockResult,
                                               method_name):
    assert_events_fired = getattr(mock_result, method_name)
    mock_result.mocker_context.event.to_transport.put_items = [
        (
            SendEventCommand(message=EventMessage(api_name="api",
                                                  event_name="event"),
                             options={}),
            None,
        ),
        (
            SendEventCommand(message=EventMessage(api_name="api",
                                                  event_name="event"),
                             options={}),
            None,
        ),
    ]

    # No error
    try:
        assert_events_fired("api.event")
    except AssertionError as e:
        assert False, f"{method_name} incorrectly raised an assertion error: {e}"

    # No error
    try:
        assert_events_fired("api.event", times=2)
    except AssertionError as e:
        assert False, f"{method_name} incorrectly raised an assertion error: {e}"

    # Error
    with pytest.raises(AssertionError):
        assert_events_fired("api.event", times=0)

    # Error
    with pytest.raises(AssertionError):
        assert_events_fired("api.event", times=1)

    # Error
    with pytest.raises(AssertionError):
        assert_events_fired("api.event", times=3)
Exemplo n.º 5
0
    async def fire_event(self, api_name, name, kwargs: dict = None, options: dict = None):
        kwargs = kwargs or {}
        try:
            api = self.api_registry.get(api_name)
        except UnknownApi:
            raise UnknownApi(
                "Lightbus tried to fire the event {api_name}.{name}, but no API named {api_name} was found in the "
                "registry. An API being in the registry implies you are an authority on that API. Therefore, "
                "Lightbus requires the API to be in the registry as it is a bad idea to fire "
                "events on behalf of remote APIs. However, this could also be caused by a typo in the "
                "API name or event name, or be because the API class has not been "
                "registered using bus.client.register_api(). ".format(**locals())
            )

        validate_event_or_rpc_name(api_name, "event", name)

        try:
            event = api.get_event(name)
        except EventNotFound:
            raise EventNotFound(
                "Lightbus tried to fire the event {api_name}.{name}, but the API {api_name} does not "
                "seem to contain an event named {name}. You may need to define the event, you "
                "may also be using the incorrect API. Also check for typos.".format(**locals())
            )

        parameter_names = {p.name if isinstance(p, Parameter) else p for p in event.parameters}

        if set(kwargs.keys()) != parameter_names:
            raise InvalidEventArguments(
                "Invalid event arguments supplied when firing event. Attempted to fire event with "
                "{} arguments: {}. Event expected {}: {}".format(
                    len(kwargs),
                    sorted(kwargs.keys()),
                    len(event.parameters),
                    sorted(parameter_names),
                )
            )

        kwargs = deform_to_bus(kwargs)
        event_message = EventMessage(
            api_name=api.meta.name, event_name=name, kwargs=kwargs, version=api.meta.version
        )

        validate_outgoing(self.config, self.schema, event_message)

        await self.hook_registry.execute("before_event_sent", event_message=event_message)
        logger.info(L("📤  Sending event {}.{}".format(Bold(api_name), Bold(name))))

        await self.producer.send(SendEventCommand(message=event_message, options=options)).wait()

        await self.hook_registry.execute("after_event_sent", event_message=event_message)
Exemplo n.º 6
0
async def test_consume_exception(consumer: InternalConsumer):
    exceptions = []

    async def fn(command):
        raise ValueError("Something went wrong")

    def on_exception(e):
        exceptions.append(e)

    # Set out customer exception handler
    consumer._on_exception = on_exception
    # Setup our command handler
    consumer.start(fn)

    from lightbus.client.internal_messaging import consumer as consumer_module

    command = SendEventCommand(message=None)
    on_done = asyncio.Event()
    consumer.queue.put_nowait((command, on_done))
    await on_done.wait()

    error: Error = consumer.error_queue.get_nowait()
    assert error.type == ValueError