Finally.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  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 Xunit;
  9. namespace Tests
  10. {
  11. public class Finally : AsyncEnumerableExTests
  12. {
  13. [Fact]
  14. public void Finally_Null()
  15. {
  16. AssertThrows<ArgumentNullException>(() => AsyncEnumerableEx.Finally(default(IAsyncEnumerable<int>), () => { }));
  17. AssertThrows<ArgumentNullException>(() => AsyncEnumerableEx.Finally(Return42, default(Action)));
  18. }
  19. [Fact]
  20. public void Finally1()
  21. {
  22. var b = false;
  23. var xs = AsyncEnumerable.Empty<int>().Finally(() => { b = true; });
  24. var e = xs.GetAsyncEnumerator();
  25. Assert.False(b);
  26. NoNext(e);
  27. Assert.True(b);
  28. }
  29. [Fact]
  30. public void Finally2()
  31. {
  32. var b = false;
  33. var xs = Return42.Finally(() => { b = true; });
  34. var e = xs.GetAsyncEnumerator();
  35. Assert.False(b);
  36. HasNext(e, 42);
  37. Assert.False(b);
  38. NoNext(e);
  39. Assert.True(b);
  40. }
  41. [Fact]
  42. public void Finally3()
  43. {
  44. var ex = new Exception("Bang!");
  45. var b = false;
  46. var xs = AsyncEnumerable.Throw<int>(ex).Finally(() => { b = true; });
  47. var e = xs.GetAsyncEnumerator();
  48. Assert.False(b);
  49. AssertThrows(() => e.MoveNextAsync().Wait(WaitTimeoutMs), (Exception ex_) => ((AggregateException)ex_).Flatten().InnerExceptions.Single() == ex);
  50. Assert.True(b);
  51. }
  52. [Fact]
  53. public void Finally4()
  54. {
  55. var b = false;
  56. var xs = new[] { 1, 2 }.ToAsyncEnumerable().Finally(() => { b = true; });
  57. var e = xs.GetAsyncEnumerator();
  58. Assert.False(b);
  59. HasNext(e, 1);
  60. Assert.False(b);
  61. HasNext(e, 2);
  62. Assert.False(b);
  63. NoNext(e);
  64. Assert.True(b);
  65. }
  66. [Fact]
  67. public async Task Finally5()
  68. {
  69. var b = false;
  70. var xs = new[] { 1, 2 }.ToAsyncEnumerable().Finally(() => { b = true; });
  71. var e = xs.GetAsyncEnumerator();
  72. Assert.False(b);
  73. HasNext(e, 1);
  74. await e.DisposeAsync();
  75. Assert.True(b);
  76. }
  77. [Fact]
  78. public async Task Finally7()
  79. {
  80. var i = 0;
  81. var xs = new[] { 1, 2 }.ToAsyncEnumerable().Finally(() => { i++; });
  82. await SequenceIdentity(xs);
  83. Assert.Equal(2, i);
  84. }
  85. }
  86. }