25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

MqttClientTests.cs 2.4 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. namespace MQTTnet.Core.Tests
  12. {
  13. [TestClass]
  14. public class MqttClientTests
  15. {
  16. [TestMethod]
  17. public async Task ClientDisconnectException()
  18. {
  19. var factory = new MqttFactory();
  20. var client = factory.CreateMqttClient();
  21. Exception ex = null;
  22. client.Disconnected += (s, e) =>
  23. {
  24. ex = e.Exception;
  25. };
  26. try
  27. {
  28. await client.ConnectAsync(new MqttClientOptionsBuilder().WithTcpServer("wrong-server").Build());
  29. }
  30. catch
  31. {
  32. }
  33. Assert.IsNotNull(ex);
  34. Assert.IsInstanceOfType(ex, typeof(MqttCommunicationException));
  35. Assert.IsInstanceOfType(ex.InnerException, typeof(SocketException));
  36. }
  37. #if DEBUG
  38. [TestMethod]
  39. public async Task ClientCleanupOnAuthentificationFails()
  40. {
  41. var channel = new TestMqttCommunicationAdapter();
  42. var channel2 = new TestMqttCommunicationAdapter();
  43. channel.Partner = channel2;
  44. channel2.Partner = channel;
  45. Task.Run(async () => {
  46. var connect = await channel2.ReceivePacketAsync(TimeSpan.Zero, CancellationToken.None);
  47. await channel2.SendPacketAsync(new MqttConnAckPacket() { ConnectReturnCode = Protocol.MqttConnectReturnCode.ConnectionRefusedNotAuthorized }, CancellationToken.None);
  48. });
  49. var fake = new TestMqttCommunicationAdapterFactory(channel);
  50. var client = new MqttClient(fake, new MqttNetLogger());
  51. try
  52. {
  53. await client.ConnectAsync(new MqttClientOptionsBuilder().WithTcpServer("any-server").Build());
  54. }
  55. catch (Exception ex)
  56. {
  57. Assert.IsInstanceOfType(ex, typeof(MqttConnectingFailedException));
  58. }
  59. Assert.IsTrue(client._packetReceiverTask == null || client._packetReceiverTask.IsCompleted, "receive loop not completed");
  60. Assert.IsTrue(client._keepAliveMessageSenderTask == null || client._keepAliveMessageSenderTask.IsCompleted, "keepalive loop not completed");
  61. }
  62. #endif
  63. }
  64. }