Count.cs 2.3 KB

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