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.

MqttFactoryTests.cs 2.6 KiB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. using Microsoft.VisualStudio.TestTools.UnitTesting;
  2. using MQTTnet.Diagnostics;
  3. using MQTTnet.Extensions.ManagedClient;
  4. using System;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. namespace MQTTnet.Tests
  8. {
  9. [TestClass]
  10. public class MqttFactoryTests
  11. {
  12. [TestMethod]
  13. public async Task Create_Managed_Client_With_Logger()
  14. {
  15. var factory = new MqttFactory();
  16. //This test compares
  17. //1. correct logID
  18. string logId = "logId";
  19. bool invalidLogIdOccured = false;
  20. //2. if the total log calls are the same for global and local
  21. int globalLogCount = 0;
  22. int localLogCount = 0;
  23. MqttNetLogger logger = new MqttNetLogger(logId);
  24. //we have a theoretical bug here if a concurrent test is also logging
  25. var globalLog = new EventHandler<MqttNetLogMessagePublishedEventArgs>((s, e) =>
  26. {
  27. if (logId != e.TraceMessage.LogId)
  28. {
  29. invalidLogIdOccured = true;
  30. }
  31. Interlocked.Increment(ref globalLogCount);
  32. });
  33. MqttNetGlobalLogger.LogMessagePublished += globalLog;
  34. logger.LogMessagePublished += (s, e) =>
  35. {
  36. if (logId != e.TraceMessage.LogId)
  37. {
  38. invalidLogIdOccured = true;
  39. }
  40. Interlocked.Increment(ref localLogCount);
  41. };
  42. var managedClient = factory.CreateManagedMqttClient(logger);
  43. try
  44. {
  45. var clientOptions = new ManagedMqttClientOptionsBuilder();
  46. clientOptions.WithClientOptions(o => o.WithTcpServer("this_is_an_invalid_host").WithCommunicationTimeout(TimeSpan.FromSeconds(1)));
  47. //try connect to get some log entries
  48. await managedClient.StartAsync(clientOptions.Build());
  49. //wait at least connect timeout or we have some log messages
  50. var tcs = new TaskCompletionSource<object>();
  51. managedClient.ConnectingFailed += (s, e) => tcs.TrySetResult(null);
  52. await Task.WhenAny(Task.Delay(managedClient.Options.ClientOptions.CommunicationTimeout), tcs.Task);
  53. }
  54. finally
  55. {
  56. MqttNetGlobalLogger.LogMessagePublished -= globalLog;
  57. await managedClient.StopAsync();
  58. }
  59. Assert.IsFalse(invalidLogIdOccured);
  60. Assert.AreNotEqual(0, globalLogCount);
  61. Assert.AreEqual(globalLogCount, localLogCount);
  62. }
  63. }
  64. }