Skip to content

Added Equal(object) to ServiceTarget so FluentAssertions of equality work correctly #1323

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

Open
wants to merge 3 commits into
base: main
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ public async Task TestCallServiceWithResponseAsync()

executeCommand!.Sequence[0].GetType().GetProperty("service")!.GetValue(executeCommand.Sequence[0])!.Should().Be("domain.service");
executeCommand.Sequence[0].GetType().GetProperty("data")!.GetValue(executeCommand.Sequence[0])!.Should().BeEquivalentTo(serviceData);
executeCommand.Sequence[0].GetType().GetProperty("target")!.GetValue(executeCommand.Sequence[0])!.Should().BeEquivalentTo(serviceTarget);
executeCommand.Sequence[0].GetType().GetProperty("target")!.GetValue(executeCommand.Sequence[0])!.Should().BeEquivalentTo(serviceTarget, options => options.ComparingByMembers<ServiceTarget>());
}

[Fact]
Expand Down
93 changes: 92 additions & 1 deletion src/HassModel/NetDaemon.HassModel.Tests/ServiceTargetTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,95 @@ public void ServiceTargetShouldContainCorrectEntitiesUsingParams()

serviceTarget.EntityIds.Should().BeEquivalentTo("light.kitchen", "light.livingroom");
}
}

[Fact]
public void ServiceTargetAndObjectShouldBeEqual()
{
var serviceTarget1 = ServiceTarget.FromEntity("light.kitchen");
object serviceTarget2 = ServiceTarget.FromEntity("light.kitchen");
serviceTarget1.Should().Be(serviceTarget2);
}

[Fact]
public void ServiceTargetAndObjectShouldNotBeEqual()
{
var serviceTarget1 = ServiceTarget.FromEntity("light.kitchen");
object serviceTarget2 = ServiceTarget.FromEntity("light.livingroom");
serviceTarget1.Should().NotBe(serviceTarget2);
}

[Fact]
public void ServiceTargetsShouldBeEqual()
{
var serviceTarget1 = ServiceTarget.FromEntity("light.kitchen");
var serviceTarget2 = ServiceTarget.FromEntity("light.kitchen");
serviceTarget1.Should().Be(serviceTarget2);
}

[Fact]
public void ServiceTargetsShouldNotBeEqual()
{
var serviceTarget1 = ServiceTarget.FromEntity("light.kitchen");
var serviceTarget2 = ServiceTarget.FromEntity("light.livingroom");
serviceTarget1.Should().NotBe(serviceTarget2);
}

[Fact]
public void ServiceTargetsOperatorEqualNotOverridden()
{
var serviceTarget1 = ServiceTarget.FromEntities("light.kitchen", "light.livingroom");
var serviceTarget2 = ServiceTarget.FromEntities("light.kitchen", "light.livingroom");

// The == operator is not overridden, so the == operator for ServiceTarget will only work on reference equality.
Assert.False((serviceTarget1 == serviceTarget2), "ServiceTargets should not be equal using ==");
}

[Fact]
public void ServiceTargetsOperatorNotEqualNorOverridden()
{
var serviceTarget1 = ServiceTarget.FromEntities("light.kitchen", "light.livingroom");
var serviceTarget2 = ServiceTarget.FromEntities("light.kitchen", "light.kitchen");

// The == operator is not overridden, so the == operator for ServiceTarget will only work on reference equality. You will ALWAYS get true for not equal if not the same reference object
Assert.True((serviceTarget1 != serviceTarget2), "ServiceTargets should not be equal using !=");
}

[Fact]
public void ServiceTargetsOperatorEqualReference()
{
var serviceTarget1 = ServiceTarget.FromEntities("light.kitchen", "light.livingroom");
var serviceTarget1b = serviceTarget1; // Reference to the same object

Assert.True((serviceTarget1 == serviceTarget1b), "ServiceTargets references should be equal using ==");
}

[Fact]
public void ServiceTargetsOperatorNotEqualReference()
{
var serviceTarget1 = ServiceTarget.FromEntity("light.kitchen");
var serviceTarget2 = ServiceTarget.FromEntity("light.livingroom");
var serviceTarget1b = serviceTarget1; // Reference to the same object
var serviceTarget2b = serviceTarget2;

Assert.True((serviceTarget1b != serviceTarget2b), "ServiceTargets references of different objects should not be equal using !=");
}

[Fact]
public void ServiceTargetObjectEqualShouldBeTrue()
{
var serviceTarget1 = ServiceTarget.FromEntity("light.kitchen");
object serviceTarget2 = ServiceTarget.FromEntity("light.kitchen");

Assert.True(serviceTarget1.Equals(serviceTarget2), "ServiceTargets should be equal using Equals.object");
}

[Fact]
public void ServiceTargetObjectEqualShouldNotBeTrue()
{
var serviceTarget1 = ServiceTarget.FromEntity("light.kitchen");
object serviceTarget2 = ServiceTarget.FromEntity("light.livingroom");

Assert.False(serviceTarget1.Equals(serviceTarget2), "ServiceTargets should not be equal using Equals.object");
}

}
72 changes: 72 additions & 0 deletions src/HassModel/NetDaemon.HassModel/ServiceTarget.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,77 @@ public static ServiceTarget FromEntities(IEnumerable<string> entityIds) =>
public static ServiceTarget FromEntities(params string[] entityIds) =>
new() { EntityIds = [.. entityIds] };

/// <summary>
/// Override low level object Equals. This is used by fluent assertions and other libraries to compare objects
/// </summary>
/// <param name="obj">The object that we are comparing to</param>
/// <returns>true if the two objects are the same (Reference equal), or if the two objects are ServiceTargets and passes the Equal test</returns>
public override bool Equals(object? obj)
{
if (ReferenceEquals(this, obj))
{
return true;
}

if (obj is null)
{
return false;
}

if (obj.GetType() != GetType())
{
return false;
}

ServiceTarget other = (ServiceTarget)obj;
//return Equals((ServiceTarget)obj);
return AreCollectionsEqual(EntityIds, other.EntityIds)
&& AreCollectionsEqual(DeviceIds, other.DeviceIds)
&& AreCollectionsEqual(AreaIds, other.AreaIds)
&& AreCollectionsEqual(FloorIds, other.FloorIds)
&& AreCollectionsEqual(LabelIds, other.LabelIds);

}

private static bool AreCollectionsEqual(IReadOnlyCollection<string>? a, IReadOnlyCollection<string>? b)
{
if (ReferenceEquals(a, b))
return true;
if (a is null || b is null)
return false;
bool bReturn = a.Count == b.Count && !a.Except(b).Any();
return bReturn;
}

/// <summary>
/// Override the GetHashCode for completeness for equality checking
/// </summary>
/// <returns>integer hash code for this ServiceTarget</returns>
public override int GetHashCode()
{
int hash = 17;
hash = hash * 23 + (EntityIds is null ? 0 : GetCollectionHashCode(EntityIds));
hash = hash * 23 + (DeviceIds is null ? 0 : GetCollectionHashCode(DeviceIds));
hash = hash * 23 + (AreaIds is null ? 0 : GetCollectionHashCode(AreaIds));
hash = hash * 23 + (FloorIds is null ? 0 : GetCollectionHashCode(FloorIds));
hash = hash * 23 + (LabelIds is null ? 0 : GetCollectionHashCode(LabelIds));
return hash;
}

private static int GetCollectionHashCode(IReadOnlyCollection<string> collection)
{
unchecked
{
int hash = 19;
foreach (var item in collection.OrderBy(x => x))
{
hash = hash * 31 + item.GetHashCode(StringComparison.Ordinal);
}
return hash;
}
}


/// <summary>
/// Creates a new empty ServiceTarget
/// </summary>
Expand Down Expand Up @@ -59,4 +130,5 @@ public ServiceTarget()
/// Ids of labels to invoke a service on
/// </summary>
public IReadOnlyCollection<string>? LabelIds { get; init; }

}
Loading