Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added ContainsAny and DoesNotContainAny to CollectionAssert #4211

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
48 changes: 48 additions & 0 deletions src/NUnitFramework/framework/CollectionAssert.cs
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,30 @@ public static void Contains (IEnumerable collection, Object actual, string messa
}
#endregion

#region ContainsAny
/// <summary>
/// Asserts that collection contains any element of another collection.
/// </summary>
/// <param name="collection">IEnumerable of objects to be considered</param>
/// <param name="expected">IEnumerable of Objects to be found within collection</param>
public static void ContainsAny(IEnumerable collection, IEnumerable expected)
{
ContainsAny(collection, expected, string.Empty, null);
}

/// <summary>
/// Asserts that collection contains any element of another collection.
/// </summary>
/// <param name="collection">IEnumerable of objects to be considered</param>
/// <param name="expected">IEnumerable of Objects to be found within collection</param>
/// <param name="message">The message that will be displayed on failure</param>
/// <param name="args">Arguments to be used in formatting the message</param>
public static void ContainsAny(IEnumerable collection, IEnumerable expected, string message, params object[] args)
{
Assert.That(collection, Is.ContainedIn(expected), message, args);
}
#endregion

#region DoesNotContain

/// <summary>
Expand All @@ -319,6 +343,30 @@ public static void DoesNotContain (IEnumerable collection, Object actual, string
}
#endregion

#region DoesNotContainAny
/// <summary>
/// Asserts that collection does not contain any element of another collection.
/// </summary>
/// <param name="collection">IEnumerable of objects to be considered</param>
/// <param name="expected">IEnumerable of Objects to be found within collection</param>
public static void DoesNotContainAny(IEnumerable collection, IEnumerable expected)
{
DoesNotContainAny(collection, expected, string.Empty, null);
}

/// <summary>
/// Asserts that collection does not contain any element of another collection.
/// </summary>
/// <param name="collection">IEnumerable of objects to be considered</param>
/// <param name="expected">IEnumerable of Objects to be found within collection</param>
/// <param name="message">The message that will be displayed on failure</param>
/// <param name="args">Arguments to be used in formatting the message</param>
public static void DoesNotContainAny(IEnumerable collection, IEnumerable expected, string message, params object[] args)
{
Assert.That(collection, Is.Not.ContainedIn(expected), message, args);
}
#endregion

#region IsNotSubsetOf

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt

#nullable enable

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework.Internal;

namespace NUnit.Framework.Constraints
{
/// <summary>
/// CollectionContainsAnyConstraint is used to determine whether
/// one collection contains any element from another collection
/// </summary>
public class CollectionContainsAnyConstraint : CollectionItemsEqualConstraint
{
private readonly IEnumerable _expected;
private List<object>? _presentItems;

/// <summary>
/// Construct a CollectionContainsAnyConstraint
/// </summary>
/// <param name="expected">The collection that any element from the actual collection is expected to be in</param>
public CollectionContainsAnyConstraint(IEnumerable expected)
: base(expected)
{
_expected = expected;
}

/// <summary>
/// The display name of this Constraint for use by ToString().
/// The default value is the name of the constraint with
/// trailing "Constraint" removed. Derived classes may set
/// this to another name in their constructors.
/// </summary>
public override string DisplayName { get { return "ContainsAny"; } }

/// <summary>
/// The Description of what this constraint tests, for
/// use in messages and in the ConstraintResult.
/// </summary>
public override string Description
{
get { return "contains any from " + MsgUtils.FormatValue(_expected); }
}

/// <summary>
/// Test whether the actual collection contains an element from
/// the expected collection provided.
/// </summary>
protected override bool Matches(IEnumerable actual)
{
CollectionTally tally = Tally(_expected);
tally.TryRemove(actual);

_presentItems = tally.Result.PresentItems;

return _presentItems.Count > 0;
}

/// <summary>
/// Test whether the constraint is satisfied by a given value.
/// </summary>
public override ConstraintResult ApplyTo<TActual>(TActual actual)
{
IEnumerable enumerable = ConstraintUtils.RequireActual<IEnumerable>(actual, nameof(actual));
bool hasElementPresent = Matches(enumerable);
return new CollectionContainsAnyConstraintResult(this, actual, hasElementPresent, _presentItems);
}

/// <summary>
/// Flag the constraint to use the supplied predicate function
/// </summary>
/// <param name="comparison">The comparison function to use.</param>
/// <returns>Self.</returns>
public CollectionContainsAnyConstraint Using<TContainsAnyType, TExpectedType>(Func<TContainsAnyType, TExpectedType, bool> comparison)
{
// internal code reverses the expected order of the arguments.
Func<TExpectedType, TContainsAnyType, bool> invertedComparison = (actual, expected) => comparison.Invoke(expected, actual);
base.Using(EqualityAdapter.For(invertedComparison));
return this;
}

#region Private CollectionContainsAnyConstraintResult Class

private sealed class CollectionContainsAnyConstraintResult : ConstraintResult
{
private readonly List<object>? _presentItems;

public CollectionContainsAnyConstraintResult(IConstraint constraint, object actualValue, bool isSuccess, List<object>? extraItems)
: base(constraint, actualValue, isSuccess)
{
_presentItems = extraItems;
}

public override void WriteAdditionalLinesTo(MessageWriter writer)
{
if (_presentItems?.Count > 0)
{
string presentItemsMessage = "Present items: ";
presentItemsMessage += MsgUtils.FormatCollection(_presentItems);

writer.WriteMessageLine(presentItemsMessage);
}
}
}

#endregion
}
}
15 changes: 13 additions & 2 deletions src/NUnitFramework/framework/Constraints/CollectionTally.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,17 @@ public sealed class CollectionTallyResult
/// <summary>Items that were not in the expected collection.</summary>
public List<object> ExtraItems { get; }

/// <summary>Items that are present in both the expected and actual collections.</summary>
public List<object> PresentItems { get; }

/// <summary>Items that were not accounted for in the expected collection.</summary>
public List<object> MissingItems { get; }

/// <summary>Initializes a new instance of the <see cref="CollectionTallyResult"/> class with the given fields.</summary>
public CollectionTallyResult(List<object> missingItems, List<object> extraItems)
public CollectionTallyResult(List<object> missingItems, List<object> presentItems, List<object> extraItems)
{
MissingItems = missingItems;
PresentItems = presentItems;
ExtraItems = extraItems;
}
}
Expand All @@ -42,6 +46,10 @@ public CollectionTallyResult Result
foreach (var o in _missingItems)
missingItems.Add(o);

var presentItems = new List<object>(_presentItems.Count);
foreach (var o in _presentItems)
presentItems.Add(o);

List<object> extraItems = new List<object>(_extraItems.Count);
if (_sorted)
{
Expand All @@ -53,12 +61,14 @@ public CollectionTallyResult Result
extraItems.AddRange(_extraItems);
}

return new CollectionTallyResult(missingItems, extraItems);
return new CollectionTallyResult(missingItems, presentItems, extraItems);
}
}

private readonly ArrayList _missingItems = new ArrayList();

private readonly List<object> _presentItems = new List<object>();

private readonly List<object> _extraItems = new List<object>();

/// <summary>Construct a CollectionTally object from a comparer and a collection.</summary>
Expand Down Expand Up @@ -91,6 +101,7 @@ public void TryRemove(object o)
{
if (ItemsEqual(_missingItems[index], o))
{
_presentItems.Add(o);
_missingItems.RemoveAt(index);
return;
}
Expand Down
14 changes: 13 additions & 1 deletion src/NUnitFramework/framework/Constraints/ConstraintExpression.cs
Original file line number Diff line number Diff line change
Expand Up @@ -771,6 +771,19 @@ public ContainsConstraint Contain(string expected)

#endregion

#region ContainedIn

/// <summary>
/// Returns a constraint that tests whether the actual value
/// contains an item of the collection supplied as an argument.
/// </summary>
public CollectionContainsAnyConstraint ContainedIn(IEnumerable expected)
{
return (CollectionContainsAnyConstraint)this.Append(new CollectionContainsAnyConstraint(expected));
}

#endregion

#region DictionaryContains
/// <summary>
/// Returns a new DictionaryContainsKeyConstraint checking for the
Expand Down Expand Up @@ -972,7 +985,6 @@ public ConstraintExpression ItemAt(params object[] indexArgs)
{
return this.Append(new IndexerOperator(indexArgs));
}

#endregion
}
}
13 changes: 13 additions & 0 deletions src/NUnitFramework/framework/Is.cs
Original file line number Diff line number Diff line change
Expand Up @@ -373,6 +373,19 @@ public static CollectionEquivalentConstraint EquivalentTo(IEnumerable expected)

#endregion

#region ContainedIn

/// <summary>
/// Returns a constraint that tests whether the actual value
/// contains a value from the collection supplied as an argument.
/// </summary>
public static CollectionContainsAnyConstraint ContainedIn(IEnumerable expected)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for adding this. I often also use the Contains class for this sort of check too. Would it be possible to also expose a Contains.All(IEnumerable) function there too?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Anytime - just want to clarify, do you use Contains with iteration to perform the checks you need? Just want to make sure we are on the same page since they perform different actions.

The naming might have been a bit misleading here - Contains.All(IEnumerable) already exists but is instead named SupersetOf(IEnumerable) within this class.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@tbenne10 Thanks for asking, I appreciate you coming back to this PR after all this time.

You make a good point. I may've mistyped my earlier suggestion in haste. I'd suggest we disregard my suggestion around Contains.All() in the interest of keeping this PR simple. Having thought it through, I agree with @OsirisTerje 's suggestion that it might make sense to expose your new constraint as a Does.ContainAny() method, which could then be easily inverted to be Does.Not.ContainAny() using the already-existing Not constraint.

I think my original comment came from a place of concern around ambiguity of the name Is.ContainedIn in relation to some other API operations when both arguments are collections. If I understand your PR right, the following will pass the first assertion but fail the second and third because they apply fundamentally different checks, though it might not be clear simply by reading them that this will happen.

var a = new[] { 1, 2, 3 };
var b = new[] { 2, 4 };

Assert.That(a, Is.ContainedIn(b));
Assert.That(a, Is.SubsetOf(b));
Assert.That(b, Contains.All(b));

{
return new CollectionContainsAnyConstraint(expected);
}

#endregion

#region SubsetOf

/// <summary>
Expand Down