Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 
 

472 righe
16 KiB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Threading;
  5. using System.Threading.Tasks;
  6. using Microsoft.VisualStudio.TestTools.UnitTesting;
  7. using MQTTnet.Diagnostics;
  8. using MQTTnet.Protocol;
  9. using MQTTnet.Server;
  10. using MQTTnet.Client;
  11. namespace MQTTnet.Core.Tests
  12. {
  13. [TestClass]
  14. public class MqttServerTests
  15. {
  16. [TestMethod]
  17. public void MqttServer_PublishSimple_AtMostOnce()
  18. {
  19. TestPublishAsync(
  20. "A/B/C",
  21. MqttQualityOfServiceLevel.AtMostOnce,
  22. "A/B/C",
  23. MqttQualityOfServiceLevel.AtMostOnce,
  24. 1).Wait();
  25. }
  26. [TestMethod]
  27. public void MqttServer_PublishSimple_AtLeastOnce()
  28. {
  29. TestPublishAsync(
  30. "A/B/C",
  31. MqttQualityOfServiceLevel.AtLeastOnce,
  32. "A/B/C",
  33. MqttQualityOfServiceLevel.AtLeastOnce,
  34. 1).Wait();
  35. }
  36. [TestMethod]
  37. public void MqttServer_PublishSimple_ExactlyOnce()
  38. {
  39. TestPublishAsync(
  40. "A/B/C",
  41. MqttQualityOfServiceLevel.ExactlyOnce,
  42. "A/B/C",
  43. MqttQualityOfServiceLevel.ExactlyOnce,
  44. 1).Wait();
  45. }
  46. [TestMethod]
  47. public async Task MqttServer_WillMessage()
  48. {
  49. var serverAdapter = new TestMqttServerAdapter();
  50. var s = new MqttFactory().CreateMqttServer(new[] { serverAdapter }, new MqttNetLogger());
  51. var receivedMessagesCount = 0;
  52. try
  53. {
  54. await s.StartAsync(new MqttServerOptions());
  55. var willMessage = new MqttApplicationMessageBuilder().WithTopic("My/last/will").WithAtMostOnceQoS().Build();
  56. var c1 = await serverAdapter.ConnectTestClient("c1");
  57. var c2 = await serverAdapter.ConnectTestClient("c2", willMessage);
  58. c1.ApplicationMessageReceived += (_, __) => receivedMessagesCount++;
  59. await c1.SubscribeAsync(new TopicFilterBuilder().WithTopic("#").Build());
  60. await c2.DisconnectAsync();
  61. await Task.Delay(1000);
  62. await c1.DisconnectAsync();
  63. }
  64. finally
  65. {
  66. await s.StopAsync();
  67. }
  68. Assert.AreEqual(0, receivedMessagesCount);
  69. }
  70. [TestMethod]
  71. public async Task MqttServer_SubscribeUnsubscribe()
  72. {
  73. var serverAdapter = new TestMqttServerAdapter();
  74. var s = new MqttFactory().CreateMqttServer(new[] { serverAdapter }, new MqttNetLogger());
  75. var receivedMessagesCount = 0;
  76. try
  77. {
  78. await s.StartAsync(new MqttServerOptions());
  79. var c1 = await serverAdapter.ConnectTestClient("c1");
  80. var c2 = await serverAdapter.ConnectTestClient("c2");
  81. c1.ApplicationMessageReceived += (_, __) => receivedMessagesCount++;
  82. var message = new MqttApplicationMessageBuilder().WithTopic("a").WithAtLeastOnceQoS().Build();
  83. await c2.PublishAsync(message);
  84. Assert.AreEqual(0, receivedMessagesCount);
  85. var subscribeEventCalled = false;
  86. s.ClientSubscribedTopic += (_, e) =>
  87. {
  88. subscribeEventCalled = e.TopicFilter.Topic == "a" && e.ClientId == "c1";
  89. };
  90. await c1.SubscribeAsync(new TopicFilter("a", MqttQualityOfServiceLevel.AtLeastOnce));
  91. await Task.Delay(100);
  92. Assert.IsTrue(subscribeEventCalled, "Subscribe event not called.");
  93. await c2.PublishAsync(message);
  94. await Task.Delay(500);
  95. Assert.AreEqual(1, receivedMessagesCount);
  96. var unsubscribeEventCalled = false;
  97. s.ClientUnsubscribedTopic += (_, e) =>
  98. {
  99. unsubscribeEventCalled = e.TopicFilter == "a" && e.ClientId == "c1";
  100. };
  101. await c1.UnsubscribeAsync("a");
  102. await Task.Delay(100);
  103. Assert.IsTrue(unsubscribeEventCalled, "Unsubscribe event not called.");
  104. await c2.PublishAsync(message);
  105. await Task.Delay(500);
  106. Assert.AreEqual(1, receivedMessagesCount);
  107. }
  108. finally
  109. {
  110. await s.StopAsync();
  111. }
  112. await Task.Delay(500);
  113. Assert.AreEqual(1, receivedMessagesCount);
  114. }
  115. [TestMethod]
  116. public async Task MqttServer_Publish()
  117. {
  118. var serverAdapter = new TestMqttServerAdapter();
  119. var s = new MqttFactory().CreateMqttServer(new[] { serverAdapter }, new MqttNetLogger());
  120. var receivedMessagesCount = 0;
  121. try
  122. {
  123. await s.StartAsync(new MqttServerOptions());
  124. var c1 = await serverAdapter.ConnectTestClient("c1");
  125. c1.ApplicationMessageReceived += (_, __) => receivedMessagesCount++;
  126. var message = new MqttApplicationMessageBuilder().WithTopic("a").WithAtLeastOnceQoS().Build();
  127. await c1.SubscribeAsync(new TopicFilter("a", MqttQualityOfServiceLevel.AtLeastOnce));
  128. await s.PublishAsync(message);
  129. await Task.Delay(500);
  130. }
  131. finally
  132. {
  133. await s.StopAsync();
  134. }
  135. Assert.AreEqual(1, receivedMessagesCount);
  136. }
  137. [TestMethod]
  138. public async Task MqttServer_RetainedMessagesFlow()
  139. {
  140. var retainedMessage = new MqttApplicationMessageBuilder().WithTopic("r").WithPayload("r").WithRetainFlag().Build();
  141. var serverAdapter = new TestMqttServerAdapter();
  142. var s = new MqttFactory().CreateMqttServer(new[] { serverAdapter }, new MqttNetLogger());
  143. await s.StartAsync(new MqttServerOptions());
  144. var c1 = await serverAdapter.ConnectTestClient("c1");
  145. await c1.PublishAsync(retainedMessage);
  146. Thread.Sleep(500);
  147. await c1.DisconnectAsync();
  148. Thread.Sleep(500);
  149. var receivedMessages = 0;
  150. var c2 = await serverAdapter.ConnectTestClient("c2");
  151. c2.ApplicationMessageReceived += (_, e) =>
  152. {
  153. receivedMessages++;
  154. };
  155. for (var i = 0; i < 5; i++)
  156. {
  157. await c2.UnsubscribeAsync("r");
  158. await Task.Delay(500);
  159. Assert.AreEqual(i, receivedMessages);
  160. await c2.SubscribeAsync("r");
  161. await Task.Delay(500);
  162. Assert.AreEqual(i + 1, receivedMessages);
  163. }
  164. await c2.DisconnectAsync();
  165. }
  166. [TestMethod]
  167. public async Task MqttServer_NoRetainedMessage()
  168. {
  169. var serverAdapter = new TestMqttServerAdapter();
  170. var s = new MqttFactory().CreateMqttServer(new[] { serverAdapter }, new MqttNetLogger());
  171. var receivedMessagesCount = 0;
  172. try
  173. {
  174. await s.StartAsync(new MqttServerOptions());
  175. var c1 = await serverAdapter.ConnectTestClient("c1");
  176. await c1.PublishAsync(new MqttApplicationMessageBuilder().WithTopic("retained").WithPayload(new byte[3]).Build());
  177. await c1.DisconnectAsync();
  178. var c2 = await serverAdapter.ConnectTestClient("c2");
  179. c2.ApplicationMessageReceived += (_, __) => receivedMessagesCount++;
  180. await c2.SubscribeAsync(new TopicFilterBuilder().WithTopic("retained").Build());
  181. await Task.Delay(500);
  182. }
  183. finally
  184. {
  185. await s.StopAsync();
  186. }
  187. Assert.AreEqual(0, receivedMessagesCount);
  188. }
  189. [TestMethod]
  190. public async Task MqttServer_RetainedMessage()
  191. {
  192. var serverAdapter = new TestMqttServerAdapter();
  193. var s = new MqttFactory().CreateMqttServer(new[] { serverAdapter }, new MqttNetLogger());
  194. var receivedMessagesCount = 0;
  195. try
  196. {
  197. await s.StartAsync(new MqttServerOptions());
  198. var c1 = await serverAdapter.ConnectTestClient("c1");
  199. await c1.PublishAndWaitForAsync(s, new MqttApplicationMessageBuilder().WithTopic("retained").WithPayload(new byte[3]).WithRetainFlag().Build());
  200. await c1.DisconnectAsync();
  201. var c2 = await serverAdapter.ConnectTestClient("c2");
  202. c2.ApplicationMessageReceived += (_, __) => receivedMessagesCount++;
  203. await c2.SubscribeAsync(new TopicFilterBuilder().WithTopic("retained").Build());
  204. await Task.Delay(500);
  205. }
  206. finally
  207. {
  208. await s.StopAsync();
  209. }
  210. Assert.AreEqual(1, receivedMessagesCount);
  211. }
  212. [TestMethod]
  213. public async Task MqttServer_ClearRetainedMessage()
  214. {
  215. var serverAdapter = new TestMqttServerAdapter();
  216. var s = new MqttFactory().CreateMqttServer(new[] { serverAdapter }, new MqttNetLogger());
  217. var receivedMessagesCount = 0;
  218. try
  219. {
  220. await s.StartAsync(new MqttServerOptions());
  221. var c1 = await serverAdapter.ConnectTestClient("c1");
  222. await c1.PublishAsync(new MqttApplicationMessageBuilder().WithTopic("retained").WithPayload(new byte[3]).WithRetainFlag().Build());
  223. await c1.PublishAsync(new MqttApplicationMessageBuilder().WithTopic("retained").WithPayload(new byte[0]).WithRetainFlag().Build());
  224. await c1.DisconnectAsync();
  225. var c2 = await serverAdapter.ConnectTestClient("c2");
  226. c2.ApplicationMessageReceived += (_, __) => receivedMessagesCount++;
  227. await Task.Delay(200);
  228. await c2.SubscribeAsync(new TopicFilter("retained", MqttQualityOfServiceLevel.AtMostOnce));
  229. await Task.Delay(500);
  230. }
  231. finally
  232. {
  233. await s.StopAsync();
  234. }
  235. Assert.AreEqual(0, receivedMessagesCount);
  236. }
  237. [TestMethod]
  238. public async Task MqttServer_PersistRetainedMessage()
  239. {
  240. var storage = new TestStorage();
  241. var serverAdapter = new TestMqttServerAdapter();
  242. var s = new MqttFactory().CreateMqttServer(new[] { serverAdapter }, new MqttNetLogger());
  243. try
  244. {
  245. var options = new MqttServerOptions { Storage = storage };
  246. await s.StartAsync(options);
  247. var c1 = await serverAdapter.ConnectTestClient("c1");
  248. await c1.PublishAndWaitForAsync(s, new MqttApplicationMessageBuilder().WithTopic("retained").WithPayload(new byte[3]).WithRetainFlag().Build());
  249. await c1.DisconnectAsync();
  250. }
  251. finally
  252. {
  253. await s.StopAsync();
  254. }
  255. Assert.AreEqual(1, storage.Messages.Count);
  256. s = new MqttFactory().CreateMqttServer(new[] { serverAdapter }, new MqttNetLogger());
  257. var receivedMessagesCount = 0;
  258. try
  259. {
  260. var options = new MqttServerOptions { Storage = storage };
  261. await s.StartAsync(options);
  262. var c2 = await serverAdapter.ConnectTestClient("c2");
  263. c2.ApplicationMessageReceived += (_, __) => receivedMessagesCount++;
  264. await c2.SubscribeAsync(new TopicFilterBuilder().WithTopic("retained").Build());
  265. await Task.Delay(500);
  266. }
  267. finally
  268. {
  269. await s.StopAsync();
  270. }
  271. Assert.AreEqual(1, receivedMessagesCount);
  272. }
  273. [TestMethod]
  274. public async Task MqttServer_InterceptMessage()
  275. {
  276. void Interceptor(MqttApplicationMessageInterceptorContext context)
  277. {
  278. context.ApplicationMessage.Payload = Encoding.ASCII.GetBytes("extended");
  279. }
  280. var serverAdapter = new TestMqttServerAdapter();
  281. var s = new MqttFactory().CreateMqttServer(new[] { serverAdapter }, new MqttNetLogger());
  282. try
  283. {
  284. var options = new MqttServerOptions { ApplicationMessageInterceptor = Interceptor };
  285. await s.StartAsync(options);
  286. var c1 = await serverAdapter.ConnectTestClient("c1");
  287. var c2 = await serverAdapter.ConnectTestClient("c2");
  288. await c2.SubscribeAsync(new TopicFilterBuilder().WithTopic("test").Build());
  289. var isIntercepted = false;
  290. c2.ApplicationMessageReceived += (sender, args) =>
  291. {
  292. isIntercepted = string.Compare("extended", Encoding.UTF8.GetString(args.ApplicationMessage.Payload), StringComparison.Ordinal) == 0;
  293. };
  294. var m = new MqttApplicationMessageBuilder().WithTopic("test").Build();
  295. await c1.PublishAsync(m);
  296. await c1.DisconnectAsync();
  297. await Task.Delay(500);
  298. Assert.IsTrue(isIntercepted);
  299. }
  300. finally
  301. {
  302. await s.StopAsync();
  303. }
  304. }
  305. [TestMethod]
  306. public async Task MqttServer_Body()
  307. {
  308. var serverAdapter = new TestMqttServerAdapter();
  309. var s = new MqttFactory().CreateMqttServer(new[] { serverAdapter }, new MqttNetLogger());
  310. var bodyIsMatching = false;
  311. try
  312. {
  313. await s.StartAsync(new MqttServerOptions());
  314. var c1 = await serverAdapter.ConnectTestClient("c1");
  315. var c2 = await serverAdapter.ConnectTestClient("c2");
  316. c1.ApplicationMessageReceived += (_, e) =>
  317. {
  318. if (Encoding.UTF8.GetString(e.ApplicationMessage.Payload) == "The body")
  319. {
  320. bodyIsMatching = true;
  321. }
  322. };
  323. await c1.SubscribeAsync("A", MqttQualityOfServiceLevel.AtMostOnce);
  324. await c2.PublishAsync(new MqttApplicationMessageBuilder().WithTopic("A").WithPayload(Encoding.UTF8.GetBytes("The body")).Build());
  325. await Task.Delay(500);
  326. }
  327. finally
  328. {
  329. await s.StopAsync();
  330. }
  331. Assert.IsTrue(bodyIsMatching);
  332. }
  333. private class TestStorage : IMqttServerStorage
  334. {
  335. public IList<MqttApplicationMessage> Messages = new List<MqttApplicationMessage>();
  336. public Task SaveRetainedMessagesAsync(IList<MqttApplicationMessage> messages)
  337. {
  338. Messages = messages;
  339. return Task.CompletedTask;
  340. }
  341. public Task<IList<MqttApplicationMessage>> LoadRetainedMessagesAsync()
  342. {
  343. return Task.FromResult(Messages);
  344. }
  345. }
  346. private static async Task TestPublishAsync(
  347. string topic,
  348. MqttQualityOfServiceLevel qualityOfServiceLevel,
  349. string topicFilter,
  350. MqttQualityOfServiceLevel filterQualityOfServiceLevel,
  351. int expectedReceivedMessagesCount)
  352. {
  353. var serverAdapter = new TestMqttServerAdapter();
  354. var s = new MqttFactory().CreateMqttServer(new[] { serverAdapter }, new MqttNetLogger());
  355. var receivedMessagesCount = 0;
  356. try
  357. {
  358. await s.StartAsync(new MqttServerOptions());
  359. var c1 = await serverAdapter.ConnectTestClient("c1");
  360. var c2 = await serverAdapter.ConnectTestClient("c2");
  361. c1.ApplicationMessageReceived += (_, __) => receivedMessagesCount++;
  362. await c1.SubscribeAsync(new TopicFilterBuilder().WithTopic(topicFilter).WithQualityOfServiceLevel(filterQualityOfServiceLevel).Build());
  363. await c2.PublishAsync(new MqttApplicationMessageBuilder().WithTopic(topic).WithPayload(new byte[0]).WithQualityOfServiceLevel(qualityOfServiceLevel).Build());
  364. await Task.Delay(500);
  365. await c1.UnsubscribeAsync(topicFilter);
  366. await Task.Delay(500);
  367. }
  368. finally
  369. {
  370. await s.StopAsync();
  371. }
  372. Assert.AreEqual(expectedReceivedMessagesCount, receivedMessagesCount);
  373. }
  374. }
  375. }