ToEnumerable.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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.Generic;
  6. using System.Linq;
  7. using System.Threading.Tasks;
  8. using Xunit;
  9. namespace Tests
  10. {
  11. public class ToEnumerable : AsyncEnumerableTests
  12. {
  13. [Fact]
  14. public void ToEnumerable_Null()
  15. {
  16. Assert.Throws<ArgumentNullException>(() => AsyncEnumerable.ToEnumerable<int>(null));
  17. }
  18. [Fact]
  19. public void ToEnumerable_Single()
  20. {
  21. var xs = Return42.ToEnumerable();
  22. Assert.True(xs.SequenceEqual([42]));
  23. }
  24. [Fact]
  25. public void ToEnumerable_Empty()
  26. {
  27. var xs = AsyncEnumerable.Empty<int>().ToEnumerable();
  28. Assert.True(xs.SequenceEqual([]));
  29. }
  30. [Fact]
  31. public void ToEnumerable_Throws_Source()
  32. {
  33. var ex = new Exception("Bang");
  34. var xs = Throw<int>(ex).ToEnumerable();
  35. Assert.Throws<Exception>(() => xs.GetEnumerator().MoveNext());
  36. }
  37. [Fact]
  38. public void ToEnumerable_Many()
  39. {
  40. var xs = new[] { 1, 2, 3 };
  41. Assert.Equal(xs, xs.ToAsyncEnumerable().ToEnumerable());
  42. }
  43. [Fact]
  44. public void ToEnumerable_Many_Yield()
  45. {
  46. var xs = new[] { 1, 2, 3 };
  47. Assert.Equal(xs, Yielded(xs).ToEnumerable());
  48. }
  49. private static async IAsyncEnumerable<int> Yielded(IEnumerable<int> xs)
  50. {
  51. try
  52. {
  53. foreach (var x in xs)
  54. {
  55. await Task.Yield();
  56. yield return x;
  57. }
  58. }
  59. finally
  60. {
  61. await Task.Yield();
  62. }
  63. }
  64. }
  65. }