Union.cs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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.Tasks;
  8. using Xunit;
  9. namespace Tests
  10. {
  11. public class Union : AsyncEnumerableTests
  12. {
  13. [Fact]
  14. public void Union_Null()
  15. {
  16. Assert.Throws<ArgumentNullException>(() => AsyncEnumerable.Union(default, Return42));
  17. Assert.Throws<ArgumentNullException>(() => AsyncEnumerable.Union(default, Return42, new Eq()));
  18. Assert.Throws<ArgumentNullException>(() => AsyncEnumerable.Union(Return42, default, new Eq()));
  19. }
  20. [Fact]
  21. public async Task Union1()
  22. {
  23. var xs = new[] { 1, 2, 3 }.ToAsyncEnumerable();
  24. var ys = new[] { 3, 5, 1, 4 }.ToAsyncEnumerable();
  25. var res = xs.Union(ys);
  26. var e = res.GetAsyncEnumerator();
  27. await HasNextAsync(e, 1);
  28. await HasNextAsync(e, 2);
  29. await HasNextAsync(e, 3);
  30. await HasNextAsync(e, 5);
  31. await HasNextAsync(e, 4);
  32. await NoNextAsync(e);
  33. }
  34. [Fact]
  35. public async Task Union2()
  36. {
  37. var xs = new[] { 1, 2, -3 }.ToAsyncEnumerable();
  38. var ys = new[] { 3, 5, -1, 4 }.ToAsyncEnumerable();
  39. var res = xs.Union(ys, new Eq());
  40. var e = res.GetAsyncEnumerator();
  41. await HasNextAsync(e, 1);
  42. await HasNextAsync(e, 2);
  43. await HasNextAsync(e, -3);
  44. await HasNextAsync(e, 5);
  45. await HasNextAsync(e, 4);
  46. await NoNextAsync(e);
  47. }
  48. [Fact]
  49. public async Task Union3()
  50. {
  51. var xs = new[] { 1, 2, 3 }.ToAsyncEnumerable();
  52. var ys = new[] { 3, 5, 1, 4 }.ToAsyncEnumerable();
  53. var zs = new[] { 5, 7, 8, 1 }.ToAsyncEnumerable();
  54. var res = xs.Union(ys).Union(zs);
  55. var e = res.GetAsyncEnumerator();
  56. await HasNextAsync(e, 1);
  57. await HasNextAsync(e, 2);
  58. await HasNextAsync(e, 3);
  59. await HasNextAsync(e, 5);
  60. await HasNextAsync(e, 4);
  61. await HasNextAsync(e, 7);
  62. await HasNextAsync(e, 8);
  63. await NoNextAsync(e);
  64. }
  65. private sealed class Eq : IEqualityComparer<int>
  66. {
  67. public bool Equals(int x, int y)
  68. {
  69. return EqualityComparer<int>.Default.Equals(Math.Abs(x), Math.Abs(y));
  70. }
  71. public int GetHashCode(int obj)
  72. {
  73. return EqualityComparer<int>.Default.GetHashCode(Math.Abs(obj));
  74. }
  75. }
  76. }
  77. }