Create.cs 2.7 KB

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