Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

ExtensionTests.cs 2.7 KiB

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