AsyncTests.cs 2.2 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;
  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. public void AssertThrows<E>(Action a)
  19. where E : Exception
  20. {
  21. Assert.Throws<E>(a);
  22. }
  23. [Obsolete("Don't use this, use Assert.ThrowsAsync and await it", true)]
  24. public Task AssertThrows<E>(Func<Task> func)
  25. where E : Exception
  26. {
  27. return Assert.ThrowsAsync<E>(func);
  28. }
  29. public void AssertThrows<E>(Action a, Func<E, bool> assert)
  30. where E : Exception
  31. {
  32. var hasFailed = false;
  33. try
  34. {
  35. a();
  36. }
  37. catch (E e)
  38. {
  39. Assert.True(assert(e));
  40. hasFailed = true;
  41. }
  42. if (!hasFailed)
  43. {
  44. Assert.True(false);
  45. }
  46. }
  47. public void NoNext<T>(IAsyncEnumerator<T> e)
  48. {
  49. Assert.False(e.MoveNext().Result);
  50. }
  51. public void HasNext<T>(IAsyncEnumerator<T> e, T value)
  52. {
  53. Assert.True(e.MoveNext().Result);
  54. Assert.Equal(value, e.Current);
  55. }
  56. public async Task SequenceIdentity<T>(IAsyncEnumerable<T> enumerable)
  57. {
  58. var en1 = enumerable.GetEnumerator();
  59. var en2 = enumerable.GetEnumerator();
  60. Assert.Equal(en1.GetType(), en2.GetType());
  61. en1.Dispose();
  62. en2.Dispose();
  63. var e1t = enumerable.ToList();
  64. var e2t = enumerable.ToList();
  65. await Task.WhenAll(e1t, e2t);
  66. var e1Result = e1t.Result;
  67. var e2Result = e2t.Result;
  68. e1Result.ShouldAllBeEquivalentTo(e2Result);
  69. }
  70. }
  71. }