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.
 
 
 
 

77 lines
2.6 KiB

  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 MqttFactory_Tests
  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. string invalidLogId = null;
  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. invalidLogId = e.TraceMessage.LogId;
  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. invalidLogId = e.TraceMessage.LogId;
  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.ConnectingFailedHandler = new ConnectingFailedHandlerDelegate(e => tcs.TrySetResult(null));
  52. await Task.WhenAny(Task.Delay(managedClient.Options.ClientOptions.CommunicationTimeout), tcs.Task);
  53. }
  54. finally
  55. {
  56. await managedClient.StopAsync();
  57. MqttNetGlobalLogger.LogMessagePublished -= globalLog;
  58. }
  59. Assert.IsNull(invalidLogId);
  60. Assert.AreNotEqual(0, globalLogCount);
  61. Assert.AreEqual(globalLogCount, localLogCount);
  62. }
  63. }
  64. }