|
| 1 | +// Licensed to the .NET Foundation under one or more agreements. |
| 2 | +// The .NET Foundation licenses this file to you under the MIT license. |
| 3 | + |
| 4 | +using System.Collections.Generic; |
| 5 | +using System.Threading; |
| 6 | +using System.Threading.Tasks; |
| 7 | +using Xunit; |
| 8 | + |
| 9 | +namespace System.Linq.Tests |
| 10 | +{ |
| 11 | + public class ShuffleTests : AsyncEnumerableTests |
| 12 | + { |
| 13 | + [Fact] |
| 14 | + public void InvalidInputs_Throws() |
| 15 | + { |
| 16 | + AssertExtensions.Throws<ArgumentNullException>("source", () => AsyncEnumerable.Shuffle<int>(null)); |
| 17 | + } |
| 18 | + |
| 19 | + [Theory] |
| 20 | + [InlineData(new int[0])] |
| 21 | + [InlineData(new int[] { 1 })] |
| 22 | + [InlineData(new int[] { 2, 4, 8 })] |
| 23 | + [InlineData(new int[] { -1, 2, 5, 6, 7, 8 })] |
| 24 | + public async Task VariousValues_ContainsAllInputValues(int[] values) |
| 25 | + { |
| 26 | + foreach (IAsyncEnumerable<int> source in CreateSources(values)) |
| 27 | + { |
| 28 | + int[] shuffled = await source.Shuffle().ToArrayAsync(); |
| 29 | + Array.Sort(shuffled); |
| 30 | + Assert.Equal(values, shuffled); |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + [Fact] |
| 35 | + public async Task ToArrayAsync_ElementsAreRandomized() |
| 36 | + { |
| 37 | + // The chance that shuffling a thousand elements produces the same order twice is infinitesimal. |
| 38 | + int length = 1000; |
| 39 | + foreach (IAsyncEnumerable<int> source in CreateSources(Enumerable.Range(0, length).ToArray())) |
| 40 | + { |
| 41 | + int[] first = await source.Shuffle().ToArrayAsync(); |
| 42 | + int[] second = await source.Shuffle().ToArrayAsync(); |
| 43 | + Assert.Equal(length, first.Length); |
| 44 | + Assert.Equal(length, second.Length); |
| 45 | + Assert.NotEqual(first, second); |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + [Fact] |
| 50 | + public async Task Cancellation_Cancels() |
| 51 | + { |
| 52 | + IAsyncEnumerable<int> source = CreateSource(2, 4, 8, 16); |
| 53 | + await Assert.ThrowsAsync<OperationCanceledException>(async () => |
| 54 | + { |
| 55 | + await ConsumeAsync(source.Shuffle().WithCancellation(new CancellationToken(true))); |
| 56 | + }); |
| 57 | + } |
| 58 | + |
| 59 | + [Fact] |
| 60 | + public async Task InterfaceCalls_ExpectedCounts() |
| 61 | + { |
| 62 | + TrackingAsyncEnumerable<int> source = CreateSource(2, 4, 8, 16).Track(); |
| 63 | + await ConsumeAsync(source.Shuffle()); |
| 64 | + Assert.Equal(5, source.MoveNextAsyncCount); |
| 65 | + Assert.Equal(4, source.CurrentCount); |
| 66 | + Assert.Equal(1, source.DisposeAsyncCount); |
| 67 | + } |
| 68 | + } |
| 69 | +} |
0 commit comments