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.

MqttClientTests.cs 2.5 KiB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using System;
  2. using System.Net.Sockets;
  3. using System.Threading;
  4. using System.Threading.Tasks;
  5. using Microsoft.VisualStudio.TestTools.UnitTesting;
  6. using MQTTnet.Adapter;
  7. using MQTTnet.Client;
  8. using MQTTnet.Diagnostics;
  9. using MQTTnet.Exceptions;
  10. using MQTTnet.Packets;
  11. using MQTTnet.Implementations;
  12. using MQTTnet.Server;
  13. namespace MQTTnet.Core.Tests
  14. {
  15. [TestClass]
  16. public class MqttClientTests
  17. {
  18. [TestMethod]
  19. public async Task ClientDisconnectException()
  20. {
  21. var factory = new MqttFactory();
  22. var client = factory.CreateMqttClient();
  23. Exception ex = null;
  24. client.Disconnected += (s, e) =>
  25. {
  26. ex = e.Exception;
  27. };
  28. try
  29. {
  30. await client.ConnectAsync(new MqttClientOptionsBuilder().WithTcpServer("wrong-server").Build());
  31. }
  32. catch
  33. {
  34. }
  35. Assert.IsNotNull(ex);
  36. Assert.IsInstanceOfType(ex, typeof(MqttCommunicationException));
  37. Assert.IsInstanceOfType(ex.InnerException, typeof(SocketException));
  38. }
  39. [TestMethod]
  40. public async Task ClientCleanupOnAuthentificationFails()
  41. {
  42. var channel = new TestMqttCommunicationAdapter();
  43. var channel2 = new TestMqttCommunicationAdapter();
  44. channel.Partner = channel2;
  45. channel2.Partner = channel;
  46. Task.Run(async () => {
  47. var connect = await channel2.ReceivePacketAsync(TimeSpan.Zero, CancellationToken.None);
  48. await channel2.SendPacketAsync(new MqttConnAckPacket() { ConnectReturnCode = Protocol.MqttConnectReturnCode.ConnectionRefusedNotAuthorized }, CancellationToken.None);
  49. });
  50. var fake = new TestMqttCommunicationAdapterFactory(channel);
  51. var client = new MqttClient(fake, new MqttNetLogger());
  52. try
  53. {
  54. await client.ConnectAsync(new MqttClientOptionsBuilder().WithTcpServer("any-server").Build());
  55. }
  56. catch (Exception ex)
  57. {
  58. Assert.IsInstanceOfType(ex, typeof(MqttConnectingFailedException));
  59. }
  60. Assert.IsTrue(client._packetReceiverTask == null || client._packetReceiverTask.IsCompleted, "receive loop not completed");
  61. Assert.IsTrue(client._keepAliveMessageSenderTask == null || client._keepAliveMessageSenderTask.IsCompleted, "keepalive loop not completed");
  62. }
  63. }
  64. }