Skip to content

Commit

Permalink
xunit/xunit#2872: Expand special handling for sets in Assert.Contains…
Browse files Browse the repository at this point in the history
…/DoesNotContain
  • Loading branch information
bradwilson committed Feb 4, 2024
1 parent 3b8edcb commit 574aeba
Showing 1 changed file with 38 additions and 14 deletions.
52 changes: 38 additions & 14 deletions CollectionAsserts.cs
Original file line number Diff line number Diff line change
Expand Up @@ -226,13 +226,25 @@ partial class Assert
{
GuardArgumentNotNull(nameof(collection), collection);

// We special case HashSet<T> because it has a custom Contains implementation that is based on the comparer
// passed into their constructors, which we don't have access to.
var hashSet = collection as HashSet<T>;
if (hashSet != null)
Contains(expected, hashSet);
else
Contains(expected, collection, GetEqualityComparer<T>());
// We special case sets because they are constructed with their comparers, which we don't have access to.
// We want to let them do their normal logic when appropriate, and not try to use our default comparer.
var set = collection as ISet<T>;
if (set != null)
{
Contains(expected, set);
return;
}
#if NET5_0_OR_GREATER
var readOnlySet = collection as IReadOnlySet<T>;
if (readOnlySet != null)
{
Contains(expected, readOnlySet);
return;
}
#endif

// Fall back to the assumption that this is a linear container and use our default comparer
Contains(expected, collection, GetEqualityComparer<T>());
}

/// <summary>
Expand Down Expand Up @@ -326,13 +338,25 @@ partial class Assert
{
GuardArgumentNotNull(nameof(collection), collection);

// We special case HashSet<T> because it has a custom Contains implementation that is based on the comparer
// passed into their constructors, which we don't have access to.
var hashSet = collection as HashSet<T>;
if (hashSet != null)
DoesNotContain(expected, hashSet);
else
DoesNotContain(expected, collection, GetEqualityComparer<T>());
// We special case sets because they are constructed with their comparers, which we don't have access to.
// We want to let them do their normal logic when appropriate, and not try to use our default comparer.
var set = collection as ISet<T>;
if (set != null)
{
DoesNotContain(expected, set);
return;
}
#if NET5_0_OR_GREATER
var readOnlySet = collection as IReadOnlySet<T>;
if (readOnlySet != null)
{
DoesNotContain(expected, readOnlySet);
return;
}
#endif

// Fall back to the assumption that this is a linear container and use our default comparer
DoesNotContain(expected, collection, GetEqualityComparer<T>());
}

/// <summary>
Expand Down

0 comments on commit 574aeba

Please sign in to comment.