AsyncEnumerableTests.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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.Linq;
  7. using System.Threading.Tasks;
  8. using FluentAssertions;
  9. using Xunit;
  10. namespace Tests
  11. {
  12. public class AsyncEnumerableTests
  13. {
  14. protected static readonly IAsyncEnumerable<int> Return42 = AsyncEnumerable.Return(42);
  15. protected static IAsyncEnumerable<T> Throw<T>(Exception exception) => AsyncEnumerable.Throw<T>(exception);
  16. protected static Func<Exception, bool> SingleInnerExceptionMatches(Exception ex) => e => ((AggregateException)e).Flatten().InnerExceptions.Single() == ex;
  17. protected const int WaitTimeoutMs = 5000;
  18. #pragma warning disable xUnit1013 // Public method should be marked as test
  19. public void AssertThrows<E>(Action a)
  20. where E : Exception
  21. {
  22. Assert.Throws<E>(a);
  23. }
  24. public void AssertThrows<E>(Action a, Func<E, bool> assert)
  25. where E : Exception
  26. {
  27. var hasFailed = false;
  28. try
  29. {
  30. a();
  31. }
  32. catch (E e)
  33. {
  34. Assert.True(assert(e));
  35. hasFailed = true;
  36. }
  37. if (!hasFailed)
  38. {
  39. Assert.True(false);
  40. }
  41. }
  42. public void NoNext<T>(IAsyncEnumerator<T> e)
  43. {
  44. Assert.False(e.MoveNextAsync().Result);
  45. }
  46. public void HasNext<T>(IAsyncEnumerator<T> e, T value)
  47. {
  48. Assert.True(e.MoveNextAsync().Result);
  49. Assert.Equal(value, e.Current);
  50. }
  51. public async Task SequenceIdentity<T>(IAsyncEnumerable<T> enumerable)
  52. {
  53. var en1 = enumerable.GetAsyncEnumerator();
  54. var en2 = enumerable.GetAsyncEnumerator();
  55. Assert.Equal(en1.GetType(), en2.GetType());
  56. await en1.DisposeAsync();
  57. await en2.DisposeAsync();
  58. var e1t = enumerable.ToList();
  59. var e2t = enumerable.ToList();
  60. await Task.WhenAll(e1t, e2t);
  61. var e1Result = e1t.Result;
  62. var e2Result = e2t.Result;
  63. e1Result.ShouldAllBeEquivalentTo(e2Result);
  64. }
  65. #pragma warning restore xUnit1013 // Public method should be marked as test
  66. }
  67. }