Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 

101 lignes
3.1 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 tasks = Enumerable.Range(0, 100000)
  75. .Select(i =>
  76. {
  77. return MqttTaskTimeout.WaitAsync(ct => Task.Delay(TimeSpan.FromMilliseconds(1), ct),
  78. TimeSpan.FromMinutes(1), CancellationToken.None);
  79. });
  80. await Task.WhenAll(tasks);
  81. AssertIsLess(3_000_000, GC.GetTotalMemory(true));
  82. }
  83. private static void AssertIsLess(long bound, long actual)
  84. {
  85. if (bound < actual)
  86. {
  87. Assert.Fail($"value must be less than {bound:N0} but is {actual:N0}");
  88. }
  89. }
  90. }
  91. }