AsyncEnumerableExTests.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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 AsyncEnumerableExTests
  13. {
  14. protected static readonly IAsyncEnumerable<int> Return42 = AsyncEnumerableEx.Return(42);
  15. protected static IAsyncEnumerable<T> Throw<T>(Exception exception) => AsyncEnumerableEx.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, Func<E, bool> assert)
  20. where E : Exception
  21. {
  22. var hasFailed = false;
  23. try
  24. {
  25. a();
  26. }
  27. catch (E e)
  28. {
  29. Assert.True(assert(e));
  30. hasFailed = true;
  31. }
  32. if (!hasFailed)
  33. {
  34. Assert.True(false);
  35. }
  36. }
  37. protected async Task NoNextAsync<T>(IAsyncEnumerator<T> e)
  38. {
  39. Assert.False(await e.MoveNextAsync());
  40. }
  41. protected async Task HasNextAsync<T>(IAsyncEnumerator<T> e, T value)
  42. {
  43. Assert.True(await e.MoveNextAsync());
  44. Assert.Equal(value, e.Current);
  45. }
  46. public async Task SequenceIdentity<T>(IAsyncEnumerable<T> enumerable)
  47. {
  48. var en1 = enumerable.GetAsyncEnumerator();
  49. var en2 = enumerable.GetAsyncEnumerator();
  50. Assert.Equal(en1.GetType(), en2.GetType());
  51. await en1.DisposeAsync();
  52. await en2.DisposeAsync();
  53. var e1t = enumerable.ToList();
  54. var e2t = enumerable.ToList();
  55. await Task.WhenAll(e1t, e2t);
  56. var e1Result = e1t.Result;
  57. var e2Result = e2t.Result;
  58. e1Result.ShouldAllBeEquivalentTo(e2Result);
  59. }
  60. #pragma warning restore xUnit1013 // Public method should be marked as test
  61. }
  62. }