Count.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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.Linq;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using Xunit;
  9. namespace Tests
  10. {
  11. public class Count : AsyncEnumerableTests
  12. {
  13. [Fact]
  14. public async Task Count_Null()
  15. {
  16. await Assert.ThrowsAsync<ArgumentNullException>(() => AsyncEnumerable.Count<int>(null));
  17. await Assert.ThrowsAsync<ArgumentNullException>(() => AsyncEnumerable.Count<int>(null, x => true));
  18. await Assert.ThrowsAsync<ArgumentNullException>(() => AsyncEnumerable.Count<int>(AsyncEnumerable.Return(42), default(Func<int, bool>)));
  19. await Assert.ThrowsAsync<ArgumentNullException>(() => AsyncEnumerable.Count<int>(null, CancellationToken.None));
  20. await Assert.ThrowsAsync<ArgumentNullException>(() => AsyncEnumerable.Count<int>(null, x => true, CancellationToken.None));
  21. await Assert.ThrowsAsync<ArgumentNullException>(() => AsyncEnumerable.Count<int>(AsyncEnumerable.Return(42), default(Func<int, bool>), CancellationToken.None));
  22. }
  23. [Fact]
  24. public void Count1()
  25. {
  26. Assert.Equal(0, new int[0].ToAsyncEnumerable().Count().Result);
  27. Assert.Equal(3, new[] { 1, 2, 3 }.ToAsyncEnumerable().Count().Result);
  28. AssertThrows<AggregateException>(() => AsyncEnumerable.Throw<int>(new Exception("Bang!")).Count().Wait(WaitTimeoutMs));
  29. }
  30. [Fact]
  31. public void Count2()
  32. {
  33. Assert.Equal(0, new int[0].ToAsyncEnumerable().Count(x => x < 3).Result);
  34. Assert.Equal(2, new[] { 1, 2, 3 }.ToAsyncEnumerable().Count(x => x < 3).Result);
  35. AssertThrows<AggregateException>(() => AsyncEnumerable.Throw<int>(new Exception("Bang!")).Count(x => x < 3).Wait(WaitTimeoutMs));
  36. }
  37. [Fact]
  38. public void Count3()
  39. {
  40. var ex = new Exception("Bang!");
  41. var ys = new[] { 1, 2, 3 }.ToAsyncEnumerable().Count(new Func<int, bool>(x => { throw ex; }));
  42. AssertThrows<Exception>(() => ys.Wait(WaitTimeoutMs), ex_ => ((AggregateException)ex_).Flatten().InnerExceptions.Single() == ex);
  43. }
  44. }
  45. }