AsyncEnumerableTests.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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 const int WaitTimeoutMs = 5000;
  17. #pragma warning disable xUnit1013 // Public method should be marked as test
  18. public void AssertThrows<E>(Action a)
  19. where E : Exception
  20. {
  21. Assert.Throws<E>(a);
  22. }
  23. public void AssertThrows<E>(Action a, Func<E, bool> assert)
  24. where E : Exception
  25. {
  26. var hasFailed = false;
  27. try
  28. {
  29. a();
  30. }
  31. catch (E e)
  32. {
  33. Assert.True(assert(e));
  34. hasFailed = true;
  35. }
  36. if (!hasFailed)
  37. {
  38. Assert.True(false);
  39. }
  40. }
  41. public void NoNext<T>(IAsyncEnumerator<T> e)
  42. {
  43. Assert.False(e.MoveNextAsync().Result);
  44. }
  45. public void HasNext<T>(IAsyncEnumerator<T> e, T value)
  46. {
  47. Assert.True(e.MoveNextAsync().Result);
  48. Assert.Equal(value, e.Current);
  49. }
  50. public async Task SequenceIdentity<T>(IAsyncEnumerable<T> enumerable)
  51. {
  52. var en1 = enumerable.GetAsyncEnumerator();
  53. var en2 = enumerable.GetAsyncEnumerator();
  54. Assert.Equal(en1.GetType(), en2.GetType());
  55. await en1.DisposeAsync();
  56. await en2.DisposeAsync();
  57. var e1t = enumerable.ToList();
  58. var e2t = enumerable.ToList();
  59. await Task.WhenAll(e1t, e2t);
  60. var e1Result = e1t.Result;
  61. var e2Result = e2t.Result;
  62. e1Result.ShouldAllBeEquivalentTo(e2Result);
  63. }
  64. #pragma warning restore xUnit1013 // Public method should be marked as test
  65. }
  66. }