import time
from threading import Thread

from assertpy import (
    assert_that,
    fail,
)
from messagebus import (
    AckMessage,
    Message,
    MessageBusException,
    MessageBusExceptionType,
)


def test_raises_timeout_when_no_reply_is_received(
    sender_message_bus,
):
    try:
        sender_message_bus.send_direct_message(
            address="tcp://invalid_address:1234",
            message=Message(
                token=1,
                timeout=10,
            ),
        )
        fail("Must raise MessageBusException")
    except MessageBusException as e:
        assert_that(e.type).is_equal_to(MessageBusExceptionType.timeout)


def test_returns_the_reply(
    sender_message_bus,
    receiver_message_bus,
    receiver_address,
):
    sent_reply = AckMessage()

    def reply_message():
        msg = receiver_message_bus.receive()
        receiver_message_bus.reply_message(
            message=msg,
            reply_message=sent_reply,
        )

    Thread(target=reply_message).start()

    time.sleep(0.1)

    received_reply = sender_message_bus.send_direct_message(
        address=receiver_address,
        message=Message(token=1),
    )

    assert_that(received_reply).is_equal_to(sent_reply)
