1
0

AsyncEnumerableTests.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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 = new[] { 42 }.ToAsyncEnumerable();
  15. protected async Task AssertThrowsAsync<TException>(Task t)
  16. where TException : Exception
  17. {
  18. await Assert.ThrowsAsync<TException>(() => t);
  19. }
  20. protected async Task AssertThrowsAsync(Task t, Exception e)
  21. {
  22. try
  23. {
  24. await t;
  25. }
  26. catch (Exception ex)
  27. {
  28. Assert.Same(e, ex);
  29. }
  30. }
  31. protected Task AssertThrowsAsync<T>(ValueTask<T> t, Exception e)
  32. {
  33. return AssertThrowsAsync(t.AsTask(), e);
  34. }
  35. protected async Task NoNextAsync<T>(IAsyncEnumerator<T> e)
  36. {
  37. Assert.False(await e.MoveNextAsync());
  38. }
  39. protected async Task HasNextAsync<T>(IAsyncEnumerator<T> e, T value)
  40. {
  41. Assert.True(await e.MoveNextAsync());
  42. Assert.Equal(value, e.Current);
  43. }
  44. protected async Task SequenceIdentity<T>(IAsyncEnumerable<T> enumerable)
  45. {
  46. var en1 = enumerable.GetAsyncEnumerator();
  47. var en2 = enumerable.GetAsyncEnumerator();
  48. Assert.Equal(en1.GetType(), en2.GetType());
  49. await en1.DisposeAsync();
  50. await en2.DisposeAsync();
  51. var res1 = await enumerable.ToListAsync();
  52. var res2 = await enumerable.ToListAsync();
  53. res1.ShouldAllBeEquivalentTo(res2);
  54. }
  55. protected static IAsyncEnumerable<TValue> Throw<TValue>(Exception exception)
  56. {
  57. if (exception == null)
  58. throw new ArgumentNullException(nameof(exception));
  59. #if NO_TASK_FROMEXCEPTION
  60. var tcs = new TaskCompletionSource<bool>();
  61. tcs.TrySetException(exception);
  62. var moveNextThrows = new ValueTask<bool>(tcs.Task);
  63. #else
  64. var moveNextThrows = new ValueTask<bool>(Task.FromException<bool>(exception));
  65. #endif
  66. return AsyncEnumerable.Create(
  67. _ => AsyncEnumerator.Create<TValue>(
  68. () => moveNextThrows,
  69. getCurrent: null,
  70. disposeAsync: null)
  71. );
  72. }
  73. }
  74. }