-
-
Notifications
You must be signed in to change notification settings - Fork 540
/
SelfReferenceEquivalencyAssertionOptions.cs
846 lines (720 loc) · 30.1 KB
/
SelfReferenceEquivalencyAssertionOptions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using FluentAssertions.Common;
using FluentAssertions.Equivalency.Matching;
using FluentAssertions.Equivalency.Ordering;
using FluentAssertions.Equivalency.Selection;
using FluentAssertions.Equivalency.Steps;
using FluentAssertions.Equivalency.Tracing;
namespace FluentAssertions.Equivalency
{
/// <summary>
/// Represents the run-time behavior of a structural equivalency assertion.
/// </summary>
public abstract class SelfReferenceEquivalencyAssertionOptions<TSelf> : IEquivalencyAssertionOptions
where TSelf : SelfReferenceEquivalencyAssertionOptions<TSelf>
{
#region Private Definitions
// REFACTOR: group the next three fields in a dedicated class
private readonly List<Type> referenceTypes = new();
private readonly List<Type> valueTypes = new();
private readonly Func<Type, EqualityStrategy> getDefaultEqualityStrategy;
private readonly ConcurrentDictionary<Type, EqualityStrategy> equalityStrategyCache = new();
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private readonly List<IMemberSelectionRule> selectionRules = new();
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private readonly List<IMemberMatchingRule> matchingRules = new();
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private readonly List<IEquivalencyStep> userEquivalencySteps = new();
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private CyclicReferenceHandling cyclicReferenceHandling = CyclicReferenceHandling.ThrowException;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
protected OrderingRuleCollection OrderingRules { get; } = new();
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private bool isRecursive;
private bool allowInfiniteRecursion;
private EnumEquivalencyHandling enumEquivalencyHandling;
private bool useRuntimeTyping;
private MemberVisibility includedProperties;
private MemberVisibility includedFields;
private bool compareRecordsByValue;
#endregion
internal SelfReferenceEquivalencyAssertionOptions()
{
AddMatchingRule(new MustMatchByNameRule());
OrderingRules.Add(new ByteArrayOrderingRule());
}
/// <summary>
/// Creates an instance of the equivalency assertions options based on defaults previously configured by the caller.
/// </summary>
protected SelfReferenceEquivalencyAssertionOptions(IEquivalencyAssertionOptions defaults)
{
isRecursive = defaults.IsRecursive;
cyclicReferenceHandling = defaults.CyclicReferenceHandling;
allowInfiniteRecursion = defaults.AllowInfiniteRecursion;
enumEquivalencyHandling = defaults.EnumEquivalencyHandling;
useRuntimeTyping = defaults.UseRuntimeTyping;
includedProperties = defaults.IncludedProperties;
includedFields = defaults.IncludedFields;
compareRecordsByValue = defaults.CompareRecordsByValue;
ConversionSelector = defaults.ConversionSelector.Clone();
selectionRules.AddRange(defaults.SelectionRules);
userEquivalencySteps.AddRange(defaults.UserEquivalencySteps);
matchingRules.AddRange(defaults.MatchingRules);
OrderingRules = new OrderingRuleCollection(defaults.OrderingRules);
getDefaultEqualityStrategy = defaults.GetEqualityStrategy;
TraceWriter = defaults.TraceWriter;
RemoveSelectionRule<AllPropertiesSelectionRule>();
RemoveSelectionRule<AllFieldsSelectionRule>();
}
/// <summary>
/// Gets an ordered collection of selection rules that define what members are included.
/// </summary>
IEnumerable<IMemberSelectionRule> IEquivalencyAssertionOptions.SelectionRules
{
get
{
bool hasConflictingRules = selectionRules.Any(rule => rule.IncludesMembers);
if (includedProperties.HasFlag(MemberVisibility.Public) && !hasConflictingRules)
{
yield return new AllPropertiesSelectionRule();
}
if (includedFields.HasFlag(MemberVisibility.Public) && !hasConflictingRules)
{
yield return new AllFieldsSelectionRule();
}
foreach (IMemberSelectionRule rule in selectionRules)
{
yield return rule;
}
}
}
/// <summary>
/// Gets an ordered collection of matching rules that determine which subject members are matched with which
/// expectation members.
/// </summary>
IEnumerable<IMemberMatchingRule> IEquivalencyAssertionOptions.MatchingRules => matchingRules;
/// <summary>
/// Gets an ordered collection of Equivalency steps how a subject is compared with the expectation.
/// </summary>
IEnumerable<IEquivalencyStep> IEquivalencyAssertionOptions.UserEquivalencySteps => userEquivalencySteps;
public ConversionSelector ConversionSelector { get; } = new();
/// <summary>
/// Gets an ordered collection of rules that determine whether or not the order of collections is important. By
/// default,
/// ordering is irrelevant.
/// </summary>
OrderingRuleCollection IEquivalencyAssertionOptions.OrderingRules => OrderingRules;
/// <summary>
/// Gets value indicating whether the equality check will include nested collections and complex types.
/// </summary>
bool IEquivalencyAssertionOptions.IsRecursive => isRecursive;
bool IEquivalencyAssertionOptions.AllowInfiniteRecursion => allowInfiniteRecursion;
/// <summary>
/// Gets value indicating how cyclic references should be handled. By default, it will throw an exception.
/// </summary>
CyclicReferenceHandling IEquivalencyAssertionOptions.CyclicReferenceHandling => cyclicReferenceHandling;
EnumEquivalencyHandling IEquivalencyAssertionOptions.EnumEquivalencyHandling => enumEquivalencyHandling;
bool IEquivalencyAssertionOptions.UseRuntimeTyping => useRuntimeTyping;
MemberVisibility IEquivalencyAssertionOptions.IncludedProperties => includedProperties;
MemberVisibility IEquivalencyAssertionOptions.IncludedFields => includedFields;
public bool CompareRecordsByValue => compareRecordsByValue;
EqualityStrategy IEquivalencyAssertionOptions.GetEqualityStrategy(Type requestedType)
{
// As the valueFactory parameter captures instance members,
// be aware if the cache must be cleared on mutating the members.
return equalityStrategyCache.GetOrAdd(requestedType, type =>
{
EqualityStrategy strategy;
if (!type.IsPrimitive && referenceTypes.Count > 0 && referenceTypes.Any(t => type.IsSameOrInherits(t)))
{
strategy = EqualityStrategy.ForceMembers;
}
else if (valueTypes.Count > 0 && valueTypes.Any(t => type.IsSameOrInherits(t)))
{
strategy = EqualityStrategy.ForceEquals;
}
else if (!type.IsPrimitive && referenceTypes.Count > 0 && referenceTypes.Any(t => type.IsAssignableToOpenGeneric(t)))
{
strategy = EqualityStrategy.ForceMembers;
}
else if (valueTypes.Count > 0 && valueTypes.Any(t => type.IsAssignableToOpenGeneric(t)))
{
strategy = EqualityStrategy.ForceEquals;
}
else if (type.IsRecord())
{
strategy = compareRecordsByValue ? EqualityStrategy.ForceEquals : EqualityStrategy.ForceMembers;
}
else
{
if (getDefaultEqualityStrategy is not null)
{
strategy = getDefaultEqualityStrategy(type);
}
else
{
strategy = type.HasValueSemantics() ? EqualityStrategy.Equals : EqualityStrategy.Members;
}
}
return strategy;
});
}
public ITraceWriter TraceWriter { get; private set; }
/// <summary>
/// Causes inclusion of only public properties of the subject as far as they are defined on the declared type.
/// </summary>
/// <remarks>
/// This clears all previously registered selection rules.
/// </remarks>
public TSelf IncludingAllDeclaredProperties()
{
RespectingDeclaredTypes();
ExcludingFields();
IncludingProperties();
WithoutSelectionRules();
return (TSelf)this;
}
/// <summary>
/// Causes inclusion of only public properties of the subject based on its run-time type rather than its declared type.
/// </summary>
/// <remarks>
/// This clears all previously registered selection rules.
/// </remarks>
public TSelf IncludingAllRuntimeProperties()
{
RespectingRuntimeTypes();
ExcludingFields();
IncludingProperties();
WithoutSelectionRules();
return (TSelf)this;
}
/// <summary>
/// Instructs the comparison to include public fields.
/// </summary>
/// <remarks>
/// This is part of the default behavior.
/// </remarks>
public TSelf IncludingFields()
{
includedFields = MemberVisibility.Public;
return (TSelf)this;
}
/// <summary>
/// Instructs the comparison to include public and internal fields.
/// </summary>
public TSelf IncludingInternalFields()
{
includedFields = MemberVisibility.Public | MemberVisibility.Internal;
return (TSelf)this;
}
/// <summary>
/// Instructs the comparison to exclude fields.
/// </summary>
/// <remarks>
/// This does not preclude use of `Including`.
/// </remarks>
public TSelf ExcludingFields()
{
includedFields = MemberVisibility.None;
return (TSelf)this;
}
/// <summary>
/// Instructs the comparison to include public properties.
/// </summary>
/// <remarks>
/// This is part of the default behavior.
/// </remarks>
public TSelf IncludingProperties()
{
includedProperties = MemberVisibility.Public;
return (TSelf)this;
}
/// <summary>
/// Instructs the comparison to include public and internal properties.
/// </summary>
public TSelf IncludingInternalProperties()
{
includedProperties = MemberVisibility.Public | MemberVisibility.Internal;
return (TSelf)this;
}
/// <summary>
/// Instructs the comparison to exclude properties.
/// </summary>
/// <remarks>
/// This does not preclude use of `Including`.
/// </remarks>
public TSelf ExcludingProperties()
{
includedProperties = MemberVisibility.None;
return (TSelf)this;
}
/// <summary>
/// Instructs the comparison to respect the expectation's runtime type.
/// </summary>
public TSelf RespectingRuntimeTypes()
{
useRuntimeTyping = true;
return (TSelf)this;
}
/// <summary>
/// Instructs the comparison to respect the expectation's declared type.
/// </summary>
public TSelf RespectingDeclaredTypes()
{
useRuntimeTyping = false;
return (TSelf)this;
}
/// <summary>
/// Excludes a (nested) property based on a predicate from the structural equality check.
/// </summary>
public TSelf Excluding(Expression<Func<IMemberInfo, bool>> predicate)
{
AddSelectionRule(new ExcludeMemberByPredicateSelectionRule(predicate));
return (TSelf)this;
}
/// <summary>
/// Includes the specified member in the equality check.
/// </summary>
/// <remarks>
/// This overrides the default behavior of including all declared members.
/// </remarks>
public TSelf Including(Expression<Func<IMemberInfo, bool>> predicate)
{
AddSelectionRule(new IncludeMemberByPredicateSelectionRule(predicate));
return (TSelf)this;
}
/// <summary>
/// Tries to match the members of the subject with equally named members on the expectation. Ignores those
/// members that don't exist on the expectation and previously registered matching rules.
/// </summary>
public TSelf ExcludingMissingMembers()
{
ClearMatchingRules();
matchingRules.Add(new TryMatchByNameRule());
return (TSelf)this;
}
/// <summary>
/// Requires the subject to have members which are equally named to members on the expectation.
/// </summary>
public TSelf ThrowingOnMissingMembers()
{
ClearMatchingRules();
matchingRules.Add(new MustMatchByNameRule());
return (TSelf)this;
}
/// <summary>
/// Overrides the comparison of subject and expectation to use provided <paramref name="action"/>
/// when the predicate is met.
/// </summary>
/// <param name="action">
/// The assertion to execute when the predicate is met.
/// </param>
public Restriction<TProperty> Using<TProperty>(Action<IAssertionContext<TProperty>> action)
{
return new Restriction<TProperty>((TSelf)this, action);
}
/// <summary>
/// Causes the structural equality check to include nested collections and complex types.
/// </summary>
public TSelf IncludingNestedObjects()
{
isRecursive = true;
return (TSelf)this;
}
/// <summary>
/// Causes the structural equality check to exclude nested collections and complex types.
/// </summary>
/// <remarks>
/// Behaves similarly to the old property assertions API.
/// </remarks>
public TSelf ExcludingNestedObjects()
{
isRecursive = false;
return (TSelf)this;
}
/// <summary>
/// Causes the structural equality check to ignore any cyclic references.
/// </summary>
/// <remarks>
/// By default, cyclic references within the object graph will cause an exception to be thrown.
/// </remarks>
public TSelf IgnoringCyclicReferences()
{
cyclicReferenceHandling = CyclicReferenceHandling.Ignore;
return (TSelf)this;
}
/// <summary>
/// Disables limitations on recursion depth when the structural equality check is configured to include nested objects
/// </summary>
public TSelf AllowingInfiniteRecursion()
{
allowInfiniteRecursion = true;
return (TSelf)this;
}
/// <summary>
/// Clears all selection rules, including those that were added by default.
/// </summary>
public void WithoutSelectionRules()
{
selectionRules.Clear();
}
/// <summary>
/// Clears all matching rules, including those that were added by default.
/// </summary>
public void WithoutMatchingRules()
{
ClearMatchingRules();
}
/// <summary>
/// Adds a selection rule to the ones already added by default, and which is evaluated after all existing rules.
/// </summary>
public TSelf Using(IMemberSelectionRule selectionRule)
{
return AddSelectionRule(selectionRule);
}
/// <summary>
/// Adds a matching rule to the ones already added by default, and which is evaluated before all existing rules.
/// </summary>
public TSelf Using(IMemberMatchingRule matchingRule)
{
return AddMatchingRule(matchingRule);
}
/// <summary>
/// Adds an ordering rule to the ones already added by default, and which is evaluated after all existing rules.
/// </summary>
public TSelf Using(IOrderingRule orderingRule)
{
return AddOrderingRule(orderingRule);
}
/// <summary>
/// Adds an equivalency step rule to the ones already added by default, and which is evaluated before previous
/// user-registered steps
/// </summary>
public TSelf Using(IEquivalencyStep equivalencyStep)
{
return AddEquivalencyStep(equivalencyStep);
}
/// <summary>
/// Ensures the equivalency comparison will create and use an instance of <typeparamref name="TEqualityComparer"/>
/// that implements <see cref="IEqualityComparer{T}"/>, any time
/// when a property is of type <typeparamref name="T"/>.
/// </summary>
public TSelf Using<T, TEqualityComparer>()
where TEqualityComparer : IEqualityComparer<T>, new()
{
return Using(new TEqualityComparer());
}
/// <summary>
/// Ensures the equivalency comparison will use the specified implementation of <see cref="IEqualityComparer{T}"/>
/// any time when a property is of type <typeparamref name="T"/>.
/// </summary>
public TSelf Using<T>(IEqualityComparer<T> comparer)
{
userEquivalencySteps.Insert(0, new EqualityComparerEquivalencyStep<T>(comparer));
return (TSelf)this;
}
/// <summary>
/// Causes all collections to be compared in the order in which the items appear in the expectation.
/// </summary>
public TSelf WithStrictOrdering()
{
OrderingRules.Clear();
OrderingRules.Add(new MatchAllOrderingRule());
return (TSelf)this;
}
/// <summary>
/// Causes the collection identified by the provided <paramref name="predicate" /> to be compared in the order
/// in which the items appear in the expectation.
/// </summary>
public TSelf WithStrictOrderingFor(Expression<Func<IObjectInfo, bool>> predicate)
{
OrderingRules.Add(new PredicateBasedOrderingRule(predicate));
return (TSelf)this;
}
/// <summary>
/// Causes all collections - except bytes - to be compared ignoring the order in which the items appear in the expectation.
/// </summary>
public TSelf WithoutStrictOrdering()
{
OrderingRules.Clear();
OrderingRules.Add(new ByteArrayOrderingRule());
return (TSelf)this;
}
/// <summary>
/// Causes the collection identified by the provided <paramref name="predicate" /> to be compared ignoring the order
/// in which the items appear in the expectation.
/// </summary>
public TSelf WithoutStrictOrderingFor(Expression<Func<IObjectInfo, bool>> predicate)
{
OrderingRules.Add(new PredicateBasedOrderingRule(predicate)
{
Invert = true
});
return (TSelf)this;
}
/// <summary>
/// Causes to compare Enum properties using the result of their ToString method.
/// </summary>
/// <remarks>
/// By default, enums are compared by value.
/// </remarks>
public TSelf ComparingEnumsByName()
{
enumEquivalencyHandling = EnumEquivalencyHandling.ByName;
return (TSelf)this;
}
/// <summary>
/// Causes to compare Enum members using their underlying value only.
/// </summary>
/// <remarks>
/// This is the default.
/// </remarks>
public TSelf ComparingEnumsByValue()
{
enumEquivalencyHandling = EnumEquivalencyHandling.ByValue;
return (TSelf)this;
}
/// <summary>
/// Ensures records by default are compared by value instead of their members.
/// </summary>
public TSelf ComparingRecordsByValue()
{
compareRecordsByValue = true;
equalityStrategyCache.Clear();
return (TSelf)this;
}
/// <summary>
/// Ensures records by default are compared by their members even though they override
/// the <see cref="object.Equals(object)" /> method.
/// </summary>
/// <remarks>
/// This is the default.
/// </remarks>
public TSelf ComparingRecordsByMembers()
{
compareRecordsByValue = false;
equalityStrategyCache.Clear();
return (TSelf)this;
}
/// <summary>
/// Marks the <typeparamref name="T" /> as a type that should be compared by its members even though it may override
/// the <see cref="object.Equals(object)" /> method.
/// </summary>
public TSelf ComparingByMembers<T>() => ComparingByMembers(typeof(T));
/// <summary>
/// Marks <paramref name="type" /> as a type that should be compared by its members even though it may override
/// the <see cref="object.Equals(object)" /> method.
/// </summary>
public TSelf ComparingByMembers(Type type)
{
Guard.ThrowIfArgumentIsNull(type, nameof(type));
if (type.IsPrimitive)
{
throw new InvalidOperationException($"Cannot compare a primitive type such as {type.Name} by its members");
}
if (valueTypes.Any(t => type.IsSameOrInherits(t)))
{
throw new InvalidOperationException(
$"Can't compare {type.Name} by its members if it already setup to be compared by value");
}
referenceTypes.Add(type);
equalityStrategyCache.Clear();
return (TSelf)this;
}
/// <summary>
/// Marks the <typeparamref name="T" /> as a value type which must be compared using its
/// <see cref="object.Equals(object)" /> method, regardless of it overriding it or not.
/// </summary>
public TSelf ComparingByValue<T>() => ComparingByValue(typeof(T));
/// <summary>
/// Marks <paramref name="type" /> as a value type which must be compared using its
/// <see cref="object.Equals(object)" /> method, regardless of it overriding it or not.
/// </summary>
public TSelf ComparingByValue(Type type)
{
Guard.ThrowIfArgumentIsNull(type, nameof(type));
if (referenceTypes.Any(t => type.IsSameOrInherits(t)))
{
throw new InvalidOperationException(
$"Can't compare {type.Name} by value if it already setup to be compared by its members");
}
valueTypes.Add(type);
equalityStrategyCache.Clear();
return (TSelf)this;
}
/// <summary>
/// Enables tracing the steps the equivalency validation followed to compare two graphs.
/// </summary>
public TSelf WithTracing(ITraceWriter writer = null)
{
TraceWriter = writer ?? new StringBuilderTraceWriter();
return (TSelf)this;
}
/// <summary>
/// Instructs the equivalency comparison to try to convert the values of
/// matching properties before running any of the other steps.
/// </summary>
public TSelf WithAutoConversion()
{
ConversionSelector.IncludeAll();
return (TSelf)this;
}
/// <summary>
/// Instructs the equivalency comparison to try to convert the value of
/// a specific member on the expectation object before running any of the other steps.
/// </summary>
public TSelf WithAutoConversionFor(Expression<Func<IObjectInfo, bool>> predicate)
{
ConversionSelector.Include(predicate);
return (TSelf)this;
}
/// <summary>
/// Instructs the equivalency comparison to prevent trying to convert the value of
/// a specific member on the expectation object before running any of the other steps.
/// </summary>
public TSelf WithoutAutoConversionFor(Expression<Func<IObjectInfo, bool>> predicate)
{
ConversionSelector.Exclude(predicate);
return (TSelf)this;
}
/// <summary>
/// Returns a string that represents the current object.
/// </summary>
/// <returns>
/// A string that represents the current object.
/// </returns>
/// <filterpriority>2</filterpriority>
public override string ToString()
{
var builder = new StringBuilder();
builder.Append("- Use ")
.Append(useRuntimeTyping ? "runtime" : "declared")
.AppendLine(" types and members");
if (isRecursive)
{
if (allowInfiniteRecursion)
{
builder.AppendLine("- Recurse indefinitely");
}
}
builder.AppendFormat(CultureInfo.InvariantCulture,
"- Compare enums by {0}" + Environment.NewLine,
enumEquivalencyHandling == EnumEquivalencyHandling.ByName ? "name" : "value");
if (cyclicReferenceHandling == CyclicReferenceHandling.Ignore)
{
builder.AppendLine("- Ignoring cyclic references");
}
builder.AppendLine($"- Compare tuples by their properties");
builder.AppendLine($"- Compare anonymous types by their properties");
if (compareRecordsByValue)
{
builder.AppendLine("- Compare records by value");
}
else
{
builder.AppendLine("- Compare records by their members");
}
foreach (Type valueType in valueTypes)
{
builder.AppendLine($"- Compare {valueType} by value");
}
foreach (Type type in referenceTypes)
{
builder.AppendLine($"- Compare {type} by its members");
}
foreach (IMemberSelectionRule rule in selectionRules)
{
builder.Append("- ").AppendLine(rule.ToString());
}
foreach (IMemberMatchingRule rule in matchingRules)
{
builder.Append("- ").AppendLine(rule.ToString());
}
foreach (IEquivalencyStep step in userEquivalencySteps)
{
builder.Append("- ").AppendLine(step.ToString());
}
foreach (IOrderingRule rule in OrderingRules)
{
builder.Append("- ").AppendLine(rule.ToString());
}
builder.Append("- ").AppendLine(ConversionSelector.ToString());
return builder.ToString();
}
/// <summary>
/// Defines additional overrides when used with <see cref="SelfReferenceEquivalencyAssertionOptions{T}" />
/// </summary>
public class Restriction<TMember>
{
private readonly Action<IAssertionContext<TMember>> action;
private readonly TSelf options;
public Restriction(TSelf options, Action<IAssertionContext<TMember>> action)
{
this.options = options;
this.action = action;
}
/// <summary>
/// Allows overriding the way structural equality is applied to (nested) objects of type
/// <typeparamref name="TMemberType" />
/// </summary>
public TSelf WhenTypeIs<TMemberType>()
where TMemberType : TMember
{
When(info => info.RuntimeType.IsSameOrInherits(typeof(TMemberType)));
return options;
}
/// <summary>
/// Allows overriding the way structural equality is applied to particular members.
/// </summary>
/// <param name="predicate">
/// A predicate based on the <see cref="IMemberInfo" /> of the subject that is used to identify the property for which
/// the
/// override applies.
/// </param>
public TSelf When(Expression<Func<IObjectInfo, bool>> predicate)
{
options.userEquivalencySteps.Insert(0,
new AssertionRuleEquivalencyStep<TMember>(predicate, action));
return options;
}
}
#region Non-fluent API
private void RemoveSelectionRule<T>()
where T : IMemberSelectionRule
{
selectionRules.RemoveAll(selectionRule => selectionRule is T);
}
private void ClearMatchingRules()
{
matchingRules.Clear();
}
protected TSelf AddSelectionRule(IMemberSelectionRule selectionRule)
{
selectionRules.Add(selectionRule);
return (TSelf)this;
}
protected TSelf AddMatchingRule(IMemberMatchingRule matchingRule)
{
matchingRules.Insert(0, matchingRule);
return (TSelf)this;
}
private TSelf AddOrderingRule(IOrderingRule orderingRule)
{
OrderingRules.Add(orderingRule);
return (TSelf)this;
}
private TSelf AddEquivalencyStep(IEquivalencyStep equivalencyStep)
{
userEquivalencySteps.Add(equivalencyStep);
return (TSelf)this;
}
#endregion
}
}