From 4c5f21945d1e8546062f8005ae0aeab02b5dc4ce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Valentin=20Breu=C3=9F?= Date: Sun, 13 Sep 2026 19:32:38 +0200 Subject: [PATCH 1/5] feat!: provide equivalency members from a registry instead of reflection Equivalency enumerates members with `Type.GetFields`/`GetProperties` and then fetches them by name, which trimming and Native AOT cannot preserve: the members are removed and the comparison silently verifies less than it claims to. `TypeMetadataRegistry` lets them be provided statically instead, and the comparison now prefers a registration, reflecting only over types that have none. Only public members are registered. The equivalency options arrive as a callback that a generator cannot inspect, so it can never emit exactly the members a call site will ask for. Asking a registered type for internal or private members therefore throws, because the zero-member guard catches a comparison that finds nothing but not one that merely comes up short. `MemberToIgnore` loses its `MemberInfo` parameter, which no registration can supply. Its only use - in the documented example and in the single test that relied on it - was telling a field from a property, so `IgnoringFields` and `IgnoringProperties` replace the overload that exposed it. A kind-scoped rule is consequently no longer asked about collection elements, which are neither a field nor a property. `RegisterEvent` and the three marker attributes have no consumer yet. They belong to the same Core surface as the members, and splitting them across releases would cost another `CoreOnly` cycle each. `BuildScope` is set to `CoreOnly`, because `aweXpect` compiles against the released `aweXpect.Core` outside `Debug` and cannot yet see the new `MemberToIgnore` shape. Reset it once `aweXpect.Core` is released and the pin is bumped. BREAKING CHANGE: `MemberToIgnore.IgnoreMember` no longer receives a `MemberInfo`, and the `Ignoring` overload that exposed one is replaced by `IgnoringFields` and `IgnoringProperties`. --- Docs/pages/06-equivalency.md | 12 +- Pipeline/Build.cs | 2 +- .../Metadata/GenerateMetadataAttribute.cs | 19 ++ .../RequiresEventMetadataAttribute.cs | 12 ++ .../RequiresMemberMetadataAttribute.cs | 17 ++ .../Core/Metadata/TypeMetadataRegistry.cs | 144 ++++++++++++++ .../EquivalencyComparison.Compare.cs | 51 ++--- .../Equivalency/EquivalencyMembers.cs | 112 +++++++++++ .../Equivalency/MemberToIgnore.cs | 29 ++- .../EquivalencyOptionsExtensions.cs | 34 +++- .../Expected/aweXpect_net10.0.txt | 6 +- .../Expected/aweXpect_net8.0.txt | 6 +- .../Expected/aweXpect_netstandard2.0.txt | 6 +- .../Expected/aweXpect.Core_net10.0.txt | 43 ++++- .../Expected/aweXpect.Core_net8.0.txt | 43 ++++- .../Expected/aweXpect.Core_netstandard2.0.txt | 43 ++++- .../EquivalencyOptionsExtensionsTests.cs | 66 ++++--- ...ThatObject.IsEquivalentTo.MetadataTests.cs | 178 ++++++++++++++++++ .../ThatObject.IsEquivalentTo.Tests.cs | 6 +- 19 files changed, 741 insertions(+), 88 deletions(-) create mode 100644 Source/aweXpect.Core/Core/Metadata/GenerateMetadataAttribute.cs create mode 100644 Source/aweXpect.Core/Core/Metadata/RequiresEventMetadataAttribute.cs create mode 100644 Source/aweXpect.Core/Core/Metadata/RequiresMemberMetadataAttribute.cs create mode 100644 Source/aweXpect.Core/Core/Metadata/TypeMetadataRegistry.cs create mode 100644 Source/aweXpect.Core/Equivalency/EquivalencyMembers.cs create mode 100644 Tests/aweXpect.Tests/Objects/ThatObject.IsEquivalentTo.MetadataTests.cs diff --git a/Docs/pages/06-equivalency.md b/Docs/pages/06-equivalency.md index a75691bfe1..92bb3aa141 100644 --- a/Docs/pages/06-equivalency.md +++ b/Docs/pages/06-equivalency.md @@ -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 @@ -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 diff --git a/Pipeline/Build.cs b/Pipeline/Build.cs index 9f6adebb6f..285fd5df72 100644 --- a/Pipeline/Build.cs +++ b/Pipeline/Build.cs @@ -20,7 +20,7 @@ partial class Build : FalloutBuild /// /// Afterward, you can update the package reference in `Directory.Packages.props` and reset this flag. /// - readonly BuildScope BuildScope = BuildScope.Default; + readonly BuildScope BuildScope = BuildScope.CoreOnly; [Parameter("Github Token")] readonly string GithubToken; [GitRepository] readonly GitRepository Repository; diff --git a/Source/aweXpect.Core/Core/Metadata/GenerateMetadataAttribute.cs b/Source/aweXpect.Core/Core/Metadata/GenerateMetadataAttribute.cs new file mode 100644 index 0000000000..e94728bc18 --- /dev/null +++ b/Source/aweXpect.Core/Core/Metadata/GenerateMetadataAttribute.cs @@ -0,0 +1,19 @@ +using System; + +namespace aweXpect.Core.Metadata; + +/// +/// Names a type whose metadata is needed although no marked call site reveals it. +/// +/// +/// The source generator only sees declared types, so a member declared as or as a base +/// type that holds a derived instance stays invisible to it. Naming such a type here registers it anyway. +/// +[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] +public sealed class GenerateMetadataAttribute(Type type) : Attribute +{ + /// + /// The type whose metadata is needed. + /// + public Type Type { get; } = type; +} diff --git a/Source/aweXpect.Core/Core/Metadata/RequiresEventMetadataAttribute.cs b/Source/aweXpect.Core/Core/Metadata/RequiresEventMetadataAttribute.cs new file mode 100644 index 0000000000..d7980cef3b --- /dev/null +++ b/Source/aweXpect.Core/Core/Metadata/RequiresEventMetadataAttribute.cs @@ -0,0 +1,12 @@ +using System; + +namespace aweXpect.Core.Metadata; + +/// +/// Marks a parameter or type parameter whose type needs its events registered. +/// +/// +/// The source generator seeds from the static type at each call site. +/// +[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.GenericParameter)] +public sealed class RequiresEventMetadataAttribute : Attribute; diff --git a/Source/aweXpect.Core/Core/Metadata/RequiresMemberMetadataAttribute.cs b/Source/aweXpect.Core/Core/Metadata/RequiresMemberMetadataAttribute.cs new file mode 100644 index 0000000000..411c2c2e95 --- /dev/null +++ b/Source/aweXpect.Core/Core/Metadata/RequiresMemberMetadataAttribute.cs @@ -0,0 +1,17 @@ +using System; + +namespace aweXpect.Core.Metadata; + +/// +/// Marks a parameter or type parameter whose type needs its fields and properties registered. +/// +/// +/// The source generator seeds from the static type at each call site, and +/// follows it through its declared members. +/// +/// 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. +/// +[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.GenericParameter)] +public sealed class RequiresMemberMetadataAttribute : Attribute; diff --git a/Source/aweXpect.Core/Core/Metadata/TypeMetadataRegistry.cs b/Source/aweXpect.Core/Core/Metadata/TypeMetadataRegistry.cs new file mode 100644 index 0000000000..d44e99146a --- /dev/null +++ b/Source/aweXpect.Core/Core/Metadata/TypeMetadataRegistry.cs @@ -0,0 +1,144 @@ +using System; +using System.Collections.Concurrent; +using System.Threading; + +namespace aweXpect.Core.Metadata; + +/// +/// Registry for the members and events that expectations access on a subject. +/// +/// +/// 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. +/// +/// Only public instance members are registered: the equivalency options arrive as a callback that a generator +/// cannot inspect, so it can never emit exactly the members a call site will ask for. Requesting non-public +/// members of a registered type therefore fails instead of silently comparing fewer members. +/// +public static class TypeMetadataRegistry +{ + /// + /// An instance instead of static fields, so that it can be verified without affecting the registrations used by + /// the running test. + /// + internal static Registration Instance { get; } = new(); + + /// + /// Registers the public field of . + /// + public static void RegisterField(string name, Func getValue) + => Instance.AddField(typeof(T), name, typeof(TMember), Wrap(getValue)); + + /// + /// Registers the public field of the type of . + /// + /// + /// The is never invoked. It only provides the type argument for types whose name + /// cannot be written in source, such as anonymous types. + /// + public static void RegisterField(T probe, string name, Func getValue) + => RegisterField(name, getValue); + + /// + /// Registers the public property of . + /// + public static void RegisterProperty(string name, Func getValue) + => Instance.AddProperty(typeof(T), name, typeof(TMember), Wrap(getValue)); + + /// + /// Registers the public property of the type of . + /// + /// + /// The is never invoked. It only provides the type argument for types whose name + /// cannot be written in source, such as anonymous types. + /// + public static void RegisterProperty(T probe, string name, Func getValue) + => RegisterProperty(name, getValue); + + /// + /// Registers the event of . + /// + /// + /// 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. + /// + public static void RegisterEvent(string name, + Func, Delegate> createHandler, + Action addHandler, + Action removeHandler) + => Instance.AddEvent(typeof(T), name, createHandler, + (subject, handler) => addHandler((T)subject, handler), + (subject, handler) => removeHandler((T)subject, handler)); + + private static Func Wrap(Func getValue) + => subject => getValue((T)subject); + + internal sealed class Registration + { + private readonly ConcurrentDictionary _metadata = new(); + private int _order; + + public void AddField(Type type, string name, Type memberType, Func getValue) + => GetOrAdd(type).Fields[name] = new RegisteredMember(name, memberType, getValue, NextOrder()); + + public void AddProperty(Type type, string name, Type memberType, Func getValue) + => GetOrAdd(type).Properties[name] = new RegisteredMember(name, memberType, getValue, NextOrder()); + + public void AddEvent(Type type, string name, Func, Delegate> createHandler, + Action addHandler, Action removeHandler) + => GetOrAdd(type).Events[name] = new RegisteredEvent(name, createHandler, addHandler, removeHandler); + + /// + /// Whether any member or event was registered for the . + /// + /// + /// There is no separate completion marker: a type without any member has nothing to emit, so it falls back to + /// reflection, which is the same outcome the zero-member guard already produces. + /// + public bool TryGet(Type type, out TypeMetadata metadata) + { + bool result = _metadata.TryGetValue(type, out TypeMetadata? found); + metadata = found ?? TypeMetadata.Empty; + return result; + } + + private TypeMetadata GetOrAdd(Type type) => _metadata.GetOrAdd(type, _ => new TypeMetadata()); + + /// + /// 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. + /// + private int NextOrder() => Interlocked.Increment(ref _order); + } + + internal sealed class TypeMetadata + { + public static TypeMetadata Empty { get; } = new(); + + public ConcurrentDictionary Fields { get; } = new(StringComparer.Ordinal); + public ConcurrentDictionary Properties { get; } = new(StringComparer.Ordinal); + public ConcurrentDictionary Events { get; } = new(StringComparer.Ordinal); + } + + internal sealed class RegisteredMember(string name, Type memberType, Func getValue, int order) + { + public string Name { get; } = name; + public Type MemberType { get; } = memberType; + public Func GetValue { get; } = getValue; + public int Order { get; } = order; + } + + internal sealed class RegisteredEvent( + string name, + Func, Delegate> createHandler, + Action addHandler, + Action removeHandler) + { + public string Name { get; } = name; + public Func, Delegate> CreateHandler { get; } = createHandler; + public Action AddHandler { get; } = addHandler; + public Action RemoveHandler { get; } = removeHandler; + } +} diff --git a/Source/aweXpect.Core/Equivalency/EquivalencyComparison.Compare.cs b/Source/aweXpect.Core/Equivalency/EquivalencyComparison.Compare.cs index d2a306157a..c41f975723 100644 --- a/Source/aweXpect.Core/Equivalency/EquivalencyComparison.Compare.cs +++ b/Source/aweXpect.Core/Equivalency/EquivalencyComparison.Compare.cs @@ -2,7 +2,6 @@ using System.Collections; using System.Diagnostics.CodeAnalysis; using System.Linq; -using System.Reflection; using System.Text; using System.Threading; using System.Threading.Tasks; @@ -197,21 +196,20 @@ private static async Task 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))) + => memberToIgnore is not MemberToIgnore.ByPropertyPredicate && + 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), @@ -224,21 +222,22 @@ private static async Task 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))) + => memberToIgnore is not MemberToIgnore.ByFieldPredicate && + 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), @@ -300,7 +299,9 @@ private static async Task object? actualObject = actual[key]; if (typeOptions.MembersToIgnore.Any(memberToIgnore - => memberToIgnore.IgnoreMember(elementMemberPath, actualObject?.GetType() ?? typeof(object), null))) + => memberToIgnore is not MemberToIgnore.ByFieldPredicate && + memberToIgnore is not MemberToIgnore.ByPropertyPredicate && + memberToIgnore.IgnoreMember(elementMemberPath, actualObject?.GetType() ?? typeof(object)))) { continue; } @@ -341,7 +342,9 @@ private static async Task string elementMemberPath = $"{memberPath}[{key}]"; object? expectedObject = expected[key]; if (typeOptions.MembersToIgnore.Any(memberToIgnore - => memberToIgnore.IgnoreMember(elementMemberPath, expectedObject?.GetType() ?? typeof(object), null))) + => memberToIgnore is not MemberToIgnore.ByFieldPredicate && + memberToIgnore is not MemberToIgnore.ByPropertyPredicate && + memberToIgnore.IgnoreMember(elementMemberPath, expectedObject?.GetType() ?? typeof(object)))) { continue; } @@ -397,7 +400,9 @@ private static async Task 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))) + => memberToIgnore is not MemberToIgnore.ByFieldPredicate && + memberToIgnore is not MemberToIgnore.ByPropertyPredicate && + memberToIgnore.IgnoreMember(elementMemberPath, actualObject?.GetType() ?? typeof(object)))) { continue; } @@ -419,7 +424,9 @@ private static async Task string elementMemberPath = $"{memberPath}[{i}]"; object? expectedObject = expectedObjects.ElementAtOrDefault(i); if (typeOptions.MembersToIgnore.Any(memberToIgnore - => memberToIgnore.IgnoreMember(elementMemberPath, expectedObject?.GetType() ?? typeof(object), null))) + => memberToIgnore is not MemberToIgnore.ByFieldPredicate && + memberToIgnore is not MemberToIgnore.ByPropertyPredicate && + memberToIgnore.IgnoreMember(elementMemberPath, expectedObject?.GetType() ?? typeof(object)))) { continue; } @@ -445,7 +452,9 @@ private static async Task 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))) + => memberToIgnore is not MemberToIgnore.ByFieldPredicate && + memberToIgnore is not MemberToIgnore.ByPropertyPredicate && + memberToIgnore.IgnoreMember(elementMemberPath, actualObject?.GetType() ?? typeof(object)))) { continue; } diff --git a/Source/aweXpect.Core/Equivalency/EquivalencyMembers.cs b/Source/aweXpect.Core/Equivalency/EquivalencyMembers.cs new file mode 100644 index 0000000000..e8e3992c00 --- /dev/null +++ b/Source/aweXpect.Core/Equivalency/EquivalencyMembers.cs @@ -0,0 +1,112 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using aweXpect.Core.Helpers; +using aweXpect.Core.Metadata; + +namespace aweXpect.Equivalency; + +/// +/// A field or property of a type, resolved either from the or by reflection. +/// +internal readonly struct EquivalencyMember(string name, Type declaredType, Func getValue) +{ + public string Name { get; } = name; + public Type DeclaredType { get; } = declaredType; + public Func GetValue { get; } = getValue; +} + +/// +/// Resolves the members that participate in an equivalency comparison. +/// +/// +/// A registered type is served from the , so that publishing with trimming or +/// Native AOT enabled does not remove the members. Every other type is reflected over, as before. +/// +internal static class EquivalencyMembers +{ + public static IEnumerable GetFields(Type type, IncludeMembers includeMembers) + { + if (TryGetRegistered(type, includeMembers, out TypeMetadataRegistry.TypeMetadata metadata)) + { + return metadata.Fields.Values + .OrderBy(member => member.Order) + .Select(member => new EquivalencyMember(member.Name, member.MemberType, member.GetValue)); + } + + return type.GetFields(includeMembers) + .Select(field => new EquivalencyMember(field.Name, field.FieldType, subject => field.GetValue(subject))); + } + + public static IEnumerable GetProperties(Type type, IncludeMembers includeMembers) + { + if (TryGetRegistered(type, includeMembers, out TypeMetadataRegistry.TypeMetadata metadata)) + { + return metadata.Properties.Values + .OrderBy(member => member.Order) + .Select(member => new EquivalencyMember(member.Name, member.MemberType, member.GetValue)); + } + + return type.GetProperties(includeMembers) + .Select(property + => new EquivalencyMember(property.Name, property.PropertyType, subject => property.GetValue(subject))); + } + + /// + /// Returns the accessor for the field on the , or + /// when it has none. + /// + public static Func? FindField(Type type, string name, IncludeMembers includeMembers) + { + if (TryGetRegistered(type, includeMembers, out TypeMetadataRegistry.TypeMetadata metadata)) + { + return metadata.Fields.TryGetValue(name, out TypeMetadataRegistry.RegisteredMember? member) + ? member.GetValue + : null; + } + + FieldInfo? field = type.GetField(name, includeMembers.GetBindingFlags()); + return field is null ? null : subject => field.GetValue(subject); + } + + /// + /// Returns the accessor for the property on the , or + /// when it has none. + /// + public static Func? FindProperty(Type type, string name, IncludeMembers includeMembers) + { + if (TryGetRegistered(type, includeMembers, out TypeMetadataRegistry.TypeMetadata metadata)) + { + return metadata.Properties.TryGetValue(name, out TypeMetadataRegistry.RegisteredMember? member) + ? member.GetValue + : null; + } + + PropertyInfo? property = type.GetProperty(name, includeMembers.GetBindingFlags()); + return property is null ? null : subject => property.GetValue(subject); + } + + /// + /// The registry only holds public members, and the zero-member guard cannot catch a comparison that comes up + /// short rather than empty, so asking a registered type for non-public members has to fail instead of silently + /// comparing fewer of them. + /// + private static bool TryGetRegistered(Type type, IncludeMembers includeMembers, + out TypeMetadataRegistry.TypeMetadata metadata) + { + if (!TypeMetadataRegistry.Instance.TryGet(type, out metadata)) + { + return false; + } + + if ((includeMembers & ~IncludeMembers.Public) != IncludeMembers.None) + { + throw new InvalidOperationException( + $"Only public members of {Formatter.Format(type)} can be compared, because its members are provided by the generated registration, which - like publishing with trimming or Native AOT enabled - does not preserve non-public members. Restrict the equivalency options to `IncludeMembers.Public`, or compare this type by value.") + .LogTrace(); + } + + return true; + } +} diff --git a/Source/aweXpect.Core/Equivalency/MemberToIgnore.cs b/Source/aweXpect.Core/Equivalency/MemberToIgnore.cs index ea7ca1ee5c..41be2d338f 100644 --- a/Source/aweXpect.Core/Equivalency/MemberToIgnore.cs +++ b/Source/aweXpect.Core/Equivalency/MemberToIgnore.cs @@ -1,5 +1,4 @@ -using System; -using System.Reflection; +using System; namespace aweXpect.Equivalency; @@ -12,28 +11,40 @@ public abstract class MemberToIgnore /// /// Checks if the member should be ignored. /// - public abstract bool IgnoreMember(string memberPath, Type memberType, MemberInfo? memberInfo); + public abstract bool IgnoreMember(string memberPath, Type memberType); /// /// Ignores all members that satisfy the . /// - public class ByPredicate(Func predicate, string description) : MemberToIgnore + public class ByPredicate(Func predicate, string description) : MemberToIgnore { - /// - public override bool IgnoreMember(string memberPath, Type memberType, MemberInfo? memberInfo) - => predicate(memberPath, memberType, memberInfo); + /// + public override bool IgnoreMember(string memberPath, Type memberType) + => predicate(memberPath, memberType); /// public override string ToString() => description; } + /// + /// Ignores all fields that satisfy the . + /// + public sealed class ByFieldPredicate(Func predicate, string description) + : ByPredicate(predicate, description); + + /// + /// Ignores all properties that satisfy the . + /// + public sealed class ByPropertyPredicate(Func predicate, string description) + : ByPredicate(predicate, description); + /// /// Ignores all members that have the provided . /// public class ByName(string memberName) : MemberToIgnore { - /// - public override bool IgnoreMember(string memberPath, Type memberType, MemberInfo? memberInfo) + /// + public override bool IgnoreMember(string memberPath, Type memberType) => memberPath.EndsWith(memberName, StringComparison.OrdinalIgnoreCase); /// diff --git a/Source/aweXpect/Equivalency/EquivalencyOptionsExtensions.cs b/Source/aweXpect/Equivalency/EquivalencyOptionsExtensions.cs index 2eb99a8843..6abafabb46 100644 --- a/Source/aweXpect/Equivalency/EquivalencyOptionsExtensions.cs +++ b/Source/aweXpect/Equivalency/EquivalencyOptionsExtensions.cs @@ -1,5 +1,4 @@ using System; -using System.Reflection; using System.Runtime.CompilerServices; using aweXpect.Customization; @@ -36,8 +35,7 @@ public static TEquivalencyOptions Ignoring( MembersToIgnore = [ ..@this.MembersToIgnore, - new MemberToIgnore.ByPredicate((memberName, memberType, _) => predicate(memberName, memberType), - doNotPopulateThisValue), + new MemberToIgnore.ByPredicate(predicate, doNotPopulateThisValue), ], }; @@ -55,7 +53,7 @@ public static TEquivalencyOptions Ignoring( MembersToIgnore = [ ..@this.MembersToIgnore, - new MemberToIgnore.ByPredicate((memberName, _, _) => predicate(memberName), + new MemberToIgnore.ByPredicate((memberName, _) => predicate(memberName), doNotPopulateThisValue), ], }; @@ -74,17 +72,17 @@ public static TEquivalencyOptions Ignoring( MembersToIgnore = [ ..@this.MembersToIgnore, - new MemberToIgnore.ByPredicate((_, memberType, _) => predicate(memberType), + new MemberToIgnore.ByPredicate((_, memberType) => predicate(memberType), doNotPopulateThisValue), ], }; /// - /// Ignores members matching the when checking for equivalency. + /// Ignores fields matching the when checking for equivalency. /// - public static TEquivalencyOptions Ignoring( + public static TEquivalencyOptions IgnoringFields( this TEquivalencyOptions @this, - Func predicate, + Func predicate, [CallerArgumentExpression("predicate")] string doNotPopulateThisValue = "") where TEquivalencyOptions : EquivalencyTypeOptions @@ -93,7 +91,25 @@ public static TEquivalencyOptions Ignoring( MembersToIgnore = [ ..@this.MembersToIgnore, - new MemberToIgnore.ByPredicate(predicate, doNotPopulateThisValue), + new MemberToIgnore.ByFieldPredicate(predicate, doNotPopulateThisValue), + ], + }; + + /// + /// Ignores properties matching the when checking for equivalency. + /// + public static TEquivalencyOptions IgnoringProperties( + this TEquivalencyOptions @this, + Func predicate, + [CallerArgumentExpression("predicate")] + string doNotPopulateThisValue = "") + where TEquivalencyOptions : EquivalencyTypeOptions + => @this with + { + MembersToIgnore = + [ + ..@this.MembersToIgnore, + new MemberToIgnore.ByPropertyPredicate(predicate, doNotPopulateThisValue), ], }; diff --git a/Tests/aweXpect.Api.Tests/Expected/aweXpect_net10.0.txt b/Tests/aweXpect.Api.Tests/Expected/aweXpect_net10.0.txt index 7dd5c6d0ec..3242f14a8c 100644 --- a/Tests/aweXpect.Api.Tests/Expected/aweXpect_net10.0.txt +++ b/Tests/aweXpect.Api.Tests/Expected/aweXpect_net10.0.txt @@ -1791,12 +1791,14 @@ namespace aweXpect.Equivalency where TEquivalencyOptions : aweXpect.Equivalency.EquivalencyTypeOptions { } public static TEquivalencyOptions Ignoring(this TEquivalencyOptions @this, System.Func predicate, [System.Runtime.CompilerServices.CallerArgumentExpression("predicate")] string doNotPopulateThisValue = "") where TEquivalencyOptions : aweXpect.Equivalency.EquivalencyTypeOptions { } - public static TEquivalencyOptions Ignoring(this TEquivalencyOptions @this, System.Func predicate, [System.Runtime.CompilerServices.CallerArgumentExpression("predicate")] string doNotPopulateThisValue = "") - where TEquivalencyOptions : aweXpect.Equivalency.EquivalencyTypeOptions { } public static TEquivalencyOptions IgnoringCollectionOrder(this TEquivalencyOptions @this, bool ignoreCollectionOrder = true) where TEquivalencyOptions : aweXpect.Equivalency.EquivalencyTypeOptions { } + public static TEquivalencyOptions IgnoringFields(this TEquivalencyOptions @this, System.Func predicate, [System.Runtime.CompilerServices.CallerArgumentExpression("predicate")] string doNotPopulateThisValue = "") + where TEquivalencyOptions : aweXpect.Equivalency.EquivalencyTypeOptions { } public static TEquivalencyOptions IgnoringMember(this TEquivalencyOptions @this, string memberToIgnore) where TEquivalencyOptions : aweXpect.Equivalency.EquivalencyTypeOptions { } + public static TEquivalencyOptions IgnoringProperties(this TEquivalencyOptions @this, System.Func predicate, [System.Runtime.CompilerServices.CallerArgumentExpression("predicate")] string doNotPopulateThisValue = "") + where TEquivalencyOptions : aweXpect.Equivalency.EquivalencyTypeOptions { } public static TEquivalencyOptions IncludingFields(this TEquivalencyOptions @this, aweXpect.Equivalency.IncludeMembers fieldsToInclude = 2) where TEquivalencyOptions : aweXpect.Equivalency.EquivalencyTypeOptions { } public static TEquivalencyOptions IncludingProperties(this TEquivalencyOptions @this, aweXpect.Equivalency.IncludeMembers propertiesToInclude = 2) diff --git a/Tests/aweXpect.Api.Tests/Expected/aweXpect_net8.0.txt b/Tests/aweXpect.Api.Tests/Expected/aweXpect_net8.0.txt index 235a4a7aaa..51b5dd0c01 100644 --- a/Tests/aweXpect.Api.Tests/Expected/aweXpect_net8.0.txt +++ b/Tests/aweXpect.Api.Tests/Expected/aweXpect_net8.0.txt @@ -1791,12 +1791,14 @@ namespace aweXpect.Equivalency where TEquivalencyOptions : aweXpect.Equivalency.EquivalencyTypeOptions { } public static TEquivalencyOptions Ignoring(this TEquivalencyOptions @this, System.Func predicate, [System.Runtime.CompilerServices.CallerArgumentExpression("predicate")] string doNotPopulateThisValue = "") where TEquivalencyOptions : aweXpect.Equivalency.EquivalencyTypeOptions { } - public static TEquivalencyOptions Ignoring(this TEquivalencyOptions @this, System.Func predicate, [System.Runtime.CompilerServices.CallerArgumentExpression("predicate")] string doNotPopulateThisValue = "") - where TEquivalencyOptions : aweXpect.Equivalency.EquivalencyTypeOptions { } public static TEquivalencyOptions IgnoringCollectionOrder(this TEquivalencyOptions @this, bool ignoreCollectionOrder = true) where TEquivalencyOptions : aweXpect.Equivalency.EquivalencyTypeOptions { } + public static TEquivalencyOptions IgnoringFields(this TEquivalencyOptions @this, System.Func predicate, [System.Runtime.CompilerServices.CallerArgumentExpression("predicate")] string doNotPopulateThisValue = "") + where TEquivalencyOptions : aweXpect.Equivalency.EquivalencyTypeOptions { } public static TEquivalencyOptions IgnoringMember(this TEquivalencyOptions @this, string memberToIgnore) where TEquivalencyOptions : aweXpect.Equivalency.EquivalencyTypeOptions { } + public static TEquivalencyOptions IgnoringProperties(this TEquivalencyOptions @this, System.Func predicate, [System.Runtime.CompilerServices.CallerArgumentExpression("predicate")] string doNotPopulateThisValue = "") + where TEquivalencyOptions : aweXpect.Equivalency.EquivalencyTypeOptions { } public static TEquivalencyOptions IncludingFields(this TEquivalencyOptions @this, aweXpect.Equivalency.IncludeMembers fieldsToInclude = 2) where TEquivalencyOptions : aweXpect.Equivalency.EquivalencyTypeOptions { } public static TEquivalencyOptions IncludingProperties(this TEquivalencyOptions @this, aweXpect.Equivalency.IncludeMembers propertiesToInclude = 2) diff --git a/Tests/aweXpect.Api.Tests/Expected/aweXpect_netstandard2.0.txt b/Tests/aweXpect.Api.Tests/Expected/aweXpect_netstandard2.0.txt index dba2ea5018..ce8394c9fc 100644 --- a/Tests/aweXpect.Api.Tests/Expected/aweXpect_netstandard2.0.txt +++ b/Tests/aweXpect.Api.Tests/Expected/aweXpect_netstandard2.0.txt @@ -1686,12 +1686,14 @@ namespace aweXpect.Equivalency where TEquivalencyOptions : aweXpect.Equivalency.EquivalencyTypeOptions { } public static TEquivalencyOptions Ignoring(this TEquivalencyOptions @this, System.Func predicate, [System.Runtime.CompilerServices.CallerArgumentExpression("predicate")] string doNotPopulateThisValue = "") where TEquivalencyOptions : aweXpect.Equivalency.EquivalencyTypeOptions { } - public static TEquivalencyOptions Ignoring(this TEquivalencyOptions @this, System.Func predicate, [System.Runtime.CompilerServices.CallerArgumentExpression("predicate")] string doNotPopulateThisValue = "") - where TEquivalencyOptions : aweXpect.Equivalency.EquivalencyTypeOptions { } public static TEquivalencyOptions IgnoringCollectionOrder(this TEquivalencyOptions @this, bool ignoreCollectionOrder = true) where TEquivalencyOptions : aweXpect.Equivalency.EquivalencyTypeOptions { } + public static TEquivalencyOptions IgnoringFields(this TEquivalencyOptions @this, System.Func predicate, [System.Runtime.CompilerServices.CallerArgumentExpression("predicate")] string doNotPopulateThisValue = "") + where TEquivalencyOptions : aweXpect.Equivalency.EquivalencyTypeOptions { } public static TEquivalencyOptions IgnoringMember(this TEquivalencyOptions @this, string memberToIgnore) where TEquivalencyOptions : aweXpect.Equivalency.EquivalencyTypeOptions { } + public static TEquivalencyOptions IgnoringProperties(this TEquivalencyOptions @this, System.Func predicate, [System.Runtime.CompilerServices.CallerArgumentExpression("predicate")] string doNotPopulateThisValue = "") + where TEquivalencyOptions : aweXpect.Equivalency.EquivalencyTypeOptions { } public static TEquivalencyOptions IncludingFields(this TEquivalencyOptions @this, aweXpect.Equivalency.IncludeMembers fieldsToInclude = 2) where TEquivalencyOptions : aweXpect.Equivalency.EquivalencyTypeOptions { } public static TEquivalencyOptions IncludingProperties(this TEquivalencyOptions @this, aweXpect.Equivalency.IncludeMembers propertiesToInclude = 2) diff --git a/Tests/aweXpect.Core.Api.Tests/Expected/aweXpect.Core_net10.0.txt b/Tests/aweXpect.Core.Api.Tests/Expected/aweXpect.Core_net10.0.txt index aa779c22df..c196dfed9e 100644 --- a/Tests/aweXpect.Core.Api.Tests/Expected/aweXpect.Core_net10.0.txt +++ b/Tests/aweXpect.Core.Api.Tests/Expected/aweXpect.Core_net10.0.txt @@ -401,6 +401,33 @@ namespace aweXpect.Core.Helpers ExplicitlyImplemented = 4, } } +namespace aweXpect.Core.Metadata +{ + [System.AttributeUsage(System.AttributeTargets.Assembly, AllowMultiple=true)] + public sealed class GenerateMetadataAttribute : System.Attribute + { + public GenerateMetadataAttribute(System.Type type) { } + public System.Type Type { get; } + } + [System.AttributeUsage(System.AttributeTargets.Parameter | System.AttributeTargets.GenericParameter)] + public sealed class RequiresEventMetadataAttribute : System.Attribute + { + public RequiresEventMetadataAttribute() { } + } + [System.AttributeUsage(System.AttributeTargets.Parameter | System.AttributeTargets.GenericParameter)] + public sealed class RequiresMemberMetadataAttribute : System.Attribute + { + public RequiresMemberMetadataAttribute() { } + } + public static class TypeMetadataRegistry + { + public static void RegisterEvent(string name, System.Func, System.Delegate> createHandler, System.Action addHandler, System.Action removeHandler) { } + public static void RegisterField(string name, System.Func getValue) { } + public static void RegisterField(T probe, string name, System.Func getValue) { } + public static void RegisterProperty(string name, System.Func getValue) { } + public static void RegisterProperty(T probe, string name, System.Func getValue) { } + } +} namespace aweXpect.Core.Sources { public class DelegateValue @@ -671,19 +698,27 @@ namespace aweXpect.Equivalency public abstract class MemberToIgnore { protected MemberToIgnore() { } - public abstract bool IgnoreMember(string memberPath, System.Type memberType, System.Reflection.MemberInfo? memberInfo); + public abstract bool IgnoreMember(string memberPath, System.Type memberType); + public sealed class ByFieldPredicate : aweXpect.Equivalency.MemberToIgnore.ByPredicate + { + public ByFieldPredicate(System.Func predicate, string description) { } + } public class ByName : aweXpect.Equivalency.MemberToIgnore { public ByName(string memberName) { } - public override bool IgnoreMember(string memberPath, System.Type memberType, System.Reflection.MemberInfo? memberInfo) { } + public override bool IgnoreMember(string memberPath, System.Type memberType) { } public override string ToString() { } } public class ByPredicate : aweXpect.Equivalency.MemberToIgnore { - public ByPredicate(System.Func predicate, string description) { } - public override bool IgnoreMember(string memberPath, System.Type memberType, System.Reflection.MemberInfo? memberInfo) { } + public ByPredicate(System.Func predicate, string description) { } + public override bool IgnoreMember(string memberPath, System.Type memberType) { } public override string ToString() { } } + public sealed class ByPropertyPredicate : aweXpect.Equivalency.MemberToIgnore.ByPredicate + { + public ByPropertyPredicate(System.Func predicate, string description) { } + } } } namespace aweXpect diff --git a/Tests/aweXpect.Core.Api.Tests/Expected/aweXpect.Core_net8.0.txt b/Tests/aweXpect.Core.Api.Tests/Expected/aweXpect.Core_net8.0.txt index 710423ffca..b9f3ee93b2 100644 --- a/Tests/aweXpect.Core.Api.Tests/Expected/aweXpect.Core_net8.0.txt +++ b/Tests/aweXpect.Core.Api.Tests/Expected/aweXpect.Core_net8.0.txt @@ -401,6 +401,33 @@ namespace aweXpect.Core.Helpers ExplicitlyImplemented = 4, } } +namespace aweXpect.Core.Metadata +{ + [System.AttributeUsage(System.AttributeTargets.Assembly, AllowMultiple=true)] + public sealed class GenerateMetadataAttribute : System.Attribute + { + public GenerateMetadataAttribute(System.Type type) { } + public System.Type Type { get; } + } + [System.AttributeUsage(System.AttributeTargets.Parameter | System.AttributeTargets.GenericParameter)] + public sealed class RequiresEventMetadataAttribute : System.Attribute + { + public RequiresEventMetadataAttribute() { } + } + [System.AttributeUsage(System.AttributeTargets.Parameter | System.AttributeTargets.GenericParameter)] + public sealed class RequiresMemberMetadataAttribute : System.Attribute + { + public RequiresMemberMetadataAttribute() { } + } + public static class TypeMetadataRegistry + { + public static void RegisterEvent(string name, System.Func, System.Delegate> createHandler, System.Action addHandler, System.Action removeHandler) { } + public static void RegisterField(string name, System.Func getValue) { } + public static void RegisterField(T probe, string name, System.Func getValue) { } + public static void RegisterProperty(string name, System.Func getValue) { } + public static void RegisterProperty(T probe, string name, System.Func getValue) { } + } +} namespace aweXpect.Core.Sources { public class DelegateValue @@ -671,19 +698,27 @@ namespace aweXpect.Equivalency public abstract class MemberToIgnore { protected MemberToIgnore() { } - public abstract bool IgnoreMember(string memberPath, System.Type memberType, System.Reflection.MemberInfo? memberInfo); + public abstract bool IgnoreMember(string memberPath, System.Type memberType); + public sealed class ByFieldPredicate : aweXpect.Equivalency.MemberToIgnore.ByPredicate + { + public ByFieldPredicate(System.Func predicate, string description) { } + } public class ByName : aweXpect.Equivalency.MemberToIgnore { public ByName(string memberName) { } - public override bool IgnoreMember(string memberPath, System.Type memberType, System.Reflection.MemberInfo? memberInfo) { } + public override bool IgnoreMember(string memberPath, System.Type memberType) { } public override string ToString() { } } public class ByPredicate : aweXpect.Equivalency.MemberToIgnore { - public ByPredicate(System.Func predicate, string description) { } - public override bool IgnoreMember(string memberPath, System.Type memberType, System.Reflection.MemberInfo? memberInfo) { } + public ByPredicate(System.Func predicate, string description) { } + public override bool IgnoreMember(string memberPath, System.Type memberType) { } public override string ToString() { } } + public sealed class ByPropertyPredicate : aweXpect.Equivalency.MemberToIgnore.ByPredicate + { + public ByPropertyPredicate(System.Func predicate, string description) { } + } } } namespace aweXpect diff --git a/Tests/aweXpect.Core.Api.Tests/Expected/aweXpect.Core_netstandard2.0.txt b/Tests/aweXpect.Core.Api.Tests/Expected/aweXpect.Core_netstandard2.0.txt index 845df256bb..04b2965311 100644 --- a/Tests/aweXpect.Core.Api.Tests/Expected/aweXpect.Core_netstandard2.0.txt +++ b/Tests/aweXpect.Core.Api.Tests/Expected/aweXpect.Core_netstandard2.0.txt @@ -387,6 +387,33 @@ namespace aweXpect.Core.Helpers ExplicitlyImplemented = 4, } } +namespace aweXpect.Core.Metadata +{ + [System.AttributeUsage(System.AttributeTargets.Assembly, AllowMultiple=true)] + public sealed class GenerateMetadataAttribute : System.Attribute + { + public GenerateMetadataAttribute(System.Type type) { } + public System.Type Type { get; } + } + [System.AttributeUsage(System.AttributeTargets.Parameter | System.AttributeTargets.GenericParameter)] + public sealed class RequiresEventMetadataAttribute : System.Attribute + { + public RequiresEventMetadataAttribute() { } + } + [System.AttributeUsage(System.AttributeTargets.Parameter | System.AttributeTargets.GenericParameter)] + public sealed class RequiresMemberMetadataAttribute : System.Attribute + { + public RequiresMemberMetadataAttribute() { } + } + public static class TypeMetadataRegistry + { + public static void RegisterEvent(string name, System.Func, System.Delegate> createHandler, System.Action addHandler, System.Action removeHandler) { } + public static void RegisterField(string name, System.Func getValue) { } + public static void RegisterField(T probe, string name, System.Func getValue) { } + public static void RegisterProperty(string name, System.Func getValue) { } + public static void RegisterProperty(T probe, string name, System.Func getValue) { } + } +} namespace aweXpect.Core.Sources { public class DelegateValue @@ -657,19 +684,27 @@ namespace aweXpect.Equivalency public abstract class MemberToIgnore { protected MemberToIgnore() { } - public abstract bool IgnoreMember(string memberPath, System.Type memberType, System.Reflection.MemberInfo? memberInfo); + public abstract bool IgnoreMember(string memberPath, System.Type memberType); + public sealed class ByFieldPredicate : aweXpect.Equivalency.MemberToIgnore.ByPredicate + { + public ByFieldPredicate(System.Func predicate, string description) { } + } public class ByName : aweXpect.Equivalency.MemberToIgnore { public ByName(string memberName) { } - public override bool IgnoreMember(string memberPath, System.Type memberType, System.Reflection.MemberInfo? memberInfo) { } + public override bool IgnoreMember(string memberPath, System.Type memberType) { } public override string ToString() { } } public class ByPredicate : aweXpect.Equivalency.MemberToIgnore { - public ByPredicate(System.Func predicate, string description) { } - public override bool IgnoreMember(string memberPath, System.Type memberType, System.Reflection.MemberInfo? memberInfo) { } + public ByPredicate(System.Func predicate, string description) { } + public override bool IgnoreMember(string memberPath, System.Type memberType) { } public override string ToString() { } } + public sealed class ByPropertyPredicate : aweXpect.Equivalency.MemberToIgnore.ByPredicate + { + public ByPropertyPredicate(System.Func predicate, string description) { } + } } } namespace aweXpect diff --git a/Tests/aweXpect.Internal.Tests/Equivalency/EquivalencyOptionsExtensionsTests.cs b/Tests/aweXpect.Internal.Tests/Equivalency/EquivalencyOptionsExtensionsTests.cs index 2a72bbc7c0..a0654e741f 100644 --- a/Tests/aweXpect.Internal.Tests/Equivalency/EquivalencyOptionsExtensionsTests.cs +++ b/Tests/aweXpect.Internal.Tests/Equivalency/EquivalencyOptionsExtensionsTests.cs @@ -47,28 +47,6 @@ await That(result.ToString()).IsEqualTo(""" """); } - [Fact] - public async Task Generic_For_Ignoring_StringTypeAndMemberInfoPredicate_ShouldSetOptionForType() - { - EquivalencyOptions options = new(); - - EquivalencyOptions result = options.For(o - => o.Ignoring((n, t, f) => n.EndsWith("At") && t == typeof(DateTime) && f != null)); - - await That(result.MembersToIgnore).IsEmpty(); - await That(result.CustomOptions).ContainsKey(typeof(MyClass)) - .WhoseValue.IsEquivalentTo(new - { - MembersToIgnore = It.Is().That.HasCount(1), - }); - await That(result.ToString()).IsEqualTo(""" - - include public fields and properties - - for EquivalencyOptionsExtensionsTests.MyClass: - - include public fields and properties - - ignore members: [(n, t, f) => n.EndsWith("At") && t == typeof(DateTime) && f != null] - """); - } - [Fact] public async Task Generic_For_Ignoring_TypePredicate_ShouldSetOptionForType() { @@ -117,6 +95,28 @@ await That(result.ToString()).IsEqualTo(""" } } + [Fact] + public async Task Generic_For_IgnoringFields_ShouldSetOptionForType() + { + EquivalencyOptions options = new(); + + EquivalencyOptions result = options.For(o + => o.IgnoringFields((n, t) => n.EndsWith("At") && t == typeof(DateTime))); + + await That(result.MembersToIgnore).IsEmpty(); + await That(result.CustomOptions).ContainsKey(typeof(MyClass)) + .WhoseValue.IsEquivalentTo(new + { + MembersToIgnore = It.Is().That.HasCount(1), + }); + await That(result.ToString()).IsEqualTo(""" + - include public fields and properties + - for EquivalencyOptionsExtensionsTests.MyClass: + - include public fields and properties + - ignore members: [(n, t) => n.EndsWith("At") && t == typeof(DateTime)] + """); + } + [Theory] [AutoData] public async Task Generic_For_IgnoringMember_ShouldSetOptionForType(string memberToIgnore) @@ -139,6 +139,28 @@ await That(result.ToString()).IsEqualTo($""" """); } + [Fact] + public async Task Generic_For_IgnoringProperties_ShouldSetOptionForType() + { + EquivalencyOptions options = new(); + + EquivalencyOptions result = options.For(o + => o.IgnoringProperties((n, t) => n.EndsWith("At") && t == typeof(DateTime))); + + await That(result.MembersToIgnore).IsEmpty(); + await That(result.CustomOptions).ContainsKey(typeof(MyClass)) + .WhoseValue.IsEquivalentTo(new + { + MembersToIgnore = It.Is().That.HasCount(1), + }); + await That(result.ToString()).IsEqualTo(""" + - include public fields and properties + - for EquivalencyOptionsExtensionsTests.MyClass: + - include public fields and properties + - ignore members: [(n, t) => n.EndsWith("At") && t == typeof(DateTime)] + """); + } + [Theory] [InlineData(IncludeMembers.None)] [InlineData(IncludeMembers.Internal)] diff --git a/Tests/aweXpect.Tests/Objects/ThatObject.IsEquivalentTo.MetadataTests.cs b/Tests/aweXpect.Tests/Objects/ThatObject.IsEquivalentTo.MetadataTests.cs new file mode 100644 index 0000000000..5f095a977b --- /dev/null +++ b/Tests/aweXpect.Tests/Objects/ThatObject.IsEquivalentTo.MetadataTests.cs @@ -0,0 +1,178 @@ +using System.Collections.Generic; +using aweXpect.Core.Metadata; +using aweXpect.Equivalency; + +namespace aweXpect.Tests; + +public sealed partial class ThatObject +{ + public sealed partial class IsEquivalentTo + { + public sealed class MetadataTests + { + [Fact] + public async Task IgnoringFields_ShouldNotIgnoreProperties() + { + MixedMembers subject = new() + { + Number = 1, + Text = "foo", + }; + MixedMembers expected = new() + { + Number = 2, + Text = "bar", + }; + + async Task Act() + => await That(subject).IsEquivalentTo(expected, o => o.IgnoringFields((_, _) => true)); + + await That(Act).Throws() + .WithMessage("*Property Text differed:*").AsWildcard() + .Because("ignoring every field must leave the properties compared"); + } + + [Fact] + public async Task IgnoringProperties_ShouldNotApplyToCollectionElements() + { + List subject = ["foo",]; + List expected = ["bar",]; + + async Task Act() + => await That(subject).IsEquivalentTo(expected, o => o.IgnoringProperties((_, _) => true)); + + await That(Act).Throws() + .WithMessage("*Element [0] differed:*").AsWildcard() + .Because("a collection element is neither a field nor a property"); + } + + [Fact] + public async Task IgnoringProperties_ShouldNotIgnoreFields() + { + MixedMembers subject = new() + { + Number = 1, + Text = "foo", + }; + MixedMembers expected = new() + { + Number = 2, + Text = "bar", + }; + + async Task Act() + => await That(subject).IsEquivalentTo(expected, o => o.IgnoringProperties((_, _) => true)); + + await That(Act).Throws() + .WithMessage("*Field Number differed:*").AsWildcard() + .Because("ignoring every property must leave the fields compared"); + } + + [Fact] + public async Task WhenRegistered_ShouldCompareOnlyTheRegisteredMembers() + { + RegisterOnlyTheRegisteredProperty(); + RegisteredType subject = new() + { + Registered = 1, + NotRegistered = 1, + }; + RegisteredType expected = new() + { + Registered = 1, + NotRegistered = 2, + }; + + async Task Act() + => await That(subject).IsEquivalentTo(expected); + + await That(Act).DoesNotThrow() + .Because("a registered type is compared through its registration instead of by reflection"); + } + + [Fact] + public async Task WhenRegistered_ShouldCompareTheRegisteredFields() + { + TypeMetadataRegistry.RegisterField( + nameof(RegisteredField.Number), x => x.Number); + RegisteredField subject = new() + { + Number = 1, + }; + RegisteredField expected = new() + { + Number = 2, + }; + + async Task Act() + => await That(subject).IsEquivalentTo(expected); + + await That(Act).Throws() + .WithMessage("*Field Number differed:*").AsWildcard() + .Because("a registered field is compared through its registration"); + } + + [Fact] + public async Task WhenRegistered_WithNonPublicMembers_ShouldThrow() + { + RegisterOnlyTheRegisteredProperty(); + RegisteredType subject = new(); + RegisteredType expected = new(); + + async Task Act() + => await That(subject).IsEquivalentTo(expected, + o => o.IncludingProperties(IncludeMembers.Private)); + + await That(Act).Throws() + .WithMessage("*Only public members of *can be compared*").AsWildcard() + .Because("the registration cannot provide members that trimming would remove"); + } + + [Fact] + public async Task WhenRegisteredWithProbe_ShouldCompareAnonymousTypes() + { + var probe = new + { + Title = default(string), + }; + TypeMetadataRegistry.RegisterProperty(probe, "Title", x => x.Title); + var subject = new + { + Title = "foo", + }; + var expected = new + { + Title = "bar", + }; + + async Task Act() + => await That(subject).IsEquivalentTo(expected); + + await That(Act).Throws() + .WithMessage("*Property Title differed:*").AsWildcard() + .Because("the probe overload registers a type whose name cannot be written in source"); + } + + private static void RegisterOnlyTheRegisteredProperty() + => TypeMetadataRegistry.RegisterProperty( + nameof(RegisteredType.Registered), x => x.Registered); + + private sealed class MixedMembers + { + public int Number; + public string Text { get; set; } = ""; + } + + private sealed class RegisteredField + { + public int Number; + } + + private sealed class RegisteredType + { + public int NotRegistered { get; set; } + public int Registered { get; set; } + } + } + } +} diff --git a/Tests/aweXpect.Tests/Objects/ThatObject.IsEquivalentTo.Tests.cs b/Tests/aweXpect.Tests/Objects/ThatObject.IsEquivalentTo.Tests.cs index a44884aa8a..dedb49b2c1 100644 --- a/Tests/aweXpect.Tests/Objects/ThatObject.IsEquivalentTo.Tests.cs +++ b/Tests/aweXpect.Tests/Objects/ThatObject.IsEquivalentTo.Tests.cs @@ -1,7 +1,6 @@ using System.Collections; using System.Collections.Generic; using System.Linq; -using System.Reflection; using aweXpect.Equivalency; // ReSharper disable UnusedMember.Local @@ -115,7 +114,7 @@ async Task Act() } [Fact] - public async Task IgnoringMismatchingPropertiesByPathTypeAndMemberInfoPredicate_ShouldBeEquivalent() + public async Task IgnoringMismatchingPropertiesByPropertyPredicate_ShouldBeEquivalent() { OuterClass subject = new() { @@ -136,8 +135,7 @@ public async Task IgnoringMismatchingPropertiesByPathTypeAndMemberInfoPredicate_ async Task Act() => await That(subject).IsEquivalentTo(expected, o => o - .Ignoring((memberPath, _, memberInfo) - => memberPath.EndsWith("IntValue") && memberInfo is PropertyInfo)); + .IgnoringProperties((memberPath, _) => memberPath.EndsWith("IntValue"))); await That(Act).DoesNotThrow(); } From 9c873c8f1c065d28f2cf4ce2ca12182133470c02 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Valentin=20Breu=C3=9F?= Date: Sun, 13 Sep 2026 21:27:38 +0200 Subject: [PATCH 2/5] fix: name the ignored member kind in the equivalency options `IgnoringFields` and `IgnoringProperties` both rendered as `ignore members:`, exactly like the unscoped `Ignoring`, so a failure message could not say whether a predicate had been applied to the fields, to the properties or to both. The two option tests asserted the same text as a result, which means they would also have passed with the two rule types wired the wrong way round. The seven sites that decide whether a rule applies to the member at hand now share a single `AppliesTo` helper instead of each restating an inline double negative, so a site added later cannot quietly get the polarity wrong. --- .../EquivalencyComparison.Compare.cs | 35 ++++++++++++------- .../Equivalency/EquivalencyTypeOptions.cs | 28 ++++++++++++--- .../EquivalencyOptionsExtensionsTests.cs | 10 +++--- 3 files changed, 52 insertions(+), 21 deletions(-) diff --git a/Source/aweXpect.Core/Equivalency/EquivalencyComparison.Compare.cs b/Source/aweXpect.Core/Equivalency/EquivalencyComparison.Compare.cs index c41f975723..740860821e 100644 --- a/Source/aweXpect.Core/Equivalency/EquivalencyComparison.Compare.cs +++ b/Source/aweXpect.Core/Equivalency/EquivalencyComparison.Compare.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections; using System.Diagnostics.CodeAnalysis; using System.Linq; @@ -93,6 +93,20 @@ private enum MemberType Value, Element, } + + /// + /// A rule scoped to one kind of member carries that scope in its type, so only the rules that match the + /// are asked. A collection element is neither a field nor a property, so a + /// scoped rule never applies to one. + /// + 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 @@ -201,7 +215,7 @@ private static async Task memberCount++; string fieldMemberPath = ConcatMemberPath(memberPath, field.Name); if (typeOptions.MembersToIgnore.Any(memberToIgnore - => memberToIgnore is not MemberToIgnore.ByPropertyPredicate && + => AppliesTo(memberToIgnore, MemberType.Field) && memberToIgnore.IgnoreMember(fieldMemberPath, field.DeclaredType))) { continue; @@ -228,7 +242,7 @@ private static async Task memberCount++; string propertyMemberPath = ConcatMemberPath(memberPath, property.Name); if (typeOptions.MembersToIgnore.Any(memberToIgnore - => memberToIgnore is not MemberToIgnore.ByFieldPredicate && + => AppliesTo(memberToIgnore, MemberType.Property) && memberToIgnore.IgnoreMember(propertyMemberPath, property.DeclaredType))) { continue; @@ -299,8 +313,7 @@ private static async Task object? actualObject = actual[key]; if (typeOptions.MembersToIgnore.Any(memberToIgnore - => memberToIgnore is not MemberToIgnore.ByFieldPredicate && - memberToIgnore is not MemberToIgnore.ByPropertyPredicate && + => AppliesTo(memberToIgnore, MemberType.Element) && memberToIgnore.IgnoreMember(elementMemberPath, actualObject?.GetType() ?? typeof(object)))) { continue; @@ -342,8 +355,7 @@ memberToIgnore is not MemberToIgnore.ByPropertyPredicate && string elementMemberPath = $"{memberPath}[{key}]"; object? expectedObject = expected[key]; if (typeOptions.MembersToIgnore.Any(memberToIgnore - => memberToIgnore is not MemberToIgnore.ByFieldPredicate && - memberToIgnore is not MemberToIgnore.ByPropertyPredicate && + => AppliesTo(memberToIgnore, MemberType.Element) && memberToIgnore.IgnoreMember(elementMemberPath, expectedObject?.GetType() ?? typeof(object)))) { continue; @@ -400,8 +412,7 @@ private static async Task string elementMemberPath = $"{memberPath}[{(keys is null ? i : keys[i])}]"; object? actualObject = actualObjects.ElementAtOrDefault(i); if (typeOptions.MembersToIgnore.Any(memberToIgnore - => memberToIgnore is not MemberToIgnore.ByFieldPredicate && - memberToIgnore is not MemberToIgnore.ByPropertyPredicate && + => AppliesTo(memberToIgnore, MemberType.Element) && memberToIgnore.IgnoreMember(elementMemberPath, actualObject?.GetType() ?? typeof(object)))) { continue; @@ -424,8 +435,7 @@ memberToIgnore is not MemberToIgnore.ByPropertyPredicate && string elementMemberPath = $"{memberPath}[{i}]"; object? expectedObject = expectedObjects.ElementAtOrDefault(i); if (typeOptions.MembersToIgnore.Any(memberToIgnore - => memberToIgnore is not MemberToIgnore.ByFieldPredicate && - memberToIgnore is not MemberToIgnore.ByPropertyPredicate && + => AppliesTo(memberToIgnore, MemberType.Element) && memberToIgnore.IgnoreMember(elementMemberPath, expectedObject?.GetType() ?? typeof(object)))) { continue; @@ -452,8 +462,7 @@ memberToIgnore is not MemberToIgnore.ByPropertyPredicate && string elementMemberPath = $"{memberPath}[{(keys is null ? i : keys[i])}]"; object? actualObject = actualObjects.ElementAtOrDefault(i); if (typeOptions.MembersToIgnore.Any(memberToIgnore - => memberToIgnore is not MemberToIgnore.ByFieldPredicate && - memberToIgnore is not MemberToIgnore.ByPropertyPredicate && + => AppliesTo(memberToIgnore, MemberType.Element) && memberToIgnore.IgnoreMember(elementMemberPath, actualObject?.GetType() ?? typeof(object)))) { continue; diff --git a/Source/aweXpect.Core/Equivalency/EquivalencyTypeOptions.cs b/Source/aweXpect.Core/Equivalency/EquivalencyTypeOptions.cs index 2153283a36..5ed69ad51b 100644 --- a/Source/aweXpect.Core/Equivalency/EquivalencyTypeOptions.cs +++ b/Source/aweXpect.Core/Equivalency/EquivalencyTypeOptions.cs @@ -1,3 +1,4 @@ +using System.Collections.Generic; using System.Linq; using System.Text; @@ -73,11 +74,30 @@ internal void AppendOptions(StringBuilder sb, string indentation = "") sb.Append(indentation).AppendLine(" - ignore collection order"); } - if (MembersToIgnore.Length > 0) + AppendMembersToIgnore(sb, indentation, "members", + MembersToIgnore.Where(x + => x is not MemberToIgnore.ByFieldPredicate and not MemberToIgnore.ByPropertyPredicate)); + AppendMembersToIgnore(sb, indentation, "fields", + MembersToIgnore.Where(x => x is MemberToIgnore.ByFieldPredicate)); + AppendMembersToIgnore(sb, indentation, "properties", + MembersToIgnore.Where(x => x is MemberToIgnore.ByPropertyPredicate)); + } + + /// + /// The kind is part of the rule, so it has to be part of the rendering too: otherwise a failure message cannot + /// say whether a predicate was applied to the fields, to the properties or to both. + /// + private static void AppendMembersToIgnore(StringBuilder sb, string indentation, string kind, + IEnumerable membersToIgnore) + { + MemberToIgnore[] members = membersToIgnore.ToArray(); + if (members.Length == 0) { - sb.Append(indentation).Append(" - ignore members: "); - Formatter.Format(sb, MembersToIgnore, FormattingOptions.SingleLine); - sb.AppendLine(); + return; } + + sb.Append(indentation).Append(" - ignore ").Append(kind).Append(": "); + Formatter.Format(sb, members, FormattingOptions.SingleLine); + sb.AppendLine(); } } diff --git a/Tests/aweXpect.Internal.Tests/Equivalency/EquivalencyOptionsExtensionsTests.cs b/Tests/aweXpect.Internal.Tests/Equivalency/EquivalencyOptionsExtensionsTests.cs index a0654e741f..b8b0ff8084 100644 --- a/Tests/aweXpect.Internal.Tests/Equivalency/EquivalencyOptionsExtensionsTests.cs +++ b/Tests/aweXpect.Internal.Tests/Equivalency/EquivalencyOptionsExtensionsTests.cs @@ -113,8 +113,9 @@ await That(result.ToString()).IsEqualTo(""" - include public fields and properties - for EquivalencyOptionsExtensionsTests.MyClass: - include public fields and properties - - ignore members: [(n, t) => n.EndsWith("At") && t == typeof(DateTime)] - """); + - ignore fields: [(n, t) => n.EndsWith("At") && t == typeof(DateTime)] + """) + .Because("the rendering has to say which kind of member the predicate is applied to"); } [Theory] @@ -157,8 +158,9 @@ await That(result.ToString()).IsEqualTo(""" - include public fields and properties - for EquivalencyOptionsExtensionsTests.MyClass: - include public fields and properties - - ignore members: [(n, t) => n.EndsWith("At") && t == typeof(DateTime)] - """); + - ignore properties: [(n, t) => n.EndsWith("At") && t == typeof(DateTime)] + """) + .Because("the rendering has to say which kind of member the predicate is applied to"); } [Theory] From b699c777670597baa4785ee4c9a7f54ae839bba2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Valentin=20Breu=C3=9F?= Date: Sun, 13 Sep 2026 21:51:49 +0200 Subject: [PATCH 3/5] fix: reflect over a type whose registration holds only events `RegisterEvent` creates the registry entry for its type, so equivalency treated an event-only registration as a complete member registration, found no fields or properties and hit the zero-member guard instead of reflecting. Only a registered field or property now counts as a member registration. The probe test registered the assembly-wide anonymous shape with a single `Title` property, which every other test using that shape would have shared. A distinctive property name keeps the registration to this test. `TypeMetadata.Empty` was a shared mutable instance handed out on a miss; a nullable `out` says the same thing and cannot be polluted. --- .../Core/Metadata/TypeMetadataRegistry.cs | 15 ++----- .../Equivalency/EquivalencyMembers.cs | 17 ++++--- ...ThatObject.IsEquivalentTo.MetadataTests.cs | 45 ++++++++++++++++--- 3 files changed, 53 insertions(+), 24 deletions(-) diff --git a/Source/aweXpect.Core/Core/Metadata/TypeMetadataRegistry.cs b/Source/aweXpect.Core/Core/Metadata/TypeMetadataRegistry.cs index d44e99146a..febbd0bd13 100644 --- a/Source/aweXpect.Core/Core/Metadata/TypeMetadataRegistry.cs +++ b/Source/aweXpect.Core/Core/Metadata/TypeMetadataRegistry.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Concurrent; +using System.Diagnostics.CodeAnalysis; using System.Threading; namespace aweXpect.Core.Metadata; @@ -93,16 +94,8 @@ public void AddEvent(Type type, string name, Func, Delegate> c /// /// Whether any member or event was registered for the . /// - /// - /// There is no separate completion marker: a type without any member has nothing to emit, so it falls back to - /// reflection, which is the same outcome the zero-member guard already produces. - /// - public bool TryGet(Type type, out TypeMetadata metadata) - { - bool result = _metadata.TryGetValue(type, out TypeMetadata? found); - metadata = found ?? TypeMetadata.Empty; - return result; - } + 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()); @@ -115,8 +108,6 @@ public bool TryGet(Type type, out TypeMetadata metadata) internal sealed class TypeMetadata { - public static TypeMetadata Empty { get; } = new(); - public ConcurrentDictionary Fields { get; } = new(StringComparer.Ordinal); public ConcurrentDictionary Properties { get; } = new(StringComparer.Ordinal); public ConcurrentDictionary Events { get; } = new(StringComparer.Ordinal); diff --git a/Source/aweXpect.Core/Equivalency/EquivalencyMembers.cs b/Source/aweXpect.Core/Equivalency/EquivalencyMembers.cs index e8e3992c00..86f4ccfeac 100644 --- a/Source/aweXpect.Core/Equivalency/EquivalencyMembers.cs +++ b/Source/aweXpect.Core/Equivalency/EquivalencyMembers.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; using aweXpect.Core.Helpers; @@ -28,7 +29,7 @@ internal static class EquivalencyMembers { public static IEnumerable GetFields(Type type, IncludeMembers includeMembers) { - if (TryGetRegistered(type, includeMembers, out TypeMetadataRegistry.TypeMetadata metadata)) + if (TryGetRegistered(type, includeMembers, out TypeMetadataRegistry.TypeMetadata? metadata)) { return metadata.Fields.Values .OrderBy(member => member.Order) @@ -41,7 +42,7 @@ public static IEnumerable GetFields(Type type, IncludeMembers public static IEnumerable GetProperties(Type type, IncludeMembers includeMembers) { - if (TryGetRegistered(type, includeMembers, out TypeMetadataRegistry.TypeMetadata metadata)) + if (TryGetRegistered(type, includeMembers, out TypeMetadataRegistry.TypeMetadata? metadata)) { return metadata.Properties.Values .OrderBy(member => member.Order) @@ -59,7 +60,7 @@ public static IEnumerable GetProperties(Type type, IncludeMem /// public static Func? FindField(Type type, string name, IncludeMembers includeMembers) { - if (TryGetRegistered(type, includeMembers, out TypeMetadataRegistry.TypeMetadata metadata)) + if (TryGetRegistered(type, includeMembers, out TypeMetadataRegistry.TypeMetadata? metadata)) { return metadata.Fields.TryGetValue(name, out TypeMetadataRegistry.RegisteredMember? member) ? member.GetValue @@ -76,7 +77,7 @@ public static IEnumerable GetProperties(Type type, IncludeMem /// public static Func? FindProperty(Type type, string name, IncludeMembers includeMembers) { - if (TryGetRegistered(type, includeMembers, out TypeMetadataRegistry.TypeMetadata metadata)) + if (TryGetRegistered(type, includeMembers, out TypeMetadataRegistry.TypeMetadata? metadata)) { return metadata.Properties.TryGetValue(name, out TypeMetadataRegistry.RegisteredMember? member) ? member.GetValue @@ -88,14 +89,18 @@ public static IEnumerable GetProperties(Type type, IncludeMem } /// + /// A type counts as registered only when it has a field or a property: an event-only registration says nothing + /// about the members, so such a type is reflected over like an unregistered one. + /// /// The registry only holds public members, and the zero-member guard cannot catch a comparison that comes up /// short rather than empty, so asking a registered type for non-public members has to fail instead of silently /// comparing fewer of them. /// private static bool TryGetRegistered(Type type, IncludeMembers includeMembers, - out TypeMetadataRegistry.TypeMetadata metadata) + [NotNullWhen(true)] out TypeMetadataRegistry.TypeMetadata? metadata) { - if (!TypeMetadataRegistry.Instance.TryGet(type, out metadata)) + if (!TypeMetadataRegistry.Instance.TryGet(type, out metadata) || + (metadata.Fields.IsEmpty && metadata.Properties.IsEmpty)) { return false; } diff --git a/Tests/aweXpect.Tests/Objects/ThatObject.IsEquivalentTo.MetadataTests.cs b/Tests/aweXpect.Tests/Objects/ThatObject.IsEquivalentTo.MetadataTests.cs index 5f095a977b..7946a02498 100644 --- a/Tests/aweXpect.Tests/Objects/ThatObject.IsEquivalentTo.MetadataTests.cs +++ b/Tests/aweXpect.Tests/Objects/ThatObject.IsEquivalentTo.MetadataTests.cs @@ -1,3 +1,4 @@ +using System; using System.Collections.Generic; using aweXpect.Core.Metadata; using aweXpect.Equivalency; @@ -68,6 +69,30 @@ await That(Act).Throws() .Because("ignoring every property must leave the fields compared"); } + [Fact] + public async Task WhenOnlyEventsAreRegistered_ShouldCompareByReflection() + { + TypeMetadataRegistry.RegisterEvent(nameof(WithEvent.Changed), + record => new EventHandler((_, _) => record([])), + (instance, handler) => instance.Changed += (EventHandler)handler, + (instance, handler) => instance.Changed -= (EventHandler)handler); + WithEvent subject = new() + { + Number = 1, + }; + WithEvent expected = new() + { + Number = 2, + }; + + async Task Act() + => await That(subject).IsEquivalentTo(expected); + + await That(Act).Throws() + .WithMessage("*Property Number differed:*").AsWildcard() + .Because("an event registration says nothing about the members, which still have to be reflected over"); + } + [Fact] public async Task WhenRegistered_ShouldCompareOnlyTheRegisteredMembers() { @@ -133,24 +158,25 @@ public async Task WhenRegisteredWithProbe_ShouldCompareAnonymousTypes() { var probe = new { - Title = default(string), + MetadataProbeTitle = default(string), }; - TypeMetadataRegistry.RegisterProperty(probe, "Title", x => x.Title); + TypeMetadataRegistry.RegisterProperty(probe, "MetadataProbeTitle", x => x.MetadataProbeTitle); var subject = new { - Title = "foo", + MetadataProbeTitle = "foo", }; var expected = new { - Title = "bar", + MetadataProbeTitle = "bar", }; async Task Act() => await That(subject).IsEquivalentTo(expected); await That(Act).Throws() - .WithMessage("*Property Title differed:*").AsWildcard() - .Because("the probe overload registers a type whose name cannot be written in source"); + .WithMessage("*Property MetadataProbeTitle differed:*").AsWildcard() + .Because( + "the probe overload registers a type whose name cannot be written in source, and the registration is shared by every anonymous type of this shape in the assembly"); } private static void RegisterOnlyTheRegisteredProperty() @@ -173,6 +199,13 @@ private sealed class RegisteredType public int NotRegistered { get; set; } public int Registered { get; set; } } + + private sealed class WithEvent + { + public event EventHandler? Changed; + public int Number { get; set; } + public void Raise() => Changed?.Invoke(this, EventArgs.Empty); + } } } } From de98ebba2a4e969ac31910d5a423c55b0b780e2b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Valentin=20Breu=C3=9F?= Date: Sun, 13 Sep 2026 22:21:06 +0200 Subject: [PATCH 4/5] fix: reflect over the non-public members of a registered type instead of throwing Once the generator registers every type that reaches a marked call site, the throw would have turned `IncludeMembers.Internal` and `IncludeMembers.Private` into a hard failure in every build, including the untrimmed ones where reflection works as it always did. The registry only promises that public members survive trimming, so the public members come from the registration and the non-public part of the request is reflected over like on an unregistered type. Under trimming this is best effort for non-public members, exactly as it is for every type today, and a member the trimmer removed is left out of the comparison silently. That is a deliberate trade against failing every untrimmed build. --- .../Core/Metadata/TypeMetadataRegistry.cs | 7 +- .../Equivalency/EquivalencyMembers.cs | 80 +++++++++---------- ...ThatObject.IsEquivalentTo.MetadataTests.cs | 21 +++-- 3 files changed, 55 insertions(+), 53 deletions(-) diff --git a/Source/aweXpect.Core/Core/Metadata/TypeMetadataRegistry.cs b/Source/aweXpect.Core/Core/Metadata/TypeMetadataRegistry.cs index febbd0bd13..c4340d5ac2 100644 --- a/Source/aweXpect.Core/Core/Metadata/TypeMetadataRegistry.cs +++ b/Source/aweXpect.Core/Core/Metadata/TypeMetadataRegistry.cs @@ -13,9 +13,10 @@ namespace aweXpect.Core.Metadata; /// 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. /// -/// Only public instance members are registered: the equivalency options arrive as a callback that a generator -/// cannot inspect, so it can never emit exactly the members a call site will ask for. Requesting non-public -/// members of a registered type therefore fails instead of silently comparing fewer members. +/// 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. /// public static class TypeMetadataRegistry { diff --git a/Source/aweXpect.Core/Equivalency/EquivalencyMembers.cs b/Source/aweXpect.Core/Equivalency/EquivalencyMembers.cs index 86f4ccfeac..e080b890d2 100644 --- a/Source/aweXpect.Core/Equivalency/EquivalencyMembers.cs +++ b/Source/aweXpect.Core/Equivalency/EquivalencyMembers.cs @@ -1,9 +1,9 @@ using System; +using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; -using aweXpect.Core.Helpers; using aweXpect.Core.Metadata; namespace aweXpect.Equivalency; @@ -22,36 +22,32 @@ internal readonly struct EquivalencyMember(string name, Type declaredType, Func< /// Resolves the members that participate in an equivalency comparison. /// /// -/// A registered type is served from the , so that publishing with trimming or -/// Native AOT enabled does not remove the members. Every other type is reflected over, as before. +/// The public members of a registered type are served from the , so that +/// publishing with trimming or Native AOT enabled does not remove them. Non-public members are never registered, +/// so they are reflected over like the members of an unregistered type. /// internal static class EquivalencyMembers { public static IEnumerable GetFields(Type type, IncludeMembers includeMembers) { - if (TryGetRegistered(type, includeMembers, out TypeMetadataRegistry.TypeMetadata? metadata)) + if (TryGetRegistered(type, out TypeMetadataRegistry.TypeMetadata? metadata)) { - return metadata.Fields.Values - .OrderBy(member => member.Order) - .Select(member => new EquivalencyMember(member.Name, member.MemberType, member.GetValue)); + return Registered(metadata.Fields, includeMembers) + .Concat(ReflectFields(type, includeMembers & ~IncludeMembers.Public)); } - return type.GetFields(includeMembers) - .Select(field => new EquivalencyMember(field.Name, field.FieldType, subject => field.GetValue(subject))); + return ReflectFields(type, includeMembers); } public static IEnumerable GetProperties(Type type, IncludeMembers includeMembers) { - if (TryGetRegistered(type, includeMembers, out TypeMetadataRegistry.TypeMetadata? metadata)) + if (TryGetRegistered(type, out TypeMetadataRegistry.TypeMetadata? metadata)) { - return metadata.Properties.Values - .OrderBy(member => member.Order) - .Select(member => new EquivalencyMember(member.Name, member.MemberType, member.GetValue)); + return Registered(metadata.Properties, includeMembers) + .Concat(ReflectProperties(type, includeMembers & ~IncludeMembers.Public)); } - return type.GetProperties(includeMembers) - .Select(property - => new EquivalencyMember(property.Name, property.PropertyType, subject => property.GetValue(subject))); + return ReflectProperties(type, includeMembers); } /// @@ -60,11 +56,10 @@ public static IEnumerable GetProperties(Type type, IncludeMem /// public static Func? FindField(Type type, string name, IncludeMembers includeMembers) { - if (TryGetRegistered(type, includeMembers, out TypeMetadataRegistry.TypeMetadata? metadata)) + if (TryGetRegistered(type, out TypeMetadataRegistry.TypeMetadata? metadata) && + metadata.Fields.TryGetValue(name, out TypeMetadataRegistry.RegisteredMember? member)) { - return metadata.Fields.TryGetValue(name, out TypeMetadataRegistry.RegisteredMember? member) - ? member.GetValue - : null; + return member.GetValue; } FieldInfo? field = type.GetField(name, includeMembers.GetBindingFlags()); @@ -77,11 +72,10 @@ public static IEnumerable GetProperties(Type type, IncludeMem /// public static Func? FindProperty(Type type, string name, IncludeMembers includeMembers) { - if (TryGetRegistered(type, includeMembers, out TypeMetadataRegistry.TypeMetadata? metadata)) + if (TryGetRegistered(type, out TypeMetadataRegistry.TypeMetadata? metadata) && + metadata.Properties.TryGetValue(name, out TypeMetadataRegistry.RegisteredMember? member)) { - return metadata.Properties.TryGetValue(name, out TypeMetadataRegistry.RegisteredMember? member) - ? member.GetValue - : null; + return member.GetValue; } PropertyInfo? property = type.GetProperty(name, includeMembers.GetBindingFlags()); @@ -91,27 +85,27 @@ public static IEnumerable GetProperties(Type type, IncludeMem /// /// A type counts as registered only when it has a field or a property: an event-only registration says nothing /// about the members, so such a type is reflected over like an unregistered one. - /// - /// The registry only holds public members, and the zero-member guard cannot catch a comparison that comes up - /// short rather than empty, so asking a registered type for non-public members has to fail instead of silently - /// comparing fewer of them. /// - private static bool TryGetRegistered(Type type, IncludeMembers includeMembers, + private static bool TryGetRegistered(Type type, [NotNullWhen(true)] out TypeMetadataRegistry.TypeMetadata? metadata) - { - if (!TypeMetadataRegistry.Instance.TryGet(type, out metadata) || - (metadata.Fields.IsEmpty && metadata.Properties.IsEmpty)) - { - return false; - } + => TypeMetadataRegistry.Instance.TryGet(type, out metadata) && + !(metadata.Fields.IsEmpty && metadata.Properties.IsEmpty); - if ((includeMembers & ~IncludeMembers.Public) != IncludeMembers.None) - { - throw new InvalidOperationException( - $"Only public members of {Formatter.Format(type)} can be compared, because its members are provided by the generated registration, which - like publishing with trimming or Native AOT enabled - does not preserve non-public members. Restrict the equivalency options to `IncludeMembers.Public`, or compare this type by value.") - .LogTrace(); - } + private static IEnumerable Registered( + ConcurrentDictionary members, + IncludeMembers includeMembers) + => includeMembers.HasFlag(IncludeMembers.Public) + ? members.Values + .OrderBy(member => member.Order) + .Select(member => new EquivalencyMember(member.Name, member.MemberType, member.GetValue)) + : Enumerable.Empty(); - return true; - } + private static IEnumerable ReflectFields(Type type, IncludeMembers includeMembers) + => type.GetFields(includeMembers) + .Select(field => new EquivalencyMember(field.Name, field.FieldType, subject => field.GetValue(subject))); + + private static IEnumerable ReflectProperties(Type type, IncludeMembers includeMembers) + => type.GetProperties(includeMembers) + .Select(property + => new EquivalencyMember(property.Name, property.PropertyType, subject => property.GetValue(subject))); } diff --git a/Tests/aweXpect.Tests/Objects/ThatObject.IsEquivalentTo.MetadataTests.cs b/Tests/aweXpect.Tests/Objects/ThatObject.IsEquivalentTo.MetadataTests.cs index 7946a02498..77cfa7e06d 100644 --- a/Tests/aweXpect.Tests/Objects/ThatObject.IsEquivalentTo.MetadataTests.cs +++ b/Tests/aweXpect.Tests/Objects/ThatObject.IsEquivalentTo.MetadataTests.cs @@ -138,19 +138,20 @@ await That(Act).Throws() } [Fact] - public async Task WhenRegistered_WithNonPublicMembers_ShouldThrow() + public async Task WhenRegistered_WithNonPublicMembers_ShouldReflectOverThem() { - RegisterOnlyTheRegisteredProperty(); - RegisteredType subject = new(); - RegisteredType expected = new(); + TypeMetadataRegistry.RegisterProperty( + nameof(RegisteredWithSecret.Registered), x => x.Registered); + RegisteredWithSecret subject = new(1); + RegisteredWithSecret expected = new(2); async Task Act() => await That(subject).IsEquivalentTo(expected, o => o.IncludingProperties(IncludeMembers.Private)); - await That(Act).Throws() - .WithMessage("*Only public members of *can be compared*").AsWildcard() - .Because("the registration cannot provide members that trimming would remove"); + await That(Act).Throws() + .WithMessage("*Property Secret differed:*").AsWildcard() + .Because("the registry only holds public members, so the non-public ones are still reflected over"); } [Fact] @@ -200,6 +201,12 @@ private sealed class RegisteredType public int Registered { get; set; } } + private sealed class RegisteredWithSecret(int secret) + { + public int Registered { get; set; } + private int Secret { get; } = secret; + } + private sealed class WithEvent { public event EventHandler? Changed; From e91ba8bdfa4146f222fd29be9e254890742dbf0e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Valentin=20Breu=C3=9F?= Date: Sun, 13 Sep 2026 22:21:07 +0200 Subject: [PATCH 5/5] fix: include a member that has any of the requested visibilities The visibility filter skipped a member unless it satisfied every requested flag at once, so `IncludeMembers.Public | IncludeMembers.Internal` - the very combination the documentation shows - matched nothing and tripped the zero-member guard. A member now qualifies when it has one of the requested visibilities. Single flags behave as before. --- .../Equivalency/IncludeMembersExtensions.cs | 17 +++++++++------ .../EquivalencyComparerTests.FieldTests.cs | 21 +++++++++++++++++++ .../EquivalencyComparerTests.PropertyTests.cs | 21 +++++++++++++++++++ 3 files changed, 53 insertions(+), 6 deletions(-) diff --git a/Source/aweXpect.Core/Equivalency/IncludeMembersExtensions.cs b/Source/aweXpect.Core/Equivalency/IncludeMembersExtensions.cs index 65f40daccd..3064f173a4 100644 --- a/Source/aweXpect.Core/Equivalency/IncludeMembersExtensions.cs +++ b/Source/aweXpect.Core/Equivalency/IncludeMembersExtensions.cs @@ -29,9 +29,7 @@ public static IEnumerable GetFields(this Type type, IncludeMembers in BindingFlags bindingFlags = GetBindingFlags(includeMembers); foreach (FieldInfo field in type.GetFields(bindingFlags)) { - if ((includeMembers.HasFlag(IncludeMembers.Internal) && !field.IsAssembly) || - (includeMembers.HasFlag(IncludeMembers.Public) && !field.IsPublic) || - (includeMembers.HasFlag(IncludeMembers.Private) && !field.IsPrivate)) + if (!Includes(includeMembers, field.IsPublic, field.IsAssembly, field.IsPrivate)) { continue; } @@ -52,9 +50,7 @@ public static IEnumerable GetProperties(this Type type, IncludeMem { MethodInfo getter = property.GetAccessors(true)[0]; if (!getter.Name.StartsWith("get_", StringComparison.Ordinal) || - (includeMembers.HasFlag(IncludeMembers.Internal) && !getter.IsAssembly) || - (includeMembers.HasFlag(IncludeMembers.Public) && !getter.IsPublic) || - (includeMembers.HasFlag(IncludeMembers.Private) && !getter.IsPrivate)) + !Includes(includeMembers, getter.IsPublic, getter.IsAssembly, getter.IsPrivate)) { continue; } @@ -62,4 +58,13 @@ public static IEnumerable GetProperties(this Type type, IncludeMem yield return property; } } + + /// + /// A member is included when it has one of the requested visibilities. Requiring all of them at once would + /// leave a combination such as Public | Internal without any member. + /// + private static bool Includes(IncludeMembers includeMembers, bool isPublic, bool isAssembly, bool isPrivate) + => (includeMembers.HasFlag(IncludeMembers.Public) && isPublic) || + (includeMembers.HasFlag(IncludeMembers.Internal) && isAssembly) || + (includeMembers.HasFlag(IncludeMembers.Private) && isPrivate); } diff --git a/Tests/aweXpect.Internal.Tests/Helpers/EquivalencyComparerTests.FieldTests.cs b/Tests/aweXpect.Internal.Tests/Helpers/EquivalencyComparerTests.FieldTests.cs index 656723d7d1..f68ce41fb4 100644 --- a/Tests/aweXpect.Internal.Tests/Helpers/EquivalencyComparerTests.FieldTests.cs +++ b/Tests/aweXpect.Internal.Tests/Helpers/EquivalencyComparerTests.FieldTests.cs @@ -144,6 +144,27 @@ await That(sut.GetExtendedFailure("it", ExpectationGrammars.None, actual, expect } } + [Theory] + [InlineData(1, 2, 1, 2, true)] + [InlineData(1, 2, 1, 3, false)] + [InlineData(1, 2, 3, 2, false)] + public async Task WhenIncludingPublicAndInternalMembers_ShouldConsiderPublicAndInternalFields( + int actualPublicValue, int actualInternalValue, int expectedPublicValue, int expectedInternalValue, + bool expectedResult) + { + MyClassWithFields actual = new(actualPublicValue, actualInternalValue, 3); + MyClassWithFields expected = new(expectedPublicValue, expectedInternalValue, 4); + EquivalencyComparer sut = new(new EquivalencyOptions + { + Fields = IncludeMembers.Public | IncludeMembers.Internal, + }); + + bool result = await sut.AreConsideredEqual(actual, expected); + + await That(result).IsEqualTo(expectedResult) + .Because("a field has to satisfy one of the requested visibilities, not all of them at once"); + } + [Theory] [InlineData(5, 5, true)] [InlineData(5, 6, false)] diff --git a/Tests/aweXpect.Internal.Tests/Helpers/EquivalencyComparerTests.PropertyTests.cs b/Tests/aweXpect.Internal.Tests/Helpers/EquivalencyComparerTests.PropertyTests.cs index 93c804d797..25e5813baa 100644 --- a/Tests/aweXpect.Internal.Tests/Helpers/EquivalencyComparerTests.PropertyTests.cs +++ b/Tests/aweXpect.Internal.Tests/Helpers/EquivalencyComparerTests.PropertyTests.cs @@ -149,6 +149,27 @@ await That(sut.GetExtendedFailure("it", ExpectationGrammars.None, actual, expect } } + [Theory] + [InlineData(1, 2, 1, 2, true)] + [InlineData(1, 2, 1, 3, false)] + [InlineData(1, 2, 3, 2, false)] + public async Task WhenIncludingPublicAndInternalMembers_ShouldConsiderPublicAndInternalProperties( + int actualPublicValue, int actualInternalValue, int expectedPublicValue, int expectedInternalValue, + bool expectedResult) + { + MyClassWithProperties actual = new(actualPublicValue, actualInternalValue, 3); + MyClassWithProperties expected = new(expectedPublicValue, expectedInternalValue, 4); + EquivalencyComparer sut = new(new EquivalencyOptions + { + Properties = IncludeMembers.Public | IncludeMembers.Internal, + }); + + bool result = await sut.AreConsideredEqual(actual, expected); + + await That(result).IsEqualTo(expectedResult) + .Because("a property has to satisfy one of the requested visibilities, not all of them at once"); + } + [Theory] [InlineData(5, 5, true)] [InlineData(5, 6, false)]