mirror of
https://github.com/dotnet/MQTTnet.git
synced 2026-10-29 01:32:37 +08:00
v4.0.0 (#1357)
This commit is contained in:
@@ -0,0 +1,27 @@
|
||||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using MQTTnet.Formatter;
|
||||
using MQTTnet.Tests.Mockups;
|
||||
|
||||
namespace MQTTnet.Tests
|
||||
{
|
||||
public abstract class BaseTestClass
|
||||
{
|
||||
public TestContext TestContext { get; set; }
|
||||
|
||||
protected TestEnvironment CreateTestEnvironment(MqttProtocolVersion protocolVersion = MqttProtocolVersion.V311)
|
||||
{
|
||||
return new TestEnvironment(TestContext, protocolVersion);
|
||||
}
|
||||
|
||||
protected Task LongTestDelay()
|
||||
{
|
||||
return Task.Delay(TimeSpan.FromSeconds(1));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using MQTTnet.Client;
|
||||
using MQTTnet.Exceptions;
|
||||
using MQTTnet.LowLevelClient;
|
||||
using MQTTnet.Packets;
|
||||
using MQTTnet.Protocol;
|
||||
|
||||
namespace MQTTnet.Tests.Client
|
||||
{
|
||||
[TestClass]
|
||||
public sealed class LowLevelMqttClient_Tests : BaseTestClass
|
||||
{
|
||||
[TestMethod]
|
||||
public async Task Authenticate()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
await testEnvironment.StartServer();
|
||||
|
||||
var factory = new MqttFactory();
|
||||
var lowLevelClient = factory.CreateLowLevelMqttClient();
|
||||
|
||||
await lowLevelClient.ConnectAsync(new MqttClientOptionsBuilder().WithTcpServer("127.0.0.1", testEnvironment.ServerPort).Build(), CancellationToken.None);
|
||||
|
||||
var receivedPacket = await Authenticate(lowLevelClient).ConfigureAwait(false);
|
||||
|
||||
await lowLevelClient.DisconnectAsync(CancellationToken.None).ConfigureAwait(false);
|
||||
|
||||
Assert.IsNotNull(receivedPacket);
|
||||
Assert.AreEqual(MqttConnectReturnCode.ConnectionAccepted, receivedPacket.ReturnCode);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Connect_And_Disconnect()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
await testEnvironment.StartServer();
|
||||
|
||||
var lowLevelClient = testEnvironment.Factory.CreateLowLevelMqttClient();
|
||||
|
||||
await lowLevelClient.ConnectAsync(new MqttClientOptionsBuilder().WithTcpServer("127.0.0.1", testEnvironment.ServerPort).Build(), CancellationToken.None);
|
||||
|
||||
await lowLevelClient.DisconnectAsync(CancellationToken.None);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(MqttCommunicationException))]
|
||||
public async Task Connect_To_Not_Existing_Broker()
|
||||
{
|
||||
var client = new MqttFactory().CreateLowLevelMqttClient();
|
||||
var options = new MqttClientOptionsBuilder().WithTcpServer("localhost").Build();
|
||||
|
||||
await client.ConnectAsync(options, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(MqttCommunicationException))]
|
||||
public async Task Connect_To_Wrong_Host()
|
||||
{
|
||||
var client = new MqttFactory().CreateLowLevelMqttClient();
|
||||
var options = new MqttClientOptionsBuilder().WithTcpServer("123.456.789.10").Build();
|
||||
|
||||
await client.ConnectAsync(options, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Loose_Connection()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
testEnvironment.ServerPort = 8364;
|
||||
var server = await testEnvironment.StartServer();
|
||||
|
||||
var client = await testEnvironment.ConnectLowLevelClient(o => o.WithTimeout(TimeSpan.Zero));
|
||||
|
||||
await Authenticate(client).ConfigureAwait(false);
|
||||
|
||||
await server.StopAsync();
|
||||
|
||||
await Task.Delay(2000);
|
||||
|
||||
try
|
||||
{
|
||||
await client.SendAsync(MqttPingReqPacket.Instance, CancellationToken.None).ConfigureAwait(false);
|
||||
await Task.Delay(2000);
|
||||
await client.SendAsync(MqttPingReqPacket.Instance, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
catch (MqttCommunicationException exception)
|
||||
{
|
||||
Assert.IsTrue(exception.InnerException is SocketException);
|
||||
return;
|
||||
}
|
||||
catch
|
||||
{
|
||||
Assert.Fail("Wrong exception type thrown.");
|
||||
}
|
||||
|
||||
Assert.Fail("This MUST fail");
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Maintain_IsConnected_Property()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
var server = await testEnvironment.StartServer();
|
||||
|
||||
using (var lowLevelClient = testEnvironment.CreateLowLevelClient())
|
||||
{
|
||||
Assert.IsFalse(lowLevelClient.IsConnected);
|
||||
|
||||
var clientOptions = new MqttClientOptionsBuilder().WithTcpServer("127.0.0.1", testEnvironment.ServerPort).WithTimeout(TimeSpan.FromSeconds(1)).Build();
|
||||
|
||||
await lowLevelClient.ConnectAsync(clientOptions, CancellationToken.None);
|
||||
|
||||
Assert.IsTrue(lowLevelClient.IsConnected);
|
||||
|
||||
await server.StopAsync();
|
||||
server.Dispose();
|
||||
|
||||
await LongTestDelay();
|
||||
|
||||
Assert.IsTrue(lowLevelClient.IsConnected);
|
||||
|
||||
try
|
||||
{
|
||||
using (var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5)))
|
||||
{
|
||||
await lowLevelClient.SendAsync(MqttPingReqPacket.Instance, CancellationToken.None);
|
||||
await LongTestDelay();
|
||||
|
||||
await lowLevelClient.ReceiveAsync(timeout.Token);
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
|
||||
Assert.IsFalse(lowLevelClient.IsConnected);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Subscribe()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
await testEnvironment.StartServer();
|
||||
|
||||
var factory = new MqttFactory();
|
||||
var lowLevelClient = factory.CreateLowLevelMqttClient();
|
||||
|
||||
await lowLevelClient.ConnectAsync(new MqttClientOptionsBuilder().WithTcpServer("127.0.0.1", testEnvironment.ServerPort).Build(), CancellationToken.None);
|
||||
|
||||
await Authenticate(lowLevelClient).ConfigureAwait(false);
|
||||
|
||||
var receivedPacket = await Subscribe(lowLevelClient, "a").ConfigureAwait(false);
|
||||
|
||||
await lowLevelClient.DisconnectAsync(CancellationToken.None).ConfigureAwait(false);
|
||||
|
||||
Assert.IsNotNull(receivedPacket);
|
||||
Assert.AreEqual(MqttSubscribeReasonCode.GrantedQoS0, receivedPacket.ReasonCodes[0]);
|
||||
}
|
||||
}
|
||||
|
||||
async Task<MqttConnAckPacket> Authenticate(LowLevelMqttClient client)
|
||||
{
|
||||
await client.SendAsync(
|
||||
new MqttConnectPacket
|
||||
{
|
||||
CleanSession = true,
|
||||
ClientId = TestContext.TestName,
|
||||
Username = "user",
|
||||
Password = Encoding.UTF8.GetBytes("pass")
|
||||
},
|
||||
CancellationToken.None)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
return await client.ReceiveAsync(CancellationToken.None).ConfigureAwait(false) as MqttConnAckPacket;
|
||||
}
|
||||
|
||||
async Task<MqttSubAckPacket> Subscribe(LowLevelMqttClient client, string topic)
|
||||
{
|
||||
await client.SendAsync(
|
||||
new MqttSubscribePacket
|
||||
{
|
||||
PacketIdentifier = 1,
|
||||
TopicFilters =
|
||||
{
|
||||
new MqttTopicFilter
|
||||
{
|
||||
Topic = topic
|
||||
}
|
||||
}
|
||||
},
|
||||
CancellationToken.None)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
return await client.ReceiveAsync(CancellationToken.None).ConfigureAwait(false) as MqttSubAckPacket;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,492 @@
|
||||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using MQTTnet.Client;
|
||||
using MQTTnet.Diagnostics;
|
||||
using MQTTnet.Extensions.ManagedClient;
|
||||
using MQTTnet.Implementations;
|
||||
using MQTTnet.Internal;
|
||||
using MQTTnet.Protocol;
|
||||
using MQTTnet.Server;
|
||||
using MQTTnet.Tests.Mockups;
|
||||
using MqttClient = MQTTnet.Client.MqttClient;
|
||||
|
||||
namespace MQTTnet.Tests.Client
|
||||
{
|
||||
[TestClass]
|
||||
public sealed class ManagedMqttClient_Tests : BaseTestClass
|
||||
{
|
||||
[TestMethod]
|
||||
public async Task Connect_To_Invalid_Server()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
testEnvironment.IgnoreClientLogErrors = true;
|
||||
|
||||
var mqttClient = testEnvironment.CreateClient();
|
||||
|
||||
var managedClient = testEnvironment.Factory.CreateManagedMqttClient(mqttClient);
|
||||
|
||||
ConnectingFailedEventArgs connectingFailedEventArgs = null;
|
||||
|
||||
managedClient.ConnectingFailedAsync += args =>
|
||||
{
|
||||
connectingFailedEventArgs = args;
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
await managedClient.StartAsync(
|
||||
new ManagedMqttClientOptions
|
||||
{
|
||||
ClientOptions = testEnvironment.Factory.CreateClientOptionsBuilder().WithTimeout(TimeSpan.FromSeconds(2)).WithTcpServer("wrong_server", 1234).Build()
|
||||
});
|
||||
|
||||
await managedClient.EnqueueAsync("test_topic_2");
|
||||
|
||||
SpinWait.SpinUntil(() => connectingFailedEventArgs != null, 10000);
|
||||
|
||||
// The wrong server must be reported in general.
|
||||
Assert.IsNotNull(connectingFailedEventArgs);
|
||||
Assert.IsNotNull(connectingFailedEventArgs.Exception);
|
||||
Assert.IsNull(connectingFailedEventArgs.ConnectResult);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Drop_New_Messages_On_Full_Queue()
|
||||
{
|
||||
var factory = new MqttFactory();
|
||||
var managedClient = factory.CreateManagedMqttClient();
|
||||
try
|
||||
{
|
||||
var clientOptions = new ManagedMqttClientOptionsBuilder().WithMaxPendingMessages(5)
|
||||
.WithPendingMessagesOverflowStrategy(MqttPendingMessagesOverflowStrategy.DropNewMessage);
|
||||
|
||||
clientOptions.WithClientOptions(o => o.WithTcpServer("localhost"));
|
||||
|
||||
await managedClient.StartAsync(clientOptions.Build());
|
||||
|
||||
await managedClient.EnqueueAsync("1");
|
||||
await managedClient.EnqueueAsync("2");
|
||||
await managedClient.EnqueueAsync("3");
|
||||
await managedClient.EnqueueAsync("4");
|
||||
await managedClient.EnqueueAsync("5");
|
||||
await managedClient.EnqueueAsync("6");
|
||||
await managedClient.EnqueueAsync("7");
|
||||
await managedClient.EnqueueAsync("8");
|
||||
|
||||
Assert.AreEqual(5, managedClient.PendingApplicationMessagesCount);
|
||||
}
|
||||
finally
|
||||
{
|
||||
await managedClient.StopAsync();
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ManagedClients_Will_Message_Send()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
await testEnvironment.StartServer();
|
||||
|
||||
var receivedMessagesCount = 0;
|
||||
|
||||
var clientOptions = new MqttClientOptionsBuilder().WithTcpServer("127.0.0.1", testEnvironment.ServerPort)
|
||||
.WithWillTopic("My/last/will")
|
||||
.WithWillQualityOfServiceLevel(MqttQualityOfServiceLevel.AtMostOnce)
|
||||
.Build();
|
||||
|
||||
var dyingClient = testEnvironment.CreateClient();
|
||||
var dyingManagedClient = new ManagedMqttClient(dyingClient, testEnvironment.ClientLogger);
|
||||
|
||||
await dyingManagedClient.StartAsync(new ManagedMqttClientOptionsBuilder().WithClientOptions(clientOptions).Build());
|
||||
|
||||
// Wait until the managed client is fully set up and running.
|
||||
await Task.Delay(1000);
|
||||
|
||||
var receivingClient = await testEnvironment.ConnectClient();
|
||||
|
||||
receivingClient.ApplicationMessageReceivedAsync += e =>
|
||||
{
|
||||
Interlocked.Increment(ref receivedMessagesCount);
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
await receivingClient.SubscribeAsync("My/last/will");
|
||||
|
||||
// Disposing the client will not sent a DISCONNECT packet so that connection is terminated
|
||||
// which will lead to the will publish.
|
||||
dyingManagedClient.Dispose();
|
||||
|
||||
// Wait for arrival of the will message at the receiver.
|
||||
await Task.Delay(5000);
|
||||
|
||||
Assert.AreEqual(1, receivedMessagesCount);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Start_Stop()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
var server = await testEnvironment.StartServer();
|
||||
|
||||
var managedClient = new ManagedMqttClient(testEnvironment.CreateClient(), new MqttNetEventLogger());
|
||||
var clientOptions = new MqttClientOptionsBuilder().WithTcpServer("localhost", testEnvironment.ServerPort);
|
||||
|
||||
var connected = GetConnectedTask(managedClient);
|
||||
|
||||
await managedClient.StartAsync(new ManagedMqttClientOptionsBuilder().WithClientOptions(clientOptions).Build());
|
||||
|
||||
await connected;
|
||||
|
||||
await managedClient.StopAsync();
|
||||
|
||||
await Task.Delay(500);
|
||||
|
||||
Assert.AreEqual(0, (await server.GetClientsAsync()).Count);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Storage_Queue_Drains()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
testEnvironment.IgnoreClientLogErrors = true;
|
||||
testEnvironment.IgnoreServerLogErrors = true;
|
||||
|
||||
await testEnvironment.StartServer();
|
||||
|
||||
var managedClient = new ManagedMqttClient(testEnvironment.CreateClient(), new MqttNetEventLogger());
|
||||
var clientOptions = new MqttClientOptionsBuilder().WithTcpServer("localhost", testEnvironment.ServerPort);
|
||||
var storage = new ManagedMqttClientTestStorage();
|
||||
|
||||
var connected = GetConnectedTask(managedClient);
|
||||
|
||||
await managedClient.StartAsync(
|
||||
new ManagedMqttClientOptionsBuilder().WithClientOptions(clientOptions).WithStorage(storage).WithAutoReconnectDelay(TimeSpan.FromSeconds(5)).Build());
|
||||
|
||||
await connected;
|
||||
|
||||
await testEnvironment.Server.StopAsync();
|
||||
|
||||
await managedClient.EnqueueAsync("1");
|
||||
|
||||
//Message should have been added to the storage queue in PublishAsync,
|
||||
//and we are awaiting PublishAsync, so the message should already be
|
||||
//in storage at this point (i.e. no waiting).
|
||||
Assert.AreEqual(1, storage.GetMessageCount());
|
||||
|
||||
connected = GetConnectedTask(managedClient);
|
||||
|
||||
await testEnvironment.Server.StartAsync();
|
||||
|
||||
await connected;
|
||||
|
||||
//Wait 500ms here so the client has time to publish the queued message
|
||||
await Task.Delay(500);
|
||||
|
||||
Assert.AreEqual(0, storage.GetMessageCount());
|
||||
|
||||
await managedClient.StopAsync();
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Subscriptions_And_Unsubscriptions_Are_Made_And_Reestablished_At_Reconnect()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
var unmanagedClient = testEnvironment.CreateClient();
|
||||
var managedClient = await CreateManagedClientAsync(testEnvironment, unmanagedClient);
|
||||
|
||||
var received = SetupReceivingOfMessages(managedClient, 2);
|
||||
|
||||
// Perform some opposing subscriptions and unsubscriptions to verify
|
||||
// that these conflicting subscriptions are handled correctly
|
||||
await managedClient.SubscribeAsync("keptSubscribed");
|
||||
await managedClient.SubscribeAsync("subscribedThenUnsubscribed");
|
||||
|
||||
await managedClient.UnsubscribeAsync("subscribedThenUnsubscribed");
|
||||
await managedClient.UnsubscribeAsync("unsubscribedThenSubscribed");
|
||||
|
||||
await managedClient.SubscribeAsync("unsubscribedThenSubscribed");
|
||||
|
||||
//wait a bit for the subscriptions to become established before the messages are published
|
||||
await Task.Delay(500);
|
||||
|
||||
var sendingClient = await testEnvironment.ConnectClient();
|
||||
|
||||
async Task PublishMessages()
|
||||
{
|
||||
await sendingClient.PublishBinaryAsync("keptSubscribed", new byte[] { 1 });
|
||||
await sendingClient.PublishBinaryAsync("subscribedThenUnsubscribed", new byte[] { 1 });
|
||||
await sendingClient.PublishBinaryAsync("unsubscribedThenSubscribed", new byte[] { 1 });
|
||||
}
|
||||
|
||||
await PublishMessages();
|
||||
|
||||
async Task AssertMessagesReceived()
|
||||
{
|
||||
var messages = await received;
|
||||
Assert.AreEqual("keptSubscribed", messages[0].Topic);
|
||||
Assert.AreEqual("unsubscribedThenSubscribed", messages[1].Topic);
|
||||
}
|
||||
|
||||
await AssertMessagesReceived();
|
||||
|
||||
var connected = GetConnectedTask(managedClient);
|
||||
|
||||
await unmanagedClient.DisconnectAsync();
|
||||
|
||||
// the managed client has to reconnect by itself
|
||||
await connected;
|
||||
|
||||
// wait a bit so that the managed client can reestablish the subscriptions
|
||||
await Task.Delay(500);
|
||||
|
||||
received = SetupReceivingOfMessages(managedClient, 2);
|
||||
|
||||
await PublishMessages();
|
||||
|
||||
// and then the same subscriptions need to exist again
|
||||
await AssertMessagesReceived();
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Subscriptions_Are_Cleared_At_Logout()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
await testEnvironment.StartServer().ConfigureAwait(false);
|
||||
|
||||
var sendingClient = await testEnvironment.ConnectClient().ConfigureAwait(false);
|
||||
await sendingClient.PublishAsync(
|
||||
new MqttApplicationMessage
|
||||
{
|
||||
Topic = "topic",
|
||||
Payload = new byte[] { 1 },
|
||||
Retain = true
|
||||
});
|
||||
|
||||
// Wait a bit for the retained message to be available
|
||||
await Task.Delay(1000);
|
||||
|
||||
await sendingClient.DisconnectAsync();
|
||||
|
||||
// Now use the managed client and check if subscriptions get cleared properly.
|
||||
|
||||
var clientOptions = new MqttClientOptionsBuilder().WithTcpServer("127.0.0.1", testEnvironment.ServerPort);
|
||||
|
||||
var receivedManagedMessages = new List<MqttApplicationMessage>();
|
||||
var managedClient = new ManagedMqttClient(testEnvironment.CreateClient(), new MqttNetEventLogger());
|
||||
managedClient.ApplicationMessageReceivedAsync += e =>
|
||||
{
|
||||
receivedManagedMessages.Add(e.ApplicationMessage);
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
await managedClient.SubscribeAsync("topic");
|
||||
|
||||
await managedClient.StartAsync(new ManagedMqttClientOptionsBuilder().WithClientOptions(clientOptions).WithAutoReconnectDelay(TimeSpan.FromSeconds(1)).Build());
|
||||
|
||||
await Task.Delay(1000);
|
||||
|
||||
Assert.AreEqual(1, receivedManagedMessages.Count);
|
||||
|
||||
await managedClient.StopAsync();
|
||||
|
||||
await Task.Delay(500);
|
||||
|
||||
await managedClient.StartAsync(new ManagedMqttClientOptionsBuilder().WithClientOptions(clientOptions).WithAutoReconnectDelay(TimeSpan.FromSeconds(1)).Build());
|
||||
|
||||
await Task.Delay(1000);
|
||||
|
||||
// After reconnect and then some delay, the retained message must not be received,
|
||||
// showing that the subscriptions were cleared
|
||||
Assert.AreEqual(1, receivedManagedMessages.Count);
|
||||
|
||||
// Make sure that it gets received after subscribing again.
|
||||
await managedClient.SubscribeAsync("topic");
|
||||
await Task.Delay(500);
|
||||
Assert.AreEqual(2, receivedManagedMessages.Count);
|
||||
}
|
||||
}
|
||||
|
||||
// This case also serves as a regression test for the previous behavior
|
||||
// that subscriptions were only published at the ConnectionCheckInterval
|
||||
[TestMethod]
|
||||
public async Task Subscriptions_Are_Published_Immediately()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
// Use a long connection check interval to verify that the subscriptions
|
||||
// do not depend on the connection check interval anymore
|
||||
var connectionCheckInterval = TimeSpan.FromSeconds(10);
|
||||
var receivingClient = await CreateManagedClientAsync(testEnvironment, null, connectionCheckInterval);
|
||||
var sendingClient = await testEnvironment.ConnectClient();
|
||||
|
||||
await sendingClient.PublishAsync(new MqttApplicationMessage { Topic = "topic", Payload = new byte[] { 1 }, Retain = true });
|
||||
|
||||
var subscribeTime = DateTime.UtcNow;
|
||||
|
||||
var messagesTask = SetupReceivingOfMessages(receivingClient, 1);
|
||||
|
||||
await receivingClient.SubscribeAsync("topic");
|
||||
|
||||
var messages = await messagesTask;
|
||||
|
||||
var elapsed = DateTime.UtcNow - subscribeTime;
|
||||
Assert.IsTrue(elapsed < TimeSpan.FromSeconds(1), $"Subscriptions must be activated immediately, this one took {elapsed}");
|
||||
Assert.AreEqual(messages.Single().Topic, "topic");
|
||||
}
|
||||
}
|
||||
|
||||
// This case also serves as a regression test for the previous behavior which re-published
|
||||
// each and every existing subscriptions with every new subscription that was made
|
||||
// (causing performance problems and having the visible symptom of retained messages being received again)
|
||||
[TestMethod]
|
||||
public async Task Subscriptions_Subscribe_Only_New_Subscriptions()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
var managedClient = await CreateManagedClientAsync(testEnvironment);
|
||||
|
||||
var sendingClient = await testEnvironment.ConnectClient();
|
||||
|
||||
await managedClient.SubscribeAsync("topic");
|
||||
|
||||
//wait a bit for the subscription to become established
|
||||
await Task.Delay(500);
|
||||
|
||||
await sendingClient.PublishAsync(new MqttApplicationMessage { Topic = "topic", Payload = new byte[] { 1 }, Retain = true });
|
||||
|
||||
var messages = await SetupReceivingOfMessages(managedClient, 1);
|
||||
|
||||
Assert.AreEqual(1, messages.Count);
|
||||
Assert.AreEqual("topic", messages.Single().Topic);
|
||||
|
||||
await managedClient.SubscribeAsync("anotherTopic");
|
||||
|
||||
await Task.Delay(500);
|
||||
|
||||
// The subscription of the other topic must not trigger a re-subscription of the existing topic
|
||||
// (and thus renewed receiving of the retained message)
|
||||
Assert.AreEqual(1, messages.Count);
|
||||
}
|
||||
}
|
||||
|
||||
async Task<ManagedMqttClient> CreateManagedClientAsync(
|
||||
TestEnvironment testEnvironment,
|
||||
MqttClient underlyingClient = null,
|
||||
TimeSpan? connectionCheckInterval = null,
|
||||
string host = "localhost")
|
||||
{
|
||||
await testEnvironment.StartServer();
|
||||
|
||||
var clientOptions = new MqttClientOptionsBuilder().WithTcpServer(host, testEnvironment.ServerPort);
|
||||
|
||||
var managedOptions = new ManagedMqttClientOptionsBuilder().WithClientOptions(clientOptions).Build();
|
||||
|
||||
// Use a short connection check interval so that subscription operations are performed quickly
|
||||
// in order to verify against a previous implementation that performed subscriptions only
|
||||
// at connection check intervals
|
||||
managedOptions.ConnectionCheckInterval = connectionCheckInterval ?? TimeSpan.FromSeconds(0.1);
|
||||
|
||||
var managedClient = new ManagedMqttClient(underlyingClient ?? testEnvironment.CreateClient(), new MqttNetEventLogger());
|
||||
|
||||
var connected = GetConnectedTask(managedClient);
|
||||
|
||||
await managedClient.StartAsync(managedOptions);
|
||||
|
||||
await connected;
|
||||
|
||||
return managedClient;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns a task that will finish when the
|
||||
/// <paramref
|
||||
/// name="managedClient" />
|
||||
/// has connected
|
||||
/// </summary>
|
||||
Task GetConnectedTask(ManagedMqttClient managedClient)
|
||||
{
|
||||
var connected = new TaskCompletionSource<bool>();
|
||||
|
||||
managedClient.ConnectedAsync += e =>
|
||||
{
|
||||
connected.TrySetResult(true);
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
return connected.Task;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns a task that will return the messages received on
|
||||
/// <paramref
|
||||
/// name="managedClient" />
|
||||
/// when
|
||||
/// <paramref
|
||||
/// name="expectedNumberOfMessages" />
|
||||
/// have been received
|
||||
/// </summary>
|
||||
Task<List<MqttApplicationMessage>> SetupReceivingOfMessages(ManagedMqttClient managedClient, int expectedNumberOfMessages)
|
||||
{
|
||||
var receivedMessages = new List<MqttApplicationMessage>();
|
||||
var result = new AsyncTaskCompletionSource<List<MqttApplicationMessage>>();
|
||||
|
||||
managedClient.ApplicationMessageReceivedAsync += e =>
|
||||
{
|
||||
receivedMessages.Add(e.ApplicationMessage);
|
||||
|
||||
if (receivedMessages.Count == expectedNumberOfMessages)
|
||||
{
|
||||
result.TrySetResult(receivedMessages);
|
||||
}
|
||||
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
return result.Task;
|
||||
}
|
||||
}
|
||||
|
||||
public class ManagedMqttClientTestStorage : IManagedMqttClientStorage
|
||||
{
|
||||
IList<ManagedMqttApplicationMessage> _messages;
|
||||
|
||||
public int GetMessageCount()
|
||||
{
|
||||
return _messages.Count;
|
||||
}
|
||||
|
||||
public Task<IList<ManagedMqttApplicationMessage>> LoadQueuedMessagesAsync()
|
||||
{
|
||||
if (_messages == null)
|
||||
{
|
||||
_messages = new List<ManagedMqttApplicationMessage>();
|
||||
}
|
||||
|
||||
return Task.FromResult(_messages);
|
||||
}
|
||||
|
||||
public Task SaveQueuedMessagesAsync(IList<ManagedMqttApplicationMessage> messages)
|
||||
{
|
||||
_messages = messages;
|
||||
return Task.FromResult(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using MQTTnet.Client;
|
||||
using MQTTnet.Extensions;
|
||||
|
||||
namespace MQTTnet.Tests.Client
|
||||
{
|
||||
[TestClass]
|
||||
public class MqttClientOptionsBuilder_Tests
|
||||
{
|
||||
[TestMethod]
|
||||
public void WithConnectionUri_Credential_Test()
|
||||
{
|
||||
var options = new MqttClientOptionsBuilder()
|
||||
.WithConnectionUri("mqtt://user:password@127.0.0.1")
|
||||
.Build();
|
||||
|
||||
Assert.AreEqual("user", options.Credentials.GetUserName(null));
|
||||
Assert.IsTrue(Encoding.UTF8.GetBytes("password").SequenceEqual(options.Credentials.GetPassword(null)));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,949 @@
|
||||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using MQTTnet.Client;
|
||||
using MQTTnet.Exceptions;
|
||||
using MQTTnet.Formatter;
|
||||
using MQTTnet.Implementations;
|
||||
using MQTTnet.Packets;
|
||||
using MQTTnet.Protocol;
|
||||
using MQTTnet.Tests.Mockups;
|
||||
|
||||
namespace MQTTnet.Tests.Client
|
||||
{
|
||||
[TestClass]
|
||||
public sealed class Client_Tests : BaseTestClass
|
||||
{
|
||||
[DataTestMethod]
|
||||
[DataRow(MqttQualityOfServiceLevel.ExactlyOnce)]
|
||||
[DataRow(MqttQualityOfServiceLevel.AtMostOnce)]
|
||||
[DataRow(MqttQualityOfServiceLevel.AtLeastOnce)]
|
||||
public async Task Concurrent_Processing(MqttQualityOfServiceLevel qos)
|
||||
{
|
||||
long concurrency = 0;
|
||||
var success = false;
|
||||
|
||||
using (var testEnvironment = new TestEnvironment(TestContext))
|
||||
{
|
||||
await testEnvironment.StartServer();
|
||||
var publisher = await testEnvironment.ConnectClient();
|
||||
var subscriber = await testEnvironment.ConnectClient(new MqttClientOptionsBuilder().WithClientId(qos.ToString()));
|
||||
await subscriber.SubscribeAsync("#", qos);
|
||||
|
||||
subscriber.ApplicationMessageReceivedAsync += e =>
|
||||
{
|
||||
e.AutoAcknowledge = false;
|
||||
|
||||
async Task InvokeInternal()
|
||||
{
|
||||
if (Interlocked.Increment(ref concurrency) > 1)
|
||||
{
|
||||
success = true;
|
||||
}
|
||||
|
||||
await Task.Delay(100);
|
||||
Interlocked.Decrement(ref concurrency);
|
||||
}
|
||||
|
||||
_ = InvokeInternal();
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
var publishes = Task.WhenAll(publisher.PublishStringAsync("a", null, qos), publisher.PublishStringAsync("b", null, qos));
|
||||
|
||||
await Task.Delay(200);
|
||||
|
||||
await publishes;
|
||||
Assert.IsTrue(success);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(MqttCommunicationException))]
|
||||
public async Task Connect_To_Invalid_Server_Port_Not_Opened()
|
||||
{
|
||||
var client = new MqttFactory().CreateMqttClient();
|
||||
await client.ConnectAsync(new MqttClientOptionsBuilder().WithTcpServer("127.0.0.1", 12345).WithTimeout(TimeSpan.FromSeconds(5)).Build());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(OperationCanceledException))]
|
||||
public async Task Connect_To_Invalid_Server_Wrong_IP()
|
||||
{
|
||||
var client = new MqttFactory().CreateMqttClient();
|
||||
using (var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(2)))
|
||||
{
|
||||
await client.ConnectAsync(new MqttClientOptionsBuilder().WithTcpServer("1.2.3.4").Build(), timeout.Token);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(MqttCommunicationException))]
|
||||
public async Task Connect_To_Invalid_Server_Wrong_Protocol()
|
||||
{
|
||||
var client = new MqttFactory().CreateMqttClient();
|
||||
await client.ConnectAsync(new MqttClientOptionsBuilder().WithTcpServer("http://127.0.0.1", 12345).WithTimeout(TimeSpan.FromSeconds(2)).Build());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ConnectTimeout_Throws_Exception()
|
||||
{
|
||||
var factory = new MqttFactory();
|
||||
using (var client = factory.CreateMqttClient())
|
||||
{
|
||||
var disconnectHandlerCalled = false;
|
||||
try
|
||||
{
|
||||
client.DisconnectedAsync += args =>
|
||||
{
|
||||
disconnectHandlerCalled = true;
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
await client.ConnectAsync(new MqttClientOptionsBuilder().WithTcpServer("1.2.3.4").Build());
|
||||
|
||||
Assert.Fail("Must fail!");
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
Assert.IsNotNull(exception);
|
||||
Assert.IsInstanceOfType(exception, typeof(MqttCommunicationException));
|
||||
//Assert.IsInstanceOfType(exception.InnerException, typeof(SocketException));
|
||||
}
|
||||
|
||||
await Task.Delay(100); // disconnected handler is called async
|
||||
Assert.IsTrue(disconnectHandlerCalled);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Disconnect_Event_Contains_Exception()
|
||||
{
|
||||
var factory = new MqttFactory();
|
||||
using (var client = factory.CreateMqttClient())
|
||||
{
|
||||
Exception ex = null;
|
||||
client.DisconnectedAsync += e =>
|
||||
{
|
||||
ex = e.Exception;
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
try
|
||||
{
|
||||
await client.ConnectAsync(new MqttClientOptionsBuilder().WithTcpServer("wrong-server").Build());
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
|
||||
await Task.Delay(500);
|
||||
|
||||
Assert.IsNotNull(ex);
|
||||
Assert.IsInstanceOfType(ex, typeof(MqttCommunicationException));
|
||||
Assert.IsInstanceOfType(ex.InnerException, typeof(SocketException));
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Ensure_Queue_Drain()
|
||||
{
|
||||
using (var testEnvironment = new TestEnvironment(TestContext))
|
||||
{
|
||||
var server = await testEnvironment.StartServer();
|
||||
var client = await testEnvironment.ConnectLowLevelClient();
|
||||
|
||||
var i = 0;
|
||||
server.InterceptingPublishAsync += c =>
|
||||
{
|
||||
i++;
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
await client.SendAsync(
|
||||
new MqttConnectPacket
|
||||
{
|
||||
ClientId = "Ensure_Queue_Drain_Test"
|
||||
},
|
||||
CancellationToken.None);
|
||||
|
||||
await client.SendAsync(
|
||||
new MqttPublishPacket
|
||||
{
|
||||
Topic = "Test"
|
||||
},
|
||||
CancellationToken.None);
|
||||
|
||||
await Task.Delay(500);
|
||||
|
||||
// This will simulate a device which closes the connection directly
|
||||
// after sending the data so do delay is added between send and dispose!
|
||||
client.Dispose();
|
||||
|
||||
await Task.Delay(1000);
|
||||
|
||||
Assert.AreEqual(1, i);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Fire_Disconnected_Event_On_Server_Shutdown()
|
||||
{
|
||||
using (var testEnvironment = new TestEnvironment(TestContext))
|
||||
{
|
||||
var server = await testEnvironment.StartServer();
|
||||
var client = await testEnvironment.ConnectClient();
|
||||
|
||||
var handlerFired = false;
|
||||
client.DisconnectedAsync += e =>
|
||||
{
|
||||
handlerFired = true;
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
await server.StopAsync();
|
||||
|
||||
await Task.Delay(4000);
|
||||
|
||||
Assert.IsTrue(handlerFired);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Frequent_Connects()
|
||||
{
|
||||
using (var testEnvironment = new TestEnvironment(TestContext))
|
||||
{
|
||||
await testEnvironment.StartServer();
|
||||
|
||||
var clients = new List<MqttClient>();
|
||||
for (var i = 0; i < 100; i++)
|
||||
{
|
||||
clients.Add(await testEnvironment.ConnectClient(new MqttClientOptionsBuilder().WithClientId("a")));
|
||||
}
|
||||
|
||||
await Task.Delay(500);
|
||||
|
||||
var clientStatus = await testEnvironment.Server.GetClientsAsync();
|
||||
var sessionStatus = await testEnvironment.Server.GetSessionsAsync();
|
||||
|
||||
for (var i = 0; i < 98; i++)
|
||||
{
|
||||
Assert.IsFalse(clients[i].IsConnected, $"clients[{i}] is not connected");
|
||||
}
|
||||
|
||||
Assert.IsTrue(clients[99].IsConnected);
|
||||
|
||||
Assert.AreEqual(1, clientStatus.Count);
|
||||
Assert.AreEqual(1, sessionStatus.Count);
|
||||
|
||||
var receiveClient = clients[99];
|
||||
object receivedPayload = null;
|
||||
receiveClient.ApplicationMessageReceivedAsync += e =>
|
||||
{
|
||||
receivedPayload = e.ApplicationMessage.ConvertPayloadToString();
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
await receiveClient.SubscribeAsync("x");
|
||||
|
||||
var sendClient = await testEnvironment.ConnectClient();
|
||||
await sendClient.PublishStringAsync("x", "1");
|
||||
|
||||
await Task.Delay(250);
|
||||
|
||||
Assert.AreEqual("1", receivedPayload);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Invalid_Connect_Throws_Exception()
|
||||
{
|
||||
var factory = new MqttFactory();
|
||||
using (var client = factory.CreateMqttClient())
|
||||
{
|
||||
try
|
||||
{
|
||||
await client.ConnectAsync(new MqttClientOptionsBuilder().WithTcpServer("wrong-server").Build());
|
||||
|
||||
Assert.Fail("Must fail!");
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
Assert.IsNotNull(exception);
|
||||
Assert.IsInstanceOfType(exception, typeof(MqttCommunicationException));
|
||||
Assert.IsInstanceOfType(exception.InnerException, typeof(SocketException));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task No_Payload()
|
||||
{
|
||||
using (var testEnvironment = new TestEnvironment(TestContext))
|
||||
{
|
||||
await testEnvironment.StartServer();
|
||||
|
||||
var sender = await testEnvironment.ConnectClient();
|
||||
var receiver = await testEnvironment.ConnectClient();
|
||||
|
||||
var message = new MqttApplicationMessageBuilder().WithTopic("A");
|
||||
|
||||
await receiver.SubscribeAsync(
|
||||
new MqttClientSubscribeOptions
|
||||
{
|
||||
TopicFilters = new List<MqttTopicFilter> { new MqttTopicFilter { Topic = "#" } }
|
||||
},
|
||||
CancellationToken.None);
|
||||
|
||||
MqttApplicationMessage receivedMessage = null;
|
||||
receiver.ApplicationMessageReceivedAsync += e =>
|
||||
{
|
||||
receivedMessage = e.ApplicationMessage;
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
await sender.PublishAsync(message.Build(), CancellationToken.None);
|
||||
|
||||
await Task.Delay(1000);
|
||||
|
||||
Assert.IsNotNull(receivedMessage);
|
||||
Assert.AreEqual("A", receivedMessage.Topic);
|
||||
Assert.AreEqual(null, receivedMessage.Payload);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task NoConnectedHandler_Connect_DoesNotThrowException()
|
||||
{
|
||||
using (var testEnvironment = new TestEnvironment(TestContext))
|
||||
{
|
||||
await testEnvironment.StartServer();
|
||||
|
||||
var client = await testEnvironment.ConnectClient();
|
||||
|
||||
Assert.IsTrue(client.IsConnected);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task NoDisconnectedHandler_Disconnect_DoesNotThrowException()
|
||||
{
|
||||
using (var testEnvironment = new TestEnvironment(TestContext))
|
||||
{
|
||||
await testEnvironment.StartServer();
|
||||
var client = await testEnvironment.ConnectClient();
|
||||
Assert.IsTrue(client.IsConnected);
|
||||
|
||||
await client.DisconnectAsync();
|
||||
|
||||
Assert.IsFalse(client.IsConnected);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task PacketIdentifier_In_Publish_Result()
|
||||
{
|
||||
using (var testEnvironment = new TestEnvironment(TestContext))
|
||||
{
|
||||
await testEnvironment.StartServer();
|
||||
var client = await testEnvironment.ConnectClient();
|
||||
|
||||
var result = await client.PublishStringAsync("a", "a");
|
||||
Assert.AreEqual(null, result.PacketIdentifier);
|
||||
|
||||
result = await client.PublishStringAsync("b", "b");
|
||||
Assert.AreEqual(null, result.PacketIdentifier);
|
||||
|
||||
result = await client.PublishStringAsync("a", "a", MqttQualityOfServiceLevel.AtLeastOnce);
|
||||
Assert.AreEqual((ushort)1, result.PacketIdentifier);
|
||||
|
||||
result = await client.PublishStringAsync("b", "b", MqttQualityOfServiceLevel.AtLeastOnce);
|
||||
Assert.AreEqual((ushort)2, result.PacketIdentifier);
|
||||
|
||||
result = await client.PublishStringAsync("a", "a", MqttQualityOfServiceLevel.ExactlyOnce);
|
||||
Assert.AreEqual((ushort)3, result.PacketIdentifier);
|
||||
|
||||
result = await client.PublishStringAsync("b", "b", MqttQualityOfServiceLevel.ExactlyOnce);
|
||||
Assert.AreEqual((ushort)4, result.PacketIdentifier);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Preserve_Message_Order()
|
||||
{
|
||||
// The messages are sent in reverse or to ensure that the delay in the handler
|
||||
// needs longer for the first messages and later messages may be processed earlier (if there
|
||||
// is an issue).
|
||||
const int MessagesCount = 50;
|
||||
|
||||
using (var testEnvironment = new TestEnvironment(TestContext))
|
||||
{
|
||||
await testEnvironment.StartServer();
|
||||
|
||||
var client1 = await testEnvironment.ConnectClient();
|
||||
await client1.SubscribeAsync("x");
|
||||
|
||||
var receivedValues = new List<int>();
|
||||
|
||||
async Task Handler1(MqttApplicationMessageReceivedEventArgs eventArgs)
|
||||
{
|
||||
var value = int.Parse(eventArgs.ApplicationMessage.ConvertPayloadToString());
|
||||
await Task.Delay(value);
|
||||
|
||||
lock (receivedValues)
|
||||
{
|
||||
receivedValues.Add(value);
|
||||
}
|
||||
}
|
||||
|
||||
client1.ApplicationMessageReceivedAsync += Handler1;
|
||||
|
||||
var client2 = await testEnvironment.ConnectClient();
|
||||
for (var i = MessagesCount; i > 0; i--)
|
||||
{
|
||||
await client2.PublishStringAsync("x", i.ToString());
|
||||
}
|
||||
|
||||
await Task.Delay(5000);
|
||||
|
||||
for (var i = MessagesCount; i > 0; i--)
|
||||
{
|
||||
Assert.AreEqual(i, receivedValues[MessagesCount - i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Preserve_Message_Order_With_Delayed_Acknowledgement()
|
||||
{
|
||||
// The messages are sent in reverse or to ensure that the delay in the handler
|
||||
// needs longer for the first messages and later messages may be processed earlier (if there
|
||||
// is an issue).
|
||||
const int MessagesCount = 50;
|
||||
|
||||
using (var testEnvironment = new TestEnvironment(TestContext))
|
||||
{
|
||||
await testEnvironment.StartServer();
|
||||
|
||||
var client1 = await testEnvironment.ConnectClient();
|
||||
await client1.SubscribeAsync("x", MqttQualityOfServiceLevel.ExactlyOnce);
|
||||
|
||||
var receivedValues = new List<int>();
|
||||
|
||||
Task Handler1(MqttApplicationMessageReceivedEventArgs eventArgs)
|
||||
{
|
||||
var value = int.Parse(eventArgs.ApplicationMessage.ConvertPayloadToString());
|
||||
eventArgs.AutoAcknowledge = false;
|
||||
Task.Delay(value).ContinueWith(x => eventArgs.AcknowledgeAsync(CancellationToken.None));
|
||||
|
||||
Debug.WriteLine($"received {value}");
|
||||
lock (receivedValues)
|
||||
{
|
||||
receivedValues.Add(value);
|
||||
}
|
||||
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
}
|
||||
|
||||
client1.ApplicationMessageReceivedAsync += Handler1;
|
||||
|
||||
var client2 = await testEnvironment.ConnectClient();
|
||||
for (var i = MessagesCount; i > 0; i--)
|
||||
{
|
||||
await client2.PublishStringAsync("x", i.ToString(), MqttQualityOfServiceLevel.ExactlyOnce);
|
||||
}
|
||||
|
||||
await Task.Delay(5000);
|
||||
|
||||
for (var i = MessagesCount; i > 0; i--)
|
||||
{
|
||||
Assert.AreEqual(i, receivedValues[MessagesCount - i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Publish_QoS_0_Over_Period_Exceeding_KeepAlive()
|
||||
{
|
||||
using (var testEnvironment = new TestEnvironment(TestContext))
|
||||
{
|
||||
const int KeepAlivePeriodSecs = 3;
|
||||
|
||||
await testEnvironment.StartServer();
|
||||
|
||||
var options = new MqttClientOptionsBuilder().WithKeepAlivePeriod(TimeSpan.FromSeconds(KeepAlivePeriodSecs));
|
||||
var client = await testEnvironment.ConnectClient(options);
|
||||
var message = new MqttApplicationMessageBuilder().WithTopic("a").Build();
|
||||
|
||||
try
|
||||
{
|
||||
// Publish messages over a time period exceeding the keep alive period.
|
||||
// This should not cause an exception because of, i.e. "Client disconnected".
|
||||
|
||||
for (var count = 0; count < KeepAlivePeriodSecs * 3; ++count)
|
||||
{
|
||||
// Send Publish requests well before the keep alive period expires
|
||||
await client.PublishAsync(message);
|
||||
await Task.Delay(1000);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Assert.Fail(ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Publish_QoS_1_In_ApplicationMessageReceiveHandler()
|
||||
{
|
||||
using (var testEnvironment = new TestEnvironment(TestContext))
|
||||
{
|
||||
await testEnvironment.StartServer();
|
||||
|
||||
const string client1Topic = "client1/topic";
|
||||
const string client2Topic = "client2/topic";
|
||||
const string expectedClient2Message = "hello client2";
|
||||
|
||||
var client1 = await testEnvironment.ConnectClient();
|
||||
client1.ApplicationMessageReceivedAsync += async e =>
|
||||
{
|
||||
await client1.PublishStringAsync(client2Topic, expectedClient2Message, MqttQualityOfServiceLevel.AtLeastOnce);
|
||||
};
|
||||
|
||||
await client1.SubscribeAsync(client1Topic, MqttQualityOfServiceLevel.AtLeastOnce);
|
||||
|
||||
var client2 = await testEnvironment.ConnectClient();
|
||||
|
||||
var client2TopicResults = new List<string>();
|
||||
|
||||
client2.ApplicationMessageReceivedAsync += e =>
|
||||
{
|
||||
client2TopicResults.Add(Encoding.UTF8.GetString(e.ApplicationMessage.Payload));
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
await client2.SubscribeAsync(client2Topic);
|
||||
|
||||
var client3 = await testEnvironment.ConnectClient();
|
||||
var message = new MqttApplicationMessageBuilder().WithTopic(client1Topic).Build();
|
||||
await client3.PublishAsync(message);
|
||||
await client3.PublishAsync(message);
|
||||
|
||||
await Task.Delay(500);
|
||||
|
||||
Assert.AreEqual(2, client2TopicResults.Count);
|
||||
Assert.AreEqual(expectedClient2Message, client2TopicResults[0]);
|
||||
Assert.AreEqual(expectedClient2Message, client2TopicResults[1]);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Publish_With_Correct_Retain_Flag()
|
||||
{
|
||||
using (var testEnvironment = new TestEnvironment(TestContext))
|
||||
{
|
||||
await testEnvironment.StartServer();
|
||||
|
||||
var receivedMessages = new List<MqttApplicationMessage>();
|
||||
|
||||
var client1 = await testEnvironment.ConnectClient();
|
||||
client1.ApplicationMessageReceivedAsync += e =>
|
||||
{
|
||||
lock (receivedMessages)
|
||||
{
|
||||
receivedMessages.Add(e.ApplicationMessage);
|
||||
}
|
||||
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
await client1.SubscribeAsync("a");
|
||||
|
||||
var client2 = await testEnvironment.ConnectClient();
|
||||
var message = new MqttApplicationMessageBuilder().WithTopic("a").WithRetainFlag().Build();
|
||||
await client2.PublishAsync(message);
|
||||
|
||||
await Task.Delay(500);
|
||||
|
||||
Assert.AreEqual(1, receivedMessages.Count);
|
||||
Assert.IsFalse(receivedMessages.First().Retain); // Must be false even if set above!
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Reconnect()
|
||||
{
|
||||
using (var testEnvironment = new TestEnvironment(TestContext))
|
||||
{
|
||||
var server = await testEnvironment.StartServer();
|
||||
var client = await testEnvironment.ConnectClient();
|
||||
|
||||
await Task.Delay(500);
|
||||
Assert.IsTrue(client.IsConnected);
|
||||
|
||||
await server.StopAsync();
|
||||
await Task.Delay(500);
|
||||
Assert.IsFalse(client.IsConnected);
|
||||
|
||||
await server.StartAsync();
|
||||
await Task.Delay(500);
|
||||
|
||||
await client.ConnectAsync(new MqttClientOptionsBuilder().WithTcpServer("127.0.0.1", testEnvironment.ServerPort).Build());
|
||||
Assert.IsTrue(client.IsConnected);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Reconnect_From_Disconnected_Event()
|
||||
{
|
||||
using (var testEnvironment = new TestEnvironment(TestContext))
|
||||
{
|
||||
testEnvironment.IgnoreClientLogErrors = true;
|
||||
|
||||
var client = testEnvironment.CreateClient();
|
||||
|
||||
var tries = 0;
|
||||
var maxTries = 3;
|
||||
|
||||
client.DisconnectedAsync += async e =>
|
||||
{
|
||||
if (tries >= maxTries)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
Interlocked.Increment(ref tries);
|
||||
|
||||
await Task.Delay(100);
|
||||
await client.ConnectAsync(new MqttClientOptionsBuilder().WithTcpServer("127.0.0.1", testEnvironment.ServerPort).Build());
|
||||
};
|
||||
|
||||
try
|
||||
{
|
||||
await client.ConnectAsync(new MqttClientOptionsBuilder().WithTcpServer("127.0.0.1", testEnvironment.ServerPort).Build());
|
||||
Assert.Fail("Must fail!");
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
|
||||
SpinWait.SpinUntil(() => tries >= maxTries, 10000);
|
||||
|
||||
Assert.AreEqual(maxTries, tries);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Reconnect_While_Server_Offline()
|
||||
{
|
||||
using (var testEnvironment = new TestEnvironment(TestContext))
|
||||
{
|
||||
testEnvironment.IgnoreClientLogErrors = true;
|
||||
|
||||
var server = await testEnvironment.StartServer();
|
||||
var client = await testEnvironment.ConnectClient();
|
||||
|
||||
await Task.Delay(500);
|
||||
Assert.IsTrue(client.IsConnected);
|
||||
|
||||
await server.StopAsync();
|
||||
await Task.Delay(500);
|
||||
Assert.IsFalse(client.IsConnected);
|
||||
|
||||
for (var i = 0; i < 5; i++)
|
||||
{
|
||||
try
|
||||
{
|
||||
await client.ConnectAsync(new MqttClientOptionsBuilder().WithTcpServer("127.0.0.1", testEnvironment.ServerPort).Build());
|
||||
Assert.Fail("Must fail!");
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
await server.StartAsync();
|
||||
await Task.Delay(500);
|
||||
|
||||
await client.ConnectAsync(new MqttClientOptionsBuilder().WithTcpServer("127.0.0.1", testEnvironment.ServerPort).Build());
|
||||
Assert.IsTrue(client.IsConnected);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Send_Manual_Ping()
|
||||
{
|
||||
using (var testEnvironment = new TestEnvironment(TestContext))
|
||||
{
|
||||
await testEnvironment.StartServer();
|
||||
var client = await testEnvironment.ConnectClient();
|
||||
|
||||
await client.PingAsync(CancellationToken.None);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Send_Reply_For_Any_Received_Message()
|
||||
{
|
||||
using (var testEnvironment = new TestEnvironment(TestContext))
|
||||
{
|
||||
await testEnvironment.StartServer();
|
||||
|
||||
var client1 = await testEnvironment.ConnectClient();
|
||||
await client1.SubscribeAsync("request/+");
|
||||
|
||||
async Task Handler1(MqttApplicationMessageReceivedEventArgs eventArgs)
|
||||
{
|
||||
await client1.PublishStringAsync($"reply/{eventArgs.ApplicationMessage.Topic}");
|
||||
}
|
||||
|
||||
client1.ApplicationMessageReceivedAsync += Handler1;
|
||||
|
||||
var client2 = await testEnvironment.ConnectClient();
|
||||
await client2.SubscribeAsync("reply/#");
|
||||
|
||||
var replies = new List<string>();
|
||||
|
||||
Task Handler2(MqttApplicationMessageReceivedEventArgs eventArgs)
|
||||
{
|
||||
lock (replies)
|
||||
{
|
||||
replies.Add(eventArgs.ApplicationMessage.Topic);
|
||||
}
|
||||
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
}
|
||||
|
||||
client2.ApplicationMessageReceivedAsync += Handler2;
|
||||
|
||||
await Task.Delay(500);
|
||||
|
||||
await client2.PublishStringAsync("request/a");
|
||||
await client2.PublishStringAsync("request/b");
|
||||
await client2.PublishStringAsync("request/c");
|
||||
|
||||
await Task.Delay(500);
|
||||
|
||||
Assert.AreEqual("reply/request/a,reply/request/b,reply/request/c", string.Join(",", replies));
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Send_Reply_In_Message_Handler()
|
||||
{
|
||||
using (var testEnvironment = new TestEnvironment())
|
||||
{
|
||||
await testEnvironment.StartServer();
|
||||
var client1 = await testEnvironment.ConnectClient();
|
||||
var client2 = await testEnvironment.ConnectClient();
|
||||
|
||||
await client1.SubscribeAsync("#");
|
||||
await client2.SubscribeAsync("#");
|
||||
|
||||
var replyReceived = false;
|
||||
|
||||
client1.ApplicationMessageReceivedAsync += e =>
|
||||
{
|
||||
if (e.ApplicationMessage.Topic == "reply")
|
||||
{
|
||||
replyReceived = true;
|
||||
}
|
||||
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
client2.ApplicationMessageReceivedAsync += async e =>
|
||||
{
|
||||
if (e.ApplicationMessage.Topic == "request")
|
||||
{
|
||||
// Use AtMostOnce here because with QoS 1 or even QoS 2 the process waits for
|
||||
// the ACK etc. The problem is that the SpinUntil below only waits until the
|
||||
// flag is set. It does not wait until the client has sent the ACK
|
||||
await client2.PublishStringAsync("reply");
|
||||
}
|
||||
};
|
||||
|
||||
await client1.PublishStringAsync("request", null, MqttQualityOfServiceLevel.AtLeastOnce);
|
||||
|
||||
await Task.Delay(500);
|
||||
|
||||
SpinWait.SpinUntil(() => replyReceived, TimeSpan.FromSeconds(10));
|
||||
|
||||
await Task.Delay(500);
|
||||
|
||||
Assert.IsTrue(replyReceived);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Send_Reply_In_Message_Handler_For_Same_Client()
|
||||
{
|
||||
using (var testEnvironment = new TestEnvironment(TestContext))
|
||||
{
|
||||
await testEnvironment.StartServer();
|
||||
var client = await testEnvironment.ConnectClient();
|
||||
|
||||
await client.SubscribeAsync("#");
|
||||
|
||||
var replyReceived = false;
|
||||
|
||||
client.ApplicationMessageReceivedAsync += e =>
|
||||
{
|
||||
if (e.ApplicationMessage.Topic == "request")
|
||||
{
|
||||
#pragma warning disable 4014
|
||||
Task.Run(() => client.PublishStringAsync("reply", null, MqttQualityOfServiceLevel.AtLeastOnce));
|
||||
#pragma warning restore 4014
|
||||
}
|
||||
else
|
||||
{
|
||||
replyReceived = true;
|
||||
}
|
||||
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
await client.PublishStringAsync("request", null, MqttQualityOfServiceLevel.AtLeastOnce);
|
||||
|
||||
SpinWait.SpinUntil(() => replyReceived, TimeSpan.FromSeconds(10));
|
||||
|
||||
Assert.IsTrue(replyReceived);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Set_ClientWasConnected_On_ClientDisconnect()
|
||||
{
|
||||
using (var testEnvironment = new TestEnvironment(TestContext))
|
||||
{
|
||||
var server = await testEnvironment.StartServer();
|
||||
var client = await testEnvironment.ConnectClient();
|
||||
|
||||
Assert.IsTrue(client.IsConnected);
|
||||
client.DisconnectedAsync += e =>
|
||||
{
|
||||
Assert.IsTrue(e.ClientWasConnected);
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
await client.DisconnectAsync();
|
||||
await Task.Delay(200);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Set_ClientWasConnected_On_ServerDisconnect()
|
||||
{
|
||||
using (var testEnvironment = new TestEnvironment(TestContext))
|
||||
{
|
||||
var server = await testEnvironment.StartServer();
|
||||
var client = await testEnvironment.ConnectClient();
|
||||
|
||||
Assert.IsTrue(client.IsConnected);
|
||||
client.DisconnectedAsync += e =>
|
||||
{
|
||||
Assert.IsTrue(e.ClientWasConnected);
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
await server.StopAsync();
|
||||
await Task.Delay(4000);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
[TestMethod]
|
||||
public async Task Subscribe_In_Callback_Events()
|
||||
{
|
||||
using (var testEnvironment = new TestEnvironment(TestContext))
|
||||
{
|
||||
await testEnvironment.StartServer();
|
||||
|
||||
var receivedMessages = new List<MqttApplicationMessage>();
|
||||
|
||||
var client = testEnvironment.CreateClient();
|
||||
|
||||
client.ConnectedAsync += async e =>
|
||||
{
|
||||
await client.SubscribeAsync("RCU/P1/H0001/R0003");
|
||||
|
||||
var msg = new MqttApplicationMessageBuilder().WithPayload("DA|18RS00SC00XI0000RV00R100R200R300R400L100L200L300L400Y100Y200AC0102031800BELK0000BM0000|")
|
||||
.WithTopic("RCU/P1/H0001/R0003");
|
||||
|
||||
await client.PublishAsync(msg.Build());
|
||||
};
|
||||
|
||||
client.ApplicationMessageReceivedAsync += e =>
|
||||
{
|
||||
lock (receivedMessages)
|
||||
{
|
||||
receivedMessages.Add(e.ApplicationMessage);
|
||||
}
|
||||
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
await client.ConnectAsync(new MqttClientOptionsBuilder().WithTcpServer("localhost", testEnvironment.ServerPort).Build());
|
||||
|
||||
await Task.Delay(500);
|
||||
|
||||
Assert.AreEqual(1, receivedMessages.Count);
|
||||
Assert.AreEqual("DA|18RS00SC00XI0000RV00R100R200R300R400L100L200L300L400Y100Y200AC0102031800BELK0000BM0000|", receivedMessages.First().ConvertPayloadToString());
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Subscribe_With_QoS2()
|
||||
{
|
||||
using (var testEnvironment = new TestEnvironment())
|
||||
{
|
||||
await testEnvironment.StartServer();
|
||||
var client1 = await testEnvironment.ConnectClient(o => o.WithProtocolVersion(MqttProtocolVersion.V500));
|
||||
var client2 = await testEnvironment.ConnectClient(o => o.WithProtocolVersion(MqttProtocolVersion.V500));
|
||||
|
||||
var disconnectedFired = false;
|
||||
client1.DisconnectedAsync += c =>
|
||||
{
|
||||
disconnectedFired = true;
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
var messageReceived = false;
|
||||
client1.ApplicationMessageReceivedAsync += e =>
|
||||
{
|
||||
messageReceived = true;
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
await client1.SubscribeAsync(new MqttTopicFilterBuilder().WithTopic("topic1").WithExactlyOnceQoS().Build());
|
||||
|
||||
await Task.Delay(500);
|
||||
|
||||
var message = new MqttApplicationMessageBuilder().WithTopic("topic1")
|
||||
.WithPayload("Hello World")
|
||||
.WithQualityOfServiceLevel(MqttQualityOfServiceLevel.ExactlyOnce)
|
||||
.WithRetainFlag()
|
||||
.Build();
|
||||
|
||||
await client2.PublishAsync(message);
|
||||
await Task.Delay(500);
|
||||
|
||||
Assert.IsTrue(messageReceived);
|
||||
Assert.IsTrue(client1.IsConnected);
|
||||
Assert.IsFalse(disconnectedFired);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using MQTTnet.Diagnostics;
|
||||
|
||||
namespace MQTTnet.Tests.Diagnostics
|
||||
{
|
||||
[TestClass]
|
||||
public sealed class Logger_Tests : BaseTestClass
|
||||
{
|
||||
[TestMethod]
|
||||
public void Log_Without_Source()
|
||||
{
|
||||
var logger = new MqttNetEventLogger();
|
||||
|
||||
MqttNetLogMessage logMessage = null;
|
||||
logger.LogMessagePublished += (s, e) => { logMessage = e.LogMessage; };
|
||||
|
||||
logger.Publish(MqttNetLogLevel.Info, "SOURCE", "MESSAGE", new object[] { "ABC" }, new InvalidOperationException());
|
||||
|
||||
Assert.AreEqual(MqttNetLogLevel.Info, logMessage.Level);
|
||||
Assert.AreEqual("SOURCE", logMessage.Source);
|
||||
Assert.AreEqual("MESSAGE", logMessage.Message);
|
||||
Assert.AreEqual("InvalidOperationException", logMessage.Exception.GetType().Name);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Root_Log_Messages()
|
||||
{
|
||||
var logger = new MqttNetEventLogger();
|
||||
var childLogger = logger.WithSource("Source1");
|
||||
|
||||
var logMessagesCount = 0;
|
||||
|
||||
logger.LogMessagePublished += (s, e) => { logMessagesCount++; };
|
||||
|
||||
childLogger.Verbose("Verbose");
|
||||
childLogger.Info("Info");
|
||||
childLogger.Warning((Exception)null, "Warning");
|
||||
childLogger.Error(null, "Error");
|
||||
|
||||
Assert.AreEqual(4, logMessagesCount);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Use_Custom_Log_Id()
|
||||
{
|
||||
var logger = new MqttNetEventLogger("logId");
|
||||
var childLogger = logger.WithSource("Source1");
|
||||
|
||||
logger.LogMessagePublished += (s, e) =>
|
||||
{
|
||||
Assert.AreEqual("logId", e.LogMessage.LogId);
|
||||
Assert.AreEqual("Source1", e.LogMessage.Source);
|
||||
};
|
||||
|
||||
childLogger.Verbose("Verbose");
|
||||
childLogger.Info("Info");
|
||||
childLogger.Warning((Exception)null, "Warning");
|
||||
childLogger.Error(null, "Error");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using MQTTnet.Implementations;
|
||||
|
||||
namespace MQTTnet.Tests.Diagnostics
|
||||
{
|
||||
[TestClass]
|
||||
public sealed class PacketInspection_Tests : BaseTestClass
|
||||
{
|
||||
[TestMethod]
|
||||
public async Task Inspect_Client_Packets()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
await testEnvironment.StartServer();
|
||||
|
||||
using (var mqttClient = testEnvironment.CreateClient())
|
||||
{
|
||||
var mqttClientOptions = testEnvironment.Factory.CreateClientOptionsBuilder()
|
||||
.WithClientId("CLIENT_ID") // Must be fixed.
|
||||
.WithTcpServer("127.0.0.1", testEnvironment.ServerPort)
|
||||
.Build();
|
||||
|
||||
var packets = new List<string>();
|
||||
|
||||
mqttClient.InspectPackage += eventArgs =>
|
||||
{
|
||||
packets.Add(eventArgs.Direction + ":" + Convert.ToBase64String(eventArgs.Buffer));
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
await mqttClient.ConnectAsync(mqttClientOptions, CancellationToken.None);
|
||||
|
||||
Assert.AreEqual(2, packets.Count);
|
||||
Assert.AreEqual("Outbound:ECwABE1RVFQEAgAPACBJbnNwZWN0X0NsaWVudF9QYWNrZXRzX0NMSUVOVF9JRA==", packets[0]); // CONNECT
|
||||
Assert.AreEqual("Inbound:IAIAAA==", packets[1]); // CONNACK
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using MQTTnet.Diagnostics;
|
||||
|
||||
namespace MQTTnet.Tests.Diagnostics
|
||||
{
|
||||
[TestClass]
|
||||
public sealed class SourceLogger_Tests : BaseTestClass
|
||||
{
|
||||
[TestMethod]
|
||||
public void Log_With_Source()
|
||||
{
|
||||
MqttNetLogMessage logMessage = null;
|
||||
|
||||
var logger = new MqttNetEventLogger();
|
||||
logger.LogMessagePublished += (s, e) =>
|
||||
{
|
||||
logMessage = e.LogMessage;
|
||||
};
|
||||
|
||||
var sourceLogger = logger.WithSource("The_Source");
|
||||
sourceLogger.Info("MESSAGE", (object)null, (object)null);
|
||||
|
||||
Assert.AreEqual("The_Source", logMessage.Source);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using MQTTnet.Exceptions;
|
||||
using MQTTnet.Internal;
|
||||
|
||||
namespace MQTTnet.Tests
|
||||
{
|
||||
[TestClass]
|
||||
public class Extension_Tests
|
||||
{
|
||||
[ExpectedException(typeof(MqttCommunicationTimedOutException))]
|
||||
[TestMethod]
|
||||
public async Task TimeoutAfter()
|
||||
{
|
||||
await MqttTaskTimeout.WaitAsync(ct => Task.Delay(TimeSpan.FromMilliseconds(500), ct),
|
||||
TimeSpan.FromMilliseconds(100), CancellationToken.None);
|
||||
}
|
||||
|
||||
[ExpectedException(typeof(MqttCommunicationTimedOutException))]
|
||||
[TestMethod]
|
||||
public async Task TimeoutAfterWithResult()
|
||||
{
|
||||
await MqttTaskTimeout.WaitAsync(
|
||||
ct => Task.Delay(TimeSpan.FromMilliseconds(500), ct).ContinueWith(t => 5, ct),
|
||||
TimeSpan.FromMilliseconds(100), CancellationToken.None);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TimeoutAfterWithInnerException()
|
||||
{
|
||||
try
|
||||
{
|
||||
await MqttTaskTimeout.WaitAsync(ct => Task.Run(() =>
|
||||
{
|
||||
var iis = new int[0];
|
||||
iis[1] = 0;
|
||||
}, ct), TimeSpan.FromSeconds(1), CancellationToken.None);
|
||||
|
||||
Assert.Fail();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Assert.IsTrue(e is IndexOutOfRangeException);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TimeoutAfterWithInnerExceptionWithResult()
|
||||
{
|
||||
try
|
||||
{
|
||||
await MqttTaskTimeout.WaitAsync(ct => Task.Run(() =>
|
||||
{
|
||||
var iis = new int[0];
|
||||
iis[1] = 0;
|
||||
return iis[0];
|
||||
}, ct), TimeSpan.FromSeconds(1), CancellationToken.None);
|
||||
|
||||
Assert.Fail();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Assert.IsTrue(e is IndexOutOfRangeException);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TimeoutAfterMemoryUsage()
|
||||
{
|
||||
var initialMemory = GC.GetTotalMemory(true);
|
||||
|
||||
var tasks = Enumerable.Range(0, 100000)
|
||||
.Select(i =>
|
||||
{
|
||||
return MqttTaskTimeout.WaitAsync(ct => Task.Delay(TimeSpan.FromMilliseconds(1), ct),
|
||||
TimeSpan.FromMinutes(1), CancellationToken.None);
|
||||
});
|
||||
|
||||
await Task.WhenAll(tasks);
|
||||
AssertIsLess(initialMemory + 2_000_000, GC.GetTotalMemory(true));
|
||||
}
|
||||
|
||||
static void AssertIsLess(long bound, long actual)
|
||||
{
|
||||
if (bound < actual)
|
||||
{
|
||||
Assert.Fail($"value must be less than {bound:N0} but is {actual:N0}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using MQTTnet.Formatter;
|
||||
using MQTTnet.Protocol;
|
||||
|
||||
namespace MQTTnet.Tests.Extensions
|
||||
{
|
||||
public static class MqttPacketWriterExtensions
|
||||
{
|
||||
public static byte[] AddMqttHeader(this MqttBufferWriter writer, MqttControlPacketType header, byte[] body)
|
||||
{
|
||||
writer.WriteByte(MqttBufferWriter.BuildFixedHeader(header));
|
||||
writer.WriteVariableByteInteger((uint)body.Length);
|
||||
writer.WriteBinary(body, 0, body.Length);
|
||||
return writer.GetBuffer();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using MQTTnet.Diagnostics;
|
||||
using MQTTnet.Extensions.ManagedClient;
|
||||
using MQTTnet.Implementations;
|
||||
using MQTTnet.Server;
|
||||
|
||||
namespace MQTTnet.Tests.Factory
|
||||
{
|
||||
[TestClass]
|
||||
public sealed class MqttFactory_Tests : BaseTestClass
|
||||
{
|
||||
[TestMethod]
|
||||
public async Task Create_Managed_Client_With_Logger()
|
||||
{
|
||||
var factory = new MqttFactory();
|
||||
|
||||
// This test compares
|
||||
// 1. correct logID
|
||||
var logId = "logId";
|
||||
var hasInvalidLogId = false;
|
||||
|
||||
// 2. if the total log calls are the same for global and local
|
||||
//var globalLogCount = 0;
|
||||
var localLogCount = 0;
|
||||
|
||||
var logger = new MqttNetEventLogger(logId);
|
||||
logger.LogMessagePublished += (s, e) =>
|
||||
{
|
||||
if (e.LogMessage.LogId != logId)
|
||||
{
|
||||
hasInvalidLogId = true;
|
||||
}
|
||||
|
||||
Interlocked.Increment(ref localLogCount);
|
||||
};
|
||||
|
||||
var managedClient = factory.CreateManagedMqttClient(logger);
|
||||
try
|
||||
{
|
||||
var clientOptions = new ManagedMqttClientOptionsBuilder();
|
||||
|
||||
clientOptions.WithClientOptions(o => o.WithTcpServer("this_is_an_invalid_host").WithTimeout(TimeSpan.FromSeconds(1)));
|
||||
|
||||
// try connect to get some log entries
|
||||
await managedClient.StartAsync(clientOptions.Build());
|
||||
|
||||
// wait at least connect timeout or we have some log messages
|
||||
var tcs = new TaskCompletionSource<object>();
|
||||
managedClient.ConnectingFailedAsync += e =>
|
||||
{
|
||||
tcs.TrySetResult(null);
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
await Task.WhenAny(Task.Delay(managedClient.Options.ClientOptions.Timeout), tcs.Task);
|
||||
}
|
||||
finally
|
||||
{
|
||||
await managedClient.StopAsync();
|
||||
}
|
||||
|
||||
await Task.Delay(500);
|
||||
|
||||
Assert.IsFalse(hasInvalidLogId);
|
||||
Assert.AreNotEqual(0, localLogCount);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Create_ApplicationMessageBuilder()
|
||||
{
|
||||
var factory = new MqttFactory();
|
||||
var builder = factory.CreateApplicationMessageBuilder();
|
||||
|
||||
Assert.IsNotNull(builder);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Create_ClientOptionsBuilder()
|
||||
{
|
||||
var factory = new MqttFactory();
|
||||
var builder = factory.CreateClientOptionsBuilder();
|
||||
|
||||
Assert.IsNotNull(builder);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Create_ServerOptionsBuilder()
|
||||
{
|
||||
var factory = new MqttFactory();
|
||||
var builder = factory.CreateServerOptionsBuilder();
|
||||
|
||||
Assert.IsNotNull(builder);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Create_SubscribeOptionsBuilder()
|
||||
{
|
||||
var factory = new MqttFactory();
|
||||
var builder = factory.CreateSubscribeOptionsBuilder();
|
||||
|
||||
Assert.IsNotNull(builder);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Create_UnsubscribeOptionsBuilder()
|
||||
{
|
||||
var factory = new MqttFactory();
|
||||
var builder = factory.CreateUnsubscribeOptionsBuilder();
|
||||
|
||||
Assert.IsNotNull(builder);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Create_TopicFilterBuilder()
|
||||
{
|
||||
var factory = new MqttFactory();
|
||||
var builder = factory.CreateTopicFilterBuilder();
|
||||
|
||||
Assert.IsNotNull(builder);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Create_MqttServer()
|
||||
{
|
||||
var factory = new MqttFactory();
|
||||
var server = factory.CreateMqttServer(new MqttServerOptionsBuilder().Build());
|
||||
|
||||
Assert.IsNotNull(server);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Create_MqttClient()
|
||||
{
|
||||
var factory = new MqttFactory();
|
||||
var client = factory.CreateMqttClient();
|
||||
|
||||
Assert.IsNotNull(client);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Create_LowLevelMqttClient()
|
||||
{
|
||||
var factory = new MqttFactory();
|
||||
var client = factory.CreateLowLevelMqttClient();
|
||||
|
||||
Assert.IsNotNull(client);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Create_ManagedMqttClient()
|
||||
{
|
||||
var factory = new MqttFactory();
|
||||
var client = factory.CreateManagedMqttClient();
|
||||
|
||||
Assert.IsNotNull(client);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,627 @@
|
||||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using MQTTnet.Adapter;
|
||||
using MQTTnet.Diagnostics;
|
||||
using MQTTnet.Exceptions;
|
||||
using MQTTnet.Formatter;
|
||||
using MQTTnet.Internal;
|
||||
using MQTTnet.Packets;
|
||||
using MQTTnet.Protocol;
|
||||
using MQTTnet.Tests.Extensions;
|
||||
|
||||
namespace MQTTnet.Tests
|
||||
{
|
||||
[TestClass]
|
||||
public sealed class MqttPacketSerialization_V3_Binary_Tests
|
||||
{
|
||||
[TestMethod]
|
||||
public void DeserializeV310_MqttConnAckPacket()
|
||||
{
|
||||
var p = new MqttConnAckPacket
|
||||
{
|
||||
ReturnCode = MqttConnectReturnCode.ConnectionRefusedNotAuthorized
|
||||
};
|
||||
|
||||
DeserializeAndCompare(p, "IAIABQ==", MqttProtocolVersion.V310);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void DeserializeV311_MqttConnAckPacket()
|
||||
{
|
||||
var p = new MqttConnAckPacket
|
||||
{
|
||||
IsSessionPresent = true,
|
||||
ReturnCode = MqttConnectReturnCode.ConnectionRefusedNotAuthorized
|
||||
};
|
||||
|
||||
DeserializeAndCompare(p, "IAIBBQ==");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void DeserializeV311_MqttConnectPacket()
|
||||
{
|
||||
var p = new MqttConnectPacket
|
||||
{
|
||||
ClientId = "XYZ",
|
||||
Password = Encoding.UTF8.GetBytes("PASS"),
|
||||
Username = "USER",
|
||||
KeepAlivePeriod = 123,
|
||||
CleanSession = true
|
||||
};
|
||||
|
||||
DeserializeAndCompare(p, "EBsABE1RVFQEwgB7AANYWVoABFVTRVIABFBBU1M=");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void DeserializeV311_MqttConnectPacketWithWillMessage()
|
||||
{
|
||||
var p = new MqttConnectPacket
|
||||
{
|
||||
ClientId = "XYZ",
|
||||
Password = Encoding.UTF8.GetBytes("PASS"),
|
||||
Username = "USER",
|
||||
KeepAlivePeriod = 123,
|
||||
CleanSession = true,
|
||||
WillFlag = true,
|
||||
WillTopic = "My/last/will",
|
||||
WillMessage = Encoding.UTF8.GetBytes("Good byte."),
|
||||
WillQoS = MqttQualityOfServiceLevel.AtLeastOnce,
|
||||
WillRetain = true
|
||||
};
|
||||
|
||||
DeserializeAndCompare(p, "EDUABE1RVFQE7gB7AANYWVoADE15L2xhc3Qvd2lsbAAKR29vZCBieXRlLgAEVVNFUgAEUEFTUw==");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void DeserializeV311_MqttPubAckPacket()
|
||||
{
|
||||
var p = new MqttPubAckPacket
|
||||
{
|
||||
PacketIdentifier = 123
|
||||
};
|
||||
|
||||
DeserializeAndCompare(p, "QAIAew==");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void DeserializeV311_MqttPubCompPacket()
|
||||
{
|
||||
var p = new MqttPubCompPacket
|
||||
{
|
||||
PacketIdentifier = 123
|
||||
};
|
||||
|
||||
DeserializeAndCompare(p, "cAIAew==");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void DeserializeV311_MqttPublishPacket()
|
||||
{
|
||||
var p = new MqttPublishPacket
|
||||
{
|
||||
PacketIdentifier = 123,
|
||||
Dup = true,
|
||||
Retain = true,
|
||||
Payload = Encoding.ASCII.GetBytes("HELLO"),
|
||||
QualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce,
|
||||
Topic = "A/B/C"
|
||||
};
|
||||
|
||||
DeserializeAndCompare(p, "Ow4ABUEvQi9DAHtIRUxMTw==");
|
||||
}
|
||||
|
||||
|
||||
[TestMethod]
|
||||
public void DeserializeV311_MqttPublishPacket_DupFalse()
|
||||
{
|
||||
var p = new MqttPublishPacket
|
||||
{
|
||||
Dup = false
|
||||
};
|
||||
|
||||
var p2 = Roundtrip(p);
|
||||
|
||||
Assert.AreEqual(p.Dup, p2.Dup);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void DeserializeV311_MqttPublishPacket_Qos1()
|
||||
{
|
||||
var p = new MqttPublishPacket
|
||||
{
|
||||
QualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce
|
||||
};
|
||||
|
||||
var p2 = Roundtrip(p);
|
||||
|
||||
Assert.AreEqual(p.QualityOfServiceLevel, p2.QualityOfServiceLevel);
|
||||
Assert.AreEqual(p.Dup, p2.Dup);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void DeserializeV311_MqttPublishPacket_Qos2()
|
||||
{
|
||||
var p = new MqttPublishPacket
|
||||
{
|
||||
QualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce,
|
||||
PacketIdentifier = 1
|
||||
};
|
||||
|
||||
var p2 = Roundtrip(p);
|
||||
|
||||
Assert.AreEqual(p.QualityOfServiceLevel, p2.QualityOfServiceLevel);
|
||||
Assert.AreEqual(p.Dup, p2.Dup);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void DeserializeV311_MqttPublishPacket_Qos3()
|
||||
{
|
||||
var p = new MqttPublishPacket
|
||||
{
|
||||
QualityOfServiceLevel = MqttQualityOfServiceLevel.ExactlyOnce,
|
||||
PacketIdentifier = 1
|
||||
};
|
||||
|
||||
var p2 = Roundtrip(p);
|
||||
|
||||
Assert.AreEqual(p.QualityOfServiceLevel, p2.QualityOfServiceLevel);
|
||||
Assert.AreEqual(p.Dup, p2.Dup);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void DeserializeV311_MqttPubRecPacket()
|
||||
{
|
||||
var p = new MqttPubRecPacket
|
||||
{
|
||||
PacketIdentifier = 123
|
||||
};
|
||||
|
||||
DeserializeAndCompare(p, "UAIAew==");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void DeserializeV311_MqttPubRelPacket()
|
||||
{
|
||||
var p = new MqttPubRelPacket
|
||||
{
|
||||
PacketIdentifier = 123
|
||||
};
|
||||
|
||||
DeserializeAndCompare(p, "YgIAew==");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void DeserializeV311_MqttSubAckPacket()
|
||||
{
|
||||
var p = new MqttSubAckPacket
|
||||
{
|
||||
PacketIdentifier = 123,
|
||||
ReasonCodes = new List<MqttSubscribeReasonCode>
|
||||
{
|
||||
MqttSubscribeReasonCode.GrantedQoS0,
|
||||
MqttSubscribeReasonCode.GrantedQoS1,
|
||||
MqttSubscribeReasonCode.GrantedQoS2,
|
||||
MqttSubscribeReasonCode.UnspecifiedError
|
||||
}
|
||||
};
|
||||
|
||||
DeserializeAndCompare(p, "kAYAewABAoA=");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void DeserializeV311_MqttSubscribePacket()
|
||||
{
|
||||
var p = new MqttSubscribePacket
|
||||
{
|
||||
PacketIdentifier = 123,
|
||||
TopicFilters = new List<MqttTopicFilter>
|
||||
{
|
||||
new MqttTopicFilter { Topic = "A/B/C", QualityOfServiceLevel = MqttQualityOfServiceLevel.ExactlyOnce },
|
||||
new MqttTopicFilter { Topic = "1/2/3", QualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce },
|
||||
new MqttTopicFilter { Topic = "x/y/z", QualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce }
|
||||
}
|
||||
};
|
||||
|
||||
DeserializeAndCompare(p, "ghoAewAFQS9CL0MCAAUxLzIvMwEABXgveS96AA==");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void DeserializeV311_MqttUnsubAckPacket()
|
||||
{
|
||||
var p = new MqttUnsubAckPacket
|
||||
{
|
||||
PacketIdentifier = 123
|
||||
};
|
||||
|
||||
DeserializeAndCompare(p, "sAIAew==");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void DeserializeV311_MqttUnsubscribePacket()
|
||||
{
|
||||
var p = new MqttUnsubscribePacket
|
||||
{
|
||||
PacketIdentifier = 123
|
||||
};
|
||||
|
||||
p.TopicFilters.Add("A/B/C");
|
||||
p.TopicFilters.Add("1/2/3");
|
||||
p.TopicFilters.Add("x/y/z");
|
||||
|
||||
DeserializeAndCompare(p, "ohcAewAFQS9CL0MABTEvMi8zAAV4L3kveg==");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void DetectVersionFromMqttConnectPacket()
|
||||
{
|
||||
var packet = new MqttConnectPacket
|
||||
{
|
||||
ClientId = "XYZ",
|
||||
Password = Encoding.UTF8.GetBytes("PASS"),
|
||||
Username = "USER",
|
||||
KeepAlivePeriod = 123,
|
||||
CleanSession = true
|
||||
};
|
||||
|
||||
Assert.AreEqual(
|
||||
MqttProtocolVersion.V310,
|
||||
DeserializeAndDetectVersion(new MqttPacketFormatterAdapter(new MqttBufferWriter(4096, 65535)), Serialize(packet, MqttProtocolVersion.V310)));
|
||||
|
||||
Assert.AreEqual(
|
||||
MqttProtocolVersion.V311,
|
||||
DeserializeAndDetectVersion(new MqttPacketFormatterAdapter(new MqttBufferWriter(4096, 65535)), Serialize(packet, MqttProtocolVersion.V311)));
|
||||
|
||||
Assert.AreEqual(
|
||||
MqttProtocolVersion.V500,
|
||||
DeserializeAndDetectVersion(new MqttPacketFormatterAdapter(new MqttBufferWriter(4096, 65535)), Serialize(packet, MqttProtocolVersion.V500)));
|
||||
|
||||
var adapter = new MqttPacketFormatterAdapter(new MqttBufferWriter(4096, 65535));
|
||||
|
||||
var ex = Assert.ThrowsException<MqttProtocolViolationException>(
|
||||
() => DeserializeAndDetectVersion(adapter, WriterFactory().AddMqttHeader(MqttControlPacketType.Connect, new byte[0])));
|
||||
Assert.AreEqual("CONNECT packet must have at least 7 bytes.", ex.Message);
|
||||
ex = Assert.ThrowsException<MqttProtocolViolationException>(
|
||||
() => DeserializeAndDetectVersion(adapter, WriterFactory().AddMqttHeader(MqttControlPacketType.Connect, new byte[7])));
|
||||
Assert.AreEqual("Protocol '' not supported.", ex.Message);
|
||||
ex = Assert.ThrowsException<MqttProtocolViolationException>(
|
||||
() => DeserializeAndDetectVersion(adapter, WriterFactory().AddMqttHeader(MqttControlPacketType.Connect, new byte[] { 255, 255, 0, 0, 0, 0, 0 })));
|
||||
Assert.AreEqual("Expected at least 65537 bytes but there are only 7 bytes", ex.Message);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Serialize_LargePacket()
|
||||
{
|
||||
const int payloadLength = 80000;
|
||||
|
||||
var payload = new byte[payloadLength];
|
||||
|
||||
var value = 0;
|
||||
for (var i = 0; i < payloadLength; i++)
|
||||
{
|
||||
if (value > 255)
|
||||
{
|
||||
value = 0;
|
||||
}
|
||||
|
||||
payload[i] = (byte)value;
|
||||
}
|
||||
|
||||
var publishPacket = new MqttPublishPacket
|
||||
{
|
||||
Topic = "abcdefghijklmnopqrstuvwxyz0123456789",
|
||||
Payload = payload
|
||||
};
|
||||
|
||||
|
||||
var serializationHelper = new MqttPacketSerializationHelper();
|
||||
|
||||
var buffer = serializationHelper.Encode(publishPacket);
|
||||
var publishPacketCopy = serializationHelper.Decode(buffer) as MqttPublishPacket;
|
||||
|
||||
Assert.IsNotNull(publishPacketCopy);
|
||||
Assert.AreEqual(publishPacket.Topic, publishPacketCopy.Topic);
|
||||
CollectionAssert.AreEqual(publishPacket.Payload, publishPacketCopy.Payload);
|
||||
|
||||
// Now modify the payload and test again.
|
||||
publishPacket.Payload = Encoding.UTF8.GetBytes("MQTT");
|
||||
|
||||
buffer = serializationHelper.Encode(publishPacket);
|
||||
var publishPacketCopy2 = serializationHelper.Decode(buffer) as MqttPublishPacket;
|
||||
|
||||
Assert.IsNotNull(publishPacketCopy2);
|
||||
Assert.AreEqual(publishPacket.Topic, publishPacketCopy2.Topic);
|
||||
CollectionAssert.AreEqual(publishPacket.Payload, publishPacketCopy2.Payload);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void SerializeV310_MqttConnAckPacket()
|
||||
{
|
||||
var p = new MqttConnAckPacket
|
||||
{
|
||||
ReturnCode = MqttConnectReturnCode.ConnectionRefusedNotAuthorized
|
||||
};
|
||||
|
||||
SerializeAndCompare(p, "IAIABQ==", MqttProtocolVersion.V310);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void SerializeV310_MqttConnectPacket()
|
||||
{
|
||||
var p = new MqttConnectPacket
|
||||
{
|
||||
ClientId = "XYZ",
|
||||
Password = Encoding.UTF8.GetBytes("PASS"),
|
||||
Username = "USER",
|
||||
KeepAlivePeriod = 123,
|
||||
CleanSession = true
|
||||
};
|
||||
|
||||
SerializeAndCompare(p, "EB0ABk1RSXNkcAPCAHsAA1hZWgAEVVNFUgAEUEFTUw==", MqttProtocolVersion.V310);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void SerializeV311_MqttConnAckPacket()
|
||||
{
|
||||
var p = new MqttConnAckPacket
|
||||
{
|
||||
IsSessionPresent = true,
|
||||
ReturnCode = MqttConnectReturnCode.ConnectionRefusedNotAuthorized
|
||||
};
|
||||
|
||||
SerializeAndCompare(p, "IAIBBQ==");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void SerializeV311_MqttConnectPacket()
|
||||
{
|
||||
var p = new MqttConnectPacket
|
||||
{
|
||||
ClientId = "XYZ",
|
||||
Password = Encoding.UTF8.GetBytes("PASS"),
|
||||
Username = "USER",
|
||||
KeepAlivePeriod = 123,
|
||||
CleanSession = true
|
||||
};
|
||||
|
||||
SerializeAndCompare(p, "EBsABE1RVFQEwgB7AANYWVoABFVTRVIABFBBU1M=");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void SerializeV311_MqttConnectPacketWithWillMessage()
|
||||
{
|
||||
var p = new MqttConnectPacket
|
||||
{
|
||||
ClientId = "XYZ",
|
||||
Password = Encoding.UTF8.GetBytes("PASS"),
|
||||
Username = "USER",
|
||||
KeepAlivePeriod = 123,
|
||||
CleanSession = true,
|
||||
WillFlag = true,
|
||||
WillTopic = "My/last/will",
|
||||
WillMessage = Encoding.UTF8.GetBytes("Good byte."),
|
||||
WillQoS = MqttQualityOfServiceLevel.AtLeastOnce,
|
||||
WillRetain = true
|
||||
};
|
||||
|
||||
SerializeAndCompare(p, "EDUABE1RVFQE7gB7AANYWVoADE15L2xhc3Qvd2lsbAAKR29vZCBieXRlLgAEVVNFUgAEUEFTUw==");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void SerializeV311_MqttDisconnectPacket()
|
||||
{
|
||||
SerializeAndCompare(new MqttDisconnectPacket(), "4AA=");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void SerializeV311_MqttPingReqPacket()
|
||||
{
|
||||
SerializeAndCompare(new MqttPingReqPacket(), "wAA=");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void SerializeV311_MqttPingRespPacket()
|
||||
{
|
||||
SerializeAndCompare(new MqttPingRespPacket(), "0AA=");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void SerializeV311_MqttPubAckPacket()
|
||||
{
|
||||
var p = new MqttPubAckPacket
|
||||
{
|
||||
PacketIdentifier = 123
|
||||
};
|
||||
|
||||
SerializeAndCompare(p, "QAIAew==");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void SerializeV311_MqttPubCompPacket()
|
||||
{
|
||||
var p = new MqttPubCompPacket
|
||||
{
|
||||
PacketIdentifier = 123
|
||||
};
|
||||
|
||||
SerializeAndCompare(p, "cAIAew==");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void SerializeV311_MqttPublishPacket()
|
||||
{
|
||||
var p = new MqttPublishPacket
|
||||
{
|
||||
PacketIdentifier = 123,
|
||||
Dup = true,
|
||||
Retain = true,
|
||||
Payload = Encoding.ASCII.GetBytes("HELLO"),
|
||||
QualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce,
|
||||
Topic = "A/B/C"
|
||||
};
|
||||
|
||||
SerializeAndCompare(p, "Ow4ABUEvQi9DAHtIRUxMTw==");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void SerializeV311_MqttPubRecPacket()
|
||||
{
|
||||
var p = new MqttPubRecPacket
|
||||
{
|
||||
PacketIdentifier = 123
|
||||
};
|
||||
|
||||
SerializeAndCompare(p, "UAIAew==");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void SerializeV311_MqttPubRelPacket()
|
||||
{
|
||||
var p = new MqttPubRelPacket
|
||||
{
|
||||
PacketIdentifier = 123
|
||||
};
|
||||
|
||||
SerializeAndCompare(p, "YgIAew==");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void SerializeV311_MqttSubAckPacket()
|
||||
{
|
||||
var p = new MqttSubAckPacket
|
||||
{
|
||||
PacketIdentifier = 123,
|
||||
ReasonCodes = new List<MqttSubscribeReasonCode>
|
||||
{
|
||||
MqttSubscribeReasonCode.GrantedQoS0,
|
||||
MqttSubscribeReasonCode.GrantedQoS1,
|
||||
MqttSubscribeReasonCode.GrantedQoS2,
|
||||
MqttSubscribeReasonCode.UnspecifiedError
|
||||
}
|
||||
};
|
||||
|
||||
SerializeAndCompare(p, "kAYAewABAoA=");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void SerializeV311_MqttSubscribePacket()
|
||||
{
|
||||
var p = new MqttSubscribePacket
|
||||
{
|
||||
PacketIdentifier = 123
|
||||
};
|
||||
|
||||
p.TopicFilters.Add(new MqttTopicFilter { Topic = "A/B/C", QualityOfServiceLevel = MqttQualityOfServiceLevel.ExactlyOnce });
|
||||
p.TopicFilters.Add(new MqttTopicFilter { Topic = "1/2/3", QualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce });
|
||||
p.TopicFilters.Add(new MqttTopicFilter { Topic = "x/y/z", QualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce });
|
||||
|
||||
SerializeAndCompare(p, "ghoAewAFQS9CL0MCAAUxLzIvMwEABXgveS96AA==");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void SerializeV311_MqttUnsubAckPacket()
|
||||
{
|
||||
var p = new MqttUnsubAckPacket
|
||||
{
|
||||
PacketIdentifier = 123
|
||||
};
|
||||
|
||||
SerializeAndCompare(p, "sAIAew==");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void SerializeV311_MqttUnsubscribePacket()
|
||||
{
|
||||
var p = new MqttUnsubscribePacket
|
||||
{
|
||||
PacketIdentifier = 123
|
||||
};
|
||||
|
||||
p.TopicFilters.Add("A/B/C");
|
||||
p.TopicFilters.Add("1/2/3");
|
||||
p.TopicFilters.Add("x/y/z");
|
||||
|
||||
SerializeAndCompare(p, "ohcAewAFQS9CL0MABTEvMi8zAAV4L3kveg==");
|
||||
}
|
||||
|
||||
|
||||
void DeserializeAndCompare(MqttPacket packet, string expectedBase64Value, MqttProtocolVersion protocolVersion = MqttProtocolVersion.V311)
|
||||
{
|
||||
var writer = WriterFactory();
|
||||
|
||||
var serializer = MqttPacketFormatterAdapter.GetMqttPacketFormatter(protocolVersion, writer);
|
||||
var buffer1 = serializer.Encode(packet);
|
||||
|
||||
using (var headerStream = new MemoryStream(buffer1.Join().ToArray()))
|
||||
{
|
||||
using (var channel = new TestMqttChannel(headerStream))
|
||||
{
|
||||
using (var adapter = new MqttChannelAdapter(
|
||||
channel,
|
||||
new MqttPacketFormatterAdapter(protocolVersion, new MqttBufferWriter(4096, 65535)),
|
||||
null,
|
||||
new MqttNetEventLogger()))
|
||||
{
|
||||
var receivedPacket = adapter.ReceivePacketAsync(CancellationToken.None).GetAwaiter().GetResult();
|
||||
|
||||
var buffer2 = serializer.Encode(receivedPacket);
|
||||
|
||||
Assert.AreEqual(expectedBase64Value, Convert.ToBase64String(buffer2.Join().ToArray()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
MqttProtocolVersion DeserializeAndDetectVersion(MqttPacketFormatterAdapter packetFormatterAdapter, byte[] buffer)
|
||||
{
|
||||
var channel = new TestMqttChannel(buffer);
|
||||
var adapter = new MqttChannelAdapter(channel, packetFormatterAdapter, null, new MqttNetEventLogger());
|
||||
|
||||
adapter.ReceivePacketAsync(CancellationToken.None).GetAwaiter().GetResult();
|
||||
return packetFormatterAdapter.ProtocolVersion;
|
||||
}
|
||||
|
||||
MqttBufferReader ReaderFactory(byte[] data)
|
||||
{
|
||||
var reader = new MqttBufferReader();
|
||||
reader.SetBuffer(data, 0, data.Length);
|
||||
return reader;
|
||||
}
|
||||
|
||||
TPacket Roundtrip<TPacket>(TPacket packet, MqttProtocolVersion protocolVersion = MqttProtocolVersion.V311, MqttBufferWriter bufferWriter = null) where TPacket : MqttPacket
|
||||
{
|
||||
var writer = bufferWriter ?? WriterFactory();
|
||||
var serializer = MqttPacketFormatterAdapter.GetMqttPacketFormatter(protocolVersion, writer);
|
||||
var buffer = serializer.Encode(packet);
|
||||
|
||||
using (var channel = new TestMqttChannel(buffer.Join().ToArray()))
|
||||
{
|
||||
var adapter = new MqttChannelAdapter(channel, new MqttPacketFormatterAdapter(protocolVersion, new MqttBufferWriter(4096, 65535)), null, new MqttNetEventLogger());
|
||||
return (TPacket)adapter.ReceivePacketAsync(CancellationToken.None).GetAwaiter().GetResult();
|
||||
}
|
||||
}
|
||||
|
||||
byte[] Serialize(MqttPacket packet, MqttProtocolVersion protocolVersion)
|
||||
{
|
||||
return MqttPacketFormatterAdapter.GetMqttPacketFormatter(protocolVersion, WriterFactory()).Encode(packet).Join().ToArray();
|
||||
}
|
||||
|
||||
void SerializeAndCompare(MqttPacket packet, string expectedBase64Value, MqttProtocolVersion protocolVersion = MqttProtocolVersion.V311)
|
||||
{
|
||||
Assert.AreEqual(expectedBase64Value, Convert.ToBase64String(Serialize(packet, protocolVersion)));
|
||||
}
|
||||
|
||||
MqttBufferWriter WriterFactory()
|
||||
{
|
||||
return new MqttBufferWriter(4096, 65535);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,495 @@
|
||||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using MQTTnet.Exceptions;
|
||||
using MQTTnet.Formatter;
|
||||
using MQTTnet.Packets;
|
||||
using MQTTnet.Protocol;
|
||||
|
||||
namespace MQTTnet.Tests
|
||||
{
|
||||
[TestClass]
|
||||
public sealed class MqttPacketSerialization_V3_Tests
|
||||
{
|
||||
[TestMethod]
|
||||
public void Serialize_Full_MqttAuthPacket_V311()
|
||||
{
|
||||
var authPacket = new MqttAuthPacket();
|
||||
Assert.ThrowsException<MqttProtocolViolationException>(() => MqttPacketSerializationHelper.EncodeAndDecodePacket(authPacket, MqttProtocolVersion.V311));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Serialize_Full_MqttConnAckPacket_V311()
|
||||
{
|
||||
var connAckPacket = new MqttConnAckPacket
|
||||
{
|
||||
AuthenticationData = Encoding.UTF8.GetBytes("AuthenticationData"),
|
||||
AuthenticationMethod = "AuthenticationMethod",
|
||||
ReasonCode = MqttConnectReasonCode.ServerUnavailable,
|
||||
ReasonString = "ReasonString",
|
||||
ReceiveMaximum = 123,
|
||||
ResponseInformation = "ResponseInformation",
|
||||
RetainAvailable = true,
|
||||
ReturnCode = MqttConnectReturnCode.ConnectionRefusedNotAuthorized,
|
||||
ServerReference = "ServerReference",
|
||||
AssignedClientIdentifier = "AssignedClientIdentifier",
|
||||
IsSessionPresent = true,
|
||||
MaximumPacketSize = 456,
|
||||
MaximumQoS = MqttQualityOfServiceLevel.ExactlyOnce,
|
||||
ServerKeepAlive = 789,
|
||||
SessionExpiryInterval = 852,
|
||||
SharedSubscriptionAvailable = true,
|
||||
SubscriptionIdentifiersAvailable = true,
|
||||
TopicAliasMaximum = 963,
|
||||
WildcardSubscriptionAvailable = true,
|
||||
UserProperties = new List<MqttUserProperty>
|
||||
{
|
||||
new MqttUserProperty("Foo", "Bar")
|
||||
}
|
||||
};
|
||||
|
||||
var deserialized = MqttPacketSerializationHelper.EncodeAndDecodePacket(connAckPacket, MqttProtocolVersion.V311);
|
||||
|
||||
CollectionAssert.AreEqual(null, deserialized.AuthenticationData); // Not supported in v3.1.1
|
||||
Assert.AreEqual(null, deserialized.AuthenticationMethod); // Not supported in v3.1.1
|
||||
//Assert.AreEqual(connAckPacket.ReasonCode, deserialized.ReasonCode);
|
||||
Assert.AreEqual(null, deserialized.ReasonString); // Not supported in v3.1.1
|
||||
Assert.AreEqual(0U, deserialized.ReceiveMaximum); // Not supported in v3.1.1
|
||||
Assert.AreEqual(null, deserialized.ResponseInformation); // Not supported in v3.1.1
|
||||
Assert.AreEqual(false, deserialized.RetainAvailable); // Not supported in v3.1.1
|
||||
Assert.AreEqual(MqttConnectReturnCode.ConnectionRefusedNotAuthorized, deserialized.ReturnCode);
|
||||
Assert.AreEqual(null, deserialized.ServerReference); // Not supported in v3.1.1
|
||||
Assert.AreEqual(null, deserialized.AssignedClientIdentifier); // Not supported in v3.1.1
|
||||
Assert.AreEqual(connAckPacket.IsSessionPresent, deserialized.IsSessionPresent);
|
||||
Assert.AreEqual(0U, deserialized.MaximumPacketSize); // Not supported in v3.1.1
|
||||
Assert.AreEqual(MqttQualityOfServiceLevel.AtMostOnce, deserialized.MaximumQoS); // Not supported in v3.1.1
|
||||
Assert.AreEqual(0U, deserialized.ServerKeepAlive); // Not supported in v3.1.1
|
||||
Assert.AreEqual(0U, deserialized.SessionExpiryInterval); // Not supported in v3.1.1
|
||||
Assert.AreEqual(false, deserialized.SharedSubscriptionAvailable); // Not supported in v3.1.1
|
||||
Assert.AreEqual(false, deserialized.SubscriptionIdentifiersAvailable); // Not supported in v3.1.1
|
||||
Assert.AreEqual(0U, deserialized.TopicAliasMaximum); // Not supported in v3.1.1
|
||||
Assert.AreEqual(false, deserialized.WildcardSubscriptionAvailable);
|
||||
Assert.IsNull(deserialized.UserProperties); // Not supported in v3.1.1
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Serialize_Full_MqttConnAckPacket_V310()
|
||||
{
|
||||
var connAckPacket = new MqttConnAckPacket
|
||||
{
|
||||
AuthenticationData = Encoding.UTF8.GetBytes("AuthenticationData"),
|
||||
AuthenticationMethod = "AuthenticationMethod",
|
||||
ReasonCode = MqttConnectReasonCode.ServerUnavailable,
|
||||
ReasonString = "ReasonString",
|
||||
ReceiveMaximum = 123,
|
||||
ResponseInformation = "ResponseInformation",
|
||||
RetainAvailable = true,
|
||||
ReturnCode = MqttConnectReturnCode.ConnectionRefusedNotAuthorized,
|
||||
ServerReference = "ServerReference",
|
||||
AssignedClientIdentifier = "AssignedClientIdentifier",
|
||||
IsSessionPresent = true,
|
||||
MaximumPacketSize = 456,
|
||||
MaximumQoS = MqttQualityOfServiceLevel.ExactlyOnce,
|
||||
ServerKeepAlive = 789,
|
||||
SessionExpiryInterval = 852,
|
||||
SharedSubscriptionAvailable = true,
|
||||
SubscriptionIdentifiersAvailable = true,
|
||||
TopicAliasMaximum = 963,
|
||||
WildcardSubscriptionAvailable = true,
|
||||
UserProperties = new List<MqttUserProperty>
|
||||
{
|
||||
new MqttUserProperty("Foo", "Bar")
|
||||
}
|
||||
};
|
||||
|
||||
var deserialized = MqttPacketSerializationHelper.EncodeAndDecodePacket(connAckPacket, MqttProtocolVersion.V310);
|
||||
|
||||
CollectionAssert.AreEqual(null, deserialized.AuthenticationData); // Not supported in v3.1.1
|
||||
Assert.AreEqual(null, deserialized.AuthenticationMethod); // Not supported in v3.1.1
|
||||
//Assert.AreEqual(connAckPacket.ReasonCode, deserialized.ReasonCode);
|
||||
Assert.AreEqual(null, deserialized.ReasonString); // Not supported in v3.1.1
|
||||
Assert.AreEqual(0U, deserialized.ReceiveMaximum); // Not supported in v3.1.1
|
||||
Assert.AreEqual(null, deserialized.ResponseInformation); // Not supported in v3.1.1
|
||||
Assert.AreEqual(false, deserialized.RetainAvailable); // Not supported in v3.1.1
|
||||
Assert.AreEqual(MqttConnectReturnCode.ConnectionRefusedNotAuthorized, deserialized.ReturnCode);
|
||||
Assert.AreEqual(null, deserialized.ServerReference); // Not supported in v3.1.1
|
||||
Assert.AreEqual(null, deserialized.AssignedClientIdentifier); // Not supported in v3.1.1
|
||||
Assert.AreEqual(false, deserialized.IsSessionPresent); // Not supported in v3.1.0 <- !
|
||||
Assert.AreEqual(0U, deserialized.MaximumPacketSize); // Not supported in v3.1.1
|
||||
Assert.AreEqual(MqttQualityOfServiceLevel.AtMostOnce, deserialized.MaximumQoS); // Not supported in v3.1.1
|
||||
Assert.AreEqual(0U, deserialized.ServerKeepAlive); // Not supported in v3.1.1
|
||||
Assert.AreEqual(0U, deserialized.SessionExpiryInterval); // Not supported in v3.1.1
|
||||
Assert.AreEqual(false, deserialized.SharedSubscriptionAvailable); // Not supported in v3.1.1
|
||||
Assert.AreEqual(false, deserialized.SubscriptionIdentifiersAvailable); // Not supported in v3.1.1
|
||||
Assert.AreEqual(0U, deserialized.TopicAliasMaximum); // Not supported in v3.1.1
|
||||
Assert.AreEqual(false, deserialized.WildcardSubscriptionAvailable);
|
||||
Assert.IsNull(deserialized.UserProperties); // Not supported in v3.1.1
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Serialize_Full_MqttConnectPacket_V311()
|
||||
{
|
||||
var connectPacket = new MqttConnectPacket
|
||||
{
|
||||
Username = "Username",
|
||||
Password = Encoding.UTF8.GetBytes("Password"),
|
||||
ClientId = "ClientId",
|
||||
AuthenticationData = Encoding.UTF8.GetBytes("AuthenticationData"),
|
||||
AuthenticationMethod = "AuthenticationMethod",
|
||||
CleanSession = true,
|
||||
ReceiveMaximum = 123,
|
||||
WillFlag = true,
|
||||
WillTopic = "WillTopic",
|
||||
WillMessage = Encoding.UTF8.GetBytes("WillMessage"),
|
||||
WillRetain = true,
|
||||
KeepAlivePeriod = 456,
|
||||
MaximumPacketSize = 789,
|
||||
RequestProblemInformation = true,
|
||||
RequestResponseInformation = true,
|
||||
SessionExpiryInterval = 27,
|
||||
TopicAliasMaximum = 67,
|
||||
WillContentType = "WillContentType",
|
||||
WillCorrelationData = Encoding.UTF8.GetBytes("WillCorrelationData"),
|
||||
WillDelayInterval = 782,
|
||||
WillQoS = MqttQualityOfServiceLevel.ExactlyOnce,
|
||||
WillResponseTopic = "WillResponseTopic",
|
||||
WillMessageExpiryInterval = 542,
|
||||
WillPayloadFormatIndicator = MqttPayloadFormatIndicator.CharacterData,
|
||||
UserProperties = new List<MqttUserProperty>
|
||||
{
|
||||
new MqttUserProperty("Foo", "Bar")
|
||||
},
|
||||
WillUserProperties = new List<MqttUserProperty>
|
||||
{
|
||||
new MqttUserProperty("WillFoo", "WillBar")
|
||||
}
|
||||
};
|
||||
|
||||
var deserialized = MqttPacketSerializationHelper.EncodeAndDecodePacket(connectPacket, MqttProtocolVersion.V311);
|
||||
|
||||
Assert.AreEqual(connectPacket.Username, deserialized.Username);
|
||||
CollectionAssert.AreEqual(connectPacket.Password, deserialized.Password);
|
||||
Assert.AreEqual(connectPacket.ClientId, deserialized.ClientId);
|
||||
CollectionAssert.AreEqual(null, deserialized.AuthenticationData); // Not supported in v3.1.1
|
||||
Assert.AreEqual(null, deserialized.AuthenticationMethod); // Not supported in v3.1.1
|
||||
Assert.AreEqual(connectPacket.CleanSession, deserialized.CleanSession);
|
||||
Assert.AreEqual(0L, deserialized.ReceiveMaximum); // Not supported in v3.1.1
|
||||
Assert.AreEqual(connectPacket.WillFlag, deserialized.WillFlag);
|
||||
Assert.AreEqual(connectPacket.WillTopic, deserialized.WillTopic);
|
||||
CollectionAssert.AreEqual(connectPacket.WillMessage, deserialized.WillMessage);
|
||||
Assert.AreEqual(connectPacket.WillRetain, deserialized.WillRetain);
|
||||
Assert.AreEqual(connectPacket.KeepAlivePeriod, deserialized.KeepAlivePeriod);
|
||||
// MaximumPacketSize not available in MQTTv3.
|
||||
// RequestProblemInformation not available in MQTTv3.
|
||||
// RequestResponseInformation not available in MQTTv3.
|
||||
// SessionExpiryInterval not available in MQTTv3.
|
||||
// TopicAliasMaximum not available in MQTTv3.
|
||||
// WillContentType not available in MQTTv3.
|
||||
// WillCorrelationData not available in MQTTv3.
|
||||
// WillDelayInterval not available in MQTTv3.
|
||||
Assert.AreEqual(connectPacket.WillQoS, deserialized.WillQoS);
|
||||
// WillResponseTopic not available in MQTTv3.
|
||||
// WillMessageExpiryInterval not available in MQTTv3.
|
||||
// WillPayloadFormatIndicator not available in MQTTv3.
|
||||
Assert.IsNull(deserialized.UserProperties); // Not supported in v3.1.1
|
||||
Assert.IsNull(deserialized.WillUserProperties); // Not supported in v3.1.1
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Serialize_Full_MqttDisconnectPacket_V311()
|
||||
{
|
||||
var disconnectPacket = new MqttDisconnectPacket
|
||||
{
|
||||
ReasonCode = MqttDisconnectReasonCode.NormalDisconnection,
|
||||
ReasonString = "ReasonString",
|
||||
ServerReference = "ServerReference",
|
||||
SessionExpiryInterval = 234,
|
||||
UserProperties = new List<MqttUserProperty>
|
||||
{
|
||||
new MqttUserProperty("Foo", "Bar")
|
||||
}
|
||||
};
|
||||
|
||||
var deserialized = MqttPacketSerializationHelper.EncodeAndDecodePacket(disconnectPacket, MqttProtocolVersion.V311);
|
||||
|
||||
|
||||
Assert.AreEqual(disconnectPacket.ReasonCode, deserialized.ReasonCode);
|
||||
Assert.AreEqual(null, deserialized.ReasonString); // Not supported in v3.1.1
|
||||
Assert.AreEqual(null, deserialized.ServerReference); // Not supported in v3.1.1
|
||||
Assert.AreEqual(0U, deserialized.SessionExpiryInterval); // Not supported in v3.1.1
|
||||
CollectionAssert.AreEqual(null, deserialized.UserProperties);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Serialize_Full_MqttPingReqPacket_V311()
|
||||
{
|
||||
var pingReqPacket = new MqttPingReqPacket();
|
||||
|
||||
var deserialized = MqttPacketSerializationHelper.EncodeAndDecodePacket(pingReqPacket, MqttProtocolVersion.V311);
|
||||
|
||||
Assert.IsNotNull(deserialized);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Serialize_Full_MqttPingRespPacket_V311()
|
||||
{
|
||||
var pingRespPacket = new MqttPingRespPacket();
|
||||
|
||||
var deserialized = MqttPacketSerializationHelper.EncodeAndDecodePacket(pingRespPacket, MqttProtocolVersion.V311);
|
||||
|
||||
Assert.IsNotNull(deserialized);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Serialize_Full_MqttPubAckPacket_V311()
|
||||
{
|
||||
var pubAckPacket = new MqttPubAckPacket
|
||||
{
|
||||
PacketIdentifier = 123,
|
||||
ReasonCode = MqttPubAckReasonCode.NoMatchingSubscribers,
|
||||
ReasonString = "ReasonString",
|
||||
UserProperties = new List<MqttUserProperty>
|
||||
{
|
||||
new MqttUserProperty("Foo", "Bar")
|
||||
}
|
||||
};
|
||||
|
||||
var deserialized = MqttPacketSerializationHelper.EncodeAndDecodePacket(pubAckPacket, MqttProtocolVersion.V311);
|
||||
|
||||
Assert.AreEqual(pubAckPacket.PacketIdentifier, deserialized.PacketIdentifier);
|
||||
Assert.AreEqual(MqttPubAckReasonCode.Success, deserialized.ReasonCode); // Not supported in v3.1.1
|
||||
Assert.AreEqual(null, deserialized.ReasonString); // Not supported in v3.1.1
|
||||
CollectionAssert.AreEqual(null, deserialized.UserProperties);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Serialize_Full_MqttPubCompPacket_V311()
|
||||
{
|
||||
var pubCompPacket = new MqttPubCompPacket
|
||||
{
|
||||
PacketIdentifier = 123,
|
||||
ReasonCode = MqttPubCompReasonCode.PacketIdentifierNotFound,
|
||||
ReasonString = "ReasonString",
|
||||
UserProperties = new List<MqttUserProperty>
|
||||
{
|
||||
new MqttUserProperty("Foo", "Bar")
|
||||
}
|
||||
};
|
||||
|
||||
var deserialized = MqttPacketSerializationHelper.EncodeAndDecodePacket(pubCompPacket, MqttProtocolVersion.V311);
|
||||
|
||||
Assert.AreEqual(pubCompPacket.PacketIdentifier, deserialized.PacketIdentifier);
|
||||
// ReasonCode not available in MQTTv3.
|
||||
// ReasonString not available in MQTTv3.
|
||||
// UserProperties not available in MQTTv3.
|
||||
Assert.IsNull(deserialized.UserProperties);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Serialize_Full_MqttPublishPacket_V311()
|
||||
{
|
||||
var publishPacket = new MqttPublishPacket
|
||||
{
|
||||
PacketIdentifier = 123,
|
||||
Dup = true,
|
||||
Retain = true,
|
||||
Payload = Encoding.ASCII.GetBytes("Payload"),
|
||||
QualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce,
|
||||
Topic = "Topic",
|
||||
ResponseTopic = "/Response",
|
||||
ContentType = "Content-Type",
|
||||
CorrelationData = Encoding.UTF8.GetBytes("CorrelationData"),
|
||||
TopicAlias = 27,
|
||||
SubscriptionIdentifiers = new List<uint>
|
||||
{
|
||||
123
|
||||
},
|
||||
MessageExpiryInterval = 38,
|
||||
PayloadFormatIndicator = MqttPayloadFormatIndicator.CharacterData,
|
||||
UserProperties = new List<MqttUserProperty>
|
||||
{
|
||||
new MqttUserProperty("Foo", "Bar")
|
||||
}
|
||||
};
|
||||
|
||||
var deserialized = MqttPacketSerializationHelper.EncodeAndDecodePacket(publishPacket, MqttProtocolVersion.V311);
|
||||
|
||||
Assert.AreEqual(publishPacket.PacketIdentifier, deserialized.PacketIdentifier);
|
||||
Assert.AreEqual(publishPacket.Dup, deserialized.Dup);
|
||||
Assert.AreEqual(publishPacket.Retain, deserialized.Retain);
|
||||
CollectionAssert.AreEqual(publishPacket.Payload, deserialized.Payload);
|
||||
Assert.AreEqual(publishPacket.QualityOfServiceLevel, deserialized.QualityOfServiceLevel);
|
||||
Assert.AreEqual(publishPacket.Topic, deserialized.Topic);
|
||||
Assert.AreEqual(null, deserialized.ResponseTopic); // Not supported in v3.1.1.
|
||||
Assert.AreEqual(null, deserialized.ContentType); // Not supported in v3.1.1.
|
||||
CollectionAssert.AreEqual(null, deserialized.CorrelationData); // Not supported in v3.1.1.
|
||||
Assert.AreEqual(0U, deserialized.TopicAlias); // Not supported in v3.1.1.
|
||||
CollectionAssert.AreEqual(null, deserialized.SubscriptionIdentifiers); // Not supported in v3.1.1
|
||||
Assert.AreEqual(0U, deserialized.MessageExpiryInterval); // Not supported in v3.1.1
|
||||
Assert.AreEqual(MqttPayloadFormatIndicator.Unspecified, deserialized.PayloadFormatIndicator); // Not supported in v3.1.1
|
||||
Assert.IsNull(deserialized.UserProperties); // Not supported in v3.1.1
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Serialize_Full_MqttPubRecPacket_V311()
|
||||
{
|
||||
var pubRecPacket = new MqttPubRecPacket
|
||||
{
|
||||
PacketIdentifier = 123,
|
||||
ReasonCode = MqttPubRecReasonCode.UnspecifiedError,
|
||||
ReasonString = "ReasonString",
|
||||
UserProperties = new List<MqttUserProperty>
|
||||
{
|
||||
new MqttUserProperty("Foo", "Bar")
|
||||
}
|
||||
};
|
||||
|
||||
var deserialized = MqttPacketSerializationHelper.EncodeAndDecodePacket(pubRecPacket, MqttProtocolVersion.V311);
|
||||
|
||||
Assert.AreEqual(pubRecPacket.PacketIdentifier, deserialized.PacketIdentifier);
|
||||
// ReasonCode not available in MQTTv3.
|
||||
// ReasonString not available in MQTTv3.
|
||||
// UserProperties not available in MQTTv3.
|
||||
Assert.IsNull(deserialized.UserProperties);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Serialize_Full_MqttPubRelPacket_V311()
|
||||
{
|
||||
var pubRelPacket = new MqttPubRelPacket
|
||||
{
|
||||
PacketIdentifier = 123,
|
||||
ReasonCode = MqttPubRelReasonCode.PacketIdentifierNotFound,
|
||||
ReasonString = "ReasonString",
|
||||
UserProperties = new List<MqttUserProperty>
|
||||
{
|
||||
new MqttUserProperty("Foo", "Bar")
|
||||
}
|
||||
};
|
||||
|
||||
var deserialized = MqttPacketSerializationHelper.EncodeAndDecodePacket(pubRelPacket, MqttProtocolVersion.V311);
|
||||
|
||||
Assert.AreEqual(pubRelPacket.PacketIdentifier, deserialized.PacketIdentifier);
|
||||
// ReasonCode not available in MQTTv3.
|
||||
// ReasonString not available in MQTTv3.
|
||||
// UserProperties not available in MQTTv3.
|
||||
Assert.IsNull(deserialized.UserProperties);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Serialize_Full_MqttSubAckPacket_V311()
|
||||
{
|
||||
var subAckPacket = new MqttSubAckPacket
|
||||
{
|
||||
PacketIdentifier = 123,
|
||||
ReasonString = "ReasonString",
|
||||
ReasonCodes = new List<MqttSubscribeReasonCode>
|
||||
{
|
||||
MqttSubscribeReasonCode.GrantedQoS1
|
||||
},
|
||||
UserProperties = new List<MqttUserProperty>
|
||||
{
|
||||
new MqttUserProperty("Foo", "Bar")
|
||||
}
|
||||
};
|
||||
|
||||
var deserialized = MqttPacketSerializationHelper.EncodeAndDecodePacket(subAckPacket, MqttProtocolVersion.V311);
|
||||
|
||||
Assert.AreEqual(subAckPacket.PacketIdentifier, deserialized.PacketIdentifier);
|
||||
Assert.AreEqual(null, deserialized.ReasonString); // Not supported in v3.1.1
|
||||
Assert.AreEqual(subAckPacket.ReasonCodes.Count, deserialized.ReasonCodes.Count);
|
||||
Assert.AreEqual(subAckPacket.ReasonCodes[0], deserialized.ReasonCodes[0]);
|
||||
CollectionAssert.AreEqual(null, deserialized.UserProperties); // Not supported in v3.1.1
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Serialize_Full_MqttSubscribePacket_V311()
|
||||
{
|
||||
var subscribePacket = new MqttSubscribePacket
|
||||
{
|
||||
PacketIdentifier = 123,
|
||||
SubscriptionIdentifier = 456,
|
||||
TopicFilters = new List<MqttTopicFilter>
|
||||
{
|
||||
new MqttTopicFilter
|
||||
{
|
||||
Topic = "Topic",
|
||||
NoLocal = true,
|
||||
RetainHandling = MqttRetainHandling.SendAtSubscribeIfNewSubscriptionOnly,
|
||||
RetainAsPublished = true,
|
||||
QualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce
|
||||
}
|
||||
},
|
||||
UserProperties = new List<MqttUserProperty>
|
||||
{
|
||||
new MqttUserProperty("Foo", "Bar")
|
||||
}
|
||||
};
|
||||
|
||||
var deserialized = MqttPacketSerializationHelper.EncodeAndDecodePacket(subscribePacket, MqttProtocolVersion.V311);
|
||||
|
||||
Assert.AreEqual(subscribePacket.PacketIdentifier, deserialized.PacketIdentifier);
|
||||
Assert.AreEqual(0U, deserialized.SubscriptionIdentifier); // Not supported in v3.1.1
|
||||
Assert.AreEqual(1, deserialized.TopicFilters.Count);
|
||||
Assert.AreEqual(subscribePacket.TopicFilters[0].Topic, deserialized.TopicFilters[0].Topic);
|
||||
Assert.AreEqual(false, deserialized.TopicFilters[0].NoLocal); // Not supported in v3.1.1
|
||||
Assert.AreEqual(MqttRetainHandling.SendAtSubscribe, deserialized.TopicFilters[0].RetainHandling); // Not supported in v3.1.1
|
||||
Assert.AreEqual(false, deserialized.TopicFilters[0].RetainAsPublished); // Not supported in v3.1.1
|
||||
Assert.AreEqual(subscribePacket.TopicFilters[0].QualityOfServiceLevel, deserialized.TopicFilters[0].QualityOfServiceLevel);
|
||||
CollectionAssert.AreEqual(null, deserialized.UserProperties); // Not supported in v3.1.1
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Serialize_Full_MqttUnsubAckPacket_V311()
|
||||
{
|
||||
var unsubAckPacket = new MqttUnsubAckPacket
|
||||
{
|
||||
PacketIdentifier = 123,
|
||||
ReasonCodes = new List<MqttUnsubscribeReasonCode>
|
||||
{
|
||||
MqttUnsubscribeReasonCode.ImplementationSpecificError
|
||||
},
|
||||
ReasonString = "ReasonString",
|
||||
UserProperties = new List<MqttUserProperty>
|
||||
{
|
||||
new MqttUserProperty("Foo", "Bar")
|
||||
}
|
||||
};
|
||||
|
||||
var deserialized = MqttPacketSerializationHelper.EncodeAndDecodePacket(unsubAckPacket, MqttProtocolVersion.V311);
|
||||
|
||||
Assert.AreEqual(unsubAckPacket.PacketIdentifier, deserialized.PacketIdentifier);
|
||||
Assert.AreEqual(null, deserialized.ReasonString); // Not supported in v3.1.1
|
||||
CollectionAssert.AreEqual(null, deserialized.ReasonCodes); // Not supported in v3.1.1
|
||||
CollectionAssert.AreEqual(null, deserialized.UserProperties); // Not supported in v3.1.1
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Serialize_Full_MqttUnsubscribePacket_V311()
|
||||
{
|
||||
var unsubscribePacket = new MqttUnsubscribePacket
|
||||
{
|
||||
PacketIdentifier = 123,
|
||||
TopicFilters = new List<string>
|
||||
{
|
||||
"TopicFilter1"
|
||||
},
|
||||
UserProperties = new List<MqttUserProperty>
|
||||
{
|
||||
new MqttUserProperty("Foo", "Bar")
|
||||
}
|
||||
};
|
||||
|
||||
var deserialized = MqttPacketSerializationHelper.EncodeAndDecodePacket(unsubscribePacket, MqttProtocolVersion.V311);
|
||||
|
||||
Assert.AreEqual(unsubscribePacket.PacketIdentifier, deserialized.PacketIdentifier);
|
||||
Assert.AreEqual(unsubscribePacket.TopicFilters.Count, deserialized.TopicFilters.Count);
|
||||
Assert.AreEqual(unsubscribePacket.TopicFilters[0], deserialized.TopicFilters[0]);
|
||||
CollectionAssert.AreEqual(null, deserialized.UserProperties);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,454 @@
|
||||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using MQTTnet.Formatter;
|
||||
using MQTTnet.Packets;
|
||||
using MQTTnet.Protocol;
|
||||
|
||||
namespace MQTTnet.Tests
|
||||
{
|
||||
[TestClass]
|
||||
public sealed class MqttPacketSerialization_V5_Tests
|
||||
{
|
||||
[TestMethod]
|
||||
public void Serialize_Full_MqttAuthPacket_V500()
|
||||
{
|
||||
var authPacket = new MqttAuthPacket
|
||||
{
|
||||
AuthenticationData = Encoding.UTF8.GetBytes("AuthenticationData"),
|
||||
AuthenticationMethod = "AuthenticationMethod",
|
||||
ReasonCode = MqttAuthenticateReasonCode.ContinueAuthentication,
|
||||
ReasonString = "ReasonString",
|
||||
UserProperties = new List<MqttUserProperty>
|
||||
{
|
||||
new MqttUserProperty("Foo", "Bar")
|
||||
}
|
||||
};
|
||||
|
||||
var deserialized = MqttPacketSerializationHelper.EncodeAndDecodePacket(authPacket, MqttProtocolVersion.V500);
|
||||
|
||||
CollectionAssert.AreEqual(authPacket.AuthenticationData, deserialized.AuthenticationData);
|
||||
Assert.AreEqual(authPacket.AuthenticationMethod, deserialized.AuthenticationMethod);
|
||||
Assert.AreEqual(authPacket.ReasonCode, deserialized.ReasonCode);
|
||||
Assert.AreEqual(authPacket.ReasonString, deserialized.ReasonString);
|
||||
CollectionAssert.AreEqual(authPacket.UserProperties, deserialized.UserProperties);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Serialize_Full_MqttConnAckPacket_V500()
|
||||
{
|
||||
var connAckPacket = new MqttConnAckPacket
|
||||
{
|
||||
AuthenticationData = Encoding.UTF8.GetBytes("AuthenticationData"),
|
||||
AuthenticationMethod = "AuthenticationMethod",
|
||||
ReasonCode = MqttConnectReasonCode.ServerUnavailable,
|
||||
ReasonString = "ReasonString",
|
||||
ReceiveMaximum = 123,
|
||||
ResponseInformation = "ResponseInformation",
|
||||
RetainAvailable = true,
|
||||
ReturnCode = MqttConnectReturnCode.ConnectionRefusedNotAuthorized,
|
||||
ServerReference = "ServerReference",
|
||||
AssignedClientIdentifier = "AssignedClientIdentifier",
|
||||
IsSessionPresent = true,
|
||||
MaximumPacketSize = 456,
|
||||
MaximumQoS = MqttQualityOfServiceLevel.ExactlyOnce,
|
||||
ServerKeepAlive = 789,
|
||||
SessionExpiryInterval = 852,
|
||||
SharedSubscriptionAvailable = true,
|
||||
SubscriptionIdentifiersAvailable = true,
|
||||
TopicAliasMaximum = 963,
|
||||
WildcardSubscriptionAvailable = true,
|
||||
UserProperties = new List<MqttUserProperty>
|
||||
{
|
||||
new MqttUserProperty("Foo", "Bar")
|
||||
}
|
||||
};
|
||||
|
||||
var deserialized = MqttPacketSerializationHelper.EncodeAndDecodePacket(connAckPacket, MqttProtocolVersion.V500);
|
||||
|
||||
CollectionAssert.AreEqual(connAckPacket.AuthenticationData, deserialized.AuthenticationData);
|
||||
Assert.AreEqual(connAckPacket.AuthenticationMethod, deserialized.AuthenticationMethod);
|
||||
Assert.AreEqual(connAckPacket.ReasonCode, deserialized.ReasonCode);
|
||||
Assert.AreEqual(connAckPacket.ReasonString, deserialized.ReasonString);
|
||||
Assert.AreEqual(connAckPacket.ReceiveMaximum, deserialized.ReceiveMaximum);
|
||||
Assert.AreEqual(connAckPacket.ResponseInformation, deserialized.ResponseInformation);
|
||||
Assert.AreEqual(connAckPacket.RetainAvailable, deserialized.RetainAvailable);
|
||||
// Return Code only used in MQTTv3
|
||||
Assert.AreEqual(connAckPacket.ServerReference, deserialized.ServerReference);
|
||||
Assert.AreEqual(connAckPacket.AssignedClientIdentifier, deserialized.AssignedClientIdentifier);
|
||||
Assert.AreEqual(connAckPacket.IsSessionPresent, deserialized.IsSessionPresent);
|
||||
Assert.AreEqual(connAckPacket.MaximumPacketSize, deserialized.MaximumPacketSize);
|
||||
Assert.AreEqual(connAckPacket.MaximumQoS, deserialized.MaximumQoS);
|
||||
Assert.AreEqual(connAckPacket.ServerKeepAlive, deserialized.ServerKeepAlive);
|
||||
Assert.AreEqual(connAckPacket.SessionExpiryInterval, deserialized.SessionExpiryInterval);
|
||||
Assert.AreEqual(connAckPacket.SharedSubscriptionAvailable, deserialized.SharedSubscriptionAvailable);
|
||||
Assert.AreEqual(connAckPacket.SubscriptionIdentifiersAvailable, deserialized.SubscriptionIdentifiersAvailable);
|
||||
Assert.AreEqual(connAckPacket.TopicAliasMaximum, deserialized.TopicAliasMaximum);
|
||||
Assert.AreEqual(connAckPacket.WildcardSubscriptionAvailable, deserialized.WildcardSubscriptionAvailable);
|
||||
CollectionAssert.AreEqual(connAckPacket.UserProperties, deserialized.UserProperties);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Serialize_Full_MqttConnectPacket_V500()
|
||||
{
|
||||
var connectPacket = new MqttConnectPacket
|
||||
{
|
||||
Username = "Username",
|
||||
Password = Encoding.UTF8.GetBytes("Password"),
|
||||
ClientId = "ClientId",
|
||||
AuthenticationData = Encoding.UTF8.GetBytes("AuthenticationData"),
|
||||
AuthenticationMethod = "AuthenticationMethod",
|
||||
CleanSession = true,
|
||||
ReceiveMaximum = 123,
|
||||
WillFlag = true,
|
||||
WillTopic = "WillTopic",
|
||||
WillMessage = Encoding.UTF8.GetBytes("WillMessage"),
|
||||
WillRetain = true,
|
||||
KeepAlivePeriod = 456,
|
||||
MaximumPacketSize = 789,
|
||||
RequestProblemInformation = true,
|
||||
RequestResponseInformation = true,
|
||||
SessionExpiryInterval = 27,
|
||||
TopicAliasMaximum = 67,
|
||||
WillContentType = "WillContentType",
|
||||
WillCorrelationData = Encoding.UTF8.GetBytes("WillCorrelationData"),
|
||||
WillDelayInterval = 782,
|
||||
WillQoS = MqttQualityOfServiceLevel.ExactlyOnce,
|
||||
WillResponseTopic = "WillResponseTopic",
|
||||
WillMessageExpiryInterval = 542,
|
||||
WillPayloadFormatIndicator = MqttPayloadFormatIndicator.CharacterData,
|
||||
UserProperties = new List<MqttUserProperty>
|
||||
{
|
||||
new MqttUserProperty("Foo", "Bar")
|
||||
},
|
||||
WillUserProperties = new List<MqttUserProperty>
|
||||
{
|
||||
new MqttUserProperty("WillFoo", "WillBar")
|
||||
}
|
||||
};
|
||||
|
||||
var deserialized = MqttPacketSerializationHelper.EncodeAndDecodePacket(connectPacket, MqttProtocolVersion.V500);
|
||||
|
||||
Assert.AreEqual(connectPacket.Username, deserialized.Username);
|
||||
CollectionAssert.AreEqual(connectPacket.Password, deserialized.Password);
|
||||
Assert.AreEqual(connectPacket.ClientId, deserialized.ClientId);
|
||||
CollectionAssert.AreEqual(connectPacket.AuthenticationData, deserialized.AuthenticationData);
|
||||
Assert.AreEqual(connectPacket.AuthenticationMethod, deserialized.AuthenticationMethod);
|
||||
Assert.AreEqual(connectPacket.CleanSession, deserialized.CleanSession);
|
||||
Assert.AreEqual(connectPacket.ReceiveMaximum, deserialized.ReceiveMaximum);
|
||||
Assert.AreEqual(connectPacket.WillFlag, deserialized.WillFlag);
|
||||
Assert.AreEqual(connectPacket.WillTopic, deserialized.WillTopic);
|
||||
CollectionAssert.AreEqual(connectPacket.WillMessage, deserialized.WillMessage);
|
||||
Assert.AreEqual(connectPacket.WillRetain, deserialized.WillRetain);
|
||||
Assert.AreEqual(connectPacket.KeepAlivePeriod, deserialized.KeepAlivePeriod);
|
||||
Assert.AreEqual(connectPacket.MaximumPacketSize, deserialized.MaximumPacketSize);
|
||||
Assert.AreEqual(connectPacket.RequestProblemInformation, deserialized.RequestProblemInformation);
|
||||
Assert.AreEqual(connectPacket.RequestResponseInformation, deserialized.RequestResponseInformation);
|
||||
Assert.AreEqual(connectPacket.SessionExpiryInterval, deserialized.SessionExpiryInterval);
|
||||
Assert.AreEqual(connectPacket.TopicAliasMaximum, deserialized.TopicAliasMaximum);
|
||||
Assert.AreEqual(connectPacket.WillContentType, deserialized.WillContentType);
|
||||
CollectionAssert.AreEqual(connectPacket.WillCorrelationData, deserialized.WillCorrelationData);
|
||||
Assert.AreEqual(connectPacket.WillDelayInterval, deserialized.WillDelayInterval);
|
||||
Assert.AreEqual(connectPacket.WillQoS, deserialized.WillQoS);
|
||||
Assert.AreEqual(connectPacket.WillResponseTopic, deserialized.WillResponseTopic);
|
||||
Assert.AreEqual(connectPacket.WillMessageExpiryInterval, deserialized.WillMessageExpiryInterval);
|
||||
Assert.AreEqual(connectPacket.WillPayloadFormatIndicator, deserialized.WillPayloadFormatIndicator);
|
||||
CollectionAssert.AreEqual(connectPacket.UserProperties, deserialized.UserProperties);
|
||||
CollectionAssert.AreEqual(connectPacket.WillUserProperties, deserialized.WillUserProperties);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Serialize_Full_MqttDisconnectPacket_V500()
|
||||
{
|
||||
var disconnectPacket = new MqttDisconnectPacket
|
||||
{
|
||||
ReasonCode = MqttDisconnectReasonCode.NormalDisconnection,
|
||||
ReasonString = "ReasonString",
|
||||
ServerReference = "ServerReference",
|
||||
SessionExpiryInterval = 234,
|
||||
UserProperties = new List<MqttUserProperty>
|
||||
{
|
||||
new MqttUserProperty("Foo", "Bar")
|
||||
}
|
||||
};
|
||||
|
||||
var deserialized = MqttPacketSerializationHelper.EncodeAndDecodePacket(disconnectPacket, MqttProtocolVersion.V500);
|
||||
|
||||
Assert.AreEqual(disconnectPacket.ReasonCode, deserialized.ReasonCode);
|
||||
Assert.AreEqual(disconnectPacket.ReasonString, deserialized.ReasonString);
|
||||
Assert.AreEqual(disconnectPacket.ServerReference, deserialized.ServerReference);
|
||||
Assert.AreEqual(disconnectPacket.SessionExpiryInterval, deserialized.SessionExpiryInterval);
|
||||
CollectionAssert.AreEqual(disconnectPacket.UserProperties, deserialized.UserProperties);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Serialize_Full_MqttPingReqPacket_V500()
|
||||
{
|
||||
var pingReqPacket = new MqttPingReqPacket();
|
||||
|
||||
var deserialized = MqttPacketSerializationHelper.EncodeAndDecodePacket(pingReqPacket, MqttProtocolVersion.V500);
|
||||
|
||||
Assert.IsNotNull(deserialized);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Serialize_Full_MqttPingRespPacket_V500()
|
||||
{
|
||||
var pingRespPacket = new MqttPingRespPacket();
|
||||
|
||||
var deserialized = MqttPacketSerializationHelper.EncodeAndDecodePacket(pingRespPacket, MqttProtocolVersion.V500);
|
||||
|
||||
Assert.IsNotNull(deserialized);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Serialize_Full_MqttPubAckPacket_V500()
|
||||
{
|
||||
var pubAckPacket = new MqttPubAckPacket
|
||||
{
|
||||
PacketIdentifier = 123,
|
||||
ReasonCode = MqttPubAckReasonCode.NoMatchingSubscribers,
|
||||
ReasonString = "ReasonString",
|
||||
UserProperties = new List<MqttUserProperty>
|
||||
{
|
||||
new MqttUserProperty("Foo", "Bar")
|
||||
}
|
||||
};
|
||||
|
||||
var deserialized = MqttPacketSerializationHelper.EncodeAndDecodePacket(pubAckPacket, MqttProtocolVersion.V500);
|
||||
|
||||
Assert.AreEqual(pubAckPacket.PacketIdentifier, deserialized.PacketIdentifier);
|
||||
Assert.AreEqual(pubAckPacket.ReasonCode, deserialized.ReasonCode);
|
||||
Assert.AreEqual(pubAckPacket.ReasonString, deserialized.ReasonString);
|
||||
CollectionAssert.AreEqual(pubAckPacket.UserProperties, deserialized.UserProperties);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Serialize_Full_MqttPubCompPacket_V500()
|
||||
{
|
||||
var pubCompPacket = new MqttPubCompPacket
|
||||
{
|
||||
PacketIdentifier = 123,
|
||||
ReasonCode = MqttPubCompReasonCode.PacketIdentifierNotFound,
|
||||
ReasonString = "ReasonString",
|
||||
UserProperties = new List<MqttUserProperty>
|
||||
{
|
||||
new MqttUserProperty("Foo", "Bar")
|
||||
}
|
||||
};
|
||||
|
||||
var deserialized = MqttPacketSerializationHelper.EncodeAndDecodePacket(pubCompPacket, MqttProtocolVersion.V500);
|
||||
|
||||
Assert.AreEqual(pubCompPacket.PacketIdentifier, deserialized.PacketIdentifier);
|
||||
Assert.AreEqual(pubCompPacket.ReasonCode, deserialized.ReasonCode);
|
||||
Assert.AreEqual(pubCompPacket.ReasonString, deserialized.ReasonString);
|
||||
CollectionAssert.AreEqual(pubCompPacket.UserProperties, deserialized.UserProperties);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Serialize_Full_MqttPublishPacket_V500()
|
||||
{
|
||||
var publishPacket = new MqttPublishPacket
|
||||
{
|
||||
PacketIdentifier = 123,
|
||||
Dup = true,
|
||||
Retain = true,
|
||||
Payload = Encoding.ASCII.GetBytes("Payload"),
|
||||
QualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce,
|
||||
Topic = "Topic",
|
||||
ResponseTopic = "/Response",
|
||||
ContentType = "Content-Type",
|
||||
CorrelationData = Encoding.UTF8.GetBytes("CorrelationData"),
|
||||
TopicAlias = 27,
|
||||
SubscriptionIdentifiers = new List<uint>
|
||||
{
|
||||
123
|
||||
},
|
||||
MessageExpiryInterval = 38,
|
||||
PayloadFormatIndicator = MqttPayloadFormatIndicator.CharacterData,
|
||||
UserProperties = new List<MqttUserProperty>
|
||||
{
|
||||
new MqttUserProperty("Foo", "Bar")
|
||||
}
|
||||
};
|
||||
|
||||
var deserialized = MqttPacketSerializationHelper.EncodeAndDecodePacket(publishPacket, MqttProtocolVersion.V500);
|
||||
|
||||
Assert.AreEqual(publishPacket.PacketIdentifier, deserialized.PacketIdentifier);
|
||||
Assert.AreEqual(publishPacket.Dup, deserialized.Dup);
|
||||
Assert.AreEqual(publishPacket.Retain, deserialized.Retain);
|
||||
CollectionAssert.AreEqual(publishPacket.Payload, deserialized.Payload);
|
||||
Assert.AreEqual(publishPacket.QualityOfServiceLevel, deserialized.QualityOfServiceLevel);
|
||||
Assert.AreEqual(publishPacket.Topic, deserialized.Topic);
|
||||
Assert.AreEqual(publishPacket.ResponseTopic, deserialized.ResponseTopic);
|
||||
Assert.AreEqual(publishPacket.ContentType, deserialized.ContentType);
|
||||
CollectionAssert.AreEqual(publishPacket.CorrelationData, deserialized.CorrelationData);
|
||||
Assert.AreEqual(publishPacket.TopicAlias, deserialized.TopicAlias);
|
||||
CollectionAssert.AreEqual(publishPacket.SubscriptionIdentifiers, deserialized.SubscriptionIdentifiers);
|
||||
Assert.AreEqual(publishPacket.MessageExpiryInterval, deserialized.MessageExpiryInterval);
|
||||
Assert.AreEqual(publishPacket.PayloadFormatIndicator, deserialized.PayloadFormatIndicator);
|
||||
CollectionAssert.AreEqual(publishPacket.UserProperties, deserialized.UserProperties);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Serialize_Full_MqttPubRecPacket_V500()
|
||||
{
|
||||
var pubRecPacket = new MqttPubRecPacket
|
||||
{
|
||||
PacketIdentifier = 123,
|
||||
ReasonCode = MqttPubRecReasonCode.UnspecifiedError,
|
||||
ReasonString = "ReasonString",
|
||||
UserProperties = new List<MqttUserProperty>
|
||||
{
|
||||
new MqttUserProperty("Foo", "Bar")
|
||||
}
|
||||
};
|
||||
|
||||
var deserialized = MqttPacketSerializationHelper.EncodeAndDecodePacket(pubRecPacket, MqttProtocolVersion.V500);
|
||||
|
||||
Assert.AreEqual(pubRecPacket.PacketIdentifier, deserialized.PacketIdentifier);
|
||||
Assert.AreEqual(pubRecPacket.ReasonCode, deserialized.ReasonCode);
|
||||
Assert.AreEqual(pubRecPacket.ReasonString, deserialized.ReasonString);
|
||||
CollectionAssert.AreEqual(pubRecPacket.UserProperties, deserialized.UserProperties);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Serialize_Full_MqttPubRelPacket_V500()
|
||||
{
|
||||
var pubRelPacket = new MqttPubRelPacket
|
||||
{
|
||||
PacketIdentifier = 123,
|
||||
ReasonCode = MqttPubRelReasonCode.PacketIdentifierNotFound,
|
||||
ReasonString = "ReasonString",
|
||||
UserProperties = new List<MqttUserProperty>
|
||||
{
|
||||
new MqttUserProperty("Foo", "Bar")
|
||||
}
|
||||
};
|
||||
|
||||
var deserialized = MqttPacketSerializationHelper.EncodeAndDecodePacket(pubRelPacket, MqttProtocolVersion.V500);
|
||||
|
||||
Assert.AreEqual(pubRelPacket.PacketIdentifier, deserialized.PacketIdentifier);
|
||||
Assert.AreEqual(pubRelPacket.ReasonCode, deserialized.ReasonCode);
|
||||
Assert.AreEqual(pubRelPacket.ReasonString, deserialized.ReasonString);
|
||||
CollectionAssert.AreEqual(pubRelPacket.UserProperties, deserialized.UserProperties);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Serialize_Full_MqttSubAckPacket_V500()
|
||||
{
|
||||
var subAckPacket = new MqttSubAckPacket
|
||||
{
|
||||
PacketIdentifier = 123,
|
||||
ReasonString = "ReasonString",
|
||||
ReasonCodes = new List<MqttSubscribeReasonCode>
|
||||
{
|
||||
MqttSubscribeReasonCode.GrantedQoS1
|
||||
},
|
||||
UserProperties = new List<MqttUserProperty>
|
||||
{
|
||||
new MqttUserProperty("Foo", "Bar")
|
||||
}
|
||||
};
|
||||
|
||||
var deserialized = MqttPacketSerializationHelper.EncodeAndDecodePacket(subAckPacket, MqttProtocolVersion.V500);
|
||||
|
||||
Assert.AreEqual(subAckPacket.PacketIdentifier, deserialized.PacketIdentifier);
|
||||
Assert.AreEqual(subAckPacket.ReasonString, deserialized.ReasonString);
|
||||
Assert.AreEqual(subAckPacket.ReasonCodes.Count, deserialized.ReasonCodes.Count);
|
||||
Assert.AreEqual(subAckPacket.ReasonCodes[0], deserialized.ReasonCodes[0]);
|
||||
CollectionAssert.AreEqual(subAckPacket.UserProperties, deserialized.UserProperties);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Serialize_Full_MqttSubscribePacket_V500()
|
||||
{
|
||||
var subscribePacket = new MqttSubscribePacket
|
||||
{
|
||||
PacketIdentifier = 123,
|
||||
SubscriptionIdentifier = 456,
|
||||
TopicFilters = new List<MqttTopicFilter>
|
||||
{
|
||||
new MqttTopicFilter
|
||||
{
|
||||
Topic = "Topic",
|
||||
NoLocal = true,
|
||||
RetainHandling = MqttRetainHandling.SendAtSubscribeIfNewSubscriptionOnly,
|
||||
RetainAsPublished = true,
|
||||
QualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce
|
||||
}
|
||||
},
|
||||
UserProperties = new List<MqttUserProperty>
|
||||
{
|
||||
new MqttUserProperty("Foo", "Bar")
|
||||
}
|
||||
};
|
||||
|
||||
var deserialized = MqttPacketSerializationHelper.EncodeAndDecodePacket(subscribePacket, MqttProtocolVersion.V500);
|
||||
|
||||
Assert.AreEqual(subscribePacket.PacketIdentifier, deserialized.PacketIdentifier);
|
||||
Assert.AreEqual(subscribePacket.SubscriptionIdentifier, deserialized.SubscriptionIdentifier);
|
||||
Assert.AreEqual(1, deserialized.TopicFilters.Count);
|
||||
Assert.AreEqual(subscribePacket.TopicFilters[0].Topic, deserialized.TopicFilters[0].Topic);
|
||||
Assert.AreEqual(subscribePacket.TopicFilters[0].NoLocal, deserialized.TopicFilters[0].NoLocal);
|
||||
Assert.AreEqual(subscribePacket.TopicFilters[0].RetainHandling, deserialized.TopicFilters[0].RetainHandling);
|
||||
Assert.AreEqual(subscribePacket.TopicFilters[0].RetainAsPublished, deserialized.TopicFilters[0].RetainAsPublished);
|
||||
Assert.AreEqual(subscribePacket.TopicFilters[0].QualityOfServiceLevel, deserialized.TopicFilters[0].QualityOfServiceLevel);
|
||||
CollectionAssert.AreEqual(subscribePacket.UserProperties, deserialized.UserProperties);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Serialize_Full_MqttUnsubAckPacket_V500()
|
||||
{
|
||||
var unsubAckPacket = new MqttUnsubAckPacket
|
||||
{
|
||||
PacketIdentifier = 123,
|
||||
ReasonCodes = new List<MqttUnsubscribeReasonCode>
|
||||
{
|
||||
MqttUnsubscribeReasonCode.ImplementationSpecificError
|
||||
},
|
||||
ReasonString = "ReasonString",
|
||||
UserProperties = new List<MqttUserProperty>
|
||||
{
|
||||
new MqttUserProperty("Foo", "Bar")
|
||||
}
|
||||
};
|
||||
|
||||
var deserialized = MqttPacketSerializationHelper.EncodeAndDecodePacket(unsubAckPacket, MqttProtocolVersion.V500);
|
||||
|
||||
Assert.AreEqual(unsubAckPacket.PacketIdentifier, deserialized.PacketIdentifier);
|
||||
Assert.AreEqual(unsubAckPacket.ReasonString, deserialized.ReasonString);
|
||||
Assert.AreEqual(unsubAckPacket.ReasonCodes.Count, deserialized.ReasonCodes.Count);
|
||||
Assert.AreEqual(unsubAckPacket.ReasonCodes[0], deserialized.ReasonCodes[0]);
|
||||
CollectionAssert.AreEqual(unsubAckPacket.UserProperties, deserialized.UserProperties);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Serialize_Full_MqttUnsubscribePacket_V500()
|
||||
{
|
||||
var unsubscribePacket = new MqttUnsubscribePacket
|
||||
{
|
||||
PacketIdentifier = 123,
|
||||
TopicFilters = new List<string>
|
||||
{
|
||||
"TopicFilter1"
|
||||
},
|
||||
UserProperties = new List<MqttUserProperty>
|
||||
{
|
||||
new MqttUserProperty("Foo", "Bar")
|
||||
}
|
||||
};
|
||||
|
||||
var deserialized = MqttPacketSerializationHelper.EncodeAndDecodePacket(unsubscribePacket, MqttProtocolVersion.V500);
|
||||
|
||||
Assert.AreEqual(unsubscribePacket.PacketIdentifier, deserialized.PacketIdentifier);
|
||||
Assert.AreEqual(unsubscribePacket.TopicFilters.Count, deserialized.TopicFilters.Count);
|
||||
Assert.AreEqual(unsubscribePacket.TopicFilters[0], deserialized.TopicFilters[0]);
|
||||
CollectionAssert.AreEqual(unsubscribePacket.UserProperties, deserialized.UserProperties);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using MQTTnet.Formatter;
|
||||
|
||||
namespace MQTTnet.Tests.Formatter
|
||||
{
|
||||
[TestClass]
|
||||
public sealed class MqttPacketWriter_Tests
|
||||
{
|
||||
[TestMethod]
|
||||
public void Reset_After_Usage()
|
||||
{
|
||||
var writer = new MqttBufferWriter(4096, 65535);
|
||||
writer.WriteString("AString");
|
||||
writer.WriteByte(0x1);
|
||||
writer.WriteByte(0x0);
|
||||
writer.WriteByte(0x1);
|
||||
writer.WriteVariableByteInteger(1234U);
|
||||
writer.WriteVariableByteInteger(9876U);
|
||||
|
||||
writer.Reset(0);
|
||||
|
||||
Assert.AreEqual(0, writer.Length);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Use_All_Data_Types()
|
||||
{
|
||||
var writer = new MqttBufferWriter(4096, 65535);
|
||||
writer.WriteString("AString");
|
||||
writer.WriteByte(0x1);
|
||||
writer.WriteByte(0x0);
|
||||
writer.WriteByte(0x1);
|
||||
writer.WriteVariableByteInteger(1234U);
|
||||
writer.WriteVariableByteInteger(9876U);
|
||||
|
||||
var buffer = writer.GetBuffer();
|
||||
|
||||
var reader = new MqttBufferReader();
|
||||
reader.SetBuffer(buffer, 0, writer.Length);
|
||||
|
||||
Assert.AreEqual("AString", reader.ReadString());
|
||||
Assert.IsTrue(reader.ReadByte() == 1);
|
||||
Assert.IsTrue(reader.ReadByte() == 0);
|
||||
Assert.IsTrue(reader.ReadByte() == 1);
|
||||
Assert.AreEqual(1234U, reader.ReadVariableByteInteger());
|
||||
Assert.AreEqual(9876U, reader.ReadVariableByteInteger());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Write_And_Read_Multiple_Times()
|
||||
{
|
||||
var writer = new MqttBufferWriter(4096, 65535);
|
||||
writer.WriteString("A relative short string.");
|
||||
writer.WriteBinaryData(new byte[1234]);
|
||||
writer.WriteByte(0x01);
|
||||
writer.WriteByte(0x02);
|
||||
writer.WriteVariableByteInteger(5647382);
|
||||
writer.WriteString("A relative short string.");
|
||||
writer.WriteVariableByteInteger(8574489);
|
||||
writer.WriteBinaryData(new byte[48]);
|
||||
writer.WriteByte(2);
|
||||
writer.WriteByte(0x02);
|
||||
writer.WriteString("fjgffiogfhgfhoihgoireghreghreguhreguireoghreouighreouighreughreguiorehreuiohruiorehreuioghreug");
|
||||
writer.WriteBinaryData(new byte[3]);
|
||||
|
||||
var readPayload = new ArraySegment<byte>(writer.GetBuffer(), 0, writer.Length).ToArray();
|
||||
|
||||
var reader = new MqttBufferReader();
|
||||
reader.SetBuffer(readPayload, 0, readPayload.Length);
|
||||
|
||||
for (var i = 0; i < 100000; i++)
|
||||
{
|
||||
reader.Seek(0);
|
||||
|
||||
reader.ReadString();
|
||||
reader.ReadBinaryData();
|
||||
reader.ReadByte();
|
||||
reader.ReadByte();
|
||||
reader.ReadVariableByteInteger();
|
||||
reader.ReadString();
|
||||
reader.ReadVariableByteInteger();
|
||||
reader.ReadBinaryData();
|
||||
reader.ReadByte();
|
||||
reader.ReadByte();
|
||||
reader.ReadString();
|
||||
reader.ReadBinaryData();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using MQTTnet.Internal;
|
||||
|
||||
namespace MQTTnet.Tests.Internal
|
||||
{
|
||||
[TestClass]
|
||||
public class AsyncLock_Tests
|
||||
{
|
||||
[TestMethod]
|
||||
public async Task Lock_Serial_Calls()
|
||||
{
|
||||
var sum = 0;
|
||||
|
||||
var @lock = new AsyncLock();
|
||||
for (var i = 0; i < 100; i++)
|
||||
{
|
||||
using (await @lock.WaitAsync(CancellationToken.None).ConfigureAwait(false))
|
||||
{
|
||||
sum++;
|
||||
}
|
||||
}
|
||||
|
||||
Assert.AreEqual(100, sum);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(TaskCanceledException))]
|
||||
public async Task Test_Cancellation()
|
||||
{
|
||||
var @lock = new AsyncLock();
|
||||
|
||||
// This call will never "release" the lock due to missing _using_.
|
||||
await @lock.WaitAsync(CancellationToken.None).ConfigureAwait(false);
|
||||
|
||||
using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(3)))
|
||||
{
|
||||
await @lock.WaitAsync(cts.Token).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
//[TestMethod]
|
||||
//public async Task Test_Cancellation_With_Later_Access()
|
||||
//{
|
||||
// var @lock = new AsyncLock();
|
||||
|
||||
// var releaser = await @lock.WaitAsync().ConfigureAwait(false);
|
||||
|
||||
// try
|
||||
// {
|
||||
// using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(3)))
|
||||
// {
|
||||
// await @lock.WaitAsync(cts.Token).ConfigureAwait(false);
|
||||
// }
|
||||
// }
|
||||
// catch (OperationCanceledException)
|
||||
// {
|
||||
// }
|
||||
|
||||
// releaser.Dispose();
|
||||
|
||||
// using (await @lock.WaitAsync().ConfigureAwait(false))
|
||||
// {
|
||||
// // When the method finished, the thread got access.
|
||||
// }
|
||||
//}
|
||||
|
||||
[TestMethod]
|
||||
public void Lock_10_Parallel_Tasks()
|
||||
{
|
||||
const int ThreadsCount = 10;
|
||||
|
||||
var threads = new Task[ThreadsCount];
|
||||
var @lock = new AsyncLock();
|
||||
var globalI = 0;
|
||||
for (var i = 0; i < ThreadsCount; i++)
|
||||
{
|
||||
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
|
||||
threads[i] = Task.Run(async () =>
|
||||
{
|
||||
using (var releaser = await @lock.WaitAsync(CancellationToken.None))
|
||||
{
|
||||
var localI = globalI;
|
||||
await Task.Delay(10); // Increase the chance for wrong data.
|
||||
localI++;
|
||||
globalI = localI;
|
||||
}
|
||||
});
|
||||
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
|
||||
}
|
||||
|
||||
Task.WaitAll(threads);
|
||||
Assert.AreEqual(ThreadsCount, globalI);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using MQTTnet.Internal;
|
||||
|
||||
namespace MQTTnet.Tests.Internal
|
||||
{
|
||||
[TestClass]
|
||||
public class AsyncQueue_Tests
|
||||
{
|
||||
[TestMethod]
|
||||
public async Task Preserve_Order()
|
||||
{
|
||||
var queue = new AsyncQueue<string>();
|
||||
queue.Enqueue("1");
|
||||
queue.Enqueue("2");
|
||||
queue.Enqueue("3");
|
||||
|
||||
Assert.AreEqual("1", (await queue.TryDequeueAsync(CancellationToken.None)).Item);
|
||||
Assert.AreEqual("2", (await queue.TryDequeueAsync(CancellationToken.None)).Item);
|
||||
Assert.AreEqual("3", (await queue.TryDequeueAsync(CancellationToken.None)).Item);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Count()
|
||||
{
|
||||
var queue = new AsyncQueue<string>();
|
||||
|
||||
queue.Enqueue("1");
|
||||
Assert.AreEqual(1, queue.Count);
|
||||
|
||||
queue.Enqueue("2");
|
||||
Assert.AreEqual(2, queue.Count);
|
||||
|
||||
queue.Enqueue("3");
|
||||
Assert.AreEqual(3, queue.Count);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Cancellation()
|
||||
{
|
||||
var queue = new AsyncQueue<int>();
|
||||
|
||||
bool success;
|
||||
using (var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(3)))
|
||||
{
|
||||
success = (await queue.TryDequeueAsync(cancellationTokenSource.Token)).IsSuccess;
|
||||
}
|
||||
|
||||
Assert.AreEqual(false, success);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Process_Async()
|
||||
{
|
||||
var queue = new AsyncQueue<int>();
|
||||
|
||||
var sum = 0;
|
||||
var worker = Task.Run(async () =>
|
||||
{
|
||||
while (sum < 6)
|
||||
{
|
||||
sum += (await queue.TryDequeueAsync(CancellationToken.None)).Item;
|
||||
}
|
||||
});
|
||||
|
||||
queue.Enqueue(1);
|
||||
await Task.Delay(500);
|
||||
|
||||
queue.Enqueue(2);
|
||||
await Task.Delay(500);
|
||||
|
||||
queue.Enqueue(3);
|
||||
await Task.Delay(500);
|
||||
|
||||
Assert.AreEqual(6, sum);
|
||||
Assert.AreEqual(TaskStatus.RanToCompletion, worker.Status);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Process_Async_With_Initial_Delay()
|
||||
{
|
||||
var queue = new AsyncQueue<int>();
|
||||
|
||||
var sum = 0;
|
||||
var worker = Task.Run(async () =>
|
||||
{
|
||||
while (sum < 6)
|
||||
{
|
||||
sum += (await queue.TryDequeueAsync(CancellationToken.None)).Item;
|
||||
}
|
||||
});
|
||||
|
||||
// This line is the diff to test _Process_Async_
|
||||
await Task.Delay(500);
|
||||
|
||||
queue.Enqueue(1);
|
||||
await Task.Delay(500);
|
||||
|
||||
queue.Enqueue(2);
|
||||
await Task.Delay(500);
|
||||
|
||||
queue.Enqueue(3);
|
||||
await Task.Delay(500);
|
||||
|
||||
Assert.AreEqual(6, sum);
|
||||
Assert.AreEqual(TaskStatus.RanToCompletion, worker.Status);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Dequeue_Sync()
|
||||
{
|
||||
var queue = new AsyncQueue<string>();
|
||||
queue.Enqueue("1");
|
||||
queue.Enqueue("2");
|
||||
queue.Enqueue("3");
|
||||
|
||||
Assert.AreEqual("1", queue.TryDequeue().Item);
|
||||
Assert.AreEqual("2", queue.TryDequeue().Item);
|
||||
Assert.AreEqual("3", queue.TryDequeue().Item);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Clear()
|
||||
{
|
||||
var queue = new AsyncQueue<string>();
|
||||
queue.Enqueue("1");
|
||||
queue.Enqueue("2");
|
||||
queue.Enqueue("3");
|
||||
|
||||
queue.Clear();
|
||||
Assert.AreEqual(0, queue.Count);
|
||||
|
||||
queue.Enqueue("4");
|
||||
|
||||
Assert.AreEqual(1, queue.Count);
|
||||
Assert.AreEqual("4", queue.TryDequeue().Item);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using MQTTnet.Internal;
|
||||
|
||||
namespace MQTTnet.Tests.Internal
|
||||
{
|
||||
[TestClass]
|
||||
public class BlockingQueue_Tests
|
||||
{
|
||||
[TestMethod]
|
||||
public void Preserve_Order()
|
||||
{
|
||||
var queue = new BlockingQueue<string>();
|
||||
queue.Enqueue("a");
|
||||
queue.Enqueue("b");
|
||||
queue.Enqueue("c");
|
||||
|
||||
Assert.AreEqual(3, queue.Count);
|
||||
|
||||
Assert.AreEqual("a", queue.Dequeue());
|
||||
Assert.AreEqual("b", queue.Dequeue());
|
||||
Assert.AreEqual("c", queue.Dequeue());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Remove_First_Items()
|
||||
{
|
||||
var queue = new BlockingQueue<string>();
|
||||
queue.Enqueue("a");
|
||||
queue.Enqueue("b");
|
||||
queue.Enqueue("c");
|
||||
|
||||
Assert.AreEqual("a", queue.RemoveFirst());
|
||||
Assert.AreEqual("b", queue.RemoveFirst());
|
||||
|
||||
Assert.AreEqual(1, queue.Count);
|
||||
|
||||
Assert.AreEqual("c", queue.Dequeue());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Clear_Items()
|
||||
{
|
||||
var queue = new BlockingQueue<string>();
|
||||
queue.Enqueue("a");
|
||||
queue.Enqueue("b");
|
||||
queue.Enqueue("c");
|
||||
|
||||
Assert.AreEqual(3, queue.Count);
|
||||
|
||||
queue.Clear();
|
||||
|
||||
Assert.AreEqual(0, queue.Count);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Wait_For_Item()
|
||||
{
|
||||
var queue = new BlockingQueue<string>();
|
||||
|
||||
string item = null;
|
||||
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
|
||||
Task.Run(() =>
|
||||
{
|
||||
item = queue.Dequeue();
|
||||
});
|
||||
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
|
||||
|
||||
await Task.Delay(100);
|
||||
|
||||
Assert.AreEqual(0, queue.Count);
|
||||
Assert.AreEqual(null, item);
|
||||
|
||||
queue.Enqueue("x");
|
||||
|
||||
await Task.Delay(100);
|
||||
|
||||
Assert.AreEqual("x", item);
|
||||
Assert.AreEqual(0, queue.Count);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Wait_For_Items()
|
||||
{
|
||||
var number = 0;
|
||||
|
||||
var queue = new BlockingQueue<int>();
|
||||
|
||||
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
|
||||
Task.Run(async () =>
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
queue.Enqueue(1);
|
||||
await Task.Delay(100);
|
||||
}
|
||||
});
|
||||
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
|
||||
|
||||
while (number < 50)
|
||||
{
|
||||
queue.Dequeue();
|
||||
Interlocked.Increment(ref number);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(OperationCanceledException))]
|
||||
public void Use_Disposed_Queue()
|
||||
{
|
||||
var queue = new BlockingQueue<int>();
|
||||
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
|
||||
Task.Run(() =>
|
||||
{
|
||||
Thread.Sleep(1000);
|
||||
queue.Dispose();
|
||||
});
|
||||
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
|
||||
|
||||
queue.Dequeue(new CancellationTokenSource(TimeSpan.FromSeconds(2)).Token);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using MQTTnet.Implementations;
|
||||
|
||||
namespace MQTTnet.Tests.Internal
|
||||
{
|
||||
[TestClass]
|
||||
public class CrossPlatformSocket_Tests
|
||||
{
|
||||
[TestMethod]
|
||||
public async Task Connect_Send_Receive()
|
||||
{
|
||||
var crossPlatformSocket = new CrossPlatformSocket();
|
||||
await crossPlatformSocket.ConnectAsync("www.google.de", 80, CancellationToken.None);
|
||||
|
||||
var requestBuffer = Encoding.UTF8.GetBytes("GET / HTTP/1.1\r\nHost: www.google.de\r\n\r\n");
|
||||
await crossPlatformSocket.SendAsync(new ArraySegment<byte>(requestBuffer), System.Net.Sockets.SocketFlags.None);
|
||||
|
||||
var buffer = new byte[1024];
|
||||
var length = await crossPlatformSocket.ReceiveAsync(new ArraySegment<byte>(buffer), System.Net.Sockets.SocketFlags.None);
|
||||
crossPlatformSocket.Dispose();
|
||||
|
||||
var responseText = Encoding.UTF8.GetString(buffer, 0, length);
|
||||
|
||||
Assert.IsTrue(responseText.Contains("HTTP/1.1 200 OK"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(OperationCanceledException))]
|
||||
public async Task Try_Connect_Invalid_Host()
|
||||
{
|
||||
var crossPlatformSocket = new CrossPlatformSocket();
|
||||
|
||||
var cancellationToken = new CancellationTokenSource(TimeSpan.FromSeconds(5));
|
||||
cancellationToken.Token.Register(() => crossPlatformSocket.Dispose());
|
||||
|
||||
await crossPlatformSocket.ConnectAsync("www.google.de", 54321, cancellationToken.Token);
|
||||
}
|
||||
|
||||
//[TestMethod]
|
||||
//public async Task Use_Disconnected_Socket()
|
||||
//{
|
||||
// var crossPlatformSocket = new CrossPlatformSocket();
|
||||
|
||||
// await crossPlatformSocket.ConnectAsync("www.google.de", 80);
|
||||
|
||||
// var requestBuffer = Encoding.UTF8.GetBytes("GET /wrong_uri HTTP/1.1\r\nConnection: close\r\n\r\n");
|
||||
// await crossPlatformSocket.SendAsync(new ArraySegment<byte>(requestBuffer), System.Net.Sockets.SocketFlags.None);
|
||||
|
||||
// var buffer = new byte[64000];
|
||||
// var length = await crossPlatformSocket.ReceiveAsync(new ArraySegment<byte>(buffer), System.Net.Sockets.SocketFlags.None);
|
||||
|
||||
// await Task.Delay(500);
|
||||
|
||||
// await crossPlatformSocket.SendAsync(new ArraySegment<byte>(requestBuffer), System.Net.Sockets.SocketFlags.None);
|
||||
//}
|
||||
|
||||
[TestMethod]
|
||||
public void Set_Options()
|
||||
{
|
||||
var crossPlatformSocket = new CrossPlatformSocket();
|
||||
|
||||
Assert.IsFalse(crossPlatformSocket.ReuseAddress);
|
||||
crossPlatformSocket.ReuseAddress = true;
|
||||
Assert.IsTrue(crossPlatformSocket.ReuseAddress);
|
||||
|
||||
Assert.IsFalse(crossPlatformSocket.NoDelay);
|
||||
crossPlatformSocket.NoDelay = true;
|
||||
Assert.IsTrue(crossPlatformSocket.NoDelay);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using MQTTnet.Internal;
|
||||
using MQTTnet.Packets;
|
||||
|
||||
namespace MQTTnet.Tests.Internal
|
||||
{
|
||||
[TestClass]
|
||||
public sealed class MqttPacketBus_Tests
|
||||
{
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(OperationCanceledException))]
|
||||
public async Task Wait_With_Empty_Bus()
|
||||
{
|
||||
var bus = new MqttPacketBus();
|
||||
|
||||
using (var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(1)))
|
||||
{
|
||||
await bus.DequeueItemAsync(timeout.Token);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Alternate_Priorities()
|
||||
{
|
||||
var bus = new MqttPacketBus();
|
||||
|
||||
bus.EnqueueItem(new MqttPacketBusItem(new MqttPublishPacket()), MqttPacketBusPartition.Data);
|
||||
bus.EnqueueItem(new MqttPacketBusItem(new MqttPublishPacket()), MqttPacketBusPartition.Data);
|
||||
bus.EnqueueItem(new MqttPacketBusItem(new MqttPublishPacket()), MqttPacketBusPartition.Data);
|
||||
|
||||
bus.EnqueueItem(new MqttPacketBusItem(new MqttSubAckPacket()), MqttPacketBusPartition.Control);
|
||||
bus.EnqueueItem(new MqttPacketBusItem(new MqttSubAckPacket()), MqttPacketBusPartition.Control);
|
||||
bus.EnqueueItem(new MqttPacketBusItem(new MqttSubAckPacket()), MqttPacketBusPartition.Control);
|
||||
|
||||
bus.EnqueueItem(new MqttPacketBusItem(new MqttPingRespPacket()), MqttPacketBusPartition.Health);
|
||||
bus.EnqueueItem(new MqttPacketBusItem(new MqttPingRespPacket()), MqttPacketBusPartition.Health);
|
||||
bus.EnqueueItem(new MqttPacketBusItem(new MqttPingRespPacket()), MqttPacketBusPartition.Health);
|
||||
|
||||
Assert.AreEqual(9, bus.ItemsCount);
|
||||
|
||||
Assert.IsInstanceOfType(bus.DequeueItemAsync(CancellationToken.None).Result.Packet, typeof(MqttPublishPacket));
|
||||
Assert.IsInstanceOfType(bus.DequeueItemAsync(CancellationToken.None).Result.Packet, typeof(MqttSubAckPacket));
|
||||
Assert.IsInstanceOfType(bus.DequeueItemAsync(CancellationToken.None).Result.Packet, typeof(MqttPingRespPacket));
|
||||
Assert.IsInstanceOfType(bus.DequeueItemAsync(CancellationToken.None).Result.Packet, typeof(MqttPublishPacket));
|
||||
Assert.IsInstanceOfType(bus.DequeueItemAsync(CancellationToken.None).Result.Packet, typeof(MqttSubAckPacket));
|
||||
Assert.IsInstanceOfType(bus.DequeueItemAsync(CancellationToken.None).Result.Packet, typeof(MqttPingRespPacket));
|
||||
Assert.IsInstanceOfType(bus.DequeueItemAsync(CancellationToken.None).Result.Packet, typeof(MqttPublishPacket));
|
||||
Assert.IsInstanceOfType(bus.DequeueItemAsync(CancellationToken.None).Result.Packet, typeof(MqttSubAckPacket));
|
||||
Assert.IsInstanceOfType(bus.DequeueItemAsync(CancellationToken.None).Result.Packet, typeof(MqttPingRespPacket));
|
||||
|
||||
Assert.AreEqual(0, bus.ItemsCount);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Export_Packets_Without_Dequeue()
|
||||
{
|
||||
var bus = new MqttPacketBus();
|
||||
|
||||
bus.EnqueueItem(new MqttPacketBusItem(new MqttPublishPacket()), MqttPacketBusPartition.Data);
|
||||
bus.EnqueueItem(new MqttPacketBusItem(new MqttPublishPacket()), MqttPacketBusPartition.Data);
|
||||
bus.EnqueueItem(new MqttPacketBusItem(new MqttPublishPacket()), MqttPacketBusPartition.Data);
|
||||
|
||||
Assert.AreEqual(3, bus.ItemsCount);
|
||||
|
||||
var exportedPackets = bus.ExportPackets(MqttPacketBusPartition.Control);
|
||||
Assert.AreEqual(0, exportedPackets.Count);
|
||||
|
||||
exportedPackets = bus.ExportPackets(MqttPacketBusPartition.Health);
|
||||
Assert.AreEqual(0, exportedPackets.Count);
|
||||
|
||||
exportedPackets = bus.ExportPackets(MqttPacketBusPartition.Data);
|
||||
Assert.AreEqual(3, exportedPackets.Count);
|
||||
|
||||
Assert.AreEqual(3, bus.ItemsCount);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Await_Single_Packet()
|
||||
{
|
||||
var bus = new MqttPacketBus();
|
||||
|
||||
var delivered = false;
|
||||
|
||||
var item1 = new MqttPacketBusItem(new MqttPublishPacket());
|
||||
var item2 = new MqttPacketBusItem(new MqttPublishPacket());
|
||||
|
||||
var item3 = new MqttPacketBusItem(new MqttPublishPacket());
|
||||
item3.Delivered += (_, __) =>
|
||||
{
|
||||
delivered = true;
|
||||
};
|
||||
|
||||
bus.EnqueueItem(item1, MqttPacketBusPartition.Data);
|
||||
bus.EnqueueItem(item2, MqttPacketBusPartition.Data);
|
||||
bus.EnqueueItem(item3, MqttPacketBusPartition.Data);
|
||||
|
||||
Assert.IsFalse(delivered);
|
||||
|
||||
bus.DequeueItemAsync(CancellationToken.None).Result.MarkAsDelivered();
|
||||
|
||||
Assert.IsFalse(delivered);
|
||||
|
||||
bus.DequeueItemAsync(CancellationToken.None).Result.MarkAsDelivered();
|
||||
|
||||
Assert.IsFalse(delivered);
|
||||
|
||||
bus.DequeueItemAsync(CancellationToken.None).Result.MarkAsDelivered();
|
||||
|
||||
// The third packet has the event attached.
|
||||
Assert.IsTrue(delivered);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFrameworks>net452;net461;netcoreapp3.1;net6.0</TargetFrameworks>
|
||||
<IsPackable>false</IsPackable>
|
||||
<LangVersion>7.3</LangVersion>
|
||||
<EnableNETAnalyzers>false</EnableNETAnalyzers>
|
||||
<EnforceCodeStyleInBuild>false</EnforceCodeStyleInBuild>
|
||||
<DisableImplicitAspNetCoreAnalyzers>true</DisableImplicitAspNetCoreAnalyzers>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="MSTest.TestAdapter" Version="2.1.2" />
|
||||
<PackageReference Include="MSTest.TestFramework" Version="2.1.2" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.8.0" />
|
||||
|
||||
<PackageReference Include="Microsoft.CodeAnalysis.Compilers" Version="4.0.1" />
|
||||
<PackageReference Include="Microsoft.Net.Compilers" Version="4.0.1" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\Source\MQTTnet.Extensions.ManagedClient\MQTTnet.Extensions.ManagedClient.csproj" />
|
||||
<ProjectReference Include="..\..\Source\MQTTnet.Extensions.Rpc\MQTTnet.Extensions.Rpc.csproj" />
|
||||
<ProjectReference Include="..\..\Source\MQTTnet\MQTTnet.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,282 @@
|
||||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using MQTTnet.Client;
|
||||
using MQTTnet.Formatter;
|
||||
using MQTTnet.Implementations;
|
||||
using MQTTnet.Packets;
|
||||
using MQTTnet.Protocol;
|
||||
using MQTTnet.Tests.Mockups;
|
||||
|
||||
namespace MQTTnet.Tests.MQTTv5
|
||||
{
|
||||
[TestClass]
|
||||
public sealed class Client_Tests : BaseTestClass
|
||||
{
|
||||
[TestMethod]
|
||||
public async Task Connect_With_New_Mqtt_Features()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
await testEnvironment.StartServer();
|
||||
|
||||
// This test can be also executed against "broker.hivemq.com" to validate package format.
|
||||
var client = await testEnvironment.ConnectClient(
|
||||
new MqttClientOptionsBuilder()
|
||||
//.WithTcpServer("broker.hivemq.com")
|
||||
.WithTcpServer("127.0.0.1", testEnvironment.ServerPort)
|
||||
.WithProtocolVersion(MqttProtocolVersion.V500)
|
||||
.WithTopicAliasMaximum(20)
|
||||
.WithReceiveMaximum(20)
|
||||
.WithWillTopic("abc")
|
||||
.WithWillDelayInterval(20)
|
||||
.Build());
|
||||
|
||||
MqttApplicationMessage receivedMessage = null;
|
||||
|
||||
await client.SubscribeAsync("a");
|
||||
client.ApplicationMessageReceivedAsync += e =>
|
||||
{
|
||||
receivedMessage = e.ApplicationMessage;
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
await client.PublishAsync(new MqttApplicationMessageBuilder()
|
||||
.WithTopic("a")
|
||||
.WithPayload("x")
|
||||
.WithUserProperty("a", "1")
|
||||
.WithUserProperty("b", "2")
|
||||
.WithPayloadFormatIndicator(MqttPayloadFormatIndicator.CharacterData)
|
||||
.WithQualityOfServiceLevel(MqttQualityOfServiceLevel.AtLeastOnce)
|
||||
.Build());
|
||||
|
||||
await Task.Delay(500);
|
||||
|
||||
Assert.IsNotNull(receivedMessage);
|
||||
|
||||
Assert.AreEqual(2, receivedMessage.UserProperties.Count);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Connect()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
await testEnvironment.StartServer();
|
||||
await testEnvironment.ConnectClient(o => o.WithProtocolVersion(MqttProtocolVersion.V500).Build());
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Connect_And_Disconnect()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
await testEnvironment.StartServer();
|
||||
|
||||
var client = await testEnvironment.ConnectClient(o => o.WithProtocolVersion(MqttProtocolVersion.V500));
|
||||
await client.DisconnectAsync();
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Subscribe()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
await testEnvironment.StartServer();
|
||||
|
||||
var client =
|
||||
await testEnvironment.ConnectClient(o => o.WithProtocolVersion(MqttProtocolVersion.V500));
|
||||
|
||||
var result = await client.SubscribeAsync(new MqttClientSubscribeOptions()
|
||||
{
|
||||
SubscriptionIdentifier = 1,
|
||||
TopicFilters = new List<MqttTopicFilter>
|
||||
{
|
||||
new MqttTopicFilter {Topic = "a", QualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce}
|
||||
}
|
||||
});
|
||||
|
||||
await client.DisconnectAsync();
|
||||
|
||||
Assert.AreEqual(1, result.Items.Count);
|
||||
Assert.AreEqual(MqttClientSubscribeResultCode.GrantedQoS1, result.Items.First().ResultCode);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Unsubscribe()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
await testEnvironment.StartServer();
|
||||
|
||||
var client = await testEnvironment.ConnectClient(o => o.WithProtocolVersion(MqttProtocolVersion.V500));
|
||||
await client.SubscribeAsync("a");
|
||||
|
||||
var result = await client.UnsubscribeAsync("a");
|
||||
await client.DisconnectAsync();
|
||||
|
||||
Assert.AreEqual(1, result.Items.Count);
|
||||
Assert.AreEqual(MqttClientUnsubscribeResultCode.Success, result.Items.First().ResultCode);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Publish_QoS_0()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
await testEnvironment.StartServer();
|
||||
|
||||
var client = await testEnvironment.ConnectClient(o => o.WithProtocolVersion(MqttProtocolVersion.V500));
|
||||
var result = await client.PublishStringAsync("a", "b");
|
||||
await client.DisconnectAsync();
|
||||
|
||||
Assert.AreEqual(MqttClientPublishReasonCode.Success, result.ReasonCode);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Publish_QoS_1()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
await testEnvironment.StartServer();
|
||||
|
||||
var client = await testEnvironment.ConnectClient(o => o.WithProtocolVersion(MqttProtocolVersion.V500));
|
||||
var result = await client.PublishStringAsync("a", "b", MqttQualityOfServiceLevel.AtLeastOnce);
|
||||
await client.DisconnectAsync();
|
||||
|
||||
Assert.AreEqual(MqttClientPublishReasonCode.Success, result.ReasonCode);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Publish_QoS_2()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
await testEnvironment.StartServer();
|
||||
|
||||
var client = await testEnvironment.ConnectClient(o => o.WithProtocolVersion(MqttProtocolVersion.V500));
|
||||
var result = await client.PublishStringAsync("a", "b", MqttQualityOfServiceLevel.ExactlyOnce);
|
||||
await client.DisconnectAsync();
|
||||
|
||||
Assert.AreEqual(MqttClientPublishReasonCode.Success, result.ReasonCode);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Publish_With_Properties()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
await testEnvironment.StartServer();
|
||||
|
||||
var client = await testEnvironment.ConnectClient(o => o.WithProtocolVersion(MqttProtocolVersion.V500));
|
||||
|
||||
var applicationMessage = new MqttApplicationMessageBuilder()
|
||||
.WithTopic("Hello")
|
||||
.WithPayload("World")
|
||||
.WithQualityOfServiceLevel(MqttQualityOfServiceLevel.AtMostOnce)
|
||||
.WithUserProperty("x", "1")
|
||||
.WithUserProperty("y", "2")
|
||||
.WithResponseTopic("response")
|
||||
.WithContentType("text")
|
||||
.WithMessageExpiryInterval(50)
|
||||
.WithCorrelationData(new byte[12])
|
||||
.WithTopicAlias(2)
|
||||
.Build();
|
||||
|
||||
var result = await client.PublishAsync(applicationMessage);
|
||||
await client.DisconnectAsync();
|
||||
|
||||
Assert.AreEqual(MqttClientPublishReasonCode.Success, result.ReasonCode);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Subscribe_And_Publish()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
await testEnvironment.StartServer();
|
||||
|
||||
var client1 = await testEnvironment.ConnectClient(o => o.WithProtocolVersion(MqttProtocolVersion.V500).WithClientId("client1"));
|
||||
|
||||
var testMessageHandler = new TestApplicationMessageReceivedHandler(client1);
|
||||
|
||||
await client1.SubscribeAsync("a");
|
||||
|
||||
var client2 = await testEnvironment.ConnectClient(o => o.WithProtocolVersion(MqttProtocolVersion.V500).WithClientId("client2"));
|
||||
await client2.PublishStringAsync("a", "b");
|
||||
|
||||
await Task.Delay(500);
|
||||
|
||||
await client2.DisconnectAsync();
|
||||
await client1.DisconnectAsync();
|
||||
|
||||
Assert.AreEqual(1, testMessageHandler.ReceivedEventArgs.Count);
|
||||
Assert.AreEqual("Subscribe_And_Publish_client1", testMessageHandler.ReceivedEventArgs[0].ClientId);
|
||||
Assert.AreEqual("a", testMessageHandler.ReceivedEventArgs[0].ApplicationMessage.Topic);
|
||||
Assert.AreEqual("b", testMessageHandler.ReceivedEventArgs[0].ApplicationMessage.ConvertPayloadToString());
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Publish_And_Receive_New_Properties()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
await testEnvironment.StartServer();
|
||||
|
||||
var receiver = await testEnvironment.ConnectClient(new MqttClientOptionsBuilder().WithProtocolVersion(MqttProtocolVersion.V500));
|
||||
await receiver.SubscribeAsync("#");
|
||||
|
||||
MqttApplicationMessage receivedMessage = null;
|
||||
receiver.ApplicationMessageReceivedAsync += e =>
|
||||
{
|
||||
receivedMessage = e.ApplicationMessage;
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
var sender = await testEnvironment.ConnectClient(new MqttClientOptionsBuilder().WithProtocolVersion(MqttProtocolVersion.V500));
|
||||
|
||||
var applicationMessage = new MqttApplicationMessageBuilder()
|
||||
.WithTopic("Hello")
|
||||
.WithPayload("World")
|
||||
.WithQualityOfServiceLevel(MqttQualityOfServiceLevel.AtMostOnce)
|
||||
.WithUserProperty("x", "1")
|
||||
.WithUserProperty("y", "2")
|
||||
.WithResponseTopic("response")
|
||||
.WithContentType("text")
|
||||
.WithMessageExpiryInterval(50)
|
||||
.WithCorrelationData(new byte[12])
|
||||
.WithTopicAlias(2)
|
||||
.Build();
|
||||
|
||||
await sender.PublishAsync(applicationMessage);
|
||||
|
||||
await Task.Delay(500);
|
||||
|
||||
Assert.IsNotNull(receivedMessage);
|
||||
Assert.AreEqual(applicationMessage.Topic, receivedMessage.Topic);
|
||||
Assert.AreEqual(applicationMessage.TopicAlias, receivedMessage.TopicAlias);
|
||||
Assert.AreEqual(applicationMessage.ContentType, receivedMessage.ContentType);
|
||||
Assert.AreEqual(applicationMessage.ResponseTopic, receivedMessage.ResponseTopic);
|
||||
Assert.AreEqual(applicationMessage.MessageExpiryInterval, receivedMessage.MessageExpiryInterval);
|
||||
CollectionAssert.AreEqual(applicationMessage.CorrelationData, receivedMessage.CorrelationData);
|
||||
CollectionAssert.AreEqual(applicationMessage.Payload, receivedMessage.Payload);
|
||||
CollectionAssert.AreEqual(applicationMessage.UserProperties, receivedMessage.UserProperties);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using MQTTnet.Client;
|
||||
using MQTTnet.Formatter;
|
||||
using MQTTnet.Tests.Mockups;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using MQTTnet.Implementations;
|
||||
using MQTTnet.Protocol;
|
||||
|
||||
namespace MQTTnet.Tests.MQTTv5
|
||||
{
|
||||
[TestClass]
|
||||
public sealed class Server_Tests : BaseTestClass
|
||||
{
|
||||
[TestMethod]
|
||||
public async Task Will_Message_Send()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
await testEnvironment.StartServer();
|
||||
|
||||
var clientOptions = new MqttClientOptionsBuilder().WithWillTopic("My/last/will").WithWillQualityOfServiceLevel(MqttQualityOfServiceLevel.AtMostOnce).WithProtocolVersion(MqttProtocolVersion.V500);
|
||||
|
||||
var c1 = await testEnvironment.ConnectClient(new MqttClientOptionsBuilder().WithProtocolVersion(MqttProtocolVersion.V500));
|
||||
|
||||
var receivedMessagesCount = 0;
|
||||
c1.ApplicationMessageReceivedAsync += e =>
|
||||
{
|
||||
Interlocked.Increment(ref receivedMessagesCount);
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
await c1.SubscribeAsync(new MqttTopicFilterBuilder().WithTopic("#").Build());
|
||||
|
||||
var c2 = await testEnvironment.ConnectClient(clientOptions);
|
||||
c2.Dispose(); // Dispose will not send a DISCONNECT pattern first so the will message must be sent.
|
||||
|
||||
await Task.Delay(1000);
|
||||
|
||||
Assert.AreEqual(1, receivedMessagesCount);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Validate_IsSessionPresent()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
// Create server with persistent sessions enabled
|
||||
|
||||
await testEnvironment.StartServer(o => o.WithPersistentSessions());
|
||||
|
||||
const string ClientId = "Client1";
|
||||
|
||||
// Create client without clean session and long session expiry interval
|
||||
var options1 = CreateClientOptions(testEnvironment, ClientId, false, 9999);
|
||||
var client1 = await testEnvironment.ConnectClient(options1);
|
||||
|
||||
// Disconnect; empty session should remain on server
|
||||
|
||||
await client1.DisconnectAsync();
|
||||
|
||||
// Simulate some time delay between connections
|
||||
|
||||
await Task.Delay(1000);
|
||||
|
||||
// Reconnect the same client ID to existing session
|
||||
|
||||
var client2 = testEnvironment.CreateClient();
|
||||
var options2 = CreateClientOptions(testEnvironment, ClientId, false, 9999);
|
||||
var result = await client2.ConnectAsync(options2).ConfigureAwait(false);
|
||||
|
||||
await client2.DisconnectAsync();
|
||||
|
||||
// Session should be present
|
||||
|
||||
Assert.IsTrue(result.IsSessionPresent, "Session not present");
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Connect_with_Undefined_SessionExpiryInterval()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
// Create server with persistent sessions enabled
|
||||
|
||||
await testEnvironment.StartServer(o => o.WithPersistentSessions());
|
||||
|
||||
const string ClientId = "Client1";
|
||||
|
||||
// Create client without clean session and NO session expiry interval,
|
||||
// that means, the session should not persist
|
||||
|
||||
var options1 = CreateClientOptions(testEnvironment, ClientId, false, 0);
|
||||
var client1 = await testEnvironment.ConnectClient(options1);
|
||||
|
||||
// Disconnect; no session should remain on server because the session expiry interval was undefined
|
||||
|
||||
await client1.DisconnectAsync();
|
||||
|
||||
// Simulate some time delay between connections
|
||||
|
||||
await Task.Delay(1000);
|
||||
|
||||
// Reconnect the same client ID to existing session
|
||||
|
||||
var client2 = testEnvironment.CreateClient();
|
||||
var options2 = CreateClientOptions(testEnvironment, ClientId, false, 9999);
|
||||
var result = await client2.ConnectAsync(options2).ConfigureAwait(false);
|
||||
|
||||
await client2.DisconnectAsync();
|
||||
|
||||
// Session should not be present
|
||||
|
||||
Assert.IsTrue(!result.IsSessionPresent, "Session is present when it should not");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
[TestMethod]
|
||||
public async Task Reconnect_with_different_SessionExpiryInterval()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
// Create server with persistent sessions enabled
|
||||
|
||||
await testEnvironment.StartServer(o => o.WithPersistentSessions());
|
||||
|
||||
const string ClientId = "Client1";
|
||||
|
||||
// Create client with clean session and session expiry interval > 0
|
||||
|
||||
var options = CreateClientOptions(testEnvironment, ClientId, true, 9999);
|
||||
var client1 = await testEnvironment.ConnectClient(options);
|
||||
|
||||
// Disconnect; session should remain on server
|
||||
|
||||
await client1.DisconnectAsync();
|
||||
|
||||
await Task.Delay(1000);
|
||||
|
||||
// Reconnect the same client ID to the existing session but leave session expiry interval undefined this time.
|
||||
// Session should be present because the client1 connection had SessionExpiryInterval > 0
|
||||
|
||||
var client2 = testEnvironment.CreateClient();
|
||||
var options2 = CreateClientOptions(testEnvironment, ClientId, false, 0);
|
||||
var result2 = await client2.ConnectAsync(options2).ConfigureAwait(false);
|
||||
|
||||
await client2.DisconnectAsync();
|
||||
|
||||
Assert.IsTrue(result2.IsSessionPresent, "Session is not present when it should");
|
||||
|
||||
// Simulate some time delay between connections
|
||||
|
||||
await Task.Delay(1000);
|
||||
|
||||
// Reconnect the same client ID.
|
||||
// No session should be present because the previous session expiry interval was undefined for the client2 connection
|
||||
|
||||
var client3 = testEnvironment.CreateClient();
|
||||
var options3 = CreateClientOptions(testEnvironment, ClientId, false, 0);
|
||||
var result3 = await client2.ConnectAsync(options3).ConfigureAwait(false);
|
||||
|
||||
await client3.DisconnectAsync();
|
||||
|
||||
// Session should be present
|
||||
|
||||
Assert.IsTrue(!result3.IsSessionPresent, "Session is present when it should not");
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
MqttClientOptions CreateClientOptions(TestEnvironment testEnvironment, string clientId, bool cleanSession, uint sessionExpiryInterval)
|
||||
{
|
||||
return testEnvironment.Factory.CreateClientOptionsBuilder()
|
||||
.WithProtocolVersion(MqttProtocolVersion.V500)
|
||||
.WithTcpServer("127.0.0.1", testEnvironment.ServerPort)
|
||||
.WithSessionExpiryInterval(sessionExpiryInterval)
|
||||
.WithCleanSession(cleanSession)
|
||||
.WithClientId(clientId)
|
||||
.Build();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using MQTTnet.Packets;
|
||||
|
||||
namespace MQTTnet.Tests.Mockups
|
||||
{
|
||||
public sealed class MqttPacketAsserts
|
||||
{
|
||||
public void AssertIsConnectPacket(MqttPacket packet)
|
||||
{
|
||||
Assert.AreEqual(packet.GetType(), typeof(MqttConnectPacket));
|
||||
}
|
||||
|
||||
public void AssertIsConnAckPacket(MqttPacket packet)
|
||||
{
|
||||
Assert.AreEqual(packet.GetType(), typeof(MqttConnAckPacket));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using MQTTnet.Client;
|
||||
using MQTTnet.Implementations;
|
||||
|
||||
namespace MQTTnet.Tests.Mockups
|
||||
{
|
||||
public sealed class TestApplicationMessageReceivedHandler
|
||||
{
|
||||
readonly List<MqttApplicationMessageReceivedEventArgs> _receivedEventArgs = new List<MqttApplicationMessageReceivedEventArgs>();
|
||||
|
||||
public TestApplicationMessageReceivedHandler(MqttClient mqttClient)
|
||||
{
|
||||
mqttClient.ApplicationMessageReceivedAsync += MqttClientOnApplicationMessageReceivedAsync;
|
||||
}
|
||||
|
||||
public List<MqttApplicationMessageReceivedEventArgs> ReceivedEventArgs
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_receivedEventArgs)
|
||||
{
|
||||
return _receivedEventArgs.ToList();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void AssertReceivedCountEquals(int expectedCount)
|
||||
{
|
||||
lock (_receivedEventArgs)
|
||||
{
|
||||
Assert.AreEqual(expectedCount, _receivedEventArgs.Count);
|
||||
}
|
||||
}
|
||||
|
||||
Task MqttClientOnApplicationMessageReceivedAsync(MqttApplicationMessageReceivedEventArgs eventArgs)
|
||||
{
|
||||
lock (_receivedEventArgs)
|
||||
{
|
||||
_receivedEventArgs.Add(eventArgs);
|
||||
}
|
||||
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,381 @@
|
||||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using MQTTnet.Client;
|
||||
using MQTTnet.Diagnostics;
|
||||
using MQTTnet.Extensions.Rpc;
|
||||
using MQTTnet.Formatter;
|
||||
using MQTTnet.Implementations;
|
||||
using MQTTnet.LowLevelClient;
|
||||
using MQTTnet.Protocol;
|
||||
using MQTTnet.Server;
|
||||
using MqttClient = MQTTnet.Client.MqttClient;
|
||||
|
||||
namespace MQTTnet.Tests.Mockups
|
||||
{
|
||||
public sealed class TestEnvironment : IDisposable
|
||||
{
|
||||
readonly List<string> _clientErrors = new List<string>();
|
||||
readonly List<MqttClient> _clients = new List<MqttClient>();
|
||||
|
||||
readonly List<Exception> _exceptions = new List<Exception>();
|
||||
readonly List<LowLevelMqttClient> _lowLevelClients = new List<LowLevelMqttClient>();
|
||||
readonly MqttProtocolVersion _protocolVersion;
|
||||
readonly List<string> _serverErrors = new List<string>();
|
||||
|
||||
public TestEnvironment() : this(null)
|
||||
{
|
||||
}
|
||||
|
||||
public TestEnvironment(TestContext testContext, MqttProtocolVersion protocolVersion = MqttProtocolVersion.V311)
|
||||
{
|
||||
_protocolVersion = protocolVersion;
|
||||
TestContext = testContext;
|
||||
|
||||
ServerLogger.LogMessagePublished += (s, e) =>
|
||||
{
|
||||
if (Debugger.IsAttached)
|
||||
{
|
||||
Debug.WriteLine(e.LogMessage.ToString());
|
||||
}
|
||||
|
||||
if (e.LogMessage.Level == MqttNetLogLevel.Error)
|
||||
{
|
||||
lock (_serverErrors)
|
||||
{
|
||||
_serverErrors.Add(e.LogMessage.ToString());
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
ClientLogger.LogMessagePublished += (s, e) =>
|
||||
{
|
||||
if (Debugger.IsAttached)
|
||||
{
|
||||
Debug.WriteLine(e.LogMessage.ToString());
|
||||
}
|
||||
|
||||
if (e.LogMessage.Level == MqttNetLogLevel.Error)
|
||||
{
|
||||
lock (_clientErrors)
|
||||
{
|
||||
_clientErrors.Add(e.LogMessage.ToString());
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public MqttNetEventLogger ClientLogger { get; } = new MqttNetEventLogger("client");
|
||||
|
||||
public static bool EnableLogger { get; set; } = true;
|
||||
|
||||
public MqttFactory Factory { get; } = new MqttFactory();
|
||||
|
||||
public bool IgnoreClientLogErrors { get; set; }
|
||||
|
||||
public bool IgnoreServerLogErrors { get; set; }
|
||||
|
||||
public MqttServer Server { get; private set; }
|
||||
|
||||
public MqttNetEventLogger ServerLogger { get; } = new MqttNetEventLogger("server");
|
||||
|
||||
public int ServerPort { get; set; }
|
||||
|
||||
public TestContext TestContext { get; }
|
||||
|
||||
public Task<MqttClient> ConnectClient()
|
||||
{
|
||||
return ConnectClient(Factory.CreateClientOptionsBuilder().WithProtocolVersion(_protocolVersion));
|
||||
}
|
||||
|
||||
public async Task<MqttClient> ConnectClient(Action<MqttClientOptionsBuilder> optionsBuilder, TimeSpan timeout = default)
|
||||
{
|
||||
if (optionsBuilder == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(optionsBuilder));
|
||||
}
|
||||
|
||||
var options = Factory.CreateClientOptionsBuilder().WithProtocolVersion(_protocolVersion).WithTcpServer("127.0.0.1", ServerPort);
|
||||
|
||||
optionsBuilder.Invoke(options);
|
||||
|
||||
var client = CreateClient();
|
||||
|
||||
if (timeout == TimeSpan.Zero)
|
||||
{
|
||||
await client.ConnectAsync(options.Build()).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
using (var timeoutToken = new CancellationTokenSource(timeout))
|
||||
{
|
||||
await client.ConnectAsync(options.Build(), timeoutToken.Token).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
return client;
|
||||
}
|
||||
|
||||
public async Task<MqttClient> ConnectClient(MqttClientOptionsBuilder options, TimeSpan timeout = default)
|
||||
{
|
||||
if (options == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(options));
|
||||
}
|
||||
|
||||
options = options.WithTcpServer("127.0.0.1", ServerPort);
|
||||
|
||||
var client = CreateClient();
|
||||
|
||||
if (timeout == TimeSpan.Zero)
|
||||
{
|
||||
await client.ConnectAsync(options.Build()).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
using (var timeoutToken = new CancellationTokenSource(timeout))
|
||||
{
|
||||
await client.ConnectAsync(options.Build(), timeoutToken.Token).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
return client;
|
||||
}
|
||||
|
||||
public async Task<MqttClient> ConnectClient(MqttClientOptions options, TimeSpan timeout = default)
|
||||
{
|
||||
if (options == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(options));
|
||||
}
|
||||
|
||||
var client = CreateClient();
|
||||
|
||||
if (timeout == TimeSpan.Zero)
|
||||
{
|
||||
await client.ConnectAsync(options).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
using (var timeoutToken = new CancellationTokenSource(timeout))
|
||||
{
|
||||
await client.ConnectAsync(options, timeoutToken.Token).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
return client;
|
||||
}
|
||||
|
||||
public async Task<LowLevelMqttClient> ConnectLowLevelClient(Action<MqttClientOptionsBuilder> optionsBuilder = null)
|
||||
{
|
||||
var options = new MqttClientOptionsBuilder();
|
||||
options = options.WithTcpServer("127.0.0.1", ServerPort);
|
||||
optionsBuilder?.Invoke(options);
|
||||
|
||||
var client = CreateLowLevelClient();
|
||||
await client.ConnectAsync(options.Build(), CancellationToken.None).ConfigureAwait(false);
|
||||
|
||||
return client;
|
||||
}
|
||||
|
||||
public async Task<MqttRpcClient> ConnectRpcClient(MqttRpcClientOptions options)
|
||||
{
|
||||
return new MqttRpcClient(await ConnectClient(), options);
|
||||
}
|
||||
|
||||
public TestApplicationMessageReceivedHandler CreateApplicationMessageHandler(MqttClient mqttClient)
|
||||
{
|
||||
return new TestApplicationMessageReceivedHandler(mqttClient);
|
||||
}
|
||||
|
||||
public MqttClient CreateClient()
|
||||
{
|
||||
lock (_clients)
|
||||
{
|
||||
var logger = EnableLogger ? (IMqttNetLogger)ClientLogger : new MqttNetNullLogger();
|
||||
|
||||
var client = Factory.CreateMqttClient(logger);
|
||||
_clients.Add(client);
|
||||
|
||||
client.ConnectingAsync += e =>
|
||||
{
|
||||
if (TestContext != null)
|
||||
{
|
||||
var clientOptions = e.ClientOptions;
|
||||
var existingClientId = clientOptions.ClientId;
|
||||
if (existingClientId != null && !existingClientId.StartsWith(TestContext.TestName))
|
||||
{
|
||||
clientOptions.ClientId = TestContext.TestName + "_" + existingClientId;
|
||||
}
|
||||
}
|
||||
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
return client;
|
||||
}
|
||||
}
|
||||
|
||||
public LowLevelMqttClient CreateLowLevelClient()
|
||||
{
|
||||
lock (_clients)
|
||||
{
|
||||
var client = Factory.CreateLowLevelMqttClient(ClientLogger);
|
||||
_lowLevelClients.Add(client);
|
||||
|
||||
return client;
|
||||
}
|
||||
}
|
||||
|
||||
public MqttServer CreateServer(MqttServerOptions options)
|
||||
{
|
||||
if (Server != null)
|
||||
{
|
||||
throw new InvalidOperationException("Server already started.");
|
||||
}
|
||||
|
||||
var logger = EnableLogger ? (IMqttNetLogger)ServerLogger : new MqttNetNullLogger();
|
||||
|
||||
Server = Factory.CreateMqttServer(options, logger);
|
||||
|
||||
Server.ValidatingConnectionAsync += e =>
|
||||
{
|
||||
if (TestContext != null)
|
||||
{
|
||||
// Null is used when the client id is assigned from the server!
|
||||
if (!string.IsNullOrEmpty(e.ClientId) && !e.ClientId.StartsWith(TestContext.TestName))
|
||||
{
|
||||
TrackException(new InvalidOperationException($"Invalid client ID used ({e.ClientId}). It must start with UnitTest name."));
|
||||
e.ReasonCode = MqttConnectReasonCode.ClientIdentifierNotValid;
|
||||
}
|
||||
}
|
||||
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
return Server;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
foreach (var mqttClient in _clients)
|
||||
{
|
||||
try
|
||||
{
|
||||
//mqttClient.DisconnectAsync().GetAwaiter().GetResult();
|
||||
}
|
||||
catch
|
||||
{
|
||||
// This can happen when the test already disconnected the client.
|
||||
}
|
||||
finally
|
||||
{
|
||||
mqttClient?.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var lowLevelMqttClient in _lowLevelClients)
|
||||
{
|
||||
lowLevelMqttClient.Dispose();
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
Server?.StopAsync().GetAwaiter().GetResult();
|
||||
}
|
||||
catch
|
||||
{
|
||||
// This can happen when the test already stopped the server.
|
||||
}
|
||||
finally
|
||||
{
|
||||
Server?.Dispose();
|
||||
}
|
||||
|
||||
ThrowIfLogErrors();
|
||||
|
||||
if (_exceptions.Any())
|
||||
{
|
||||
throw new Exception($"{_exceptions.Count} exceptions tracked.\r\n" + string.Join(Environment.NewLine, _exceptions));
|
||||
}
|
||||
}
|
||||
|
||||
public Task<MqttServer> StartServer()
|
||||
{
|
||||
return StartServer(Factory.CreateServerOptionsBuilder());
|
||||
}
|
||||
|
||||
public async Task<MqttServer> StartServer(MqttServerOptionsBuilder optionsBuilder)
|
||||
{
|
||||
optionsBuilder.WithDefaultEndpoint();
|
||||
optionsBuilder.WithDefaultEndpointPort(ServerPort);
|
||||
optionsBuilder.WithMaxPendingMessagesPerClient(int.MaxValue);
|
||||
|
||||
var options = optionsBuilder.Build();
|
||||
var server = CreateServer(options);
|
||||
await server.StartAsync();
|
||||
|
||||
// The OS has chosen the port to we have to properly expose it to the tests.
|
||||
ServerPort = options.DefaultEndpointOptions.Port;
|
||||
return server;
|
||||
}
|
||||
|
||||
public async Task<MqttServer> StartServer(Action<MqttServerOptionsBuilder> configure)
|
||||
{
|
||||
var optionsBuilder = Factory.CreateServerOptionsBuilder();
|
||||
|
||||
optionsBuilder.WithDefaultEndpoint();
|
||||
optionsBuilder.WithDefaultEndpointPort(ServerPort);
|
||||
optionsBuilder.WithMaxPendingMessagesPerClient(int.MaxValue);
|
||||
|
||||
configure?.Invoke(optionsBuilder);
|
||||
|
||||
var options = optionsBuilder.Build();
|
||||
var server = CreateServer(options);
|
||||
await server.StartAsync();
|
||||
|
||||
// The OS has chosen the port to we have to properly expose it to the tests.
|
||||
ServerPort = options.DefaultEndpointOptions.Port;
|
||||
return server;
|
||||
}
|
||||
|
||||
public void ThrowIfLogErrors()
|
||||
{
|
||||
lock (_serverErrors)
|
||||
{
|
||||
if (!IgnoreServerLogErrors && _serverErrors.Count > 0)
|
||||
{
|
||||
var message = $"Server had {_serverErrors.Count} errors (${string.Join(Environment.NewLine, _serverErrors)}).";
|
||||
Console.WriteLine(message);
|
||||
throw new Exception(message);
|
||||
}
|
||||
}
|
||||
|
||||
lock (_clientErrors)
|
||||
{
|
||||
if (!IgnoreClientLogErrors && _clientErrors.Count > 0)
|
||||
{
|
||||
var message = $"Client(s) had {_clientErrors.Count} errors (${string.Join(Environment.NewLine, _clientErrors)})";
|
||||
Console.WriteLine(message);
|
||||
throw new Exception(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void TrackException(Exception exception)
|
||||
{
|
||||
lock (_exceptions)
|
||||
{
|
||||
_exceptions.Add(exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System;
|
||||
using MQTTnet.Diagnostics;
|
||||
|
||||
namespace MQTTnet.Tests.Mockups
|
||||
{
|
||||
public sealed class TestLogger : IMqttNetLogger
|
||||
{
|
||||
public event EventHandler<MqttNetLogMessagePublishedEventArgs> LogMessagePublished;
|
||||
|
||||
public bool IsEnabled { get; } = true;
|
||||
|
||||
public void Publish(MqttNetLogLevel logLevel, string source, string message, object[] parameters, Exception exception)
|
||||
{
|
||||
LogMessagePublished?.Invoke(this, new MqttNetLogMessagePublishedEventArgs(new MqttNetLogMessage
|
||||
{
|
||||
Level = logLevel,
|
||||
Message = string.Format(message, parameters),
|
||||
Exception = exception
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using MQTTnet.Protocol;
|
||||
|
||||
namespace MQTTnet.Tests
|
||||
{
|
||||
[TestClass]
|
||||
public class MqttApplicationMessageBuilder_Tests
|
||||
{
|
||||
[TestMethod]
|
||||
public void CreateApplicationMessage_TopicOnly()
|
||||
{
|
||||
var message = new MqttApplicationMessageBuilder().WithTopic("Abc").Build();
|
||||
Assert.AreEqual("Abc", message.Topic);
|
||||
Assert.IsFalse(message.Retain);
|
||||
Assert.AreEqual(MqttQualityOfServiceLevel.AtMostOnce, message.QualityOfServiceLevel);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CreateApplicationMessage_TimeStampPayload()
|
||||
{
|
||||
var message = new MqttApplicationMessageBuilder().WithTopic("xyz").WithPayload(TimeSpan.FromSeconds(360).ToString()).Build();
|
||||
Assert.AreEqual("xyz", message.Topic);
|
||||
Assert.IsFalse(message.Retain);
|
||||
Assert.AreEqual(MqttQualityOfServiceLevel.AtMostOnce, message.QualityOfServiceLevel);
|
||||
Assert.AreEqual(Encoding.UTF8.GetString(message.Payload), "00:06:00");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CreateApplicationMessage_StreamPayload()
|
||||
{
|
||||
var stream = new MemoryStream(Encoding.UTF8.GetBytes("xHello")) { Position = 1 };
|
||||
|
||||
var message = new MqttApplicationMessageBuilder().WithTopic("123").WithPayload(stream).Build();
|
||||
Assert.AreEqual("123", message.Topic);
|
||||
Assert.IsFalse(message.Retain);
|
||||
Assert.AreEqual(MqttQualityOfServiceLevel.AtMostOnce, message.QualityOfServiceLevel);
|
||||
Assert.AreEqual(Encoding.UTF8.GetString(message.Payload), "Hello");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CreateApplicationMessage_Retained()
|
||||
{
|
||||
var message = new MqttApplicationMessageBuilder().WithTopic("lol").WithRetainFlag().Build();
|
||||
Assert.AreEqual("lol", message.Topic);
|
||||
Assert.IsTrue(message.Retain);
|
||||
Assert.AreEqual(MqttQualityOfServiceLevel.AtMostOnce, message.QualityOfServiceLevel);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CreateApplicationMessage_QosLevel2()
|
||||
{
|
||||
var message = new MqttApplicationMessageBuilder().WithTopic("rofl").WithRetainFlag().WithQualityOfServiceLevel(MqttQualityOfServiceLevel.ExactlyOnce).Build();
|
||||
Assert.AreEqual("rofl", message.Topic);
|
||||
Assert.IsTrue(message.Retain);
|
||||
Assert.AreEqual(MqttQualityOfServiceLevel.ExactlyOnce, message.QualityOfServiceLevel);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using MQTTnet.Client;
|
||||
|
||||
namespace MQTTnet.Tests
|
||||
{
|
||||
[TestClass]
|
||||
public class MqttPacketIdentifierProvider_Tests
|
||||
{
|
||||
[TestMethod]
|
||||
public void Reset()
|
||||
{
|
||||
var p = new MqttPacketIdentifierProvider();
|
||||
Assert.AreEqual(1, p.GetNextPacketIdentifier());
|
||||
Assert.AreEqual(2, p.GetNextPacketIdentifier());
|
||||
p.Reset();
|
||||
Assert.AreEqual(1, p.GetNextPacketIdentifier());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ReachBoundaries()
|
||||
{
|
||||
var p = new MqttPacketIdentifierProvider();
|
||||
|
||||
for (ushort i = 0; i < ushort.MaxValue; i++)
|
||||
{
|
||||
Assert.AreEqual(i + 1, p.GetNextPacketIdentifier());
|
||||
}
|
||||
|
||||
Assert.AreEqual(1, p.GetNextPacketIdentifier());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
using System;
|
||||
using System.Threading;
|
||||
using MQTTnet.Adapter;
|
||||
using MQTTnet.Diagnostics;
|
||||
using MQTTnet.Formatter;
|
||||
using MQTTnet.Internal;
|
||||
using MQTTnet.Packets;
|
||||
|
||||
namespace MQTTnet.Tests
|
||||
{
|
||||
public sealed class MqttPacketSerializationHelper : IDisposable
|
||||
{
|
||||
readonly IMqttPacketFormatter _packetFormatter;
|
||||
readonly MqttProtocolVersion _protocolVersion;
|
||||
|
||||
public MqttPacketSerializationHelper(MqttProtocolVersion protocolVersion = MqttProtocolVersion.V311, MqttBufferWriter bufferWriter = null)
|
||||
{
|
||||
_protocolVersion = protocolVersion;
|
||||
|
||||
if (bufferWriter == null)
|
||||
{
|
||||
bufferWriter = new MqttBufferWriter(4096, 65535);
|
||||
}
|
||||
|
||||
_packetFormatter = MqttPacketFormatterAdapter.GetMqttPacketFormatter(_protocolVersion, bufferWriter);
|
||||
}
|
||||
|
||||
public MqttPacket Decode(MqttPacketBuffer buffer)
|
||||
{
|
||||
using (var channel = new TestMqttChannel(buffer.ToArray()))
|
||||
{
|
||||
var formatterAdapter = new MqttPacketFormatterAdapter(_protocolVersion, new MqttBufferWriter(4096, 65535));
|
||||
|
||||
var adapter = new MqttChannelAdapter(channel, formatterAdapter, null, MqttNetNullLogger.Instance);
|
||||
return adapter.ReceivePacketAsync(CancellationToken.None).GetAwaiter().GetResult();
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
}
|
||||
|
||||
public MqttPacketBuffer Encode(MqttPacket packet)
|
||||
{
|
||||
return _packetFormatter.Encode(packet);
|
||||
}
|
||||
|
||||
public static TPacket EncodeAndDecodePacket<TPacket>(TPacket packet, MqttProtocolVersion protocolVersion) where TPacket : MqttPacket
|
||||
{
|
||||
using (var helper = new MqttPacketSerializationHelper(protocolVersion))
|
||||
{
|
||||
var buffer = helper.Encode(packet);
|
||||
return (TPacket)helper.Decode(buffer);
|
||||
}
|
||||
}
|
||||
|
||||
public static byte[] EncodePacket(MqttPacket packet)
|
||||
{
|
||||
using (var helper = new MqttPacketSerializationHelper())
|
||||
{
|
||||
return helper.Encode(packet).ToArray();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using MQTTnet.Formatter;
|
||||
|
||||
namespace MQTTnet.Tests
|
||||
{
|
||||
[TestClass]
|
||||
public class MqttPacketWriter_Tests
|
||||
{
|
||||
protected virtual MqttBufferWriter WriterFactory()
|
||||
{
|
||||
return new MqttBufferWriter(4096, 65535);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void WritePacket()
|
||||
{
|
||||
var writer = WriterFactory();
|
||||
Assert.AreEqual(0, writer.Length);
|
||||
|
||||
writer.WriteString("1234567890");
|
||||
Assert.AreEqual(10 + 2, writer.Length);
|
||||
|
||||
writer.WriteBinaryData(new byte[300]);
|
||||
Assert.AreEqual(300 + 2 + 12, writer.Length);
|
||||
|
||||
writer.WriteBinaryData(new byte[5000]);
|
||||
Assert.AreEqual(5000 + 2 + 300 + 2 + 12, writer.Length);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using MQTTnet.Implementations;
|
||||
using System;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MQTTnet.Tests
|
||||
{
|
||||
[TestClass]
|
||||
public class MqttTcpChannel_Tests
|
||||
{
|
||||
[TestMethod]
|
||||
public async Task Dispose_Channel_While_Used()
|
||||
{
|
||||
var ct = new CancellationTokenSource();
|
||||
var serverSocket = new CrossPlatformSocket(AddressFamily.InterNetwork);
|
||||
|
||||
try
|
||||
{
|
||||
serverSocket.Bind(new IPEndPoint(IPAddress.Any, 50001));
|
||||
serverSocket.Listen(0);
|
||||
|
||||
#pragma warning disable 4014
|
||||
Task.Run(async () =>
|
||||
#pragma warning restore 4014
|
||||
{
|
||||
while (!ct.IsCancellationRequested)
|
||||
{
|
||||
var client = await serverSocket.AcceptAsync();
|
||||
var data = new byte[] { 128 };
|
||||
await client.SendAsync(new ArraySegment<byte>(data), SocketFlags.None);
|
||||
}
|
||||
}, ct.Token);
|
||||
|
||||
var clientSocket = new CrossPlatformSocket(AddressFamily.InterNetwork);
|
||||
await clientSocket.ConnectAsync("localhost", 50001, CancellationToken.None);
|
||||
|
||||
var tcpChannel = new MqttTcpChannel(clientSocket.GetStream(), "test", null);
|
||||
|
||||
await Task.Delay(100, ct.Token);
|
||||
|
||||
var buffer = new byte[1];
|
||||
await tcpChannel.ReadAsync(buffer, 0, 1, ct.Token);
|
||||
|
||||
Assert.AreEqual(128, buffer[0]);
|
||||
|
||||
// This block should fail after dispose.
|
||||
#pragma warning disable 4014
|
||||
Task.Run(() =>
|
||||
#pragma warning restore 4014
|
||||
{
|
||||
Task.Delay(200, ct.Token);
|
||||
tcpChannel.Dispose();
|
||||
}, ct.Token);
|
||||
|
||||
try
|
||||
{
|
||||
await tcpChannel.ReadAsync(buffer, 0, 1, CancellationToken.None);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
Assert.IsInstanceOfType(exception, typeof(SocketException));
|
||||
Assert.AreEqual(SocketError.OperationAborted, ((SocketException)exception).SocketErrorCode);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
ct.Cancel(false);
|
||||
serverSocket.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using MQTTnet.Exceptions;
|
||||
using MQTTnet.Protocol;
|
||||
|
||||
namespace MQTTnet.Tests
|
||||
{
|
||||
[TestClass]
|
||||
public class MqttTopicValidatorSubscribe_Tests
|
||||
{
|
||||
[TestMethod]
|
||||
public void Valid_Topic()
|
||||
{
|
||||
MqttTopicValidator.ThrowIfInvalidSubscribe("/a/b/c");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Valid_Topic_Plus_In_Between()
|
||||
{
|
||||
MqttTopicValidator.ThrowIfInvalidSubscribe("/a/+/c");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Valid_Topic_Plus_Last_Char()
|
||||
{
|
||||
MqttTopicValidator.ThrowIfInvalidSubscribe("/a/+");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Valid_Topic_Hash_Last_Char()
|
||||
{
|
||||
MqttTopicValidator.ThrowIfInvalidSubscribe("/a/#");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Valid_Topic_Only_Hash()
|
||||
{
|
||||
MqttTopicValidator.ThrowIfInvalidSubscribe("#");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(MqttProtocolViolationException))]
|
||||
public void Invalid_Topic_Hash_In_Between()
|
||||
{
|
||||
MqttTopicValidator.ThrowIfInvalidSubscribe("/a/#/c");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(MqttProtocolViolationException))]
|
||||
public void Invalid_Topic_Empty()
|
||||
{
|
||||
MqttTopicValidator.ThrowIfInvalidSubscribe(string.Empty);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using MQTTnet.Exceptions;
|
||||
using MQTTnet.Protocol;
|
||||
|
||||
namespace MQTTnet.Tests
|
||||
{
|
||||
[TestClass]
|
||||
public class MqttTopicValidator_Tests
|
||||
{
|
||||
[TestMethod]
|
||||
public void Valid_Topic()
|
||||
{
|
||||
MqttTopicValidator.ThrowIfInvalid("/a/b/c");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(MqttProtocolViolationException))]
|
||||
public void Invalid_Topic_Plus()
|
||||
{
|
||||
MqttTopicValidator.ThrowIfInvalid("/a/+/c");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(MqttProtocolViolationException))]
|
||||
public void Invalid_Topic_Hash()
|
||||
{
|
||||
MqttTopicValidator.ThrowIfInvalid("/a/#/c");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(MqttProtocolViolationException))]
|
||||
public void Invalid_Topic_Empty()
|
||||
{
|
||||
MqttTopicValidator.ThrowIfInvalid(string.Empty);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using MQTTnet.Formatter;
|
||||
|
||||
namespace MQTTnet.Tests
|
||||
{
|
||||
[TestClass]
|
||||
public class Protocol_Tests
|
||||
{
|
||||
[TestMethod]
|
||||
public void Encode_Four_Byte_Integer()
|
||||
{
|
||||
var writer = new MqttBufferWriter(4, 4);
|
||||
|
||||
for (uint value = 0; value < 268435455; value++)
|
||||
{
|
||||
writer.WriteVariableByteInteger(value);
|
||||
|
||||
var buffer = writer.GetBuffer();
|
||||
|
||||
var reader = new MqttBufferReader();
|
||||
reader.SetBuffer(buffer, 0, writer.Length);
|
||||
var checkValue = reader.ReadVariableByteInteger();
|
||||
|
||||
Assert.AreEqual(value, checkValue);
|
||||
|
||||
writer.Reset(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using MQTTnet.Tests.Mockups;
|
||||
using MQTTnet.Client;
|
||||
using MQTTnet.Exceptions;
|
||||
using MQTTnet.Extensions.Rpc;
|
||||
using MQTTnet.Protocol;
|
||||
using MQTTnet.Formatter;
|
||||
using MQTTnet.Implementations;
|
||||
|
||||
namespace MQTTnet.Tests
|
||||
{
|
||||
[TestClass]
|
||||
public sealed class RPC_Tests : BaseTestClass
|
||||
{
|
||||
[TestMethod]
|
||||
public Task Execute_Success_With_QoS_0()
|
||||
{
|
||||
return Execute_Success(MqttQualityOfServiceLevel.AtMostOnce, MqttProtocolVersion.V311);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public Task Execute_Success_With_QoS_1()
|
||||
{
|
||||
return Execute_Success(MqttQualityOfServiceLevel.AtLeastOnce, MqttProtocolVersion.V311);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public Task Execute_Success_With_QoS_2()
|
||||
{
|
||||
return Execute_Success(MqttQualityOfServiceLevel.ExactlyOnce, MqttProtocolVersion.V311);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public Task Execute_Success_With_QoS_0_MQTT_V5()
|
||||
{
|
||||
return Execute_Success(MqttQualityOfServiceLevel.AtMostOnce, MqttProtocolVersion.V500);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public Task Execute_Success_With_QoS_1_MQTT_V5()
|
||||
{
|
||||
return Execute_Success(MqttQualityOfServiceLevel.AtLeastOnce, MqttProtocolVersion.V500);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public Task Execute_Success_With_QoS_2_MQTT_V5()
|
||||
{
|
||||
return Execute_Success(MqttQualityOfServiceLevel.ExactlyOnce, MqttProtocolVersion.V500);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public Task Execute_Success_With_QoS_0_MQTT_V5_Use_ResponseTopic()
|
||||
{
|
||||
return Execute_Success_MQTT_V5(MqttQualityOfServiceLevel.AtMostOnce);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public Task Execute_Success_With_QoS_1_MQTT_V5_Use_ResponseTopic()
|
||||
{
|
||||
return Execute_Success_MQTT_V5(MqttQualityOfServiceLevel.AtLeastOnce);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public Task Execute_Success_With_QoS_2_MQTT_V5_Use_ResponseTopic()
|
||||
{
|
||||
return Execute_Success_MQTT_V5(MqttQualityOfServiceLevel.ExactlyOnce);
|
||||
}
|
||||
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(MqttCommunicationTimedOutException))]
|
||||
public async Task Execute_Timeout()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
await testEnvironment.StartServer();
|
||||
|
||||
var requestSender = await testEnvironment.ConnectClient();
|
||||
|
||||
var rpcClient = new MqttRpcClient(requestSender, new MqttRpcClientOptionsBuilder().Build());
|
||||
await rpcClient.ExecuteAsync(TimeSpan.FromSeconds(2), "ping", "", MqttQualityOfServiceLevel.AtMostOnce);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(MqttCommunicationTimedOutException))]
|
||||
public async Task Execute_With_Custom_Topic_Names()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
await testEnvironment.StartServer();
|
||||
|
||||
var requestSender = await testEnvironment.ConnectClient();
|
||||
|
||||
var rpcClient = await testEnvironment.ConnectRpcClient(new MqttRpcClientOptionsBuilder().WithTopicGenerationStrategy(new TestTopicStrategy()).Build());
|
||||
|
||||
await rpcClient.ExecuteAsync(TimeSpan.FromSeconds(2), "ping", "", MqttQualityOfServiceLevel.AtMostOnce);
|
||||
}
|
||||
}
|
||||
|
||||
async Task Execute_Success(MqttQualityOfServiceLevel qosLevel, MqttProtocolVersion protocolVersion)
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
await testEnvironment.StartServer();
|
||||
var responseSender = await testEnvironment.ConnectClient(new MqttClientOptionsBuilder().WithProtocolVersion(protocolVersion));
|
||||
await responseSender.SubscribeAsync("MQTTnet.RPC/+/ping", qosLevel);
|
||||
|
||||
responseSender.ApplicationMessageReceivedAsync += e => responseSender.PublishStringAsync(e.ApplicationMessage.Topic + "/response", "pong");
|
||||
|
||||
var requestSender = await testEnvironment.ConnectClient();
|
||||
|
||||
using (var rpcClient = new MqttRpcClient(requestSender, new MqttRpcClientOptionsBuilder().Build()))
|
||||
{
|
||||
var response = await rpcClient.ExecuteAsync(TimeSpan.FromSeconds(5), "ping", "", qosLevel);
|
||||
|
||||
Assert.AreEqual("pong", Encoding.UTF8.GetString(response));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async Task Execute_Success_MQTT_V5(MqttQualityOfServiceLevel qosLevel)
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
await testEnvironment.StartServer();
|
||||
var responseSender = await testEnvironment.ConnectClient(new MqttClientOptionsBuilder().WithProtocolVersion(MqttProtocolVersion.V500));
|
||||
await responseSender.SubscribeAsync("MQTTnet.RPC/+/ping", qosLevel);
|
||||
|
||||
responseSender.ApplicationMessageReceivedAsync += async e =>
|
||||
{
|
||||
await responseSender.PublishStringAsync(e.ApplicationMessage.ResponseTopic, "pong");
|
||||
};
|
||||
|
||||
var requestSender = await testEnvironment.ConnectClient(new MqttClientOptionsBuilder().WithProtocolVersion(MqttProtocolVersion.V500));
|
||||
|
||||
using (var rpcClient = new MqttRpcClient(requestSender, new MqttRpcClientOptionsBuilder().Build()))
|
||||
{
|
||||
var response = await rpcClient.ExecuteAsync(TimeSpan.FromSeconds(5), "ping", "", qosLevel);
|
||||
|
||||
Assert.AreEqual("pong", Encoding.UTF8.GetString(response));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Execute_Success_MQTT_V5_Mixed_Clients()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
await testEnvironment.StartServer();
|
||||
var responseSender = await testEnvironment.ConnectClient();
|
||||
await responseSender.SubscribeAsync("MQTTnet.RPC/+/ping", MqttQualityOfServiceLevel.AtMostOnce);
|
||||
|
||||
responseSender.ApplicationMessageReceivedAsync += async e =>
|
||||
{
|
||||
Assert.IsNull(e.ApplicationMessage.ResponseTopic);
|
||||
await responseSender.PublishStringAsync(e.ApplicationMessage.Topic + "/response", "pong");
|
||||
};
|
||||
|
||||
var requestSender = await testEnvironment.ConnectClient(new MqttClientOptionsBuilder().WithProtocolVersion(MqttProtocolVersion.V500));
|
||||
|
||||
using (var rpcClient = new MqttRpcClient(requestSender, new MqttRpcClientOptionsBuilder().Build()))
|
||||
{
|
||||
var response = await rpcClient.ExecuteAsync(TimeSpan.FromSeconds(5), "ping", "", MqttQualityOfServiceLevel.AtMostOnce);
|
||||
|
||||
Assert.AreEqual("pong", Encoding.UTF8.GetString(response));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(MqttCommunicationTimedOutException))]
|
||||
public async Task Execute_Timeout_MQTT_V5_Mixed_Clients()
|
||||
{
|
||||
using (var testEnvironment = new TestEnvironment(TestContext))
|
||||
{
|
||||
await testEnvironment.StartServer();
|
||||
var responseSender = await testEnvironment.ConnectClient();
|
||||
await responseSender.SubscribeAsync("MQTTnet.RPC/+/ping", MqttQualityOfServiceLevel.AtMostOnce);
|
||||
|
||||
responseSender.ApplicationMessageReceivedAsync += async e =>
|
||||
{
|
||||
Assert.IsNull(e.ApplicationMessage.ResponseTopic);
|
||||
await PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
var requestSender = await testEnvironment.ConnectClient(new MqttClientOptionsBuilder().WithProtocolVersion(MqttProtocolVersion.V500));
|
||||
|
||||
using (var rpcClient = new MqttRpcClient(requestSender, new MqttRpcClientOptionsBuilder().Build()))
|
||||
{
|
||||
var response = await rpcClient.ExecuteAsync(TimeSpan.FromSeconds(2), "ping", "", MqttQualityOfServiceLevel.AtMostOnce);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class TestTopicStrategy : IMqttRpcClientTopicGenerationStrategy
|
||||
{
|
||||
public MqttRpcTopicPair CreateRpcTopics(TopicGenerationContext context)
|
||||
{
|
||||
return new MqttRpcTopicPair
|
||||
{
|
||||
RequestTopic = "a",
|
||||
ResponseTopic = "b"
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using MQTTnet.Client;
|
||||
using MQTTnet.Implementations;
|
||||
using MQTTnet.Tests.Mockups;
|
||||
|
||||
namespace MQTTnet.Tests
|
||||
{
|
||||
[TestClass]
|
||||
public class RoundtripTime_Tests
|
||||
{
|
||||
public TestContext TestContext { get; set; }
|
||||
|
||||
[TestMethod]
|
||||
public async Task Round_Trip_Time()
|
||||
{
|
||||
using (var testEnvironment = new TestEnvironment(TestContext))
|
||||
{
|
||||
await testEnvironment.StartServer();
|
||||
|
||||
var receiverClient = await testEnvironment.ConnectClient();
|
||||
var senderClient = await testEnvironment.ConnectClient();
|
||||
|
||||
TaskCompletionSource<string> response = null;
|
||||
|
||||
receiverClient.ApplicationMessageReceivedAsync += e =>
|
||||
{
|
||||
response?.TrySetResult(e.ApplicationMessage.ConvertPayloadToString());
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
await receiverClient.SubscribeAsync("#");
|
||||
|
||||
var times = new List<TimeSpan>();
|
||||
var stopwatch = Stopwatch.StartNew();
|
||||
|
||||
await Task.Delay(1000);
|
||||
|
||||
for (var i = 0; i < 100; i++)
|
||||
{
|
||||
response = new TaskCompletionSource<string>();
|
||||
await senderClient.PublishStringAsync("test", DateTime.UtcNow.Ticks.ToString());
|
||||
if (!response.Task.Wait(TimeSpan.FromSeconds(5)))
|
||||
{
|
||||
throw new TimeoutException();
|
||||
}
|
||||
|
||||
stopwatch.Stop();
|
||||
times.Add(stopwatch.Elapsed);
|
||||
stopwatch.Restart();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using MQTTnet.Client;
|
||||
using MQTTnet.Formatter;
|
||||
using MQTTnet.Implementations;
|
||||
using MQTTnet.Protocol;
|
||||
|
||||
namespace MQTTnet.Tests.Server
|
||||
{
|
||||
[TestClass]
|
||||
public sealed class Assigned_Client_ID_Tests : BaseTestClass
|
||||
{
|
||||
[TestMethod]
|
||||
public Task Connect_With_No_Client_Id()
|
||||
{
|
||||
return Connect_With_Client_Id("test_123", "test_123", null, "test_123");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public Task Connect_With_Client_Id()
|
||||
{
|
||||
return Connect_With_Client_Id("Connect_With_Client_Id_test_456", null, "test_456", null);
|
||||
}
|
||||
|
||||
async Task Connect_With_Client_Id(string expectedClientId, string expectedReturnedClientId, string usedClientId, string assignedClientId)
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
string serverConnectedClientId = null;
|
||||
string serverDisconnectedClientId = null;
|
||||
string clientAssignedClientId = null;
|
||||
|
||||
// Arrange server
|
||||
var disconnectedMre = new ManualResetEventSlim();
|
||||
|
||||
var server = await testEnvironment.StartServer();
|
||||
server.ValidatingConnectionAsync += e =>
|
||||
{
|
||||
if (string.IsNullOrEmpty(e.ClientId))
|
||||
{
|
||||
e.AssignedClientIdentifier = assignedClientId;
|
||||
e.ReasonCode = MqttConnectReasonCode.Success;
|
||||
}
|
||||
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
testEnvironment.Server.ClientConnectedAsync += args =>
|
||||
{
|
||||
serverConnectedClientId = args.ClientId;
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
testEnvironment.Server.ClientDisconnectedAsync += args =>
|
||||
{
|
||||
serverDisconnectedClientId = args.ClientId;
|
||||
disconnectedMre.Set();
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
// Arrange client
|
||||
var client = testEnvironment.CreateClient();
|
||||
client.ConnectedAsync += args =>
|
||||
{
|
||||
clientAssignedClientId = args.ConnectResult.AssignedClientIdentifier;
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
// Act
|
||||
await client.ConnectAsync(new MqttClientOptionsBuilder()
|
||||
.WithTcpServer("127.0.0.1", testEnvironment.ServerPort)
|
||||
.WithProtocolVersion(MqttProtocolVersion.V500)
|
||||
.WithClientId(usedClientId)
|
||||
.Build());
|
||||
|
||||
await client.DisconnectAsync();
|
||||
|
||||
// Wait for ClientDisconnectedHandler to trigger
|
||||
disconnectedMre.Wait(1000);
|
||||
|
||||
// Assert
|
||||
Assert.AreEqual(expectedClientId, serverConnectedClientId);
|
||||
Assert.AreEqual(expectedClientId, serverDisconnectedClientId);
|
||||
Assert.AreEqual(expectedReturnedClientId, clientAssignedClientId);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using MQTTnet.Implementations;
|
||||
using MQTTnet.Server;
|
||||
|
||||
namespace MQTTnet.Tests.Server
|
||||
{
|
||||
[TestClass]
|
||||
public sealed class Connection_Tests : BaseTestClass
|
||||
{
|
||||
[TestMethod]
|
||||
public async Task Close_Idle_Connection_On_Connect()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
await testEnvironment.StartServer(new MqttServerOptionsBuilder().WithDefaultCommunicationTimeout(TimeSpan.FromSeconds(1)));
|
||||
|
||||
var client = new CrossPlatformSocket(AddressFamily.InterNetwork);
|
||||
await client.ConnectAsync("localhost", testEnvironment.ServerPort, CancellationToken.None);
|
||||
|
||||
// Don't send anything. The server should close the connection.
|
||||
await Task.Delay(TimeSpan.FromSeconds(3));
|
||||
|
||||
try
|
||||
{
|
||||
var receivedBytes = await client.ReceiveAsync(new ArraySegment<byte>(new byte[10]), SocketFlags.Partial);
|
||||
if (receivedBytes == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
Assert.Fail("Receive should throw an exception.");
|
||||
}
|
||||
catch (SocketException)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Send_Garbage()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
await testEnvironment.StartServer(new MqttServerOptionsBuilder().WithDefaultCommunicationTimeout(TimeSpan.FromSeconds(1)));
|
||||
|
||||
// Send an invalid packet and ensure that the server will close the connection and stay in a waiting state
|
||||
// forever. This is security related.
|
||||
var client = new CrossPlatformSocket(AddressFamily.InterNetwork);
|
||||
await client.ConnectAsync("localhost", testEnvironment.ServerPort, CancellationToken.None);
|
||||
|
||||
var buffer = Encoding.UTF8.GetBytes("Garbage");
|
||||
await client.SendAsync(new ArraySegment<byte>(buffer), SocketFlags.None);
|
||||
|
||||
await Task.Delay(TimeSpan.FromSeconds(3));
|
||||
|
||||
try
|
||||
{
|
||||
var receivedBytes = await client.ReceiveAsync(new ArraySegment<byte>(new byte[10]), SocketFlags.Partial);
|
||||
if (receivedBytes == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
Assert.Fail("Receive should throw an exception.");
|
||||
}
|
||||
catch (SocketException)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using MQTTnet.Client;
|
||||
using MQTTnet.Formatter;
|
||||
using MQTTnet.Implementations;
|
||||
using MQTTnet.Protocol;
|
||||
using MQTTnet.Server;
|
||||
|
||||
namespace MQTTnet.Tests.Server
|
||||
{
|
||||
[TestClass]
|
||||
public sealed class Events_Tests : BaseTestClass
|
||||
{
|
||||
[TestMethod]
|
||||
public async Task Fire_Client_Connected_Event()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
var server = await testEnvironment.StartServer();
|
||||
|
||||
ClientConnectedEventArgs eventArgs = null;
|
||||
server.ClientConnectedAsync += e =>
|
||||
{
|
||||
eventArgs = e;
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
await testEnvironment.ConnectClient(o => o.WithCredentials("TheUser"));
|
||||
|
||||
await LongTestDelay();
|
||||
|
||||
Assert.IsNotNull(eventArgs);
|
||||
|
||||
Assert.IsTrue(eventArgs.ClientId.StartsWith(nameof(Fire_Client_Connected_Event)));
|
||||
Assert.IsTrue(eventArgs.Endpoint.Contains("127.0.0.1"));
|
||||
Assert.AreEqual(MqttProtocolVersion.V311, eventArgs.ProtocolVersion);
|
||||
Assert.AreEqual("TheUser", eventArgs.UserName);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Fire_Client_Disconnected_Event()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
var server = await testEnvironment.StartServer();
|
||||
|
||||
ClientDisconnectedEventArgs eventArgs = null;
|
||||
server.ClientDisconnectedAsync += e =>
|
||||
{
|
||||
eventArgs = e;
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
var client = await testEnvironment.ConnectClient(o => o.WithCredentials("TheUser"));
|
||||
await client.DisconnectAsync();
|
||||
|
||||
await LongTestDelay();
|
||||
|
||||
Assert.IsNotNull(eventArgs);
|
||||
|
||||
Assert.IsTrue(eventArgs.ClientId.StartsWith(nameof(Fire_Client_Disconnected_Event)));
|
||||
Assert.IsTrue(eventArgs.Endpoint.Contains("127.0.0.1"));
|
||||
Assert.AreEqual(MqttClientDisconnectType.Clean, eventArgs.DisconnectType);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Fire_Client_Subscribed_Event()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
var server = await testEnvironment.StartServer();
|
||||
|
||||
ClientSubscribedTopicEventArgs eventArgs = null;
|
||||
server.ClientSubscribedTopicAsync += e =>
|
||||
{
|
||||
eventArgs = e;
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
var client = await testEnvironment.ConnectClient();
|
||||
await client.SubscribeAsync("The/Topic", MqttQualityOfServiceLevel.AtLeastOnce);
|
||||
|
||||
await LongTestDelay();
|
||||
|
||||
Assert.IsNotNull(eventArgs);
|
||||
|
||||
Assert.IsTrue(eventArgs.ClientId.StartsWith(nameof(Fire_Client_Subscribed_Event)));
|
||||
Assert.AreEqual("The/Topic", eventArgs.TopicFilter.Topic);
|
||||
Assert.AreEqual(MqttQualityOfServiceLevel.AtLeastOnce, eventArgs.TopicFilter.QualityOfServiceLevel);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Fire_Client_Unsubscribed_Event()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
var server = await testEnvironment.StartServer();
|
||||
|
||||
ClientUnsubscribedTopicEventArgs eventArgs = null;
|
||||
server.ClientUnsubscribedTopicAsync += e =>
|
||||
{
|
||||
eventArgs = e;
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
var client = await testEnvironment.ConnectClient();
|
||||
await client.UnsubscribeAsync("The/Topic");
|
||||
|
||||
await LongTestDelay();
|
||||
|
||||
Assert.IsNotNull(eventArgs);
|
||||
|
||||
Assert.IsTrue(eventArgs.ClientId.StartsWith(nameof(Fire_Client_Unsubscribed_Event)));
|
||||
Assert.AreEqual("The/Topic", eventArgs.TopicFilter);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Fire_Application_Message_Received_Event()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
var server = await testEnvironment.StartServer();
|
||||
|
||||
InterceptingPublishEventArgs eventArgs = null;
|
||||
server.InterceptingPublishAsync += e =>
|
||||
{
|
||||
eventArgs = e;
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
var client = await testEnvironment.ConnectClient();
|
||||
await client.PublishStringAsync("The_Topic", "The_Payload");
|
||||
|
||||
await LongTestDelay();
|
||||
|
||||
Assert.IsNotNull(eventArgs);
|
||||
|
||||
Assert.IsTrue(eventArgs.ClientId.StartsWith(nameof(Fire_Application_Message_Received_Event)));
|
||||
Assert.AreEqual("The_Topic", eventArgs.ApplicationMessage.Topic);
|
||||
Assert.AreEqual("The_Payload", eventArgs.ApplicationMessage.ConvertPayloadToString());
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Fire_Started_Event()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
var server = testEnvironment.CreateServer(new MqttServerOptions());
|
||||
|
||||
EventArgs eventArgs = null;
|
||||
server.StartedAsync += e =>
|
||||
{
|
||||
eventArgs = e;
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
await server.StartAsync();
|
||||
|
||||
await LongTestDelay();
|
||||
|
||||
Assert.IsNotNull(eventArgs);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Fire_Stopped_Event()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
var server = await testEnvironment.StartServer();
|
||||
|
||||
EventArgs eventArgs = null;
|
||||
server.StoppedAsync += e =>
|
||||
{
|
||||
eventArgs = e;
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
await server.StopAsync();
|
||||
|
||||
await LongTestDelay();
|
||||
|
||||
Assert.IsNotNull(eventArgs);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,64 @@
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using MQTTnet.Client;
|
||||
using MQTTnet.Server;
|
||||
|
||||
namespace MQTTnet.Tests.Server
|
||||
{
|
||||
[TestClass]
|
||||
public sealed class Injection_Tests : BaseTestClass
|
||||
{
|
||||
[TestMethod]
|
||||
public async Task Inject_Application_Message_At_Session_Level()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
var server = await testEnvironment.StartServer();
|
||||
var receiver1 = await testEnvironment.ConnectClient();
|
||||
var receiver2 = await testEnvironment.ConnectClient();
|
||||
var messageReceivedHandler1 = testEnvironment.CreateApplicationMessageHandler(receiver1);
|
||||
var messageReceivedHandler2 = testEnvironment.CreateApplicationMessageHandler(receiver2);
|
||||
|
||||
var status = await server.GetSessionsAsync();
|
||||
var clientStatus = status[0];
|
||||
|
||||
await receiver1.SubscribeAsync("#");
|
||||
await receiver2.SubscribeAsync("#");
|
||||
|
||||
await clientStatus.EnqueueApplicationMessageAsync(new MqttApplicationMessageBuilder().WithTopic("InjectedOne").Build());
|
||||
|
||||
await LongTestDelay();
|
||||
|
||||
Assert.AreEqual(1, messageReceivedHandler1.ReceivedEventArgs.Count);
|
||||
Assert.AreEqual("InjectedOne", messageReceivedHandler1.ReceivedEventArgs[0].ApplicationMessage.Topic);
|
||||
|
||||
// The second receiver should NOT receive the message.
|
||||
Assert.AreEqual(0, messageReceivedHandler2.ReceivedEventArgs.Count);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Inject_ApplicationMessage_At_Server_Level()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
var server = await testEnvironment.StartServer();
|
||||
|
||||
var receiver = await testEnvironment.ConnectClient();
|
||||
|
||||
var messageReceivedHandler = testEnvironment.CreateApplicationMessageHandler(receiver);
|
||||
|
||||
await receiver.SubscribeAsync("#");
|
||||
|
||||
var injectedApplicationMessage = new MqttApplicationMessageBuilder().WithTopic("InjectedOne").Build();
|
||||
|
||||
await server.InjectApplicationMessage(new InjectedMqttApplicationMessage(injectedApplicationMessage));
|
||||
|
||||
await LongTestDelay();
|
||||
|
||||
Assert.AreEqual(1, messageReceivedHandler.ReceivedEventArgs.Count);
|
||||
Assert.AreEqual("InjectedOne", messageReceivedHandler.ReceivedEventArgs[0].ApplicationMessage.Topic);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using MQTTnet.Formatter;
|
||||
using MQTTnet.Packets;
|
||||
using MQTTnet.Protocol;
|
||||
|
||||
namespace MQTTnet.Tests.Server
|
||||
{
|
||||
[TestClass]
|
||||
public sealed class KeepAlive_Tests : BaseTestClass
|
||||
{
|
||||
[TestMethod]
|
||||
public async Task Disconnect_Client_DueTo_KeepAlive()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
await testEnvironment.StartServer();
|
||||
|
||||
var client = await testEnvironment.ConnectLowLevelClient(o => o
|
||||
.WithTimeout(TimeSpan.FromSeconds(1))
|
||||
.WithTimeout(TimeSpan.Zero)
|
||||
.WithProtocolVersion(MqttProtocolVersion.V500)).ConfigureAwait(false);
|
||||
|
||||
await client.SendAsync(new MqttConnectPacket
|
||||
{
|
||||
CleanSession = true,
|
||||
ClientId = "Disconnect_Client_DueTo_KeepAlive",
|
||||
KeepAlivePeriod = 1
|
||||
}, CancellationToken.None).ConfigureAwait(false);
|
||||
|
||||
var responsePacket = await client.ReceiveAsync(CancellationToken.None).ConfigureAwait(false);
|
||||
Assert.IsTrue(responsePacket is MqttConnAckPacket);
|
||||
|
||||
for (var i = 0; i < 6; i++)
|
||||
{
|
||||
await Task.Delay(500);
|
||||
|
||||
await client.SendAsync(MqttPingReqPacket.Instance, CancellationToken.None);
|
||||
responsePacket = await client.ReceiveAsync(CancellationToken.None);
|
||||
Assert.IsTrue(responsePacket is MqttPingRespPacket);
|
||||
}
|
||||
|
||||
// If we reach this point everything works as expected (server did not close the connection
|
||||
// due to proper ping messages.
|
||||
// Now we will wait 1.1 seconds because the server MUST wait 1.5 seconds in total (See spec).
|
||||
|
||||
await Task.Delay(1100);
|
||||
await client.SendAsync(MqttPingReqPacket.Instance, CancellationToken.None);
|
||||
responsePacket = await client.ReceiveAsync(CancellationToken.None);
|
||||
Assert.IsTrue(responsePacket is MqttPingRespPacket);
|
||||
|
||||
// Now we will wait longer than 1.5 so that the server will close the connection.
|
||||
responsePacket = await client.ReceiveAsync(CancellationToken.None);
|
||||
|
||||
var disconnectPacket = responsePacket as MqttDisconnectPacket;
|
||||
|
||||
Assert.IsTrue(disconnectPacket != null);
|
||||
Assert.AreEqual(disconnectPacket.ReasonCode, MqttDisconnectReasonCode.KeepAliveTimeout);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using MQTTnet.Client;
|
||||
using MQTTnet.Implementations;
|
||||
using MQTTnet.Packets;
|
||||
using MQTTnet.Protocol;
|
||||
|
||||
namespace MQTTnet.Tests.Server
|
||||
{
|
||||
[TestClass]
|
||||
public sealed class Load_Tests : BaseTestClass
|
||||
{
|
||||
[TestMethod]
|
||||
public async Task Handle_100_000_Messages_In_Receiving_Client()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
await testEnvironment.StartServer();
|
||||
|
||||
var receivedMessages = 0;
|
||||
|
||||
using (var receiverClient = await testEnvironment.ConnectClient())
|
||||
{
|
||||
receiverClient.ApplicationMessageReceivedAsync += e =>
|
||||
{
|
||||
Interlocked.Increment(ref receivedMessages);
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
await receiverClient.SubscribeAsync("t/+");
|
||||
|
||||
|
||||
for (var i = 0; i < 100; i++)
|
||||
{
|
||||
_ = Task.Run(
|
||||
async () =>
|
||||
{
|
||||
using (var client = await testEnvironment.ConnectClient())
|
||||
{
|
||||
var applicationMessageBuilder = new MqttApplicationMessageBuilder();
|
||||
|
||||
for (var j = 0; j < 1000; j++)
|
||||
{
|
||||
var message = applicationMessageBuilder.WithTopic("t/" + j)
|
||||
.Build();
|
||||
|
||||
await client.PublishAsync(message)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await client.DisconnectAsync();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
SpinWait.SpinUntil(() => receivedMessages == 100000, TimeSpan.FromSeconds(60));
|
||||
|
||||
Assert.AreEqual(100000, receivedMessages);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Handle_100_000_Messages_In_Low_Level_Client()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
var server = await testEnvironment.StartServer();
|
||||
|
||||
var receivedMessages = 0;
|
||||
|
||||
server.InterceptingPublishAsync += e =>
|
||||
{
|
||||
Interlocked.Increment(ref receivedMessages);
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
for (var i = 0; i < 100; i++)
|
||||
{
|
||||
_ = Task.Run(
|
||||
async () =>
|
||||
{
|
||||
try
|
||||
{
|
||||
using (var client = await testEnvironment.ConnectLowLevelClient())
|
||||
{
|
||||
await client.SendAsync(
|
||||
new MqttConnectPacket
|
||||
{
|
||||
ClientId = "Handle_100_000_Messages_In_Low_Level_Client_" + Guid.NewGuid()
|
||||
}, CancellationToken.None);
|
||||
|
||||
var packet = await client.ReceiveAsync(CancellationToken.None);
|
||||
|
||||
var connAckPacket = packet as MqttConnAckPacket;
|
||||
|
||||
Assert.IsTrue(connAckPacket != null);
|
||||
Assert.AreEqual(MqttConnectReasonCode.Success, connAckPacket.ReasonCode);
|
||||
|
||||
var publishPacket = new MqttPublishPacket();
|
||||
|
||||
for (var j = 0; j < 1000; j++)
|
||||
{
|
||||
publishPacket.Topic = j.ToString();
|
||||
|
||||
await client.SendAsync(publishPacket, CancellationToken.None)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await client.DisconnectAsync(CancellationToken.None);
|
||||
}
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
Console.WriteLine(exception);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
SpinWait.SpinUntil(() => receivedMessages == 100000, TimeSpan.FromSeconds(10));
|
||||
|
||||
Assert.AreEqual(100000, receivedMessages);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Handle_100_000_Messages_In_Server()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
var server = await testEnvironment.StartServer();
|
||||
|
||||
var receivedMessages = 0;
|
||||
|
||||
server.InterceptingPublishAsync += e =>
|
||||
{
|
||||
Interlocked.Increment(ref receivedMessages);
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
for (var i = 0; i < 100; i++)
|
||||
{
|
||||
_ = Task.Run(
|
||||
async () =>
|
||||
{
|
||||
using (var client = await testEnvironment.ConnectClient())
|
||||
{
|
||||
var applicationMessageBuilder = new MqttApplicationMessageBuilder();
|
||||
|
||||
for (var j = 0; j < 1000; j++)
|
||||
{
|
||||
var message = applicationMessageBuilder.WithTopic(j.ToString())
|
||||
.Build();
|
||||
|
||||
await client.PublishAsync(message)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await client.DisconnectAsync();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
SpinWait.SpinUntil(() => receivedMessages == 100000, TimeSpan.FromSeconds(10));
|
||||
|
||||
Assert.AreEqual(100000, receivedMessages);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using MQTTnet.Packets;
|
||||
using MQTTnet.Protocol;
|
||||
using MQTTnet.Server;
|
||||
using MQTTnet.Tests.Mockups;
|
||||
|
||||
namespace MQTTnet.Tests.Server
|
||||
{
|
||||
[TestClass]
|
||||
public sealed class MqttSubscriptionsManager_Tests : BaseTestClass
|
||||
{
|
||||
MqttClientSubscriptionsManager _subscriptionsManager;
|
||||
|
||||
[TestMethod]
|
||||
public async Task MqttSubscriptionsManager_SubscribeAndUnsubscribeSingle()
|
||||
{
|
||||
var sp = new MqttSubscribePacket
|
||||
{
|
||||
TopicFilters = new List<MqttTopicFilter>
|
||||
{
|
||||
new MqttTopicFilterBuilder().WithTopic("A/B/C").Build()
|
||||
}
|
||||
};
|
||||
|
||||
await _subscriptionsManager.Subscribe(sp, CancellationToken.None);
|
||||
|
||||
Assert.IsTrue(CheckSubscriptions("A/B/C", MqttQualityOfServiceLevel.AtMostOnce, "").IsSubscribed);
|
||||
|
||||
var up = new MqttUnsubscribePacket();
|
||||
up.TopicFilters.Add("A/B/C");
|
||||
await _subscriptionsManager.Unsubscribe(up, CancellationToken.None);
|
||||
|
||||
Assert.IsFalse(CheckSubscriptions("A/B/C", MqttQualityOfServiceLevel.AtMostOnce, "").IsSubscribed);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task MqttSubscriptionsManager_SubscribeDifferentQoSSuccess()
|
||||
{
|
||||
var sp = new MqttSubscribePacket
|
||||
{
|
||||
TopicFilters = new List<MqttTopicFilter>
|
||||
{
|
||||
new MqttTopicFilter { Topic = "A/B/C", QualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce }
|
||||
}
|
||||
};
|
||||
|
||||
await _subscriptionsManager.Subscribe(sp, CancellationToken.None);
|
||||
|
||||
var result = CheckSubscriptions("A/B/C", MqttQualityOfServiceLevel.ExactlyOnce, "");
|
||||
Assert.IsTrue(result.IsSubscribed);
|
||||
Assert.AreEqual(result.QualityOfServiceLevel, MqttQualityOfServiceLevel.AtMostOnce);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task MqttSubscriptionsManager_SubscribeSingleNoSuccess()
|
||||
{
|
||||
var sp = new MqttSubscribePacket
|
||||
{
|
||||
TopicFilters = new List<MqttTopicFilter>
|
||||
{
|
||||
new MqttTopicFilterBuilder().WithTopic("A/B/C").Build()
|
||||
}
|
||||
};
|
||||
|
||||
await _subscriptionsManager.Subscribe(sp, CancellationToken.None);
|
||||
|
||||
Assert.IsFalse(CheckSubscriptions("A/B/X", MqttQualityOfServiceLevel.AtMostOnce, "").IsSubscribed);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task MqttSubscriptionsManager_SubscribeSingleSuccess()
|
||||
{
|
||||
var sp = new MqttSubscribePacket
|
||||
{
|
||||
TopicFilters = new List<MqttTopicFilter>
|
||||
{
|
||||
new MqttTopicFilterBuilder().WithTopic("A/B/C").Build()
|
||||
}
|
||||
};
|
||||
|
||||
await _subscriptionsManager.Subscribe(sp, CancellationToken.None);
|
||||
|
||||
var result = CheckSubscriptions("A/B/C", MqttQualityOfServiceLevel.AtMostOnce, "");
|
||||
|
||||
Assert.IsTrue(result.IsSubscribed);
|
||||
Assert.AreEqual(result.QualityOfServiceLevel, MqttQualityOfServiceLevel.AtMostOnce);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task MqttSubscriptionsManager_SubscribeTwoTimesSuccess()
|
||||
{
|
||||
var sp = new MqttSubscribePacket
|
||||
{
|
||||
TopicFilters = new List<MqttTopicFilter>
|
||||
{
|
||||
new MqttTopicFilter { Topic = "#", QualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce },
|
||||
new MqttTopicFilter { Topic = "A/B/C", QualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce }
|
||||
}
|
||||
};
|
||||
|
||||
await _subscriptionsManager.Subscribe(sp, CancellationToken.None);
|
||||
|
||||
var result = CheckSubscriptions("A/B/C", MqttQualityOfServiceLevel.ExactlyOnce, "");
|
||||
|
||||
Assert.IsTrue(result.IsSubscribed);
|
||||
Assert.AreEqual(result.QualityOfServiceLevel, MqttQualityOfServiceLevel.AtLeastOnce);
|
||||
}
|
||||
|
||||
[TestInitialize]
|
||||
public void TestInitialize()
|
||||
{
|
||||
var logger = new TestLogger();
|
||||
var options = new MqttServerOptions();
|
||||
var retainedMessagesManager = new MqttRetainedMessagesManager(new MqttServerEventContainer(), logger);
|
||||
var eventContainer = new MqttServerEventContainer();
|
||||
var clientSessionManager = new MqttClientSessionsManager(options, retainedMessagesManager, eventContainer, logger);
|
||||
|
||||
var session = new MqttSession("", false, new ConcurrentDictionary<object, object>(), options, eventContainer, retainedMessagesManager, clientSessionManager);
|
||||
|
||||
_subscriptionsManager = new MqttClientSubscriptionsManager(session, new MqttServerEventContainer(), retainedMessagesManager, clientSessionManager);
|
||||
}
|
||||
|
||||
CheckSubscriptionsResult CheckSubscriptions(string topic, MqttQualityOfServiceLevel applicationMessageQoSLevel, string senderClientId)
|
||||
{
|
||||
ulong topicHashMask; // not needed
|
||||
bool hasWildcard; // not needed
|
||||
MqttSubscription.CalculateTopicHash(topic, out var topicHash, out topicHashMask, out hasWildcard);
|
||||
return _subscriptionsManager.CheckSubscriptions(topic, topicHash, applicationMessageQoSLevel, senderClientId);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using MQTTnet.Client;
|
||||
using MQTTnet.Formatter;
|
||||
|
||||
namespace MQTTnet.Tests.Server
|
||||
{
|
||||
[TestClass]
|
||||
public sealed class No_Local_Tests : BaseTestClass
|
||||
{
|
||||
[TestMethod]
|
||||
public Task Subscribe_With_No_Local()
|
||||
{
|
||||
return ExecuteTest(true, 0);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public Task Subscribe_Without_No_Local()
|
||||
{
|
||||
return ExecuteTest(false, 1);
|
||||
}
|
||||
|
||||
async Task ExecuteTest(
|
||||
bool noLocal,
|
||||
int expectedCountAfterPublish)
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment(MqttProtocolVersion.V500))
|
||||
{
|
||||
await testEnvironment.StartServer();
|
||||
|
||||
var client1 = await testEnvironment.ConnectClient();
|
||||
var applicationMessageHandler = testEnvironment.CreateApplicationMessageHandler(client1);
|
||||
var topicFilter = testEnvironment.Factory.CreateTopicFilterBuilder().WithTopic("Topic").WithNoLocal(noLocal).Build();
|
||||
await client1.SubscribeAsync(topicFilter);
|
||||
await LongTestDelay();
|
||||
|
||||
applicationMessageHandler.AssertReceivedCountEquals(0);
|
||||
|
||||
// The client will publish a message where it is itself subscribing to.
|
||||
await client1.PublishStringAsync("Topic", "Payload", retain: true);
|
||||
await LongTestDelay();
|
||||
|
||||
applicationMessageHandler.AssertReceivedCountEquals(expectedCountAfterPublish);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using MQTTnet.Formatter;
|
||||
using MQTTnet.Client;
|
||||
|
||||
namespace MQTTnet.Tests.Server
|
||||
{
|
||||
[TestClass]
|
||||
public sealed class Retain_As_Published_Tests : BaseTestClass
|
||||
{
|
||||
[TestMethod]
|
||||
public Task Subscribe_With_Retain_As_Published()
|
||||
{
|
||||
return ExecuteTest(true);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public Task Subscribe_Without_Retain_As_Published()
|
||||
{
|
||||
return ExecuteTest(false);
|
||||
}
|
||||
|
||||
async Task ExecuteTest(bool retainAsPublished)
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment(MqttProtocolVersion.V500))
|
||||
{
|
||||
await testEnvironment.StartServer();
|
||||
|
||||
var client1 = await testEnvironment.ConnectClient();
|
||||
var applicationMessageHandler = testEnvironment.CreateApplicationMessageHandler(client1);
|
||||
var topicFilter = testEnvironment.Factory.CreateTopicFilterBuilder().WithTopic("Topic").WithRetainAsPublished(retainAsPublished).Build();
|
||||
await client1.SubscribeAsync(topicFilter);
|
||||
await LongTestDelay();
|
||||
|
||||
// The client will publish a message where it is itself subscribing to.
|
||||
await client1.PublishStringAsync("Topic", "Payload", retain: true);
|
||||
await LongTestDelay();
|
||||
|
||||
applicationMessageHandler.AssertReceivedCountEquals(1);
|
||||
Assert.AreEqual(retainAsPublished, applicationMessageHandler.ReceivedEventArgs[0].ApplicationMessage.Retain);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using MQTTnet.Client;
|
||||
using MQTTnet.Formatter;
|
||||
using MQTTnet.Protocol;
|
||||
|
||||
namespace MQTTnet.Tests.Server
|
||||
{
|
||||
[TestClass]
|
||||
public sealed class Retain_Handling_Tests : BaseTestClass
|
||||
{
|
||||
[TestMethod]
|
||||
public Task Send_At_Subscribe()
|
||||
{
|
||||
return ExecuteTest(MqttRetainHandling.SendAtSubscribe, 1, 2, 3);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public Task Do_Not_Send_On_Subscribe()
|
||||
{
|
||||
return ExecuteTest(MqttRetainHandling.DoNotSendOnSubscribe, 0, 1, 1);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public Task Send_At_Subscribe_If_New_Subscription_Only()
|
||||
{
|
||||
return ExecuteTest(MqttRetainHandling.SendAtSubscribeIfNewSubscriptionOnly, 1, 2, 2);
|
||||
}
|
||||
|
||||
async Task ExecuteTest(
|
||||
MqttRetainHandling retainHandling,
|
||||
int expectedCountAfterSubscribe,
|
||||
int expectedCountAfterSecondPublish,
|
||||
int expectedCountAfterSecondSubscribe)
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment(MqttProtocolVersion.V500))
|
||||
{
|
||||
await testEnvironment.StartServer();
|
||||
|
||||
var client1 = await testEnvironment.ConnectClient();
|
||||
await client1.PublishStringAsync("Topic", "Payload", retain: true);
|
||||
|
||||
await LongTestDelay();
|
||||
|
||||
var client2 = await testEnvironment.ConnectClient();
|
||||
var applicationMessageHandler = testEnvironment.CreateApplicationMessageHandler(client2);
|
||||
|
||||
var topicFilter = testEnvironment.Factory.CreateTopicFilterBuilder().WithTopic("Topic").WithRetainHandling(retainHandling).Build();
|
||||
await client2.SubscribeAsync(topicFilter);
|
||||
await LongTestDelay();
|
||||
|
||||
applicationMessageHandler.AssertReceivedCountEquals(expectedCountAfterSubscribe);
|
||||
|
||||
await client1.PublishStringAsync("Topic", "Payload", retain: true);
|
||||
await LongTestDelay();
|
||||
|
||||
applicationMessageHandler.AssertReceivedCountEquals(expectedCountAfterSecondPublish);
|
||||
|
||||
await client2.SubscribeAsync(topicFilter);
|
||||
await LongTestDelay();
|
||||
|
||||
applicationMessageHandler.AssertReceivedCountEquals(expectedCountAfterSecondSubscribe);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using MQTTnet.Client;
|
||||
using MQTTnet.Formatter;
|
||||
using MQTTnet.Packets;
|
||||
using MQTTnet.Protocol;
|
||||
|
||||
namespace MQTTnet.Tests.Server
|
||||
{
|
||||
[TestClass]
|
||||
public sealed class Retained_Messages_Tests : BaseTestClass
|
||||
{
|
||||
[TestMethod]
|
||||
public async Task Server_Reports_Retained_Messages_Supported_V3()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
await testEnvironment.StartServer();
|
||||
|
||||
var client = testEnvironment.CreateClient();
|
||||
|
||||
var connectResult = await client.ConnectAsync(testEnvironment.Factory.CreateClientOptionsBuilder()
|
||||
.WithProtocolVersion(MqttProtocolVersion.V311)
|
||||
.WithTcpServer("127.0.0.1", testEnvironment.ServerPort).Build());
|
||||
|
||||
Assert.IsTrue(connectResult.RetainAvailable);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Server_Reports_Retained_Messages_Supported_V5()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment(MqttProtocolVersion.V500))
|
||||
{
|
||||
await testEnvironment.StartServer();
|
||||
|
||||
var client = testEnvironment.CreateClient();
|
||||
var connectResult = await client.ConnectAsync(testEnvironment.Factory.CreateClientOptionsBuilder()
|
||||
.WithProtocolVersion(MqttProtocolVersion.V500)
|
||||
.WithTcpServer("127.0.0.1", testEnvironment.ServerPort).Build());
|
||||
|
||||
Assert.IsTrue(connectResult.RetainAvailable);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Retained_Messages_Flow()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
var retainedMessage = new MqttApplicationMessageBuilder().WithTopic("r").WithPayload("r").WithRetainFlag().Build();
|
||||
|
||||
await testEnvironment.StartServer();
|
||||
var c1 = await testEnvironment.ConnectClient();
|
||||
|
||||
var c2 = await testEnvironment.ConnectClient();
|
||||
var messageHandler = testEnvironment.CreateApplicationMessageHandler(c2);
|
||||
|
||||
await c1.PublishAsync(retainedMessage);
|
||||
await c1.DisconnectAsync();
|
||||
await LongTestDelay();
|
||||
|
||||
for (var i = 0; i < 5; i++)
|
||||
{
|
||||
await c2.UnsubscribeAsync("r");
|
||||
await Task.Delay(100);
|
||||
messageHandler.AssertReceivedCountEquals(i);
|
||||
|
||||
await c2.SubscribeAsync("r");
|
||||
await Task.Delay(100);
|
||||
messageHandler.AssertReceivedCountEquals(i + 1);
|
||||
}
|
||||
|
||||
await c2.DisconnectAsync();
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Receive_No_Retained_Message_After_Subscribe()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
await testEnvironment.StartServer();
|
||||
|
||||
var c1 = await testEnvironment.ConnectClient();
|
||||
await c1.PublishAsync(new MqttApplicationMessageBuilder().WithTopic("retained").WithPayload(new byte[3]).WithRetainFlag().Build());
|
||||
await c1.DisconnectAsync();
|
||||
|
||||
var c2 = await testEnvironment.ConnectClient();
|
||||
var messageHandler = testEnvironment.CreateApplicationMessageHandler(c2);
|
||||
await c2.SubscribeAsync(new MqttTopicFilterBuilder().WithTopic("retained_other").Build());
|
||||
|
||||
await Task.Delay(500);
|
||||
|
||||
messageHandler.AssertReceivedCountEquals(0);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Receive_Retained_Message_After_Subscribe()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
await testEnvironment.StartServer();
|
||||
|
||||
var c1 = await testEnvironment.ConnectClient();
|
||||
await c1.PublishAsync(new MqttApplicationMessageBuilder().WithTopic("retained").WithPayload(new byte[3]).WithRetainFlag().Build());
|
||||
await c1.DisconnectAsync();
|
||||
|
||||
var c2 = await testEnvironment.ConnectClient();
|
||||
var messageHandler = testEnvironment.CreateApplicationMessageHandler(c2);
|
||||
|
||||
await c2.SubscribeAsync(new MqttTopicFilterBuilder().WithTopic("retained").Build());
|
||||
|
||||
await Task.Delay(500);
|
||||
|
||||
messageHandler.AssertReceivedCountEquals(1);
|
||||
Assert.IsTrue(messageHandler.ReceivedEventArgs.First().ApplicationMessage.Retain);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Clear_Retained_Message_With_Empty_Payload()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
await testEnvironment.StartServer();
|
||||
|
||||
var c1 = await testEnvironment.ConnectClient();
|
||||
|
||||
await c1.PublishAsync(new MqttApplicationMessageBuilder().WithTopic("retained").WithPayload(new byte[3]).WithRetainFlag().Build());
|
||||
await c1.PublishAsync(new MqttApplicationMessageBuilder().WithTopic("retained").WithPayload(new byte[0]).WithRetainFlag().Build());
|
||||
|
||||
await c1.DisconnectAsync();
|
||||
|
||||
var c2 = await testEnvironment.ConnectClient();
|
||||
var messageHandler = testEnvironment.CreateApplicationMessageHandler(c2);
|
||||
|
||||
await Task.Delay(200);
|
||||
await c2.SubscribeAsync(new MqttTopicFilter { Topic = "retained", QualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce });
|
||||
await Task.Delay(500);
|
||||
|
||||
messageHandler.AssertReceivedCountEquals(0);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Clear_Retained_Message_With_Null_Payload()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
await testEnvironment.StartServer();
|
||||
|
||||
var c1 = await testEnvironment.ConnectClient();
|
||||
|
||||
await c1.PublishAsync(new MqttApplicationMessageBuilder().WithTopic("retained").WithPayload(new byte[3]).WithRetainFlag().Build());
|
||||
await c1.PublishAsync(new MqttApplicationMessageBuilder().WithTopic("retained").WithPayload((byte[])null).WithRetainFlag().Build());
|
||||
|
||||
await c1.DisconnectAsync();
|
||||
|
||||
var c2 = await testEnvironment.ConnectClient();
|
||||
var messageHandler = testEnvironment.CreateApplicationMessageHandler(c2);
|
||||
|
||||
await Task.Delay(200);
|
||||
await c2.SubscribeAsync(new MqttTopicFilter { Topic = "retained", QualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce });
|
||||
await Task.Delay(500);
|
||||
|
||||
messageHandler.AssertReceivedCountEquals(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using MQTTnet.Adapter;
|
||||
using MQTTnet.Client;
|
||||
using MQTTnet.Exceptions;
|
||||
using MQTTnet.Implementations;
|
||||
using MQTTnet.Protocol;
|
||||
|
||||
namespace MQTTnet.Tests.Server
|
||||
{
|
||||
[TestClass]
|
||||
public sealed class Security_Tests : BaseTestClass
|
||||
{
|
||||
[TestMethod]
|
||||
public async Task Use_Username_Null_Password_Empty()
|
||||
{
|
||||
string username = null;
|
||||
var password = string.Empty;
|
||||
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
testEnvironment.IgnoreClientLogErrors = true;
|
||||
|
||||
await testEnvironment.StartServer();
|
||||
|
||||
var client = testEnvironment.CreateClient();
|
||||
|
||||
var clientOptions = new MqttClientOptionsBuilder()
|
||||
.WithTcpServer("127.0.0.1", testEnvironment.ServerPort)
|
||||
.WithCredentials(username, password)
|
||||
.Build();
|
||||
|
||||
var ex = await Assert.ThrowsExceptionAsync<MqttConnectingFailedException>(async () => await client.ConnectAsync(clientOptions));
|
||||
Assert.IsInstanceOfType(ex.InnerException, typeof(MqttProtocolViolationException));
|
||||
Assert.AreEqual("Error while authenticating. If the User Name Flag is set to 0, the Password Flag MUST be set to 0 [MQTT-3.1.2-22].", ex.Message, false);
|
||||
Assert.AreEqual(MqttClientConnectResultCode.UnspecifiedError, ex.ResultCode);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public Task Handle_Wrong_UserName()
|
||||
{
|
||||
return TestCredentials("x", "Password1");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public Task Handle_Wrong_Password()
|
||||
{
|
||||
return TestCredentials("UserName", "x");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public Task Handle_Wrong_UserName_And_Password()
|
||||
{
|
||||
return TestCredentials("x", "x");
|
||||
}
|
||||
|
||||
private async Task TestCredentials(string userName, string password)
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
testEnvironment.IgnoreClientLogErrors = true;
|
||||
|
||||
var server = await testEnvironment.StartServer();
|
||||
|
||||
server.ValidatingConnectionAsync += e =>
|
||||
{
|
||||
if (e.Username != "UserName1")
|
||||
{
|
||||
e.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
|
||||
}
|
||||
|
||||
if (e.Password != "Password1")
|
||||
{
|
||||
e.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
|
||||
}
|
||||
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
var client = testEnvironment.CreateClient();
|
||||
|
||||
var clientOptions = new MqttClientOptionsBuilder()
|
||||
.WithTcpServer("127.0.0.1", testEnvironment.ServerPort)
|
||||
.WithCredentials(userName, password)
|
||||
.Build();
|
||||
|
||||
var ex = await Assert.ThrowsExceptionAsync<MqttConnectingFailedException>(async () => await client.ConnectAsync(clientOptions));
|
||||
Assert.AreEqual(MqttClientConnectResultCode.BadUserNameOrPassword, ex.Result.ResultCode);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using MQTTnet.Adapter;
|
||||
using MQTTnet.Client;
|
||||
using MQTTnet.Formatter;
|
||||
using MQTTnet.Implementations;
|
||||
using MQTTnet.Protocol;
|
||||
|
||||
namespace MQTTnet.Tests.Server
|
||||
{
|
||||
[TestClass]
|
||||
public sealed class Server_Reference_Tests : BaseTestClass
|
||||
{
|
||||
[TestMethod]
|
||||
public async Task Server_Reports_With_Reference_Server()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
testEnvironment.IgnoreClientLogErrors = true;
|
||||
|
||||
var server = await testEnvironment.StartServer();
|
||||
|
||||
server.ValidatingConnectionAsync += e =>
|
||||
{
|
||||
e.ReasonCode = MqttConnectReasonCode.ServerMoved;
|
||||
e.ServerReference = "new_server";
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
try
|
||||
{
|
||||
var client = testEnvironment.CreateClient();
|
||||
|
||||
await client.ConnectAsync(new MqttClientOptionsBuilder()
|
||||
.WithProtocolVersion(MqttProtocolVersion.V500)
|
||||
.WithTcpServer("127.0.0.1", testEnvironment.ServerPort)
|
||||
.Build());
|
||||
|
||||
Assert.Fail();
|
||||
}
|
||||
catch (MqttConnectingFailedException e)
|
||||
{
|
||||
Assert.AreEqual(MqttClientConnectResultCode.ServerMoved, e.ResultCode);
|
||||
Assert.AreEqual("new_server", e.Result.ServerReference);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,317 @@
|
||||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using MQTTnet.Client;
|
||||
using MQTTnet.Formatter;
|
||||
using MQTTnet.Implementations;
|
||||
using MQTTnet.Protocol;
|
||||
using MQTTnet.Server;
|
||||
using MQTTnet.Tests.Mockups;
|
||||
using MqttClient = MQTTnet.Client.MqttClient;
|
||||
|
||||
namespace MQTTnet.Tests.Server
|
||||
{
|
||||
[TestClass]
|
||||
public sealed class Session_Tests : BaseTestClass
|
||||
{
|
||||
[TestMethod]
|
||||
public async Task Clean_Session_Persistence()
|
||||
{
|
||||
using (var testEnvironment = new TestEnvironment(TestContext))
|
||||
{
|
||||
// Create server with persistent sessions enabled
|
||||
|
||||
await testEnvironment.StartServer(o => o.WithPersistentSessions());
|
||||
|
||||
const string ClientId = "Client1";
|
||||
|
||||
// Create client with clean session and long session expiry interval
|
||||
|
||||
var client1 = await testEnvironment.ConnectClient(
|
||||
o => o.WithProtocolVersion(MqttProtocolVersion.V311)
|
||||
.WithTcpServer("127.0.0.1", testEnvironment.ServerPort)
|
||||
.WithSessionExpiryInterval(9999) // not relevant for v311 but testing impact
|
||||
.WithCleanSession() // start and end with clean session
|
||||
.WithClientId(ClientId)
|
||||
.Build());
|
||||
|
||||
// Disconnect; empty session should be removed from server
|
||||
|
||||
await client1.DisconnectAsync();
|
||||
|
||||
// Simulate some time delay between connections
|
||||
|
||||
await Task.Delay(1000);
|
||||
|
||||
// Reconnect the same client ID without clean session
|
||||
|
||||
var client2 = testEnvironment.CreateClient();
|
||||
var options = testEnvironment.Factory.CreateClientOptionsBuilder()
|
||||
.WithProtocolVersion(MqttProtocolVersion.V311)
|
||||
.WithTcpServer("127.0.0.1", testEnvironment.ServerPort)
|
||||
.WithSessionExpiryInterval(9999) // not relevant for v311 but testing impact
|
||||
.WithCleanSession(false) // see if there is a session
|
||||
.WithClientId(ClientId)
|
||||
.Build();
|
||||
|
||||
|
||||
var result = await client2.ConnectAsync(options).ConfigureAwait(false);
|
||||
|
||||
await client2.DisconnectAsync();
|
||||
|
||||
// Session should NOT be present for MQTT v311 and initial CleanSession == true
|
||||
|
||||
Assert.IsTrue(!result.IsSessionPresent, "Session present");
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Fire_Deleted_Event()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
// Arrange client and server.
|
||||
var server = await testEnvironment.StartServer(o => o.WithPersistentSessions(false));
|
||||
|
||||
var deletedEventFired = false;
|
||||
server.SessionDeletedAsync += e =>
|
||||
{
|
||||
deletedEventFired = true;
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
var client = await testEnvironment.ConnectClient();
|
||||
|
||||
// Act: Disconnect the client -> Event must be fired.
|
||||
await client.DisconnectAsync();
|
||||
|
||||
await LongTestDelay();
|
||||
|
||||
// Assert that the event was fired properly.
|
||||
Assert.IsTrue(deletedEventFired);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Get_Session_Items_In_Status()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
var server = await testEnvironment.StartServer();
|
||||
|
||||
server.ValidatingConnectionAsync += e =>
|
||||
{
|
||||
// Don't validate anything. Just set some session items.
|
||||
e.SessionItems["can_subscribe_x"] = true;
|
||||
e.SessionItems["default_payload"] = "Hello World";
|
||||
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
await testEnvironment.ConnectClient();
|
||||
|
||||
var sessionStatus = await testEnvironment.Server.GetSessionsAsync();
|
||||
var session = sessionStatus.First();
|
||||
|
||||
Assert.AreEqual(true, session.Items["can_subscribe_x"]);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Handle_Parallel_Connection_Attempts()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
testEnvironment.IgnoreClientLogErrors = true;
|
||||
|
||||
await testEnvironment.StartServer();
|
||||
|
||||
var options = new MqttClientOptionsBuilder().WithClientId("1").WithKeepAlivePeriod(TimeSpan.FromSeconds(5));
|
||||
|
||||
var hasReceive = false;
|
||||
|
||||
void OnReceive()
|
||||
{
|
||||
if (!hasReceive)
|
||||
{
|
||||
hasReceive = true;
|
||||
}
|
||||
}
|
||||
|
||||
// Try to connect 50 clients at the same time.
|
||||
var clients = await Task.WhenAll(Enumerable.Range(0, 50).Select(i => ConnectAndSubscribe(testEnvironment, options, OnReceive)));
|
||||
var connectedClients = clients.Where(c => c?.IsConnected ?? false).ToList();
|
||||
|
||||
Assert.AreEqual(1, connectedClients.Count);
|
||||
|
||||
await Task.Delay(5000);
|
||||
|
||||
var option2 = new MqttClientOptionsBuilder().WithClientId("2").WithKeepAlivePeriod(TimeSpan.FromSeconds(10));
|
||||
var sendClient = await testEnvironment.ConnectClient(option2);
|
||||
await sendClient.PublishStringAsync("aaa", "1");
|
||||
|
||||
await Task.Delay(3000);
|
||||
|
||||
Assert.AreEqual(true, hasReceive);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Manage_Session_MaxParallel()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
testEnvironment.IgnoreClientLogErrors = true;
|
||||
var serverOptions = new MqttServerOptionsBuilder();
|
||||
await testEnvironment.StartServer(serverOptions);
|
||||
|
||||
var options = new MqttClientOptionsBuilder().WithClientId("1");
|
||||
|
||||
var clients = await Task.WhenAll(Enumerable.Range(0, 10).Select(i => TryConnect(testEnvironment, options)));
|
||||
|
||||
var connectedClients = clients.Where(c => c?.IsConnected ?? false).ToList();
|
||||
|
||||
Assert.AreEqual(1, connectedClients.Count);
|
||||
}
|
||||
}
|
||||
|
||||
[DataTestMethod]
|
||||
[DataRow(MqttQualityOfServiceLevel.ExactlyOnce)]
|
||||
[DataRow(MqttQualityOfServiceLevel.AtLeastOnce)]
|
||||
public async Task Retry_If_Not_PubAck(MqttQualityOfServiceLevel qos)
|
||||
{
|
||||
long count = 0;
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
await testEnvironment.StartServer(o => o.WithPersistentSessions());
|
||||
|
||||
var publisher = await testEnvironment.ConnectClient();
|
||||
|
||||
var subscriber = await testEnvironment.ConnectClient(o => o.WithClientId(qos.ToString()).WithCleanSession(false));
|
||||
|
||||
subscriber.ApplicationMessageReceivedAsync += c =>
|
||||
{
|
||||
c.AutoAcknowledge = false;
|
||||
++count;
|
||||
Console.WriteLine("process");
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
await subscriber.SubscribeAsync("#", qos);
|
||||
|
||||
var pub = publisher.PublishStringAsync("a", null, qos);
|
||||
|
||||
await Task.Delay(100);
|
||||
await subscriber.DisconnectAsync();
|
||||
await subscriber.ConnectAsync(subscriber.Options);
|
||||
await Task.Delay(100);
|
||||
|
||||
var res = await pub;
|
||||
|
||||
Assert.AreEqual(MqttClientPublishReasonCode.Success, res.ReasonCode);
|
||||
Assert.AreEqual(2, count);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Set_Session_Item()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
var server = await testEnvironment.StartServer();
|
||||
|
||||
server.ValidatingConnectionAsync += e =>
|
||||
{
|
||||
// Don't validate anything. Just set some session items.
|
||||
e.SessionItems["can_subscribe_x"] = true;
|
||||
e.SessionItems["default_payload"] = "Hello World";
|
||||
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
server.InterceptingSubscriptionAsync += e =>
|
||||
{
|
||||
if (e.TopicFilter.Topic == "x")
|
||||
{
|
||||
if (e.SessionItems["can_subscribe_x"] as bool? == false)
|
||||
{
|
||||
e.Response.ReasonCode = MqttSubscribeReasonCode.ImplementationSpecificError;
|
||||
}
|
||||
}
|
||||
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
server.InterceptingPublishAsync += e =>
|
||||
{
|
||||
e.ApplicationMessage.Payload = Encoding.UTF8.GetBytes(e.SessionItems["default_payload"] as string ?? string.Empty);
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
string receivedPayload = null;
|
||||
|
||||
var client = await testEnvironment.ConnectClient();
|
||||
client.ApplicationMessageReceivedAsync += e =>
|
||||
{
|
||||
receivedPayload = e.ApplicationMessage.ConvertPayloadToString();
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
var subscribeResult = await client.SubscribeAsync("x");
|
||||
|
||||
Assert.AreEqual(MqttClientSubscribeResultCode.GrantedQoS0, subscribeResult.Items.First().ResultCode);
|
||||
|
||||
var client2 = await testEnvironment.ConnectClient();
|
||||
await client2.PublishStringAsync("x");
|
||||
|
||||
await Task.Delay(1000);
|
||||
|
||||
Assert.AreEqual("Hello World", receivedPayload);
|
||||
}
|
||||
}
|
||||
|
||||
async Task<MqttClient> ConnectAndSubscribe(TestEnvironment testEnvironment, MqttClientOptionsBuilder options, Action onReceive)
|
||||
{
|
||||
try
|
||||
{
|
||||
var sendClient = await testEnvironment.ConnectClient(options);
|
||||
|
||||
sendClient.ApplicationMessageReceivedAsync += e =>
|
||||
{
|
||||
onReceive();
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
using (var subscribeTimeout = new CancellationTokenSource(TimeSpan.FromSeconds(5)))
|
||||
{
|
||||
await sendClient.SubscribeAsync("aaa", MqttQualityOfServiceLevel.AtMostOnce, subscribeTimeout.Token).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return sendClient;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async Task<MqttClient> TryConnect(TestEnvironment testEnvironment, MqttClientOptionsBuilder options)
|
||||
{
|
||||
try
|
||||
{
|
||||
return await testEnvironment.ConnectClient(options);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using MQTTnet.Client;
|
||||
using MQTTnet.Formatter;
|
||||
|
||||
namespace MQTTnet.Tests.Server
|
||||
{
|
||||
[TestClass]
|
||||
public sealed class Shared_Subscriptions_Tests : BaseTestClass
|
||||
{
|
||||
[TestMethod]
|
||||
public async Task Server_Reports_Shared_Subscriptions_Not_Supported()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment(MqttProtocolVersion.V500))
|
||||
{
|
||||
await testEnvironment.StartServer();
|
||||
|
||||
var client = testEnvironment.CreateClient();
|
||||
var connectResult = await client.ConnectAsync(testEnvironment.Factory.CreateClientOptionsBuilder()
|
||||
.WithProtocolVersion(MqttProtocolVersion.V500)
|
||||
.WithTcpServer("127.0.0.1", testEnvironment.ServerPort).Build());
|
||||
|
||||
Assert.IsFalse(connectResult.SharedSubscriptionAvailable);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Subscription_Of_Shared_Subscription_Is_Denied()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment(MqttProtocolVersion.V500))
|
||||
{
|
||||
await testEnvironment.StartServer();
|
||||
|
||||
var client = testEnvironment.CreateClient();
|
||||
await client.ConnectAsync(testEnvironment.Factory.CreateClientOptionsBuilder()
|
||||
.WithProtocolVersion(MqttProtocolVersion.V500)
|
||||
.WithTcpServer("127.0.0.1", testEnvironment.ServerPort).Build());
|
||||
|
||||
var subscribeResult = await client.SubscribeAsync("$share/A");
|
||||
|
||||
Assert.AreEqual(MqttClientSubscribeResultCode.SharedSubscriptionsNotSupported, subscribeResult.Items.First().ResultCode);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using MQTTnet.Client;
|
||||
using MQTTnet.Protocol;
|
||||
using MQTTnet.Server;
|
||||
using MQTTnet.Tests.Mockups;
|
||||
|
||||
namespace MQTTnet.Tests.Server
|
||||
{
|
||||
[TestClass]
|
||||
public sealed class Status_Tests : BaseTestClass
|
||||
{
|
||||
[TestMethod]
|
||||
public async Task Show_Client_And_Session_Statistics()
|
||||
{
|
||||
using (var testEnvironment = new TestEnvironment(TestContext))
|
||||
{
|
||||
var server = await testEnvironment.StartServer();
|
||||
|
||||
var c1 = await testEnvironment.ConnectClient(new MqttClientOptionsBuilder().WithClientId("client1"));
|
||||
var c2 = await testEnvironment.ConnectClient(new MqttClientOptionsBuilder().WithClientId("client2"));
|
||||
|
||||
await Task.Delay(500);
|
||||
|
||||
var clientStatus = await server.GetClientsAsync();
|
||||
var sessionStatus = await server.GetSessionsAsync();
|
||||
|
||||
Assert.AreEqual(2, clientStatus.Count);
|
||||
Assert.AreEqual(2, sessionStatus.Count);
|
||||
|
||||
Assert.IsTrue(clientStatus.Any(s => s.Id == c1.Options.ClientId));
|
||||
Assert.IsTrue(clientStatus.Any(s => s.Id == c2.Options.ClientId));
|
||||
|
||||
await c1.DisconnectAsync();
|
||||
await c2.DisconnectAsync();
|
||||
|
||||
await Task.Delay(500);
|
||||
|
||||
clientStatus = await server.GetClientsAsync();
|
||||
sessionStatus = await server.GetSessionsAsync();
|
||||
|
||||
Assert.AreEqual(0, clientStatus.Count);
|
||||
Assert.AreEqual(0, sessionStatus.Count);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Disconnect_Client()
|
||||
{
|
||||
using (var testEnvironment = new TestEnvironment(TestContext))
|
||||
{
|
||||
var server = await testEnvironment.StartServer();
|
||||
|
||||
var c1 = await testEnvironment.ConnectClient(new MqttClientOptionsBuilder().WithClientId("client1"));
|
||||
|
||||
await Task.Delay(1000);
|
||||
|
||||
var clientStatus = await server.GetClientsAsync();
|
||||
|
||||
Assert.AreEqual(1, clientStatus.Count);
|
||||
Assert.IsTrue(clientStatus.Any(s => s.Id == c1.Options.ClientId));
|
||||
|
||||
await clientStatus.First().DisconnectAsync();
|
||||
|
||||
await Task.Delay(500);
|
||||
|
||||
Assert.IsFalse(c1.IsConnected);
|
||||
|
||||
clientStatus = await server.GetClientsAsync();
|
||||
|
||||
Assert.AreEqual(0, clientStatus.Count);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Keep_Persistent_Session()
|
||||
{
|
||||
using (var testEnvironment = new TestEnvironment(TestContext))
|
||||
{
|
||||
var server = await testEnvironment.StartServer(new MqttServerOptionsBuilder().WithPersistentSessions());
|
||||
|
||||
var c1 = await testEnvironment.ConnectClient(new MqttClientOptionsBuilder().WithClientId("client1").WithCleanSession(false));
|
||||
var c2 = await testEnvironment.ConnectClient(new MqttClientOptionsBuilder().WithClientId("client2").WithCleanSession(false));
|
||||
|
||||
await c1.DisconnectAsync();
|
||||
|
||||
await Task.Delay(500);
|
||||
|
||||
var clientStatus = await server.GetClientsAsync();
|
||||
var sessionStatus = await server.GetSessionsAsync();
|
||||
|
||||
Assert.AreEqual(1, clientStatus.Count);
|
||||
Assert.AreEqual(2, sessionStatus.Count);
|
||||
|
||||
await c2.DisconnectAsync();
|
||||
|
||||
await Task.Delay(500);
|
||||
|
||||
clientStatus = await server.GetClientsAsync();
|
||||
sessionStatus = await server.GetSessionsAsync();
|
||||
|
||||
Assert.AreEqual(0, clientStatus.Count);
|
||||
Assert.AreEqual(2, sessionStatus.Count);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Track_Sent_Application_Messages()
|
||||
{
|
||||
using (var testEnvironment = new TestEnvironment(TestContext))
|
||||
{
|
||||
var server = await testEnvironment.StartServer(new MqttServerOptionsBuilder().WithPersistentSessions());
|
||||
|
||||
var c1 = await testEnvironment.ConnectClient();
|
||||
|
||||
for (var i = 1; i < 25; i++)
|
||||
{
|
||||
await c1.PublishStringAsync("a");
|
||||
await Task.Delay(50);
|
||||
|
||||
var clientStatus = await server.GetClientsAsync();
|
||||
Assert.AreEqual(i, clientStatus.First().SentApplicationMessagesCount);
|
||||
Assert.AreEqual(0, clientStatus.First().ReceivedApplicationMessagesCount);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Track_Sent_Packets()
|
||||
{
|
||||
using (var testEnvironment = new TestEnvironment(TestContext))
|
||||
{
|
||||
var server = await testEnvironment.StartServer(new MqttServerOptionsBuilder().WithPersistentSessions());
|
||||
|
||||
var c1 = await testEnvironment.ConnectClient(new MqttClientOptionsBuilder().WithNoKeepAlive());
|
||||
|
||||
for (var i = 1; i < 25; i++)
|
||||
{
|
||||
// At most once will send one packet to the client and the server will reply
|
||||
// with an additional ACK packet.
|
||||
await c1.PublishStringAsync("a", string.Empty, MqttQualityOfServiceLevel.AtLeastOnce);
|
||||
|
||||
await Task.Delay(500);
|
||||
|
||||
var clientStatus = await server.GetClientsAsync();
|
||||
|
||||
Assert.AreEqual(i, clientStatus.First().SentApplicationMessagesCount, "SAMC invalid!");
|
||||
|
||||
// + 1 because CONNECT is also counted.
|
||||
Assert.AreEqual(i + 1, clientStatus.First().SentPacketsCount, "SPC invalid!");
|
||||
|
||||
// +2 because ConnACK + PubAck package is already counted.
|
||||
Assert.AreEqual(i + 2, clientStatus.First().ReceivedPacketsCount, "RPC invalid!");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,317 @@
|
||||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using MQTTnet.Client;
|
||||
using MQTTnet.Formatter;
|
||||
using MQTTnet.Implementations;
|
||||
using MQTTnet.Packets;
|
||||
using MQTTnet.Protocol;
|
||||
|
||||
namespace MQTTnet.Tests.Server
|
||||
{
|
||||
[TestClass]
|
||||
public sealed class Subscribe_Tests : BaseTestClass
|
||||
{
|
||||
[TestMethod]
|
||||
public async Task Intercept_Subscription()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
var server = await testEnvironment.StartServer();
|
||||
|
||||
server.InterceptingSubscriptionAsync += e =>
|
||||
{
|
||||
// Set the topic to "a" regards what the client wants to subscribe.
|
||||
e.TopicFilter.Topic = "a";
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
var topicAReceived = false;
|
||||
var topicBReceived = false;
|
||||
|
||||
var client = await testEnvironment.ConnectClient();
|
||||
client.ApplicationMessageReceivedAsync += e =>
|
||||
{
|
||||
if (e.ApplicationMessage.Topic == "a")
|
||||
{
|
||||
topicAReceived = true;
|
||||
}
|
||||
else if (e.ApplicationMessage.Topic == "b")
|
||||
{
|
||||
topicBReceived = true;
|
||||
}
|
||||
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
await client.SubscribeAsync("b");
|
||||
|
||||
await client.PublishStringAsync("a");
|
||||
|
||||
await Task.Delay(500);
|
||||
|
||||
Assert.IsTrue(topicAReceived);
|
||||
Assert.IsFalse(topicBReceived);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Subscribe_Unsubscribe()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
var receivedMessagesCount = 0;
|
||||
|
||||
var server = await testEnvironment.StartServer();
|
||||
|
||||
var c1 = await testEnvironment.ConnectClient(new MqttClientOptionsBuilder().WithClientId("c1"));
|
||||
c1.ApplicationMessageReceivedAsync += e =>
|
||||
{
|
||||
Interlocked.Increment(ref receivedMessagesCount);
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
var c2 = await testEnvironment.ConnectClient(new MqttClientOptionsBuilder().WithClientId("c2"));
|
||||
|
||||
var message = new MqttApplicationMessageBuilder().WithTopic("a").WithQualityOfServiceLevel(MqttQualityOfServiceLevel.ExactlyOnce).Build();
|
||||
await c2.PublishAsync(message);
|
||||
|
||||
await Task.Delay(500);
|
||||
Assert.AreEqual(0, receivedMessagesCount);
|
||||
|
||||
var subscribeEventCalled = false;
|
||||
server.ClientSubscribedTopicAsync += e =>
|
||||
{
|
||||
subscribeEventCalled = e.TopicFilter.Topic == "a" && e.ClientId == c1.Options.ClientId;
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
await c1.SubscribeAsync(new MqttTopicFilter { Topic = "a", QualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce });
|
||||
await Task.Delay(250);
|
||||
Assert.IsTrue(subscribeEventCalled, "Subscribe event not called.");
|
||||
|
||||
await c2.PublishAsync(message);
|
||||
await Task.Delay(250);
|
||||
Assert.AreEqual(1, receivedMessagesCount);
|
||||
|
||||
var unsubscribeEventCalled = false;
|
||||
server.ClientUnsubscribedTopicAsync += e =>
|
||||
{
|
||||
unsubscribeEventCalled = e.TopicFilter == "a" && e.ClientId == c1.Options.ClientId;
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
await c1.UnsubscribeAsync("a");
|
||||
await Task.Delay(250);
|
||||
Assert.IsTrue(unsubscribeEventCalled, "Unsubscribe event not called.");
|
||||
|
||||
await c2.PublishAsync(message);
|
||||
await Task.Delay(500);
|
||||
Assert.AreEqual(1, receivedMessagesCount);
|
||||
|
||||
await Task.Delay(500);
|
||||
|
||||
Assert.AreEqual(1, receivedMessagesCount);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Subscribe_Multiple_In_Single_Request()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
var receivedMessagesCount = 0;
|
||||
|
||||
await testEnvironment.StartServer();
|
||||
|
||||
var c1 = await testEnvironment.ConnectClient();
|
||||
c1.ApplicationMessageReceivedAsync += e =>
|
||||
{
|
||||
Interlocked.Increment(ref receivedMessagesCount);
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
await c1.SubscribeAsync(new MqttClientSubscribeOptionsBuilder()
|
||||
.WithTopicFilter("a")
|
||||
.WithTopicFilter("b")
|
||||
.WithTopicFilter("c")
|
||||
.Build());
|
||||
|
||||
var c2 = await testEnvironment.ConnectClient();
|
||||
|
||||
await c2.PublishStringAsync("a");
|
||||
await Task.Delay(100);
|
||||
Assert.AreEqual(receivedMessagesCount, 1);
|
||||
|
||||
await c2.PublishStringAsync("b");
|
||||
await Task.Delay(100);
|
||||
Assert.AreEqual(receivedMessagesCount, 2);
|
||||
|
||||
await c2.PublishStringAsync("c");
|
||||
await Task.Delay(100);
|
||||
Assert.AreEqual(receivedMessagesCount, 3);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Subscribe_Lots_In_Single_Request()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
var receivedMessagesCount = 0;
|
||||
|
||||
await testEnvironment.StartServer();
|
||||
|
||||
var c1 = await testEnvironment.ConnectClient();
|
||||
c1.ApplicationMessageReceivedAsync += e =>
|
||||
{
|
||||
Interlocked.Increment(ref receivedMessagesCount);
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
var optionsBuilder = new MqttClientSubscribeOptionsBuilder();
|
||||
for (var i = 0; i < 500; i++)
|
||||
{
|
||||
optionsBuilder.WithTopicFilter(i.ToString());
|
||||
}
|
||||
|
||||
await c1.SubscribeAsync(optionsBuilder.Build()).ConfigureAwait(false);
|
||||
|
||||
var c2 = await testEnvironment.ConnectClient();
|
||||
|
||||
var messageBuilder = new MqttApplicationMessageBuilder();
|
||||
for (var i = 0; i < 500; i++)
|
||||
{
|
||||
messageBuilder.WithTopic(i.ToString());
|
||||
|
||||
await c2.PublishAsync(messageBuilder.Build()).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
SpinWait.SpinUntil(() => receivedMessagesCount == 500, TimeSpan.FromSeconds(20));
|
||||
|
||||
Assert.AreEqual(500, receivedMessagesCount);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Subscribe_Lots_In_Multiple_Requests()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
var receivedMessagesCount = 0;
|
||||
|
||||
await testEnvironment.StartServer();
|
||||
|
||||
var c1 = await testEnvironment.ConnectClient();
|
||||
c1.ApplicationMessageReceivedAsync += e =>
|
||||
{
|
||||
Interlocked.Increment(ref receivedMessagesCount);
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
for (var i = 0; i < 500; i++)
|
||||
{
|
||||
var so = new MqttClientSubscribeOptionsBuilder()
|
||||
.WithTopicFilter(i.ToString()).Build();
|
||||
|
||||
await c1.SubscribeAsync(so).ConfigureAwait(false);
|
||||
|
||||
await Task.Delay(10);
|
||||
}
|
||||
|
||||
var c2 = await testEnvironment.ConnectClient();
|
||||
|
||||
var messageBuilder = new MqttApplicationMessageBuilder();
|
||||
for (var i = 0; i < 500; i++)
|
||||
{
|
||||
messageBuilder.WithTopic(i.ToString());
|
||||
|
||||
await c2.PublishAsync(messageBuilder.Build()).ConfigureAwait(false);
|
||||
|
||||
await Task.Delay(10);
|
||||
}
|
||||
|
||||
SpinWait.SpinUntil(() => receivedMessagesCount == 500, 5000);
|
||||
|
||||
Assert.AreEqual(500, receivedMessagesCount);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Subscribe_Multiple_In_Multiple_Request()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
var receivedMessagesCount = 0;
|
||||
|
||||
await testEnvironment.StartServer();
|
||||
|
||||
var c1 = await testEnvironment.ConnectClient();
|
||||
c1.ApplicationMessageReceivedAsync += e =>
|
||||
{
|
||||
Interlocked.Increment(ref receivedMessagesCount);
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
await c1.SubscribeAsync(new MqttClientSubscribeOptionsBuilder()
|
||||
.WithTopicFilter("a")
|
||||
.Build());
|
||||
|
||||
await c1.SubscribeAsync(new MqttClientSubscribeOptionsBuilder()
|
||||
.WithTopicFilter("b")
|
||||
.Build());
|
||||
|
||||
await c1.SubscribeAsync(new MqttClientSubscribeOptionsBuilder()
|
||||
.WithTopicFilter("c")
|
||||
.Build());
|
||||
|
||||
var c2 = await testEnvironment.ConnectClient();
|
||||
|
||||
await c2.PublishStringAsync("a");
|
||||
await Task.Delay(100);
|
||||
Assert.AreEqual(receivedMessagesCount, 1);
|
||||
|
||||
await c2.PublishStringAsync("b");
|
||||
await Task.Delay(100);
|
||||
Assert.AreEqual(receivedMessagesCount, 2);
|
||||
|
||||
await c2.PublishStringAsync("c");
|
||||
await Task.Delay(100);
|
||||
Assert.AreEqual(receivedMessagesCount, 3);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Deny_Invalid_Topic()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment(MqttProtocolVersion.V500))
|
||||
{
|
||||
var server = await testEnvironment.StartServer();
|
||||
|
||||
server.InterceptingSubscriptionAsync += e =>
|
||||
{
|
||||
if (e.TopicFilter.Topic == "not_allowed_topic")
|
||||
{
|
||||
e.Response.ReasonCode = MqttSubscribeReasonCode.TopicFilterInvalid;
|
||||
}
|
||||
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
var client = await testEnvironment.ConnectClient();
|
||||
|
||||
var subscribeResult =await client.SubscribeAsync("allowed_topic");
|
||||
Assert.AreEqual(MqttClientSubscribeResultCode.GrantedQoS0, subscribeResult.Items.First().ResultCode);
|
||||
|
||||
subscribeResult =await client.SubscribeAsync("not_allowed_topic");
|
||||
Assert.AreEqual(MqttClientSubscribeResultCode.TopicFilterInvalid, subscribeResult.Items.First().ResultCode);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using MQTTnet.Client;
|
||||
using MQTTnet.Formatter;
|
||||
|
||||
namespace MQTTnet.Tests.Server
|
||||
{
|
||||
[TestClass]
|
||||
public sealed class Subscription_Identifier_Tests : BaseTestClass
|
||||
{
|
||||
[TestMethod]
|
||||
public async Task Server_Reports_Subscription_Identifiers_Supported()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment(MqttProtocolVersion.V500))
|
||||
{
|
||||
await testEnvironment.StartServer();
|
||||
|
||||
var client = testEnvironment.CreateClient();
|
||||
var connectResult = await client.ConnectAsync(testEnvironment.Factory.CreateClientOptionsBuilder()
|
||||
.WithProtocolVersion(MqttProtocolVersion.V500)
|
||||
.WithTcpServer("127.0.0.1", testEnvironment.ServerPort).Build());
|
||||
|
||||
Assert.IsTrue(connectResult.SubscriptionIdentifiersAvailable);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Subscribe_With_Subscription_Identifier()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment(MqttProtocolVersion.V500))
|
||||
{
|
||||
await testEnvironment.StartServer();
|
||||
|
||||
var client1 = await testEnvironment.ConnectClient();
|
||||
var applicationMessageHandler = testEnvironment.CreateApplicationMessageHandler(client1);
|
||||
var topicFilter = testEnvironment.Factory.CreateTopicFilterBuilder().WithTopic("Topic").Build();
|
||||
var subscribeOptions = testEnvironment.Factory.CreateSubscribeOptionsBuilder().WithSubscriptionIdentifier(456).WithTopicFilter(topicFilter).Build();
|
||||
|
||||
await client1.SubscribeAsync(subscribeOptions);
|
||||
await LongTestDelay();
|
||||
|
||||
applicationMessageHandler.AssertReceivedCountEquals(0);
|
||||
|
||||
// The client will publish a message where it is itself subscribing to.
|
||||
await client1.PublishStringAsync("Topic", "Payload", retain: true);
|
||||
await LongTestDelay();
|
||||
|
||||
applicationMessageHandler.AssertReceivedCountEquals(1);
|
||||
|
||||
applicationMessageHandler.ReceivedEventArgs[0].ApplicationMessage.SubscriptionIdentifiers.Contains(456);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Subscribe_With_Multiple_Subscription_Identifiers()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment(MqttProtocolVersion.V500))
|
||||
{
|
||||
await testEnvironment.StartServer();
|
||||
|
||||
var client1 = await testEnvironment.ConnectClient();
|
||||
var applicationMessageHandler = testEnvironment.CreateApplicationMessageHandler(client1);
|
||||
|
||||
var topicFilter = testEnvironment.Factory.CreateTopicFilterBuilder().WithTopic("Topic/A").Build();
|
||||
var subscribeOptions = testEnvironment.Factory.CreateSubscribeOptionsBuilder().WithSubscriptionIdentifier(456).WithTopicFilter(topicFilter).Build();
|
||||
await client1.SubscribeAsync(subscribeOptions);
|
||||
|
||||
await LongTestDelay();
|
||||
|
||||
topicFilter = testEnvironment.Factory.CreateTopicFilterBuilder().WithTopic("Topic/+").Build();
|
||||
subscribeOptions = testEnvironment.Factory.CreateSubscribeOptionsBuilder().WithSubscriptionIdentifier(789).WithTopicFilter(topicFilter).Build();
|
||||
await client1.SubscribeAsync(subscribeOptions);
|
||||
|
||||
await LongTestDelay();
|
||||
|
||||
applicationMessageHandler.AssertReceivedCountEquals(0);
|
||||
|
||||
// The client will publish a message where it is itself subscribing to.
|
||||
await client1.PublishStringAsync("Topic/A", "Payload", retain: true);
|
||||
await LongTestDelay();
|
||||
|
||||
applicationMessageHandler.AssertReceivedCountEquals(1);
|
||||
|
||||
applicationMessageHandler.ReceivedEventArgs[0].ApplicationMessage.SubscriptionIdentifiers.Contains(456);
|
||||
applicationMessageHandler.ReceivedEventArgs[0].ApplicationMessage.SubscriptionIdentifiers.Contains(789);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,612 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using MQTTnet.Client;
|
||||
using MQTTnet.Protocol;
|
||||
using MQTTnet.Server;
|
||||
using MQTTnet.Tests.Mockups;
|
||||
|
||||
namespace MQTTnet.Tests.Server
|
||||
{
|
||||
[TestClass]
|
||||
public class Subscription_TopicHash_Tests
|
||||
{
|
||||
enum TopicHashSelector { NoWildcard, SingleWildcard, MultiWildcard };
|
||||
|
||||
MQTTnet.Server.MqttSession _clientSession;
|
||||
|
||||
[TestMethod]
|
||||
public void Match_Hash_Test_SingleWildCard()
|
||||
{
|
||||
var l0 = "pub0";
|
||||
var l1 = "topic1";
|
||||
var l2 = "+";
|
||||
var l3 = "prop1";
|
||||
var topic = string.Format("{0}/{1}/{2}/{3}", l0, l1, l2, l3);
|
||||
|
||||
|
||||
UInt64 topicHash;
|
||||
UInt64 topicHashMask;
|
||||
bool topicHasWildcard;
|
||||
MQTTnet.Server.MqttSubscription.CalculateTopicHash(topic, out topicHash, out topicHashMask, out topicHasWildcard);
|
||||
|
||||
Assert.IsTrue(topicHasWildcard, "Wildcard not detected");
|
||||
|
||||
var hashBytes = GetBytes(topicHash);
|
||||
Assert.AreNotEqual(hashBytes[0], 0, "checksum 0 mismatch");
|
||||
Assert.AreNotEqual(hashBytes[1], 0, "checksum 1 mismatch");
|
||||
Assert.AreEqual(hashBytes[2], 0, "checksum 2 mismatch");
|
||||
Assert.AreNotEqual(hashBytes[3], 0, "checksum 3 mismatch");
|
||||
Assert.AreEqual(hashBytes[4], 0, "checksum 4 mismatch");
|
||||
Assert.AreEqual(hashBytes[5], 0, "checksum 5 mismatch");
|
||||
Assert.AreEqual(hashBytes[6], 0, "checksum 6 mismatch");
|
||||
Assert.AreEqual(hashBytes[7], 0, "checksum 7 mismatch");
|
||||
|
||||
// The mask should have zeroes where the wildcard and ff at the end
|
||||
var hashMaskBytes = GetBytes(topicHashMask);
|
||||
Assert.AreEqual(hashMaskBytes[0], 0xff, "mask 0 mismatch");
|
||||
Assert.AreEqual(hashMaskBytes[1], 0xff, "mask 1 mismatch");
|
||||
Assert.AreEqual(hashMaskBytes[2], 0, "mask 2 mismatch");
|
||||
Assert.AreEqual(hashMaskBytes[3], 0xff, "mask 3 mismatch");
|
||||
Assert.AreEqual(hashMaskBytes[4], 0xff, "mask 4 mismatch");
|
||||
Assert.AreEqual(hashMaskBytes[5], 0xff, "mask 5 mismatch");
|
||||
Assert.AreEqual(hashMaskBytes[6], 0xff, "mask 6 mismatch");
|
||||
Assert.AreEqual(hashMaskBytes[7], 0xff, "mask 7 mismatch");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Match_Hash_Test_MultiWildCard()
|
||||
{
|
||||
var l0 = "pub0";
|
||||
var l1 = "topic1";
|
||||
var l2 = "sub1";
|
||||
var l3 = "#";
|
||||
var topic = string.Format("{0}/{1}/{2}/{3}", l0, l1, l2, l3);
|
||||
|
||||
UInt64 topicHash;
|
||||
UInt64 topicHashMask;
|
||||
bool topicHasWildcard;
|
||||
|
||||
MQTTnet.Server.MqttSubscription.CalculateTopicHash(topic, out topicHash, out topicHashMask, out topicHasWildcard);
|
||||
|
||||
Assert.IsTrue(topicHasWildcard, "Wildcard not detected");
|
||||
|
||||
var hashBytes = GetBytes(topicHash);
|
||||
Assert.AreNotEqual(hashBytes[0], 0, "checksum 0 mismatch");
|
||||
Assert.AreNotEqual(hashBytes[1], 0, "checksum 1 mismatch");
|
||||
Assert.AreNotEqual(hashBytes[2], 0, "checksum 2 mismatch");
|
||||
Assert.AreEqual(hashBytes[3], 0, "checksum 3 mismatch");
|
||||
Assert.AreEqual(hashBytes[4], 0, "checksum 4 mismatch");
|
||||
Assert.AreEqual(hashBytes[5], 0, "checksum 5 mismatch");
|
||||
Assert.AreEqual(hashBytes[6], 0, "checksum 6 mismatch");
|
||||
Assert.AreEqual(hashBytes[7], 0, "checksum 7 mismatch");
|
||||
|
||||
// The mask should have zeroes where the wildcard is and zero onward
|
||||
var hashMaskBytes = GetBytes(topicHashMask);
|
||||
Assert.AreEqual(hashMaskBytes[0], 0xff, "mask 0 mismatch");
|
||||
Assert.AreEqual(hashMaskBytes[1], 0xff, "mask 1 mismatch");
|
||||
Assert.AreEqual(hashMaskBytes[2], 0xff, "mask 2 mismatch");
|
||||
Assert.AreEqual(hashMaskBytes[3], 0, "mask 3 mismatch");
|
||||
Assert.AreEqual(hashMaskBytes[4], 0, "mask 4 mismatch");
|
||||
Assert.AreEqual(hashMaskBytes[5], 0, "mask 5 mismatch");
|
||||
Assert.AreEqual(hashMaskBytes[6], 0, "mask 6 mismatch");
|
||||
Assert.AreEqual(hashMaskBytes[7], 0, "mask 7 mismatch");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Match_Hash_Test_NoWildCard()
|
||||
{
|
||||
var l0 = "pub0";
|
||||
var l1 = "topic1";
|
||||
var l2 = "sub1";
|
||||
var l3 = "prop1";
|
||||
var topic = string.Format("{0}/{1}/{2}/{3}", l0, l1, l2, l3);
|
||||
|
||||
UInt64 topicHash;
|
||||
UInt64 topicHashMask;
|
||||
bool topicHasWildcard;
|
||||
|
||||
MQTTnet.Server.MqttSubscription.CalculateTopicHash(topic, out topicHash, out topicHashMask, out topicHasWildcard);
|
||||
|
||||
Assert.IsFalse(topicHasWildcard, "Wildcard detected when not wildcard present");
|
||||
|
||||
|
||||
var hashBytes = GetBytes(topicHash);
|
||||
Assert.AreNotEqual(hashBytes[0], 0, "checksum 0 mismatch");
|
||||
Assert.AreNotEqual(hashBytes[1], 0, "checksum 1 mismatch");
|
||||
Assert.AreNotEqual(hashBytes[2], 0, "checksum 2 mismatch");
|
||||
Assert.AreNotEqual(hashBytes[3], 0, "checksum 3 mismatch");
|
||||
Assert.AreEqual(hashBytes[4], 0, "checksum 4 mismatch");
|
||||
Assert.AreEqual(hashBytes[5], 0, "checksum 5 mismatch");
|
||||
Assert.AreEqual(hashBytes[6], 0, "checksum 6 mismatch");
|
||||
Assert.AreEqual(hashBytes[7], 0, "checksum 7 mismatch");
|
||||
|
||||
// The mask should have ff
|
||||
var hashMaskBytes = GetBytes(topicHashMask);
|
||||
Assert.AreEqual(hashMaskBytes[0], 0xff, "mask 0 mismatch");
|
||||
Assert.AreEqual(hashMaskBytes[1], 0xff, "mask 1 mismatch");
|
||||
Assert.AreEqual(hashMaskBytes[2], 0xff, "mask 2 mismatch");
|
||||
Assert.AreEqual(hashMaskBytes[3], 0xff, "mask 3 mismatch");
|
||||
Assert.AreEqual(hashMaskBytes[4], 0xff, "mask 4 mismatch");
|
||||
Assert.AreEqual(hashMaskBytes[5], 0xff, "mask 5 mismatch");
|
||||
Assert.AreEqual(hashMaskBytes[6], 0xff, "mask 6 mismatch");
|
||||
Assert.AreEqual(hashMaskBytes[7], 0xff, "mask 7 mismatch");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Test long topic name with last level being #
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public void Match_Hash_Test_LongTopic_MultiWildcard()
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
const int NumLevels = 8;
|
||||
var levelNames = new string[NumLevels];
|
||||
for (var i = 0; i < NumLevels; ++i)
|
||||
{
|
||||
if (i > 0)
|
||||
sb.Append("/");
|
||||
string levelName;
|
||||
if (i == NumLevels - 1)
|
||||
{
|
||||
// last one is #
|
||||
levelName = "#";
|
||||
}
|
||||
else
|
||||
{
|
||||
levelName = "level" + i;
|
||||
}
|
||||
levelNames[i] = levelName;
|
||||
sb.Append(levelName);
|
||||
}
|
||||
var topic = sb.ToString();
|
||||
|
||||
// UInt64 is limited to 8 levels
|
||||
|
||||
UInt64 topicHash;
|
||||
UInt64 topicHashMask;
|
||||
bool topicHasWildcard;
|
||||
|
||||
MQTTnet.Server.MqttSubscription.CalculateTopicHash(topic, out topicHash, out topicHashMask, out topicHasWildcard);
|
||||
|
||||
Assert.IsTrue(topicHasWildcard, "Wildcard not detected");
|
||||
|
||||
var hashBytes = GetBytes(topicHash);
|
||||
// all bytes should contain checksum
|
||||
int count = 0;
|
||||
foreach (var h in hashBytes)
|
||||
{
|
||||
if (count < 7)
|
||||
{
|
||||
Assert.AreNotEqual(h, 0, "checksum mismatch");
|
||||
}
|
||||
else
|
||||
{
|
||||
Assert.AreEqual(h, 0, "checksum mismatch");
|
||||
}
|
||||
++count;
|
||||
}
|
||||
// The mask should have ff except for last level
|
||||
var hashMaskBytes = GetBytes(topicHashMask);
|
||||
count = 0;
|
||||
foreach (var h in hashMaskBytes)
|
||||
{
|
||||
if (count < 7)
|
||||
{
|
||||
Assert.AreEqual(h, 0xff, "mask mismatch");
|
||||
}
|
||||
else
|
||||
{
|
||||
Assert.AreEqual(h, 0, "last mask mismatch");
|
||||
}
|
||||
++count;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Test long topic name with last level being +
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public void Match_Hash_Test_LongTopic_SingleWildCard()
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
const int NumLevels = 8;
|
||||
var levelNames = new string[NumLevels];
|
||||
for (var i = 0; i < NumLevels; ++i)
|
||||
{
|
||||
if (i > 0)
|
||||
sb.Append("/");
|
||||
string levelName;
|
||||
if (i == NumLevels - 1)
|
||||
{
|
||||
// last one is +
|
||||
levelName = "+";
|
||||
}
|
||||
else
|
||||
{
|
||||
levelName = "level" + i;
|
||||
}
|
||||
levelNames[i] = levelName;
|
||||
sb.Append(levelName);
|
||||
}
|
||||
var topic = sb.ToString();
|
||||
|
||||
UInt64 topicHash;
|
||||
UInt64 topicHashMask;
|
||||
bool topicHasWildcard;
|
||||
|
||||
MQTTnet.Server.MqttSubscription.CalculateTopicHash(topic, out topicHash, out topicHashMask, out topicHasWildcard);
|
||||
|
||||
Assert.IsTrue(topicHasWildcard, "Wildcard not detected");
|
||||
|
||||
|
||||
var hashBytes = GetBytes(topicHash);
|
||||
// all bytes should contain checksum
|
||||
int count = 0;
|
||||
foreach (var h in hashBytes)
|
||||
{
|
||||
if (count < 7)
|
||||
{
|
||||
Assert.AreNotEqual(h, 0, "checksum mismatch");
|
||||
}
|
||||
else
|
||||
{
|
||||
// wildcard position
|
||||
Assert.AreEqual(h, 0, "checksum mismatch");
|
||||
}
|
||||
++count;
|
||||
}
|
||||
// The mask should have ff
|
||||
var hashMaskBytes = GetBytes(topicHashMask);
|
||||
count = 0;
|
||||
foreach (var h in hashMaskBytes)
|
||||
{
|
||||
if (count < 7)
|
||||
{
|
||||
Assert.AreEqual(h, 0xff, "mask mismatch");
|
||||
}
|
||||
else
|
||||
{
|
||||
Assert.AreEqual(h, 0, "last mask mismatch");
|
||||
}
|
||||
++count;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Test long topic name exceeding 8 levels
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public void Match_Hash_Test_LongTopic_NoWildCard()
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
const int NumLevels = 9;
|
||||
var levelNames = new string[NumLevels];
|
||||
for(var i=0; i < NumLevels; ++i)
|
||||
{
|
||||
if (i > 0)
|
||||
sb.Append("/");
|
||||
var levelName = "level" + i;
|
||||
levelNames[i] = levelName;
|
||||
sb.Append(levelName);
|
||||
}
|
||||
var topic = sb.ToString();
|
||||
|
||||
UInt64 topicHash;
|
||||
UInt64 topicHashMask;
|
||||
bool topicHasWildcard;
|
||||
|
||||
MQTTnet.Server.MqttSubscription.CalculateTopicHash(topic, out topicHash, out topicHashMask, out topicHasWildcard);
|
||||
|
||||
Assert.IsFalse(topicHasWildcard, "Wildcard detected when not present");
|
||||
|
||||
|
||||
var hashBytes = GetBytes(topicHash);
|
||||
// all bytes should contain checksum
|
||||
int count = 0;
|
||||
foreach(var h in hashBytes)
|
||||
{
|
||||
Assert.AreNotEqual(h, 0, "checksum mismatch");
|
||||
++count;
|
||||
}
|
||||
// The mask should have ff
|
||||
var hashMaskBytes = GetBytes(topicHashMask);
|
||||
count = 0;
|
||||
foreach (var h in hashMaskBytes)
|
||||
{
|
||||
Assert.AreEqual(h, 0xff, "mask mismatch");
|
||||
++count;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Test long topic name with last level being +
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public void Match_Hash_Test_LongTopic_DetectSingleLevelWildcard()
|
||||
{
|
||||
var topic = "asdfasdf/asdfasdf/asdfasdf/asdfasdf/asdfas/dfaf/assfdgsdfgdf/+";
|
||||
|
||||
UInt64 topicHash;
|
||||
UInt64 topicHashMask;
|
||||
bool topicHasWildcard;
|
||||
|
||||
MQTTnet.Server.MqttSubscription.CalculateTopicHash(topic, out topicHash, out topicHashMask, out topicHasWildcard);
|
||||
|
||||
Assert.IsTrue(topicHasWildcard, "Wildcard not detected");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Test long topic name with last level being #
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public void Match_Hash_Test_LongTopic_DetectMultiLevelWildcard()
|
||||
{
|
||||
var topic = "asdfasdf/asdfasdf/asdfasdf/asdfasdf/asdfas/dfaf/assfdgsdfgdf/#";
|
||||
|
||||
UInt64 topicHash;
|
||||
UInt64 topicHashMask;
|
||||
bool topicHasWildcard;
|
||||
|
||||
MQTTnet.Server.MqttSubscription.CalculateTopicHash(topic, out topicHash, out topicHashMask, out topicHasWildcard);
|
||||
|
||||
Assert.IsTrue(topicHasWildcard, "Wildcard not detected");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Match_Hash_Test_Search_NoWildcard()
|
||||
{
|
||||
var topics = await PrepareTopicHashSubscriptions(TopicHashSelector.NoWildcard);
|
||||
|
||||
// all match lookup
|
||||
var matchCount = CheckTopicSubscriptions(_clientSession, topics, "No Wildcard All Match");
|
||||
|
||||
Assert.AreEqual(topics.Count, matchCount, "Not all topics matched");
|
||||
|
||||
// no match lookup
|
||||
{
|
||||
{
|
||||
var topicsToFind = new List<string>();
|
||||
foreach (var t in topics)
|
||||
{
|
||||
topicsToFind.Add(t + "x");
|
||||
}
|
||||
|
||||
matchCount = CheckTopicSubscriptions(_clientSession, topicsToFind, "No Wildcard No Match (Append X)");
|
||||
|
||||
Assert.AreEqual(0, matchCount, "Topic match count not zero");
|
||||
}
|
||||
|
||||
{
|
||||
var topicsToFind = new List<string>();
|
||||
foreach (var t in topics)
|
||||
{
|
||||
// replace last letter with x
|
||||
topicsToFind.Add(t.Substring(0, t.Length - 1) + "x");
|
||||
}
|
||||
|
||||
matchCount = CheckTopicSubscriptions(_clientSession, topicsToFind, "No Wildcard No Match (Replace X)");
|
||||
|
||||
Assert.AreEqual(0, matchCount, "Topic match count not zero");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Match_Hash_Test_Search_SingleWildcard()
|
||||
{
|
||||
var topics = await PrepareTopicHashSubscriptions(TopicHashSelector.SingleWildcard);
|
||||
var matchCount = CheckTopicSubscriptions(_clientSession, topics, "Single Wildcard");
|
||||
// Should match all topics
|
||||
Assert.AreEqual(topics.Count, matchCount, "Topics not matched");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Match_Hash_Test_Search_MultiWildcard()
|
||||
{
|
||||
var topics = await PrepareTopicHashSubscriptions(TopicHashSelector.MultiWildcard);
|
||||
var matchCount = CheckTopicSubscriptions(_clientSession, topics, "Multi Wildcard");
|
||||
// Should match all topics
|
||||
Assert.AreEqual(topics.Count, matchCount, "Topics not matched");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Even fairly regularly named topics as generated by the topic generator should result in shallow hash buckets
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
[TestMethod]
|
||||
public void Check_Hash_Bucket_Depth()
|
||||
{
|
||||
Dictionary<string, List<string>> topicsByPublisher;
|
||||
Dictionary<string, List<string>> singleWildcardTopicsByPublisher;
|
||||
Dictionary<string, List<string>> multiWildcardTopicsByPublisher;
|
||||
|
||||
const int NumPublishers = 5000;
|
||||
const int NumTopicsPerPublisher = 10;
|
||||
|
||||
TopicGenerator.Generate(NumPublishers, NumTopicsPerPublisher, out topicsByPublisher, out singleWildcardTopicsByPublisher, out multiWildcardTopicsByPublisher);
|
||||
|
||||
// There will be many 'similar' topics ending with, i.e. "sensor100", "sensor101", ...
|
||||
// Hash bucket depths should remain low.
|
||||
var bucketDepths = new Dictionary<UInt64, int>();
|
||||
int maxBucketDepth = 0;
|
||||
UInt64 maxBucketDepthHash = 0;
|
||||
|
||||
var topicsByHash = new Dictionary<UInt64, List<string>>();
|
||||
|
||||
foreach (var t in topicsByPublisher)
|
||||
{
|
||||
var topics = t.Value;
|
||||
foreach (var topic in topics)
|
||||
{
|
||||
UInt64 topicHash;
|
||||
UInt64 hashMask;
|
||||
bool hasWildcard;
|
||||
MQTTnet.Server.MqttSubscription.CalculateTopicHash(topic, out topicHash, out hashMask, out hasWildcard);
|
||||
|
||||
bucketDepths.TryGetValue(topicHash, out var currentValue);
|
||||
++currentValue;
|
||||
bucketDepths[topicHash] = currentValue;
|
||||
|
||||
if (currentValue > maxBucketDepth)
|
||||
{
|
||||
maxBucketDepth = currentValue;
|
||||
maxBucketDepthHash = topicHash;
|
||||
}
|
||||
|
||||
if (!topicsByHash.TryGetValue(topicHash, out var topicList))
|
||||
{
|
||||
topicList = new List<string>();
|
||||
topicsByHash.Add(topicHash, topicList);
|
||||
}
|
||||
topicList.Add(topic);
|
||||
}
|
||||
}
|
||||
|
||||
var maxDepthTopics = topicsByHash[maxBucketDepthHash];
|
||||
|
||||
Console.Write("Max bucket depth is " + maxBucketDepth);
|
||||
|
||||
// for the test case the bucket depth should be less than 100
|
||||
Assert.IsTrue(maxBucketDepth < 100, "Unexpected high topic hash bucket depth");
|
||||
}
|
||||
|
||||
|
||||
[TestMethod]
|
||||
public void Check_Selected_Topic_Hashes()
|
||||
{
|
||||
CheckTopicHash("client1/building1/level1/sensor1", 0x655D4AF100000000, 0xFFFFFFFFFFFFFFFF);
|
||||
CheckTopicHash("client1/building1/+/sensor1", 0x655D00F100000000, 0xFFFF00FFFFFFFFFF);
|
||||
CheckTopicHash("client1/+/level1/+", 0x65004A0000000000, 0xFF00FF00FFFFFFFF);
|
||||
CheckTopicHash("client1/building1/level1/#", 0x655D4A0000000000, 0xFFFFFF0000000000);
|
||||
CheckTopicHash("client1/+/level1/#", 0x65004A0000000000, 0xFF00FF0000000000);
|
||||
}
|
||||
|
||||
void CheckTopicHash(string topic, ulong expectedHash, ulong expectedHashMask)
|
||||
{
|
||||
ulong topicHash;
|
||||
ulong hashMask;
|
||||
bool hasWildcard;
|
||||
|
||||
MQTTnet.Server.MqttSubscription.CalculateTopicHash(topic, out topicHash, out hashMask, out hasWildcard);
|
||||
|
||||
Console.WriteLine();
|
||||
Console.WriteLine("Topic: " + topic);
|
||||
Console.WriteLine(string.Format("Hash: {0:X8}", topicHash));
|
||||
Console.WriteLine(string.Format("Hash Mask: {0:X8}", hashMask));
|
||||
|
||||
Assert.AreEqual(expectedHash, topicHash, "Topic hash not as expected. Has the hash function changed?");
|
||||
Assert.AreEqual(expectedHashMask, hashMask, "Topic hash mask not as expected");
|
||||
}
|
||||
|
||||
|
||||
async Task<List<string>> PrepareTopicHashSubscriptions(TopicHashSelector selector)
|
||||
{
|
||||
Dictionary<string, List<string>> topicsByPublisher;
|
||||
Dictionary<string, List<string>> singleWildcardTopicsByPublisher;
|
||||
Dictionary<string, List<string>> multiWildcardTopicsByPublisher;
|
||||
|
||||
const int NumPublishers = 1;
|
||||
const int NumTopicsPerPublisher = 10000;
|
||||
|
||||
TopicGenerator.Generate(NumPublishers, NumTopicsPerPublisher, out topicsByPublisher, out singleWildcardTopicsByPublisher, out multiWildcardTopicsByPublisher);
|
||||
|
||||
var topics = topicsByPublisher.FirstOrDefault().Value;
|
||||
var singleWildcardTopics = singleWildcardTopicsByPublisher.FirstOrDefault().Value;
|
||||
var multiWildcardTopics = multiWildcardTopicsByPublisher.FirstOrDefault().Value;
|
||||
|
||||
const string ClientId = "Client1";
|
||||
var logger = new Mockups.TestLogger();
|
||||
var serverOptions = new MQTTnet.Server.MqttServerOptions();
|
||||
var eventContainer = new MQTTnet.Server.MqttServerEventContainer();
|
||||
var retainedMessagesManager = new MqttRetainedMessagesManager(eventContainer, logger);
|
||||
var sessionManager = new MqttClientSessionsManager(serverOptions, retainedMessagesManager, eventContainer, logger);
|
||||
_clientSession = new MQTTnet.Server.MqttSession(
|
||||
ClientId,
|
||||
false,
|
||||
new Dictionary<object, object>(),
|
||||
serverOptions,
|
||||
eventContainer,
|
||||
retainedMessagesManager,
|
||||
sessionManager
|
||||
);
|
||||
|
||||
List<string> topicsToSubscribe;
|
||||
|
||||
switch (selector)
|
||||
{
|
||||
case TopicHashSelector.SingleWildcard:
|
||||
topicsToSubscribe = singleWildcardTopics;
|
||||
break;
|
||||
case TopicHashSelector.MultiWildcard:
|
||||
topicsToSubscribe = multiWildcardTopics;
|
||||
break;
|
||||
default:
|
||||
topicsToSubscribe = topics;
|
||||
break;
|
||||
}
|
||||
foreach (var t in topicsToSubscribe)
|
||||
{
|
||||
var subPacket = new Packets.MqttSubscribePacket();
|
||||
var filter = new Packets.MqttTopicFilter();
|
||||
filter.Topic = t;
|
||||
subPacket.TopicFilters.Add(filter);
|
||||
await _clientSession.SubscriptionsManager.Subscribe(subPacket, default(CancellationToken));
|
||||
}
|
||||
|
||||
return topics;
|
||||
}
|
||||
|
||||
int CheckTopicSubscriptions(MQTTnet.Server.MqttSession clientSession, List<string> topicsToFind, string subject)
|
||||
{
|
||||
var matchCount = 0;
|
||||
|
||||
{
|
||||
int resultCount = 0;
|
||||
|
||||
var stopWatch = new System.Diagnostics.Stopwatch();
|
||||
stopWatch.Start();
|
||||
var countUp = 0;
|
||||
var countDown = topicsToFind.Count - 1;
|
||||
for (; countUp < topicsToFind.Count; ++countUp, --countDown)
|
||||
{
|
||||
var topicToFind = topicsToFind[countDown];
|
||||
|
||||
UInt64 topicHash;
|
||||
UInt64 hashMask;
|
||||
bool hasWildcard;
|
||||
MQTTnet.Server.MqttSubscription.CalculateTopicHash((string)topicToFind, out topicHash, out hashMask, out hasWildcard);
|
||||
|
||||
var result = clientSession.SubscriptionsManager.CheckSubscriptions((string)topicToFind, topicHash, MqttQualityOfServiceLevel.AtMostOnce, "OtherClient");
|
||||
if (result.IsSubscribed)
|
||||
{
|
||||
++matchCount;
|
||||
}
|
||||
++resultCount;
|
||||
}
|
||||
|
||||
stopWatch.Stop();
|
||||
|
||||
Console.Write("Match count: " + matchCount + "; ");
|
||||
|
||||
Console.WriteLine(subject + " lookup milliseconds: " + stopWatch.ElapsedMilliseconds);
|
||||
}
|
||||
|
||||
return matchCount;
|
||||
}
|
||||
|
||||
byte[] GetBytes(UInt64 value)
|
||||
{
|
||||
var bytes = BitConverter.GetBytes(value);
|
||||
// Ensure that highest byte comes first for comparison left to right
|
||||
if (BitConverter.IsLittleEndian)
|
||||
return bytes.Reverse().ToArray();
|
||||
return bytes;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using MQTTnet.Client;
|
||||
using MQTTnet.Formatter;
|
||||
using MQTTnet.Implementations;
|
||||
|
||||
namespace MQTTnet.Tests.Server
|
||||
{
|
||||
[TestClass]
|
||||
public sealed class Topic_Alias_Tests : BaseTestClass
|
||||
{
|
||||
[TestMethod]
|
||||
public async Task Server_Reports_Topic_Alias_Supported()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
await testEnvironment.StartServer();
|
||||
|
||||
var client = testEnvironment.CreateClient();
|
||||
|
||||
var connectResult = await client.ConnectAsync(new MqttClientOptionsBuilder()
|
||||
.WithProtocolVersion(MqttProtocolVersion.V500)
|
||||
.WithTcpServer("127.0.0.1", testEnvironment.ServerPort)
|
||||
.Build());
|
||||
|
||||
Assert.AreEqual(connectResult.TopicAliasMaximum, ushort.MaxValue);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Publish_With_Topic_Alias()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
await testEnvironment.StartServer();
|
||||
|
||||
var receivedTopics = new List<string>();
|
||||
|
||||
var c1 = await testEnvironment.ConnectClient(options => options.WithProtocolVersion(MqttProtocolVersion.V500));
|
||||
c1.ApplicationMessageReceivedAsync += e =>
|
||||
{
|
||||
lock (receivedTopics)
|
||||
{
|
||||
receivedTopics.Add(e.ApplicationMessage.Topic);
|
||||
}
|
||||
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
await c1.SubscribeAsync("#");
|
||||
|
||||
var c2 = await testEnvironment.ConnectClient(options => options.WithProtocolVersion(MqttProtocolVersion.V500));
|
||||
|
||||
var message = new MqttApplicationMessage
|
||||
{
|
||||
Topic = "this_is_the_topic",
|
||||
TopicAlias = 22
|
||||
};
|
||||
|
||||
await c2.PublishAsync(message);
|
||||
|
||||
message.Topic = null;
|
||||
|
||||
await c2.PublishAsync(message);
|
||||
await c2.PublishAsync(message);
|
||||
|
||||
await Task.Delay(500);
|
||||
|
||||
Assert.AreEqual(3, receivedTopics.Count);
|
||||
CollectionAssert.AllItemsAreNotNull(receivedTopics);
|
||||
Assert.IsTrue(receivedTopics.All(t => t.Equals("this_is_the_topic")));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using MQTTnet.Client;
|
||||
using MQTTnet.Formatter;
|
||||
using MQTTnet.Implementations;
|
||||
using MQTTnet.Packets;
|
||||
using MQTTnet.Tests.Mockups;
|
||||
|
||||
namespace MQTTnet.Tests.Server
|
||||
{
|
||||
[TestClass]
|
||||
public class Feature_Tests
|
||||
{
|
||||
public TestContext TestContext { get; set; }
|
||||
|
||||
[TestMethod]
|
||||
public async Task Use_User_Properties()
|
||||
{
|
||||
using (var testEnvironment = new TestEnvironment(TestContext))
|
||||
{
|
||||
await testEnvironment.StartServer();
|
||||
|
||||
var sender = await testEnvironment.ConnectClient(new MqttClientOptionsBuilder().WithProtocolVersion(MqttProtocolVersion.V500));
|
||||
var receiver = await testEnvironment.ConnectClient(new MqttClientOptionsBuilder().WithProtocolVersion(MqttProtocolVersion.V500));
|
||||
|
||||
var message = new MqttApplicationMessageBuilder()
|
||||
.WithTopic("A")
|
||||
.WithUserProperty("x", "1")
|
||||
.WithUserProperty("y", "2")
|
||||
.WithUserProperty("z", "3")
|
||||
.WithUserProperty("z", "4"); // z is here two times to test list of items
|
||||
|
||||
await receiver.SubscribeAsync(new MqttClientSubscribeOptions
|
||||
{
|
||||
TopicFilters = new List<MqttTopicFilter>
|
||||
{
|
||||
new MqttTopicFilter { Topic = "#" }
|
||||
}
|
||||
}, CancellationToken.None);
|
||||
|
||||
MqttApplicationMessage receivedMessage = null;
|
||||
receiver.ApplicationMessageReceivedAsync += e =>
|
||||
{
|
||||
receivedMessage = e.ApplicationMessage;
|
||||
return PlatformAbstractionLayer.CompletedTask;
|
||||
};
|
||||
|
||||
await sender.PublishAsync(message.Build(), CancellationToken.None);
|
||||
|
||||
await Task.Delay(1000);
|
||||
|
||||
Assert.IsNotNull(receivedMessage);
|
||||
Assert.AreEqual("A", receivedMessage.Topic);
|
||||
Assert.AreEqual(4, receivedMessage.UserProperties.Count);
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using MQTTnet.Client;
|
||||
using MQTTnet.Formatter;
|
||||
|
||||
namespace MQTTnet.Tests.Server
|
||||
{
|
||||
[TestClass]
|
||||
public sealed class Wildcard_Subscription_Available_Tests : BaseTestClass
|
||||
{
|
||||
[TestMethod]
|
||||
public async Task Server_Reports_Wildcard_Subscription_Available_Tests_Supported_V3()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment())
|
||||
{
|
||||
await testEnvironment.StartServer();
|
||||
|
||||
var client = testEnvironment.CreateClient();
|
||||
var connectResult = await client.ConnectAsync(testEnvironment.Factory.CreateClientOptionsBuilder()
|
||||
.WithProtocolVersion(MqttProtocolVersion.V311)
|
||||
.WithTcpServer("127.0.0.1", testEnvironment.ServerPort).Build());
|
||||
|
||||
Assert.IsTrue(connectResult.WildcardSubscriptionAvailable);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Server_Reports_Wildcard_Subscription_Available_Tests_Supported_V5()
|
||||
{
|
||||
using (var testEnvironment = CreateTestEnvironment(MqttProtocolVersion.V500))
|
||||
{
|
||||
await testEnvironment.StartServer();
|
||||
|
||||
var client = testEnvironment.CreateClient();
|
||||
var connectResult = await client.ConnectAsync(testEnvironment.Factory.CreateClientOptionsBuilder()
|
||||
.WithProtocolVersion(MqttProtocolVersion.V500)
|
||||
.WithTcpServer("127.0.0.1", testEnvironment.ServerPort).Build());
|
||||
|
||||
Assert.IsTrue(connectResult.WildcardSubscriptionAvailable);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using MQTTnet.Server;
|
||||
|
||||
namespace MQTTnet.Tests
|
||||
{
|
||||
[TestClass]
|
||||
public sealed class MqttTopicFilterComparer_Tests
|
||||
{
|
||||
[TestMethod]
|
||||
public void AllLevelsWildcardMatch()
|
||||
{
|
||||
CompareAndAssert("A/B/C/D", "#", MqttTopicFilterCompareResult.IsMatch);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void BeginningOneLevelWildcardMatch()
|
||||
{
|
||||
CompareAndAssert("A/B/C", "+/B/C", MqttTopicFilterCompareResult.IsMatch);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Compare_UTF8_String_Match()
|
||||
{
|
||||
CompareAndAssert("öäüß", "öäüß", MqttTopicFilterCompareResult.IsMatch);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Compare_UTF8_String_No_Match()
|
||||
{
|
||||
CompareAndAssert("ae", "ä", MqttTopicFilterCompareResult.NoMatch);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void DirectMatch()
|
||||
{
|
||||
CompareAndAssert("A/B/C", "A/B/C", MqttTopicFilterCompareResult.IsMatch);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void DirectNoMatch()
|
||||
{
|
||||
CompareAndAssert("A/B/X", "A/B/C", MqttTopicFilterCompareResult.NoMatch);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void EndMultipleLevelsWildcardMatch()
|
||||
{
|
||||
CompareAndAssert("A/B/C", "A/#", MqttTopicFilterCompareResult.IsMatch);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void EndMultipleLevelsWildcardMatchEmptyLevel()
|
||||
{
|
||||
CompareAndAssert("A/", "A/#", MqttTopicFilterCompareResult.IsMatch);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void EndMultipleLevelsWildcardNoMatch()
|
||||
{
|
||||
CompareAndAssert("A/B/C/D", "A/C/#", MqttTopicFilterCompareResult.NoMatch);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void EndOneLevelWildcardMatch()
|
||||
{
|
||||
CompareAndAssert("A/B/C", "A/B/+", MqttTopicFilterCompareResult.IsMatch);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Hash_Match_With_Separator_Only()
|
||||
{
|
||||
//A Topic Name or Topic Filter consisting only of the ‘/’ character is valid
|
||||
CompareAndAssert("/", "#", MqttTopicFilterCompareResult.IsMatch);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void MiddleOneLevelWildcardMatch()
|
||||
{
|
||||
CompareAndAssert("A/B/C", "A/+/C", MqttTopicFilterCompareResult.IsMatch);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void MiddleOneLevelWildcardNoMatch()
|
||||
{
|
||||
CompareAndAssert("A/B/C/D", "A/+/C", MqttTopicFilterCompareResult.NoMatch);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void MultiLevel_Sport()
|
||||
{
|
||||
// Tests from official MQTT spec (4.7.1.2 Multi-level wildcard)
|
||||
CompareAndAssert("sport/tennis/player1", "sport/tennis/player1/#", MqttTopicFilterCompareResult.IsMatch);
|
||||
CompareAndAssert("sport/tennis/player1/ranking", "sport/tennis/player1/#", MqttTopicFilterCompareResult.IsMatch);
|
||||
CompareAndAssert("sport/tennis/player1/score/wimbledon", "sport/tennis/player1/#", MqttTopicFilterCompareResult.IsMatch);
|
||||
|
||||
CompareAndAssert("sport/tennis/player1", "sport/tennis/+", MqttTopicFilterCompareResult.IsMatch);
|
||||
CompareAndAssert("sport/tennis/player2", "sport/tennis/+", MqttTopicFilterCompareResult.IsMatch);
|
||||
CompareAndAssert("sport/tennis/player1/ranking", "sport/tennis/+", MqttTopicFilterCompareResult.NoMatch);
|
||||
|
||||
CompareAndAssert("sport", "sport/#", MqttTopicFilterCompareResult.IsMatch);
|
||||
CompareAndAssert("sport", "sport/+", MqttTopicFilterCompareResult.NoMatch);
|
||||
CompareAndAssert("sport/", "sport/+", MqttTopicFilterCompareResult.IsMatch);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Plus_Match_With_Separator_Only()
|
||||
{
|
||||
//A Topic Name or Topic Filter consisting only of the ‘/’ character is valid
|
||||
CompareAndAssert("A", "+", MqttTopicFilterCompareResult.IsMatch);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Reserved_Multi_Level_Wildcard_Only()
|
||||
{
|
||||
CompareAndAssert("$SPECIAL/TOPIC", "#", MqttTopicFilterCompareResult.NoMatch);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Reserved_Single_Level_Wildcard()
|
||||
{
|
||||
CompareAndAssert("$SYS/monitor/Clients", "$SYS/#", MqttTopicFilterCompareResult.IsMatch);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Reserved_Single_Level_Wildcard_Prefix()
|
||||
{
|
||||
CompareAndAssert("$SYS/monitor/Clients", "+/monitor/Clients", MqttTopicFilterCompareResult.NoMatch);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Reserved_Single_Level_Wildcard_Suffix()
|
||||
{
|
||||
CompareAndAssert("$SYS/monitor/Clients", "$SYS/monitor/+", MqttTopicFilterCompareResult.IsMatch);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void SingleLevel_Finance()
|
||||
{
|
||||
// Tests from official MQTT spec (4.7.1.3 Single level wildcard)
|
||||
CompareAndAssert("/finance", "+/+", MqttTopicFilterCompareResult.IsMatch);
|
||||
CompareAndAssert("/finance", "/+", MqttTopicFilterCompareResult.IsMatch);
|
||||
CompareAndAssert("/finance", "+", MqttTopicFilterCompareResult.NoMatch);
|
||||
}
|
||||
|
||||
static void CompareAndAssert(string topic, string filter, MqttTopicFilterCompareResult expectedResult)
|
||||
{
|
||||
Assert.AreEqual(expectedResult, MqttTopicFilterComparer.Compare(topic, filter));
|
||||
|
||||
ulong topicHash;
|
||||
ulong topicHashMask;
|
||||
bool topicHasWildcard;
|
||||
|
||||
MqttSubscription.CalculateTopicHash(topic, out topicHash, out topicHashMask, out topicHasWildcard);
|
||||
|
||||
|
||||
ulong filterTopicHash;
|
||||
ulong filterTopicHashMask;
|
||||
bool filterTopicHasWildcard;
|
||||
|
||||
MqttSubscription.CalculateTopicHash(filter, out filterTopicHash, out filterTopicHashMask, out filterTopicHasWildcard);
|
||||
|
||||
if (expectedResult == MqttTopicFilterCompareResult.IsMatch)
|
||||
{
|
||||
// If it matches then the hash evaluation should also indicate a match
|
||||
Assert.IsTrue((topicHash & filterTopicHashMask) == filterTopicHash, "Incorrect topic hash (is equal)");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace MQTTnet.Tests.Server
|
||||
{
|
||||
public class TopicGenerator
|
||||
{
|
||||
public static void Generate(
|
||||
int numPublishers, int numTopicsPerPublisher,
|
||||
out Dictionary<string, List<string>> topicsByPublisher,
|
||||
out Dictionary<string, List<string>> singleWildcardTopicsByPublisher,
|
||||
out Dictionary<string, List<string>> multiWildcardTopicsByPublisher
|
||||
)
|
||||
{
|
||||
topicsByPublisher = new Dictionary<string, List<string>>();
|
||||
singleWildcardTopicsByPublisher = new Dictionary<string, List<string>>();
|
||||
multiWildcardTopicsByPublisher = new Dictionary<string, List<string>>();
|
||||
|
||||
// Find some reasonable distribution across three topic levels
|
||||
var topicsPerLevel = (int)Math.Pow(numTopicsPerPublisher, (1.0 / 3.0));
|
||||
if (topicsPerLevel <= 0)
|
||||
{
|
||||
topicsPerLevel = 1;
|
||||
}
|
||||
|
||||
int numLevel1Topics = topicsPerLevel;
|
||||
int numLevel2Topics = topicsPerLevel;
|
||||
|
||||
var maxNumLevel3Topics = 1 + (int)((double)numTopicsPerPublisher / numLevel1Topics / numLevel2Topics);
|
||||
if (maxNumLevel3Topics <= 0)
|
||||
{
|
||||
maxNumLevel3Topics = 1;
|
||||
}
|
||||
|
||||
for (var p = 0; p < numPublishers; ++p)
|
||||
{
|
||||
int publisherTopicCount = 0;
|
||||
var publisherName = "pub" + p;
|
||||
for (var l1 = 0; l1 < numLevel1Topics; ++l1)
|
||||
{
|
||||
for (var l2 = 0; l2 < numLevel2Topics; ++l2)
|
||||
{
|
||||
for (var l3 = 0; l3 < maxNumLevel3Topics; ++l3)
|
||||
{
|
||||
if (publisherTopicCount >= numTopicsPerPublisher)
|
||||
break;
|
||||
|
||||
var topic = string.Format("{0}/building{1}/level{2}/sensor{3}", publisherName, l1 + 1, l2 + 1, l3 + 1);
|
||||
AddPublisherTopic(publisherName, topic, topicsByPublisher);
|
||||
|
||||
if (l2 == 0)
|
||||
{
|
||||
var singleWildcardTopic = string.Format("{0}/building{1}/+/sensor{2}", publisherName, l1 + 1, l3 + 1);
|
||||
AddPublisherTopic(publisherName, singleWildcardTopic, singleWildcardTopicsByPublisher);
|
||||
}
|
||||
if ((l1 == 0) && (l3 == 0))
|
||||
{
|
||||
var multiWildcardTopic = string.Format("{0}/+/level{1}/+", publisherName, l2 + 1);
|
||||
AddPublisherTopic(publisherName, multiWildcardTopic, multiWildcardTopicsByPublisher);
|
||||
}
|
||||
|
||||
++publisherTopicCount;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void AddPublisherTopic(string publisherName, string topic, Dictionary<string, List<string>> topicsByPublisher)
|
||||
{
|
||||
List<string> topicList;
|
||||
if (!topicsByPublisher.TryGetValue(publisherName, out topicList))
|
||||
{
|
||||
topicList = new List<string>();
|
||||
topicsByPublisher.Add(publisherName, topicList);
|
||||
}
|
||||
topicList.Add(topic);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user