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.
 
 
 
 

407 lines
16 KiB

  1. using System.Collections.Generic;
  2. using System.Threading;
  3. using System.Threading.Tasks;
  4. using Microsoft.VisualStudio.TestTools.UnitTesting;
  5. using MQTTnet.Client;
  6. using MQTTnet.Client.Options;
  7. using MQTTnet.Client.Publishing;
  8. using MQTTnet.Client.Receiving;
  9. using MQTTnet.Client.Subscribing;
  10. using MQTTnet.Client.Unsubscribing;
  11. using MQTTnet.Formatter;
  12. using MQTTnet.Protocol;
  13. using MQTTnet.Server;
  14. using MQTTnet.Tests.Mockups;
  15. namespace MQTTnet.Tests.MQTTv5
  16. {
  17. [TestClass]
  18. public class Client_Tests
  19. {
  20. public TestContext TestContext { get; set; }
  21. [TestMethod]
  22. public async Task Connect_With_New_Mqtt_Features()
  23. {
  24. using (var testEnvironment = new TestEnvironment(TestContext))
  25. {
  26. await testEnvironment.StartServerAsync();
  27. // This test can be also executed against "broker.hivemq.com" to validate package format.
  28. var client = await testEnvironment.ConnectClientAsync(
  29. new MqttClientOptionsBuilder()
  30. //.WithTcpServer("broker.hivemq.com")
  31. .WithTcpServer("127.0.0.1", testEnvironment.ServerPort)
  32. .WithProtocolVersion(MqttProtocolVersion.V500)
  33. .WithTopicAliasMaximum(20)
  34. .WithReceiveMaximum(20)
  35. .WithWillMessage(new MqttApplicationMessageBuilder().WithTopic("abc").Build())
  36. .WithWillDelayInterval(20)
  37. .Build());
  38. MqttApplicationMessage receivedMessage = null;
  39. await client.SubscribeAsync("a");
  40. client.UseApplicationMessageReceivedHandler(context => { receivedMessage = context.ApplicationMessage; });
  41. await client.PublishAsync(new MqttApplicationMessageBuilder()
  42. .WithTopic("a")
  43. .WithPayload("x")
  44. .WithUserProperty("a", "1")
  45. .WithUserProperty("b", "2")
  46. .WithPayloadFormatIndicator(MqttPayloadFormatIndicator.CharacterData)
  47. .WithAtLeastOnceQoS()
  48. .Build());
  49. await Task.Delay(500);
  50. Assert.IsNotNull(receivedMessage);
  51. Assert.AreEqual(2, receivedMessage.UserProperties.Count);
  52. }
  53. }
  54. [TestMethod]
  55. public async Task Connect_With_AssignedClientId()
  56. {
  57. using (var testEnvironment = new TestEnvironment(TestContext))
  58. {
  59. string serverConnectedClientId = null;
  60. string serverDisconnectedClientId = null;
  61. string clientAssignedClientId = null;
  62. // Arrange server
  63. var disconnectedMre = new ManualResetEventSlim();
  64. var serverOptions = new MqttServerOptionsBuilder()
  65. .WithConnectionValidator((context) =>
  66. {
  67. if (string.IsNullOrEmpty(context.ClientId))
  68. {
  69. context.AssignedClientIdentifier = "test123";
  70. context.ReasonCode = MqttConnectReasonCode.Success;
  71. }
  72. });
  73. await testEnvironment.StartServerAsync(serverOptions);
  74. testEnvironment.Server.UseClientConnectedHandler((args) =>
  75. {
  76. serverConnectedClientId = args.ClientId;
  77. });
  78. testEnvironment.Server.UseClientDisconnectedHandler((args) =>
  79. {
  80. serverDisconnectedClientId = args.ClientId;
  81. disconnectedMre.Set();
  82. });
  83. // Arrange client
  84. var client = testEnvironment.CreateClient();
  85. client.UseConnectedHandler((args) =>
  86. {
  87. clientAssignedClientId = args.AuthenticateResult.AssignedClientIdentifier;
  88. });
  89. // Act
  90. await client.ConnectAsync(new MqttClientOptionsBuilder()
  91. .WithTcpServer("127.0.0.1", testEnvironment.ServerPort)
  92. .WithProtocolVersion(MqttProtocolVersion.V500)
  93. .WithClientId(null)
  94. .Build());
  95. await client.DisconnectAsync();
  96. // Wait for ClientDisconnectedHandler to trigger
  97. disconnectedMre.Wait(500);
  98. // Assert
  99. Assert.IsNotNull(serverConnectedClientId);
  100. Assert.IsNotNull(serverDisconnectedClientId);
  101. Assert.IsNotNull(clientAssignedClientId);
  102. Assert.AreEqual("test123", serverConnectedClientId);
  103. Assert.AreEqual("test123", serverDisconnectedClientId);
  104. Assert.AreEqual("test123", clientAssignedClientId);
  105. }
  106. }
  107. [TestMethod]
  108. public async Task Connect()
  109. {
  110. var server = new MqttFactory().CreateMqttServer();
  111. var client = new MqttFactory().CreateMqttClient();
  112. try
  113. {
  114. await server.StartAsync(new MqttServerOptions());
  115. await client.ConnectAsync(new MqttClientOptionsBuilder().WithTcpServer("127.0.0.1").WithProtocolVersion(MqttProtocolVersion.V500).Build());
  116. }
  117. finally
  118. {
  119. await server.StopAsync();
  120. }
  121. }
  122. [TestMethod]
  123. public async Task Connect_And_Disconnect()
  124. {
  125. var server = new MqttFactory().CreateMqttServer();
  126. var client = new MqttFactory().CreateMqttClient();
  127. try
  128. {
  129. await server.StartAsync(new MqttServerOptions());
  130. await client.ConnectAsync(new MqttClientOptionsBuilder().WithTcpServer("127.0.0.1").WithProtocolVersion(MqttProtocolVersion.V500).Build());
  131. await client.DisconnectAsync();
  132. }
  133. finally
  134. {
  135. await server.StopAsync();
  136. }
  137. }
  138. [TestMethod]
  139. public async Task Subscribe()
  140. {
  141. var server = new MqttFactory().CreateMqttServer();
  142. var client = new MqttFactory().CreateMqttClient();
  143. try
  144. {
  145. await server.StartAsync(new MqttServerOptions());
  146. await client.ConnectAsync(new MqttClientOptionsBuilder().WithTcpServer("127.0.0.1").WithProtocolVersion(MqttProtocolVersion.V500).Build());
  147. var result = await client.SubscribeAsync(new MqttClientSubscribeOptions()
  148. {
  149. SubscriptionIdentifier = 1,
  150. TopicFilters = new List<TopicFilter>
  151. {
  152. new TopicFilter { Topic = "a", QualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce}
  153. }
  154. });
  155. await client.DisconnectAsync();
  156. Assert.AreEqual(1, result.Items.Count);
  157. Assert.AreEqual(MqttClientSubscribeResultCode.GrantedQoS1, result.Items[0].ResultCode);
  158. }
  159. finally
  160. {
  161. await server.StopAsync();
  162. }
  163. }
  164. [TestMethod]
  165. public async Task Unsubscribe()
  166. {
  167. var server = new MqttFactory().CreateMqttServer();
  168. var client = new MqttFactory().CreateMqttClient();
  169. try
  170. {
  171. await server.StartAsync(new MqttServerOptions());
  172. await client.ConnectAsync(new MqttClientOptionsBuilder().WithTcpServer("127.0.0.1").WithProtocolVersion(MqttProtocolVersion.V500).Build());
  173. await client.SubscribeAsync("a");
  174. var result = await client.UnsubscribeAsync("a");
  175. await client.DisconnectAsync();
  176. Assert.AreEqual(1, result.Items.Count);
  177. Assert.AreEqual(MqttClientUnsubscribeResultCode.Success, result.Items[0].ReasonCode);
  178. }
  179. finally
  180. {
  181. await server.StopAsync();
  182. }
  183. }
  184. [TestMethod]
  185. public async Task Publish_QoS_0()
  186. {
  187. var server = new MqttFactory().CreateMqttServer();
  188. var client = new MqttFactory().CreateMqttClient();
  189. try
  190. {
  191. await server.StartAsync(new MqttServerOptions());
  192. await client.ConnectAsync(new MqttClientOptionsBuilder().WithTcpServer("127.0.0.1").WithProtocolVersion(MqttProtocolVersion.V500).Build());
  193. var result = await client.PublishAsync("a", "b");
  194. await client.DisconnectAsync();
  195. Assert.AreEqual(MqttClientPublishReasonCode.Success, result.ReasonCode);
  196. }
  197. finally
  198. {
  199. await server.StopAsync();
  200. }
  201. }
  202. [TestMethod]
  203. public async Task Publish_QoS_1()
  204. {
  205. var server = new MqttFactory().CreateMqttServer();
  206. var client = new MqttFactory().CreateMqttClient();
  207. try
  208. {
  209. await server.StartAsync(new MqttServerOptions());
  210. await client.ConnectAsync(new MqttClientOptionsBuilder().WithTcpServer("127.0.0.1").WithProtocolVersion(MqttProtocolVersion.V500).Build());
  211. var result = await client.PublishAsync("a", "b", MqttQualityOfServiceLevel.AtLeastOnce);
  212. await client.DisconnectAsync();
  213. Assert.AreEqual(MqttClientPublishReasonCode.Success, result.ReasonCode);
  214. }
  215. finally
  216. {
  217. await server.StopAsync();
  218. }
  219. }
  220. [TestMethod]
  221. public async Task Publish_QoS_2()
  222. {
  223. var server = new MqttFactory().CreateMqttServer();
  224. var client = new MqttFactory().CreateMqttClient();
  225. try
  226. {
  227. await server.StartAsync(new MqttServerOptions());
  228. await client.ConnectAsync(new MqttClientOptionsBuilder().WithTcpServer("127.0.0.1").WithProtocolVersion(MqttProtocolVersion.V500).Build());
  229. var result = await client.PublishAsync("a", "b", MqttQualityOfServiceLevel.ExactlyOnce);
  230. await client.DisconnectAsync();
  231. Assert.AreEqual(MqttClientPublishReasonCode.Success, result.ReasonCode);
  232. }
  233. finally
  234. {
  235. await server.StopAsync();
  236. }
  237. }
  238. [TestMethod]
  239. public async Task Publish_With_Properties()
  240. {
  241. var server = new MqttFactory().CreateMqttServer();
  242. var client = new MqttFactory().CreateMqttClient();
  243. try
  244. {
  245. await server.StartAsync(new MqttServerOptions());
  246. var applicationMessage = new MqttApplicationMessageBuilder()
  247. .WithTopic("Hello")
  248. .WithPayload("World")
  249. .WithAtMostOnceQoS()
  250. .WithUserProperty("x", "1")
  251. .WithUserProperty("y", "2")
  252. .WithResponseTopic("response")
  253. .WithContentType("text")
  254. .WithMessageExpiryInterval(50)
  255. .WithCorrelationData(new byte[12])
  256. .WithTopicAlias(2)
  257. .Build();
  258. await client.ConnectAsync(new MqttClientOptionsBuilder().WithTcpServer("127.0.0.1").WithProtocolVersion(MqttProtocolVersion.V500).Build());
  259. var result = await client.PublishAsync(applicationMessage);
  260. await client.DisconnectAsync();
  261. Assert.AreEqual(MqttClientPublishReasonCode.Success, result.ReasonCode);
  262. }
  263. finally
  264. {
  265. await server.StopAsync();
  266. }
  267. }
  268. [TestMethod]
  269. public async Task Subscribe_And_Publish()
  270. {
  271. var server = new MqttFactory().CreateMqttServer();
  272. var client1 = new MqttFactory().CreateMqttClient();
  273. var client2 = new MqttFactory().CreateMqttClient();
  274. try
  275. {
  276. await server.StartAsync(new MqttServerOptions());
  277. var receivedMessages = new List<MqttApplicationMessageReceivedEventArgs>();
  278. await client1.ConnectAsync(new MqttClientOptionsBuilder().WithTcpServer("127.0.0.1").WithClientId("client1").WithProtocolVersion(MqttProtocolVersion.V500).Build());
  279. client1.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(e =>
  280. {
  281. lock (receivedMessages)
  282. {
  283. receivedMessages.Add(e);
  284. }
  285. });
  286. await client1.SubscribeAsync("a");
  287. await client2.ConnectAsync(new MqttClientOptionsBuilder().WithTcpServer("127.0.0.1").WithClientId("client2").WithProtocolVersion(MqttProtocolVersion.V500).Build());
  288. await client2.PublishAsync("a", "b");
  289. await Task.Delay(500);
  290. await client2.DisconnectAsync();
  291. await client1.DisconnectAsync();
  292. Assert.AreEqual(1, receivedMessages.Count);
  293. Assert.AreEqual("client1", receivedMessages[0].ClientId);
  294. Assert.AreEqual("a", receivedMessages[0].ApplicationMessage.Topic);
  295. Assert.AreEqual("b", receivedMessages[0].ApplicationMessage.ConvertPayloadToString());
  296. }
  297. finally
  298. {
  299. await server.StopAsync();
  300. }
  301. }
  302. [TestMethod]
  303. public async Task Publish_And_Receive_New_Properties()
  304. {
  305. using (var testEnvironment = new TestEnvironment(TestContext))
  306. {
  307. await testEnvironment.StartServerAsync();
  308. var receiver = await testEnvironment.ConnectClientAsync(new MqttClientOptionsBuilder().WithProtocolVersion(MqttProtocolVersion.V500));
  309. await receiver.SubscribeAsync("#");
  310. MqttApplicationMessage receivedMessage = null;
  311. receiver.UseApplicationMessageReceivedHandler(c =>
  312. {
  313. receivedMessage = c.ApplicationMessage;
  314. });
  315. var sender = await testEnvironment.ConnectClientAsync(new MqttClientOptionsBuilder().WithProtocolVersion(MqttProtocolVersion.V500));
  316. var applicationMessage = new MqttApplicationMessageBuilder()
  317. .WithTopic("Hello")
  318. .WithPayload("World")
  319. .WithAtMostOnceQoS()
  320. .WithUserProperty("x", "1")
  321. .WithUserProperty("y", "2")
  322. .WithResponseTopic("response")
  323. .WithContentType("text")
  324. .WithMessageExpiryInterval(50)
  325. .WithCorrelationData(new byte[12])
  326. .WithTopicAlias(2)
  327. .Build();
  328. await sender.PublishAsync(applicationMessage);
  329. await Task.Delay(500);
  330. Assert.IsNotNull(receivedMessage);
  331. Assert.AreEqual(applicationMessage.Topic, receivedMessage.Topic);
  332. Assert.AreEqual(applicationMessage.TopicAlias, receivedMessage.TopicAlias);
  333. Assert.AreEqual(applicationMessage.ContentType, receivedMessage.ContentType);
  334. Assert.AreEqual(applicationMessage.ResponseTopic, receivedMessage.ResponseTopic);
  335. Assert.AreEqual(applicationMessage.MessageExpiryInterval, receivedMessage.MessageExpiryInterval);
  336. CollectionAssert.AreEqual(applicationMessage.CorrelationData, receivedMessage.CorrelationData);
  337. CollectionAssert.AreEqual(applicationMessage.Payload, receivedMessage.Payload);
  338. CollectionAssert.AreEqual(applicationMessage.UserProperties, receivedMessage.UserProperties);
  339. }
  340. }
  341. }
  342. }