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.

AsyncQueue_Tests.cs 2.6 KiB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. using System.Threading;
  2. using System.Threading.Tasks;
  3. using Microsoft.VisualStudio.TestTools.UnitTesting;
  4. using MQTTnet.Internal;
  5. namespace MQTTnet.Tests
  6. {
  7. [TestClass]
  8. public class AsyncQueue_Tests
  9. {
  10. [TestMethod]
  11. public async Task Preserve_Order()
  12. {
  13. var queue = new AsyncQueue<string>();
  14. queue.Enqueue("1");
  15. queue.Enqueue("2");
  16. queue.Enqueue("3");
  17. Assert.AreEqual("1", (await queue.TryDequeueAsync(CancellationToken.None)).Item);
  18. Assert.AreEqual("2", (await queue.TryDequeueAsync(CancellationToken.None)).Item);
  19. Assert.AreEqual("3", (await queue.TryDequeueAsync(CancellationToken.None)).Item);
  20. }
  21. [TestMethod]
  22. public void Count()
  23. {
  24. var queue = new AsyncQueue<string>();
  25. queue.Enqueue("1");
  26. Assert.AreEqual(1, queue.Count);
  27. queue.Enqueue("2");
  28. Assert.AreEqual(2, queue.Count);
  29. queue.Enqueue("3");
  30. Assert.AreEqual(3, queue.Count);
  31. }
  32. [TestMethod]
  33. public async Task Preserve_ProcessAsync()
  34. {
  35. var queue = new AsyncQueue<int>();
  36. var sum = 0;
  37. var worker = Task.Run(async () =>
  38. {
  39. while (sum < 6)
  40. {
  41. sum += (await queue.TryDequeueAsync(CancellationToken.None)).Item;
  42. }
  43. });
  44. queue.Enqueue(1);
  45. await Task.Delay(500);
  46. queue.Enqueue(2);
  47. await Task.Delay(500);
  48. queue.Enqueue(3);
  49. await Task.Delay(500);
  50. Assert.AreEqual(6, sum);
  51. Assert.AreEqual(TaskStatus.RanToCompletion, worker.Status);
  52. }
  53. [TestMethod]
  54. public void Dequeue_Sync()
  55. {
  56. var queue = new AsyncQueue<string>();
  57. queue.Enqueue("1");
  58. queue.Enqueue("2");
  59. queue.Enqueue("3");
  60. Assert.AreEqual("1", queue.TryDequeue().Item);
  61. Assert.AreEqual("2", queue.TryDequeue().Item);
  62. Assert.AreEqual("3", queue.TryDequeue().Item);
  63. }
  64. [TestMethod]
  65. public void Clear()
  66. {
  67. var queue = new AsyncQueue<string>();
  68. queue.Enqueue("1");
  69. queue.Enqueue("2");
  70. queue.Enqueue("3");
  71. queue.Clear();
  72. Assert.AreEqual(0, queue.Count);
  73. queue.Enqueue("4");
  74. Assert.AreEqual(1, queue.Count);
  75. Assert.AreEqual("4", queue.TryDequeue().Item);
  76. }
  77. }
  78. }