Refactor package object model.

This commit is contained in:
Christian Kratky
2020-10-28 23:11:12 +01:00
parent adce5662eb
commit b7fb0c1002
71 changed files with 761 additions and 582 deletions
+61 -2
View File
@@ -1,4 +1,5 @@
using System.Threading;
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MQTTnet.Internal;
@@ -9,7 +10,65 @@ namespace MQTTnet.Tests
public class AsyncLock_Tests
{
[TestMethod]
public void AsyncLock()
public async Task Lock_Serial_Calls()
{
var sum = 0;
var @lock = new AsyncLock();
for (var i = 0; i < 100; i++)
{
using (await @lock.WaitAsync().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().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;
+47 -3
View File
@@ -1,4 +1,5 @@
using System.Threading;
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MQTTnet.Internal;
@@ -36,9 +37,22 @@ namespace MQTTnet.Tests
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 Preserve_ProcessAsync()
public async Task Process_Async()
{
var queue = new AsyncQueue<int>();
@@ -50,7 +64,37 @@ namespace MQTTnet.Tests
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);
@@ -1,10 +1,12 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MQTTnet.Client.Options;
using MQTTnet.LowLevelClient;
using MQTTnet.Packets;
using MQTTnet.Protocol;
using MQTTnet.Tests.Mockups;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
@@ -34,7 +36,7 @@ namespace MQTTnet.Tests
{
using (var testEnvironment = new TestEnvironment(TestContext))
{
var server = await testEnvironment.StartServerAsync();
await testEnvironment.StartServerAsync();
var factory = new MqttFactory();
var lowLevelClient = factory.CreateLowLevelMqttClient();
@@ -50,7 +52,7 @@ namespace MQTTnet.Tests
{
using (var testEnvironment = new TestEnvironment(TestContext))
{
var server = await testEnvironment.StartServerAsync();
await testEnvironment.StartServerAsync();
var factory = new MqttFactory();
var lowLevelClient = factory.CreateLowLevelMqttClient();
@@ -71,7 +73,7 @@ namespace MQTTnet.Tests
{
using (var testEnvironment = new TestEnvironment(TestContext))
{
var server = await testEnvironment.StartServerAsync();
await testEnvironment.StartServerAsync();
var factory = new MqttFactory();
var lowLevelClient = factory.CreateLowLevelMqttClient();
@@ -89,6 +91,39 @@ namespace MQTTnet.Tests
}
}
[TestMethod]
public async Task Loose_Connection()
{
using (var testEnvironment = new TestEnvironment(TestContext))
{
testEnvironment.ServerPort = 8364;
var server = await testEnvironment.StartServerAsync();
var client = await testEnvironment.ConnectLowLevelClientAsync(o => o.WithCommunicationTimeout(TimeSpan.Zero));
await Authenticate(client).ConfigureAwait(false);
await server.StopAsync();
await Task.Delay(1000);
try
{
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");
}
}
async Task<MqttConnAckPacket> Authenticate(ILowLevelMqttClient client)
{
await client.SendAsync(new MqttConnectPacket
@@ -6,7 +6,9 @@ using MQTTnet.Server;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using MQTTnet.LowLevelClient;
namespace MQTTnet.Tests.Mockups
{
@@ -100,6 +102,25 @@ namespace MQTTnet.Tests.Mockups
return ConnectClientAsync(new MqttClientOptionsBuilder());
}
public Task<ILowLevelMqttClient> ConnectLowLevelClientAsync()
{
return ConnectLowLevelClientAsync(o => {});
}
public async Task<ILowLevelMqttClient> ConnectLowLevelClientAsync(Action<MqttClientOptionsBuilder> optionsBuilder)
{
if (optionsBuilder == null) throw new ArgumentNullException(nameof(optionsBuilder));
var options = new MqttClientOptionsBuilder();
options = options.WithTcpServer("127.0.0.1", ServerPort);
optionsBuilder.Invoke(options);
var client = new MqttFactory().CreateLowLevelMqttClient();
await client.ConnectAsync(options.Build(), CancellationToken.None).ConfigureAwait(false);
return client;
}
public async Task<IMqttClient> ConnectClientAsync(MqttClientOptionsBuilder options)
{
if (options == null) throw new ArgumentNullException(nameof(options));
@@ -111,7 +132,7 @@ namespace MQTTnet.Tests.Mockups
return client;
}
public async Task<IMqttClient> ConnectClientAsync(IMqttClientOptions options)
{
if (options == null) throw new ArgumentNullException(nameof(options));
@@ -11,7 +11,7 @@ namespace MQTTnet.Tests.Mockups
{
public class TestMqttCommunicationAdapter : IMqttChannelAdapter
{
private readonly BlockingCollection<MqttBasePacket> _incomingPackets = new BlockingCollection<MqttBasePacket>();
readonly BlockingCollection<MqttBasePacket> _incomingPackets = new BlockingCollection<MqttBasePacket>();
public TestMqttCommunicationAdapter Partner { get; set; }
@@ -26,8 +26,7 @@ namespace MQTTnet.Tests.Mockups
public long BytesSent { get; }
public long BytesReceived { get; }
public Action ReadingPacketStartedCallback { get; set; }
public Action ReadingPacketCompletedCallback { get; set; }
public bool IsReadingPacket { get; }
public void Dispose()
{
@@ -1,118 +0,0 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MQTTnet.Adapter;
using MQTTnet.Diagnostics;
using MQTTnet.Server;
using MQTTnet.Server.Status;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace MQTTnet.Tests
{
[TestClass]
public class MqttKeepAliveMonitor_Tests
{
[TestMethod]
public async Task KeepAlive_Timeout()
{
var counter = 0;
var monitor = new MqttClientKeepAliveMonitor("", () =>
{
counter++;
return Task.CompletedTask;
},
new MqttNetLogger());
Assert.AreEqual(0, counter);
monitor.Start(1, CancellationToken.None);
Assert.AreEqual(0, counter);
await Task.Delay(2000); // Internally the keep alive timeout is multiplied with 1.5 as per protocol specification.
Assert.AreEqual(1, counter);
}
[TestMethod]
public async Task KeepAlive_NoTimeout()
{
var counter = 0;
var monitor = new MqttClientKeepAliveMonitor("", () =>
{
counter++;
return Task.CompletedTask;
},
new MqttNetLogger());
Assert.AreEqual(0, counter);
monitor.Start(1, CancellationToken.None);
Assert.AreEqual(0, counter);
// Simulate traffic.
await Task.Delay(1000); // Internally the keep alive timeout is multiplied with 1.5 as per protocol specification.
monitor.PacketReceived();
await Task.Delay(1000);
monitor.PacketReceived();
await Task.Delay(1000);
Assert.AreEqual(0, counter);
await Task.Delay(2000);
Assert.AreEqual(1, counter);
}
private class TestClientSession : IMqttClientSession
{
public string ClientId { get; }
public int StopCalledCount { get; private set; }
public void FillStatus(MqttClientStatus status)
{
throw new NotSupportedException();
}
public void EnqueueApplicationMessage(MqttClientConnection senderClientSession, MqttApplicationMessage applicationMessage)
{
throw new NotSupportedException();
}
public void ClearPendingApplicationMessages()
{
throw new NotSupportedException();
}
public Task RunAsync(MqttApplicationMessage willMessage, int keepAlivePeriod, IMqttChannelAdapter adapter)
{
throw new NotSupportedException();
}
public Task StopAsync()
{
StopCalledCount++;
return Task.FromResult(0);
}
public Task SubscribeAsync(IList<MqttTopicFilter> topicFilters)
{
throw new NotSupportedException();
}
public Task UnsubscribeAsync(IList<string> topicFilters)
{
throw new NotSupportedException();
}
public void Dispose()
{
}
}
}
}
@@ -0,0 +1,78 @@
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;
using MQTTnet.Tests.Mockups;
namespace MQTTnet.Tests
{
[TestClass]
public sealed class Server_Connection_Tests
{
[TestMethod]
public async Task Close_Idle_Connection_On_Connect()
{
using (var testEnvironment = new TestEnvironment())
{
await testEnvironment.StartServerAsync(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 = new TestEnvironment())
{
await testEnvironment.StartServerAsync(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,58 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MQTTnet.Packets;
using MQTTnet.Tests.Mockups;
namespace MQTTnet.Tests
{
[TestClass]
public sealed class Server_KeepAlive_Tests
{
[TestMethod]
public async Task Disconnect_Client_DueTo_KeepAlive()
{
using (var testEnvironment = new TestEnvironment())
{
var server = await testEnvironment.StartServerAsync();
var client = await testEnvironment.ConnectLowLevelClientAsync(o => o.WithCommunicationTimeout(TimeSpan.FromSeconds(2))).ConfigureAwait(false);
await client.SendAsync(new MqttConnectPacket
{
CleanSession = true,
ClientId = "abc",
KeepAlivePeriod = 1,
}, CancellationToken.None).ConfigureAwait(false);
var response = await client.ReceiveAsync(CancellationToken.None).ConfigureAwait(false);
Assert.IsTrue(response is MqttConnAckPacket);
await client.SendAsync(MqttPingReqPacket.Instance, CancellationToken.None);
await Task.Delay(500);
await client.SendAsync(MqttPingReqPacket.Instance, CancellationToken.None);
await Task.Delay(500);
await client.SendAsync(MqttPingReqPacket.Instance, CancellationToken.None);
await Task.Delay(500);
await client.SendAsync(MqttPingReqPacket.Instance, CancellationToken.None);
// 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.2 seconds because the server MUST wait 1.5 seconds in total (See spec).
await Task.Delay(1200);
await client.SendAsync(MqttPingReqPacket.Instance, CancellationToken.None);
// Now we will wait longer than 1.5 so that the server will close the connection.
await Task.Delay(3000);
await server.StopAsync();
await client.ReceiveAsync(CancellationToken.None);
}
}
}
}
@@ -6,7 +6,6 @@ using MQTTnet.Tests.Mockups;
using MQTTnet.Client;
using MQTTnet.Protocol;
using MQTTnet.Server;
using System.Threading;
namespace MQTTnet.Tests
{
@@ -63,7 +62,6 @@ namespace MQTTnet.Tests
var clientStatus = await server.GetClientStatusAsync();
Assert.AreEqual(1, clientStatus.Count);
Assert.IsTrue(clientStatus.Any(s => s.ClientId == c1.Options.ClientId));
await clientStatus.First().DisconnectAsync();
+3 -67
View File
@@ -6,14 +6,12 @@ using MQTTnet.Client.Disconnecting;
using MQTTnet.Client.Options;
using MQTTnet.Client.Receiving;
using MQTTnet.Client.Subscribing;
using MQTTnet.Implementations;
using MQTTnet.Protocol;
using MQTTnet.Server;
using MQTTnet.Tests.Mockups;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
@@ -21,7 +19,7 @@ using System.Threading.Tasks;
namespace MQTTnet.Tests
{
[TestClass]
public class Server_Tests
public sealed class Server_Tests
{
public TestContext TestContext { get; set; }
@@ -331,7 +329,7 @@ namespace MQTTnet.Tests
await Task.Delay(10);
}
var c2 = await testEnvironment.ConnectClientAsync();
var messageBuilder = new MqttApplicationMessageBuilder();
@@ -1219,68 +1217,6 @@ namespace MQTTnet.Tests
}
}
[TestMethod]
public async Task Close_Idle_Connection()
{
using (var testEnvironment = new TestEnvironment(TestContext))
{
await testEnvironment.StartServerAsync(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 = new TestEnvironment(TestContext))
{
await testEnvironment.StartServerAsync(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)
{
}
}
}
[TestMethod]
public async Task Do_Not_Send_Retained_Messages_For_Denied_Subscription()
{
@@ -1471,7 +1407,7 @@ namespace MQTTnet.Tests
await client.SubscribeAsync(topic, MqttQualityOfServiceLevel.AtLeastOnce);
await client.PublishAsync(new MqttApplicationMessage{ Topic = topic, QualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce });
await client.PublishAsync(new MqttApplicationMessage { Topic = topic, QualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce });
await Task.Delay(500);