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..c4340d5ac2 --- /dev/null +++ b/Source/aweXpect.Core/Core/Metadata/TypeMetadataRegistry.cs @@ -0,0 +1,136 @@ +using System; +using System.Collections.Concurrent; +using System.Diagnostics.CodeAnalysis; +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, 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 +{ + /// + /// 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 . + /// + 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()); + + /// + /// 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 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..740860821e 100644 --- a/Source/aweXpect.Core/Equivalency/EquivalencyComparison.Compare.cs +++ b/Source/aweXpect.Core/Equivalency/EquivalencyComparison.Compare.cs @@ -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; @@ -94,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 @@ -197,21 +210,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))) + => 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), @@ -224,21 +236,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))) + => 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), @@ -300,7 +313,8 @@ private static async Task 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; } @@ -341,7 +355,8 @@ 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))) + => AppliesTo(memberToIgnore, MemberType.Element) && + memberToIgnore.IgnoreMember(elementMemberPath, expectedObject?.GetType() ?? typeof(object)))) { continue; } @@ -397,7 +412,8 @@ 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))) + => AppliesTo(memberToIgnore, MemberType.Element) && + memberToIgnore.IgnoreMember(elementMemberPath, actualObject?.GetType() ?? typeof(object)))) { continue; } @@ -419,7 +435,8 @@ 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))) + => AppliesTo(memberToIgnore, MemberType.Element) && + memberToIgnore.IgnoreMember(elementMemberPath, expectedObject?.GetType() ?? typeof(object)))) { continue; } @@ -445,7 +462,8 @@ 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))) + => AppliesTo(memberToIgnore, MemberType.Element) && + 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..e080b890d2 --- /dev/null +++ b/Source/aweXpect.Core/Equivalency/EquivalencyMembers.cs @@ -0,0 +1,111 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Reflection; +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. +/// +/// +/// 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, out TypeMetadataRegistry.TypeMetadata? metadata)) + { + return Registered(metadata.Fields, includeMembers) + .Concat(ReflectFields(type, includeMembers & ~IncludeMembers.Public)); + } + + return ReflectFields(type, includeMembers); + } + + public static IEnumerable GetProperties(Type type, IncludeMembers includeMembers) + { + if (TryGetRegistered(type, out TypeMetadataRegistry.TypeMetadata? metadata)) + { + return Registered(metadata.Properties, includeMembers) + .Concat(ReflectProperties(type, includeMembers & ~IncludeMembers.Public)); + } + + return ReflectProperties(type, includeMembers); + } + + /// + /// 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, out TypeMetadataRegistry.TypeMetadata? metadata) && + metadata.Fields.TryGetValue(name, out TypeMetadataRegistry.RegisteredMember? member)) + { + return member.GetValue; + } + + 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, out TypeMetadataRegistry.TypeMetadata? metadata) && + metadata.Properties.TryGetValue(name, out TypeMetadataRegistry.RegisteredMember? member)) + { + return member.GetValue; + } + + PropertyInfo? property = type.GetProperty(name, includeMembers.GetBindingFlags()); + return property is null ? null : subject => property.GetValue(subject); + } + + /// + /// 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. + /// + private static bool TryGetRegistered(Type type, + [NotNullWhen(true)] out TypeMetadataRegistry.TypeMetadata? metadata) + => TypeMetadataRegistry.Instance.TryGet(type, out metadata) && + !(metadata.Fields.IsEmpty && metadata.Properties.IsEmpty); + + 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(); + + 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/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/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/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..b8b0ff8084 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,29 @@ 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 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] [AutoData] public async Task Generic_For_IgnoringMember_ShouldSetOptionForType(string memberToIgnore) @@ -139,6 +140,29 @@ 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 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] [InlineData(IncludeMembers.None)] [InlineData(IncludeMembers.Internal)] 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)] 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..77cfa7e06d --- /dev/null +++ b/Tests/aweXpect.Tests/Objects/ThatObject.IsEquivalentTo.MetadataTests.cs @@ -0,0 +1,218 @@ +using System; +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 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() + { + 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_ShouldReflectOverThem() + { + 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("*Property Secret differed:*").AsWildcard() + .Because("the registry only holds public members, so the non-public ones are still reflected over"); + } + + [Fact] + public async Task WhenRegisteredWithProbe_ShouldCompareAnonymousTypes() + { + var probe = new + { + MetadataProbeTitle = default(string), + }; + TypeMetadataRegistry.RegisterProperty(probe, "MetadataProbeTitle", x => x.MetadataProbeTitle); + var subject = new + { + MetadataProbeTitle = "foo", + }; + var expected = new + { + MetadataProbeTitle = "bar", + }; + + async Task Act() + => await That(subject).IsEquivalentTo(expected); + + await That(Act).Throws() + .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() + => 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; } + } + + private sealed class RegisteredWithSecret(int secret) + { + public int Registered { get; set; } + private int Secret { get; } = secret; + } + + private sealed class WithEvent + { + public event EventHandler? Changed; + public int Number { get; set; } + public void Raise() => Changed?.Invoke(this, EventArgs.Empty); + } + } + } +} 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(); }