예제 #1
0
async def test_async_queue_by_queue_client_conn_str_receive_handler_receiveanddelete(
        live_servicebus_config, standard_queue):
    queue_client = QueueClient.from_connection_string(
        live_servicebus_config['conn_str'], name=standard_queue, debug=True)
    queue_client.get_properties()

    async with queue_client.get_sender() as sender:
        for i in range(10):
            message = Message("Handler message no. {}".format(i))
            message.enqueue_sequence_number = i
            await sender.send(message)

    messages = []
    receiver = queue_client.get_receiver(
        mode=ReceiveSettleMode.ReceiveAndDelete, idle_timeout=5)
    async for message in receiver:
        messages.append(message)
        with pytest.raises(MessageAlreadySettled):
            await message.complete()

    assert not receiver.running
    assert len(messages) == 10
    time.sleep(30)

    messages = []
    receiver = queue_client.get_receiver(
        mode=ReceiveSettleMode.ReceiveAndDelete, idle_timeout=5)
    async for message in receiver:
        messages.append(message)
    assert len(messages) == 0
예제 #2
0
async def main():
    queue_client = QueueClient.from_connection_string(
        receiver_constr, 'simplequeue')

    async with queue_client.get_receiver(idle_timeout=2) as receiver:
        async for message in receiver:
            await process_message(message)
async def test_async_session_by_session_client_conn_str_receive_handler_with_stop(
        live_servicebus_config, session_queue):
    queue_client = QueueClient.from_connection_string(
        live_servicebus_config['conn_str'], name=session_queue, debug=True)

    session_id = str(uuid.uuid4())
    async with queue_client.get_sender(session=session_id) as sender:
        for i in range(10):
            message = Message("Stop message no. {}".format(i))
            await sender.send(message)

    messages = []
    session = queue_client.get_receiver(session=session_id, idle_timeout=5)
    async for message in session:
        assert session_id == session.session_id
        assert session_id == message.session_id
        messages.append(message)
        await message.complete()
        if len(messages) >= 5:
            break

    assert session.running
    assert len(messages) == 5

    async with session:
        async for message in session:
            assert session_id == session.session_id
            assert session_id == message.session_id
            messages.append(message)
            await message.complete()
            if len(messages) >= 5:
                break

    assert not session.running
    assert len(messages) == 6
async def test_async_session_by_queue_client_conn_str_receive_handler_receiveanddelete(live_servicebus_config, session_queue):
    queue_client = QueueClient.from_connection_string(
        live_servicebus_config['conn_str'],
        name=session_queue,
        debug=True)
    queue_client.get_properties()

    session_id = str(uuid.uuid4())
    async with queue_client.get_sender(session=session_id) as sender:
        for i in range(10):
            message = Message("Handler message no. {}".format(i))
            await sender.send(message)

    messages = []
    session = queue_client.get_receiver(session=session_id, mode=ReceiveSettleMode.ReceiveAndDelete, idle_timeout=5)
    async for message in session:
        messages.append(message)
        assert session_id == session.session_id
        assert session_id == message.session_id
        with pytest.raises(MessageAlreadySettled):
            await message.complete()

    assert not session.running
    assert len(messages) == 10
    time.sleep(30)

    messages = []
    session = queue_client.get_receiver(session=session_id, mode=ReceiveSettleMode.ReceiveAndDelete, idle_timeout=5)
    async for message in session:
        messages.append(message)
    assert len(messages) == 0
async def test_async_session_by_session_client_conn_str_receive_handler_peeklock(live_servicebus_config, session_queue):
    queue_client = QueueClient.from_connection_string(
        live_servicebus_config['conn_str'],
        name=session_queue,
        debug=True)
    queue_client.get_properties()

    session_id = str(uuid.uuid4())
    async with queue_client.get_sender(session=session_id) as sender:
        for i in range(3):
            message = Message("Handler message no. {}".format(i))
            await sender.send(message)

    with pytest.raises(ValueError):
        session = queue_client.get_receiver(idle_timeout=5)

    session = queue_client.get_receiver(session=session_id, idle_timeout=5)
    count = 0
    async for message in session:
        print_message(message)
        assert message.session_id == session_id
        count += 1
        await message.complete()

    assert count == 3
async def test_async_queue_by_queue_client_conn_str_receive_handler_receiveanddelete(live_servicebus_config, standard_queue):
    queue_client = QueueClient.from_connection_string(
        live_servicebus_config['conn_str'],
        name=standard_queue,
        debug=True)
    queue_client.get_properties()

    async with queue_client.get_sender() as sender:
        for i in range(10):
            message = Message("Handler message no. {}".format(i))
            message.enqueue_sequence_number = i
            await sender.send(message)

    messages = []
    receiver = queue_client.get_receiver(mode=ReceiveSettleMode.ReceiveAndDelete, idle_timeout=5)
    async for message in receiver:
        messages.append(message)
        with pytest.raises(MessageAlreadySettled):
            await message.complete()

    assert not receiver.running
    assert len(messages) == 10
    time.sleep(30)

    messages = []
    receiver = queue_client.get_receiver(mode=ReceiveSettleMode.ReceiveAndDelete, idle_timeout=5)
    async for message in receiver:
        messages.append(message)
    assert len(messages) == 0
예제 #7
0
    async def test_async_session_get_set_state_with_receiver(
            self, servicebus_namespace_connection_string, servicebus_queue,
            **kwargs):

        queue_client = QueueClient.from_connection_string(
            servicebus_namespace_connection_string,
            name=servicebus_queue.name,
            debug=False)

        session_id = str(uuid.uuid4())
        queue_client.get_properties()
        async with queue_client.get_sender(session=session_id) as sender:
            for i in range(3):
                message = Message("Handler message no. {}".format(i))
                await sender.send(message)

        async with queue_client.get_receiver(session=session_id,
                                             idle_timeout=5) as session:
            assert await session.get_session_state() == None
            await session.set_session_state("first_state")
            count = 0
            async for m in session:
                assert m.properties.group_id == session_id.encode('utf-8')
                count += 1
            with pytest.raises(InvalidHandlerState):
                await session.get_session_state()
        assert count == 3
async def test_async_session_by_queue_client_conn_str_receive_handler_receiveanddelete(live_servicebus_config, session_queue):
    queue_client = QueueClient.from_connection_string(
        live_servicebus_config['conn_str'],
        name=session_queue,
        debug=True)
    queue_client.get_properties()

    session_id = str(uuid.uuid4())
    async with queue_client.get_sender(session=session_id) as sender:
        for i in range(10):
            message = Message("Handler message no. {}".format(i))
            await sender.send(message)

    messages = []
    session = queue_client.get_receiver(session=session_id, mode=ReceiveSettleMode.ReceiveAndDelete, idle_timeout=5)
    async for message in session:
        messages.append(message)
        assert session_id == session.session_id
        assert session_id == message.session_id
        with pytest.raises(MessageAlreadySettled):
            await message.complete()

    assert not session.running
    assert len(messages) == 10
    time.sleep(30)

    messages = []
    session = queue_client.get_receiver(session=session_id, mode=ReceiveSettleMode.ReceiveAndDelete, idle_timeout=5)
    async for message in session:
        messages.append(message)
    assert len(messages) == 0
예제 #9
0
async def test_async_queue_by_queue_client_conn_str_receive_handler_with_stop(
        live_servicebus_config, standard_queue):
    queue_client = QueueClient.from_connection_string(
        live_servicebus_config['conn_str'], name=standard_queue, debug=True)

    async with queue_client.get_sender() as sender:
        for i in range(10):
            message = Message("Stop message no. {}".format(i))
            await sender.send(message)

    messages = []
    receiver = queue_client.get_receiver(idle_timeout=5)
    async for message in receiver:
        messages.append(message)
        await message.complete()
        if len(messages) >= 5:
            break

    assert receiver.running
    assert len(messages) == 5

    async with receiver:
        async for message in receiver:
            messages.append(message)
            await message.complete()
            if len(messages) >= 5:
                break

    assert not receiver.running
    assert len(messages) == 6
async def test_async_session_by_session_client_conn_str_receive_handler_peeklock(live_servicebus_config, session_queue):
    queue_client = QueueClient.from_connection_string(
        live_servicebus_config['conn_str'],
        name=session_queue,
        debug=True)
    queue_client.get_properties()

    session_id = str(uuid.uuid4())
    async with queue_client.get_sender(session=session_id) as sender:
        for i in range(3):
            message = Message("Handler message no. {}".format(i))
            await sender.send(message)

    with pytest.raises(ValueError):
        session = queue_client.get_receiver(idle_timeout=5)

    session = queue_client.get_receiver(session=session_id, idle_timeout=5)
    count = 0
    async for message in session:
        print_message(message)
        assert message.session_id == session_id
        count += 1
        await message.complete()

    assert count == 3
async def test_async_queue_by_queue_client_conn_str_receive_handler_with_stop(live_servicebus_config, standard_queue):
    queue_client = QueueClient.from_connection_string(
        live_servicebus_config['conn_str'],
        name=standard_queue,
        debug=True)

    async with queue_client.get_sender() as sender:
        for i in range(10):
            message = Message("Stop message no. {}".format(i))
            await sender.send(message)

    messages = []
    receiver = queue_client.get_receiver(idle_timeout=5)
    async for message in receiver:
        messages.append(message)
        await message.complete()
        if len(messages) >= 5:
            break

    assert receiver.running
    assert len(messages) == 5

    async with receiver:
        async for message in receiver:
            messages.append(message)
            await message.complete()
            if len(messages) >= 5:
                break

    assert not receiver.running
    assert len(messages) == 6
async def test_async_session_by_session_client_conn_str_receive_handler_with_no_session(
        live_servicebus_config, session_queue):
    queue_client = QueueClient.from_connection_string(
        live_servicebus_config['conn_str'], name=session_queue, debug=True)

    session = queue_client.get_receiver(session=NEXT_AVAILABLE, idle_timeout=5)
    with pytest.raises(NoActiveSession):
        await session.open()
예제 #13
0
    async def test_async_session_by_conn_str_receive_handler_with_autolockrenew(
            self, servicebus_namespace_connection_string, servicebus_queue,
            **kwargs):

        session_id = str(uuid.uuid4())
        queue_client = QueueClient.from_connection_string(
            servicebus_namespace_connection_string,
            name=servicebus_queue.name,
            debug=False)

        async with queue_client.get_sender(session=session_id) as sender:
            for i in range(10):
                message = Message("{}".format(i))
                await sender.send(message)

        renewer = AutoLockRenew()
        messages = []
        async with queue_client.get_receiver(session=session_id,
                                             idle_timeout=5,
                                             mode=ReceiveSettleMode.PeekLock,
                                             prefetch=20) as session:
            renewer.register(session, timeout=60)
            print("Registered lock renew thread", session.locked_until,
                  datetime.now())
            with pytest.raises(SessionLockExpired):
                async for message in session:
                    if not messages:
                        await asyncio.sleep(45)
                        print("First sleep {}".format(session.locked_until -
                                                      datetime.now()))
                        assert not session.expired
                        with pytest.raises(TypeError):
                            message.expired
                        assert message.locked_until is None
                        with pytest.raises(TypeError):
                            await message.renew_lock()
                        assert message.lock_token is None
                        await message.complete()
                        messages.append(message)

                    elif len(messages) == 1:
                        await asyncio.sleep(45)
                        print("Second sleep {}".format(session.locked_until -
                                                       datetime.now()))
                        assert session.expired
                        assert isinstance(session.auto_renew_error,
                                          AutoLockRenewTimeout)
                        try:
                            await message.complete()
                            raise AssertionError(
                                "Didn't raise SessionLockExpired")
                        except SessionLockExpired as e:
                            assert isinstance(e.inner_exception,
                                              AutoLockRenewTimeout)
                        messages.append(message)

        await renewer.shutdown()
        assert len(messages) == 2
async def test_async_session_by_session_client_conn_str_receive_handler_with_no_session(live_servicebus_config, session_queue):
    queue_client = QueueClient.from_connection_string(
        live_servicebus_config['conn_str'],
        name=session_queue,
        debug=True)

    session = queue_client.get_receiver(session=NEXT_AVAILABLE, idle_timeout=5)
    with pytest.raises(NoActiveSession):
        await session.open()
예제 #15
0
async def main(count: int):
    queue_client: QueueClient = QueueClient.from_connection_string(
        sender_constr, 'simplequeue')
    msg = Message(body='This is the message content')

    for index in range(count):
        msg = Message(f'New Message {index}')
        msg.properties.content_type = 'text/plain'
        msg.properties.message_id = uuid.uuid4().hex
        await queue_client.send(msg)
예제 #16
0
    async def test_async_session_by_session_client_conn_str_receive_handler_with_no_session(
            self, servicebus_namespace_connection_string, servicebus_queue,
            **kwargs):

        queue_client = QueueClient.from_connection_string(
            servicebus_namespace_connection_string,
            name=servicebus_queue.name,
            debug=False)

        session = queue_client.get_receiver(session=NEXT_AVAILABLE,
                                            idle_timeout=5)
        with pytest.raises(NoActiveSession):
            await session.open()
async def test_async_session_by_session_client_conn_str_receive_handler_with_inactive_session(live_servicebus_config, session_queue):
    queue_client = QueueClient.from_connection_string(
        live_servicebus_config['conn_str'],
        name=session_queue,
        debug=True)

    session_id = str(uuid.uuid4())
    messages = []
    session = queue_client.get_receiver(session=session_id, mode=ReceiveSettleMode.ReceiveAndDelete, idle_timeout=5)
    async for message in session:
        messages.append(message)

    assert not session.running
    assert len(messages) == 0
async def test_async_session_by_session_client_conn_str_receive_handler_with_inactive_session(live_servicebus_config, session_queue):
    queue_client = QueueClient.from_connection_string(
        live_servicebus_config['conn_str'],
        name=session_queue,
        debug=True)

    session_id = str(uuid.uuid4())
    messages = []
    session = queue_client.get_receiver(session=session_id, mode=ReceiveSettleMode.ReceiveAndDelete, idle_timeout=5)
    async for message in session:
        messages.append(message)

    assert not session.running
    assert len(messages) == 0
예제 #19
0
async def test_async_queue_by_queue_client_conn_str_receive_handler_with_autolockrenew(
        live_servicebus_config, standard_queue):
    queue_client = QueueClient.from_connection_string(
        live_servicebus_config['conn_str'], name=standard_queue, debug=True)

    async with queue_client.get_sender() as sender:
        for i in range(10):
            message = Message("{}".format(i))
            await sender.send(message)

    renewer = AutoLockRenew()
    messages = []
    async with queue_client.get_receiver(idle_timeout=5,
                                         mode=ReceiveSettleMode.PeekLock,
                                         prefetch=10) as receiver:
        async for message in receiver:
            if not messages:
                messages.append(message)
                assert not message.expired
                renewer.register(message, timeout=60)
                print("Registered lock renew thread", message.locked_until,
                      datetime.now())
                await asyncio.sleep(50)
                print("Finished first sleep", message.locked_until)
                assert not message.expired
                await asyncio.sleep(25)
                print("Finished second sleep", message.locked_until,
                      datetime.now())
                assert message.expired
                try:
                    await message.complete()
                    raise AssertionError("Didn't raise MessageLockExpired")
                except MessageLockExpired as e:
                    assert isinstance(e.inner_exception, AutoLockRenewTimeout)
            else:
                if message.expired:
                    print("Remaining messages", message.locked_until,
                          datetime.now())
                    assert message.expired
                    with pytest.raises(MessageLockExpired):
                        await message.complete()
                else:
                    assert message.header.delivery_count >= 1
                    print("Remaining messages", message.locked_until,
                          datetime.now())
                    messages.append(message)
                    await message.complete()
    await renewer.shutdown()
    assert len(messages) == 11
async def test_async_session_by_conn_str_receive_handler_with_autolockrenew(live_servicebus_config, session_queue):
    session_id = str(uuid.uuid4())
    queue_client = QueueClient.from_connection_string(
        live_servicebus_config['conn_str'],
        name=session_queue,
        debug=True)

    async with queue_client.get_sender(session=session_id) as sender:
        for i in range(10):
            message = Message("{}".format(i))
            await sender.send(message)

    renewer = AutoLockRenew()
    messages = []
    async with queue_client.get_receiver(session=session_id, idle_timeout=5, mode=ReceiveSettleMode.PeekLock, prefetch=20) as session:
        renewer.register(session, timeout=60)
        print("Registered lock renew thread", session.locked_until, datetime.now())
        with pytest.raises(SessionLockExpired):
            async for message in session:
                if not messages:
                    await asyncio.sleep(45)
                    print("First sleep {}".format(session.locked_until - datetime.now()))
                    assert not session.expired
                    with pytest.raises(TypeError):
                        message.expired
                    assert message.locked_until is None
                    with pytest.raises(TypeError):
                        await message.renew_lock()
                    assert message.lock_token is None
                    await message.complete()
                    messages.append(message)

                elif len(messages) == 1:
                    await asyncio.sleep(45)
                    print("Second sleep {}".format(session.locked_until - datetime.now()))
                    assert session.expired
                    assert isinstance(session.auto_renew_error, AutoLockRenewTimeout)
                    try:
                        await message.complete()
                        raise AssertionError("Didn't raise SessionLockExpired")
                    except SessionLockExpired as e:
                        assert isinstance(e.inner_exception, AutoLockRenewTimeout)
                    messages.append(message)

    await renewer.shutdown()
    assert len(messages) == 2
async def test_async_queue_by_queue_client_conn_str_receive_handler_with_autolockrenew(live_servicebus_config, standard_queue):
    queue_client = QueueClient.from_connection_string(
        live_servicebus_config['conn_str'],
        name=standard_queue,
        debug=True)

    async with queue_client.get_sender() as sender:
        for i in range(10):
            message = Message("{}".format(i))
            await sender.send(message)

    renewer = AutoLockRenew()
    messages = []
    async with queue_client.get_receiver(idle_timeout=5, mode=ReceiveSettleMode.PeekLock, prefetch=10) as receiver:
        async for message in receiver:
            if not messages:
                messages.append(message)
                assert not message.expired
                renewer.register(message, timeout=60)
                print("Registered lock renew thread", message.locked_until, datetime.now())
                await asyncio.sleep(50)
                print("Finished first sleep", message.locked_until)
                assert not message.expired
                await asyncio.sleep(25)
                print("Finished second sleep", message.locked_until, datetime.now())
                assert message.expired
                try:
                    await message.complete()
                    raise AssertionError("Didn't raise MessageLockExpired")
                except MessageLockExpired as e:
                    assert isinstance(e.inner_exception, AutoLockRenewTimeout)
            else:
                if message.expired:
                    print("Remaining messages", message.locked_until, datetime.now())
                    assert message.expired
                    with pytest.raises(MessageLockExpired):
                        await message.complete()
                else:
                    assert message.header.delivery_count >= 1
                    print("Remaining messages", message.locked_until, datetime.now())
                    messages.append(message)
                    await message.complete()
    await renewer.shutdown()
    assert len(messages) == 11
예제 #22
0
async def test_async_queue_by_queue_client_conn_str_receive_handler_peeklock(
        live_servicebus_config, standard_queue):
    queue_client = QueueClient.from_connection_string(
        live_servicebus_config['conn_str'], name=standard_queue, debug=True)
    queue_client.get_properties()

    async with queue_client.get_sender() as sender:
        for i in range(10):
            message = Message("Handler message no. {}".format(i))
            message.enqueue_sequence_number = i
            await sender.send(message)

    with pytest.raises(ValueError):
        queue_client.get_receiver(session="test", idle_timeout=5)

    receiver = queue_client.get_receiver(idle_timeout=5)
    count = 0
    async for message in receiver:
        print_message(message)
        count += 1
        await message.complete()

    assert count == 10
async def test_async_session_get_set_state_with_receiver(live_servicebus_config, session_queue):
    queue_client = QueueClient.from_connection_string(
        live_servicebus_config['conn_str'],
        name=session_queue,
        debug=True)

    session_id = str(uuid.uuid4())
    queue_client.get_properties()
    async with queue_client.get_sender(session=session_id) as sender:
        for i in range(3):
            message = Message("Handler message no. {}".format(i))
            await sender.send(message)

    async with queue_client.get_receiver(session=session_id, idle_timeout=5) as session:
        assert await session.get_session_state() == None
        await session.set_session_state("first_state")
        count = 0
        async for m in session:
            assert m.properties.group_id == session_id.encode('utf-8')
            count += 1
        with pytest.raises(InvalidHandlerState):
            await session.get_session_state()
    assert count == 3
async def test_async_queue_by_queue_client_conn_str_receive_handler_peeklock(live_servicebus_config, standard_queue):
    queue_client = QueueClient.from_connection_string(
        live_servicebus_config['conn_str'],
        name=standard_queue,
        debug=True)
    queue_client.get_properties()

    async with queue_client.get_sender() as sender:
        for i in range(10):
            message = Message("Handler message no. {}".format(i))
            message.enqueue_sequence_number = i
            await sender.send(message)

    with pytest.raises(ValueError):
        queue_client.get_receiver(session="test", idle_timeout=5)

    receiver = queue_client.get_receiver(idle_timeout=5)
    count = 0
    async for message in receiver:
        print_message(message)
        count += 1
        await message.complete()

    assert count == 10
async def test_async_session_by_session_client_conn_str_receive_handler_with_stop(live_servicebus_config, session_queue):
    queue_client = QueueClient.from_connection_string(
        live_servicebus_config['conn_str'],
        name=session_queue,
        debug=True)

    session_id = str(uuid.uuid4())
    async with queue_client.get_sender(session=session_id) as sender:
        for i in range(10):
            message = Message("Stop message no. {}".format(i))
            await sender.send(message)

    messages = []
    session = queue_client.get_receiver(session=session_id, idle_timeout=5)
    async for message in session:
        assert session_id == session.session_id
        assert session_id == message.session_id
        messages.append(message)
        await message.complete()
        if len(messages) >= 5:
            break

    assert session.running
    assert len(messages) == 5

    async with session:
        async for message in session:
            assert session_id == session.session_id
            assert session_id == message.session_id
            messages.append(message)
            await message.complete()
            if len(messages) >= 5:
                break

    assert not session.running
    assert len(messages) == 6
예제 #26
0
 def __init__(self):
     self.connection_string = os.environ['SB_CONNECTION_STRING']
     self._scrape_client = QueueClient.from_connection_string(self.connection_string, SCRAPE_QUEUE_NAME)
async def test_async_snippet_sessions(live_servicebus_config, session_queue):
    queue_client = QueueClient.from_connection_string(
        live_servicebus_config['conn_str'], name=session_queue)
    queue_client.get_properties()

    # [START open_close_session_sender_context]
    from azure.servicebus.aio import Message

    async with queue_client.get_sender(session="MySessionID") as sender:

        await sender.send(Message("First"))
        await sender.send(Message("Second"))
    # [END open_close_session_sender_context]

    # [START queue_session_sender_messages]
    async with queue_client.get_sender(session="MySessionID") as sender:

        sender.queue_message(Message("First"))
        sender.queue_message(Message("Second"))
        await sender.send_pending_messages()
    # [END queue_session_sender_messages]

    # [START schedule_session_messages]
    async with queue_client.get_sender(session="MySessionID") as sender:

        enqueue_time = datetime.now() + timedelta(minutes=10)
        await sender.schedule(enqueue_time, Message("First"),
                              Message("Second"))
    # [END schedule_session_messages]

    # [START open_close_receiver_session_context]
    async with queue_client.get_receiver(session="MySessionID") as session:
        async for message in session:
            await process_message(message)
            # [END open_close_receiver_session_context]
            break

    # [START open_close_receiver_session_nextavailable]
    from azure.servicebus import NEXT_AVAILABLE, NoActiveSession

    try:
        async with queue_client.get_receiver(session=NEXT_AVAILABLE,
                                             idle_timeout=5) as receiver:
            async for message in receiver:
                await process_message(message)
    except NoActiveSession:
        pass
    # [END open_close_receiver_session_nextavailable]

    # [START set_session_state]
    async with queue_client.get_receiver(session="MySessionID",
                                         idle_timeout=5) as session:
        current_state = await session.get_session_state()
        if not current_state:
            await session.set_session_state("OPENED")
    # [END set_session_state]

    try:
        # [START receiver_peek_session_messages]
        async with queue_client.get_receiver(session=NEXT_AVAILABLE,
                                             idle_timeout=5) as receiver:
            pending_messages = await receiver.peek(count=5)
        # [END receiver_peek_session_messages]
    except NoActiveSession:
        pass

    await queue_client.send([
        Message("a"),
        Message("b"),
        Message("c"),
        Message("d"),
        Message("e"),
        Message("f")
    ],
                            session="MySessionID")
    try:
        # [START receiver_defer_session_messages]
        async with queue_client.get_receiver(session="MySessionID",
                                             idle_timeout=5) as receiver:
            sequence_numbers = []
            async for message in receiver:
                sequence_numbers.append(message.sequence_number)
                await message.defer()
                break

            message = await receiver.receive_deferred_messages(sequence_numbers
                                                               )
        # [END receiver_defer_session_messages]
    except ServiceBusError:
        pass

    # [START receiver_renew_session_lock]
    async with queue_client.get_receiver(session="MySessionID",
                                         idle_timeout=5) as session:
        async for message in session:
            await process_message(message)
            await session.renew_lock()
            # [END receiver_renew_session_lock]
            break

    # [START auto_lock_renew_async_session]
    from azure.servicebus.aio import AutoLockRenew

    lock_renewal = AutoLockRenew()
    async with queue_client.get_receiver(session="MySessionID",
                                         idle_timeout=3) as session:
        lock_renewal.register(session)

        async for message in session:
            await process_message(message)
            await message.complete()
            # [END auto_lock_renew_async_session]
            break
async def test_async_snippet_sessions(live_servicebus_config, session_queue):
    queue_client = QueueClient.from_connection_string(
        live_servicebus_config['conn_str'],
        name=session_queue)
    queue_client.get_properties()

    # [START open_close_session_sender_context]
    from azure.servicebus.aio import Message

    async with queue_client.get_sender(session="MySessionID") as sender:

        await sender.send(Message("First"))
        await sender.send(Message("Second"))
    # [END open_close_session_sender_context]

    # [START queue_session_sender_messages]
    async with queue_client.get_sender(session="MySessionID") as sender:

        sender.queue_message(Message("First"))
        sender.queue_message(Message("Second"))
        await sender.send_pending_messages()
    # [END queue_session_sender_messages]

    # [START schedule_session_messages]
    async with queue_client.get_sender(session="MySessionID") as sender:

        enqueue_time = datetime.now() + timedelta(minutes=10)
        await sender.schedule(enqueue_time, Message("First"), Message("Second"))
    # [END schedule_session_messages]

    # [START open_close_receiver_session_context]
    async with queue_client.get_receiver(session="MySessionID") as session:
        async for message in session:
            await process_message(message)
    # [END open_close_receiver_session_context]
            break

    # [START open_close_receiver_session_nextavailable]
    from azure.servicebus import NEXT_AVAILABLE, NoActiveSession

    try:
        async with queue_client.get_receiver(session=NEXT_AVAILABLE, idle_timeout=5) as receiver:
            async for message in receiver:
                await process_message(message)
    except NoActiveSession:
        pass
    # [END open_close_receiver_session_nextavailable]

    # [START set_session_state]
    async with queue_client.get_receiver(session="MySessionID", idle_timeout=5) as session:
        current_state = await session.get_session_state()
        if not current_state:
            await session.set_session_state("OPENED")
    # [END set_session_state]

    try:
        # [START receiver_peek_session_messages]
        async with queue_client.get_receiver(session=NEXT_AVAILABLE, idle_timeout=5) as receiver:
            pending_messages = await receiver.peek(count=5)
        # [END receiver_peek_session_messages]
    except NoActiveSession:
        pass

    await queue_client.send([Message("a"), Message("b"), Message("c"),  Message("d"),  Message("e"),  Message("f")], session="MySessionID")
    try:
        # [START receiver_defer_session_messages]
        async with queue_client.get_receiver(session="MySessionID", idle_timeout=5) as receiver:
            sequence_numbers = []
            async for message in receiver:
                sequence_numbers.append(message.sequence_number)
                await message.defer()
                break

            message = await receiver.receive_deferred_messages(sequence_numbers)
        # [END receiver_defer_session_messages]
    except ServiceBusError:
        pass

    # [START receiver_renew_session_lock]
    async with queue_client.get_receiver(session="MySessionID", idle_timeout=5) as session:
        async for message in session:
            await process_message(message)
            await session.renew_lock()
    # [END receiver_renew_session_lock]
            break

    # [START auto_lock_renew_async_session]
    from azure.servicebus.aio import AutoLockRenew

    lock_renewal = AutoLockRenew()
    async with queue_client.get_receiver(session="MySessionID", idle_timeout=3) as session:
        lock_renewal.register(session)

        async for message in session:
            await process_message(message)
            await message.complete()
    # [END auto_lock_renew_async_session]
            break
async def test_async_snippet_queues(live_servicebus_config, standard_queue):
    # [START create_async_servicebus_client]
    import os
    from azure.servicebus.aio import ServiceBusClient, Message

    namespace = os.environ['SERVICE_BUS_HOSTNAME']
    shared_access_policy = os.environ['SERVICE_BUS_SAS_POLICY']
    shared_access_key = os.environ['SERVICE_BUS_SAS_KEY']

    client = ServiceBusClient(
        service_namespace=namespace,
        shared_access_key_name=shared_access_policy,
        shared_access_key_value=shared_access_key)
    # [END create_async_servicebus_client]

    # [START create_async_servicebus_client_connstr]
    connection_str = os.environ['SERVICE_BUS_CONNECTION_STR']

    client = ServiceBusClient.from_connection_string(connection_str)
    # [END create_async_servicebus_client_connstr]

    # [START get_async_queue_client]
    from azure.servicebus import ServiceBusResourceNotFound

    try:
        queue_client = client.get_queue("MyQueue")
    except ServiceBusResourceNotFound:
        pass
    # [END get_async_queue_client]
    try:
        # [START create_queue_client]
        import os
        from azure.servicebus.aio import QueueClient

        connection_str = os.environ['SERVICE_BUS_CONNECTION_STR']
        queue_client = QueueClient.from_connection_string(connection_str, name="MyQueue")
        queue_properties = queue_client.get_properties()

        # [END create_queue_client]
    except ServiceBusResourceNotFound:
        pass

    queue_client = client.get_queue(standard_queue)

    # [START client_peek_messages]
    peeked_messages = await queue_client.peek(count=5)
    # [END client_peek_messages]

    await queue_client.send(Message("a"))
    try:
        # [START client_defer_messages]
        sequence_numbers = []
        async with queue_client.get_receiver() as receiver:
            async for message in receiver:
                sequence_numbers.append(message.sequence_number)
                await message.defer()
                break

        deferred = await queue_client.receive_deferred_messages(sequence_numbers)
        # [END client_defer_messages]
    except ValueError:
        pass

    await queue_client.send(Message("a"))
    try:
        sequence_numbers = []
        async with queue_client.get_receiver(idle_timeout=2) as receiver:
            async for message in receiver:
                sequence_numbers.append(message.sequence_number)
                await message.defer()
                break
        # [START client_settle_deferred_messages]
        deferred = await queue_client.receive_deferred_messages(sequence_numbers)

        await queue_client.settle_deferred_messages('completed', deferred)
        # [END client_settle_deferred_messages]
    except ValueError:
        pass

    # [START open_close_sender_directly]
    from azure.servicebus.aio import Message

    sender = queue_client.get_sender()
    try:
        await sender.open()
        await sender.send(Message("foobar"))
    finally:
        await sender.close()
    # [END open_close_sender_directly]

    # [START queue_client_send]
    from azure.servicebus.aio import Message

    message = Message("Hello World")
    await queue_client.send(message)
    # [END queue_client_send]

    # [START queue_client_send_multiple]
    from azure.servicebus.aio import Message

    messages = [Message("First"), Message("Second")]
    await queue_client.send(messages, message_timeout=30)
    # [END queue_client_send_multiple]

    # [START open_close_receiver_directly]
    receiver = queue_client.get_receiver()
    async for message in receiver:
        print(message)
        break
    await receiver.close()
    # [END open_close_receiver_directly]

    await queue_client.send(Message("a"))
    # [START open_close_receiver_context]
    async with queue_client.get_receiver() as receiver:
        async for message in receiver:
            await process_message(message)
    # [END open_close_receiver_context]
            break

    # [START open_close_sender_context]
    async with queue_client.get_sender() as sender:

        await sender.send(Message("First"))
        await sender.send(Message("Second"))
    # [END open_close_sender_context]

    # [START queue_sender_messages]
    async with queue_client.get_sender() as sender:

        sender.queue_message(Message("First"))
        sender.queue_message(Message("Second"))
        await sender.send_pending_messages()
    # [END queue_sender_messages]

    # [START schedule_messages]
    async with queue_client.get_sender() as sender:

        enqueue_time = datetime.now() + timedelta(minutes=10)
        await sender.schedule(enqueue_time, Message("First"), Message("Second"))
    # [END schedule_messages]

    # [START cancel_schedule_messages]
    async with queue_client.get_sender() as sender:

        enqueue_time = datetime.now() + timedelta(minutes=10)
        sequence_numbers = await sender.schedule(enqueue_time, Message("First"), Message("Second"))

        await sender.cancel_scheduled_messages(*sequence_numbers)
    # [END cancel_schedule_messages]

    # [START receiver_peek_messages]
    async with queue_client.get_receiver() as receiver:
        pending_messages = await receiver.peek(count=5)
    # [END receiver_peek_messages]

    try:
        await queue_client.send(Message("a"))
        # [START receiver_defer_messages]
        async with queue_client.get_receiver() as receiver:
            async for message in receiver:
                sequence_no = message.sequence_number
                await message.defer()
                break

            message = await receiver.receive_deferred_messages([sequence_no])
        # [END receiver_defer_messages]
    except ServiceBusError:
        pass

    await queue_client.send(Message("a"))
    # [START receiver_deadletter_messages]
    async with queue_client.get_receiver(idle_timeout=5) as receiver:
        async for message in receiver:
            await message.dead_letter()

    async with queue_client.get_deadletter_receiver() as receiver:
        async for message in receiver:
            await message.complete()
    # [END receiver_deadletter_messages]
            break

    # [START receiver_fetch_batch]
    async with queue_client.get_receiver(idle_timeout=5, prefetch=100) as receiver:
        messages = await receiver.fetch_next(timeout=5)
        await asyncio.gather(*[m.complete() for m in messages])
    # [END receiver_fetch_batch]

    # [START auto_lock_renew_async_message]
    from azure.servicebus.aio import AutoLockRenew

    lock_renewal = AutoLockRenew()
    async with queue_client.get_receiver(idle_timeout=3) as queue_receiver:
        async for message in queue_receiver:
            lock_renewal.register(message, timeout=60)
            await process_message(message)

            await message.complete()
async def test_async_snippet_queues(live_servicebus_config, standard_queue):
    # [START create_async_servicebus_client]
    import os
    from azure.servicebus.aio import ServiceBusClient, Message

    namespace = os.environ['SERVICE_BUS_HOSTNAME']
    shared_access_policy = os.environ['SERVICE_BUS_SAS_POLICY']
    shared_access_key = os.environ['SERVICE_BUS_SAS_KEY']

    client = ServiceBusClient(service_namespace=namespace,
                              shared_access_key_name=shared_access_policy,
                              shared_access_key_value=shared_access_key)
    # [END create_async_servicebus_client]

    # [START create_async_servicebus_client_connstr]
    connection_str = os.environ['SERVICE_BUS_CONNECTION_STR']

    client = ServiceBusClient.from_connection_string(connection_str)
    # [END create_async_servicebus_client_connstr]

    # [START get_async_queue_client]
    from azure.servicebus import ServiceBusResourceNotFound

    try:
        queue_client = client.get_queue("MyQueue")
    except ServiceBusResourceNotFound:
        pass
    # [END get_async_queue_client]
    try:
        # [START create_queue_client]
        import os
        from azure.servicebus.aio import QueueClient

        connection_str = os.environ['SERVICE_BUS_CONNECTION_STR']
        queue_client = QueueClient.from_connection_string(connection_str,
                                                          name="MyQueue")
        queue_properties = queue_client.get_properties()

        # [END create_queue_client]
    except ServiceBusResourceNotFound:
        pass

    queue_client = client.get_queue(standard_queue)

    # [START client_peek_messages]
    peeked_messages = await queue_client.peek(count=5)
    # [END client_peek_messages]

    await queue_client.send(Message("a"))
    try:
        # [START client_defer_messages]
        sequence_numbers = []
        async with queue_client.get_receiver() as receiver:
            async for message in receiver:
                sequence_numbers.append(message.sequence_number)
                await message.defer()
                break

        deferred = await queue_client.receive_deferred_messages(
            sequence_numbers)
        # [END client_defer_messages]
    except ValueError:
        pass

    await queue_client.send(Message("a"))
    try:
        sequence_numbers = []
        async with queue_client.get_receiver(idle_timeout=2) as receiver:
            async for message in receiver:
                sequence_numbers.append(message.sequence_number)
                await message.defer()
                break
        # [START client_settle_deferred_messages]
        deferred = await queue_client.receive_deferred_messages(
            sequence_numbers)

        await queue_client.settle_deferred_messages('completed', deferred)
        # [END client_settle_deferred_messages]
    except ValueError:
        pass

    # [START open_close_sender_directly]
    from azure.servicebus.aio import Message

    sender = queue_client.get_sender()
    try:
        await sender.open()
        await sender.send(Message("foobar"))
    finally:
        await sender.close()
    # [END open_close_sender_directly]

    # [START queue_client_send]
    from azure.servicebus.aio import Message

    message = Message("Hello World")
    await queue_client.send(message)
    # [END queue_client_send]

    # [START queue_client_send_multiple]
    from azure.servicebus.aio import Message

    messages = [Message("First"), Message("Second")]
    await queue_client.send(messages, message_timeout=30)
    # [END queue_client_send_multiple]

    # [START open_close_receiver_directly]
    receiver = queue_client.get_receiver()
    async for message in receiver:
        print(message)
        break
    await receiver.close()
    # [END open_close_receiver_directly]

    await queue_client.send(Message("a"))
    # [START open_close_receiver_context]
    async with queue_client.get_receiver() as receiver:
        async for message in receiver:
            await process_message(message)
            # [END open_close_receiver_context]
            break

    # [START open_close_sender_context]
    async with queue_client.get_sender() as sender:

        await sender.send(Message("First"))
        await sender.send(Message("Second"))
    # [END open_close_sender_context]

    # [START queue_sender_messages]
    async with queue_client.get_sender() as sender:

        sender.queue_message(Message("First"))
        sender.queue_message(Message("Second"))
        await sender.send_pending_messages()
    # [END queue_sender_messages]

    # [START schedule_messages]
    async with queue_client.get_sender() as sender:

        enqueue_time = datetime.now() + timedelta(minutes=10)
        await sender.schedule(enqueue_time, Message("First"),
                              Message("Second"))
    # [END schedule_messages]

    # [START cancel_schedule_messages]
    async with queue_client.get_sender() as sender:

        enqueue_time = datetime.now() + timedelta(minutes=10)
        sequence_numbers = await sender.schedule(enqueue_time,
                                                 Message("First"),
                                                 Message("Second"))

        await sender.cancel_scheduled_messages(*sequence_numbers)
    # [END cancel_schedule_messages]

    # [START receiver_peek_messages]
    async with queue_client.get_receiver() as receiver:
        pending_messages = await receiver.peek(count=5)
    # [END receiver_peek_messages]

    try:
        await queue_client.send(Message("a"))
        # [START receiver_defer_messages]
        async with queue_client.get_receiver() as receiver:
            async for message in receiver:
                sequence_no = message.sequence_number
                await message.defer()
                break

            message = await receiver.receive_deferred_messages([sequence_no])
        # [END receiver_defer_messages]
    except ServiceBusError:
        pass

    await queue_client.send(Message("a"))
    # [START receiver_deadletter_messages]
    async with queue_client.get_receiver(idle_timeout=5) as receiver:
        async for message in receiver:
            await message.dead_letter()

    async with queue_client.get_deadletter_receiver() as receiver:
        async for message in receiver:
            await message.complete()
            # [END receiver_deadletter_messages]
            break

    # [START receiver_fetch_batch]
    async with queue_client.get_receiver(idle_timeout=5,
                                         prefetch=100) as receiver:
        messages = await receiver.fetch_next(timeout=5)
        await asyncio.gather(*[m.complete() for m in messages])
    # [END receiver_fetch_batch]

    # [START auto_lock_renew_async_message]
    from azure.servicebus.aio import AutoLockRenew

    lock_renewal = AutoLockRenew()
    async with queue_client.get_receiver(idle_timeout=3) as queue_receiver:
        async for message in queue_receiver:
            lock_renewal.register(message, timeout=60)
            await process_message(message)

            await message.complete()
예제 #31
0
 async def send_response(self, original_message_id: str, reply_to: str, reply_content: str):
     complete_client = QueueClient.from_connection_string(self.connection_string, reply_to)
     async with complete_client.get_sender() as reply_sender:
         reply_msg = Message(reply_content)
         reply_msg.properties.correlation_id = original_message_id
         await reply_sender.send(reply_msg)