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 // See the LICENSE file in the project root for more information. 4 5 using System.Linq.Expressions; 6 using Xunit; 7 8 namespace System.Linq.Tests 9 { 10 public class SingleTests : EnumerableBasedTests 11 { 12 [Fact] Empty()13 public void Empty() 14 { 15 int[] source = { }; 16 Assert.Throws<InvalidOperationException>(() => source.AsQueryable().Single()); 17 } 18 19 [Fact] SingleElement()20 public void SingleElement() 21 { 22 int[] source = { 4 }; 23 Assert.Equal(4, source.AsQueryable().Single()); 24 } 25 26 [Fact] ManyElement()27 public void ManyElement() 28 { 29 int[] source = { 4, 4, 4, 4, 4 }; 30 Assert.Throws<InvalidOperationException>(() => source.AsQueryable().Single()); 31 } 32 33 [Fact] EmptySourceWithPredicate()34 public void EmptySourceWithPredicate() 35 { 36 int[] source = { }; 37 Assert.Throws<InvalidOperationException>(() => source.AsQueryable().Single(i => i % 2 == 0)); 38 } 39 40 [Fact] ManyElementsPredicateFalseForAll()41 public void ManyElementsPredicateFalseForAll() 42 { 43 int[] source = { 3, 1, 7, 9, 13, 19 }; 44 Assert.Throws<InvalidOperationException>(() => source.AsQueryable().Single(i => i % 2 == 0)); 45 } 46 47 [Fact] ManyElementsPredicateTrueForLast()48 public void ManyElementsPredicateTrueForLast() 49 { 50 int[] source = { 3, 1, 7, 9, 13, 19, 20 }; 51 Assert.Equal(20, source.AsQueryable().Single(i => i % 2 == 0)); 52 } 53 54 [Theory] 55 [InlineData(1, 100)] 56 [InlineData(42, 100)] FindSingleMatch(int target, int range)57 public void FindSingleMatch(int target, int range) 58 { 59 Assert.Equal(target, Enumerable.Range(0, range).AsQueryable().Single(i => i == target)); 60 } 61 62 [Fact] ThrowsOnNullSource()63 public void ThrowsOnNullSource() 64 { 65 IQueryable<int> source = null; 66 AssertExtensions.Throws<ArgumentNullException>("source", () => source.Single()); 67 AssertExtensions.Throws<ArgumentNullException>("source", () => source.Single(i => i % 2 == 0)); 68 } 69 70 [Fact] ThrowsOnNullPredicate()71 public void ThrowsOnNullPredicate() 72 { 73 int[] source = { }; 74 Expression<Func<int, bool>> nullPredicate = null; 75 AssertExtensions.Throws<ArgumentNullException>("predicate", () => source.AsQueryable().Single(nullPredicate)); 76 } 77 78 [Fact] Single1()79 public void Single1() 80 { 81 var val = (new int[] { 2 }).AsQueryable().Single(); 82 Assert.Equal(2, val); 83 } 84 85 [Fact] Single2()86 public void Single2() 87 { 88 var val = (new int[] { 2 }).AsQueryable().Single(n => n > 1); 89 Assert.Equal(2, val); 90 } 91 } 92 } 93