Ejemplo n.º 1
0
 async Task TopicClientReceiveDeleteTestCase(bool partitioned, bool sessionEnabled, int messageCount = 10)
 {
     await ServiceBusScope.UsingTopicAsync(partitioned, sessionEnabled, async (topicName, subscriptionName) =>
     {
         var topicClient        = new TopicClient(TestUtility.NamespaceConnectionString, topicName);
         var subscriptionClient = new SubscriptionClient(
             TestUtility.NamespaceConnectionString,
             topicName,
             subscriptionName,
             ReceiveMode.ReceiveAndDelete);
         try
         {
             await
             this.ReceiveDeleteTestCase(
                 topicClient.InnerSender,
                 subscriptionClient.InnerSubscriptionClient.InnerReceiver,
                 messageCount);
         }
         finally
         {
             await subscriptionClient.CloseAsync();
             await topicClient.CloseAsync();
         }
     });
 }
        private async Task OnMessageTestAsync(bool partitioned, bool sessionEnabled, int maxConcurrentCalls, ReceiveMode mode, bool autoComplete)
        {
            const int messageCount = 10;

            await ServiceBusScope.UsingTopicAsync(partitioned, sessionEnabled, async (topicName, subscriptionName) =>
            {
                var topicClient        = new TopicClient(TestUtility.NamespaceConnectionString, topicName);
                var subscriptionClient = new SubscriptionClient(
                    TestUtility.NamespaceConnectionString,
                    topicName,
                    subscriptionName,
                    mode);

                try
                {
                    await this.OnMessageAsyncTestCase(
                        topicClient.InnerSender,
                        subscriptionClient.InnerSubscriptionClient.InnerReceiver,
                        maxConcurrentCalls,
                        autoComplete,
                        messageCount);
                }
                finally
                {
                    await subscriptionClient.CloseAsync();
                    await topicClient.CloseAsync();
                }
            });
        }
Ejemplo n.º 3
0
        async Task TopicClientPeekLockWithDeadLetterTestCase(bool partitioned, bool sessionEnabled, int messageCount = 10)
        {
            await ServiceBusScope.UsingTopicAsync(partitioned, sessionEnabled, async (topicName, subscriptionName) =>
            {
                var topicClient        = new TopicClient(TestUtility.NamespaceConnectionString, topicName);
                var subscriptionClient = new SubscriptionClient(
                    TestUtility.NamespaceConnectionString,
                    topicName,
                    subscriptionName);

                // Create DLQ Client To Receive DeadLetteredMessages
                var subscriptionDeadletterPath   = EntityNameHelper.FormatDeadLetterPath(subscriptionName);
                var deadLetterSubscriptionClient = new SubscriptionClient(
                    TestUtility.NamespaceConnectionString,
                    topicName,
                    subscriptionDeadletterPath);

                try
                {
                    await
                    this.PeekLockWithDeadLetterTestCase(
                        topicClient.InnerSender,
                        subscriptionClient.InnerSubscriptionClient.InnerReceiver,
                        deadLetterSubscriptionClient.InnerSubscriptionClient.InnerReceiver,
                        messageCount);
                }
                finally
                {
                    await deadLetterSubscriptionClient.CloseAsync();
                    await topicClient.CloseAsync();
                    await subscriptionClient.CloseAsync();
                }
            });
        }
Ejemplo n.º 4
0
        public async Task UpdatingPrefetchCountOnSubscriptionClientUpdatesTheReceiverPrefetchCount()
        {
            await ServiceBusScope.UsingTopicAsync(partitioned : false, sessionEnabled : false, async (topicName, subscriptionName) =>
            {
                var subscriptionClient = new SubscriptionClient(
                    TestUtility.NamespaceConnectionString,
                    topicName,
                    subscriptionName,
                    ReceiveMode.ReceiveAndDelete);

                try
                {
                    Assert.Equal(0, subscriptionClient.PrefetchCount);

                    subscriptionClient.PrefetchCount = 2;
                    Assert.Equal(2, subscriptionClient.PrefetchCount);
                    // Message receiver should be created with latest prefetch count (lazy load).
                    Assert.Equal(2, subscriptionClient.InnerSubscriptionClient.InnerReceiver.PrefetchCount);

                    subscriptionClient.PrefetchCount = 3;
                    Assert.Equal(3, subscriptionClient.PrefetchCount);
                    // Already created message receiver should have its prefetch value updated.
                    Assert.Equal(3, subscriptionClient.InnerSubscriptionClient.InnerReceiver.PrefetchCount);
                }
                finally
                {
                    await subscriptionClient.CloseAsync();
                }
            });
        }
Ejemplo n.º 5
0
        public async Task CreatingLinkToNonExistingEntityShouldThrowEntityNotFoundException()
        {
            var receiver = new MessageReceiver(TestUtility.NamespaceConnectionString, "nonExistingEntity"); // Covers queue and topic
            await Assert.ThrowsAsync <MessagingEntityNotFoundException>(async() => await receiver.ReceiveAsync());

            await ServiceBusScope.UsingTopicAsync(partitioned : false, sessionEnabled : false, async (topicName, subscriptionName) =>
            {
                receiver = new MessageReceiver(TestUtility.NamespaceConnectionString, EntityNameHelper.FormatSubscriptionPath(topicName, "nonexistingsub"));
                await Assert.ThrowsAsync <MessagingEntityNotFoundException>(async() => await receiver.ReceiveAsync());
            });
        }
Ejemplo n.º 6
0
        public async Task OnSessionExceptionHandlerCalledWhenRegisteredOnNonSessionFulSubscription()
        {
            await ServiceBusScope.UsingTopicAsync(partitioned : false, sessionEnabled : false, async (topicName, subscriptionName) =>
            {
                var exceptionReceivedHandlerCalled = false;
                var topicClient        = new TopicClient(TestUtility.NamespaceConnectionString, topicName);
                var subscriptionClient = new SubscriptionClient(
                    TestUtility.NamespaceConnectionString,
                    topicClient.TopicName,
                    subscriptionName,
                    ReceiveMode.PeekLock);

                var sessionHandlerOptions = new SessionHandlerOptions(eventArgs =>
                {
                    Assert.NotNull(eventArgs);
                    Assert.NotNull(eventArgs.Exception);
                    if (eventArgs.Exception is InvalidOperationException)
                    {
                        exceptionReceivedHandlerCalled = true;
                    }
                    return(Task.CompletedTask);
                })
                {
                    MaxConcurrentSessions = 1
                };

                subscriptionClient.RegisterSessionHandler(
                    (session, message, token) => Task.CompletedTask,
                    sessionHandlerOptions);

                try
                {
                    var stopwatch = Stopwatch.StartNew();
                    while (stopwatch.Elapsed.TotalSeconds <= 10)
                    {
                        if (exceptionReceivedHandlerCalled)
                        {
                            break;
                        }

                        await Task.Delay(TimeSpan.FromSeconds(1));
                    }

                    TestUtility.Log($"{DateTime.Now}: ExceptionReceivedHandlerCalled: {exceptionReceivedHandlerCalled}");
                    Assert.True(exceptionReceivedHandlerCalled);
                }
                finally
                {
                    await subscriptionClient.CloseAsync();
                    await topicClient.CloseAsync();
                }
            });
        }
Ejemplo n.º 7
0
        private async Task OnSessionTestAsync(bool partitioned, bool sessionEnabled, int maxConcurrentCalls, ReceiveMode mode, bool autoComplete)
        {
            await ServiceBusScope.UsingTopicAsync(partitioned, sessionEnabled, async (topicName, subscriptionName) =>
            {
                TestUtility.Log($"Topic: {topicName}, MaxConcurrentCalls: {maxConcurrentCalls}, Receive Mode: {mode.ToString()}, AutoComplete: {autoComplete}");
                var topicClient        = new TopicClient(TestUtility.NamespaceConnectionString, topicName);
                var subscriptionClient = new SubscriptionClient(
                    TestUtility.NamespaceConnectionString,
                    topicClient.TopicName,
                    subscriptionName,
                    ReceiveMode.PeekLock);

                try
                {
                    var sessionHandlerOptions =
                        new SessionHandlerOptions(ExceptionReceivedHandler)
                    {
                        MaxConcurrentSessions = 5,
                        MessageWaitTimeout    = TimeSpan.FromSeconds(5),
                        AutoComplete          = true
                    };

                    var testSessionHandler = new TestSessionHandler(
                        subscriptionClient.ReceiveMode,
                        sessionHandlerOptions,
                        topicClient.InnerSender,
                        subscriptionClient.SessionPumpHost);

                    // Send messages to Session
                    await testSessionHandler.SendSessionMessages();

                    // Register handler
                    testSessionHandler.RegisterSessionHandler(sessionHandlerOptions);

                    // Verify messages were received.
                    await testSessionHandler.VerifyRun();
                }
                finally
                {
                    await subscriptionClient.CloseAsync();
                    await topicClient.CloseAsync();
                }
            });
        }
Ejemplo n.º 8
0
        public async Task SqlFilterTestCase(bool partitioned, bool sessionEnabled)
        {
            await ServiceBusScope.UsingTopicAsync(partitioned, sessionEnabled, async (topicName, subscriptionName) =>
            {
                var topicClient        = new TopicClient(TestUtility.NamespaceConnectionString, topicName);
                var subscriptionClient = new SubscriptionClient(
                    TestUtility.NamespaceConnectionString,
                    topicName,
                    subscriptionName,
                    ReceiveMode.ReceiveAndDelete);

                try
                {
                    try
                    {
                        await subscriptionClient.RemoveRuleAsync(RuleDescription.DefaultRuleName);
                    }
                    catch (Exception e)
                    {
                        TestUtility.Log($"Remove Default Rule failed with: {e.Message}");
                    }

                    await subscriptionClient.AddRuleAsync(new RuleDescription
                    {
                        Filter = new SqlFilter("Color = 'RedSql'"),
                        Name   = "RedSql"
                    });

                    var messageId1 = Guid.NewGuid().ToString();
                    await topicClient.SendAsync(new Message
                    {
                        MessageId      = messageId1,
                        Label          = "BlueSql",
                        UserProperties = { { "color", "BlueSql" } }
                    });
                    TestUtility.Log($"Sent Message: {messageId1}");

                    var messageId2 = Guid.NewGuid().ToString();
                    await topicClient.SendAsync(new Message
                    {
                        MessageId      = messageId2,
                        Label          = "RedSql",
                        UserProperties = { { "color", "RedSql" } }
                    });
                    TestUtility.Log($"Sent Message: {messageId2}");

                    var messages = await subscriptionClient.InnerSubscriptionClient.InnerReceiver.ReceiveAsync(maxMessageCount: 2);
                    Assert.NotNull(messages);
                    Assert.True(messages.Count == 1);
                    Assert.Equal(messageId2, messages.First().MessageId);
                }
                finally
                {
                    try
                    {
                        await subscriptionClient.RemoveRuleAsync("RedSql");
                        await subscriptionClient.AddRuleAsync(RuleDescription.DefaultRuleName, new TrueFilter());
                    }
                    catch (Exception e)
                    {
                        TestUtility.Log($" Cleanup failed with Exception: {e.Message}");
                    }

                    await subscriptionClient.CloseAsync();
                    await topicClient.CloseAsync();
                }
            });
        }
Ejemplo n.º 9
0
        public async Task GetRulesTestCase()
        {
            await ServiceBusScope.UsingTopicAsync(partitioned : false, sessionEnabled : false, async (topicName, subscriptionName) =>
            {
                var subscriptionClient = new SubscriptionClient(
                    TestUtility.NamespaceConnectionString,
                    topicName,
                    subscriptionName,
                    ReceiveMode.ReceiveAndDelete);
                var sqlRuleName         = "sqlRule";
                var correlationRuleName = "correlationRule";

                try
                {
                    var rules = (await subscriptionClient.GetRulesAsync()).ToList();
                    Assert.Single(rules);
                    var firstRule = rules[0];
                    Assert.Equal(RuleDescription.DefaultRuleName, firstRule.Name);
                    Assert.IsAssignableFrom <SqlFilter>(firstRule.Filter);
                    Assert.Null(firstRule.Action);

                    await subscriptionClient.AddRuleAsync(sqlRuleName, new SqlFilter("price > 10"));

                    var ruleDescription = new RuleDescription(correlationRuleName)
                    {
                        Filter = new CorrelationFilter
                        {
                            CorrelationId = "correlationId",
                            Label         = "label",
                            MessageId     = "messageId",
                            Properties    =
                            {
                                { "key1", "value1" }
                            },
                            ReplyTo          = "replyTo",
                            ReplyToSessionId = "replyToSessionId",
                            SessionId        = "sessionId",
                            To = "to"
                        },
                        Action = new SqlRuleAction("Set CorrelationId = 'newValue'")
                    };
                    await subscriptionClient.AddRuleAsync(ruleDescription);

                    rules = (await subscriptionClient.GetRulesAsync()).ToList();
                    Assert.Equal(3, rules.Count);

                    var sqlRule = rules.FirstOrDefault(rule => rule.Name.Equals(sqlRuleName));
                    Assert.NotNull(sqlRule);
                    Assert.Null(sqlRule.Action);
                    Assert.IsType <SqlFilter>(sqlRule.Filter);
                    Assert.Equal("price > 10", ((SqlFilter)sqlRule.Filter).SqlExpression);

                    var correlationRule = rules.FirstOrDefault(rule => rule.Name.Equals(correlationRuleName));
                    Assert.NotNull(correlationRule);
                    Assert.IsType <SqlRuleAction>(correlationRule.Action);
                    var sqlRuleAction = correlationRule.Action as SqlRuleAction;
                    Assert.NotNull(sqlRuleAction);
                    Assert.Equal("Set CorrelationId = 'newValue'", sqlRuleAction.SqlExpression);
                    Assert.IsType <CorrelationFilter>(correlationRule.Filter);
                    var correlationFilter = correlationRule.Filter as CorrelationFilter;
                    Assert.NotNull(correlationFilter);
                    Assert.Equal("correlationId", correlationFilter.CorrelationId);
                    Assert.Equal("label", correlationFilter.Label);
                    Assert.Equal("messageId", correlationFilter.MessageId);
                    Assert.Equal("replyTo", correlationFilter.ReplyTo);
                    Assert.Equal("replyToSessionId", correlationFilter.ReplyToSessionId);
                    Assert.Equal("sessionId", correlationFilter.SessionId);
                    Assert.Equal("to", correlationFilter.To);
                    Assert.NotNull(correlationFilter.Properties);
                    Assert.Equal("value1", correlationFilter.Properties["key1"]);
                }
                finally
                {
                    // Attempt to cleanup rules that may or may not exist; ignore any exceptions, as they're expected.
                    var _ = Task.WhenAll(
                        subscriptionClient.RemoveRuleAsync(sqlRuleName),
                        subscriptionClient.RemoveRuleAsync(correlationRuleName)).ConfigureAwait(false);

                    await subscriptionClient.CloseAsync();
                }
            });
        }
        private async Task OnSessionTestAsync(bool partitioned, bool sessionEnabled, int maxConcurrentCalls, ReceiveMode mode, bool autoComplete)
        {
            await ServiceBusScope.UsingTopicAsync(partitioned, sessionEnabled, async (topicName, subscriptionName) =>
            {
                TestUtility.Log($"Topic: {topicName}, MaxConcurrentCalls: {maxConcurrentCalls}, Receive Mode: {mode.ToString()}, AutoComplete: {autoComplete}");
                var topicClient        = new TopicClient(TestUtility.NamespaceConnectionString, topicName);
                var subscriptionClient = new SubscriptionClient(
                    TestUtility.NamespaceConnectionString,
                    topicClient.TopicName,
                    subscriptionName,
                    ReceiveMode.PeekLock);

                try
                {
                    var sessionHandlerOptions =
                        new SessionHandlerOptions(ExceptionReceivedHandler)
                    {
                        MaxConcurrentSessions = maxConcurrentCalls,
                        MessageWaitTimeout    = TimeSpan.FromSeconds(5),
                        AutoComplete          = true
                    };

                    var testSessionHandler = new TestSessionHandler(
                        subscriptionClient.ReceiveMode,
                        sessionHandlerOptions,
                        topicClient.InnerSender,
                        subscriptionClient.SessionPumpHost);

                    // Send messages to Session
                    await testSessionHandler.SendSessionMessages();

                    // Register handler
                    testSessionHandler.RegisterSessionHandler(sessionHandlerOptions);

                    // Verify messages were received.
                    await testSessionHandler.VerifyRun();

                    testSessionHandler.ClearData();
                }
                finally
                {
                    await subscriptionClient.CloseAsync();
                    await topicClient.CloseAsync();
                }
            });

            // test UnregisterSessionHandler can wait for message handling upto the timeout user defined.
            await ServiceBusScope.UsingTopicAsync(partitioned, sessionEnabled, async (topicName, subscriptionName) =>
            {
                TestUtility.Log($"Topic: {topicName}, MaxConcurrentCalls: {maxConcurrentCalls}, Receive Mode: {mode.ToString()}, AutoComplete: {autoComplete}");
                var topicClient        = new TopicClient(TestUtility.NamespaceConnectionString, topicName);
                var subscriptionClient = new SubscriptionClient(
                    TestUtility.NamespaceConnectionString,
                    topicClient.TopicName,
                    subscriptionName,
                    ReceiveMode.PeekLock);

                try
                {
                    var sessionHandlerOptions =
                        new SessionHandlerOptions(ExceptionReceivedHandler)
                    {
                        MaxConcurrentSessions = maxConcurrentCalls,
                        MessageWaitTimeout    = TimeSpan.FromSeconds(5),
                        AutoComplete          = true
                    };

                    var testSessionHandler = new TestSessionHandler(
                        subscriptionClient.ReceiveMode,
                        sessionHandlerOptions,
                        topicClient.InnerSender,
                        subscriptionClient.SessionPumpHost);

                    // Send messages to Session
                    await testSessionHandler.SendSessionMessages();

                    // Register handler
                    testSessionHandler.RegisterSessionHandlerAndRecordReceivedMessageCount(subscriptionClient.ReceiveMode == ReceiveMode.PeekLock, 8);

                    // Session handler set up has greater latency than message handler. Delay here to enable some processing time of the session pump.
                    await Task.Delay(TimeSpan.FromSeconds(2));

                    // UnregisterSessionHandler should wait up to the provided timeout to finish the message handling tasks
                    await testSessionHandler.UnregisterSessionHandler(TimeSpan.FromSeconds(10));
                    Assert.True(testSessionHandler.ReceivedMessageCount == maxConcurrentCalls);

                    // Reregister won't have any problems
                    testSessionHandler.RegisterSessionHandlerAndRecordReceivedMessageCount(subscriptionClient.ReceiveMode == ReceiveMode.PeekLock, 0);
                    await testSessionHandler.WaitForAllMessagesReceived(ExpectedMessageCount);
                    Assert.True(testSessionHandler.ReceivedMessageCount == ExpectedMessageCount);

                    testSessionHandler.ClearData();
                }
                finally
                {
                    await subscriptionClient.CloseAsync();
                    await topicClient.CloseAsync();
                }
            });

            // test UnregisterSessionHandler can close down in time when message handling takes longer than wait timeout user defined.
            await ServiceBusScope.UsingTopicAsync(partitioned, sessionEnabled, async (topicName, subscriptionName) =>
            {
                TestUtility.Log($"Topic: {topicName}, MaxConcurrentCalls: {maxConcurrentCalls}, Receive Mode: {mode.ToString()}, AutoComplete: {autoComplete}");
                var topicClient        = new TopicClient(TestUtility.NamespaceConnectionString, topicName);
                var subscriptionClient = new SubscriptionClient(
                    TestUtility.NamespaceConnectionString,
                    topicClient.TopicName,
                    subscriptionName,
                    ReceiveMode.PeekLock);

                try
                {
                    var sessionHandlerOptions =
                        new SessionHandlerOptions(ExceptionReceivedHandler)
                    {
                        MaxConcurrentSessions = maxConcurrentCalls,
                        MessageWaitTimeout    = TimeSpan.FromSeconds(5),
                        AutoComplete          = true
                    };

                    var testSessionHandler = new TestSessionHandler(
                        subscriptionClient.ReceiveMode,
                        sessionHandlerOptions,
                        topicClient.InnerSender,
                        subscriptionClient.SessionPumpHost);

                    // Send messages to Session
                    await testSessionHandler.SendSessionMessages();

                    // Register handler
                    testSessionHandler.RegisterSessionHandlerAndRecordReceivedMessageCount(subscriptionClient.ReceiveMode == ReceiveMode.PeekLock, 8);

                    // UnregisterSessionHandler should wait up to the provided timeout to finish the message handling tasks
                    await testSessionHandler.UnregisterSessionHandler(TimeSpan.FromSeconds(2));
                    Assert.True(testSessionHandler.ReceivedMessageCount == 0);

                    // Reregister won't have any problems
                    testSessionHandler.RegisterSessionHandlerAndRecordReceivedMessageCount(subscriptionClient.ReceiveMode == ReceiveMode.PeekLock, 0);
                    await testSessionHandler.WaitForAllMessagesReceived(ExpectedMessageCount);
                    Assert.True(testSessionHandler.ReceivedMessageCount == ExpectedMessageCount);

                    testSessionHandler.ClearData();
                }
                finally
                {
                    await subscriptionClient.CloseAsync();
                    await topicClient.CloseAsync();
                }
            });
        }
        private async Task OnSessionTestAsync(bool partitioned, bool sessionEnabled, int maxConcurrentCalls, ReceiveMode mode, bool autoComplete)
        {
            await ServiceBusScope.UsingTopicAsync(partitioned, sessionEnabled, async (topicName, subscriptionName) =>
            {
                TestUtility.Log($"Topic: {topicName}, MaxConcurrentCalls: {maxConcurrentCalls}, Receive Mode: {mode.ToString()}, AutoComplete: {autoComplete}");
                var topicClient        = new TopicClient(TestUtility.NamespaceConnectionString, topicName);
                var subscriptionClient = new SubscriptionClient(
                    TestUtility.NamespaceConnectionString,
                    topicClient.TopicName,
                    subscriptionName,
                    ReceiveMode.PeekLock);

                try
                {
                    var sessionHandlerOptions =
                        new SessionHandlerOptions(ExceptionReceivedHandler)
                    {
                        MaxConcurrentSessions = maxConcurrentCalls,
                        MessageWaitTimeout    = TimeSpan.FromSeconds(5),
                        AutoComplete          = true
                    };

                    var testSessionHandler = new TestSessionHandler(
                        subscriptionClient.ReceiveMode,
                        sessionHandlerOptions,
                        topicClient.InnerSender,
                        subscriptionClient.SessionPumpHost);

                    // Send messages to Session
                    await testSessionHandler.SendSessionMessages();

                    // Register handler
                    testSessionHandler.RegisterSessionHandler(sessionHandlerOptions);

                    // Verify messages were received.
                    await testSessionHandler.VerifyRun();

                    testSessionHandler.ClearData();
                }
                finally
                {
                    await subscriptionClient.CloseAsync();
                    await topicClient.CloseAsync();
                }
            });

            // test UnregisterSessionHandler can wait for message handling upto the timeout user defined.
            await ServiceBusScope.UsingTopicAsync(partitioned, sessionEnabled, async (topicName, subscriptionName) =>
            {
                TestUtility.Log($"Topic: {topicName}, MaxConcurrentCalls: {maxConcurrentCalls}, Receive Mode: {mode.ToString()}, AutoComplete: {autoComplete}");
                var topicClient        = new TopicClient(TestUtility.NamespaceConnectionString, topicName);
                var subscriptionClient = new SubscriptionClient(
                    TestUtility.NamespaceConnectionString,
                    topicClient.TopicName,
                    subscriptionName,
                    ReceiveMode.PeekLock);

                try
                {
                    var sessionHandlerOptions =
                        new SessionHandlerOptions(ExceptionReceivedHandler)
                    {
                        MaxConcurrentSessions = maxConcurrentCalls,
                        MessageWaitTimeout    = TimeSpan.FromSeconds(5),
                        AutoComplete          = true
                    };

                    var testSessionHandler = new TestSessionHandler(
                        subscriptionClient.ReceiveMode,
                        sessionHandlerOptions,
                        topicClient.InnerSender,
                        subscriptionClient.SessionPumpHost);

                    // Send messages to Session
                    await testSessionHandler.SendSessionMessages();

                    // Register handler
                    var count = 0;
                    testSessionHandler.RegisterSessionHandler(
                        async(session, message, token) =>
                    {
                        await Task.Delay(TimeSpan.FromSeconds(8));
                        TestUtility.Log($"Received Session: {session.SessionId} message: SequenceNumber: {message.SystemProperties.SequenceNumber}");

                        if (subscriptionClient.ReceiveMode == ReceiveMode.PeekLock && !sessionHandlerOptions.AutoComplete)
                        {
                            await session.CompleteAsync(message.SystemProperties.LockToken);
                        }
                        Interlocked.Increment(ref count);
                    },
                        sessionHandlerOptions);

                    await Task.Delay(TimeSpan.FromSeconds(2));
                    // UnregisterSessionHandler should wait up to the provided timeout to finish the message handling tasks
                    await testSessionHandler.UnregisterSessionHandler(TimeSpan.FromSeconds(10));
                    Assert.True(count == maxConcurrentCalls);

                    testSessionHandler.ClearData();
                }
                finally
                {
                    await subscriptionClient.CloseAsync();
                    await topicClient.CloseAsync();
                }
            });

            // test UnregisterSessionHandler can close down in time when message handling takes longer than wait timeout user defined.
            await ServiceBusScope.UsingTopicAsync(partitioned, sessionEnabled, async (topicName, subscriptionName) =>
            {
                TestUtility.Log($"Topic: {topicName}, MaxConcurrentCalls: {maxConcurrentCalls}, Receive Mode: {mode.ToString()}, AutoComplete: {autoComplete}");
                var topicClient        = new TopicClient(TestUtility.NamespaceConnectionString, topicName);
                var subscriptionClient = new SubscriptionClient(
                    TestUtility.NamespaceConnectionString,
                    topicClient.TopicName,
                    subscriptionName,
                    ReceiveMode.PeekLock);

                try
                {
                    var sessionHandlerOptions =
                        new SessionHandlerOptions(ExceptionReceivedHandler)
                    {
                        MaxConcurrentSessions = maxConcurrentCalls,
                        MessageWaitTimeout    = TimeSpan.FromSeconds(5),
                        AutoComplete          = true
                    };

                    var testSessionHandler = new TestSessionHandler(
                        subscriptionClient.ReceiveMode,
                        sessionHandlerOptions,
                        topicClient.InnerSender,
                        subscriptionClient.SessionPumpHost);

                    // Send messages to Session
                    await testSessionHandler.SendSessionMessages();

                    // Register handler
                    var count = 0;
                    testSessionHandler.RegisterSessionHandler(
                        async(session, message, token) =>
                    {
                        await Task.Delay(TimeSpan.FromSeconds(8));
                        TestUtility.Log($"Received Session: {session.SessionId} message: SequenceNumber: {message.SystemProperties.SequenceNumber}");

                        if (subscriptionClient.ReceiveMode == ReceiveMode.PeekLock && !sessionHandlerOptions.AutoComplete)
                        {
                            await session.CompleteAsync(message.SystemProperties.LockToken);
                        }
                        Interlocked.Increment(ref count);
                    },
                        sessionHandlerOptions);

                    await Task.Delay(TimeSpan.FromSeconds(2));
                    // UnregisterSessionHandler should wait up to the provided timeout to finish the message handling tasks
                    await testSessionHandler.UnregisterSessionHandler(TimeSpan.FromSeconds(2));
                    Assert.True(count == 0);

                    testSessionHandler.ClearData();
                }
                finally
                {
                    await subscriptionClient.CloseAsync();
                    await topicClient.CloseAsync();
                }
            });
        }