Any.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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;
  8. using System.Threading.Tasks;
  9. using Xunit;
  10. namespace Tests
  11. {
  12. public class Any : AsyncEnumerableTests
  13. {
  14. [Fact]
  15. public async Task Any_Null()
  16. {
  17. await Assert.ThrowsAsync<ArgumentNullException>(() => AsyncEnumerable.Any<int>(default(IAsyncEnumerable<int>)));
  18. await Assert.ThrowsAsync<ArgumentNullException>(() => AsyncEnumerable.Any<int>(default(IAsyncEnumerable<int>), x => true));
  19. await Assert.ThrowsAsync<ArgumentNullException>(() => AsyncEnumerable.Any<int>(Return42, default(Func<int, bool>)));
  20. await Assert.ThrowsAsync<ArgumentNullException>(() => AsyncEnumerable.Any<int>(default(IAsyncEnumerable<int>), CancellationToken.None));
  21. await Assert.ThrowsAsync<ArgumentNullException>(() => AsyncEnumerable.Any<int>(default(IAsyncEnumerable<int>), x => true, CancellationToken.None));
  22. await Assert.ThrowsAsync<ArgumentNullException>(() => AsyncEnumerable.Any<int>(Return42, default(Func<int, bool>), CancellationToken.None));
  23. }
  24. [Fact]
  25. public void Any1()
  26. {
  27. var res = new[] { 1, 2, 3, 4 }.ToAsyncEnumerable().Any(x => x % 2 == 0);
  28. Assert.True(res.Result);
  29. }
  30. [Fact]
  31. public void Any2()
  32. {
  33. var res = new[] { 2, 8, 4 }.ToAsyncEnumerable().Any(x => x % 2 != 0);
  34. Assert.False(res.Result);
  35. }
  36. [Fact]
  37. public void Any3()
  38. {
  39. var ex = new Exception("Bang!");
  40. var res = AsyncEnumerable.Throw<int>(ex).Any(x => x % 2 == 0);
  41. AssertThrows<Exception>(() => res.Wait(WaitTimeoutMs), ex_ => ((AggregateException)ex_).Flatten().InnerExceptions.Single() == ex);
  42. }
  43. [Fact]
  44. public void Any4()
  45. {
  46. var ex = new Exception("Bang!");
  47. var res = new[] { 2, 8, 4 }.ToAsyncEnumerable().Any(new Func<int, bool>(x => { throw ex; }));
  48. AssertThrows<Exception>(() => res.Wait(WaitTimeoutMs), ex_ => ((AggregateException)ex_).Flatten().InnerExceptions.Single() == ex);
  49. }
  50. [Fact]
  51. public void Any5()
  52. {
  53. var res = new[] { 1, 2, 3, 4 }.ToAsyncEnumerable().Any();
  54. Assert.True(res.Result);
  55. }
  56. [Fact]
  57. public void Any6()
  58. {
  59. var res = new int[0].ToAsyncEnumerable().Any();
  60. Assert.False(res.Result);
  61. }
  62. }
  63. }