AsyncTests.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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;
  6. using System.Collections.Generic;
  7. using System.Diagnostics.CodeAnalysis;
  8. using System.Linq;
  9. using System.Reflection;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. using Xunit;
  13. using FluentAssertions;
  14. namespace Tests
  15. {
  16. public partial class AsyncTests
  17. {
  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. [Obsolete("Don't use this, use Assert.ThrowsAsync and await it", true)]
  25. public Task AssertThrows<E>(Func<Task> func)
  26. where E : Exception
  27. {
  28. return Assert.ThrowsAsync<E>(func);
  29. }
  30. public void AssertThrows<E>(Action a, Func<E, bool> assert)
  31. where E : Exception
  32. {
  33. var hasFailed = false;
  34. try
  35. {
  36. a();
  37. }
  38. catch (E e)
  39. {
  40. Assert.True(assert(e));
  41. hasFailed = true;
  42. }
  43. if (!hasFailed)
  44. {
  45. Assert.True(false);
  46. }
  47. }
  48. public void NoNext<T>(IAsyncEnumerator<T> e)
  49. {
  50. Assert.False(e.MoveNext().Result);
  51. }
  52. public void HasNext<T>(IAsyncEnumerator<T> e, T value)
  53. {
  54. Assert.True(e.MoveNext().Result);
  55. Assert.Equal(value, e.Current);
  56. }
  57. public async Task SequenceIdentity<T>(IAsyncEnumerable<T> enumerable)
  58. {
  59. var en1 = enumerable.GetEnumerator();
  60. var en2 = enumerable.GetEnumerator();
  61. Assert.Equal(en1.GetType(), en2.GetType());
  62. en1.Dispose();
  63. en2.Dispose();
  64. var e1t = enumerable.ToList();
  65. var e2t = enumerable.ToList();
  66. await Task.WhenAll(e1t, e2t);
  67. var e1Result = e1t.Result;
  68. var e2Result = e2t.Result;
  69. e1Result.ShouldAllBeEquivalentTo(e2Result);
  70. }
  71. #pragma warning restore xUnit1013 // Public method should be marked as test
  72. }
  73. }