namespace System.Collections.Immutable.Tests
{
- public abstract class ImmutableDictionaryBuilderTestBase : ImmutablesTestBase
+ public abstract partial class ImmutableDictionaryBuilderTestBase : ImmutablesTestBase
{
[Fact]
public void Add()
}
[Fact]
- public void TryGetKey()
- {
- var builder = Empty<int>(StringComparer.OrdinalIgnoreCase)
- .Add("a", 1).ToBuilder();
- string actualKey;
- Assert.True(TryGetKeyHelper(builder, "a", out actualKey));
- Assert.Equal("a", actualKey);
-
- Assert.True(TryGetKeyHelper(builder, "A", out actualKey));
- Assert.Equal("a", actualKey);
-
- Assert.False(TryGetKeyHelper(builder, "b", out actualKey));
- Assert.Equal("b", actualKey);
- }
-
- [Fact]
public void EnumerateTest()
{
var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5).Add("six", 6);
--- /dev/null
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Collections.Generic;
+using System.Linq;
+using Xunit;
+
+namespace System.Collections.Immutable.Tests
+{
+ public abstract partial class ImmutableDictionaryBuilderTestBase : ImmutablesTestBase
+ {
+ [Fact]
+ public void TryGetKey()
+ {
+ var builder = Empty<int>(StringComparer.OrdinalIgnoreCase)
+ .Add("a", 1).ToBuilder();
+ string actualKey;
+ Assert.True(TryGetKeyHelper(builder, "a", out actualKey));
+ Assert.Equal("a", actualKey);
+
+ Assert.True(TryGetKeyHelper(builder, "A", out actualKey));
+ Assert.Equal("a", actualKey);
+
+ Assert.False(TryGetKeyHelper(builder, "b", out actualKey));
+ Assert.Equal("b", actualKey);
+ }
+ }
+}
namespace System.Collections.Immutable.Tests
{
- public class ImmutableDictionaryTest : ImmutableDictionaryTestBase
+ public partial class ImmutableDictionaryTest : ImmutableDictionaryTestBase
{
[Fact]
public void AddExistingKeySameValueTest()
}
[Fact]
- public override void EmptyTest()
- {
- base.EmptyTest();
- this.EmptyTestHelperHash(Empty<int, bool>(), 5);
- }
-
- [Fact]
public void ContainsValueTest()
{
this.ContainsValueTestHelper(ImmutableDictionary<int, GenericParameterHelper>.Empty, 1, new GenericParameterHelper());
}
[Fact]
- public void EnumeratorWithHashCollisionsTest()
- {
- var emptyMap = Empty<int, GenericParameterHelper>(new BadHasher<int>());
- this.EnumeratorTestHelper(emptyMap);
- }
-
- [Fact]
public void Create()
{
IEnumerable<KeyValuePair<string, string>> pairs = new Dictionary<string, string> { { "a", "b" } };
return ((ImmutableDictionary<TKey, TValue>)dictionary).ValueComparer;
}
- internal override IBinaryTree GetRootNode<TKey, TValue>(IImmutableDictionary<TKey, TValue> dictionary)
- {
- return ((ImmutableDictionary<TKey, TValue>)dictionary).Root;
- }
-
protected void ContainsValueTestHelper<TKey, TValue>(ImmutableDictionary<TKey, TValue> map, TKey key, TValue value)
{
Assert.False(map.ContainsValue(value));
return ImmutableDictionary<TKey, TValue>.Empty.WithComparers(keyComparer, valueComparer);
}
- private void EmptyTestHelperHash<TKey, TValue>(IImmutableDictionary<TKey, TValue> empty, TKey someKey)
- {
- Assert.Same(EqualityComparer<TKey>.Default, ((IHashKeyCollection<TKey>)empty).KeyComparer);
- }
-
/// <summary>
/// An ordinal comparer for case-insensitive strings.
/// </summary>
--- /dev/null
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+using System.Reflection;
+using Xunit;
+
+namespace System.Collections.Immutable.Tests
+{
+ public partial class ImmutableDictionaryTest : ImmutableDictionaryTestBase
+ {
+ [Fact]
+ public override void EmptyTest()
+ {
+ base.EmptyTest();
+ this.EmptyTestHelperHash(Empty<int, bool>(), 5);
+ }
+
+ [Fact]
+ public void EnumeratorWithHashCollisionsTest()
+ {
+ var emptyMap = Empty<int, GenericParameterHelper>(new BadHasher<int>());
+ this.EnumeratorTestHelper(emptyMap);
+ }
+
+ internal override IBinaryTree GetRootNode<TKey, TValue>(IImmutableDictionary<TKey, TValue> dictionary)
+ {
+ return ((ImmutableDictionary<TKey, TValue>)dictionary).Root;
+ }
+
+ private void EmptyTestHelperHash<TKey, TValue>(IImmutableDictionary<TKey, TValue> empty, TKey someKey)
+ {
+ Assert.Same(EqualityComparer<TKey>.Default, ((IHashKeyCollection<TKey>)empty).KeyComparer);
+ }
+ }
+}
namespace System.Collections.Immutable.Tests
{
- public abstract class ImmutableDictionaryTestBase : ImmutablesTestBase
+ public abstract partial class ImmutableDictionaryTestBase : ImmutablesTestBase
{
[Fact]
public virtual void EmptyTest()
}
[Fact]
- public void EnumeratorTest()
- {
- this.EnumeratorTestHelper(this.Empty<int, GenericParameterHelper>());
- }
-
- [Fact]
public void ContainsTest()
{
this.ContainsTestHelper(Empty<int, string>(), 5, "foo");
}
[Fact]
- public void KeysTest()
- {
- this.KeysTestHelper(Empty<int, bool>(), 5);
- }
-
- [Fact]
- public void ValuesTest()
- {
- this.ValuesTestHelper(Empty<int, bool>(), 5);
- }
-
- [Fact]
- public void AddAscendingTest()
- {
- this.AddAscendingTestHelper(Empty<int, GenericParameterHelper>());
- }
-
- [Fact]
- public void AddRangeTest()
- {
- var map = Empty<int, GenericParameterHelper>();
- map = map.AddRange(Enumerable.Range(1, 100).Select(n => new KeyValuePair<int, GenericParameterHelper>(n, new GenericParameterHelper())));
- CollectionAssertAreEquivalent(map.Select(kv => kv.Key).ToList(), Enumerable.Range(1, 100).ToList());
- this.VerifyAvlTreeState(map);
- Assert.Equal(100, map.Count);
-
- // Test optimization for empty map.
- var map2 = Empty<int, GenericParameterHelper>();
- var jointMap = map2.AddRange(map);
- Assert.Same(map, jointMap);
-
- jointMap = map2.AddRange(map.ToReadOnlyDictionary());
- Assert.Same(map, jointMap);
-
- jointMap = map2.AddRange(map.ToBuilder());
- Assert.Same(map, jointMap);
- }
-
- [Fact]
- public void AddDescendingTest()
- {
- this.AddDescendingTestHelper(Empty<int, GenericParameterHelper>());
- }
-
- [Fact]
- public void AddRemoveRandomDataTest()
- {
- this.AddRemoveRandomDataTestHelper(Empty<double, GenericParameterHelper>());
- }
-
- [Fact]
- public void AddRemoveEnumerableTest()
- {
- this.AddRemoveEnumerableTestHelper(Empty<int, int>());
- }
-
- [Fact]
public void SetItemTest()
{
var map = this.Empty<string, int>()
Assert.Equal(5, map[3]);
}
- [Fact]
- public void DictionaryRemoveThrowsTest()
- {
- IDictionary<int, int> map = this.Empty<int, int>().Add(5, 3).ToReadOnlyDictionary();
- Assert.Throws<NotSupportedException>(() => map.Remove(5));
- }
-
- [Fact]
- public void DictionaryAddThrowsTest()
- {
- IDictionary<int, int> map = this.Empty<int, int>().ToReadOnlyDictionary();
- Assert.Throws<NotSupportedException>(() => map.Add(5, 3));
- }
-
- [Fact]
- public void DictionaryIndexSetThrowsTest()
- {
- IDictionary<int, int> map = this.Empty<int, int>().ToReadOnlyDictionary();
- Assert.Throws<NotSupportedException>(() => map[3] = 5);
- }
-
- [Fact]
- public void EqualsTest()
- {
- Assert.False(Empty<int, int>().Equals(null));
- Assert.False(Empty<int, int>().Equals("hi"));
- Assert.True(Empty<int, int>().Equals(Empty<int, int>()));
- Assert.False(Empty<int, int>().Add(3, 2).Equals(Empty<int, int>().Add(3, 2)));
- Assert.False(Empty<int, int>().Add(3, 2).Equals(Empty<int, int>().Add(3, 1)));
- Assert.False(Empty<int, int>().Add(5, 1).Equals(Empty<int, int>().Add(3, 1)));
- Assert.False(Empty<int, int>().Add(3, 1).Add(5, 1).Equals(Empty<int, int>().Add(3, 1)));
- Assert.False(Empty<int, int>().Add(3, 1).Equals(Empty<int, int>().Add(3, 1).Add(5, 1)));
-
- Assert.True(Empty<int, int>().ToReadOnlyDictionary().Equals(Empty<int, int>()));
- Assert.True(Empty<int, int>().Equals(Empty<int, int>().ToReadOnlyDictionary()));
- Assert.True(Empty<int, int>().ToReadOnlyDictionary().Equals(Empty<int, int>().ToReadOnlyDictionary()));
- Assert.False(Empty<int, int>().Add(3, 1).ToReadOnlyDictionary().Equals(Empty<int, int>()));
- Assert.False(Empty<int, int>().Equals(Empty<int, int>().Add(3, 1).ToReadOnlyDictionary()));
- Assert.False(Empty<int, int>().ToReadOnlyDictionary().Equals(Empty<int, int>().Add(3, 1).ToReadOnlyDictionary()));
- }
-
/// <summary>
/// Verifies that the GetHashCode method returns the standard one.
/// </summary>
Assert.Equal(default(V), value);
}
- private IImmutableDictionary<TKey, TValue> AddTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue> map, TKey key, TValue value) where TKey : IComparable<TKey>
- {
- Assert.NotNull(map);
- Assert.NotNull(key);
-
- IImmutableDictionary<TKey, TValue> addedMap = map.Add(key, value);
- Assert.NotSame(map, addedMap);
- ////Assert.Equal(map.Count + 1, addedMap.Count);
- Assert.False(map.ContainsKey(key));
- Assert.True(addedMap.ContainsKey(key));
- AssertAreSame(value, addedMap.GetValueOrDefault(key));
-
- this.VerifyAvlTreeState(addedMap);
-
- return addedMap;
- }
-
- protected void AddAscendingTestHelper(IImmutableDictionary<int, GenericParameterHelper> map)
- {
- Assert.NotNull(map);
-
- for (int i = 0; i < 10; i++)
- {
- map = this.AddTestHelper(map, i, new GenericParameterHelper(i));
- }
-
- Assert.Equal(10, map.Count);
- for (int i = 0; i < 10; i++)
- {
- Assert.True(map.ContainsKey(i));
- }
- }
-
- protected void AddDescendingTestHelper(IImmutableDictionary<int, GenericParameterHelper> map)
- {
- for (int i = 10; i > 0; i--)
- {
- map = this.AddTestHelper(map, i, new GenericParameterHelper(i));
- }
-
- Assert.Equal(10, map.Count);
- for (int i = 10; i > 0; i--)
- {
- Assert.True(map.ContainsKey(i));
- }
- }
-
- protected void AddRemoveRandomDataTestHelper(IImmutableDictionary<double, GenericParameterHelper> map)
- {
- Assert.NotNull(map);
-
- double[] inputs = GenerateDummyFillData();
- for (int i = 0; i < inputs.Length; i++)
- {
- map = this.AddTestHelper(map, inputs[i], new GenericParameterHelper());
- }
-
- Assert.Equal(inputs.Length, map.Count);
- for (int i = 0; i < inputs.Length; i++)
- {
- Assert.True(map.ContainsKey(inputs[i]));
- }
-
- for (int i = 0; i < inputs.Length; i++)
- {
- map = map.Remove(inputs[i]);
- this.VerifyAvlTreeState(map);
- }
-
- Assert.Equal(0, map.Count);
- }
-
- protected void AddRemoveEnumerableTestHelper(IImmutableDictionary<int, int> empty)
- {
- Assert.NotNull(empty);
-
- Assert.Same(empty, empty.RemoveRange(Enumerable.Empty<int>()));
- Assert.Same(empty, empty.AddRange(Enumerable.Empty<KeyValuePair<int, int>>()));
- var list = new List<KeyValuePair<int, int>> { new KeyValuePair<int, int>(3, 5), new KeyValuePair<int, int>(8, 10) };
- var nonEmpty = empty.AddRange(list);
- this.VerifyAvlTreeState(nonEmpty);
- var halfRemoved = nonEmpty.RemoveRange(Enumerable.Range(1, 5));
- Assert.Equal(1, halfRemoved.Count);
- Assert.True(halfRemoved.ContainsKey(8));
- this.VerifyAvlTreeState(halfRemoved);
- }
-
protected void AddExistingKeySameValueTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue> map, TKey key, TValue value1, TValue value2)
{
Assert.NotNull(map);
Assert.False(removedMap.ContainsKey(key));
}
- protected void KeysTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue> map, TKey key)
- {
- Assert.Equal(0, map.Keys.Count());
- Assert.Equal(0, map.ToReadOnlyDictionary().Keys.Count());
-
- var nonEmpty = map.Add(key, default(TValue));
- Assert.Equal(1, nonEmpty.Keys.Count());
- Assert.Equal(1, nonEmpty.ToReadOnlyDictionary().Keys.Count());
- KeysOrValuesTestHelper(((IDictionary<TKey, TValue>)nonEmpty).Keys, key);
- }
-
- protected void ValuesTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue> map, TKey key)
- {
- Assert.Equal(0, map.Values.Count());
- Assert.Equal(0, map.ToReadOnlyDictionary().Values.Count());
-
- var nonEmpty = map.Add(key, default(TValue));
- Assert.Equal(1, nonEmpty.Values.Count());
- Assert.Equal(1, nonEmpty.ToReadOnlyDictionary().Values.Count());
- KeysOrValuesTestHelper(((IDictionary<TKey, TValue>)nonEmpty).Values, default(TValue));
- }
-
- protected void EnumeratorTestHelper(IImmutableDictionary<int, GenericParameterHelper> map)
- {
- for (int i = 0; i < 10; i++)
- {
- map = this.AddTestHelper(map, i, new GenericParameterHelper(i));
- }
-
- int j = 0;
- foreach (KeyValuePair<int, GenericParameterHelper> pair in map)
- {
- Assert.Equal(j, pair.Key);
- Assert.Equal(j, pair.Value.Data);
- j++;
- }
-
- var list = map.ToList();
- Assert.Equal<KeyValuePair<int, GenericParameterHelper>>(list, ImmutableSetTest.ToListNonGeneric<KeyValuePair<int, GenericParameterHelper>>(map));
-
- // Apply some less common uses to the enumerator to test its metal.
- using (var enumerator = map.GetEnumerator())
- {
- enumerator.Reset(); // reset isn't usually called before MoveNext
- ManuallyEnumerateTest(list, enumerator);
- enumerator.Reset();
- ManuallyEnumerateTest(list, enumerator);
-
- // this time only partially enumerate
- enumerator.Reset();
- enumerator.MoveNext();
- enumerator.Reset();
- ManuallyEnumerateTest(list, enumerator);
- }
-
- var manualEnum = map.GetEnumerator();
- Assert.Throws<InvalidOperationException>(() => manualEnum.Current);
- while (manualEnum.MoveNext()) { }
- Assert.False(manualEnum.MoveNext());
- Assert.Throws<InvalidOperationException>(() => manualEnum.Current);
- }
-
protected abstract IImmutableDictionary<TKey, TValue> Empty<TKey, TValue>();
protected abstract IImmutableDictionary<string, TValue> Empty<TValue>(StringComparer comparer);
protected abstract IEqualityComparer<TValue> GetValueComparer<TKey, TValue>(IImmutableDictionary<TKey, TValue> dictionary);
-
- internal abstract IBinaryTree GetRootNode<TKey, TValue>(IImmutableDictionary<TKey, TValue> dictionary);
-
- private static void KeysOrValuesTestHelper<T>(ICollection<T> collection, T containedValue)
- {
- Requires.NotNull(collection, nameof(collection));
-
- Assert.True(collection.Contains(containedValue));
- Assert.Throws<NotSupportedException>(() => collection.Add(default(T)));
- Assert.Throws<NotSupportedException>(() => collection.Clear());
-
- var nonGeneric = (ICollection)collection;
- Assert.NotNull(nonGeneric.SyncRoot);
- Assert.Same(nonGeneric.SyncRoot, nonGeneric.SyncRoot);
- Assert.True(nonGeneric.IsSynchronized);
- Assert.True(collection.IsReadOnly);
-
- AssertExtensions.Throws<ArgumentNullException>("array", () => nonGeneric.CopyTo(null, 0));
- var array = new T[collection.Count + 1];
- nonGeneric.CopyTo(array, 1);
- Assert.Equal(default(T), array[0]);
- Assert.Equal(array.Skip(1), nonGeneric.Cast<T>().ToArray());
- }
-
- private void VerifyAvlTreeState<TKey, TValue>(IImmutableDictionary<TKey, TValue> dictionary)
- {
- var rootNode = this.GetRootNode(dictionary);
- rootNode.VerifyBalanced();
- rootNode.VerifyHeightIsWithinTolerance(dictionary.Count);
- }
}
}
--- /dev/null
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Collections.Generic;
+using System.Linq;
+using Xunit;
+
+namespace System.Collections.Immutable.Tests
+{
+ public abstract partial class ImmutableDictionaryTestBase : ImmutablesTestBase
+ {
+ [Fact]
+ public void EnumeratorTest()
+ {
+ this.EnumeratorTestHelper(this.Empty<int, GenericParameterHelper>());
+ }
+
+ [Fact]
+ public void KeysTest()
+ {
+ this.KeysTestHelper(Empty<int, bool>(), 5);
+ }
+
+ [Fact]
+ public void ValuesTest()
+ {
+ this.ValuesTestHelper(Empty<int, bool>(), 5);
+ }
+
+ [Fact]
+ public void AddAscendingTest()
+ {
+ this.AddAscendingTestHelper(Empty<int, GenericParameterHelper>());
+ }
+
+ [Fact]
+ public void DictionaryRemoveThrowsTest()
+ {
+ IDictionary<int, int> map = this.Empty<int, int>().Add(5, 3).ToReadOnlyDictionary();
+ Assert.Throws<NotSupportedException>(() => map.Remove(5));
+ }
+
+ [Fact]
+ public void DictionaryAddThrowsTest()
+ {
+ IDictionary<int, int> map = this.Empty<int, int>().ToReadOnlyDictionary();
+ Assert.Throws<NotSupportedException>(() => map.Add(5, 3));
+ }
+
+ [Fact]
+ public void DictionaryIndexSetThrowsTest()
+ {
+ IDictionary<int, int> map = this.Empty<int, int>().ToReadOnlyDictionary();
+ Assert.Throws<NotSupportedException>(() => map[3] = 5);
+ }
+
+ [Fact]
+ public void EqualsTest()
+ {
+ Assert.False(Empty<int, int>().Equals(null));
+ Assert.False(Empty<int, int>().Equals("hi"));
+ Assert.True(Empty<int, int>().Equals(Empty<int, int>()));
+ Assert.False(Empty<int, int>().Add(3, 2).Equals(Empty<int, int>().Add(3, 2)));
+ Assert.False(Empty<int, int>().Add(3, 2).Equals(Empty<int, int>().Add(3, 1)));
+ Assert.False(Empty<int, int>().Add(5, 1).Equals(Empty<int, int>().Add(3, 1)));
+ Assert.False(Empty<int, int>().Add(3, 1).Add(5, 1).Equals(Empty<int, int>().Add(3, 1)));
+ Assert.False(Empty<int, int>().Add(3, 1).Equals(Empty<int, int>().Add(3, 1).Add(5, 1)));
+
+ Assert.True(Empty<int, int>().ToReadOnlyDictionary().Equals(Empty<int, int>()));
+ Assert.True(Empty<int, int>().Equals(Empty<int, int>().ToReadOnlyDictionary()));
+ Assert.True(Empty<int, int>().ToReadOnlyDictionary().Equals(Empty<int, int>().ToReadOnlyDictionary()));
+ Assert.False(Empty<int, int>().Add(3, 1).ToReadOnlyDictionary().Equals(Empty<int, int>()));
+ Assert.False(Empty<int, int>().Equals(Empty<int, int>().Add(3, 1).ToReadOnlyDictionary()));
+ Assert.False(Empty<int, int>().ToReadOnlyDictionary().Equals(Empty<int, int>().Add(3, 1).ToReadOnlyDictionary()));
+ }
+
+ [Fact]
+ public void AddRangeTest()
+ {
+ var map = Empty<int, GenericParameterHelper>();
+ map = map.AddRange(Enumerable.Range(1, 100).Select(n => new KeyValuePair<int, GenericParameterHelper>(n, new GenericParameterHelper())));
+ CollectionAssertAreEquivalent(map.Select(kv => kv.Key).ToList(), Enumerable.Range(1, 100).ToList());
+ this.VerifyAvlTreeState(map);
+ Assert.Equal(100, map.Count);
+
+ // Test optimization for empty map.
+ var map2 = Empty<int, GenericParameterHelper>();
+ var jointMap = map2.AddRange(map);
+ Assert.Same(map, jointMap);
+
+ jointMap = map2.AddRange(map.ToReadOnlyDictionary());
+ Assert.Same(map, jointMap);
+
+ jointMap = map2.AddRange(map.ToBuilder());
+ Assert.Same(map, jointMap);
+ }
+
+ [Fact]
+ public void AddDescendingTest()
+ {
+ this.AddDescendingTestHelper(Empty<int, GenericParameterHelper>());
+ }
+
+ [Fact]
+ public void AddRemoveRandomDataTest()
+ {
+ this.AddRemoveRandomDataTestHelper(Empty<double, GenericParameterHelper>());
+ }
+
+ [Fact]
+ public void AddRemoveEnumerableTest()
+ {
+ this.AddRemoveEnumerableTestHelper(Empty<int, int>());
+ }
+
+ private IImmutableDictionary<TKey, TValue> AddTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue> map, TKey key, TValue value) where TKey : IComparable<TKey>
+ {
+ Assert.NotNull(map);
+ Assert.NotNull(key);
+
+ IImmutableDictionary<TKey, TValue> addedMap = map.Add(key, value);
+ Assert.NotSame(map, addedMap);
+ ////Assert.Equal(map.Count + 1, addedMap.Count);
+ Assert.False(map.ContainsKey(key));
+ Assert.True(addedMap.ContainsKey(key));
+ AssertAreSame(value, addedMap.GetValueOrDefault(key));
+
+ this.VerifyAvlTreeState(addedMap);
+
+ return addedMap;
+ }
+
+ protected void AddAscendingTestHelper(IImmutableDictionary<int, GenericParameterHelper> map)
+ {
+ Assert.NotNull(map);
+
+ for (int i = 0; i < 10; i++)
+ {
+ map = this.AddTestHelper(map, i, new GenericParameterHelper(i));
+ }
+
+ Assert.Equal(10, map.Count);
+ for (int i = 0; i < 10; i++)
+ {
+ Assert.True(map.ContainsKey(i));
+ }
+ }
+
+ protected void AddDescendingTestHelper(IImmutableDictionary<int, GenericParameterHelper> map)
+ {
+ for (int i = 10; i > 0; i--)
+ {
+ map = this.AddTestHelper(map, i, new GenericParameterHelper(i));
+ }
+
+ Assert.Equal(10, map.Count);
+ for (int i = 10; i > 0; i--)
+ {
+ Assert.True(map.ContainsKey(i));
+ }
+ }
+
+ protected void AddRemoveRandomDataTestHelper(IImmutableDictionary<double, GenericParameterHelper> map)
+ {
+ Assert.NotNull(map);
+
+ double[] inputs = GenerateDummyFillData();
+ for (int i = 0; i < inputs.Length; i++)
+ {
+ map = this.AddTestHelper(map, inputs[i], new GenericParameterHelper());
+ }
+
+ Assert.Equal(inputs.Length, map.Count);
+ for (int i = 0; i < inputs.Length; i++)
+ {
+ Assert.True(map.ContainsKey(inputs[i]));
+ }
+
+ for (int i = 0; i < inputs.Length; i++)
+ {
+ map = map.Remove(inputs[i]);
+ this.VerifyAvlTreeState(map);
+ }
+
+ Assert.Equal(0, map.Count);
+ }
+
+ protected void AddRemoveEnumerableTestHelper(IImmutableDictionary<int, int> empty)
+ {
+ Assert.NotNull(empty);
+
+ Assert.Same(empty, empty.RemoveRange(Enumerable.Empty<int>()));
+ Assert.Same(empty, empty.AddRange(Enumerable.Empty<KeyValuePair<int, int>>()));
+ var list = new List<KeyValuePair<int, int>> { new KeyValuePair<int, int>(3, 5), new KeyValuePair<int, int>(8, 10) };
+ var nonEmpty = empty.AddRange(list);
+ this.VerifyAvlTreeState(nonEmpty);
+ var halfRemoved = nonEmpty.RemoveRange(Enumerable.Range(1, 5));
+ Assert.Equal(1, halfRemoved.Count);
+ Assert.True(halfRemoved.ContainsKey(8));
+ this.VerifyAvlTreeState(halfRemoved);
+ }
+
+ protected void KeysTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue> map, TKey key)
+ {
+ Assert.Equal(0, map.Keys.Count());
+ Assert.Equal(0, map.ToReadOnlyDictionary().Keys.Count());
+
+ var nonEmpty = map.Add(key, default(TValue));
+ Assert.Equal(1, nonEmpty.Keys.Count());
+ Assert.Equal(1, nonEmpty.ToReadOnlyDictionary().Keys.Count());
+ KeysOrValuesTestHelper(((IDictionary<TKey, TValue>)nonEmpty).Keys, key);
+ }
+
+ protected void ValuesTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue> map, TKey key)
+ {
+ Assert.Equal(0, map.Values.Count());
+ Assert.Equal(0, map.ToReadOnlyDictionary().Values.Count());
+
+ var nonEmpty = map.Add(key, default(TValue));
+ Assert.Equal(1, nonEmpty.Values.Count());
+ Assert.Equal(1, nonEmpty.ToReadOnlyDictionary().Values.Count());
+ KeysOrValuesTestHelper(((IDictionary<TKey, TValue>)nonEmpty).Values, default(TValue));
+ }
+
+ protected void EnumeratorTestHelper(IImmutableDictionary<int, GenericParameterHelper> map)
+ {
+ for (int i = 0; i < 10; i++)
+ {
+ map = this.AddTestHelper(map, i, new GenericParameterHelper(i));
+ }
+
+ int j = 0;
+ foreach (KeyValuePair<int, GenericParameterHelper> pair in map)
+ {
+ Assert.Equal(j, pair.Key);
+ Assert.Equal(j, pair.Value.Data);
+ j++;
+ }
+
+ var list = map.ToList();
+ Assert.Equal<KeyValuePair<int, GenericParameterHelper>>(list, ImmutableSetTest.ToListNonGeneric<KeyValuePair<int, GenericParameterHelper>>(map));
+
+ // Apply some less common uses to the enumerator to test its metal.
+ using (var enumerator = map.GetEnumerator())
+ {
+ enumerator.Reset(); // reset isn't usually called before MoveNext
+ ManuallyEnumerateTest(list, enumerator);
+ enumerator.Reset();
+ ManuallyEnumerateTest(list, enumerator);
+
+ // this time only partially enumerate
+ enumerator.Reset();
+ enumerator.MoveNext();
+ enumerator.Reset();
+ ManuallyEnumerateTest(list, enumerator);
+ }
+
+ var manualEnum = map.GetEnumerator();
+ Assert.Throws<InvalidOperationException>(() => manualEnum.Current);
+ while (manualEnum.MoveNext()) { }
+ Assert.False(manualEnum.MoveNext());
+ Assert.Throws<InvalidOperationException>(() => manualEnum.Current);
+ }
+
+ internal abstract IBinaryTree GetRootNode<TKey, TValue>(IImmutableDictionary<TKey, TValue> dictionary);
+
+ private static void KeysOrValuesTestHelper<T>(ICollection<T> collection, T containedValue)
+ {
+ Requires.NotNull(collection, nameof(collection));
+
+ Assert.True(collection.Contains(containedValue));
+ Assert.Throws<NotSupportedException>(() => collection.Add(default(T)));
+ Assert.Throws<NotSupportedException>(() => collection.Clear());
+
+ var nonGeneric = (ICollection)collection;
+ Assert.NotNull(nonGeneric.SyncRoot);
+ Assert.Same(nonGeneric.SyncRoot, nonGeneric.SyncRoot);
+ Assert.True(nonGeneric.IsSynchronized);
+ Assert.True(collection.IsReadOnly);
+
+ AssertExtensions.Throws<ArgumentNullException>("array", () => nonGeneric.CopyTo(null, 0));
+ var array = new T[collection.Count + 1];
+ nonGeneric.CopyTo(array, 1);
+ Assert.Equal(default(T), array[0]);
+ Assert.Equal(array.Skip(1), nonGeneric.Cast<T>().ToArray());
+ }
+
+ private void VerifyAvlTreeState<TKey, TValue>(IImmutableDictionary<TKey, TValue> dictionary)
+ {
+ var rootNode = this.GetRootNode(dictionary);
+ rootNode.VerifyBalanced();
+ rootNode.VerifyHeightIsWithinTolerance(dictionary.Count);
+ }
+ }
+}
namespace System.Collections.Immutable.Tests
{
- public class ImmutableHashSetTest : ImmutableSetTest
+ public partial class ImmutableHashSetTest : ImmutableSetTest
{
protected override bool IncludesGetHashCodeDerivative
{
}
[Fact]
- public void EmptyTest()
- {
- this.EmptyTestHelper(Empty<int>(), 5, null);
- this.EmptyTestHelper(EmptyTyped<string>().WithComparer(StringComparer.OrdinalIgnoreCase), "a", StringComparer.OrdinalIgnoreCase);
- }
-
- [Fact]
public void CustomSort()
{
this.CustomSortTestHelper(
}
[Fact]
- public void TryGetValueTest()
- {
- this.TryGetValueTestHelper(ImmutableHashSet<string>.Empty.WithComparer(StringComparer.OrdinalIgnoreCase));
- }
-
- [Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Cannot do DebuggerAttribute testing on UapAot: requires internal Reflection on framework types.")]
public void DebuggerAttributesValid()
{
{
return new HashSet<T>();
}
-
- internal override IBinaryTree GetRootNode<T>(IImmutableSet<T> set)
- {
- return ((ImmutableHashSet<T>)set).Root;
- }
-
- /// <summary>
- /// Tests various aspects of an unordered set.
- /// </summary>
- /// <typeparam name="T">The type of element stored in the set.</typeparam>
- /// <param name="emptySet">The empty set.</param>
- /// <param name="value">A value that could be placed in the set.</param>
- /// <param name="comparer">The comparer used to obtain the empty set, if any.</param>
- private void EmptyTestHelper<T>(IImmutableSet<T> emptySet, T value, IEqualityComparer<T> comparer)
- {
- Assert.NotNull(emptySet);
-
- this.EmptyTestHelper(emptySet);
- Assert.Same(emptySet, emptySet.ToImmutableHashSet(comparer));
- Assert.Same(comparer ?? EqualityComparer<T>.Default, ((IHashKeyCollection<T>)emptySet).KeyComparer);
-
- if (comparer == null)
- {
- Assert.Same(emptySet, ImmutableHashSet<T>.Empty);
- }
-
- var reemptied = emptySet.Add(value).Clear();
- Assert.Same(reemptied, reemptied.ToImmutableHashSet(comparer)); //, "Getting the empty set from a non-empty instance did not preserve the comparer.");
- }
}
}
--- /dev/null
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+using System.Reflection;
+using Xunit;
+
+namespace System.Collections.Immutable.Tests
+{
+ public partial class ImmutableHashSetTest : ImmutableSetTest
+ {
+ [Fact]
+ public void EmptyTest()
+ {
+ this.EmptyTestHelper(Empty<int>(), 5, null);
+ this.EmptyTestHelper(EmptyTyped<string>().WithComparer(StringComparer.OrdinalIgnoreCase), "a", StringComparer.OrdinalIgnoreCase);
+ }
+
+ [Fact]
+ public void TryGetValueTest()
+ {
+ this.TryGetValueTestHelper(ImmutableHashSet<string>.Empty.WithComparer(StringComparer.OrdinalIgnoreCase));
+ }
+
+ internal override IBinaryTree GetRootNode<T>(IImmutableSet<T> set)
+ {
+ return ((ImmutableHashSet<T>)set).Root;
+ }
+
+ /// <summary>
+ /// Tests various aspects of an unordered set.
+ /// </summary>
+ /// <typeparam name="T">The type of element stored in the set.</typeparam>
+ /// <param name="emptySet">The empty set.</param>
+ /// <param name="value">A value that could be placed in the set.</param>
+ /// <param name="comparer">The comparer used to obtain the empty set, if any.</param>
+ private void EmptyTestHelper<T>(IImmutableSet<T> emptySet, T value, IEqualityComparer<T> comparer)
+ {
+ Assert.NotNull(emptySet);
+
+ this.EmptyTestHelper(emptySet);
+ Assert.Same(emptySet, emptySet.ToImmutableHashSet(comparer));
+ Assert.Same(comparer ?? EqualityComparer<T>.Default, ((IHashKeyCollection<T>)emptySet).KeyComparer);
+
+ if (comparer == null)
+ {
+ Assert.Same(emptySet, ImmutableHashSet<T>.Empty);
+ }
+
+ var reemptied = emptySet.Add(value).Clear();
+ Assert.Same(reemptied, reemptied.ToImmutableHashSet(comparer)); //, "Getting the empty set from a non-empty instance did not preserve the comparer.");
+ }
+ }
+}
namespace System.Collections.Immutable.Tests
{
- public abstract class ImmutableSetTest : ImmutablesTestBase
+ public abstract partial class ImmutableSetTest : ImmutablesTestBase
{
[Fact]
public void AddTest()
Assert.Same(set, empty2.Union(set)); // "Filling an empty immutable set with the contents of another immutable set with the exact same comparer should return the other set."
}
- [Fact]
- public void ExceptTest()
- {
- this.ExceptTestHelper(Empty<int>().Add(1).Add(3).Add(5).Add(7), 3, 7);
- }
-
/// <summary>
/// Verifies that Except *does* enumerate its argument if the collection is empty.
/// </summary>
}
[Fact]
- public void SymmetricExceptTest()
- {
- this.SymmetricExceptTestHelper(Empty<int>().Add(1).Add(3).Add(5).Add(7), Enumerable.Range(0, 9).ToArray());
- this.SymmetricExceptTestHelper(Empty<int>().Add(1).Add(3).Add(5).Add(7), Enumerable.Range(0, 5).ToArray());
- }
-
- [Fact]
- public void EnumeratorTest()
- {
- IComparer<double> comparer = null;
- var set = this.Empty<double>();
- var sortedSet = set as ISortKeyCollection<double>;
- if (sortedSet != null)
- {
- comparer = sortedSet.KeyComparer;
- }
-
- this.EnumeratorTestHelper(set, comparer, 3, 5, 1);
- double[] data = this.GenerateDummyFillData();
- this.EnumeratorTestHelper(set, comparer, data);
- }
-
- [Fact]
- public void IntersectTest()
- {
- this.IntersectTestHelper(Empty<int>().Union(Enumerable.Range(1, 10)), 8, 3, 5);
- }
-
- [Fact]
- public void UnionTest()
- {
- this.UnionTestHelper(this.Empty<int>(), new[] { 1, 3, 5, 7 });
- this.UnionTestHelper(this.Empty<int>().Union(new[] { 2, 4, 6 }), new[] { 1, 3, 5, 7 });
- this.UnionTestHelper(this.Empty<int>().Union(new[] { 1, 2, 3 }), new int[0] { });
- this.UnionTestHelper(this.Empty<int>().Union(new[] { 2 }), Enumerable.Range(0, 1000).ToArray());
- }
-
- [Fact]
public void SetEqualsTest()
{
Assert.True(this.Empty<int>().SetEquals(this.Empty<int>()));
protected abstract ISet<T> EmptyMutable<T>();
- internal abstract IBinaryTree GetRootNode<T>(IImmutableSet<T> set);
-
- protected void TryGetValueTestHelper(IImmutableSet<string> set)
- {
- Requires.NotNull(set, nameof(set));
-
- string expected = "egg";
- set = set.Add(expected);
- string actual;
- string lookupValue = expected.ToUpperInvariant();
- Assert.True(set.TryGetValue(lookupValue, out actual));
- Assert.Same(expected, actual);
-
- Assert.False(set.TryGetValue("foo", out actual));
- Assert.Equal("foo", actual);
-
- Assert.False(set.Clear().TryGetValue("nonexistent", out actual));
- Assert.Equal("nonexistent", actual);
- }
-
protected IImmutableSet<T> SetWith<T>(params T[] items)
{
return this.Empty<T>().Union(items);
Assert.Throws<ObjectDisposedException>(() => enumerator.Current);
}
- private void ExceptTestHelper<T>(IImmutableSet<T> set, params T[] valuesToRemove)
- {
- Assert.NotNull(set);
- Assert.NotNull(valuesToRemove);
-
- var expectedSet = new HashSet<T>(set);
- expectedSet.ExceptWith(valuesToRemove);
-
- var actualSet = set.Except(valuesToRemove);
- CollectionAssertAreEquivalent(expectedSet.ToList(), actualSet.ToList());
-
- this.VerifyAvlTreeState(actualSet);
- }
-
- private void SymmetricExceptTestHelper<T>(IImmutableSet<T> set, params T[] otherCollection)
- {
- Assert.NotNull(set);
- Assert.NotNull(otherCollection);
-
- var expectedSet = new HashSet<T>(set);
- expectedSet.SymmetricExceptWith(otherCollection);
-
- var actualSet = set.SymmetricExcept(otherCollection);
- CollectionAssertAreEquivalent(expectedSet.ToList(), actualSet.ToList());
-
- this.VerifyAvlTreeState(actualSet);
- }
-
- private void IntersectTestHelper<T>(IImmutableSet<T> set, params T[] values)
- {
- Assert.NotNull(set);
- Assert.NotNull(values);
-
- Assert.True(set.Intersect(Enumerable.Empty<T>()).Count == 0);
-
- var expected = new HashSet<T>(set);
- expected.IntersectWith(values);
-
- var actual = set.Intersect(values);
- CollectionAssertAreEquivalent(expected.ToList(), actual.ToList());
-
- this.VerifyAvlTreeState(actual);
- }
-
- private void UnionTestHelper<T>(IImmutableSet<T> set, params T[] values)
- {
- Assert.NotNull(set);
- Assert.NotNull(values);
-
- var expected = new HashSet<T>(set);
- expected.UnionWith(values);
-
- var actual = set.Union(values);
- CollectionAssertAreEquivalent(expected.ToList(), actual.ToList());
-
- this.VerifyAvlTreeState(actual);
- }
-
private void AddTestHelper<T>(IImmutableSet<T> set, params T[] values)
{
Assert.NotNull(set);
set = nextSet;
}
}
-
- private void VerifyAvlTreeState<T>(IImmutableSet<T> set)
- {
- var rootNode = this.GetRootNode(set);
- rootNode.VerifyBalanced();
- rootNode.VerifyHeightIsWithinTolerance(set.Count);
- }
}
}
--- /dev/null
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Collections.Generic;
+using System.Linq;
+using Xunit;
+using SetTriad = System.Tuple<System.Collections.Generic.IEnumerable<int>, System.Collections.Generic.IEnumerable<int>, bool>;
+
+namespace System.Collections.Immutable.Tests
+{
+ public abstract partial class ImmutableSetTest : ImmutablesTestBase
+ {
+ [Fact]
+ public void ExceptTest()
+ {
+ this.ExceptTestHelper(Empty<int>().Add(1).Add(3).Add(5).Add(7), 3, 7);
+ }
+
+ [Fact]
+ public void SymmetricExceptTest()
+ {
+ this.SymmetricExceptTestHelper(Empty<int>().Add(1).Add(3).Add(5).Add(7), Enumerable.Range(0, 9).ToArray());
+ this.SymmetricExceptTestHelper(Empty<int>().Add(1).Add(3).Add(5).Add(7), Enumerable.Range(0, 5).ToArray());
+ }
+
+ [Fact]
+ public void EnumeratorTest()
+ {
+ IComparer<double> comparer = null;
+ var set = this.Empty<double>();
+ var sortedSet = set as ISortKeyCollection<double>;
+ if (sortedSet != null)
+ {
+ comparer = sortedSet.KeyComparer;
+ }
+
+ this.EnumeratorTestHelper(set, comparer, 3, 5, 1);
+ double[] data = this.GenerateDummyFillData();
+ this.EnumeratorTestHelper(set, comparer, data);
+ }
+
+ [Fact]
+ public void IntersectTest()
+ {
+ this.IntersectTestHelper(Empty<int>().Union(Enumerable.Range(1, 10)), 8, 3, 5);
+ }
+
+ [Fact]
+ public void UnionTest()
+ {
+ this.UnionTestHelper(this.Empty<int>(), new[] { 1, 3, 5, 7 });
+ this.UnionTestHelper(this.Empty<int>().Union(new[] { 2, 4, 6 }), new[] { 1, 3, 5, 7 });
+ this.UnionTestHelper(this.Empty<int>().Union(new[] { 1, 2, 3 }), new int[0] { });
+ this.UnionTestHelper(this.Empty<int>().Union(new[] { 2 }), Enumerable.Range(0, 1000).ToArray());
+ }
+
+ internal abstract IBinaryTree GetRootNode<T>(IImmutableSet<T> set);
+
+ protected void TryGetValueTestHelper(IImmutableSet<string> set)
+ {
+ Requires.NotNull(set, nameof(set));
+
+ string expected = "egg";
+ set = set.Add(expected);
+ string actual;
+ string lookupValue = expected.ToUpperInvariant();
+ Assert.True(set.TryGetValue(lookupValue, out actual));
+ Assert.Same(expected, actual);
+
+ Assert.False(set.TryGetValue("foo", out actual));
+ Assert.Equal("foo", actual);
+
+ Assert.False(set.Clear().TryGetValue("nonexistent", out actual));
+ Assert.Equal("nonexistent", actual);
+ }
+
+ private void ExceptTestHelper<T>(IImmutableSet<T> set, params T[] valuesToRemove)
+ {
+ Assert.NotNull(set);
+ Assert.NotNull(valuesToRemove);
+
+ var expectedSet = new HashSet<T>(set);
+ expectedSet.ExceptWith(valuesToRemove);
+
+ var actualSet = set.Except(valuesToRemove);
+ CollectionAssertAreEquivalent(expectedSet.ToList(), actualSet.ToList());
+
+ this.VerifyAvlTreeState(actualSet);
+ }
+
+ private void SymmetricExceptTestHelper<T>(IImmutableSet<T> set, params T[] otherCollection)
+ {
+ Assert.NotNull(set);
+ Assert.NotNull(otherCollection);
+
+ var expectedSet = new HashSet<T>(set);
+ expectedSet.SymmetricExceptWith(otherCollection);
+
+ var actualSet = set.SymmetricExcept(otherCollection);
+ CollectionAssertAreEquivalent(expectedSet.ToList(), actualSet.ToList());
+
+ this.VerifyAvlTreeState(actualSet);
+ }
+
+ private void IntersectTestHelper<T>(IImmutableSet<T> set, params T[] values)
+ {
+ Assert.NotNull(set);
+ Assert.NotNull(values);
+
+ Assert.True(set.Intersect(Enumerable.Empty<T>()).Count == 0);
+
+ var expected = new HashSet<T>(set);
+ expected.IntersectWith(values);
+
+ var actual = set.Intersect(values);
+ CollectionAssertAreEquivalent(expected.ToList(), actual.ToList());
+
+ this.VerifyAvlTreeState(actual);
+ }
+
+ private void UnionTestHelper<T>(IImmutableSet<T> set, params T[] values)
+ {
+ Assert.NotNull(set);
+ Assert.NotNull(values);
+
+ var expected = new HashSet<T>(set);
+ expected.UnionWith(values);
+
+ var actual = set.Union(values);
+ CollectionAssertAreEquivalent(expected.ToList(), actual.ToList());
+
+ this.VerifyAvlTreeState(actual);
+ }
+
+ private void VerifyAvlTreeState<T>(IImmutableSet<T> set)
+ {
+ var rootNode = this.GetRootNode(set);
+ rootNode.VerifyBalanced();
+ rootNode.VerifyHeightIsWithinTolerance(set.Count);
+ }
+ }
+}
namespace System.Collections.Immutable.Tests
{
- public class ImmutableSortedDictionaryTest : ImmutableDictionaryTestBase
+ public partial class ImmutableSortedDictionaryTest : ImmutableDictionaryTestBase
{
private enum Operation
{
return ((ImmutableSortedDictionary<TKey, TValue>)dictionary).ValueComparer;
}
- internal override IBinaryTree GetRootNode<TKey, TValue>(IImmutableDictionary<TKey, TValue> dictionary)
- {
- return ((ImmutableSortedDictionary<TKey, TValue>)dictionary).Root;
- }
-
protected void ContainsValueTestHelper<TKey, TValue>(ImmutableSortedDictionary<TKey, TValue> map, TKey key, TValue value)
{
Assert.False(map.ContainsValue(value));
--- /dev/null
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.IO;
+using System.Linq;
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using Xunit;
+
+namespace System.Collections.Immutable.Tests
+{
+ public partial class ImmutableSortedDictionaryTest : ImmutableDictionaryTestBase
+ {
+ internal override IBinaryTree GetRootNode<TKey, TValue>(IImmutableDictionary<TKey, TValue> dictionary)
+ {
+ return ((ImmutableSortedDictionary<TKey, TValue>)dictionary).Root;
+ }
+ }
+}
namespace System.Collections.Immutable.Tests
{
- public class ImmutableSortedSetBuilderTest : ImmutablesTestBase
+ public partial class ImmutableSortedSetBuilderTest : ImmutablesTestBase
{
[Fact]
public void CreateBuilder()
TargetInvocationException tie = Assert.Throws<TargetInvocationException>(() => Activator.CreateInstance(proxyType, (object)null));
Assert.IsType<ArgumentNullException>(tie.InnerException);
}
-
- [Fact]
- public void ItemRef()
- {
- var array = new[] { 1, 2, 3 }.ToImmutableSortedSet();
- var builder = new ImmutableSortedSet<int>.Builder(array);
-
- ref readonly var safeRef = ref builder.ItemRef(1);
- ref var unsafeRef = ref Unsafe.AsRef(safeRef);
-
- Assert.Equal(2, builder.ItemRef(1));
-
- unsafeRef = 4;
-
- Assert.Equal(4, builder.ItemRef(1));
- }
-
- [Fact]
- public void ItemRef_OutOfBounds()
- {
- var array = new[] { 1, 2, 3 }.ToImmutableSortedSet();
- var builder = new ImmutableSortedSet<int>.Builder(array);
-
- Assert.Throws<ArgumentOutOfRangeException> (() => builder.ItemRef(5));
- }
}
}
--- /dev/null
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using Xunit;
+
+namespace System.Collections.Immutable.Tests
+{
+ public partial class ImmutableSortedSetBuilderTest : ImmutablesTestBase
+ {
+ [Fact]
+ public void ItemRef()
+ {
+ var array = new[] { 1, 2, 3 }.ToImmutableSortedSet();
+ var builder = new ImmutableSortedSet<int>.Builder(array);
+
+ ref readonly var safeRef = ref builder.ItemRef(1);
+ ref var unsafeRef = ref Unsafe.AsRef(safeRef);
+
+ Assert.Equal(2, builder.ItemRef(1));
+
+ unsafeRef = 4;
+
+ Assert.Equal(4, builder.ItemRef(1));
+ }
+
+ [Fact]
+ public void ItemRef_OutOfBounds()
+ {
+ var array = new[] { 1, 2, 3 }.ToImmutableSortedSet();
+ var builder = new ImmutableSortedSet<int>.Builder(array);
+
+ Assert.Throws<ArgumentOutOfRangeException>(() => builder.ItemRef(5));
+ }
+ }
+}
namespace System.Collections.Immutable.Tests
{
- public class ImmutableSortedSetTest : ImmutableSetTest
+ public partial class ImmutableSortedSetTest : ImmutableSetTest
{
private enum Operation
{
}
[Fact]
- [ActiveIssue("Sporadic failure, needs a port of https://github.com/dotnet/coreclr/pull/4340", TargetFrameworkMonikers.NetFramework)]
- public void EmptyTest()
- {
- this.EmptyTestHelper(Empty<int>(), 5, null);
- this.EmptyTestHelper(Empty<string>().ToImmutableSortedSet(StringComparer.OrdinalIgnoreCase), "a", StringComparer.OrdinalIgnoreCase);
- }
-
- [Fact]
public void CustomSort()
{
this.CustomSortTestHelper(
}
[Fact]
- public void TryGetValueTest()
- {
- this.TryGetValueTestHelper(ImmutableSortedSet<string>.Empty.WithComparer(StringComparer.OrdinalIgnoreCase));
- }
-
- [Fact]
public void EnumeratorRecyclingMisuse()
{
var collection = ImmutableSortedSet.Create<int>();
{
return new SortedSet<T>();
}
-
- internal override IBinaryTree GetRootNode<T>(IImmutableSet<T> set)
- {
- return ((ImmutableSortedSet<T>)set).Root;
- }
-
- /// <summary>
- /// Tests various aspects of a sorted set.
- /// </summary>
- /// <typeparam name="T">The type of element stored in the set.</typeparam>
- /// <param name="emptySet">The empty set.</param>
- /// <param name="value">A value that could be placed in the set.</param>
- /// <param name="comparer">The comparer used to obtain the empty set, if any.</param>
- private void EmptyTestHelper<T>(IImmutableSet<T> emptySet, T value, IComparer<T> comparer)
- {
- Assert.NotNull(emptySet);
-
- this.EmptyTestHelper(emptySet);
- Assert.Same(emptySet, emptySet.ToImmutableSortedSet(comparer));
- Assert.Same(comparer ?? Comparer<T>.Default, ((ISortKeyCollection<T>)emptySet).KeyComparer);
-
- var reemptied = emptySet.Add(value).Clear();
- Assert.Same(reemptied, reemptied.ToImmutableSortedSet(comparer)); //, "Getting the empty set from a non-empty instance did not preserve the comparer.");
- }
}
}
--- /dev/null
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using Xunit;
+
+namespace System.Collections.Immutable.Tests
+{
+ public partial class ImmutableSortedSetTest : ImmutableSetTest
+ {
+ [Fact]
+ [ActiveIssue("Sporadic failure, needs a port of https://github.com/dotnet/coreclr/pull/4340", TargetFrameworkMonikers.NetFramework)]
+ public void EmptyTest()
+ {
+ this.EmptyTestHelper(Empty<int>(), 5, null);
+ this.EmptyTestHelper(Empty<string>().ToImmutableSortedSet(StringComparer.OrdinalIgnoreCase), "a", StringComparer.OrdinalIgnoreCase);
+ }
+
+ [Fact]
+ public void TryGetValueTest()
+ {
+ this.TryGetValueTestHelper(ImmutableSortedSet<string>.Empty.WithComparer(StringComparer.OrdinalIgnoreCase));
+ }
+
+ internal override IBinaryTree GetRootNode<T>(IImmutableSet<T> set)
+ {
+ return ((ImmutableSortedSet<T>)set).Root;
+ }
+
+ /// <summary>
+ /// Tests various aspects of a sorted set.
+ /// </summary>
+ /// <typeparam name="T">The type of element stored in the set.</typeparam>
+ /// <param name="emptySet">The empty set.</param>
+ /// <param name="value">A value that could be placed in the set.</param>
+ /// <param name="comparer">The comparer used to obtain the empty set, if any.</param>
+ private void EmptyTestHelper<T>(IImmutableSet<T> emptySet, T value, IComparer<T> comparer)
+ {
+ Assert.NotNull(emptySet);
+
+ this.EmptyTestHelper(emptySet);
+ Assert.Same(emptySet, emptySet.ToImmutableSortedSet(comparer));
+ Assert.Same(comparer ?? Comparer<T>.Default, ((ISortKeyCollection<T>)emptySet).KeyComparer);
+
+ var reemptied = emptySet.Add(value).Clear();
+ Assert.Same(reemptied, reemptied.ToImmutableSortedSet(comparer)); //, "Getting the empty set from a non-empty instance did not preserve the comparer.");
+ }
+ }
+}
namespace System.Collections.Immutable.Tests
{
- public abstract class ImmutablesTestBase
+ public abstract partial class ImmutablesTestBase
{
/// <summary>
/// Gets the number of operations to perform in randomized tests.
return inputs;
}
- /// <summary>
- /// Tests the EqualsStructurally public method and the IStructuralEquatable.Equals method.
- /// </summary>
- /// <typeparam name="TCollection">The type of tested collection.</typeparam>
- /// <typeparam name="TElement">The type of element stored in the collection.</typeparam>
- /// <param name="objectUnderTest">An instance of the collection to test, which must have at least two elements.</param>
- /// <param name="additionalItem">A unique item that does not already exist in <paramref name="objectUnderTest" />.</param>
- /// <param name="equalsStructurally">A delegate that invokes the EqualsStructurally method.</param>
- protected static void StructuralEqualityHelper<TCollection, TElement>(TCollection objectUnderTest, TElement additionalItem, Func<TCollection, IEnumerable<TElement>, bool> equalsStructurally)
- where TCollection : class, IEnumerable<TElement>
- {
- Requires.NotNull(objectUnderTest, nameof(objectUnderTest));
- Requires.Argument(objectUnderTest.Count() >= 2, nameof(objectUnderTest), "Collection must contain at least two elements.");
- Requires.NotNull(equalsStructurally, nameof(equalsStructurally));
-
- var structuralEquatableUnderTest = objectUnderTest as IStructuralEquatable;
- var enumerableUnderTest = (IEnumerable<TElement>)objectUnderTest;
-
- var equivalentSequence = objectUnderTest.ToList();
- var shorterSequence = equivalentSequence.Take(equivalentSequence.Count() - 1);
- var longerSequence = equivalentSequence.Concat(new[] { additionalItem });
- var differentSequence = shorterSequence.Concat(new[] { additionalItem });
- var nonUniqueSubsetSequenceOfSameLength = shorterSequence.Concat(shorterSequence.Take(1));
-
- var testValues = new IEnumerable<TElement>[] {
- objectUnderTest,
- null,
- Enumerable.Empty<TElement>(),
- equivalentSequence,
- longerSequence,
- shorterSequence,
- nonUniqueSubsetSequenceOfSameLength,
- };
-
- foreach (var value in testValues)
- {
- bool expectedResult = value != null && Enumerable.SequenceEqual(objectUnderTest, value);
-
- if (structuralEquatableUnderTest != null)
- {
- Assert.Equal(expectedResult, structuralEquatableUnderTest.Equals(value, null));
-
- if (value != null)
- {
- Assert.Equal(
- expectedResult,
- structuralEquatableUnderTest.Equals(new NonGenericEnumerableWrapper(value), null));
- }
- }
-
- Assert.Equal(expectedResult, equalsStructurally(objectUnderTest, value));
- }
- }
-
private class DeferredToString
{
private readonly Func<string> _generator;
return _generator();
}
}
-
- private class NonGenericEnumerableWrapper : IEnumerable
- {
- private readonly IEnumerable _enumerable;
-
- internal NonGenericEnumerableWrapper(IEnumerable enumerable)
- {
- Requires.NotNull(enumerable, nameof(enumerable));
- _enumerable = enumerable;
- }
-
- public IEnumerator GetEnumerator()
- {
- return _enumerable.GetEnumerator();
- }
- }
}
}
--- /dev/null
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+using System.Reflection;
+using System.Text;
+using Xunit;
+
+namespace System.Collections.Immutable.Tests
+{
+ public abstract partial class ImmutablesTestBase
+ {
+ /// <summary>
+ /// Tests the EqualsStructurally public method and the IStructuralEquatable.Equals method.
+ /// </summary>
+ /// <typeparam name="TCollection">The type of tested collection.</typeparam>
+ /// <typeparam name="TElement">The type of element stored in the collection.</typeparam>
+ /// <param name="objectUnderTest">An instance of the collection to test, which must have at least two elements.</param>
+ /// <param name="additionalItem">A unique item that does not already exist in <paramref name="objectUnderTest" />.</param>
+ /// <param name="equalsStructurally">A delegate that invokes the EqualsStructurally method.</param>
+ protected static void StructuralEqualityHelper<TCollection, TElement>(TCollection objectUnderTest, TElement additionalItem, Func<TCollection, IEnumerable<TElement>, bool> equalsStructurally)
+ where TCollection : class, IEnumerable<TElement>
+ {
+ Requires.NotNull(objectUnderTest, nameof(objectUnderTest));
+ Requires.Argument(objectUnderTest.Count() >= 2, nameof(objectUnderTest), "Collection must contain at least two elements.");
+ Requires.NotNull(equalsStructurally, nameof(equalsStructurally));
+
+ var structuralEquatableUnderTest = objectUnderTest as IStructuralEquatable;
+ var enumerableUnderTest = (IEnumerable<TElement>)objectUnderTest;
+
+ var equivalentSequence = objectUnderTest.ToList();
+ var shorterSequence = equivalentSequence.Take(equivalentSequence.Count() - 1);
+ var longerSequence = equivalentSequence.Concat(new[] { additionalItem });
+ var differentSequence = shorterSequence.Concat(new[] { additionalItem });
+ var nonUniqueSubsetSequenceOfSameLength = shorterSequence.Concat(shorterSequence.Take(1));
+
+ var testValues = new IEnumerable<TElement>[] {
+ objectUnderTest,
+ null,
+ Enumerable.Empty<TElement>(),
+ equivalentSequence,
+ longerSequence,
+ shorterSequence,
+ nonUniqueSubsetSequenceOfSameLength,
+ };
+
+ foreach (var value in testValues)
+ {
+ bool expectedResult = value != null && Enumerable.SequenceEqual(objectUnderTest, value);
+
+ if (structuralEquatableUnderTest != null)
+ {
+ Assert.Equal(expectedResult, structuralEquatableUnderTest.Equals(value, null));
+
+ if (value != null)
+ {
+ Assert.Equal(
+ expectedResult,
+ structuralEquatableUnderTest.Equals(new NonGenericEnumerableWrapper(value), null));
+ }
+ }
+
+ Assert.Equal(expectedResult, equalsStructurally(objectUnderTest, value));
+ }
+ }
+
+ private class NonGenericEnumerableWrapper : IEnumerable
+ {
+ private readonly IEnumerable _enumerable;
+
+ internal NonGenericEnumerableWrapper(IEnumerable enumerable)
+ {
+ Requires.NotNull(enumerable, nameof(enumerable));
+ _enumerable = enumerable;
+ }
+
+ public IEnumerator GetEnumerator()
+ {
+ return _enumerable.GetEnumerator();
+ }
+ }
+ }
+}
</Compile>
<Compile Include="BadHasher.cs" />
<Compile Include="EverythingEqual.cs" />
- <Compile Include="ImmutableArrayBuilderTest.cs" />
<Compile Include="ImmutableArrayExtensionsTest.cs" />
<Compile Include="ImmutableArrayTest.cs" />
<Compile Include="ImmutableArrayTestBase.cs" />
<Compile Include="ImmutableDictionaryBuilderTest.cs" />
<Compile Include="ImmutableHashSetBuilderTest.cs" />
<Compile Include="ImmutableInterlockedTests.cs" />
- <Compile Include="ImmutableListTestBase.cs" />
- <Compile Include="ImmutableListBuilderTest.cs" />
<Compile Include="ImmutableDictionaryTest.cs" />
<Compile Include="ImmutableHashSetTest.cs" />
- <Compile Include="ImmutableListTest.cs" />
<Compile Include="ImmutableDictionaryTestBase.cs" />
<Compile Include="ImmutableQueueTest.cs" />
<Compile Include="ImmutableSetTest.cs" />
<Compile Include="ImmutableSortedDictionaryBuilderTest.cs" />
<Compile Include="ImmutableSortedDictionaryTest.cs" />
- <Compile Include="ImmutableSortedSetBuilderDebuggerProxyTest.cs" />
<Compile Include="ImmutableSortedSetBuilderTest.cs" />
<Compile Include="ImmutableSortedSetTest.cs" />
<Compile Include="ImmutableStackTest.cs" />
<Compile Include="ImmutableTestBase.cs" />
<Compile Include="IndexOfTests.cs" />
- <Compile Include="RequiresTests.cs" />
<Compile Include="SimpleElementImmutablesTestBase.cs" />
<Compile Include="TestExtensionsMethods.cs" />
<Compile Include="$(CommonTestPath)\System\Diagnostics\DebuggerAttributes.cs">
<None Include="ClassDiagram1.cd" />
<Compile Include="ImmutableArray\ImmutableArray.Generic.Tests.cs" />
</ItemGroup>
- <ItemGroup>
+ <ItemGroup Condition="'$(TargetGroup)' != 'netstandard'">
<!-- Some internal types are needed, so we reference the implementation assembly, rather than the reference assembly. -->
<TargetingPackExclusions Include="System.Collections.Immutable" />
<ReferenceFromRuntime Include="System.Collections.Immutable" />
+ <Compile Include="ImmutableListTestBase.cs" />
+ <Compile Include="ImmutableListTest.cs" />
+ <Compile Include="ImmutableListBuilderTest.cs" />
+ <Compile Include="RequiresTests.cs" />
+ <Compile Include="ImmutableArrayBuilderTest.cs" />
+ <Compile Include="ImmutableDictionaryTestBase.nonnetstandard.cs" />
+ <Compile Include="ImmutableDictionaryTest.nonnetstandard.cs" />
+ <Compile Include="TestExtensionsMethods.nonnetstandard.cs" />
+ <Compile Include="ImmutableSetTest.nonnetstandard.cs" />
+ <Compile Include="ImmutableHashSetTest.nonnetstandard.cs" />
+ <Compile Include="ImmutableSortedSetTest.nonnetstandard.cs" />
+ <Compile Include="ImmutableTestBase.nonnetstandard.cs" />
+ <Compile Include="ImmutableDictionaryBuilderTestBase.nonnetstandard.cs" />
+ <Compile Include="ImmutableSortedSetBuilderDebuggerProxyTest.cs" />
+ <Compile Include="ImmutableSortedSetBuilderTest.nonnetstandard.cs" />
+ <Compile Include="ImmutableSortedDictionaryTest.nonnetstandard.cs" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Resources\$(AssemblyName).rd.xml" />
namespace System.Collections.Immutable.Tests
{
- internal static class TestExtensionsMethods
+ internal static partial class TestExtensionsMethods
{
private static readonly double s_GoldenRatio = (1 + Math.Sqrt(5)) / 2;
- internal static IDictionary<TKey, TValue> ToReadOnlyDictionary<TKey, TValue>(this IImmutableDictionary<TKey, TValue> dictionary)
- {
- Requires.NotNull(dictionary, nameof(dictionary));
-
- return (IDictionary<TKey, TValue>)dictionary;
- }
-
- internal static IDictionary<TKey, TValue> ToBuilder<TKey, TValue>(this IImmutableDictionary<TKey, TValue> dictionary)
- {
- Requires.NotNull(dictionary, nameof(dictionary));
-
- var hashDictionary = dictionary as ImmutableDictionary<TKey, TValue>;
- if (hashDictionary != null)
- {
- return hashDictionary.ToBuilder();
- }
-
- var sortedDictionary = dictionary as ImmutableSortedDictionary<TKey, TValue>;
- if (sortedDictionary != null)
- {
- return sortedDictionary.ToBuilder();
- }
-
- throw new NotSupportedException();
- }
-
- /// <summary>
- /// Verifies that a binary tree is balanced according to AVL rules.
- /// </summary>
- /// <param name="node">The root node of the binary tree.</param>
- internal static void VerifyBalanced(this IBinaryTree node)
- {
- if (node.Left != null)
- {
- VerifyBalanced(node.Left);
- }
-
- if (node.Right != null)
- {
- VerifyBalanced(node.Right);
- }
-
- if (node.Right != null && node.Left != null)
- {
- Assert.InRange(node.Left.Height - node.Right.Height, -1, 1);
- }
- else if (node.Right != null)
- {
- Assert.InRange(node.Right.Height, 0, 1);
- }
- else if (node.Left != null)
- {
- Assert.InRange(node.Left.Height, 0, 1);
- }
- }
-
- /// <summary>
- /// Verifies that a binary tree is no taller than necessary to store the data if it were optimally balanced.
- /// </summary>
- /// <param name="node">The root node.</param>
- /// <param name="count">The number of nodes in the tree. May be <c>null</c> if <see cref="IBinaryTree.Count"/> is functional.</param>
- internal static void VerifyHeightIsWithinTolerance(this IBinaryTree node, int? count = null)
- {
- // http://en.wikipedia.org/wiki/AVL_tree
- double heightMustBeLessThan = Math.Log(2, s_GoldenRatio) * Math.Log(Math.Sqrt(5) * ((count ?? node.Count) + 2), 2) - 2;
- Assert.True(node.Height < heightMustBeLessThan);
- }
-
internal static void ValidateDefaultThisBehavior(Action a)
{
if (!PlatformDetection.IsNetNative) // ActiveIssue UapAot: TFS 428550, https://github.com/dotnet/corefx/issues/19016 - ImmutableArray's null-guard check (ThrowNullRefIfNotInitialized) can get optimized away by certain compilers.
--- /dev/null
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Collections.Generic;
+using Xunit;
+
+namespace System.Collections.Immutable.Tests
+{
+ internal static partial class TestExtensionsMethods
+ {
+ internal static IDictionary<TKey, TValue> ToReadOnlyDictionary<TKey, TValue>(this IImmutableDictionary<TKey, TValue> dictionary)
+ {
+ Requires.NotNull(dictionary, nameof(dictionary));
+
+ return (IDictionary<TKey, TValue>)dictionary;
+ }
+
+ internal static IDictionary<TKey, TValue> ToBuilder<TKey, TValue>(this IImmutableDictionary<TKey, TValue> dictionary)
+ {
+ Requires.NotNull(dictionary, nameof(dictionary));
+
+ var hashDictionary = dictionary as ImmutableDictionary<TKey, TValue>;
+ if (hashDictionary != null)
+ {
+ return hashDictionary.ToBuilder();
+ }
+
+ var sortedDictionary = dictionary as ImmutableSortedDictionary<TKey, TValue>;
+ if (sortedDictionary != null)
+ {
+ return sortedDictionary.ToBuilder();
+ }
+
+ throw new NotSupportedException();
+ }
+
+ /// <summary>
+ /// Verifies that a binary tree is balanced according to AVL rules.
+ /// </summary>
+ /// <param name="node">The root node of the binary tree.</param>
+ internal static void VerifyBalanced(this IBinaryTree node)
+ {
+ if (node.Left != null)
+ {
+ VerifyBalanced(node.Left);
+ }
+
+ if (node.Right != null)
+ {
+ VerifyBalanced(node.Right);
+ }
+
+ if (node.Right != null && node.Left != null)
+ {
+ Assert.InRange(node.Left.Height - node.Right.Height, -1, 1);
+ }
+ else if (node.Right != null)
+ {
+ Assert.InRange(node.Right.Height, 0, 1);
+ }
+ else if (node.Left != null)
+ {
+ Assert.InRange(node.Left.Height, 0, 1);
+ }
+ }
+
+ /// <summary>
+ /// Verifies that a binary tree is no taller than necessary to store the data if it were optimally balanced.
+ /// </summary>
+ /// <param name="node">The root node.</param>
+ /// <param name="count">The number of nodes in the tree. May be <c>null</c> if <see cref="IBinaryTree.Count"/> is functional.</param>
+ internal static void VerifyHeightIsWithinTolerance(this IBinaryTree node, int? count = null)
+ {
+ // http://en.wikipedia.org/wiki/AVL_tree
+ double heightMustBeLessThan = Math.Log(2, s_GoldenRatio) * Math.Log(Math.Sqrt(5) * ((count ?? node.Count) + 2), 2) - 2;
+ Assert.True(node.Height < heightMustBeLessThan);
+ }
+ }
+}