You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

422 lines
17 KiB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading;
  5. using System.Threading.Tasks;
  6. using Microsoft.VisualStudio.TestTools.UnitTesting;
  7. using MQTTnet.Client;
  8. using MQTTnet.Client.Connecting;
  9. using MQTTnet.Client.Options;
  10. using MQTTnet.Client.Receiving;
  11. using MQTTnet.Diagnostics;
  12. using MQTTnet.Extensions.ManagedClient;
  13. using MQTTnet.Server;
  14. using MQTTnet.Tests.Mockups;
  15. namespace MQTTnet.Tests
  16. {
  17. [TestClass]
  18. public class ManagedMqttClient_Tests
  19. {
  20. public TestContext TestContext { get; set; }
  21. [TestMethod]
  22. public async Task Drop_New_Messages_On_Full_Queue()
  23. {
  24. var factory = new MqttFactory();
  25. var managedClient = factory.CreateManagedMqttClient();
  26. try
  27. {
  28. var clientOptions = new ManagedMqttClientOptionsBuilder()
  29. .WithMaxPendingMessages(5)
  30. .WithPendingMessagesOverflowStrategy(MqttPendingMessagesOverflowStrategy.DropNewMessage);
  31. clientOptions.WithClientOptions(o => o.WithTcpServer("localhost"));
  32. await managedClient.StartAsync(clientOptions.Build());
  33. await managedClient.PublishAsync(new MqttApplicationMessage { Topic = "1" });
  34. await managedClient.PublishAsync(new MqttApplicationMessage { Topic = "2" });
  35. await managedClient.PublishAsync(new MqttApplicationMessage { Topic = "3" });
  36. await managedClient.PublishAsync(new MqttApplicationMessage { Topic = "4" });
  37. await managedClient.PublishAsync(new MqttApplicationMessage { Topic = "5" });
  38. await managedClient.PublishAsync(new MqttApplicationMessage { Topic = "6" });
  39. await managedClient.PublishAsync(new MqttApplicationMessage { Topic = "7" });
  40. await managedClient.PublishAsync(new MqttApplicationMessage { Topic = "8" });
  41. Assert.AreEqual(5, managedClient.PendingApplicationMessagesCount);
  42. }
  43. finally
  44. {
  45. await managedClient.StopAsync();
  46. }
  47. }
  48. [TestMethod]
  49. public async Task ManagedClients_Will_Message_Send()
  50. {
  51. using (var testEnvironment = new TestEnvironment(TestContext))
  52. {
  53. var receivedMessagesCount = 0;
  54. var factory = new MqttFactory();
  55. await testEnvironment.StartServerAsync();
  56. var willMessage = new MqttApplicationMessageBuilder().WithTopic("My/last/will").WithAtMostOnceQoS().Build();
  57. var clientOptions = new MqttClientOptionsBuilder()
  58. .WithTcpServer("localhost", testEnvironment.ServerPort)
  59. .WithWillMessage(willMessage);
  60. var dyingClient = testEnvironment.CreateClient();
  61. var dyingManagedClient = new ManagedMqttClient(dyingClient, testEnvironment.ClientLogger.CreateChildLogger());
  62. await dyingManagedClient.StartAsync(new ManagedMqttClientOptionsBuilder()
  63. .WithClientOptions(clientOptions)
  64. .Build());
  65. var recievingClient = await testEnvironment.ConnectClientAsync();
  66. await recievingClient.SubscribeAsync("My/last/will");
  67. recievingClient.UseApplicationMessageReceivedHandler(context => Interlocked.Increment(ref receivedMessagesCount));
  68. dyingManagedClient.Dispose();
  69. await Task.Delay(1000);
  70. Assert.AreEqual(1, receivedMessagesCount);
  71. }
  72. }
  73. [TestMethod]
  74. public async Task Start_Stop()
  75. {
  76. using (var testEnvironment = new TestEnvironment(TestContext))
  77. {
  78. var factory = new MqttFactory();
  79. var server = await testEnvironment.StartServerAsync();
  80. var managedClient = new ManagedMqttClient(testEnvironment.CreateClient(), new MqttNetLogger().CreateChildLogger());
  81. var clientOptions = new MqttClientOptionsBuilder()
  82. .WithTcpServer("localhost", testEnvironment.ServerPort);
  83. var connected = GetConnectedTask(managedClient);
  84. await managedClient.StartAsync(new ManagedMqttClientOptionsBuilder()
  85. .WithClientOptions(clientOptions)
  86. .Build());
  87. await connected;
  88. await managedClient.StopAsync();
  89. Assert.AreEqual(0, (await server.GetClientStatusAsync()).Count);
  90. }
  91. }
  92. [TestMethod]
  93. public async Task Storage_Queue_Drains()
  94. {
  95. using (var testEnvironment = new TestEnvironment(TestContext))
  96. {
  97. testEnvironment.IgnoreClientLogErrors = true;
  98. testEnvironment.IgnoreServerLogErrors = true;
  99. var factory = new MqttFactory();
  100. var server = await testEnvironment.StartServerAsync();
  101. var managedClient = new ManagedMqttClient(testEnvironment.CreateClient(), new MqttNetLogger().CreateChildLogger());
  102. var clientOptions = new MqttClientOptionsBuilder()
  103. .WithTcpServer("localhost", testEnvironment.ServerPort);
  104. var storage = new ManagedMqttClientTestStorage();
  105. var connected = GetConnectedTask(managedClient);
  106. await managedClient.StartAsync(new ManagedMqttClientOptionsBuilder()
  107. .WithClientOptions(clientOptions)
  108. .WithStorage(storage)
  109. .WithAutoReconnectDelay(System.TimeSpan.FromSeconds(5))
  110. .Build());
  111. await connected;
  112. await testEnvironment.Server.StopAsync();
  113. await managedClient.PublishAsync(new MqttApplicationMessage { Topic = "1" });
  114. //Message should have been added to the storage queue in PublishAsync,
  115. //and we are awaiting PublishAsync, so the message should already be
  116. //in storage at this point (i.e. no waiting).
  117. Assert.AreEqual(1, storage.GetMessageCount());
  118. connected = GetConnectedTask(managedClient);
  119. await testEnvironment.Server.StartAsync(new MqttServerOptionsBuilder()
  120. .WithDefaultEndpointPort(testEnvironment.ServerPort).Build());
  121. await connected;
  122. //Wait 500ms here so the client has time to publish the queued message
  123. await Task.Delay(500);
  124. Assert.AreEqual(0, storage.GetMessageCount());
  125. await managedClient.StopAsync();
  126. }
  127. }
  128. [TestMethod]
  129. public async Task Subscriptions_And_Unsubscriptions_Are_Made_And_Reestablished_At_Reconnect()
  130. {
  131. using (var testEnvironment = new TestEnvironment(TestContext))
  132. {
  133. var unmanagedClient = testEnvironment.CreateClient();
  134. var managedClient = await CreateManagedClientAsync(testEnvironment, unmanagedClient);
  135. var received = SetupReceivingOfMessages(managedClient, 2);
  136. // Perform some opposing subscriptions and unsubscriptions to verify
  137. // that these conflicting subscriptions are handled correctly
  138. await managedClient.SubscribeAsync("keptSubscribed");
  139. await managedClient.SubscribeAsync("subscribedThenUnsubscribed");
  140. await managedClient.UnsubscribeAsync("subscribedThenUnsubscribed");
  141. await managedClient.UnsubscribeAsync("unsubscribedThenSubscribed");
  142. await managedClient.SubscribeAsync("unsubscribedThenSubscribed");
  143. //wait a bit for the subscriptions to become established before the messages are published
  144. await Task.Delay(500);
  145. var sendingClient = await testEnvironment.ConnectClientAsync();
  146. async Task PublishMessages()
  147. {
  148. await sendingClient.PublishAsync("keptSubscribed", new byte[] { 1 });
  149. await sendingClient.PublishAsync("subscribedThenUnsubscribed", new byte[] { 1 });
  150. await sendingClient.PublishAsync("unsubscribedThenSubscribed", new byte[] { 1 });
  151. }
  152. await PublishMessages();
  153. async Task AssertMessagesReceived()
  154. {
  155. var messages = await received;
  156. Assert.AreEqual("keptSubscribed", messages[0].Topic);
  157. Assert.AreEqual("unsubscribedThenSubscribed", messages[1].Topic);
  158. }
  159. await AssertMessagesReceived();
  160. var connected = GetConnectedTask(managedClient);
  161. await unmanagedClient.DisconnectAsync();
  162. // the managed client has to reconnect by itself
  163. await connected;
  164. // wait a bit so that the managed client can reestablish the subscriptions
  165. await Task.Delay(500);
  166. received = SetupReceivingOfMessages(managedClient, 2);
  167. await PublishMessages();
  168. // and then the same subscriptions need to exist again
  169. await AssertMessagesReceived();
  170. }
  171. }
  172. // This case also serves as a regression test for the previous behavior which re-published
  173. // each and every existing subscriptions with every new subscription that was made
  174. // (causing performance problems and having the visible symptom of retained messages being received again)
  175. [TestMethod]
  176. public async Task Subscriptions_Subscribe_Only_New_Subscriptions()
  177. {
  178. using (var testEnvironment = new TestEnvironment(TestContext))
  179. {
  180. var managedClient = await CreateManagedClientAsync(testEnvironment);
  181. var sendingClient = await testEnvironment.ConnectClientAsync();
  182. await managedClient.SubscribeAsync("topic");
  183. //wait a bit for the subscription to become established
  184. await Task.Delay(500);
  185. await sendingClient.PublishAsync(new MqttApplicationMessage { Topic = "topic", Payload = new byte[] { 1 }, Retain = true });
  186. var messages = await SetupReceivingOfMessages(managedClient, 1);
  187. Assert.AreEqual(1, messages.Count);
  188. Assert.AreEqual("topic", messages.Single().Topic);
  189. await managedClient.SubscribeAsync("anotherTopic");
  190. await Task.Delay(500);
  191. // The subscription of the other topic must not trigger a re-subscription of the existing topic
  192. // (and thus renewed receiving of the retained message)
  193. Assert.AreEqual(1, messages.Count);
  194. }
  195. }
  196. // This case also serves as a regression test for the previous behavior
  197. // that subscriptions were only published at the ConnectionCheckInterval
  198. [TestMethod]
  199. public async Task Subscriptions_Are_Published_Immediately()
  200. {
  201. using (var testEnvironment = new TestEnvironment(TestContext))
  202. {
  203. // Use a long connection check interval to verify that the subscriptions
  204. // do not depend on the connection check interval anymore
  205. var connectionCheckInterval = TimeSpan.FromSeconds(10);
  206. var managedClient = await CreateManagedClientAsync(testEnvironment, null, connectionCheckInterval);
  207. var sendingClient = await testEnvironment.ConnectClientAsync();
  208. await sendingClient.PublishAsync(new MqttApplicationMessage { Topic = "topic", Payload = new byte[] { 1 }, Retain = true });
  209. await managedClient.SubscribeAsync("topic");
  210. var subscribeTime = DateTime.UtcNow;
  211. var messages = await SetupReceivingOfMessages(managedClient, 1);
  212. var elapsed = DateTime.UtcNow - subscribeTime;
  213. Assert.IsTrue(elapsed < TimeSpan.FromSeconds(1), $"Subscriptions must be activated immediately, this one took {elapsed}");
  214. Assert.AreEqual(messages.Single().Topic, "topic");
  215. }
  216. }
  217. [TestMethod]
  218. public async Task Subscriptions_Are_Cleared_At_Logout()
  219. {
  220. using (var testEnvironment = new TestEnvironment(TestContext))
  221. {
  222. var managedClient = await CreateManagedClientAsync(testEnvironment);
  223. var sendingClient = await testEnvironment.ConnectClientAsync();
  224. await sendingClient.PublishAsync(new MqttApplicationMessage
  225. { Topic = "topic", Payload = new byte[] { 1 }, Retain = true });
  226. // Wait a bit for the retained message to be available
  227. await Task.Delay(500);
  228. await managedClient.SubscribeAsync("topic");
  229. await SetupReceivingOfMessages(managedClient, 1);
  230. await managedClient.StopAsync();
  231. var clientOptions = new MqttClientOptionsBuilder()
  232. .WithTcpServer("localhost", testEnvironment.ServerPort);
  233. await managedClient.StartAsync(new ManagedMqttClientOptionsBuilder()
  234. .WithClientOptions(clientOptions)
  235. .WithAutoReconnectDelay(TimeSpan.FromSeconds(1))
  236. .Build());
  237. var messages = new List<MqttApplicationMessage>();
  238. managedClient.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(r =>
  239. {
  240. messages.Add(r.ApplicationMessage);
  241. });
  242. await Task.Delay(500);
  243. // After reconnect and then some delay, the retained message must not be received,
  244. // showing that the subscriptions were cleared
  245. Assert.AreEqual(0, messages.Count);
  246. }
  247. }
  248. private async Task<ManagedMqttClient> CreateManagedClientAsync(
  249. TestEnvironment testEnvironment,
  250. IMqttClient underlyingClient = null,
  251. TimeSpan? connectionCheckInterval = null)
  252. {
  253. await testEnvironment.StartServerAsync();
  254. var clientOptions = new MqttClientOptionsBuilder()
  255. .WithTcpServer("localhost", testEnvironment.ServerPort);
  256. var managedOptions = new ManagedMqttClientOptionsBuilder()
  257. .WithClientOptions(clientOptions)
  258. .Build();
  259. // Use a short connection check interval so that subscription operations are performed quickly
  260. // in order to verify against a previous implementation that performed subscriptions only
  261. // at connection check intervals
  262. managedOptions.ConnectionCheckInterval = connectionCheckInterval ?? TimeSpan.FromSeconds(0.1);
  263. var managedClient =
  264. new ManagedMqttClient(underlyingClient ?? testEnvironment.CreateClient(), new MqttNetLogger().CreateChildLogger());
  265. var connected = GetConnectedTask(managedClient);
  266. await managedClient.StartAsync(managedOptions);
  267. await connected;
  268. return managedClient;
  269. }
  270. /// <summary>
  271. /// Returns a task that will finish when the <paramref name="managedClient"/> has connected
  272. /// </summary>
  273. private Task GetConnectedTask(ManagedMqttClient managedClient)
  274. {
  275. TaskCompletionSource<bool> connected = new TaskCompletionSource<bool>();
  276. managedClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate(e =>
  277. {
  278. managedClient.ConnectedHandler = null;
  279. connected.SetResult(true);
  280. });
  281. return connected.Task;
  282. }
  283. /// <summary>
  284. /// Returns a task that will return the messages received on <paramref name="managedClient"/>
  285. /// when <paramref name="expectedNumberOfMessages"/> have been received
  286. /// </summary>
  287. private Task<List<MqttApplicationMessage>> SetupReceivingOfMessages(ManagedMqttClient managedClient, int expectedNumberOfMessages)
  288. {
  289. var receivedMessages = new List<MqttApplicationMessage>();
  290. var allReceived = new TaskCompletionSource<List<MqttApplicationMessage>>();
  291. managedClient.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(r =>
  292. {
  293. receivedMessages.Add(r.ApplicationMessage);
  294. if (receivedMessages.Count == expectedNumberOfMessages)
  295. {
  296. allReceived.SetResult(receivedMessages);
  297. }
  298. });
  299. return allReceived.Task;
  300. }
  301. }
  302. public class ManagedMqttClientTestStorage : IManagedMqttClientStorage
  303. {
  304. private IList<ManagedMqttApplicationMessage> _messages = null;
  305. public Task<IList<ManagedMqttApplicationMessage>> LoadQueuedMessagesAsync()
  306. {
  307. if (_messages == null)
  308. {
  309. _messages = new List<ManagedMqttApplicationMessage>();
  310. }
  311. return Task.FromResult(_messages);
  312. }
  313. public Task SaveQueuedMessagesAsync(IList<ManagedMqttApplicationMessage> messages)
  314. {
  315. _messages = messages;
  316. return Task.FromResult(0);
  317. }
  318. public int GetMessageCount()
  319. {
  320. return _messages.Count;
  321. }
  322. }
  323. }