async def test_dispatching_selection():
    """Test that routing works in agent."""
    dispatcher = Dispatcher()

    called_event = asyncio.Event()

    async def route_gets_called(_msg, **kwargs):
        kwargs["event"].set()

    async def route_not_called(_msg, **_kwargs):
        print("this should not be called")

    dispatcher.add(
        MsgType("test_protocol/2.0/testing_type"),
        route_gets_called,
    )
    dispatcher.add(
        MsgType("test_protocol/1.0/testing_type"),
        route_not_called,
    )

    test_msg = Message.parse_obj(
        {"@type": "test_protocol/2.0/testing_type", "test": "test"}
    )
    await dispatcher.dispatch(test_msg, event=called_event)

    assert called_event.is_set()
async def test_dispatching_selection_message_too_old():
    """Test that routing works in agent."""
    dispatcher = Dispatcher()

    dispatcher.add(MsgType("test_protocol/3.0/testing_type"), lambda msg: msg)
    dispatcher.add(MsgType("test_protocol/2.0/testing_type"), lambda msg: msg)

    test_msg = Message.parse_obj(
        {"@type": "test_protocol/1.0/testing_type", "test": "test"}
    )
    with pytest.raises(NoRegisteredHandlerException):
        await dispatcher.dispatch(test_msg)
async def test_dispatching_no_handler():
    """Test that routing works in agent."""
    dispatcher = Dispatcher()

    async def route_gets_called(_msg):
        pass

    dispatcher.add(MsgType("test_protocol/1.0/testing_type"), route_gets_called)

    test_msg = Message.parse_obj(
        {"@type": "test_protocol/4.0/other_type", "test": "test"}
    )
    with pytest.raises(NoRegisteredHandlerException):
        await dispatcher.dispatch(test_msg)
def test_valid_message():
    """Test basic message creation and member access."""
    id_ = "12345"

    msg = Message.parse_obj({"@type": TEST_TYPE, "@id": id_})
    assert msg.type == TEST_TYPE
    assert msg.id == id_
    assert msg.type.doc_uri == "test_type/"
    assert msg.type.protocol == "protocol"
    assert msg.type.version == "1.0"
    assert msg.type.normalized_version == "1.0.0"
    assert msg.type.name == "test"
    assert msg.type.version_info == MsgVersion(1, 0, 0)
    assert len(msg) == 2
def test_bad_message_id(id_):
    """Test message with bad message id"""
    with pytest.raises(ValueError):
        Message.parse_obj({"@type": TEST_TYPE, "@id": id_})
def test_pretty_print():
    """Assert pretty print is returning something crazy."""
    assert isinstance(
        Message.parse_obj({
            "@type": TEST_TYPE
        }).pretty_print(), str)
def test_bad_message_no_type():
    """Test no type in message raises error."""
    with pytest.raises(ValueError):
        Message.parse_obj({"test": "test"})
def test_id_generated():
    """Test ID is generated for message where one is not specified."""
    msg = Message.parse_obj({"@type": TEST_TYPE})
    assert msg.type == TEST_TYPE
    assert msg.id is not None