Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 

91 linhas
2.7 KiB

  1. using System;
  2. using System.Linq;
  3. using System.Threading.Tasks;
  4. using Microsoft.VisualStudio.TestTools.UnitTesting;
  5. using MQTTnet.Core.Exceptions;
  6. using MQTTnet.Core.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. }