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.
 
 
 
 

81 lines
2.7 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. var logId = "logId";
  19. var hasInvalidLogId = false;
  20. // 2. if the total log calls are the same for global and local
  21. //var globalLogCount = 0;
  22. var localLogCount = 0;
  23. var logger = new MqttNetLogger(logId);
  24. // TODO: This is commented out because it is affected by other tests.
  25. //// we have a theoretical bug here if a concurrent test is also logging
  26. //var globalLog = new EventHandler<MqttNetLogMessagePublishedEventArgs>((s, e) =>
  27. //{
  28. // if (e.TraceMessage.LogId != logId)
  29. // {
  30. // invalidLogId = e.TraceMessage.LogId;
  31. // }
  32. // Interlocked.Increment(ref globalLogCount);
  33. //});
  34. //MqttNetGlobalLogger.LogMessagePublished += globalLog;
  35. logger.LogMessagePublished += (s, e) =>
  36. {
  37. if (e.LogMessage.LogId != logId)
  38. {
  39. hasInvalidLogId = true;
  40. }
  41. Interlocked.Increment(ref localLogCount);
  42. };
  43. var managedClient = factory.CreateManagedMqttClient(logger);
  44. try
  45. {
  46. var clientOptions = new ManagedMqttClientOptionsBuilder();
  47. clientOptions.WithClientOptions(o => o.WithTcpServer("this_is_an_invalid_host").WithCommunicationTimeout(TimeSpan.FromSeconds(1)));
  48. // try connect to get some log entries
  49. await managedClient.StartAsync(clientOptions.Build());
  50. // wait at least connect timeout or we have some log messages
  51. var tcs = new TaskCompletionSource<object>();
  52. managedClient.ConnectingFailedHandler = new ConnectingFailedHandlerDelegate(e => tcs.TrySetResult(null));
  53. await Task.WhenAny(Task.Delay(managedClient.Options.ClientOptions.CommunicationTimeout), tcs.Task);
  54. }
  55. finally
  56. {
  57. await managedClient.StopAsync();
  58. //MqttNetGlobalLogger.LogMessagePublished -= globalLog;
  59. }
  60. await Task.Delay(500);
  61. Assert.IsFalse(hasInvalidLogId);
  62. Assert.AreNotEqual(0, localLogCount);
  63. }
  64. }
  65. }