AsyncEnumerableTests.cs 2.2 KB

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