CreateTest.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the Apache 2.0 License.
  3. // See the LICENSE file in the project root for more information.
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Text;
  7. using System.Linq;
  8. using Xunit;
  9. using System.Collections;
  10. using System.Threading;
  11. namespace Tests
  12. {
  13. public class CreateTest : Tests
  14. {
  15. [Fact]
  16. public void Create_Arguments()
  17. {
  18. AssertThrows<ArgumentNullException>(() => EnumerableEx.Create<int>(default));
  19. }
  20. [Fact]
  21. public void Create1()
  22. {
  23. var hot = false;
  24. var res = EnumerableEx.Create<int>(() =>
  25. {
  26. hot = true;
  27. return MyEnumerator();
  28. });
  29. Assert.False(hot);
  30. var e = res.GetEnumerator();
  31. Assert.True(hot);
  32. HasNext(e, 1);
  33. HasNext(e, 2);
  34. NoNext(e);
  35. hot = false;
  36. var f = ((IEnumerable)res).GetEnumerator();
  37. Assert.True(hot);
  38. }
  39. [Fact]
  40. public void CreateYield()
  41. {
  42. SynchronizationContext.SetSynchronizationContext(null);
  43. var xs = EnumerableEx.Create<int>(async yield =>
  44. {
  45. var i = 0;
  46. while (i < 10)
  47. {
  48. await yield.Return(i++);
  49. }
  50. });
  51. var j = 0;
  52. foreach (var elem in xs)
  53. {
  54. Assert.Equal(j, elem);
  55. j++;
  56. }
  57. Assert.Equal(10, j);
  58. }
  59. [Fact]
  60. public void CreateYieldBreak()
  61. {
  62. SynchronizationContext.SetSynchronizationContext(null);
  63. var xs = EnumerableEx.Create<int>(async yield =>
  64. {
  65. var i = 0;
  66. while (true)
  67. {
  68. if (i == 10)
  69. {
  70. await yield.Break();
  71. return;
  72. }
  73. await yield.Return(i++);
  74. }
  75. });
  76. var j = 0;
  77. foreach (var elem in xs)
  78. {
  79. Assert.Equal(elem, j);
  80. j++;
  81. }
  82. Assert.Equal(10, j);
  83. }
  84. [Fact]
  85. public void YielderNoReset()
  86. {
  87. var xs = EnumerableEx.Create<int>(async yield =>
  88. {
  89. await yield.Break();
  90. });
  91. AssertThrows<NotSupportedException>(() => xs.GetEnumerator().Reset());
  92. }
  93. private static IEnumerator<int> MyEnumerator()
  94. {
  95. yield return 1;
  96. yield return 2;
  97. }
  98. }
  99. }