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.
 
 
 
 

103 regels
3.2 KiB

  1. using System;
  2. using System.Linq;
  3. using System.Threading;
  4. using System.Threading.Tasks;
  5. using Microsoft.VisualStudio.TestTools.UnitTesting;
  6. using MQTTnet.Exceptions;
  7. using MQTTnet.Internal;
  8. namespace MQTTnet.Tests
  9. {
  10. [TestClass]
  11. public class Extension_Tests
  12. {
  13. [ExpectedException(typeof(MqttCommunicationTimedOutException))]
  14. [TestMethod]
  15. public async Task TimeoutAfter()
  16. {
  17. await MqttTaskTimeout.WaitAsync(ct => Task.Delay(TimeSpan.FromMilliseconds(500), ct),
  18. TimeSpan.FromMilliseconds(100), CancellationToken.None);
  19. }
  20. [ExpectedException(typeof(MqttCommunicationTimedOutException))]
  21. [TestMethod]
  22. public async Task TimeoutAfterWithResult()
  23. {
  24. await MqttTaskTimeout.WaitAsync(
  25. ct => Task.Delay(TimeSpan.FromMilliseconds(500), ct).ContinueWith(t => 5, ct),
  26. TimeSpan.FromMilliseconds(100), CancellationToken.None);
  27. }
  28. [TestMethod]
  29. public async Task TimeoutAfterCompleteInTime()
  30. {
  31. var result = await MqttTaskTimeout.WaitAsync(
  32. ct => Task.Delay(TimeSpan.FromMilliseconds(100), ct).ContinueWith(t => 5, ct),
  33. TimeSpan.FromMilliseconds(500), CancellationToken.None);
  34. Assert.AreEqual(5, result);
  35. }
  36. [TestMethod]
  37. public async Task TimeoutAfterWithInnerException()
  38. {
  39. try
  40. {
  41. await MqttTaskTimeout.WaitAsync(ct => Task.Run(() =>
  42. {
  43. var iis = new int[0];
  44. iis[1] = 0;
  45. }, ct), TimeSpan.FromSeconds(1), CancellationToken.None);
  46. Assert.Fail();
  47. }
  48. catch (Exception e)
  49. {
  50. Assert.IsTrue(e is IndexOutOfRangeException);
  51. }
  52. }
  53. [TestMethod]
  54. public async Task TimeoutAfterWithInnerExceptionWithResult()
  55. {
  56. try
  57. {
  58. await MqttTaskTimeout.WaitAsync(ct => Task.Run(() =>
  59. {
  60. var iis = new int[0];
  61. iis[1] = 0;
  62. return iis[0];
  63. }, ct), TimeSpan.FromSeconds(1), CancellationToken.None);
  64. Assert.Fail();
  65. }
  66. catch (Exception e)
  67. {
  68. Assert.IsTrue(e is IndexOutOfRangeException);
  69. }
  70. }
  71. [TestMethod]
  72. public async Task TimeoutAfterMemoryUsage()
  73. {
  74. var initialMemory = GC.GetTotalMemory(true);
  75. var tasks = Enumerable.Range(0, 100000)
  76. .Select(i =>
  77. {
  78. return MqttTaskTimeout.WaitAsync(ct => Task.Delay(TimeSpan.FromMilliseconds(1), ct),
  79. TimeSpan.FromMinutes(1), CancellationToken.None);
  80. });
  81. await Task.WhenAll(tasks);
  82. AssertIsLess(initialMemory + 2_000_000, GC.GetTotalMemory(true));
  83. }
  84. static void AssertIsLess(long bound, long actual)
  85. {
  86. if (bound < actual)
  87. {
  88. Assert.Fail($"value must be less than {bound:N0} but is {actual:N0}");
  89. }
  90. }
  91. }
  92. }