1
0

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