ElementAt.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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 ElementAt : AsyncEnumerableTests
  13. {
  14. [Fact]
  15. public async Task ElementAt_Null()
  16. {
  17. await Assert.ThrowsAsync<ArgumentNullException>(() => AsyncEnumerable.ElementAt<int>(default(IAsyncEnumerable<int>), 0));
  18. await Assert.ThrowsAsync<ArgumentOutOfRangeException>(() => AsyncEnumerable.ElementAt<int>(Return42, -1));
  19. await Assert.ThrowsAsync<ArgumentNullException>(() => AsyncEnumerable.ElementAt<int>(default(IAsyncEnumerable<int>), 0, CancellationToken.None));
  20. await Assert.ThrowsAsync<ArgumentOutOfRangeException>(() => AsyncEnumerable.ElementAt<int>(Return42, -1, CancellationToken.None));
  21. }
  22. [Fact]
  23. public void ElementAt1()
  24. {
  25. var res = AsyncEnumerable.Empty<int>().ElementAt(0);
  26. AssertThrows<Exception>(() => res.Wait(WaitTimeoutMs), ex_ => ((AggregateException)ex_).Flatten().InnerExceptions.Single() is ArgumentOutOfRangeException);
  27. }
  28. [Fact]
  29. public void ElementAt2()
  30. {
  31. var res = Return42.ElementAt(0);
  32. Assert.Equal(42, res.Result);
  33. }
  34. [Fact]
  35. public void ElementAt3()
  36. {
  37. var res = Return42.ElementAt(1);
  38. AssertThrows<Exception>(() => res.Wait(WaitTimeoutMs), ex_ => ((AggregateException)ex_).Flatten().InnerExceptions.Single() is ArgumentOutOfRangeException);
  39. }
  40. [Fact]
  41. public void ElementAt4()
  42. {
  43. var res = new[] { 1, 42, 3 }.ToAsyncEnumerable().ElementAt(1);
  44. Assert.Equal(42, res.Result);
  45. }
  46. [Fact]
  47. public void ElementAt5()
  48. {
  49. var res = new[] { 1, 42, 3 }.ToAsyncEnumerable().ElementAt(7);
  50. AssertThrows<Exception>(() => res.Wait(WaitTimeoutMs), ex_ => ((AggregateException)ex_).Flatten().InnerExceptions.Single() is ArgumentOutOfRangeException);
  51. }
  52. [Fact]
  53. public void ElementAt6()
  54. {
  55. var ex = new Exception("Bang!");
  56. var res = AsyncEnumerable.Throw<int>(ex).ElementAt(15);
  57. AssertThrows<Exception>(() => res.Wait(WaitTimeoutMs), ex_ => ((AggregateException)ex_).Flatten().InnerExceptions.Single() == ex);
  58. }
  59. }
  60. }