Skip to content
Merged
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
12 changes: 8 additions & 4 deletions Docs/pages/06-equivalency.md
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ elements, the index is bracketed (e.g. `"Tracks[3]"`).

### Ignoring members by predicate

There are four overloads of `Ignoring`, depending on which information you need:
There are three overloads of `Ignoring`, depending on which information you need:

```csharp
// by member path and type
Expand All @@ -115,11 +115,15 @@ await Expect.That(album).IsEquivalentTo(expected, o => o
// by type only
await Expect.That(album).IsEquivalentTo(expected, o => o
.Ignoring(memberType => memberType == typeof(DateTime)));
```

Use `IgnoringFields` or `IgnoringProperties` instead of `Ignoring` to restrict a predicate to one kind of member.
They take the same member path and type, and are never applied to collection elements, which are neither a field nor a
property:

// by member path, type and reflected MemberInfo
```csharp
await Expect.That(album).IsEquivalentTo(expected, o => o
.Ignoring((memberPath, _, memberInfo)
=> memberPath.EndsWith("PlayCount") && memberInfo is PropertyInfo));
.IgnoringProperties((memberPath, _) => memberPath.EndsWith("PlayCount")));
```

### Including fields and properties
Expand Down
2 changes: 1 addition & 1 deletion Pipeline/Build.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ partial class Build : FalloutBuild
/// <para />
/// Afterward, you can update the package reference in `Directory.Packages.props` and reset this flag.
/// </summary>
readonly BuildScope BuildScope = BuildScope.Default;
readonly BuildScope BuildScope = BuildScope.CoreOnly;

[Parameter("Github Token")] readonly string GithubToken;
[GitRepository] readonly GitRepository Repository;
Expand Down
19 changes: 19 additions & 0 deletions Source/aweXpect.Core/Core/Metadata/GenerateMetadataAttribute.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
using System;

namespace aweXpect.Core.Metadata;

/// <summary>
/// Names a type whose metadata is needed although no marked call site reveals it.
/// </summary>
/// <remarks>
/// The source generator only sees declared types, so a member declared as <see langword="object" /> or as a base
/// type that holds a derived instance stays invisible to it. Naming such a type here registers it anyway.
/// </remarks>
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class GenerateMetadataAttribute(Type type) : Attribute
{
/// <summary>
/// The type whose metadata is needed.
/// </summary>
public Type Type { get; } = type;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
using System;

namespace aweXpect.Core.Metadata;

/// <summary>
/// Marks a parameter or type parameter whose type needs its events registered.
/// </summary>
/// <remarks>
/// The source generator seeds <see cref="TypeMetadataRegistry" /> from the static type at each call site.
/// </remarks>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.GenericParameter)]
public sealed class RequiresEventMetadataAttribute : Attribute;
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
using System;

namespace aweXpect.Core.Metadata;

/// <summary>
/// Marks a parameter or type parameter whose type needs its fields and properties registered.
/// </summary>
/// <remarks>
/// The source generator seeds <see cref="TypeMetadataRegistry" /> from the static type at each call site, and
/// follows it through its declared members.
/// <para />
/// Apply it to every API whose argument reaches an equivalency comparison, including extension methods that only
/// forward to one: a generic extension method carries just an open type parameter at its own call site, so a
/// consumer's call site is the only place the concrete type is visible.
/// </remarks>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.GenericParameter)]
public sealed class RequiresMemberMetadataAttribute : Attribute;
136 changes: 136 additions & 0 deletions Source/aweXpect.Core/Core/Metadata/TypeMetadataRegistry.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
using System;
using System.Collections.Concurrent;
using System.Diagnostics.CodeAnalysis;
using System.Threading;

namespace aweXpect.Core.Metadata;

/// <summary>
/// Registry for the members and events that expectations access on a subject.
/// </summary>
/// <remarks>
/// Reflecting over a type cannot work when the application is published with trimming or Native AOT enabled,
/// because members that are only referenced reflectively are removed. The registrations provide them statically
/// instead, and are normally emitted by the source generator from the call sites that need them.
/// <para />
/// Only public instance members are registered, because a generated accessor cannot reach the non-public members
/// of a type from another assembly on every target. Non-public members are still reflected over when requested,
/// which works unchanged in a normal build and remains best effort when publishing with trimming or Native AOT
/// enabled, where members removed by the trimmer are silently left out of the comparison.
/// </remarks>
public static class TypeMetadataRegistry
{
/// <remarks>
/// An instance instead of static fields, so that it can be verified without affecting the registrations used by
/// the running test.
/// </remarks>
internal static Registration Instance { get; } = new();

/// <summary>
/// Registers the public field <paramref name="name" /> of <typeparamref name="T" />.
/// </summary>
public static void RegisterField<T, TMember>(string name, Func<T, TMember> getValue)
=> Instance.AddField(typeof(T), name, typeof(TMember), Wrap(getValue));

/// <summary>
/// Registers the public field <paramref name="name" /> of the type of <paramref name="probe" />.
/// </summary>
/// <remarks>
/// The <paramref name="probe" /> is never invoked. It only provides the type argument for types whose name
/// cannot be written in source, such as anonymous types.
/// </remarks>
public static void RegisterField<T, TMember>(T probe, string name, Func<T, TMember> getValue)
=> RegisterField(name, getValue);

/// <summary>
/// Registers the public property <paramref name="name" /> of <typeparamref name="T" />.
/// </summary>
public static void RegisterProperty<T, TMember>(string name, Func<T, TMember> getValue)
=> Instance.AddProperty(typeof(T), name, typeof(TMember), Wrap(getValue));

/// <summary>
/// Registers the public property <paramref name="name" /> of the type of <paramref name="probe" />.
/// </summary>
/// <remarks>
/// The <paramref name="probe" /> is never invoked. It only provides the type argument for types whose name
/// cannot be written in source, such as anonymous types.
/// </remarks>
public static void RegisterProperty<T, TMember>(T probe, string name, Func<T, TMember> getValue)
=> RegisterProperty(name, getValue);

/// <summary>
/// Registers the event <paramref name="name" /> of <typeparamref name="T" />.
/// </summary>
/// <remarks>
/// <paramref name="createHandler" /> receives the callback that records an occurrence and returns a delegate of
/// the event handler type. Creating the handler in generated code avoids binding it reflectively, which cannot
/// work for a handler with value-type parameters.
/// </remarks>
public static void RegisterEvent<T>(string name,
Func<Action<object?[]>, Delegate> createHandler,
Action<T, Delegate> addHandler,
Action<T, Delegate> removeHandler)
=> Instance.AddEvent(typeof(T), name, createHandler,
(subject, handler) => addHandler((T)subject, handler),
(subject, handler) => removeHandler((T)subject, handler));

private static Func<object, object?> Wrap<T, TMember>(Func<T, TMember> getValue)
=> subject => getValue((T)subject);

internal sealed class Registration
{
private readonly ConcurrentDictionary<Type, TypeMetadata> _metadata = new();
private int _order;

public void AddField(Type type, string name, Type memberType, Func<object, object?> getValue)
=> GetOrAdd(type).Fields[name] = new RegisteredMember(name, memberType, getValue, NextOrder());

public void AddProperty(Type type, string name, Type memberType, Func<object, object?> getValue)
=> GetOrAdd(type).Properties[name] = new RegisteredMember(name, memberType, getValue, NextOrder());

public void AddEvent(Type type, string name, Func<Action<object?[]>, Delegate> createHandler,
Action<object, Delegate> addHandler, Action<object, Delegate> removeHandler)
=> GetOrAdd(type).Events[name] = new RegisteredEvent(name, createHandler, addHandler, removeHandler);

/// <summary>
/// Whether any member or event was registered for the <paramref name="type" />.
/// </summary>
public bool TryGet(Type type, [NotNullWhen(true)] out TypeMetadata? metadata)
=> _metadata.TryGetValue(type, out metadata);

private TypeMetadata GetOrAdd(Type type) => _metadata.GetOrAdd(type, _ => new TypeMetadata());

/// <remarks>
/// Registrations keep the order the generator emitted them in, so that a failure message lists the members of
/// a registered type in the same order as the reflected one.
/// </remarks>
private int NextOrder() => Interlocked.Increment(ref _order);
}

internal sealed class TypeMetadata
{
public ConcurrentDictionary<string, RegisteredMember> Fields { get; } = new(StringComparer.Ordinal);
public ConcurrentDictionary<string, RegisteredMember> Properties { get; } = new(StringComparer.Ordinal);
public ConcurrentDictionary<string, RegisteredEvent> Events { get; } = new(StringComparer.Ordinal);
}

internal sealed class RegisteredMember(string name, Type memberType, Func<object, object?> getValue, int order)
{
public string Name { get; } = name;
public Type MemberType { get; } = memberType;
public Func<object, object?> GetValue { get; } = getValue;
public int Order { get; } = order;
}

internal sealed class RegisteredEvent(
string name,
Func<Action<object?[]>, Delegate> createHandler,
Action<object, Delegate> addHandler,
Action<object, Delegate> removeHandler)
{
public string Name { get; } = name;
public Func<Action<object?[]>, Delegate> CreateHandler { get; } = createHandler;
public Action<object, Delegate> AddHandler { get; } = addHandler;
public Action<object, Delegate> RemoveHandler { get; } = removeHandler;
}
}
62 changes: 40 additions & 22 deletions Source/aweXpect.Core/Equivalency/EquivalencyComparison.Compare.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
using System;
using System;
using System.Collections;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
Expand Down Expand Up @@ -94,6 +93,20 @@ private enum MemberType
Value,
Element,
}

/// <remarks>
/// A rule scoped to one kind of member carries that scope in its type, so only the rules that match the
/// <paramref name="memberType" /> are asked. A collection element is neither a field nor a property, so a
/// scoped rule never applies to one.
/// </remarks>
private static bool AppliesTo(MemberToIgnore memberToIgnore, MemberType memberType)
=> memberType switch
{
MemberType.Field => memberToIgnore is not MemberToIgnore.ByPropertyPredicate,
MemberType.Property => memberToIgnore is not MemberToIgnore.ByFieldPredicate,
_ => memberToIgnore is not MemberToIgnore.ByFieldPredicate and
not MemberToIgnore.ByPropertyPredicate,
};
#pragma warning disable S3776 // https://rules.sonarsource.com/csharp/RSPEC-3776
#pragma warning disable S107 // https://rules.sonarsource.com/csharp/RSPEC-107
#if NET8_0_OR_GREATER
Expand Down Expand Up @@ -197,21 +210,20 @@ private static async Task<bool>
int memberCount = 0;
if (typeOptions.Fields != IncludeMembers.None)
{
BindingFlags fieldBindingFlags = typeOptions.Fields.GetBindingFlags();
foreach (FieldInfo? fieldInfo in expected.GetType().GetFields(typeOptions.Fields))
foreach (EquivalencyMember field in EquivalencyMembers.GetFields(expected.GetType(), typeOptions.Fields))
{
memberCount++;
string fieldMemberPath = ConcatMemberPath(memberPath, fieldInfo.Name);
string fieldMemberPath = ConcatMemberPath(memberPath, field.Name);
if (typeOptions.MembersToIgnore.Any(memberToIgnore
=> memberToIgnore.IgnoreMember(fieldMemberPath, fieldInfo.FieldType, fieldInfo)))
=> AppliesTo(memberToIgnore, MemberType.Field) &&
memberToIgnore.IgnoreMember(fieldMemberPath, field.DeclaredType)))
{
continue;
}

object? actualFieldValue =
actual.GetType().GetField(fieldInfo.Name, fieldBindingFlags)?.GetValue(actual);
object? expectedFieldValue =
expected.GetType().GetField(fieldInfo.Name, fieldBindingFlags)?.GetValue(expected);
EquivalencyMembers.FindField(actual.GetType(), field.Name, typeOptions.Fields)?.Invoke(actual);
object? expectedFieldValue = field.GetValue(expected);

if (!await Compare(actualFieldValue, expectedFieldValue,
options, options.GetTypeOptions(actualFieldValue?.GetType(), typeOptions),
Expand All @@ -224,21 +236,22 @@ private static async Task<bool>

if (typeOptions.Properties != IncludeMembers.None)
{
BindingFlags propertyBindingFlags = typeOptions.Properties.GetBindingFlags();
foreach (PropertyInfo? propertyInfo in expected.GetType().GetProperties(typeOptions.Properties))
foreach (EquivalencyMember property in EquivalencyMembers.GetProperties(expected.GetType(),
typeOptions.Properties))
{
memberCount++;
string propertyMemberPath = ConcatMemberPath(memberPath, propertyInfo.Name);
string propertyMemberPath = ConcatMemberPath(memberPath, property.Name);
if (typeOptions.MembersToIgnore.Any(memberToIgnore
=> memberToIgnore.IgnoreMember(propertyMemberPath, propertyInfo.PropertyType, propertyInfo)))
=> AppliesTo(memberToIgnore, MemberType.Property) &&
memberToIgnore.IgnoreMember(propertyMemberPath, property.DeclaredType)))
{
continue;
}

object? actualPropertyValue = actual.GetType().GetProperty(propertyInfo.Name, propertyBindingFlags)
?.GetValue(actual);
object? expectedPropertyValue =
expected.GetType().GetProperty(propertyInfo.Name, propertyBindingFlags)?.GetValue(expected);
object? actualPropertyValue =
EquivalencyMembers.FindProperty(actual.GetType(), property.Name, typeOptions.Properties)
?.Invoke(actual);
object? expectedPropertyValue = property.GetValue(expected);

if (!await Compare(actualPropertyValue, expectedPropertyValue,
options, options.GetTypeOptions(actualPropertyValue?.GetType(), typeOptions),
Expand Down Expand Up @@ -300,7 +313,8 @@ private static async Task<bool>

object? actualObject = actual[key];
if (typeOptions.MembersToIgnore.Any(memberToIgnore
=> memberToIgnore.IgnoreMember(elementMemberPath, actualObject?.GetType() ?? typeof(object), null)))
=> AppliesTo(memberToIgnore, MemberType.Element) &&
memberToIgnore.IgnoreMember(elementMemberPath, actualObject?.GetType() ?? typeof(object))))
{
continue;
}
Expand Down Expand Up @@ -341,7 +355,8 @@ private static async Task<bool>
string elementMemberPath = $"{memberPath}[{key}]";
object? expectedObject = expected[key];
if (typeOptions.MembersToIgnore.Any(memberToIgnore
=> memberToIgnore.IgnoreMember(elementMemberPath, expectedObject?.GetType() ?? typeof(object), null)))
=> AppliesTo(memberToIgnore, MemberType.Element) &&
memberToIgnore.IgnoreMember(elementMemberPath, expectedObject?.GetType() ?? typeof(object))))
{
continue;
}
Expand Down Expand Up @@ -397,7 +412,8 @@ private static async Task<bool>
string elementMemberPath = $"{memberPath}[{(keys is null ? i : keys[i])}]";
object? actualObject = actualObjects.ElementAtOrDefault(i);
if (typeOptions.MembersToIgnore.Any(memberToIgnore
=> memberToIgnore.IgnoreMember(elementMemberPath, actualObject?.GetType() ?? typeof(object), null)))
=> AppliesTo(memberToIgnore, MemberType.Element) &&
memberToIgnore.IgnoreMember(elementMemberPath, actualObject?.GetType() ?? typeof(object))))
{
continue;
}
Expand All @@ -419,7 +435,8 @@ private static async Task<bool>
string elementMemberPath = $"{memberPath}[{i}]";
object? expectedObject = expectedObjects.ElementAtOrDefault(i);
if (typeOptions.MembersToIgnore.Any(memberToIgnore
=> memberToIgnore.IgnoreMember(elementMemberPath, expectedObject?.GetType() ?? typeof(object), null)))
=> AppliesTo(memberToIgnore, MemberType.Element) &&
memberToIgnore.IgnoreMember(elementMemberPath, expectedObject?.GetType() ?? typeof(object))))
{
continue;
}
Expand All @@ -445,7 +462,8 @@ private static async Task<bool>
string elementMemberPath = $"{memberPath}[{(keys is null ? i : keys[i])}]";
object? actualObject = actualObjects.ElementAtOrDefault(i);
if (typeOptions.MembersToIgnore.Any(memberToIgnore
=> memberToIgnore.IgnoreMember(elementMemberPath, actualObject?.GetType() ?? typeof(object), null)))
=> AppliesTo(memberToIgnore, MemberType.Element) &&
memberToIgnore.IgnoreMember(elementMemberPath, actualObject?.GetType() ?? typeof(object))))
{
continue;
}
Expand Down
Loading
Loading