diff --git a/Build/_build.csproj.DotSettings b/Build/_build.csproj.DotSettings index 9aac7d8e8d..7348ae5acb 100644 --- a/Build/_build.csproj.DotSettings +++ b/Build/_build.csproj.DotSettings @@ -13,6 +13,8 @@ False <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /> <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /> + <Policy><Descriptor Staticness="Instance" AccessRightKinds="Private" Description="Instance fields (private)"><ElementKinds><Kind Name="FIELD" /><Kind Name="READONLY_FIELD" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /></Policy> + <Policy><Descriptor Staticness="Static" AccessRightKinds="Private" Description="Static fields (private)"><ElementKinds><Kind Name="FIELD" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /></Policy> True True True @@ -21,4 +23,5 @@ True True True - True + True + True diff --git a/FluentAssertions.sln.DotSettings b/FluentAssertions.sln.DotSettings index 318b42ebc7..785299fbe3 100644 --- a/FluentAssertions.sln.DotSettings +++ b/FluentAssertions.sln.DotSettings @@ -104,6 +104,8 @@ UseExplicitType <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> + <Policy><Descriptor Staticness="Instance" AccessRightKinds="Private" Description="Instance fields (private)"><ElementKinds><Kind Name="FIELD" /><Kind Name="READONLY_FIELD" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /></Policy> + <Policy><Descriptor Staticness="Static" AccessRightKinds="Private" Description="Static fields (private)"><ElementKinds><Kind Name="FIELD" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /></Policy> <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /> @@ -154,6 +156,7 @@ True True True + True D:\Workspaces\FluentAssertions\Default.testsettings 4 False diff --git a/Src/FluentAssertions/AndWhich.cs b/Src/FluentAssertions/AndWhich.cs index 0ef993bc02..0e0e2d30ce 100644 --- a/Src/FluentAssertions/AndWhich.cs +++ b/Src/FluentAssertions/AndWhich.cs @@ -9,16 +9,16 @@ namespace FluentAssertions; public class AndWhich : AndConstraint { - private readonly Assertion assertion; + private readonly AssertionChain assertionChain; private readonly string pathPostfix; private readonly Lazy getSubject; - public AndWhich(TParent parent, TSubject subject, Assertion assertion, string pathPostfix) + public AndWhich(TParent parent, TSubject subject, AssertionChain assertionChain, string pathPostfix) : base(parent) { getSubject = new Lazy(() => subject); - this.assertion = assertion; + this.assertionChain = assertionChain; this.pathPostfix = pathPostfix; } @@ -43,9 +43,9 @@ public TSubject Which { get { - assertion.AddCallerPostfix(pathPostfix); + assertionChain.AddCallerPostfix(pathPostfix); - Assertion.ReuseOnce(assertion); + AssertionChain.ReuseOnce(assertionChain); return getSubject.Value; } diff --git a/Src/FluentAssertions/AssertionExtensions.cs b/Src/FluentAssertions/AssertionExtensions.cs index 1e17c0ec97..6fddf39bbe 100644 --- a/Src/FluentAssertions/AssertionExtensions.cs +++ b/Src/FluentAssertions/AssertionExtensions.cs @@ -1,7 +1,6 @@ using System; using System.Collections; using System.Collections.Generic; -using System.Data; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; @@ -167,8 +166,7 @@ public static ExecutionTime ExecutionTime(this Func action) [Pure] public static ExecutionTimeAssertions Should(this ExecutionTime executionTime) { - return new ExecutionTimeAssertions(executionTime, Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + return new ExecutionTimeAssertions(executionTime, AssertionChain.GetOrCreate()); } /// @@ -178,8 +176,7 @@ public static ExecutionTimeAssertions Should(this ExecutionTime executionTime) [Pure] public static AssemblyAssertions Should(this Assembly assembly) { - return new AssemblyAssertions(assembly, Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + return new AssemblyAssertions(assembly, AssertionChain.GetOrCreate()); } /// @@ -189,8 +186,7 @@ public static AssemblyAssertions Should(this Assembly assembly) [Pure] public static XDocumentAssertions Should(this XDocument actualValue) { - return new XDocumentAssertions(actualValue, Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + return new XDocumentAssertions(actualValue, AssertionChain.GetOrCreate()); } /// @@ -200,8 +196,7 @@ public static XDocumentAssertions Should(this XDocument actualValue) [Pure] public static XElementAssertions Should(this XElement actualValue) { - return new XElementAssertions(actualValue, Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + return new XElementAssertions(actualValue, AssertionChain.GetOrCreate()); } /// @@ -211,8 +206,7 @@ public static XElementAssertions Should(this XElement actualValue) [Pure] public static XAttributeAssertions Should(this XAttribute actualValue) { - return new XAttributeAssertions(actualValue, Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + return new XAttributeAssertions(actualValue, AssertionChain.GetOrCreate()); } /// @@ -222,8 +216,7 @@ public static XAttributeAssertions Should(this XAttribute actualValue) [Pure] public static StreamAssertions Should(this Stream actualValue) { - return new StreamAssertions(actualValue, Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + return new StreamAssertions(actualValue, AssertionChain.GetOrCreate()); } /// @@ -233,8 +226,7 @@ public static StreamAssertions Should(this Stream actualValue) [Pure] public static BufferedStreamAssertions Should(this BufferedStream actualValue) { - return new BufferedStreamAssertions(actualValue, Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + return new BufferedStreamAssertions(actualValue, AssertionChain.GetOrCreate()); } /// @@ -291,14 +283,12 @@ private static void ForceEnumeration(T subject, Func enumerab [Pure] public static ObjectAssertions Should(this object actualValue) { - return new ObjectAssertions(actualValue, Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + return new ObjectAssertions(actualValue, AssertionChain.GetOrCreate()); } public static ObjectAssertions Should(this WhichResult tuple) { - return new ObjectAssertions(tuple.MatchedElement, Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + return new ObjectAssertions(tuple.MatchedElement, AssertionChain.GetOrCreate()); } /// @@ -308,8 +298,7 @@ public static ObjectAssertions Should(this WhichResult tuple) [Pure] public static BooleanAssertions Should(this bool actualValue) { - return new BooleanAssertions(actualValue, Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + return new BooleanAssertions(actualValue, AssertionChain.GetOrCreate()); } /// @@ -319,8 +308,7 @@ public static BooleanAssertions Should(this bool actualValue) [Pure] public static NullableBooleanAssertions Should(this bool? actualValue) { - return new NullableBooleanAssertions(actualValue, Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + return new NullableBooleanAssertions(actualValue, AssertionChain.GetOrCreate()); } /// @@ -330,8 +318,7 @@ public static NullableBooleanAssertions Should(this bool? actualValue) [Pure] public static HttpResponseMessageAssertions Should(this HttpResponseMessage actualValue) { - return new HttpResponseMessageAssertions(actualValue, Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + return new HttpResponseMessageAssertions(actualValue, AssertionChain.GetOrCreate()); } /// @@ -341,8 +328,7 @@ public static HttpResponseMessageAssertions Should(this HttpResponseMessage actu [Pure] public static GuidAssertions Should(this Guid actualValue) { - return new GuidAssertions(actualValue, Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + return new GuidAssertions(actualValue, AssertionChain.GetOrCreate()); } /// @@ -352,8 +338,7 @@ public static GuidAssertions Should(this Guid actualValue) [Pure] public static NullableGuidAssertions Should(this Guid? actualValue) { - return new NullableGuidAssertions(actualValue, Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + return new NullableGuidAssertions(actualValue, AssertionChain.GetOrCreate()); } /// @@ -363,7 +348,7 @@ public static NullableGuidAssertions Should(this Guid? actualValue) [Pure] public static GenericCollectionAssertions Should(this IEnumerable actualValue) { - return new GenericCollectionAssertions(actualValue, Assertion.GetOrCreate(() => AssertionScope.Current, () => AssertionScope.Current.GetIdentifier())); + return new GenericCollectionAssertions(actualValue, AssertionChain.GetOrCreate()); } /// @@ -373,7 +358,7 @@ public static GenericCollectionAssertions Should(this IEnumerable actua [Pure] public static StringCollectionAssertions Should(this IEnumerable @this) { - return new StringCollectionAssertions(@this, Assertion.GetOrCreate(() => AssertionScope.Current, () => AssertionScope.Current.GetIdentifier())); + return new StringCollectionAssertions(@this, AssertionChain.GetOrCreate()); } /// @@ -384,8 +369,7 @@ public static StringCollectionAssertions Should(this IEnumerable @this) public static GenericDictionaryAssertions, TKey, TValue> Should( this IDictionary actualValue) { - return new GenericDictionaryAssertions, TKey, TValue>(actualValue, Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + return new GenericDictionaryAssertions, TKey, TValue>(actualValue, AssertionChain.GetOrCreate()); } /// @@ -397,8 +381,7 @@ public static StringCollectionAssertions Should(this IEnumerable @this) this IEnumerable> actualValue) { return new GenericDictionaryAssertions>, TKey, TValue>(actualValue, - Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + AssertionChain.GetOrCreate()); } /// @@ -410,8 +393,7 @@ public static StringCollectionAssertions Should(this IEnumerable @this) this TCollection actualValue) where TCollection : IEnumerable> { - return new GenericDictionaryAssertions(actualValue, Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + return new GenericDictionaryAssertions(actualValue, AssertionChain.GetOrCreate()); } /// @@ -421,8 +403,7 @@ public static StringCollectionAssertions Should(this IEnumerable @this) [Pure] public static DateTimeAssertions Should(this DateTime actualValue) { - return new DateTimeAssertions(actualValue, Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + return new DateTimeAssertions(actualValue, AssertionChain.GetOrCreate()); } /// @@ -432,8 +413,7 @@ public static DateTimeAssertions Should(this DateTime actualValue) [Pure] public static DateTimeOffsetAssertions Should(this DateTimeOffset actualValue) { - return new DateTimeOffsetAssertions(actualValue, Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + return new DateTimeOffsetAssertions(actualValue, AssertionChain.GetOrCreate()); } /// @@ -443,8 +423,7 @@ public static DateTimeOffsetAssertions Should(this DateTimeOffset actualValue) [Pure] public static NullableDateTimeAssertions Should(this DateTime? actualValue) { - return new NullableDateTimeAssertions(actualValue, Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + return new NullableDateTimeAssertions(actualValue, AssertionChain.GetOrCreate()); } /// @@ -454,8 +433,7 @@ public static NullableDateTimeAssertions Should(this DateTime? actualValue) [Pure] public static NullableDateTimeOffsetAssertions Should(this DateTimeOffset? actualValue) { - return new NullableDateTimeOffsetAssertions(actualValue, Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + return new NullableDateTimeOffsetAssertions(actualValue, AssertionChain.GetOrCreate()); } #if NET6_0_OR_GREATER @@ -466,8 +444,7 @@ public static NullableDateTimeOffsetAssertions Should(this DateTimeOffset? actua [Pure] public static DateOnlyAssertions Should(this DateOnly actualValue) { - return new DateOnlyAssertions(actualValue, Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + return new DateOnlyAssertions(actualValue, AssertionChain.GetOrCreate()); } /// @@ -477,8 +454,7 @@ public static DateOnlyAssertions Should(this DateOnly actualValue) [Pure] public static NullableDateOnlyAssertions Should(this DateOnly? actualValue) { - return new NullableDateOnlyAssertions(actualValue, Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + return new NullableDateOnlyAssertions(actualValue, AssertionChain.GetOrCreate()); } /// @@ -488,8 +464,7 @@ public static NullableDateOnlyAssertions Should(this DateOnly? actualValue) [Pure] public static TimeOnlyAssertions Should(this TimeOnly actualValue) { - return new TimeOnlyAssertions(actualValue, Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + return new TimeOnlyAssertions(actualValue, AssertionChain.GetOrCreate()); } /// @@ -499,8 +474,7 @@ public static TimeOnlyAssertions Should(this TimeOnly actualValue) [Pure] public static NullableTimeOnlyAssertions Should(this TimeOnly? actualValue) { - return new NullableTimeOnlyAssertions(actualValue, Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + return new NullableTimeOnlyAssertions(actualValue, AssertionChain.GetOrCreate()); } #endif @@ -512,8 +486,7 @@ public static NullableTimeOnlyAssertions Should(this TimeOnly? actualValue) [Pure] public static ComparableTypeAssertions Should(this IComparable comparableValue) { - return new ComparableTypeAssertions(comparableValue, Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + return new ComparableTypeAssertions(comparableValue, AssertionChain.GetOrCreate()); } /// @@ -523,8 +496,7 @@ public static ComparableTypeAssertions Should(this IComparable comparab [Pure] public static ComparableTypeAssertions Should(this WhichResult> tuple) { - return new ComparableTypeAssertions(tuple.MatchedElement, Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + return new ComparableTypeAssertions(tuple.MatchedElement, AssertionChain.GetOrCreate()); } /// @@ -534,8 +506,7 @@ public static ComparableTypeAssertions Should(this WhichResult Should(this int actualValue) { - return new Int32Assertions(actualValue, Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + return new Int32Assertions(actualValue, AssertionChain.GetOrCreate()); } /// @@ -545,8 +516,7 @@ public static NumericAssertions Should(this int actualValue) [Pure] public static NumericAssertions Should(this WhichResult actualValue) { - return new Int32Assertions(actualValue.MatchedElement, Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + return new Int32Assertions(actualValue.MatchedElement, AssertionChain.GetOrCreate()); } /// @@ -556,8 +526,7 @@ public static NumericAssertions Should(this WhichResult actualValue) [Pure] public static NullableNumericAssertions Should(this int? actualValue) { - return new NullableInt32Assertions(actualValue, Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + return new NullableInt32Assertions(actualValue, AssertionChain.GetOrCreate()); } /// @@ -567,8 +536,7 @@ public static NullableNumericAssertions Should(this int? actualValue) [Pure] public static NumericAssertions Should(this uint actualValue) { - return new UInt32Assertions(actualValue, Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + return new UInt32Assertions(actualValue, AssertionChain.GetOrCreate()); } /// @@ -578,8 +546,7 @@ public static NumericAssertions Should(this uint actualValue) [Pure] public static NullableNumericAssertions Should(this uint? actualValue) { - return new NullableUInt32Assertions(actualValue, Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + return new NullableUInt32Assertions(actualValue, AssertionChain.GetOrCreate()); } /// @@ -589,8 +556,7 @@ public static NullableNumericAssertions Should(this uint? actualValue) [Pure] public static NumericAssertions Should(this decimal actualValue) { - return new DecimalAssertions(actualValue, Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + return new DecimalAssertions(actualValue, AssertionChain.GetOrCreate()); } /// @@ -600,8 +566,7 @@ public static NumericAssertions Should(this decimal actualValue) [Pure] public static NullableNumericAssertions Should(this decimal? actualValue) { - return new NullableDecimalAssertions(actualValue, Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + return new NullableDecimalAssertions(actualValue, AssertionChain.GetOrCreate()); } /// @@ -611,8 +576,7 @@ public static NullableNumericAssertions Should(this decimal? actualValu [Pure] public static NumericAssertions Should(this byte actualValue) { - return new ByteAssertions(actualValue, Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + return new ByteAssertions(actualValue, AssertionChain.GetOrCreate()); } /// @@ -622,8 +586,7 @@ public static NumericAssertions Should(this byte actualValue) [Pure] public static NullableNumericAssertions Should(this byte? actualValue) { - return new NullableByteAssertions(actualValue, Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + return new NullableByteAssertions(actualValue, AssertionChain.GetOrCreate()); } /// @@ -633,8 +596,7 @@ public static NullableNumericAssertions Should(this byte? actualValue) [Pure] public static NumericAssertions Should(this sbyte actualValue) { - return new SByteAssertions(actualValue, Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + return new SByteAssertions(actualValue, AssertionChain.GetOrCreate()); } /// @@ -644,8 +606,7 @@ public static NumericAssertions Should(this sbyte actualValue) [Pure] public static NullableNumericAssertions Should(this sbyte? actualValue) { - return new NullableSByteAssertions(actualValue, Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + return new NullableSByteAssertions(actualValue, AssertionChain.GetOrCreate()); } /// @@ -655,8 +616,7 @@ public static NullableNumericAssertions Should(this sbyte? actualValue) [Pure] public static NumericAssertions Should(this short actualValue) { - return new Int16Assertions(actualValue, Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + return new Int16Assertions(actualValue, AssertionChain.GetOrCreate()); } /// @@ -666,8 +626,7 @@ public static NumericAssertions Should(this short actualValue) [Pure] public static NullableNumericAssertions Should(this short? actualValue) { - return new NullableInt16Assertions(actualValue, Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + return new NullableInt16Assertions(actualValue, AssertionChain.GetOrCreate()); } /// @@ -677,8 +636,7 @@ public static NullableNumericAssertions Should(this short? actualValue) [Pure] public static NumericAssertions Should(this ushort actualValue) { - return new UInt16Assertions(actualValue, Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + return new UInt16Assertions(actualValue, AssertionChain.GetOrCreate()); } /// @@ -688,8 +646,7 @@ public static NumericAssertions Should(this ushort actualValue) [Pure] public static NullableNumericAssertions Should(this ushort? actualValue) { - return new NullableUInt16Assertions(actualValue, Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + return new NullableUInt16Assertions(actualValue, AssertionChain.GetOrCreate()); } /// @@ -699,8 +656,7 @@ public static NullableNumericAssertions Should(this ushort? actualValue) [Pure] public static NumericAssertions Should(this long actualValue) { - return new Int64Assertions(actualValue, Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + return new Int64Assertions(actualValue, AssertionChain.GetOrCreate()); } /// @@ -710,8 +666,7 @@ public static NumericAssertions Should(this long actualValue) [Pure] public static NullableNumericAssertions Should(this long? actualValue) { - return new NullableInt64Assertions(actualValue, Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + return new NullableInt64Assertions(actualValue, AssertionChain.GetOrCreate()); } /// @@ -721,8 +676,7 @@ public static NullableNumericAssertions Should(this long? actualValue) [Pure] public static NumericAssertions Should(this ulong actualValue) { - return new UInt64Assertions(actualValue, Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + return new UInt64Assertions(actualValue, AssertionChain.GetOrCreate()); } /// @@ -732,8 +686,7 @@ public static NumericAssertions Should(this ulong actualValue) [Pure] public static NullableNumericAssertions Should(this ulong? actualValue) { - return new NullableUInt64Assertions(actualValue, Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + return new NullableUInt64Assertions(actualValue, AssertionChain.GetOrCreate()); } /// @@ -743,8 +696,7 @@ public static NullableNumericAssertions Should(this ulong? actualValue) [Pure] public static NumericAssertions Should(this float actualValue) { - return new SingleAssertions(actualValue, Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + return new SingleAssertions(actualValue, AssertionChain.GetOrCreate()); } /// @@ -754,8 +706,7 @@ public static NumericAssertions Should(this float actualValue) [Pure] public static NullableNumericAssertions Should(this float? actualValue) { - return new NullableSingleAssertions(actualValue, Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + return new NullableSingleAssertions(actualValue, AssertionChain.GetOrCreate()); } /// @@ -765,8 +716,7 @@ public static NullableNumericAssertions Should(this float? actualValue) [Pure] public static NumericAssertions Should(this double actualValue) { - return new DoubleAssertions(actualValue, Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + return new DoubleAssertions(actualValue, AssertionChain.GetOrCreate()); } /// @@ -776,8 +726,7 @@ public static NumericAssertions Should(this double actualValue) [Pure] public static NullableNumericAssertions Should(this double? actualValue) { - return new NullableDoubleAssertions(actualValue, Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + return new NullableDoubleAssertions(actualValue, AssertionChain.GetOrCreate()); } /// @@ -788,7 +737,7 @@ public static NullableNumericAssertions Should(this double? actualValue) public static StringAssertions Should(this string actualValue) { return new StringAssertions(actualValue, - Assertion.GetOrCreate(() => AssertionScope.Current, () => AssertionScope.Current.GetIdentifier())); + AssertionChain.GetOrCreate()); } /// @@ -798,8 +747,7 @@ public static StringAssertions Should(this string actualValue) [Pure] public static SimpleTimeSpanAssertions Should(this TimeSpan actualValue) { - return new SimpleTimeSpanAssertions(actualValue, Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + return new SimpleTimeSpanAssertions(actualValue, AssertionChain.GetOrCreate()); } /// @@ -809,8 +757,7 @@ public static SimpleTimeSpanAssertions Should(this TimeSpan actualValue) [Pure] public static NullableSimpleTimeSpanAssertions Should(this TimeSpan? actualValue) { - return new NullableSimpleTimeSpanAssertions(actualValue, Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + return new NullableSimpleTimeSpanAssertions(actualValue, AssertionChain.GetOrCreate()); } /// @@ -820,8 +767,7 @@ public static NullableSimpleTimeSpanAssertions Should(this TimeSpan? actualValue [Pure] public static TypeAssertions Should(this Type subject) { - return new TypeAssertions(subject, Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + return new TypeAssertions(subject, AssertionChain.GetOrCreate()); } /// @@ -834,8 +780,7 @@ public static TypeSelectorAssertions Should(this TypeSelector typeSelector) { Guard.ThrowIfArgumentIsNull(typeSelector); - return new TypeSelectorAssertions(Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier()), typeSelector.ToArray()); + return new TypeSelectorAssertions(AssertionChain.GetOrCreate(), typeSelector.ToArray()); } /// @@ -846,8 +791,7 @@ public static TypeSelectorAssertions Should(this TypeSelector typeSelector) [Pure] public static ConstructorInfoAssertions Should(this ConstructorInfo constructorInfo) { - return new ConstructorInfoAssertions(constructorInfo, Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + return new ConstructorInfoAssertions(constructorInfo, AssertionChain.GetOrCreate()); } /// @@ -857,8 +801,7 @@ public static ConstructorInfoAssertions Should(this ConstructorInfo constructorI [Pure] public static MethodInfoAssertions Should(this MethodInfo methodInfo) { - return new MethodInfoAssertions(methodInfo, Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + return new MethodInfoAssertions(methodInfo, AssertionChain.GetOrCreate()); } /// @@ -872,8 +815,7 @@ public static MethodInfoSelectorAssertions Should(this MethodInfoSelector method { Guard.ThrowIfArgumentIsNull(methodSelector); - return new MethodInfoSelectorAssertions(Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier()), methodSelector.ToArray()); + return new MethodInfoSelectorAssertions(AssertionChain.GetOrCreate(), methodSelector.ToArray()); } /// @@ -884,8 +826,7 @@ public static MethodInfoSelectorAssertions Should(this MethodInfoSelector method [Pure] public static PropertyInfoAssertions Should(this PropertyInfo propertyInfo) { - return new PropertyInfoAssertions(propertyInfo, Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + return new PropertyInfoAssertions(propertyInfo, AssertionChain.GetOrCreate()); } /// @@ -899,9 +840,7 @@ public static PropertyInfoSelectorAssertions Should(this PropertyInfoSelector pr { Guard.ThrowIfArgumentIsNull(propertyInfoSelector); - return new PropertyInfoSelectorAssertions(Assertion.GetOrCreate( - () => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier()), propertyInfoSelector.ToArray()); + return new PropertyInfoSelectorAssertions(AssertionChain.GetOrCreate(), propertyInfoSelector.ToArray()); } /// @@ -911,8 +850,7 @@ public static PropertyInfoSelectorAssertions Should(this PropertyInfoSelector pr [Pure] public static ActionAssertions Should(this Action action) { - return new ActionAssertions(action, Extractor, Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + return new ActionAssertions(action, Extractor, AssertionChain.GetOrCreate()); } /// @@ -922,8 +860,7 @@ public static ActionAssertions Should(this Action action) [Pure] public static NonGenericAsyncFunctionAssertions Should(this Func action) { - return new NonGenericAsyncFunctionAssertions(action, Extractor, Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + return new NonGenericAsyncFunctionAssertions(action, Extractor, AssertionChain.GetOrCreate()); } /// @@ -933,8 +870,7 @@ public static NonGenericAsyncFunctionAssertions Should(this Func action) [Pure] public static GenericAsyncFunctionAssertions Should(this Func> action) { - return new GenericAsyncFunctionAssertions(action, Extractor, Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + return new GenericAsyncFunctionAssertions(action, Extractor, AssertionChain.GetOrCreate()); } /// @@ -944,8 +880,7 @@ public static GenericAsyncFunctionAssertions Should(this Func> act [Pure] public static FunctionAssertions Should(this Func func) { - return new FunctionAssertions(func, Extractor, Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + return new FunctionAssertions(func, Extractor, AssertionChain.GetOrCreate()); } /// @@ -955,8 +890,7 @@ public static FunctionAssertions Should(this Func func) [Pure] public static TaskCompletionSourceAssertions Should(this TaskCompletionSource tcs) { - return new TaskCompletionSourceAssertions(tcs, Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + return new TaskCompletionSourceAssertions(tcs, AssertionChain.GetOrCreate()); } #if !NETSTANDARD2_0 @@ -985,7 +919,7 @@ public static IMonitor Monitor(this T eventSource, Func utcNow = [Pure] public static TaskCompletionSourceAssertions Should(this TaskCompletionSource tcs) { - return new TaskCompletionSourceAssertions(tcs, Assertion.GetOrCreate(() => AssertionScope.Current, + return new TaskCompletionSourceAssertions(tcs, AssertionChain.GetOrCreate(() => AssertionScope.Current, () => AssertionScope.Current.GetIdentifier())); } diff --git a/Src/FluentAssertions/Collections/GenericCollectionAssertions.cs b/Src/FluentAssertions/Collections/GenericCollectionAssertions.cs index 0fd02caf80..7e1797575e 100644 --- a/Src/FluentAssertions/Collections/GenericCollectionAssertions.cs +++ b/Src/FluentAssertions/Collections/GenericCollectionAssertions.cs @@ -17,8 +17,8 @@ namespace FluentAssertions.Collections; [DebuggerNonUserCode] public class GenericCollectionAssertions : GenericCollectionAssertions, T, GenericCollectionAssertions> { - public GenericCollectionAssertions(IEnumerable actualValue, Assertion assertion) - : base(actualValue, assertion) + public GenericCollectionAssertions(IEnumerable actualValue, AssertionChain assertionChain) + : base(actualValue, assertionChain) { } } @@ -28,8 +28,8 @@ public class GenericCollectionAssertions : GenericCollectionAssertions> where TCollection : IEnumerable { - public GenericCollectionAssertions(TCollection actualValue, Assertion assertion) - : base(actualValue, assertion) + public GenericCollectionAssertions(TCollection actualValue, AssertionChain assertionChain) + : base(actualValue, assertionChain) { } } @@ -42,12 +42,12 @@ public class GenericCollectionAssertions : Referenc where TCollection : IEnumerable where TAssertions : GenericCollectionAssertions { - private readonly Assertion assertion; + private readonly AssertionChain assertionChain; - public GenericCollectionAssertions(TCollection actualValue, Assertion assertion) - : base(actualValue, assertion) + public GenericCollectionAssertions(TCollection actualValue, AssertionChain assertionChain) + : base(actualValue, assertionChain) { - this.assertion = assertion; + this.assertionChain = assertionChain; } /// @@ -69,7 +69,7 @@ public GenericCollectionAssertions(TCollection actualValue, Assertion assertion) public AndWhichConstraint> AllBeAssignableTo(string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected type to be {0}{reason}, but found {context:the collection} is .", @@ -77,9 +77,9 @@ public GenericCollectionAssertions(TCollection actualValue, Assertion assertion) IEnumerable matches = []; - if (assertion.Succeeded) + if (assertionChain.Succeeded) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected type to be {0}{reason}, ", typeof(TExpectation).FullName) .ForCondition(Subject!.All(x => x is not null)) @@ -110,7 +110,7 @@ public AndConstraint AllBeAssignableTo(Type expectedType, string be { Guard.ThrowIfArgumentIsNull(expectedType); - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected type to be {0}{reason}, ", expectedType.FullName) .Given(() => Subject) @@ -212,7 +212,7 @@ public AndConstraint AllBeAssignableTo(Type expectedType, string be public AndWhichConstraint> AllBeOfType(string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected type to be {0}{reason}, but found {context:collection} is .", @@ -220,9 +220,9 @@ public AndConstraint AllBeAssignableTo(Type expectedType, string be IEnumerable matches = []; - if (assertion.Succeeded) + if (assertionChain.Succeeded) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected type to be {0}{reason}, ", typeof(TExpectation).FullName) .ForCondition(Subject!.All(x => x is not null)) @@ -253,7 +253,7 @@ public AndConstraint AllBeOfType(Type expectedType, string because { Guard.ThrowIfArgumentIsNull(expectedType); - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected type to be {0}{reason}, ", expectedType.FullName) .Given(() => Subject) @@ -282,7 +282,7 @@ public AndConstraint AllBeOfType(Type expectedType, string because public AndConstraint BeEmpty(string because = "", params object[] becauseArgs) { var singleItemArray = Subject?.Take(1).ToArray(); - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected {context:collection} to be empty{reason}, ") .Given(() => singleItemArray) @@ -636,7 +636,7 @@ public AndConstraint BeNullOrEmpty(string because = "", params obje var singleItemArray = Subject?.Take(1).ToArray(); var nullOrEmpty = singleItemArray is null || singleItemArray.Length == 0; - assertion.ForCondition(nullOrEmpty) + assertionChain.ForCondition(nullOrEmpty) .BecauseOf(because, becauseArgs) .FailWith( "Expected {context:collection} to be null or empty{reason}, but found at least one item {0}.", @@ -663,7 +663,7 @@ public AndConstraint BeNullOrEmpty(string because = "", params obje Guard.ThrowIfArgumentIsNull(expectedSuperset, nameof(expectedSuperset), "Cannot verify a subset against a collection."); - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected {context:collection} to be a subset of {0}{reason}, ", expectedSuperset) .Given(() => Subject) @@ -690,18 +690,18 @@ public AndConstraint BeNullOrEmpty(string because = "", params obje /// public AndWhichConstraint Contain(T expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected {context:collection} to contain {0}{reason}, but found .", expected); IEnumerable matches = []; - if (assertion.Succeeded) + if (assertionChain.Succeeded) { ICollection collection = Subject.ConvertOrCastToCollection(); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(collection.Contains(expected)) .FailWith("Expected {context:collection} {0} to contain {1}{reason}.", collection, expected); @@ -729,18 +729,18 @@ public AndConstraint BeNullOrEmpty(string because = "", params obje { Guard.ThrowIfArgumentIsNull(predicate); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected {context:collection} to contain {0}{reason}, but found .", predicate.Body); IEnumerable matches = []; - if (assertion.Succeeded) + if (assertionChain.Succeeded) { Func func = predicate.Compile(); - assertion + assertionChain .ForCondition(Subject!.Any(func)) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:collection} {0} to have an item matching {1}{reason}.", Subject, predicate.Body); @@ -772,12 +772,12 @@ public AndConstraint Contain(IEnumerable expected, string becaus ICollection expectedObjects = expected.ConvertOrCastToCollection(); Guard.ThrowIfArgumentIsEmpty(expectedObjects, nameof(expected), "Cannot verify containment against an empty collection"); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected {context:collection} to contain {0}{reason}, but found .", expectedObjects); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { IEnumerable missingItems = expectedObjects.Except(Subject!); @@ -785,14 +785,14 @@ public AndConstraint Contain(IEnumerable expected, string becaus { if (expectedObjects.Count > 1) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .FailWith("Expected {context:collection} {0} to contain {1}{reason}, but could not find {2}.", Subject, expectedObjects, missingItems); } else { - assertion + assertionChain .BecauseOf(because, becauseArgs) .FailWith("Expected {context:collection} {0} to contain {1}{reason}.", Subject, expectedObjects.Single()); @@ -866,17 +866,17 @@ public AndConstraint Contain(IEnumerable expected, string becaus { Guard.ThrowIfArgumentIsNull(config); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected {context:collection} to contain equivalent of {0}{reason}, but found .", expectation); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { EquivalencyOptions options = config(AssertionOptions.CloneDefaults()); using var scope = new AssertionScope(); - scope.AddReportable("configuration", () => options.ToString()); + assertionChain.AddReportable("configuration", () => options.ToString()); foreach (T actualItem in Subject!) { @@ -905,7 +905,7 @@ public AndConstraint Contain(IEnumerable expected, string becaus } } - assertion + assertionChain .BecauseOf(because, becauseArgs) .FailWith("Expected {context:collection} {0} to contain equivalent of {1}{reason}.", Subject, expectation); } @@ -943,12 +943,12 @@ public AndConstraint ContainInOrder(params T[] expected) { Guard.ThrowIfArgumentIsNull(expected, nameof(expected), "Cannot verify ordered containment against a collection."); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected {context:collection} to contain {0} in order{reason}, but found .", expected); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { IList expectedItems = expected.ConvertOrCastToList(); IList actualItems = Subject.ConvertOrCastToList(); @@ -962,7 +962,7 @@ public AndConstraint ContainInOrder(params T[] expected) if (subjectIndex == -1) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .FailWith( "Expected {context:collection} {0} to contain items {1} in order{reason}" + @@ -1005,12 +1005,12 @@ public AndConstraint ContainInConsecutiveOrder(params T[] expected) { Guard.ThrowIfArgumentIsNull(expected, nameof(expected), "Cannot verify ordered containment against a collection."); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected {context:collection} to contain {0} in order{reason}, but found .", expected); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { IList expectedItems = expected.ConvertOrCastToList(); @@ -1042,7 +1042,7 @@ public AndConstraint ContainInConsecutiveOrder(params T[] expected) } } - assertion + assertionChain .BecauseOf(because, becauseArgs) .FailWith( "Expected {context:collection} {0} to contain items {1} in order{reason}" + @@ -1065,7 +1065,7 @@ public AndConstraint ContainInConsecutiveOrder(params T[] expected) /// public AndConstraint ContainItemsAssignableTo(string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected {context:collection} to contain at least one element assignable to type {0}{reason}, ", typeof(TExpectation).FullName) @@ -1109,7 +1109,7 @@ public AndConstraint NotContainItemsAssignableTo(Type type, string { Guard.ThrowIfArgumentIsNull(type); - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected {context:collection} to not contain any elements assignable to type {0}{reason}, ", type.FullName) @@ -1135,21 +1135,21 @@ public AndConstraint NotContainItemsAssignableTo(Type type, string /// public AndWhich ContainSingle(string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected {context:collection} to contain a single item{reason}, but found ."); T match = default; - if (assertion.Succeeded) + if (assertionChain.Succeeded) { ICollection actualItems = Subject.ConvertOrCastToCollection(); switch (actualItems.Count) { case 0: // Fail, Collection is empty - assertion + assertionChain .BecauseOf(because, becauseArgs) .FailWith("Expected {context:collection} to contain a single item{reason}, but the collection is empty."); @@ -1158,7 +1158,7 @@ public AndConstraint NotContainItemsAssignableTo(Type type, string match = actualItems.Single(); break; default: // Fail, Collection contains more than a single item - assertion + assertionChain .BecauseOf(because, becauseArgs) .FailWith("Expected {context:collection} to contain a single item{reason}, but found {0}.", Subject); @@ -1166,7 +1166,7 @@ public AndConstraint NotContainItemsAssignableTo(Type type, string } } - return new AndWhich((TAssertions)this, match, assertion, "[0]"); + return new AndWhich((TAssertions)this, match, assertionChain, "[0]"); } /// @@ -1189,18 +1189,18 @@ public AndConstraint NotContainItemsAssignableTo(Type type, string const string expectationPrefix = "Expected {context:collection} to contain a single item matching {0}{reason}, "; - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith(expectationPrefix + "but found .", predicate); T[] matches = []; - if (assertion.Succeeded) + if (assertionChain.Succeeded) { ICollection actualItems = Subject.ConvertOrCastToCollection(); - assertion + assertionChain .ForCondition(actualItems.Count > 0) .BecauseOf(because, becauseArgs) .FailWith(expectationPrefix + "but the collection is empty.", predicate); @@ -1210,13 +1210,13 @@ public AndConstraint NotContainItemsAssignableTo(Type type, string if (count == 0) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .FailWith(expectationPrefix + "but no such item was found.", predicate); } else if (count > 1) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .FailWith( expectationPrefix + "but " + count.ToString(CultureInfo.InvariantCulture) + " such items were found.", @@ -1367,16 +1367,16 @@ public AndConstraint Equal(IEnumerable expected, string because /// public AndConstraint HaveCount(int expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected {context:collection} to contain {0} item(s){reason}, but found .", expected); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { int actualCount = Subject!.Count(); - assertion + assertionChain .ForCondition(actualCount == expected) .BecauseOf(because, becauseArgs) .FailWith( @@ -1405,12 +1405,12 @@ public AndConstraint HaveCount(int expected, string because = "", p Guard.ThrowIfArgumentIsNull(countPredicate, nameof(countPredicate), "Cannot compare collection count against a predicate."); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected {context:collection} to contain {0} items{reason}, but found .", countPredicate.Body); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { Func compiledPredicate = countPredicate.Compile(); @@ -1418,7 +1418,7 @@ public AndConstraint HaveCount(int expected, string because = "", p if (!compiledPredicate(actualCount)) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .FailWith("Expected {context:collection} to have a count {0}{reason}, but count is {1}: {2}.", countPredicate.Body, actualCount, Subject); @@ -1442,7 +1442,7 @@ public AndConstraint HaveCount(int expected, string because = "", p public AndConstraint HaveCountGreaterThanOrEqualTo(int expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected {context:collection} to contain at least {0} item(s){reason}, ", expected) .Given(() => Subject) @@ -1469,7 +1469,7 @@ public AndConstraint HaveCount(int expected, string because = "", p /// public AndConstraint HaveCountGreaterThan(int expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected {context:collection} to contain more than {0} item(s){reason}, ", expected) .Given(() => Subject) @@ -1496,7 +1496,7 @@ public AndConstraint HaveCountGreaterThan(int expected, string beca /// public AndConstraint HaveCountLessThanOrEqualTo(int expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected {context:collection} to contain at most {0} item(s){reason}, ", expected) .Given(() => Subject) @@ -1523,7 +1523,7 @@ public AndConstraint HaveCountLessThanOrEqualTo(int expected, strin /// public AndConstraint HaveCountLessThan(int expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected {context:collection} to contain fewer than {0} item(s){reason}, ", expected) .Given(() => Subject) @@ -1553,27 +1553,27 @@ public AndConstraint HaveCountLessThan(int expected, string because public AndWhichConstraint HaveElementAt(int index, T element, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected {context:collection} to have element at index {0}{reason}, but found .", index); T actual = default; - if (assertion.Succeeded) + if (assertionChain.Succeeded) { if (index < Subject!.Count()) { actual = Subject.ElementAt(index); - assertion + assertionChain .ForCondition(ObjectExtensions.GetComparer()(actual, element)) .BecauseOf(because, becauseArgs) .FailWith("Expected {0} at index {1}{reason}, but found {2}.", element, index, actual); } else { - assertion + assertionChain .BecauseOf(because, becauseArgs) .FailWith("Expected {0} at index {1}{reason}, but found no element.", element, index); } @@ -1597,7 +1597,7 @@ public AndConstraint HaveCountLessThan(int expected, string because public AndConstraint HaveElementPreceding(T successor, T expectation, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected {context:collection} to have {0} precede {1}{reason}, ", expectation, successor) .Given(() => Subject) @@ -1632,7 +1632,7 @@ public AndConstraint HaveCountLessThan(int expected, string because public AndConstraint HaveElementSucceeding(T predecessor, T expectation, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected {context:collection} to have {0} succeed {1}{reason}, ", expectation, predecessor) .Given(() => Subject) @@ -1669,7 +1669,7 @@ public AndConstraint HaveCountLessThan(int expected, string because { Guard.ThrowIfArgumentIsNull(otherCollection, nameof(otherCollection), "Cannot verify count against a collection."); - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected {context:collection} to have ") .Given(() => Subject) @@ -1701,16 +1701,16 @@ public AndConstraint HaveCountLessThan(int expected, string because Guard.ThrowIfArgumentIsNull(otherCollection, nameof(otherCollection), "Cannot verify intersection against a collection."); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected {context:collection} to intersect with {0}{reason}, but found .", otherCollection); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { IEnumerable sharedItems = Subject!.Intersect(otherCollection); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(sharedItems.Any()) .FailWith( @@ -1733,7 +1733,7 @@ public AndConstraint HaveCountLessThan(int expected, string because /// public AndConstraint NotBeEmpty(string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected {context:collection} not to be empty{reason}") .Given(() => Subject) @@ -1766,14 +1766,14 @@ public AndConstraint NotBeEmpty(string because = "", params object[ if (Subject is null) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .FailWith("Expected {context:collection} not to be equivalent{reason}, but found ."); } if (ReferenceEquals(Subject, unexpected)) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .FailWith( "Expected {context:collection} {0} not to be equivalent with collection {1}{reason}, but they both reference the same object.", @@ -1810,7 +1810,7 @@ public AndConstraint NotBeEmpty(string because = "", params object[ if (Subject is null) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .FailWith("Expected {context:collection} not to be equivalent{reason}, but found ."); } @@ -1824,7 +1824,7 @@ public AndConstraint NotBeEmpty(string because = "", params object[ failures = scope.Discard(); } - assertion + assertionChain .ForCondition(failures.Length > 0) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:collection} {0} not to be equivalent to collection {1}{reason}.", Subject, @@ -2107,16 +2107,16 @@ public AndConstraint NotBeNullOrEmpty(string because = "", params o public AndConstraint NotBeSubsetOf(IEnumerable unexpectedSuperset, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Cannot assert a collection against a subset."); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { if (ReferenceEquals(Subject, unexpectedSuperset)) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .FailWith( "Did not expect {context:collection} {0} to be a subset of {1}{reason}, but they both reference the same object.", @@ -2128,7 +2128,7 @@ public AndConstraint NotBeNullOrEmpty(string because = "", params o if (actualItems.Intersect(unexpectedSuperset).Count() == actualItems.Count) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .FailWith("Did not expect {context:collection} {0} to be a subset of {1}{reason}.", actualItems, unexpectedSuperset); @@ -2151,20 +2151,20 @@ public AndConstraint NotBeNullOrEmpty(string because = "", params o /// public AndWhichConstraint NotContain(T unexpected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected {context:collection} to not contain {0}{reason}, but found .", unexpected); IEnumerable matched = []; - if (assertion.Succeeded) + if (assertionChain.Succeeded) { ICollection collection = Subject.ConvertOrCastToCollection(); if (collection.Contains(unexpected)) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .FailWith("Expected {context:collection} {0} to not contain {1}{reason}.", collection, unexpected); } @@ -2192,17 +2192,17 @@ public AndConstraint NotBeNullOrEmpty(string because = "", params o { Guard.ThrowIfArgumentIsNull(predicate); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected {context:collection} not to contain {0}{reason}, but found .", predicate.Body); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { Func compiledPredicate = predicate.Compile(); IEnumerable unexpectedItems = Subject!.Where(item => compiledPredicate(item)); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(!unexpectedItems.Any()) .FailWith("Expected {context:collection} {0} to not have any items matching {1}{reason}, but found {2}.", @@ -2235,12 +2235,12 @@ public AndConstraint NotContain(IEnumerable unexpected, string b Guard.ThrowIfArgumentIsEmpty(unexpectedObjects, nameof(unexpected), "Cannot verify non-containment against an empty collection"); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected {context:collection} to not contain {0}{reason}, but found .", unexpected); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { IEnumerable foundItems = unexpectedObjects.Intersect(Subject!); @@ -2248,14 +2248,14 @@ public AndConstraint NotContain(IEnumerable unexpected, string b { if (unexpectedObjects.Count > 1) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .FailWith("Expected {context:collection} {0} to not contain {1}{reason}, but found {2}.", Subject, unexpected, foundItems); } else { - assertion + assertionChain .BecauseOf(because, becauseArgs) .FailWith("Expected {context:collection} {0} to not contain {1}{reason}.", Subject, unexpectedObjects.First()); @@ -2330,13 +2330,13 @@ public AndConstraint NotContain(IEnumerable unexpected, string b { Guard.ThrowIfArgumentIsNull(config); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected {context:collection} not to contain equivalent of {0}{reason}, but collection is .", unexpected); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { EquivalencyOptions options = config(AssertionOptions.CloneDefaults()); @@ -2380,7 +2380,7 @@ public AndConstraint NotContain(IEnumerable unexpected, string b { using (new AssertionScope()) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected {context:collection} {0} not to contain equivalent of {1}{reason}, ", Subject, unexpected) @@ -2388,12 +2388,12 @@ public AndConstraint NotContain(IEnumerable unexpected, string b if (foundIndices.Count == 1) { - assertion + assertionChain .FailWith("but found one at index {0}.", foundIndices[0]); } else { - assertion + assertionChain .FailWith("but found several at indices {0}.", foundIndices); } } @@ -2439,7 +2439,7 @@ public AndConstraint NotContainInOrder(params T[] unexpected) if (Subject is null) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .FailWith("Cannot verify absence of ordered containment in a collection."); @@ -2463,7 +2463,7 @@ public AndConstraint NotContainInOrder(params T[] unexpected) } } - assertion + assertionChain .BecauseOf(because, becauseArgs) .FailWith( "Expected {context:collection} {0} to not contain items {1} in order{reason}, " + @@ -2510,7 +2510,7 @@ public AndConstraint NotContainInConsecutiveOrder(params T[] unexpe if (Subject is null) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .FailWith("Cannot verify absence of ordered containment in a collection."); @@ -2540,7 +2540,7 @@ public AndConstraint NotContainInConsecutiveOrder(params T[] unexpe if (consecutiveItems == unexpectedItems.Count) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .FailWith( "Expected {context:collection} {0} to not contain items {1} in consecutive order{reason}, " + @@ -2574,12 +2574,12 @@ public AndConstraint NotContainInConsecutiveOrder(params T[] unexpe { Guard.ThrowIfArgumentIsNull(predicate); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected {context:collection} not to contain s{reason}, but collection is ."); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { Func compiledPredicate = predicate.Compile(); @@ -2587,7 +2587,7 @@ public AndConstraint NotContainInConsecutiveOrder(params T[] unexpe .Where(e => compiledPredicate(e) is null) .ToArray(); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(values.Length == 0) .FailWith("Expected {context:collection} not to contain s on {0}{reason}, but found {1}.", @@ -2609,12 +2609,12 @@ public AndConstraint NotContainInConsecutiveOrder(params T[] unexpe /// public AndConstraint NotContainNulls(string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected {context:collection} not to contain s{reason}, but collection is ."); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { int[] indices = Subject! .Select((item, index) => (Item: item, Index: index)) @@ -2626,7 +2626,7 @@ public AndConstraint NotContainNulls(string because = "", params ob { if (indices.Length > 1) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .FailWith( "Expected {context:collection} not to contain s{reason}, but found several at indices {0}.", @@ -2634,7 +2634,7 @@ public AndConstraint NotContainNulls(string because = "", params ob } else { - assertion + assertionChain .BecauseOf(because, becauseArgs) .FailWith("Expected {context:collection} not to contain s{reason}, but found one at index {0}.", indices[0]); @@ -2662,7 +2662,7 @@ public AndConstraint NotEqual(IEnumerable unexpected, string bec { Guard.ThrowIfArgumentIsNull(unexpected, nameof(unexpected), "Cannot compare collection with ."); - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected collections not to be equal{reason}, ") .Given(() => Subject) @@ -2692,7 +2692,7 @@ public AndConstraint NotEqual(IEnumerable unexpected, string bec /// public AndConstraint NotHaveCount(int unexpected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected {context:collection} to not contain {0} item(s){reason}, ", unexpected) .Given(() => Subject) @@ -2724,7 +2724,7 @@ public AndConstraint NotHaveCount(int unexpected, string because = { Guard.ThrowIfArgumentIsNull(otherCollection, nameof(otherCollection), "Cannot verify count against a collection."); - assertion + assertionChain .BecauseOf(because, becauseArgs) .Given(() => Subject) .ForCondition(subject => subject is not null) @@ -2764,7 +2764,7 @@ public AndConstraint NotHaveCount(int unexpected, string because = Guard.ThrowIfArgumentIsNull(otherCollection, nameof(otherCollection), "Cannot verify intersection against a collection."); - assertion + assertionChain .BecauseOf(because, becauseArgs) .Given(() => Subject) .ForCondition(subject => subject is not null) @@ -2805,7 +2805,7 @@ public AndConstraint NotHaveCount(int unexpected, string because = Func compiledPredicate = predicate.Compile(); - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected {context:collection} to contain only items matching {0}{reason}, ", predicate.Body) .Given(() => Subject) @@ -2836,12 +2836,12 @@ public AndConstraint NotHaveCount(int unexpected, string because = { Guard.ThrowIfArgumentIsNull(predicate); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected {context:collection} to only have unique items{reason}, but found ."); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { Func compiledPredicate = predicate.Compile(); @@ -2854,7 +2854,7 @@ public AndConstraint NotHaveCount(int unexpected, string because = { if (groupWithMultipleItems.Length > 1) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .FailWith( "Expected {context:collection} to only have unique items on {0}{reason}, but items {1} are not unique.", @@ -2863,7 +2863,7 @@ public AndConstraint NotHaveCount(int unexpected, string because = } else { - assertion + assertionChain .BecauseOf(because, becauseArgs) .FailWith( "Expected {context:collection} to only have unique items on {0}{reason}, but item {1} is not unique.", @@ -2888,23 +2888,24 @@ public AndConstraint NotHaveCount(int unexpected, string because = /// public AndConstraint OnlyHaveUniqueItems(string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected {context:collection} to only have unique items{reason}, but found ."); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { - IEnumerable groupWithMultipleItems = Subject! + T[] groupWithMultipleItems = Subject! .GroupBy(o => o) .Where(g => g.Count() > 1) - .Select(g => g.Key); + .Select(g => g.Key) + .ToArray(); if (groupWithMultipleItems.Any()) { - if (groupWithMultipleItems.Count() > 1) + if (groupWithMultipleItems.Length > 1) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .FailWith( "Expected {context:collection} to only have unique items{reason}, but items {0} are not unique.", @@ -2912,7 +2913,7 @@ public AndConstraint OnlyHaveUniqueItems(string because = "", param } else { - assertion + assertionChain .BecauseOf(because, becauseArgs) .FailWith("Expected {context:collection} to only have unique items{reason}, but item {0} is not unique.", groupWithMultipleItems.First()); @@ -2942,14 +2943,14 @@ public AndConstraint AllSatisfy(Action expected, string because { Guard.ThrowIfArgumentIsNull(expected, nameof(expected), "Cannot verify against a inspector"); - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected {context:collection} to contain only items satisfying the inspector{reason}, ") .Given(() => Subject) .ForCondition(subject => subject is not null) .FailWith("but collection is ."); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { string[] failuresFromInspectors; @@ -2964,7 +2965,7 @@ public AndConstraint AllSatisfy(Action expected, string because string failureMessage = Environment.NewLine + string.Join(Environment.NewLine, failuresFromInspectors.Select(x => x.IndentLines())); - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected {context:collection} to contain only items satisfying the inspector{reason}:") .FailWithPreFormatted(failureMessage); @@ -3018,7 +3019,7 @@ public AndConstraint SatisfyRespectively(params Action[] element Guard.ThrowIfArgumentIsEmpty(elementInspectors, nameof(expected), "Cannot verify against an empty collection of inspectors"); - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected {context:collection} to satisfy all inspectors{reason}, ") .Given(() => Subject) @@ -3034,7 +3035,7 @@ public AndConstraint SatisfyRespectively(params Action[] element "Expected {context:collection} to contain exactly {0} items{reason}, but it contains {1} items", count => count.inspectors, count => count.elements); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { string[] failuresFromInspectors; @@ -3048,7 +3049,7 @@ public AndConstraint SatisfyRespectively(params Action[] element string failureMessage = Environment.NewLine + string.Join(Environment.NewLine, failuresFromInspectors.Select(x => x.IndentLines())); - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation( "Expected {context:collection} to satisfy all inspectors{reason}, but some inspectors are not satisfied:") @@ -3104,7 +3105,7 @@ public AndConstraint Satisfy(params Expression>[] pre Guard.ThrowIfArgumentIsEmpty(predicatesList, nameof(predicates), "Cannot verify against an empty collection of predicates"); - assertion + assertionChain .BecauseOf(because, becauseArgs) .Given(() => Subject) .ForCondition(subject => subject is not null) @@ -3113,7 +3114,7 @@ public AndConstraint Satisfy(params Expression>[] pre .ForCondition(subject => subject.Any()) .FailWith("Expected {context:collection} to satisfy all predicates{reason}, but collection is empty."); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { MaximumMatchingSolution maximumMatchingSolution = new MaximumMatchingProblem(predicatesList, Subject).Solve(); @@ -3145,7 +3146,7 @@ public AndConstraint Satisfy(params Expression>[] pre message += doubleNewLine + string.Join(doubleNewLine, elementDescriptions); } - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected {context:collection} to satisfy all predicates{reason}, but:") .FailWithPreFormatted(message); @@ -3239,18 +3240,18 @@ public AndConstraint StartWith(T element, string because = "", para direction, unordered); - assertion + assertionChain .ForCondition(unordered.SequenceEqual(expectation)) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:collection} {0} to be ordered {1}{reason} and result in {2}.", () => Subject, () => GetExpressionOrderString(propertyExpression), () => expectation); return new AndConstraint>( - new SubsequentOrderingAssertions(Subject, expectation, assertion)); + new SubsequentOrderingAssertions(Subject, expectation, assertionChain)); } return new AndConstraint>( - new SubsequentOrderingAssertions(Subject, Enumerable.Empty().OrderBy(x => x), assertion)); + new SubsequentOrderingAssertions(Subject, Enumerable.Empty().OrderBy(x => x), assertionChain)); } internal virtual IOrderedEnumerable GetOrderedEnumerable( @@ -3284,7 +3285,7 @@ protected static IEnumerable RepeatAsManyAs(TExpecta { Guard.ThrowIfArgumentIsNull(equalityComparison); - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected {context:collection} to end with {0}{reason}, ", expected) .Given(() => actual) @@ -3306,7 +3307,7 @@ protected static IEnumerable RepeatAsManyAs(TExpecta { Guard.ThrowIfArgumentIsNull(equalityComparison); - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected {context:collection} to start with {0}{reason}, ", expected) .Given(() => actualItems) @@ -3334,7 +3335,7 @@ protected static IEnumerable RepeatAsManyAs(TExpecta ICollection expectedItems = expectation.ConvertOrCastToCollection(); - var scope = assertion.BecauseOf(because, becauseArgs); + var scope = assertionChain.BecauseOf(because, becauseArgs); if (subjectIsNull) { @@ -3440,13 +3441,13 @@ private string[] CollectFailuresFromInspectors(IEnumerable> elementIns propertyExpression.ValidateMemberPath(); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected {context:collection} to be ordered by {0}{reason} but found .", () => propertyExpression.GetMemberPath()); - return assertion.Succeeded; + return assertionChain.Succeeded; } private AndConstraint NotBeOrderedBy( @@ -3466,7 +3467,7 @@ private string[] CollectFailuresFromInspectors(IEnumerable> elementIns direction, unordered); - assertion + assertionChain .ForCondition(!unordered.SequenceEqual(expectation)) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:collection} {0} to not be ordered {1}{reason} and not result in {2}.", @@ -3485,14 +3486,14 @@ private string[] CollectFailuresFromInspectors(IEnumerable> elementIns { string sortOrder = expectedOrder == SortOrder.Ascending ? "ascending" : "descending"; - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith($"Expected {{context:collection}} to be in {sortOrder} order{{reason}}, but found ."); IOrderedEnumerable ordering = Array.Empty().OrderBy(x => x); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { IList actualItems = Subject.ConvertOrCastToList(); @@ -3507,19 +3508,19 @@ private string[] CollectFailuresFromInspectors(IEnumerable> elementIns { if (!areSameOrEqual(actualItems[index], orderedItems[index])) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .FailWith("Expected {context:collection} to be in " + sortOrder + " order{reason}, but found {0} where item at index {1} is in wrong order.", actualItems, index); return new AndConstraint>( - new SubsequentOrderingAssertions(Subject, Enumerable.Empty().OrderBy(x => x), assertion)); + new SubsequentOrderingAssertions(Subject, Enumerable.Empty().OrderBy(x => x), assertionChain)); } } } - return new AndConstraint>(new SubsequentOrderingAssertions(Subject, ordering, assertion)); + return new AndConstraint>(new SubsequentOrderingAssertions(Subject, ordering, assertionChain)); } /// @@ -3531,12 +3532,12 @@ private string[] CollectFailuresFromInspectors(IEnumerable> elementIns { string sortOrder = order == SortOrder.Ascending ? "ascending" : "descending"; - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith($"Did not expect {{context:collection}} to be in {sortOrder} order{{reason}}, but found ."); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { IList actualItems = Subject.ConvertOrCastToList(); @@ -3550,7 +3551,7 @@ private string[] CollectFailuresFromInspectors(IEnumerable> elementIns .Where((actualItem, index) => !areSameOrEqual(actualItem, orderedItems[index])) .Any(); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(itemsAreUnordered) .FailWith( diff --git a/Src/FluentAssertions/Collections/GenericDictionaryAssertions.cs b/Src/FluentAssertions/Collections/GenericDictionaryAssertions.cs index 342b8b9769..d0f140c24f 100644 --- a/Src/FluentAssertions/Collections/GenericDictionaryAssertions.cs +++ b/Src/FluentAssertions/Collections/GenericDictionaryAssertions.cs @@ -17,8 +17,8 @@ public class GenericDictionaryAssertions : GenericDictionaryAssertions> where TCollection : IEnumerable> { - public GenericDictionaryAssertions(TCollection keyValuePairs, Assertion assertion) - : base(keyValuePairs, assertion) + public GenericDictionaryAssertions(TCollection keyValuePairs, AssertionChain assertionChain) + : base(keyValuePairs, assertionChain) { } } @@ -32,12 +32,12 @@ public class GenericDictionaryAssertions where TCollection : IEnumerable> where TAssertions : GenericDictionaryAssertions { - private readonly Assertion assertion; + private readonly AssertionChain assertionChain; - public GenericDictionaryAssertions(TCollection keyValuePairs, Assertion assertion) - : base(keyValuePairs, assertion) + public GenericDictionaryAssertions(TCollection keyValuePairs, AssertionChain assertionChain) + : base(keyValuePairs, assertionChain) { - this.assertion = assertion; + this.assertionChain = assertionChain; } #region Equal @@ -62,12 +62,12 @@ public GenericDictionaryAssertions(TCollection keyValuePairs, Assertion assertio { Guard.ThrowIfArgumentIsNull(expected, nameof(expected), "Cannot compare dictionary with ."); - assertion + assertionChain .ForCondition(Subject is not null) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:dictionary} to be equal to {0}{reason}, but found {1}.", expected, Subject); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { IEnumerable subjectKeys = GetKeys(Subject); IEnumerable expectedKeys = GetKeys(expected); @@ -76,7 +76,7 @@ public GenericDictionaryAssertions(TCollection keyValuePairs, Assertion assertio if (missingKeys.Any()) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .FailWith("Expected {context:dictionary} to be equal to {0}{reason}, but could not find keys {1}.", expected, missingKeys); @@ -84,7 +84,7 @@ public GenericDictionaryAssertions(TCollection keyValuePairs, Assertion assertio if (additionalKeys.Any()) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .FailWith("Expected {context:dictionary} to be equal to {0}{reason}, but found additional keys {1}.", expected, additionalKeys); @@ -94,7 +94,7 @@ public GenericDictionaryAssertions(TCollection keyValuePairs, Assertion assertio foreach (var key in expectedKeys) { - assertion + assertionChain .ForCondition(areSameOrEqual(GetValue(Subject, key), GetValue(expected, key))) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:dictionary} to be equal to {0}{reason}, but {1} differs at key {2}.", @@ -125,16 +125,16 @@ public GenericDictionaryAssertions(TCollection keyValuePairs, Assertion assertio { Guard.ThrowIfArgumentIsNull(unexpected, nameof(unexpected), "Cannot compare dictionary with ."); - assertion + assertionChain .ForCondition(Subject is not null) .BecauseOf(because, becauseArgs) .FailWith("Expected dictionaries not to be equal{reason}, but found {0}.", Subject); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { if (ReferenceEquals(Subject, unexpected)) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .FailWith("Expected dictionaries not to be equal{reason}, but they both reference the same object."); } @@ -152,7 +152,7 @@ public GenericDictionaryAssertions(TCollection keyValuePairs, Assertion assertio if (!foundDifference) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .FailWith("Did not expect dictionaries {0} and {1} to be equal{reason}.", unexpected, Subject); } @@ -298,12 +298,12 @@ public AndConstraint ContainKeys(params TKey[] expected) ICollection expectedKeys = expected.ConvertOrCastToCollection(); Guard.ThrowIfArgumentIsEmpty(expectedKeys, nameof(expected), "Cannot verify key containment against an empty sequence"); - assertion + assertionChain .ForCondition(Subject is not null) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:dictionary} to contain keys {0}{reason}, but found .", expected); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { IEnumerable missingKeys = expectedKeys.Where(key => !ContainsKey(Subject, key)); @@ -311,14 +311,14 @@ public AndConstraint ContainKeys(params TKey[] expected) { if (expectedKeys.Count > 1) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .FailWith("Expected {context:dictionary} {0} to contain keys {1}{reason}, but could not find {2}.", Subject, expected, missingKeys); } else { - assertion + assertionChain .BecauseOf(because, becauseArgs) .FailWith("Expected {context:dictionary} {0} to contain key {1}{reason}.", Subject, expected.First()); @@ -348,14 +348,14 @@ public AndConstraint ContainKeys(params TKey[] expected) public AndConstraint NotContainKey(TKey unexpected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject is not null) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:dictionary} not to contain key {0}{reason}, but found .", unexpected); - if (assertion.Succeeded && ContainsKey(Subject, unexpected)) + if (assertionChain.Succeeded && ContainsKey(Subject, unexpected)) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .FailWith("Expected {context:dictionary} {0} not to contain key {1}{reason}, but found it anyhow.", Subject, unexpected); @@ -399,12 +399,12 @@ public AndConstraint NotContainKeys(params TKey[] unexpected) Guard.ThrowIfArgumentIsEmpty(unexpectedKeys, nameof(unexpected), "Cannot verify key containment against an empty sequence"); - assertion + assertionChain .ForCondition(Subject is not null) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:dictionary} to not contain keys {0}{reason}, but found .", unexpectedKeys); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { IEnumerable foundKeys = unexpectedKeys.Where(key => ContainsKey(Subject, key)); @@ -412,14 +412,14 @@ public AndConstraint NotContainKeys(params TKey[] unexpected) { if (unexpectedKeys.Count > 1) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .FailWith("Expected {context:dictionary} {0} to not contain keys {1}{reason}, but found {2}.", Subject, unexpectedKeys, foundKeys); } else { - assertion + assertionChain .BecauseOf(because, becauseArgs) .FailWith("Expected {context:dictionary} {0} to not contain key {1}{reason}.", Subject, unexpectedKeys.First()); @@ -499,14 +499,14 @@ public AndConstraint ContainValues(params TValue[] expected) Guard.ThrowIfArgumentIsEmpty(expectedValues, nameof(expected), "Cannot verify value containment against an empty sequence"); - assertion + assertionChain .ForCondition(Subject is not null) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:dictionary} to contain values {0}{reason}, but found {1}.", expected, Subject); IEnumerable matchedConstraint = null; - if (assertion.Succeeded) + if (assertionChain.Succeeded) { IEnumerable subjectValues = GetValues(Subject); IEnumerable missingValues = expectedValues.Except(subjectValues); @@ -515,14 +515,14 @@ public AndConstraint ContainValues(params TValue[] expected) { if (expectedValues.Count > 1) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .FailWith("Expected {context:dictionary} {0} to contain value {1}{reason}, but could not find {2}.", Subject, expected, missingValues); } else { - assertion + assertionChain .BecauseOf(because, becauseArgs) .FailWith("Expected {context:dictionary} {0} to contain value {1}{reason}.", Subject, expected.First()); @@ -565,14 +565,14 @@ public AndConstraint ContainValues(params TValue[] expected) public AndConstraint NotContainValue(TValue unexpected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject is not null) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:dictionary} not to contain value {0}{reason}, but found .", unexpected); - if (assertion.Succeeded && GetValues(Subject).Contains(unexpected)) + if (assertionChain.Succeeded && GetValues(Subject).Contains(unexpected)) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .FailWith("Expected {context:dictionary} {0} not to contain value {1}{reason}, but found it anyhow.", Subject, unexpected); @@ -616,12 +616,12 @@ public AndConstraint NotContainValues(params TValue[] unexpected) Guard.ThrowIfArgumentIsEmpty(unexpectedValues, nameof(unexpected), "Cannot verify value containment with an empty sequence"); - assertion + assertionChain .ForCondition(Subject is not null) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:dictionary} to not contain values {0}{reason}, but found .", unexpected); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { IEnumerable foundValues = unexpectedValues.Intersect(GetValues(Subject)); @@ -629,14 +629,14 @@ public AndConstraint NotContainValues(params TValue[] unexpected) { if (unexpectedValues.Count > 1) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .FailWith("Expected {context:dictionary} {0} to not contain value {1}{reason}, but found {2}.", Subject, unexpected, foundValues); } else { - assertion + assertionChain .BecauseOf(because, becauseArgs) .FailWith("Expected {context:dictionary} {0} to not contain value {1}{reason}.", Subject, unexpected.First()); @@ -688,13 +688,13 @@ public AndConstraint Contain(params KeyValuePair[] ex Guard.ThrowIfArgumentIsEmpty(expectedKeyValuePairs, nameof(expected), "Cannot verify key containment against an empty collection of key/value pairs"); - assertion + assertionChain .ForCondition(Subject is not null) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:dictionary} to contain key/value pairs {0}{reason}, but dictionary is .", expected); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { TKey[] expectedKeys = expectedKeyValuePairs.Select(keyValuePair => keyValuePair.Key).ToArray(); IEnumerable missingKeys = expectedKeys.Where(key => !ContainsKey(Subject, key)); @@ -703,7 +703,7 @@ public AndConstraint Contain(params KeyValuePair[] ex { if (expectedKeyValuePairs.Count > 1) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .FailWith("Expected {context:dictionary} {0} to contain key(s) {1}{reason}, but could not find keys {2}.", Subject, @@ -711,7 +711,7 @@ public AndConstraint Contain(params KeyValuePair[] ex } else { - assertion + assertionChain .BecauseOf(because, becauseArgs) .FailWith("Expected {context:dictionary} {0} to contain key {1}{reason}.", Subject, expectedKeys[0]); @@ -727,7 +727,7 @@ public AndConstraint Contain(params KeyValuePair[] ex { if (keyValuePairsNotSameOrEqualInSubject.Length > 1) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .FailWith( "Expected {context:dictionary} to contain {0}{reason}, but {context:dictionary} differs at keys {1}.", @@ -738,7 +738,7 @@ public AndConstraint Contain(params KeyValuePair[] ex KeyValuePair expectedKeyValuePair = keyValuePairsNotSameOrEqualInSubject[0]; TValue actual = GetValue(Subject, expectedKeyValuePair.Key); - assertion + assertionChain .BecauseOf(because, becauseArgs) .FailWith("Expected {context:dictionary} to contain value {0} at key {1}{reason}, but found {2}.", expectedKeyValuePair.Value, expectedKeyValuePair.Key, actual); @@ -786,19 +786,19 @@ public AndConstraint Contain(params KeyValuePair[] ex public AndConstraint Contain(TKey key, TValue value, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject is not null) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:dictionary} to contain value {0} at key {1}{reason}, but dictionary is .", value, key); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { if (TryGetValue(Subject, key, out TValue actual)) { Func areSameOrEqual = ObjectExtensions.GetComparer(); - assertion + assertionChain .ForCondition(areSameOrEqual(actual, value)) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:dictionary} to contain value {0} at key {1}{reason}, but found {2}.", value, key, @@ -806,7 +806,7 @@ public AndConstraint Contain(params KeyValuePair[] ex } else { - assertion + assertionChain .BecauseOf(because, becauseArgs) .FailWith("Expected {context:dictionary} to contain value {0} at key {1}{reason}, but the key was not found.", value, @@ -857,13 +857,13 @@ public AndConstraint NotContain(params KeyValuePair[] Guard.ThrowIfArgumentIsEmpty(keyValuePairs, nameof(items), "Cannot verify key containment against an empty collection of key/value pairs"); - assertion + assertionChain .ForCondition(Subject is not null) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:dictionary} to not contain key/value pairs {0}{reason}, but dictionary is .", items); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { KeyValuePair[] keyValuePairsFound = keyValuePairs.Where(keyValuePair => ContainsKey(Subject, keyValuePair.Key)).ToArray(); @@ -879,7 +879,7 @@ public AndConstraint NotContain(params KeyValuePair[] { if (keyValuePairsSameOrEqualInSubject.Length > 1) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .FailWith( "Expected {context:dictionary} to not contain key/value pairs {0}{reason}, but found them anyhow.", @@ -889,7 +889,7 @@ public AndConstraint NotContain(params KeyValuePair[] { KeyValuePair keyValuePair = keyValuePairsSameOrEqualInSubject[0]; - assertion + assertionChain .BecauseOf(because, becauseArgs) .FailWith( "Expected {context:dictionary} to not contain value {0} at key {1}{reason}, but found it anyhow.", @@ -939,15 +939,15 @@ public AndConstraint NotContain(params KeyValuePair[] public AndConstraint NotContain(TKey key, TValue value, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject is not null) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:dictionary} not to contain value {0} at key {1}{reason}, but dictionary is .", value, key); - if (assertion.Succeeded && TryGetValue(Subject, key, out TValue actual)) + if (assertionChain.Succeeded && TryGetValue(Subject, key, out TValue actual)) { - assertion + assertionChain .ForCondition(!ObjectExtensions.GetComparer()(actual, value)) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:dictionary} not to contain value {0} at key {1}{reason}, but found it anyhow.", diff --git a/Src/FluentAssertions/Collections/StringCollectionAssertions.cs b/Src/FluentAssertions/Collections/StringCollectionAssertions.cs index 2acb362388..9070727a16 100644 --- a/Src/FluentAssertions/Collections/StringCollectionAssertions.cs +++ b/Src/FluentAssertions/Collections/StringCollectionAssertions.cs @@ -12,8 +12,8 @@ public class StringCollectionAssertions : StringCollectionAssertions /// Initializes a new instance of the class. /// - public StringCollectionAssertions(IEnumerable actualValue, Assertion assertion) - : base(actualValue, assertion) + public StringCollectionAssertions(IEnumerable actualValue, AssertionChain assertionChain) + : base(actualValue, assertionChain) { } } @@ -25,8 +25,8 @@ public class StringCollectionAssertions /// /// Initializes a new instance of the class. /// - public StringCollectionAssertions(TCollection actualValue, Assertion assertion) - : base(actualValue, assertion) + public StringCollectionAssertions(TCollection actualValue, AssertionChain assertionChain) + : base(actualValue, assertionChain) { } } @@ -35,15 +35,15 @@ public class StringCollectionAssertions : GenericColle where TCollection : IEnumerable where TAssertions : StringCollectionAssertions { - private readonly Assertion assertion; + private readonly AssertionChain assertionChain; /// /// Initializes a new instance of the class. /// - public StringCollectionAssertions(TCollection actualValue, Assertion assertion) - : base(actualValue, assertion) + public StringCollectionAssertions(TCollection actualValue, AssertionChain assertionChain) + : base(actualValue, assertionChain) { - this.assertion = assertion; + this.assertionChain = assertionChain; } /// @@ -251,16 +251,16 @@ public AndConstraint BeEquivalentTo(params string[] expectation) Guard.ThrowIfArgumentIsEmpty(wildcardPattern, nameof(wildcardPattern), "Cannot match strings in collection against an empty string. Provide a wildcard pattern or use the Contain method."); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected {context:collection} to contain a match of {0}{reason}, but found .", wildcardPattern); IEnumerable matched = []; - if (assertion.Succeeded) + if (assertionChain.Succeeded) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(ContainsMatch(wildcardPattern)) .FailWith("Expected {context:collection} {0} to contain a match of {1}{reason}.", Subject, wildcardPattern); @@ -336,15 +336,15 @@ private IEnumerable AllThatMatch(string wildcardPattern) Guard.ThrowIfArgumentIsEmpty(wildcardPattern, nameof(wildcardPattern), "Cannot match strings in collection against an empty string. Provide a wildcard pattern or use the NotContain method."); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Did not expect {context:collection} to contain a match of {0}{reason}, but found .", wildcardPattern); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(NotContainsMatch(wildcardPattern)) .FailWith("Did not expect {context:collection} {0} to contain a match of {1}{reason}.", Subject, wildcardPattern); diff --git a/Src/FluentAssertions/Collections/SubsequentOrderingAssertions.cs b/Src/FluentAssertions/Collections/SubsequentOrderingAssertions.cs index b6c6811deb..82634696b1 100644 --- a/Src/FluentAssertions/Collections/SubsequentOrderingAssertions.cs +++ b/Src/FluentAssertions/Collections/SubsequentOrderingAssertions.cs @@ -9,8 +9,8 @@ namespace FluentAssertions.Collections; public class SubsequentOrderingAssertions : SubsequentOrderingGenericCollectionAssertions, T, SubsequentOrderingAssertions> { - public SubsequentOrderingAssertions(IEnumerable actualValue, IOrderedEnumerable previousOrderedEnumerable, Assertion assertion) - : base(actualValue, previousOrderedEnumerable, assertion) + public SubsequentOrderingAssertions(IEnumerable actualValue, IOrderedEnumerable previousOrderedEnumerable, AssertionChain assertionChain) + : base(actualValue, previousOrderedEnumerable, assertionChain) { } } diff --git a/Src/FluentAssertions/Collections/SubsequentOrderingGenericCollectionAssertions.cs b/Src/FluentAssertions/Collections/SubsequentOrderingGenericCollectionAssertions.cs index 544261e866..3019fd7d10 100644 --- a/Src/FluentAssertions/Collections/SubsequentOrderingGenericCollectionAssertions.cs +++ b/Src/FluentAssertions/Collections/SubsequentOrderingGenericCollectionAssertions.cs @@ -17,8 +17,8 @@ public class SubsequentOrderingGenericCollectionAssertions previousOrderedEnumerable; private bool subsequentOrdering; - public SubsequentOrderingGenericCollectionAssertions(TCollection actualValue, IOrderedEnumerable previousOrderedEnumerable, Assertion assertion) - : base(actualValue, assertion) + public SubsequentOrderingGenericCollectionAssertions(TCollection actualValue, IOrderedEnumerable previousOrderedEnumerable, AssertionChain assertionChain) + : base(actualValue, assertionChain) { this.previousOrderedEnumerable = previousOrderedEnumerable; } @@ -168,8 +168,8 @@ public class SubsequentOrderingGenericCollectionAssertions : SubsequentOrderingGenericCollectionAssertions> where TCollection : IEnumerable { - public SubsequentOrderingGenericCollectionAssertions(TCollection actualValue, IOrderedEnumerable previousOrderedEnumerable, Assertion assertion) - : base(actualValue, previousOrderedEnumerable, assertion) + public SubsequentOrderingGenericCollectionAssertions(TCollection actualValue, IOrderedEnumerable previousOrderedEnumerable, AssertionChain assertionChain) + : base(actualValue, previousOrderedEnumerable, assertionChain) { } } diff --git a/Src/FluentAssertions/EnumAssertionsExtensions.cs b/Src/FluentAssertions/EnumAssertionsExtensions.cs index af4fd8bbdd..da15e34440 100644 --- a/Src/FluentAssertions/EnumAssertionsExtensions.cs +++ b/Src/FluentAssertions/EnumAssertionsExtensions.cs @@ -20,7 +20,7 @@ public static class EnumAssertionsExtensions public static EnumAssertions Should(this TEnum @enum) where TEnum : struct, Enum { - return new EnumAssertions(@enum, Assertion.GetOrCreate()); + return new EnumAssertions(@enum, AssertionChain.GetOrCreate()); } /// @@ -31,6 +31,6 @@ public static EnumAssertions Should(this TEnum @enum) public static NullableEnumAssertions Should(this TEnum? @enum) where TEnum : struct, Enum { - return new NullableEnumAssertions(@enum, Assertion.GetOrCreate()); + return new NullableEnumAssertions(@enum, AssertionChain.GetOrCreate()); } } diff --git a/Src/FluentAssertions/Equivalency/EquivalencyStep.cs b/Src/FluentAssertions/Equivalency/EquivalencyStep.cs index 346b8cd354..98835a16f1 100644 --- a/Src/FluentAssertions/Equivalency/EquivalencyStep.cs +++ b/Src/FluentAssertions/Equivalency/EquivalencyStep.cs @@ -7,7 +7,7 @@ namespace FluentAssertions.Equivalency; /// public abstract class EquivalencyStep : IEquivalencyStep { - public EquivalencyResult Handle(Comparands comparands, Assertion assertion, IEquivalencyValidationContext context, + public EquivalencyResult Handle(Comparands comparands, AssertionChain assertionChain, IEquivalencyValidationContext context, IValidateChildNodeEquivalency nestedValidator) { if (!typeof(T).IsAssignableFrom(comparands.GetExpectedType(context.Options))) @@ -15,13 +15,13 @@ public abstract class EquivalencyStep : IEquivalencyStep return EquivalencyResult.ContinueWithNext; } - return OnHandle(comparands, assertion, context, nestedValidator); + return OnHandle(comparands, assertionChain, context, nestedValidator); } /// /// Implements , but only gets called when the expected type matches . /// - protected abstract EquivalencyResult OnHandle(Comparands comparands, Assertion assertion, + protected abstract EquivalencyResult OnHandle(Comparands comparands, AssertionChain assertionChain, IEquivalencyValidationContext context, IValidateChildNodeEquivalency nestedValidator); } diff --git a/Src/FluentAssertions/Equivalency/EquivalencyValidationContext.cs b/Src/FluentAssertions/Equivalency/EquivalencyValidationContext.cs index 9d7215a971..2fbced998e 100644 --- a/Src/FluentAssertions/Equivalency/EquivalencyValidationContext.cs +++ b/Src/FluentAssertions/Equivalency/EquivalencyValidationContext.cs @@ -75,7 +75,7 @@ public bool IsCyclicReference(object expectation) is EqualityStrategy.Members or EqualityStrategy.ForceMembers; var reference = new ObjectReference(expectation, CurrentNode.PathAndName, compareByMembers); - return CyclicReferenceDetector.IsCyclicReference(reference, Options.CyclicReferenceHandling, Reason); + return CyclicReferenceDetector.IsCyclicReference(reference); } public ITraceWriter TraceWriter { get; set; } diff --git a/Src/FluentAssertions/Equivalency/EquivalencyValidator.cs b/Src/FluentAssertions/Equivalency/EquivalencyValidator.cs index 3ff3f1bea4..6a3b0fb080 100644 --- a/Src/FluentAssertions/Equivalency/EquivalencyValidator.cs +++ b/Src/FluentAssertions/Equivalency/EquivalencyValidator.cs @@ -15,9 +15,7 @@ public void AssertEquality(Comparands comparands, EquivalencyValidationContext c { using var scope = new AssertionScope(); - var getIdentifierOnce = new Lazy(() => scope.GetIdentifier()); - - var assertion = Assertion.GetOrCreate(() => scope, () => getIdentifierOnce.Value); + var assertion = AssertionChain.GetOrCreate(); assertion.WithReportable("configuration", () => context.Options.ToString()); assertion.BecauseOf(context.Reason); @@ -30,44 +28,54 @@ public void AssertEquality(Comparands comparands, EquivalencyValidationContext c } } - private void RecursivelyAssertEquivalencyOf(Comparands comparands, Assertion assertion, IEquivalencyValidationContext context) + private void RecursivelyAssertEquivalencyOf(Comparands comparands, AssertionChain assertionChain, IEquivalencyValidationContext context) { - AssertEquivalencyOf(comparands, assertion, context); + AssertEquivalencyOf(comparands, assertionChain, context); } - public void AssertEquivalencyOf(Comparands comparands, Assertion assertion, IEquivalencyValidationContext context) + public void AssertEquivalencyOf(Comparands comparands, AssertionChain assertionChain, IEquivalencyValidationContext context) { - if (ShouldContinueThisDeep(context.CurrentNode, context.Options, assertion)) + if (ShouldContinueThisDeep(context.CurrentNode, context.Options, assertionChain)) { - TrackWhatIsNeededToProvideContextToFailures(assertion, comparands, context.CurrentNode); + TrackWhatIsNeededToProvideContextToFailures(assertionChain, comparands, context.CurrentNode); if (!context.IsCyclicReference(comparands.Expectation)) { - TryToProveNodesAreEquivalent(assertion, comparands, context); + TryToProveNodesAreEquivalent(assertionChain, comparands, context); + } + else if (context.Options.CyclicReferenceHandling == CyclicReferenceHandling.ThrowException) + { + assertionChain + .BecauseOf(context.Reason) + .FailWith("Expected {context:subject} to be {expectation}{reason}, but it contains a cyclic reference."); + } + else + { + // If cyclic references are allowed, we consider the objects to be equivalent } } } private static bool ShouldContinueThisDeep(INode currentNode, IEquivalencyOptions options, - Assertion assertion) + AssertionChain assertionChain) { bool shouldRecurse = options.AllowInfiniteRecursion || currentNode.Depth <= MaxDepth; if (!shouldRecurse) { // This will throw, unless we're inside an AssertionScope - assertion.FailWith($"The maximum recursion depth of {MaxDepth} was reached. "); + assertionChain.FailWith($"The maximum recursion depth of {MaxDepth} was reached. "); } return shouldRecurse; } - private static void TrackWhatIsNeededToProvideContextToFailures(Assertion assertion, Comparands comparands, INode currentNode) + private static void TrackWhatIsNeededToProvideContextToFailures(AssertionChain assertionChain, Comparands comparands, INode currentNode) { - assertion.Context = new Lazy(() => currentNode.Description); - assertion.TrackComparands(comparands.Subject, comparands.Expectation); + assertionChain.Context = new Lazy(() => currentNode.Description); + assertionChain.TrackComparands(comparands.Subject, comparands.Expectation); } - private void TryToProveNodesAreEquivalent(Assertion assertion, Comparands comparands, IEquivalencyValidationContext context) + private void TryToProveNodesAreEquivalent(AssertionChain assertionChain, Comparands comparands, IEquivalencyValidationContext context) { using var _ = context.Tracer.WriteBlock(node => node.Description); @@ -75,7 +83,7 @@ private void TryToProveNodesAreEquivalent(Assertion assertion, Comparands compar foreach (IEquivalencyStep step in AssertionOptions.EquivalencyPlan) { - var result = step.Handle(comparands, assertion, context, this); + var result = step.Handle(comparands, assertionChain, context, this); if (result == EquivalencyResult.EquivalencyProven) { context.Tracer.WriteLine(getMessage(step)); diff --git a/Src/FluentAssertions/Equivalency/Execution/CyclicReferenceDetector.cs b/Src/FluentAssertions/Equivalency/Execution/CyclicReferenceDetector.cs index 600823aee9..4ca13ce49d 100644 --- a/Src/FluentAssertions/Equivalency/Execution/CyclicReferenceDetector.cs +++ b/Src/FluentAssertions/Equivalency/Execution/CyclicReferenceDetector.cs @@ -19,24 +19,13 @@ internal class CyclicReferenceDetector : ICloneable2 /// Determines whether the specified object reference is a cyclic reference to the same object earlier in the /// equivalency validation. /// - /// - /// The behavior of a cyclic reference is determined by the parameter. - /// - public bool IsCyclicReference(ObjectReference reference, CyclicReferenceHandling handling, Reason reason = null) + public bool IsCyclicReference(ObjectReference reference) { bool isCyclic = false; if (reference.CompareByMembers) { isCyclic = !observedReferences.Add(reference); - - if (isCyclic && handling == CyclicReferenceHandling.ThrowException) - { - AssertionScope.Current - .BecauseOf(reason) - .FailWith( - "Expected {context:subject} to be {expectation}{reason}, but it contains a cyclic reference."); - } } return isCyclic; diff --git a/Src/FluentAssertions/Equivalency/IEquivalencyStep.cs b/Src/FluentAssertions/Equivalency/IEquivalencyStep.cs index 4ca2ab6402..6ea8272a5b 100644 --- a/Src/FluentAssertions/Equivalency/IEquivalencyStep.cs +++ b/Src/FluentAssertions/Equivalency/IEquivalencyStep.cs @@ -17,6 +17,6 @@ public interface IEquivalencyStep /// /// May throw when preconditions are not met or if it detects mismatching data. /// - EquivalencyResult Handle(Comparands comparands, Assertion assertion, IEquivalencyValidationContext context, + EquivalencyResult Handle(Comparands comparands, AssertionChain assertionChain, IEquivalencyValidationContext context, IValidateChildNodeEquivalency nestedValidator); } diff --git a/Src/FluentAssertions/Equivalency/IMemberMatchingRule.cs b/Src/FluentAssertions/Equivalency/IMemberMatchingRule.cs index 93ad1d3dba..0a59d796eb 100644 --- a/Src/FluentAssertions/Equivalency/IMemberMatchingRule.cs +++ b/Src/FluentAssertions/Equivalency/IMemberMatchingRule.cs @@ -25,10 +25,10 @@ public interface IMemberMatchingRule /// /// /// - /// + /// /// /// Returns the of the property with which to compare the subject with, or /// if no match was found. /// - IMember Match(IMember expectedMember, object subject, INode parent, IEquivalencyOptions options, Assertion assertion); + IMember Match(IMember expectedMember, object subject, INode parent, IEquivalencyOptions options, AssertionChain assertionChain); } diff --git a/Src/FluentAssertions/Equivalency/IValidateChildNodeEquivalency.cs b/Src/FluentAssertions/Equivalency/IValidateChildNodeEquivalency.cs index 02e5e70f05..ce46f7bea7 100644 --- a/Src/FluentAssertions/Equivalency/IValidateChildNodeEquivalency.cs +++ b/Src/FluentAssertions/Equivalency/IValidateChildNodeEquivalency.cs @@ -7,5 +7,5 @@ public interface IValidateChildNodeEquivalency /// /// Runs a deep recursive equivalency assertion on the provided . /// - void AssertEquivalencyOf(Comparands comparands, Assertion assertion, IEquivalencyValidationContext context); + void AssertEquivalencyOf(Comparands comparands, AssertionChain assertionChain, IEquivalencyValidationContext context); } diff --git a/Src/FluentAssertions/Equivalency/Matching/MappedMemberMatchingRule.cs b/Src/FluentAssertions/Equivalency/Matching/MappedMemberMatchingRule.cs index 9609870579..faa1aaaea2 100644 --- a/Src/FluentAssertions/Equivalency/Matching/MappedMemberMatchingRule.cs +++ b/Src/FluentAssertions/Equivalency/Matching/MappedMemberMatchingRule.cs @@ -30,7 +30,7 @@ public MappedMemberMatchingRule(string expectationMemberName, string subjectMemb this.subjectMemberName = subjectMemberName; } - public IMember Match(IMember expectedMember, object subject, INode parent, IEquivalencyOptions options, Assertion assertion) + public IMember Match(IMember expectedMember, object subject, INode parent, IEquivalencyOptions options, AssertionChain assertionChain) { if (parent.Type.IsSameOrInherits(typeof(TExpectation)) && subject is TSubject && expectedMember.Name == expectationMemberName) diff --git a/Src/FluentAssertions/Equivalency/Matching/MappedPathMatchingRule.cs b/Src/FluentAssertions/Equivalency/Matching/MappedPathMatchingRule.cs index 59b5c48807..88c44a8f4c 100644 --- a/Src/FluentAssertions/Equivalency/Matching/MappedPathMatchingRule.cs +++ b/Src/FluentAssertions/Equivalency/Matching/MappedPathMatchingRule.cs @@ -43,7 +43,7 @@ public MappedPathMatchingRule(string expectationMemberPath, string subjectMember } } - public IMember Match(IMember expectedMember, object subject, INode parent, IEquivalencyOptions options, Assertion assertion) + public IMember Match(IMember expectedMember, object subject, INode parent, IEquivalencyOptions options, AssertionChain assertionChain) { MemberPath path = expectationPath; diff --git a/Src/FluentAssertions/Equivalency/Matching/MustMatchByNameRule.cs b/Src/FluentAssertions/Equivalency/Matching/MustMatchByNameRule.cs index 457c8e40ff..dc5ac17c6e 100644 --- a/Src/FluentAssertions/Equivalency/Matching/MustMatchByNameRule.cs +++ b/Src/FluentAssertions/Equivalency/Matching/MustMatchByNameRule.cs @@ -9,7 +9,7 @@ namespace FluentAssertions.Equivalency.Matching; /// internal class MustMatchByNameRule : IMemberMatchingRule { - public IMember Match(IMember expectedMember, object subject, INode parent, IEquivalencyOptions options, Assertion assertion) + public IMember Match(IMember expectedMember, object subject, INode parent, IEquivalencyOptions options, AssertionChain assertionChain) { IMember subjectMember = null; @@ -33,12 +33,12 @@ public IMember Match(IMember expectedMember, object subject, INode parent, IEqui if (subjectMember is null) { - assertion.FailWith( + assertionChain.FailWith( $"Expectation has {expectedMember.Description} that the other object does not have."); } else if (options.IgnoreNonBrowsableOnSubject && !subjectMember.IsBrowsable) { - assertion.FailWith( + assertionChain.FailWith( $"Expectation has {expectedMember.Description} that is non-browsable in the other object, and non-browsable " + "members on the subject are ignored with the current configuration"); } diff --git a/Src/FluentAssertions/Equivalency/Matching/TryMatchByNameRule.cs b/Src/FluentAssertions/Equivalency/Matching/TryMatchByNameRule.cs index 9254f0f865..9d6d7dc95c 100644 --- a/Src/FluentAssertions/Equivalency/Matching/TryMatchByNameRule.cs +++ b/Src/FluentAssertions/Equivalency/Matching/TryMatchByNameRule.cs @@ -9,7 +9,7 @@ namespace FluentAssertions.Equivalency.Matching; /// internal class TryMatchByNameRule : IMemberMatchingRule { - public IMember Match(IMember expectedMember, object subject, INode parent, IEquivalencyOptions options, Assertion assertion) + public IMember Match(IMember expectedMember, object subject, INode parent, IEquivalencyOptions options, AssertionChain assertionChain) { if (options.IncludedProperties != MemberVisibility.None) { diff --git a/Src/FluentAssertions/Equivalency/MultiDimensionalArrayEquivalencyStep.cs b/Src/FluentAssertions/Equivalency/MultiDimensionalArrayEquivalencyStep.cs index 86ec9077dd..3dc6152649 100644 --- a/Src/FluentAssertions/Equivalency/MultiDimensionalArrayEquivalencyStep.cs +++ b/Src/FluentAssertions/Equivalency/MultiDimensionalArrayEquivalencyStep.cs @@ -10,7 +10,7 @@ namespace FluentAssertions.Equivalency; /// internal class MultiDimensionalArrayEquivalencyStep : IEquivalencyStep { - public EquivalencyResult Handle(Comparands comparands, Assertion assertion, IEquivalencyValidationContext context, + public EquivalencyResult Handle(Comparands comparands, AssertionChain assertionChain, IEquivalencyValidationContext context, IValidateChildNodeEquivalency nestedValidator) { if (comparands.Expectation is not Array expectationAsArray || expectationAsArray.Rank == 1) @@ -18,7 +18,7 @@ internal class MultiDimensionalArrayEquivalencyStep : IEquivalencyStep return EquivalencyResult.ContinueWithNext; } - if (AreComparable(comparands, expectationAsArray)) + if (AreComparable(comparands, expectationAsArray, assertionChain)) { if (expectationAsArray.Length == 0) { @@ -36,7 +36,7 @@ internal class MultiDimensionalArrayEquivalencyStep : IEquivalencyStep IEquivalencyValidationContext itemContext = context.AsCollectionItem(listOfIndices); - nestedValidator.AssertEquivalencyOf(new Comparands(subject, expectation, typeof(object)), assertion, itemContext); + nestedValidator.AssertEquivalencyOf(new Comparands(subject, expectation, typeof(object)), assertionChain, itemContext); } while (digit.Increment()); } @@ -52,25 +52,27 @@ private static Digit BuildDigitsRepresentingAllIndices(Array subjectAsArray) .Aggregate((Digit)null, (next, rank) => new Digit(subjectAsArray.GetLength(rank), next)); } - private static bool AreComparable(Comparands comparands, Array expectationAsArray) + private static bool AreComparable(Comparands comparands, Array expectationAsArray, AssertionChain assertionChain) { return - IsArray(comparands.Subject) && - HaveSameRank(comparands.Subject, expectationAsArray) && - HaveSameDimensions(comparands.Subject, expectationAsArray); + IsArray(comparands.Subject, assertionChain) && + HaveSameRank(comparands.Subject, expectationAsArray, assertionChain) && + HaveSameDimensions(comparands.Subject, expectationAsArray, assertionChain); } - private static bool IsArray(object type) + private static bool IsArray(object type, AssertionChain assertionChain) { - return AssertionScope.Current + assertionChain .ForCondition(type is not null) .FailWith("Cannot compare a multi-dimensional array to .") .Then .ForCondition(type is Array) .FailWith("Cannot compare a multi-dimensional array to something else."); + + return assertionChain.Succeeded; } - private static bool HaveSameDimensions(object subject, Array expectation) + private static bool HaveSameDimensions(object subject, Array expectation, AssertionChain assertionChain) { bool sameDimensions = true; @@ -79,22 +81,24 @@ private static bool HaveSameDimensions(object subject, Array expectation) int actualLength = ((Array)subject).GetLength(dimension); int expectedLength = expectation.GetLength(dimension); - sameDimensions &= AssertionScope.Current + assertionChain .ForCondition(expectedLength == actualLength) .FailWith("Expected dimension {0} to contain {1} item(s), but found {2}.", dimension, expectedLength, actualLength); } - return sameDimensions; + return sameDimensions & assertionChain.Succeeded; } - private static bool HaveSameRank(object subject, Array expectation) + private static bool HaveSameRank(object subject, Array expectation, AssertionChain assertionChain) { var subjectAsArray = (Array)subject; - return AssertionScope.Current + assertionChain .ForCondition(subjectAsArray.Rank == expectation.Rank) .FailWith("Expected {context:array} to have {0} dimension(s), but it has {1}.", expectation.Rank, subjectAsArray.Rank); + + return assertionChain.Succeeded; } } diff --git a/Src/FluentAssertions/Equivalency/Steps/AssertionRuleEquivalencyStep.cs b/Src/FluentAssertions/Equivalency/Steps/AssertionRuleEquivalencyStep.cs index 9db1e3bc37..04463d4edd 100644 --- a/Src/FluentAssertions/Equivalency/Steps/AssertionRuleEquivalencyStep.cs +++ b/Src/FluentAssertions/Equivalency/Steps/AssertionRuleEquivalencyStep.cs @@ -22,7 +22,7 @@ public class AssertionRuleEquivalencyStep : IEquivalencyStep description = predicate.ToString(); } - public EquivalencyResult Handle(Comparands comparands, Assertion assertion, IEquivalencyValidationContext context, + public EquivalencyResult Handle(Comparands comparands, AssertionChain assertionChain, IEquivalencyValidationContext context, IValidateChildNodeEquivalency nestedValidator) { bool success = false; @@ -32,7 +32,7 @@ public class AssertionRuleEquivalencyStep : IEquivalencyStep // Try without conversion if (AppliesTo(comparands, context.CurrentNode)) { - success = ExecuteAssertion(comparands, context); + success = ExecuteAssertion(comparands, context, assertionChain); } bool converted = false; @@ -41,16 +41,16 @@ public class AssertionRuleEquivalencyStep : IEquivalencyStep { // Convert into a child context context = context.Clone(); - converter.Handle(comparands, assertion, context, nestedValidator); + converter.Handle(comparands, assertionChain, context, nestedValidator); converted = true; } if (converted && AppliesTo(comparands, context.CurrentNode)) { // Try again after conversion - success = ExecuteAssertion(comparands, context); + success = ExecuteAssertion(comparands, context, assertionChain); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { // If the assertion succeeded after conversion, discard the failures from // the previous attempt. If it didn't, let the scope throw with those failures. @@ -64,26 +64,26 @@ public class AssertionRuleEquivalencyStep : IEquivalencyStep private bool AppliesTo(Comparands comparands, INode currentNode) => predicate(new ObjectInfo(comparands, currentNode)); - private bool ExecuteAssertion(Comparands comparands, IEquivalencyValidationContext context) + private bool ExecuteAssertion(Comparands comparands, IEquivalencyValidationContext context, AssertionChain assertionChain) { bool subjectIsNull = comparands.Subject is null; + bool expectationIsNull = comparands.Expectation is null; - bool subjectIsValidType = - AssertionScope.Current + assertionChain .ForCondition(subjectIsNull || comparands.Subject.GetType().IsSameOrInherits(typeof(TSubject))) .FailWith("Expected " + context.CurrentNode.Description + " from subject to be a {0}{reason}, but found a {1}.", typeof(TSubject), comparands.Subject?.GetType()); - bool expectationIsNull = comparands.Expectation is null; - - bool expectationIsValidType = - AssertionScope.Current + if (assertionChain.Succeeded) + { + assertionChain .ForCondition(expectationIsNull || comparands.Expectation.GetType().IsSameOrInherits(typeof(TSubject))) .FailWith( "Expected " + context.CurrentNode.Description + " from expectation to be a {0}{reason}, but found a {1}.", typeof(TSubject), comparands.Expectation?.GetType()); + } - if (subjectIsValidType && expectationIsValidType) + if (assertionChain.Succeeded) { if ((subjectIsNull || expectationIsNull) && !CanBeNull()) { diff --git a/Src/FluentAssertions/Equivalency/Steps/AutoConversionStep.cs b/Src/FluentAssertions/Equivalency/Steps/AutoConversionStep.cs index 4b883b9293..862909d0c3 100644 --- a/Src/FluentAssertions/Equivalency/Steps/AutoConversionStep.cs +++ b/Src/FluentAssertions/Equivalency/Steps/AutoConversionStep.cs @@ -14,7 +14,7 @@ namespace FluentAssertions.Equivalency.Steps; /// public class AutoConversionStep : IEquivalencyStep { - public EquivalencyResult Handle(Comparands comparands, Assertion assertion, IEquivalencyValidationContext context, + public EquivalencyResult Handle(Comparands comparands, AssertionChain assertionChain, IEquivalencyValidationContext context, IValidateChildNodeEquivalency nestedValidator) { if (!context.Options.ConversionSelector.RequiresConversion(comparands, context.CurrentNode)) diff --git a/Src/FluentAssertions/Equivalency/Steps/DictionaryEquivalencyStep.cs b/Src/FluentAssertions/Equivalency/Steps/DictionaryEquivalencyStep.cs index 062dad5c22..3c93bd9d22 100644 --- a/Src/FluentAssertions/Equivalency/Steps/DictionaryEquivalencyStep.cs +++ b/Src/FluentAssertions/Equivalency/Steps/DictionaryEquivalencyStep.cs @@ -8,14 +8,14 @@ namespace FluentAssertions.Equivalency.Steps; public class DictionaryEquivalencyStep : EquivalencyStep { [SuppressMessage("ReSharper", "PossibleNullReferenceException")] - protected override EquivalencyResult OnHandle(Comparands comparands, Assertion assertion, + protected override EquivalencyResult OnHandle(Comparands comparands, AssertionChain assertionChain, IEquivalencyValidationContext context, IValidateChildNodeEquivalency nestedValidator) { var subject = comparands.Subject as IDictionary; var expectation = comparands.Expectation as IDictionary; - if (PreconditionsAreMet(expectation, subject, assertion) && expectation is not null) + if (PreconditionsAreMet(expectation, subject, assertionChain) && expectation is not null) { foreach (object key in expectation.Keys) { @@ -25,7 +25,7 @@ public class DictionaryEquivalencyStep : EquivalencyStep Invariant($"Recursing into dictionary item {key} at {member.Description}")); nestedValidator.AssertEquivalencyOf(new Comparands(subject[key], expectation[key], typeof(object)), - assertion, context.AsDictionaryItem(key)); + assertionChain, context.AsDictionaryItem(key)); } else { @@ -41,38 +41,38 @@ public class DictionaryEquivalencyStep : EquivalencyStep return EquivalencyResult.EquivalencyProven; } - private static bool PreconditionsAreMet(IDictionary expectation, IDictionary subject, Assertion assertion) + private static bool PreconditionsAreMet(IDictionary expectation, IDictionary subject, AssertionChain assertionChain) { - return AssertIsDictionary(subject, assertion) - && AssertEitherIsNotNull(expectation, subject, assertion) - && AssertSameLength(expectation, subject, assertion); + return AssertIsDictionary(subject, assertionChain) + && AssertEitherIsNotNull(expectation, subject, assertionChain) + && AssertSameLength(expectation, subject, assertionChain); } - private static bool AssertEitherIsNotNull(IDictionary expectation, IDictionary subject, Assertion assertion) + private static bool AssertEitherIsNotNull(IDictionary expectation, IDictionary subject, AssertionChain assertionChain) { - assertion + assertionChain .ForCondition((expectation is null && subject is null) || expectation is not null) .FailWith("Expected {context:subject} to be {0}{reason}, but found {1}.", null, subject); - return assertion.Succeeded; + return assertionChain.Succeeded; } - private static bool AssertIsDictionary(IDictionary subject, Assertion assertion) + private static bool AssertIsDictionary(IDictionary subject, AssertionChain assertionChain) { - assertion + assertionChain .ForCondition(subject is not null) .FailWith("Expected {context:subject} to be a dictionary, but it is not."); - return assertion.Succeeded; + return assertionChain.Succeeded; } - private static bool AssertSameLength(IDictionary expectation, IDictionary subject, Assertion assertion) + private static bool AssertSameLength(IDictionary expectation, IDictionary subject, AssertionChain assertionChain) { - assertion + assertionChain .ForCondition(expectation is null || subject.Keys.Count == expectation.Keys.Count) .FailWith("Expected {context:subject} to be a dictionary with {0} item(s), but it only contains {1} item(s).", expectation?.Keys.Count, subject?.Keys.Count); - return assertion.Succeeded; + return assertionChain.Succeeded; } } diff --git a/Src/FluentAssertions/Equivalency/Steps/DictionaryInterfaceInfo.cs b/Src/FluentAssertions/Equivalency/Steps/DictionaryInterfaceInfo.cs index f24ac8a726..07da897a76 100644 --- a/Src/FluentAssertions/Equivalency/Steps/DictionaryInterfaceInfo.cs +++ b/Src/FluentAssertions/Equivalency/Steps/DictionaryInterfaceInfo.cs @@ -73,11 +73,8 @@ public static DictionaryInterfaceInfo FindFromWithKey(Type target, string role, if (suitableDictionaryInterfaces.Length > 1) { - // SMELL: Code could be written to handle this better, but is it really worth the effort? - AssertionScope.Current.FailWith( + throw new InvalidOperationException( $"The {role} implements multiple IDictionary interfaces taking a key of {key}. "); - - return null; } if (suitableDictionaryInterfaces.Length == 0) diff --git a/Src/FluentAssertions/Equivalency/Steps/EnumEqualityStep.cs b/Src/FluentAssertions/Equivalency/Steps/EnumEqualityStep.cs index 40f403f2c5..9d5023aafc 100644 --- a/Src/FluentAssertions/Equivalency/Steps/EnumEqualityStep.cs +++ b/Src/FluentAssertions/Equivalency/Steps/EnumEqualityStep.cs @@ -10,7 +10,7 @@ namespace FluentAssertions.Equivalency.Steps; public class EnumEqualityStep : IEquivalencyStep { - public EquivalencyResult Handle(Comparands comparands, Assertion assertion, IEquivalencyValidationContext context, + public EquivalencyResult Handle(Comparands comparands, AssertionChain assertionChain, IEquivalencyValidationContext context, IValidateChildNodeEquivalency nestedValidator) { if (!comparands.GetExpectedType(context.Options).IsEnum) @@ -18,7 +18,7 @@ public class EnumEqualityStep : IEquivalencyStep return EquivalencyResult.ContinueWithNext; } - assertion + assertionChain .ForCondition(comparands.Subject?.GetType().IsEnum == true) .BecauseOf(context.Reason) .FailWith(() => @@ -31,16 +31,16 @@ public class EnumEqualityStep : IEquivalencyStep comparands.Subject); }); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { switch (context.Options.EnumEquivalencyHandling) { case EnumEquivalencyHandling.ByValue: - HandleByValue(assertion, comparands, context.Reason); + HandleByValue(assertionChain, comparands, context.Reason); break; case EnumEquivalencyHandling.ByName: - HandleByName(assertion, comparands, context.Reason); + HandleByName(assertionChain, comparands, context.Reason); break; default: @@ -51,12 +51,12 @@ public class EnumEqualityStep : IEquivalencyStep return EquivalencyResult.EquivalencyProven; } - private static void HandleByValue(Assertion assertion, Comparands comparands, Reason reason) + private static void HandleByValue(AssertionChain assertionChain, Comparands comparands, Reason reason) { decimal? subjectsUnderlyingValue = ExtractDecimal(comparands.Subject); decimal? expectationsUnderlyingValue = ExtractDecimal(comparands.Expectation); - assertion + assertionChain .ForCondition(subjectsUnderlyingValue == expectationsUnderlyingValue) .BecauseOf(reason) .FailWith(() => @@ -69,12 +69,12 @@ private static void HandleByValue(Assertion assertion, Comparands comparands, Re }); } - private static void HandleByName(Assertion assertion, Comparands comparands, Reason reason) + private static void HandleByName(AssertionChain assertionChain, Comparands comparands, Reason reason) { string subject = comparands.Subject.ToString(); string expected = comparands.Expectation.ToString(); - assertion + assertionChain .ForCondition(subject == expected) .BecauseOf(reason) .FailWith(() => diff --git a/Src/FluentAssertions/Equivalency/Steps/EnumerableEquivalencyStep.cs b/Src/FluentAssertions/Equivalency/Steps/EnumerableEquivalencyStep.cs index 89ad200d68..5a74feb5bf 100644 --- a/Src/FluentAssertions/Equivalency/Steps/EnumerableEquivalencyStep.cs +++ b/Src/FluentAssertions/Equivalency/Steps/EnumerableEquivalencyStep.cs @@ -7,7 +7,7 @@ namespace FluentAssertions.Equivalency.Steps; public class EnumerableEquivalencyStep : IEquivalencyStep { - public EquivalencyResult Handle(Comparands comparands, Assertion assertion, IEquivalencyValidationContext context, + public EquivalencyResult Handle(Comparands comparands, AssertionChain assertionChain, IEquivalencyValidationContext context, IValidateChildNodeEquivalency nestedValidator) { if (!IsCollection(comparands.GetExpectedType(context.Options))) @@ -15,9 +15,9 @@ public class EnumerableEquivalencyStep : IEquivalencyStep return EquivalencyResult.ContinueWithNext; } - if (AssertSubjectIsCollection(comparands.Subject)) + if (AssertSubjectIsCollection(assertionChain, comparands.Subject)) { - var validator = new EnumerableEquivalencyValidator(assertion, nestedValidator, context) + var validator = new EnumerableEquivalencyValidator(assertionChain, nestedValidator, context) { Recursive = context.CurrentNode.IsRoot || context.Options.IsRecursive, OrderingRules = context.Options.OrderingRules @@ -29,20 +29,20 @@ public class EnumerableEquivalencyStep : IEquivalencyStep return EquivalencyResult.EquivalencyProven; } - private static bool AssertSubjectIsCollection(object subject) + private static bool AssertSubjectIsCollection(AssertionChain assertionChain, object subject) { - bool conditionMet = AssertionScope.Current + assertionChain .ForCondition(subject is not null) .FailWith("Expected a collection, but {context:Subject} is ."); - if (conditionMet) + if (assertionChain.Succeeded) { - conditionMet = AssertionScope.Current + assertionChain .ForCondition(IsCollection(subject.GetType())) .FailWith("Expected a collection, but {context:Subject} is of a non-collection type."); } - return conditionMet; + return assertionChain.Succeeded; } private static bool IsCollection(Type type) diff --git a/Src/FluentAssertions/Equivalency/Steps/EnumerableEquivalencyValidator.cs b/Src/FluentAssertions/Equivalency/Steps/EnumerableEquivalencyValidator.cs index 0caf93e252..07715e575c 100644 --- a/Src/FluentAssertions/Equivalency/Steps/EnumerableEquivalencyValidator.cs +++ b/Src/FluentAssertions/Equivalency/Steps/EnumerableEquivalencyValidator.cs @@ -16,15 +16,15 @@ internal class EnumerableEquivalencyValidator #region Private Definitions - private readonly Assertion assertion; + private readonly AssertionChain assertionChain; private readonly IValidateChildNodeEquivalency parent; private readonly IEquivalencyValidationContext context; #endregion - public EnumerableEquivalencyValidator(Assertion assertion, IValidateChildNodeEquivalency parent, IEquivalencyValidationContext context) + public EnumerableEquivalencyValidator(AssertionChain assertionChain, IValidateChildNodeEquivalency parent, IEquivalencyValidationContext context) { - this.assertion = assertion; + this.assertionChain = assertionChain; this.parent = parent; this.context = context; Recursive = false; @@ -56,23 +56,26 @@ public void Execute(object[] subject, T[] expectation) } } - private static bool AssertIsNotNull(object expectation, object[] subject) + private bool AssertIsNotNull(object expectation, object[] subject) { - return AssertionScope.Current + assertionChain .ForCondition(expectation is not null) - .FailWith("Expected {context:subject} to be , but found {0}.", new object[] { subject }); + .FailWith("Expected {context:subject} to be , but found {0}.", [subject]); + + return assertionChain.Succeeded; } - private static Continuation AssertCollectionsHaveSameCount(ICollection subject, ICollection expectation) + private bool AssertCollectionsHaveSameCount(ICollection subject, ICollection expectation) { - return AssertionScope.Current + assertionChain .WithExpectation("Expected {context:subject} to be a collection with {0} item(s){reason}", expectation.Count) .AssertEitherCollectionIsNotEmpty(subject, expectation) .Then .AssertCollectionHasEnoughItems(subject, expectation) .Then - .AssertCollectionHasNotTooManyItems(subject, expectation) - ; + .AssertCollectionHasNotTooManyItems(subject, expectation); + + return assertionChain.Succeeded; } private void AssertElementGraphEquivalency(object[] subjects, T[] expectations, INode currentNode) @@ -186,7 +189,7 @@ private bool LooselyMatchAgainst(IList subjects, T expectation, int e foreach (string failure in results.SelectClosestMatchFor(expectationIndex)) { - AssertionScope.Current.AddPreFormattedFailure(failure); + assertionChain.AddPreFormattedFailure(failure); } return indexToBeRemoved != -1; @@ -197,7 +200,7 @@ private string[] TryToMatch(object subject, T expectation, int expectationInd using var scope = new AssertionScope(); parent.AssertEquivalencyOf(new Comparands(subject, expectation, typeof(T)), - assertion, context.AsCollectionItem(expectationIndex)); + assertionChain, context.AsCollectionItem(expectationIndex)); return scope.Discard(); } @@ -208,7 +211,7 @@ private bool StrictlyMatchAgainst(object[] subjects, T expectation, int expec object subject = subjects[expectationIndex]; IEquivalencyValidationContext equivalencyValidationContext = context.AsCollectionItem(expectationIndex); - parent.AssertEquivalencyOf(new Comparands(subject, expectation, typeof(T)), assertion, equivalencyValidationContext); + parent.AssertEquivalencyOf(new Comparands(subject, expectation, typeof(T)), assertionChain, equivalencyValidationContext); bool failed = scope.HasFailures(); return !failed; diff --git a/Src/FluentAssertions/Equivalency/Steps/EnumerableEquivalencyValidatorExtensions.cs b/Src/FluentAssertions/Equivalency/Steps/EnumerableEquivalencyValidatorExtensions.cs index 473811c746..f666eebb55 100644 --- a/Src/FluentAssertions/Equivalency/Steps/EnumerableEquivalencyValidatorExtensions.cs +++ b/Src/FluentAssertions/Equivalency/Steps/EnumerableEquivalencyValidatorExtensions.cs @@ -6,10 +6,10 @@ namespace FluentAssertions.Equivalency.Steps; internal static class EnumerableEquivalencyValidatorExtensions { - public static Continuation AssertEitherCollectionIsNotEmpty(this IAssertionScope scope, ICollection subject, + public static NewContinuation AssertEitherCollectionIsNotEmpty(this AssertionChain assertionChain, ICollection subject, ICollection expectation) { - return scope + return assertionChain .ForCondition(subject.Count > 0 || expectation.Count == 0) .FailWith(", but found an empty collection.") .Then @@ -19,10 +19,10 @@ internal static class EnumerableEquivalencyValidatorExtensions subject.Count); } - public static Continuation AssertCollectionHasEnoughItems(this IAssertionScope scope, ICollection subject, + public static NewContinuation AssertCollectionHasEnoughItems(this AssertionChain assertionChain, ICollection subject, ICollection expectation) { - return scope + return assertionChain .ForCondition(subject.Count >= expectation.Count) .FailWith($", but {{0}}{Environment.NewLine}contains {{1}} item(s) less than{Environment.NewLine}{{2}}.", subject, @@ -30,10 +30,10 @@ internal static class EnumerableEquivalencyValidatorExtensions expectation); } - public static Continuation AssertCollectionHasNotTooManyItems(this IAssertionScope scope, ICollection subject, + public static NewContinuation AssertCollectionHasNotTooManyItems(this AssertionChain assertionChain, ICollection subject, ICollection expectation) { - return scope + return assertionChain .ForCondition(subject.Count <= expectation.Count) .FailWith($", but {{0}}{Environment.NewLine}contains {{1}} item(s) more than{Environment.NewLine}{{2}}.", subject, diff --git a/Src/FluentAssertions/Equivalency/Steps/EqualityComparerEquivalencyStep.cs b/Src/FluentAssertions/Equivalency/Steps/EqualityComparerEquivalencyStep.cs index 46a29e9dc2..ce28615023 100644 --- a/Src/FluentAssertions/Equivalency/Steps/EqualityComparerEquivalencyStep.cs +++ b/Src/FluentAssertions/Equivalency/Steps/EqualityComparerEquivalencyStep.cs @@ -13,7 +13,7 @@ public EqualityComparerEquivalencyStep(IEqualityComparer comparer) this.comparer = comparer ?? throw new ArgumentNullException(nameof(comparer)); } - public EquivalencyResult Handle(Comparands comparands, Assertion assertion, IEquivalencyValidationContext context, + public EquivalencyResult Handle(Comparands comparands, AssertionChain assertionChain, IEquivalencyValidationContext context, IValidateChildNodeEquivalency nestedValidator) { if (comparands.GetExpectedType(context.Options) != typeof(T)) @@ -27,7 +27,7 @@ public EqualityComparerEquivalencyStep(IEqualityComparer comparer) return EquivalencyResult.ContinueWithNext; } - assertion + assertionChain .BecauseOf(context.Reason.FormattedMessage, context.Reason.Arguments) .ForCondition(comparands.Subject is T) .FailWith("Expected {context:object} to be of type {0}{because}, but found {1}", typeof(T), comparands.Subject) diff --git a/Src/FluentAssertions/Equivalency/Steps/GenericDictionaryEquivalencyStep.cs b/Src/FluentAssertions/Equivalency/Steps/GenericDictionaryEquivalencyStep.cs index e28c861734..2b952dd021 100644 --- a/Src/FluentAssertions/Equivalency/Steps/GenericDictionaryEquivalencyStep.cs +++ b/Src/FluentAssertions/Equivalency/Steps/GenericDictionaryEquivalencyStep.cs @@ -11,12 +11,12 @@ public class GenericDictionaryEquivalencyStep : IEquivalencyStep { #pragma warning disable SA1110 // Allow opening parenthesis on new line to reduce line length private static readonly MethodInfo AssertDictionaryEquivalenceMethod = - new Action, IDictionary> (AssertDictionaryEquivalence).GetMethodInfo().GetGenericMethodDefinition(); #pragma warning restore SA1110 - public EquivalencyResult Handle(Comparands comparands, Assertion assertion, IEquivalencyValidationContext context, + public EquivalencyResult Handle(Comparands comparands, AssertionChain assertionChain, IEquivalencyValidationContext context, IValidateChildNodeEquivalency nestedValidator) { if (comparands.Expectation is null) @@ -37,10 +37,10 @@ public class GenericDictionaryEquivalencyStep : IEquivalencyStep return EquivalencyResult.ContinueWithNext; } - if (IsNotNull(comparands.Subject) - && EnsureSubjectIsOfTheExpectedDictionaryType(comparands, expectedDictionary) is { } actualDictionary) + if (IsNotNull(assertionChain, comparands.Subject) + && EnsureSubjectIsOfTheExpectedDictionaryType(assertionChain, comparands, expectedDictionary) is { } actualDictionary) { - AssertDictionaryEquivalence(comparands, assertion, context, nestedValidator, actualDictionary, expectedDictionary); + AssertDictionaryEquivalence(comparands, assertionChain, context, nestedValidator, actualDictionary, expectedDictionary); } return EquivalencyResult.EquivalencyProven; @@ -57,14 +57,16 @@ private static bool IsNonGenericDictionary(object subject) @interface.IsGenericType && @interface.GetGenericTypeDefinition() == typeof(IDictionary<,>)); } - private static bool IsNotNull(object subject) + private static bool IsNotNull(AssertionChain assertionChain, object subject) { - return AssertionScope.Current + assertionChain .ForCondition(subject is not null) .FailWith("Expected {context:Subject} not to be {0}{reason}.", new object[] { null }); + + return assertionChain.Succeeded; } - private static DictionaryInterfaceInfo EnsureSubjectIsOfTheExpectedDictionaryType(Comparands comparands, + private static DictionaryInterfaceInfo EnsureSubjectIsOfTheExpectedDictionaryType(AssertionChain assertionChain, Comparands comparands, DictionaryInterfaceInfo expectedDictionary) { var actualDictionary = DictionaryInterfaceInfo.FindFromWithKey(comparands.Subject.GetType(), "subject", @@ -78,7 +80,7 @@ private static bool IsNotNull(object subject) if (actualDictionary is null) { - AssertionScope.Current.FailWith( + assertionChain.FailWith( "Expected {context:subject} to be a dictionary or collection of key-value pairs that is keyed to " + $"type {expectedDictionary.Key}."); } @@ -89,7 +91,7 @@ private static bool IsNotNull(object subject) private static void FailWithLengthDifference( IDictionary subject, IDictionary expectation, - Assertion assertion) + AssertionChain assertionChain) // Type constraint of TExpectedKey is asymmetric in regards to TSubjectKey // but it is valid. This constraint is implicitly enforced by the dictionary interface info which is called before @@ -101,7 +103,7 @@ private static bool IsNotNull(object subject) bool hasMissingKeys = keyDifference.MissingKeys.Count > 0; bool hasAdditionalKeys = keyDifference.AdditionalKeys.Count > 0; - assertion + assertionChain .WithExpectation("Expected {context:subject} to be a dictionary with {0} item(s){reason}, ", expectation.Count) .ForCondition(!hasMissingKeys || hasAdditionalKeys) .FailWith("but it misses key(s) {0}", keyDifference.MissingKeys) @@ -148,16 +150,16 @@ private static bool IsNotNull(object subject) return new KeyDifference(missingKeys, additionalKeys); } - private static void AssertDictionaryEquivalence(Comparands comparands, Assertion assertion, IEquivalencyValidationContext context, + private static void AssertDictionaryEquivalence(Comparands comparands, AssertionChain assertionChain, IEquivalencyValidationContext context, IValidateChildNodeEquivalency parent, DictionaryInterfaceInfo actualDictionary, DictionaryInterfaceInfo expectedDictionary) { AssertDictionaryEquivalenceMethod .MakeGenericMethod(actualDictionary.Key, actualDictionary.Value, expectedDictionary.Key, expectedDictionary.Value) - .Invoke(null, [assertion, context, parent, context.Options, comparands.Subject, comparands.Expectation]); + .Invoke(null, [assertionChain, context, parent, context.Options, comparands.Subject, comparands.Expectation]); } private static void AssertDictionaryEquivalence( - Assertion assertion, + AssertionChain assertionChain, EquivalencyValidationContext context, IValidateChildNodeEquivalency parent, IEquivalencyOptions options, @@ -167,7 +169,7 @@ private static bool IsNotNull(object subject) { if (subject.Count != expectation.Count) { - FailWithLengthDifference(subject, expectation, assertion); + FailWithLengthDifference(subject, expectation, assertionChain); } else { @@ -183,7 +185,7 @@ private static bool IsNotNull(object subject) var nestedComparands = new Comparands(subject[key], expectation[key], typeof(TExpectedValue)); parent.AssertEquivalencyOf(nestedComparands, - assertion, context.AsDictionaryItem(key)); + assertionChain, context.AsDictionaryItem(key)); } } else @@ -193,7 +195,7 @@ private static bool IsNotNull(object subject) } else { - AssertionScope.Current + assertionChain .BecauseOf(context.Reason) .FailWith("Expected {context:subject} to contain key {0}{reason}.", key); } diff --git a/Src/FluentAssertions/Equivalency/Steps/GenericEnumerableEquivalencyStep.cs b/Src/FluentAssertions/Equivalency/Steps/GenericEnumerableEquivalencyStep.cs index 7b0877c31b..4043915dad 100644 --- a/Src/FluentAssertions/Equivalency/Steps/GenericEnumerableEquivalencyStep.cs +++ b/Src/FluentAssertions/Equivalency/Steps/GenericEnumerableEquivalencyStep.cs @@ -15,7 +15,7 @@ public class GenericEnumerableEquivalencyStep : IEquivalencyStep (HandleImpl).GetMethodInfo().GetGenericMethodDefinition(); #pragma warning restore SA1110 - public EquivalencyResult Handle(Comparands comparands, Assertion assertion, IEquivalencyValidationContext context, + public EquivalencyResult Handle(Comparands comparands, AssertionChain assertionChain, IEquivalencyValidationContext context, IValidateChildNodeEquivalency nestedValidator) { Type expectedType = comparands.GetExpectedType(context.Options); @@ -27,15 +27,15 @@ public class GenericEnumerableEquivalencyStep : IEquivalencyStep Type[] interfaceTypes = GetIEnumerableInterfaces(expectedType); - AssertionScope.Current + assertionChain .ForCondition(interfaceTypes.Length == 1) .FailWith(() => new FailReason("{context:Expectation} implements {0}, so cannot determine which one " + "to use for asserting the equivalency of the collection. ", interfaceTypes.Select(type => "IEnumerable<" + type.GetGenericArguments().Single() + ">"))); - if (AssertSubjectIsCollection(comparands.Subject)) + if (AssertSubjectIsCollection(assertionChain, comparands.Subject)) { - var validator = new EnumerableEquivalencyValidator(assertion, nestedValidator, context) + var validator = new EnumerableEquivalencyValidator(assertionChain, nestedValidator, context) { Recursive = context.CurrentNode.IsRoot || context.Options.IsRecursive, OrderingRules = context.Options.OrderingRules @@ -62,20 +62,20 @@ public class GenericEnumerableEquivalencyStep : IEquivalencyStep private static void HandleImpl(EnumerableEquivalencyValidator validator, object[] subject, IEnumerable expectation) => validator.Execute(subject, ToArray(expectation)); - private static bool AssertSubjectIsCollection(object subject) + private static bool AssertSubjectIsCollection(AssertionChain assertionChain, object subject) { - bool conditionMet = AssertionScope.Current + assertionChain .ForCondition(subject is not null) .FailWith("Expected {context:subject} not to be {0}.", new object[] { null }); - if (conditionMet) + if (assertionChain.Succeeded) { - conditionMet = AssertionScope.Current + assertionChain .ForCondition(IsCollection(subject.GetType())) .FailWith("Expected {context:subject} to be a collection, but it was a {0}", subject.GetType()); } - return conditionMet; + return assertionChain.Succeeded; } private static bool IsCollection(Type type) diff --git a/Src/FluentAssertions/Equivalency/Steps/ReferenceEqualityEquivalencyStep.cs b/Src/FluentAssertions/Equivalency/Steps/ReferenceEqualityEquivalencyStep.cs index 611151ace5..a373da07ef 100644 --- a/Src/FluentAssertions/Equivalency/Steps/ReferenceEqualityEquivalencyStep.cs +++ b/Src/FluentAssertions/Equivalency/Steps/ReferenceEqualityEquivalencyStep.cs @@ -4,7 +4,7 @@ namespace FluentAssertions.Equivalency.Steps; public class ReferenceEqualityEquivalencyStep : IEquivalencyStep { - public EquivalencyResult Handle(Comparands comparands, Assertion assertion, IEquivalencyValidationContext context, + public EquivalencyResult Handle(Comparands comparands, AssertionChain assertionChain, IEquivalencyValidationContext context, IValidateChildNodeEquivalency nestedValidator) { return ReferenceEquals(comparands.Subject, comparands.Expectation) diff --git a/Src/FluentAssertions/Equivalency/Steps/RunAllUserStepsEquivalencyStep.cs b/Src/FluentAssertions/Equivalency/Steps/RunAllUserStepsEquivalencyStep.cs index 1da9de6af4..01929a4e0b 100644 --- a/Src/FluentAssertions/Equivalency/Steps/RunAllUserStepsEquivalencyStep.cs +++ b/Src/FluentAssertions/Equivalency/Steps/RunAllUserStepsEquivalencyStep.cs @@ -8,12 +8,12 @@ namespace FluentAssertions.Equivalency.Steps; /// public class RunAllUserStepsEquivalencyStep : IEquivalencyStep { - public EquivalencyResult Handle(Comparands comparands, Assertion assertion, IEquivalencyValidationContext context, + public EquivalencyResult Handle(Comparands comparands, AssertionChain assertionChain, IEquivalencyValidationContext context, IValidateChildNodeEquivalency nestedValidator) { foreach (IEquivalencyStep step in context.Options.UserEquivalencySteps) { - if (step.Handle(comparands, assertion, context, nestedValidator) == EquivalencyResult.EquivalencyProven) + if (step.Handle(comparands, assertionChain, context, nestedValidator) == EquivalencyResult.EquivalencyProven) { return EquivalencyResult.EquivalencyProven; } diff --git a/Src/FluentAssertions/Equivalency/Steps/SimpleEqualityEquivalencyStep.cs b/Src/FluentAssertions/Equivalency/Steps/SimpleEqualityEquivalencyStep.cs index 669f75d776..de46a36666 100644 --- a/Src/FluentAssertions/Equivalency/Steps/SimpleEqualityEquivalencyStep.cs +++ b/Src/FluentAssertions/Equivalency/Steps/SimpleEqualityEquivalencyStep.cs @@ -4,7 +4,7 @@ namespace FluentAssertions.Equivalency.Steps; public class SimpleEqualityEquivalencyStep : IEquivalencyStep { - public EquivalencyResult Handle(Comparands comparands, Assertion assertion, IEquivalencyValidationContext context, + public EquivalencyResult Handle(Comparands comparands, AssertionChain assertionChain, IEquivalencyValidationContext context, IValidateChildNodeEquivalency nestedValidator) { if (!context.Options.IsRecursive && !context.CurrentNode.IsRoot) diff --git a/Src/FluentAssertions/Equivalency/Steps/StringEqualityEquivalencyStep.cs b/Src/FluentAssertions/Equivalency/Steps/StringEqualityEquivalencyStep.cs index 7b1d7b3716..9dd571040c 100644 --- a/Src/FluentAssertions/Equivalency/Steps/StringEqualityEquivalencyStep.cs +++ b/Src/FluentAssertions/Equivalency/Steps/StringEqualityEquivalencyStep.cs @@ -5,7 +5,7 @@ namespace FluentAssertions.Equivalency.Steps; public class StringEqualityEquivalencyStep : IEquivalencyStep { - public EquivalencyResult Handle(Comparands comparands, Assertion assertion, IEquivalencyValidationContext context, + public EquivalencyResult Handle(Comparands comparands, AssertionChain assertionChain, IEquivalencyValidationContext context, IValidateChildNodeEquivalency nestedValidator) { Type expectationType = comparands.GetExpectedType(context.Options); @@ -15,12 +15,12 @@ public class StringEqualityEquivalencyStep : IEquivalencyStep return EquivalencyResult.ContinueWithNext; } - if (!ValidateAgainstNulls(comparands, context.CurrentNode)) + if (!ValidateAgainstNulls(assertionChain, comparands, context.CurrentNode)) { return EquivalencyResult.EquivalencyProven; } - bool subjectIsString = ValidateSubjectIsString(comparands, context.CurrentNode); + bool subjectIsString = ValidateSubjectIsString(assertionChain, comparands, context.CurrentNode); if (subjectIsString) { @@ -34,7 +34,7 @@ public class StringEqualityEquivalencyStep : IEquivalencyStep return EquivalencyResult.EquivalencyProven; } - private static bool ValidateAgainstNulls(Comparands comparands, INode currentNode) + private static bool ValidateAgainstNulls(AssertionChain assertionChain, Comparands comparands, INode currentNode) { object expected = comparands.Expectation; object subject = comparands.Subject; @@ -43,7 +43,7 @@ private static bool ValidateAgainstNulls(Comparands comparands, INode currentNod if (onlyOneNull) { - AssertionScope.Current.FailWith( + assertionChain.FailWith( $"Expected {currentNode.Description} to be {{0}}{{reason}}, but found {{1}}.", expected, subject); return false; @@ -52,16 +52,17 @@ private static bool ValidateAgainstNulls(Comparands comparands, INode currentNod return true; } - private static bool ValidateSubjectIsString(Comparands comparands, INode currentNode) + private static bool ValidateSubjectIsString(AssertionChain assertionChain, Comparands comparands, INode currentNode) { if (comparands.Subject is string) { return true; } - return - AssertionScope.Current - .FailWith($"Expected {currentNode} to be {{0}}, but found {{1}}.", + assertionChain.FailWith( + $"Expected {currentNode} to be {{0}}, but found {{1}}.", comparands.RuntimeType, comparands.Subject.GetType()); + + return assertionChain.Succeeded; } } diff --git a/Src/FluentAssertions/Equivalency/Steps/StructuralEqualityEquivalencyStep.cs b/Src/FluentAssertions/Equivalency/Steps/StructuralEqualityEquivalencyStep.cs index 0257e9b815..8f89334133 100644 --- a/Src/FluentAssertions/Equivalency/Steps/StructuralEqualityEquivalencyStep.cs +++ b/Src/FluentAssertions/Equivalency/Steps/StructuralEqualityEquivalencyStep.cs @@ -7,7 +7,7 @@ namespace FluentAssertions.Equivalency.Steps; public class StructuralEqualityEquivalencyStep : IEquivalencyStep { - public EquivalencyResult Handle(Comparands comparands, Assertion assertion, IEquivalencyValidationContext context, + public EquivalencyResult Handle(Comparands comparands, AssertionChain assertionChain, IEquivalencyValidationContext context, IValidateChildNodeEquivalency nestedValidator) { if (!context.CurrentNode.IsRoot && !context.Options.IsRecursive) @@ -17,7 +17,7 @@ public class StructuralEqualityEquivalencyStep : IEquivalencyStep if (comparands.Expectation is null) { - AssertionScope.Current + assertionChain .BecauseOf(context.Reason) .FailWith( "Expected {context:subject} to be {reason}, but found {0}.", @@ -25,7 +25,7 @@ public class StructuralEqualityEquivalencyStep : IEquivalencyStep } else if (comparands.Subject is null) { - AssertionScope.Current + assertionChain .BecauseOf(context.Reason) .FailWith( "Expected {context:object} to be {0}{reason}, but found {1}.", @@ -45,7 +45,7 @@ public class StructuralEqualityEquivalencyStep : IEquivalencyStep foreach (IMember selectedMember in selectedMembers) { - AssertMemberEquality(comparands, context, nestedValidator, selectedMember, context.Options, assertion); + AssertMemberEquality(comparands, context, nestedValidator, selectedMember, context.Options, assertionChain); } } @@ -53,9 +53,9 @@ public class StructuralEqualityEquivalencyStep : IEquivalencyStep } private static void AssertMemberEquality(Comparands comparands, IEquivalencyValidationContext context, - IValidateChildNodeEquivalency parent, IMember selectedMember, IEquivalencyOptions options, Assertion assertion) + IValidateChildNodeEquivalency parent, IMember selectedMember, IEquivalencyOptions options, AssertionChain assertionChain) { - IMember matchingMember = FindMatchFor(selectedMember, context.CurrentNode, comparands.Subject, options, assertion); + IMember matchingMember = FindMatchFor(selectedMember, context.CurrentNode, comparands.Subject, options, assertionChain); if (matchingMember is not null) { @@ -73,16 +73,16 @@ public class StructuralEqualityEquivalencyStep : IEquivalencyStep selectedMember.Name = matchingMember.Name; } - parent.AssertEquivalencyOf(nestedComparands, assertion, context.AsNestedMember(selectedMember)); + parent.AssertEquivalencyOf(nestedComparands, assertionChain, context.AsNestedMember(selectedMember)); } } private static IMember FindMatchFor(IMember selectedMember, INode currentNode, object subject, - IEquivalencyOptions config, Assertion assertion) + IEquivalencyOptions config, AssertionChain assertionChain) { IEnumerable query = from rule in config.MatchingRules - let match = rule.Match(selectedMember, subject, currentNode, config, assertion) + let match = rule.Match(selectedMember, subject, currentNode, config, assertionChain) where match is not null select match; diff --git a/Src/FluentAssertions/Equivalency/Steps/ValueTypeEquivalencyStep.cs b/Src/FluentAssertions/Equivalency/Steps/ValueTypeEquivalencyStep.cs index 7bd10a9568..ba638e8453 100644 --- a/Src/FluentAssertions/Equivalency/Steps/ValueTypeEquivalencyStep.cs +++ b/Src/FluentAssertions/Equivalency/Steps/ValueTypeEquivalencyStep.cs @@ -8,7 +8,7 @@ namespace FluentAssertions.Equivalency.Steps; /// public class ValueTypeEquivalencyStep : IEquivalencyStep { - public EquivalencyResult Handle(Comparands comparands, Assertion assertion, IEquivalencyValidationContext context, + public EquivalencyResult Handle(Comparands comparands, AssertionChain assertionChain, IEquivalencyValidationContext context, IValidateChildNodeEquivalency nestedValidator) { Type expectationType = comparands.GetExpectedType(context.Options); diff --git a/Src/FluentAssertions/Equivalency/Steps/XAttributeEquivalencyStep.cs b/Src/FluentAssertions/Equivalency/Steps/XAttributeEquivalencyStep.cs index 6503986f2c..4749f02165 100644 --- a/Src/FluentAssertions/Equivalency/Steps/XAttributeEquivalencyStep.cs +++ b/Src/FluentAssertions/Equivalency/Steps/XAttributeEquivalencyStep.cs @@ -5,7 +5,7 @@ namespace FluentAssertions.Equivalency.Steps; public class XAttributeEquivalencyStep : EquivalencyStep { - protected override EquivalencyResult OnHandle(Comparands comparands, Assertion assertion, + protected override EquivalencyResult OnHandle(Comparands comparands, AssertionChain assertionChain, IEquivalencyValidationContext context, IValidateChildNodeEquivalency nestedValidator) { diff --git a/Src/FluentAssertions/Equivalency/Steps/XDocumentEquivalencyStep.cs b/Src/FluentAssertions/Equivalency/Steps/XDocumentEquivalencyStep.cs index a08a45b8f1..0b9e4a7c7c 100644 --- a/Src/FluentAssertions/Equivalency/Steps/XDocumentEquivalencyStep.cs +++ b/Src/FluentAssertions/Equivalency/Steps/XDocumentEquivalencyStep.cs @@ -5,7 +5,7 @@ namespace FluentAssertions.Equivalency.Steps; public class XDocumentEquivalencyStep : EquivalencyStep { - protected override EquivalencyResult OnHandle(Comparands comparands, Assertion assertion, + protected override EquivalencyResult OnHandle(Comparands comparands, AssertionChain assertionChain, IEquivalencyValidationContext context, IValidateChildNodeEquivalency nestedValidator) { diff --git a/Src/FluentAssertions/Equivalency/Steps/XElementEquivalencyStep.cs b/Src/FluentAssertions/Equivalency/Steps/XElementEquivalencyStep.cs index ed22b87a28..4690463702 100644 --- a/Src/FluentAssertions/Equivalency/Steps/XElementEquivalencyStep.cs +++ b/Src/FluentAssertions/Equivalency/Steps/XElementEquivalencyStep.cs @@ -5,7 +5,7 @@ namespace FluentAssertions.Equivalency.Steps; public class XElementEquivalencyStep : EquivalencyStep { - protected override EquivalencyResult OnHandle(Comparands comparands, Assertion assertion, + protected override EquivalencyResult OnHandle(Comparands comparands, AssertionChain assertionChain, IEquivalencyValidationContext context, IValidateChildNodeEquivalency nestedValidator) { diff --git a/Src/FluentAssertions/EventRaisingExtensions.cs b/Src/FluentAssertions/EventRaisingExtensions.cs index f395d074cd..2ad550a054 100644 --- a/Src/FluentAssertions/EventRaisingExtensions.cs +++ b/Src/FluentAssertions/EventRaisingExtensions.cs @@ -23,7 +23,7 @@ public static IEventRecording WithSender(this IEventRecording eventRecording, ob { var eventsForSender = new List(); var otherSenders = new List(); - var assertion = Assertion.GetOrCreate(); + var assertion = AssertionChain.GetOrCreate(); foreach (OccurredEvent @event in eventRecording) { @@ -84,7 +84,7 @@ public static IEventRecording WithArgs(this IEventRecording eventRecording, E bool foundMatchingEvent = eventsWithMatchingPredicate.Count > 0; - Assertion + AssertionChain .GetOrCreate() .ForCondition(foundMatchingEvent) .FailWith("Expected at least one event with some argument of type <{0}> that matches {1}, but found none.", @@ -138,7 +138,7 @@ public static IEventRecording WithArgs(this IEventRecording eventRecording, p if (!foundMatchingEvent) { - Assertion + AssertionChain .GetOrCreate() .FailWith( "Expected at least one event with some arguments of type <{0}> that pairwise match {1}, but found none.", diff --git a/Src/FluentAssertions/Events/EventAssertions.cs b/Src/FluentAssertions/Events/EventAssertions.cs index 471ee615ed..5acd3c2659 100644 --- a/Src/FluentAssertions/Events/EventAssertions.cs +++ b/Src/FluentAssertions/Events/EventAssertions.cs @@ -15,12 +15,12 @@ namespace FluentAssertions.Events; public class EventAssertions : ReferenceTypeAssertions> { private const string PropertyChangedEventName = "PropertyChanged"; - private readonly Assertion assertion; + private readonly AssertionChain assertionChain; - protected internal EventAssertions(IMonitor monitor, Assertion assertion) - : base(monitor.Subject, assertion) + protected internal EventAssertions(IMonitor monitor, AssertionChain assertionChain) + : base(monitor.Subject, assertionChain) { - this.assertion = assertion; + this.assertionChain = assertionChain; Monitor = monitor; } @@ -48,7 +48,7 @@ public IEventRecording Raise(string eventName, string because = "", params objec if (!recording.Any()) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .FailWith("Expected object {0} to raise event {1}{reason}, but it did not.", Monitor.Subject, eventName); } @@ -75,7 +75,7 @@ public void NotRaise(string eventName, string because = "", params object[] beca if (events.Any()) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .FailWith("Expected object {0} to not raise event {1}{reason}, but it did.", Monitor.Subject, eventName); } @@ -102,14 +102,14 @@ public void NotRaise(string eventName, string because = "", params object[] beca IEventRecording recording = Monitor.GetRecordingFor(PropertyChangedEventName); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(recording.Any()) .FailWith( "Expected object {0} to raise event {1} for property {2}{reason}, but it did not raise that event at all.", Monitor.Subject, PropertyChangedEventName, propertyName); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { var actualPropertyNames = recording .SelectMany(@event => @event.Parameters.OfType()) @@ -117,7 +117,7 @@ public void NotRaise(string eventName, string because = "", params object[] beca .Distinct() .ToArray(); - assertion + assertionChain .ForCondition(actualPropertyNames.Contains(propertyName)) .BecauseOf(because, becauseArgs) .FailWith("Expected object {0} to raise event {1} for property {2}{reason}, but it was only raised for {3}.", @@ -149,7 +149,7 @@ public void NotRaise(string eventName, string because = "", params object[] beca if (recording.Any(@event => GetAffectedPropertyName(@event) == propertyName)) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .FailWith("Did not expect object {0} to raise the {1} event for property {2}{reason}, but it did.", Monitor.Subject, PropertyChangedEventName, propertyName); diff --git a/Src/FluentAssertions/Events/EventMonitor.cs b/Src/FluentAssertions/Events/EventMonitor.cs index b32ce0c4e2..6aac167a01 100644 --- a/Src/FluentAssertions/Events/EventMonitor.cs +++ b/Src/FluentAssertions/Events/EventMonitor.cs @@ -68,7 +68,7 @@ public void Clear() public EventAssertions Should() { - return new EventAssertions(this, Assertion.GetOrCreate()); + return new EventAssertions(this, AssertionChain.GetOrCreate()); } public IEventRecording GetRecordingFor(string eventName) diff --git a/Src/FluentAssertions/ExceptionAssertionsExtensions.cs b/Src/FluentAssertions/ExceptionAssertionsExtensions.cs index 55e7ad73cc..74356ae567 100644 --- a/Src/FluentAssertions/ExceptionAssertionsExtensions.cs +++ b/Src/FluentAssertions/ExceptionAssertionsExtensions.cs @@ -166,7 +166,7 @@ public static class ExceptionAssertionsExtensions params object[] becauseArgs) where TException : ArgumentException { - Assertion.GetOrCreate() + AssertionChain.GetOrCreate() .ForCondition(parent.Which.ParamName == paramName) .BecauseOf(because, becauseArgs) .FailWith("Expected exception with parameter name {0}{reason}, but found {1}.", paramName, parent.Which.ParamName); diff --git a/Src/FluentAssertions/Execution/Assertion.cs b/Src/FluentAssertions/Execution/AssertionChain.cs similarity index 58% rename from Src/FluentAssertions/Execution/Assertion.cs rename to Src/FluentAssertions/Execution/AssertionChain.cs index da6885a6a3..8c0cf64ada 100644 --- a/Src/FluentAssertions/Execution/Assertion.cs +++ b/Src/FluentAssertions/Execution/AssertionChain.cs @@ -7,11 +7,10 @@ namespace FluentAssertions.Execution; -public class Assertion : IAssertion - where TAssertion : Assertion +public class AssertionChain { private readonly StringBuilder tracing = new(); - private readonly ContextDataItems contextData = new(); + private readonly Func getCurrentScope; private string fallbackIdentifier = "object"; private Func getCallerIdentifier; private bool previousAssertionSucceeded; @@ -19,17 +18,30 @@ public class Assertion : IAssertion private bool? succeeded; private Func expectation; - protected Assertion(Func getCurrentScope, Func getCallerIdentifier, bool previousAssertionSucceeded = true) + private static readonly AsyncLocal Instance = new(); + + public static void ReuseOnce(AssertionChain assertionChain) { - this.GetCurrentScope = getCurrentScope; - this.getCallerIdentifier = getCallerIdentifier; - this.previousAssertionSucceeded = previousAssertionSucceeded; + Instance.Value = assertionChain; } - protected Assertion(IAssertion previousAssertion) - : this(previousAssertion.GetCurrentScope, previousAssertion.GetCallerIdentifier, previousAssertion.Succeeded) + public static AssertionChain GetOrCreate() { - reason = previousAssertion.Reason; + if (Instance.Value != null) + { + AssertionChain assertionChain = Instance.Value; + Instance.Value = null; + return assertionChain; + } + + return new AssertionChain(() => AssertionScope.Current, () => AssertionScope.Current.GetIdentifier()); + } + + private AssertionChain(Func getCurrentScope, Func getCallerIdentifier, bool previousAssertionSucceeded = true) + { + this.getCurrentScope = getCurrentScope; + this.getCallerIdentifier = getCallerIdentifier; + this.previousAssertionSucceeded = previousAssertionSucceeded; } /// @@ -42,13 +54,12 @@ protected Assertion(IAssertion previousAssertion) /// /// Adds an explanation of why the assertion is supposed to succeed to the scope. /// - public TAssertion BecauseOf(Reason reason) + public AssertionChain BecauseOf(Reason reason) { return BecauseOf(reason.FormattedMessage, reason.Arguments); } - /// - public TAssertion BecauseOf(string because, params object[] becauseArgs) + public AssertionChain BecauseOf(string because, params object[] becauseArgs) { reason = () => { @@ -67,36 +78,31 @@ public TAssertion BecauseOf(string because, params object[] becauseArgs) } }; - return (TAssertion)this; + return this; } - /// - public TAssertion ForCondition(bool condition) + public AssertionChain ForCondition(bool condition) { if (previousAssertionSucceeded) { succeeded = condition; } - return (TAssertion)this; + return this; } - void IAssertion.ForCondition(bool predicate) => ForCondition(predicate); - - void IAssertion.FailWith(string message, object[] args) => FailWith(message, args); - - public TAssertion ForConstraint(OccurrenceConstraint constraint, int actualOccurrences) + public AssertionChain ForConstraint(OccurrenceConstraint constraint, int actualOccurrences) { if (previousAssertionSucceeded) { - constraint.RegisterReportables(GetCurrentScope()); + constraint.RegisterReportables(this); succeeded = constraint.Assert(actualOccurrences); } - return (TAssertion)this; + return this; } - public TAssertion WithExpectation(string message, params object[] args) + public AssertionChain WithExpectation(string message, params object[] args) { if (previousAssertionSucceeded) { @@ -104,7 +110,7 @@ public TAssertion WithExpectation(string message, params object[] args) expectation = () => { - var messageBuilder = new MessageBuilder(GetCurrentScope().FormattingOptions); + var messageBuilder = new MessageBuilder(getCurrentScope().FormattingOptions); string actualReason = localReason?.Invoke() ?? string.Empty; string identifier = getCallerIdentifier(); @@ -112,25 +118,24 @@ public TAssertion WithExpectation(string message, params object[] args) message, args, actualReason, - GetCurrentScope().ContextData, + contextData, identifier, fallbackIdentifier); }; } - return (TAssertion)this; + return this; } public void WithReportable(string name, Func content) { - GetCurrentScope().AddReportable(name, content); + AddReportable(name, content); } - /// - public TAssertion WithDefaultIdentifier(string identifier) + public AssertionChain WithDefaultIdentifier(string identifier) { fallbackIdentifier = identifier; - return (TAssertion)this; + return this; } public NewGivenSelector Given(Func selector) @@ -138,22 +143,22 @@ public NewGivenSelector Given(Func selector) return new NewGivenSelector(selector, this); } - internal NewContinuation FailWithPreFormatted(string formattedFailReason) + internal NewContinuation FailWithPreFormatted(string formattedFailReason) { return FailWith(() => formattedFailReason); } - public NewContinuation FailWith(string message) + public NewContinuation FailWith(string message) { return FailWith(() => new FailReason(message)); } - public NewContinuation FailWith(string message, params object[] args) + public NewContinuation FailWith(string message, params object[] args) { return FailWith(() => new FailReason(message, args)); } - public NewContinuation FailWith(string message, params Func[] argProviders) + public NewContinuation FailWith(string message, params Func[] argProviders) { return FailWith( () => new FailReason( @@ -161,13 +166,12 @@ public NewContinuation FailWith(string message, params Func< argProviders.Select(a => a()).ToArray())); } - public NewContinuation FailWith(Func failReasonFunc) + public NewContinuation FailWith(Func failReasonFunc) { - return FailWith( - () => + return FailWith(() => { string localReason = reason?.Invoke() ?? string.Empty; - var messageBuilder = new MessageBuilder(GetCurrentScope().FormattingOptions); + var messageBuilder = new MessageBuilder(getCurrentScope().FormattingOptions); string identifier = getCallerIdentifier(); FailReason failReason = failReasonFunc(); @@ -175,7 +179,7 @@ public NewContinuation FailWith(Func failReasonF failReason.Message, failReason.Args, localReason, - contextData, + getCurrentScope().ContextData, identifier, fallbackIdentifier); @@ -183,7 +187,7 @@ public NewContinuation FailWith(Func failReasonF }); } - private NewContinuation FailWith(Func failReasonFunc) + private NewContinuation FailWith(Func failReasonFunc) { if (previousAssertionSucceeded) { @@ -197,14 +201,14 @@ private NewContinuation FailWith(Func failReasonFunc result = expectation() + result; } - GetCurrentScope().AddPreFormattedFailure(result.Capitalize()); + getCurrentScope().AddPreFormattedFailure(result.Capitalize()); } } // Reset the state for successive assertions on this object succeeded = null; - return new NewContinuation(this); + return new NewContinuation(this); } public void AddCallerPostfix(string postfix) @@ -213,6 +217,33 @@ public void AddCallerPostfix(string postfix) getCallerIdentifier = () => originalCallerIdentifier() + postfix; } + /// + /// Tracks a keyed object in the current scope that is excluded from the failure message in case an assertion fails. + /// + public void AddNonReportable(string key, object value) + { + contextData.Add(new ContextDataItems.DataItem(key, value, reportable: false, requiresFormatting: false)); + } + + /// + /// Adds some information to the assertion scope that will be included in the message + /// that is emitted if an assertion fails. + /// + public void AddReportable(string key, string value) + { + contextData.Add(new ContextDataItems.DataItem(key, value, reportable: true, requiresFormatting: false)); + } + + /// + /// Adds some information to the assertion scope that will be included in the message + /// that is emitted if an assertion fails. The value is only calculated on failure. + /// + public void AddReportable(string key, Func valueFunc) + { + contextData.Add(new ContextDataItems.DataItem(key, new DeferredReportable(valueFunc), reportable: true, + requiresFormatting: false)); + } + /// /// Adds a block of tracing to the scope for reporting when an assertion fails. /// @@ -221,59 +252,37 @@ public void AppendTracing(string tracingBlock) tracing.Append(tracingBlock); } + public void AddPreFormattedFailure(string failure) + { + getCurrentScope().AddPreFormattedFailure(failure); + } + internal void TrackComparands(object subject, object expectation) { contextData.Add(new ContextDataItems.DataItem("subject", subject, reportable: false, requiresFormatting: true)); contextData.Add(new ContextDataItems.DataItem("expectation", expectation, reportable: false, requiresFormatting: true)); } - public Func GetCurrentScope { get; } - - public Func GetCallerIdentifier => getCallerIdentifier; - public bool Succeeded => previousAssertionSucceeded && (succeeded is null or true); - public TAssertion UsingLineBreaks + public AssertionChain UsingLineBreaks { get { - GetCurrentScope().FormattingOptions.UseLineBreaks = true; - return (TAssertion)this; + getCurrentScope().FormattingOptions.UseLineBreaks = true; + return this; } } - public Func Reason => reason; -} - -public sealed class Assertion : Assertion -{ - // REFACTOR: Do we really need to pass in the scope and identifier? - private Assertion(Func currentScope, Func getCallerIdentifier) - : base(currentScope, getCallerIdentifier, previousAssertionSucceeded: true) - { - } - - private static readonly AsyncLocal Instance = new(); - - public static void ReuseOnce(Assertion assertion) + private sealed class DeferredReportable { - Instance.Value = assertion; - } + private readonly Lazy lazyValue; - public static Assertion GetOrCreate() - { - return GetOrCreate(() => AssertionScope.Current, () => AssertionScope.Current.GetIdentifier()); - } - - public static Assertion GetOrCreate(Func getCurrent, Func getCallerIdentifier) - { - if (Instance.Value != null) + public DeferredReportable(Func valueFunc) { - Assertion assertion = Instance.Value; - Instance.Value = null; - return assertion; + lazyValue = new Lazy(valueFunc); } - return new Assertion(getCurrent, getCallerIdentifier); + public override string ToString() => lazyValue.Value; } } diff --git a/Src/FluentAssertions/Execution/AssertionScope.cs b/Src/FluentAssertions/Execution/AssertionScope.cs index f6030a6a90..7d4b7a335a 100644 --- a/Src/FluentAssertions/Execution/AssertionScope.cs +++ b/Src/FluentAssertions/Execution/AssertionScope.cs @@ -1,10 +1,6 @@ using System; -using System.Collections.Generic; -using System.Globalization; using System.Linq; -using System.Text; using System.Threading; -using FluentAssertions.Common; using FluentAssertions.Formatting; namespace FluentAssertions.Execution; @@ -17,33 +13,16 @@ namespace FluentAssertions.Execution; /// such as when using or . /// // Remove all assertion logic from this class since it is superseded by the Assertion class -public sealed class AssertionScope : IAssertionScope +public sealed class AssertionScope : IDisposable { #region Private Definitions private readonly IAssertionStrategy assertionStrategy; - private readonly StringBuilder tracing = new(); - - private Func reason; - private static readonly AsyncLocal CurrentScope = new(); private readonly Func callerIdentityProvider = () => CallerIdentifier.DetermineCallerIdentity(); - private AssertionScope parent; - private Func expectation; - private string fallbackIdentifier = "object"; - private bool? succeeded; - - private sealed class DeferredReportable - { - private readonly Lazy lazyValue; + private readonly ContextDataItems contextData = new(); - public DeferredReportable(Func valueFunc) - { - lazyValue = new Lazy(valueFunc); - } - - public override string ToString() => lazyValue.Value; - } + private AssertionScope parent; #endregion @@ -105,9 +84,7 @@ private AssertionScope(IAssertionStrategy assertionStrategy, AssertionScope pare if (parent is not null) { - ContextData.Add(parent.ContextData); Context = parent.Context; - reason = parent.reason; callerIdentityProvider = parent.callerIdentityProvider; FormattingOptions = parent.FormattingOptions.Clone(); } @@ -134,168 +111,11 @@ public static AssertionScope Current private set => SetCurrentAssertionScope(value); } - /// - public AssertionScope UsingLineBreaks - { - get - { - FormattingOptions.UseLineBreaks = true; - return this; - } - } - /// /// Exposes the options the scope will use for formatting objects in case an assertion fails. /// public FormattingOptions FormattingOptions { get; } = AssertionOptions.FormattingOptions.Clone(); - internal bool Succeeded => succeeded == true; - - public ContextDataItems ContextData { get; } = new(); - - /// - /// Adds an explanation of why the assertion is supposed to succeed to the scope. - /// - public AssertionScope BecauseOf(Reason reason) - { - return BecauseOf(reason.FormattedMessage, reason.Arguments); - } - - /// - public AssertionScope BecauseOf(string because, params object[] becauseArgs) - { - reason = () => - { - try - { - string becauseOrEmpty = because ?? string.Empty; - - return becauseArgs?.Length > 0 - ? string.Format(CultureInfo.InvariantCulture, becauseOrEmpty, becauseArgs) - : becauseOrEmpty; - } - catch (FormatException formatException) - { - return - $"**WARNING** because message '{because}' could not be formatted with string.Format{Environment.NewLine}{formatException.StackTrace}"; - } - }; - - return this; - } - - /// - public AssertionScope WithExpectation(string message, params object[] args) - { - Func localReason = reason; - - expectation = () => - { - var messageBuilder = new MessageBuilder(FormattingOptions); - string actualReason = localReason?.Invoke() ?? string.Empty; - string identifier = GetIdentifier(); - - return messageBuilder.Build(message, args, actualReason, ContextData, identifier, fallbackIdentifier); - }; - - return this; - } - - /// - public Continuation ClearExpectation() - { - expectation = null; - - // SMELL: Isn't this always going to return null? Or this method also called without FailWith (which sets the success state to null) - return new Continuation(this, Succeeded); - } - - public GivenSelector Given(Func selector) - { - return new GivenSelector(selector, this, continueAsserting: succeeded != false); - } - - /// - public AssertionScope ForCondition(bool condition) - { - succeeded = condition; - - return this; - } - - /// - public AssertionScope ForConstraint(OccurrenceConstraint constraint, int actualOccurrences) - { - constraint.RegisterReportables(this); - succeeded = constraint.Assert(actualOccurrences); - - return this; - } - - /// - public Continuation FailWith(Func failReasonFunc) - { - return FailWith(() => - { - string localReason = reason?.Invoke() ?? string.Empty; - var messageBuilder = new MessageBuilder(FormattingOptions); - string identifier = GetIdentifier(); - FailReason failReason = failReasonFunc(); - - string result = messageBuilder.Build(failReason.Message, failReason.Args, localReason, ContextData, identifier, - fallbackIdentifier); - - return result; - }); - } - - private Continuation FailWith(Func failReasonFunc) - { - try - { - bool failed = succeeded != true; - - if (failed) - { - string result = failReasonFunc(); - - if (expectation is not null) - { - result = expectation() + result; - } - - assertionStrategy.HandleFailure(result.Capitalize()); - - succeeded = false; - } - - return new Continuation(this, continueAsserting: !failed); - } - finally - { - succeeded = null; - } - } - - /// - public Continuation FailWith(string message) - { - return FailWith(() => new FailReason(message)); - } - - /// - public Continuation FailWith(string message, params object[] args) - { - return FailWith(() => new FailReason(message, args)); - } - - /// - public Continuation FailWith(string message, params Func[] argProviders) - { - return FailWith(() => new FailReason(message, - argProviders.Select(a => a()).ToArray())); - } - public string GetIdentifier() { var identifier = Context?.Value; @@ -321,41 +141,6 @@ public void AddPreFormattedFailure(string formattedFailureMessage) assertionStrategy.HandleFailure(formattedFailureMessage); } - /// - /// Adds a block of tracing to the scope for reporting when an assertion fails. - /// - public void AppendTracing(string tracingBlock) - { - tracing.Append(tracingBlock); - } - - /// - /// Tracks a keyed object in the current scope that is excluded from the failure message in case an assertion fails. - /// - public void AddNonReportable(string key, object value) - { - ContextData.Add(new ContextDataItems.DataItem(key, value, reportable: false, requiresFormatting: false)); - } - - /// - /// Adds some information to the assertion scope that will be included in the message - /// that is emitted if an assertion fails. - /// - public void AddReportable(string key, string value) - { - ContextData.Add(new ContextDataItems.DataItem(key, value, reportable: true, requiresFormatting: false)); - } - - /// - /// Adds some information to the assertion scope that will be included in the message - /// that is emitted if an assertion fails. The value is only calculated on failure. - /// - public void AddReportable(string key, Func valueFunc) - { - ContextData.Add(new ContextDataItems.DataItem(key, new DeferredReportable(valueFunc), reportable: true, - requiresFormatting: false)); - } - /// /// Returns all failures that happened up to this point and ensures they will not cause /// to fail the assertion. @@ -370,14 +155,6 @@ public bool HasFailures() return assertionStrategy.FailureMessages.Any(); } - /// - /// Gets data associated with the current scope and identified by . - /// - public T Get(string key) - { - return ContextData.Get(key); - } - /// public void Dispose() { @@ -390,31 +167,14 @@ public void Dispose() parent.assertionStrategy.HandleFailure(failureMessage); } - parent.ContextData.Add(ContextData); - parent.AppendTracing(tracing.ToString()); - parent = null; } else { - IDictionary reportable = ContextData.GetReportable(); - - if (tracing.Length > 0) - { - reportable.Add("trace", tracing.ToString()); - } - assertionStrategy.ThrowIfAny(reportable); } } - /// - public AssertionScope WithDefaultIdentifier(string identifier) - { - fallbackIdentifier = identifier; - return this; - } - private static AssertionScope GetCurrentAssertionScope() { return CurrentScope.Value; @@ -424,20 +184,4 @@ private static void SetCurrentAssertionScope(AssertionScope scope) { CurrentScope.Value = scope; } - - #region Explicit Implementation to support the interface - - IAssertionScope IAssertionScope.ForCondition(bool condition) => ForCondition(condition); - - IAssertionScope IAssertionScope.ForConstraint(OccurrenceConstraint constraint, int actualOccurrences) => ForConstraint(constraint, actualOccurrences); - - IAssertionScope IAssertionScope.BecauseOf(string because, params object[] becauseArgs) => BecauseOf(because, becauseArgs); - - IAssertionScope IAssertionScope.WithExpectation(string message, params object[] args) => WithExpectation(message, args); - - IAssertionScope IAssertionScope.WithDefaultIdentifier(string identifier) => WithDefaultIdentifier(identifier); - - IAssertionScope IAssertionScope.UsingLineBreaks => UsingLineBreaks; - - #endregion } diff --git a/Src/FluentAssertions/Execution/ContextDataItems.cs b/Src/FluentAssertions/Execution/ContextDataItems.cs index 62c463f3ad..14c83f05c8 100644 --- a/Src/FluentAssertions/Execution/ContextDataItems.cs +++ b/Src/FluentAssertions/Execution/ContextDataItems.cs @@ -7,7 +7,7 @@ namespace FluentAssertions.Execution; /// /// Represents a collection of data items that are associated with an . /// -public class ContextDataItems +internal class ContextDataItems { private readonly List items = []; diff --git a/Src/FluentAssertions/Execution/Continuation.cs b/Src/FluentAssertions/Execution/Continuation.cs deleted file mode 100644 index 42264aae15..0000000000 --- a/Src/FluentAssertions/Execution/Continuation.cs +++ /dev/null @@ -1,35 +0,0 @@ -namespace FluentAssertions.Execution; - -/// -/// Enables chaining multiple assertions on an . -/// -public class Continuation -{ - private readonly AssertionScope sourceScope; - private readonly bool continueAsserting; - - internal Continuation(AssertionScope sourceScope, bool continueAsserting) - { - this.sourceScope = sourceScope; - this.continueAsserting = continueAsserting; - } - - /// - /// Continuous the assertion chain if the previous assertion was successful. - /// - public IAssertionScope Then - { - get - { - return new ContinuedAssertionScope(sourceScope, continueAsserting); - } - } - - /// - /// Provides back-wards compatibility for code that expects to return a boolean. - /// - public static implicit operator bool(Continuation continuation) - { - return continuation.continueAsserting; - } -} diff --git a/Src/FluentAssertions/Execution/ContinuationOfGiven.cs b/Src/FluentAssertions/Execution/ContinuationOfGiven.cs deleted file mode 100644 index f080c83d08..0000000000 --- a/Src/FluentAssertions/Execution/ContinuationOfGiven.cs +++ /dev/null @@ -1,28 +0,0 @@ -namespace FluentAssertions.Execution; - -/// -/// Enables chaining multiple assertions from a call. -/// -public class ContinuationOfGiven -{ - private readonly bool succeeded; - - internal ContinuationOfGiven(GivenSelector parent, bool succeeded) - { - this.succeeded = succeeded; - Then = parent; - } - - /// - /// Continuous the assertion chain if the previous assertion was successful. - /// - public GivenSelector Then { get; } - - /// - /// Provides back-wards compatibility for code that expects to return a boolean. - /// - public static implicit operator bool(ContinuationOfGiven continuationOfGiven) - { - return continuationOfGiven.succeeded; - } -} diff --git a/Src/FluentAssertions/Execution/ContinuedAssertion.cs b/Src/FluentAssertions/Execution/ContinuedAssertion.cs deleted file mode 100644 index 1655e08cba..0000000000 --- a/Src/FluentAssertions/Execution/ContinuedAssertion.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System; - -namespace FluentAssertions.Execution; - -public class ContinuedAssertion : Assertion -{ - public ContinuedAssertion(IAssertion previousAssertion) - : base(previousAssertion) - { - } -} diff --git a/Src/FluentAssertions/Execution/ContinuedAssertionScope.cs b/Src/FluentAssertions/Execution/ContinuedAssertionScope.cs deleted file mode 100644 index 4b01cd9725..0000000000 --- a/Src/FluentAssertions/Execution/ContinuedAssertionScope.cs +++ /dev/null @@ -1,166 +0,0 @@ -using System; -using FluentAssertions.Formatting; - -namespace FluentAssertions.Execution; - -/// -/// Allows chaining multiple assertion scopes together using . -/// -/// -/// If the parent scope has captured a failed assertion, -/// this class ensures that successive assertions are no longer evaluated. -/// -public sealed class ContinuedAssertionScope : IAssertionScope -{ - private readonly AssertionScope predecessor; - private readonly bool continueAsserting; - - internal ContinuedAssertionScope(AssertionScope predecessor, bool continueAsserting) - { - this.predecessor = predecessor; - this.continueAsserting = continueAsserting; - } - - /// - public GivenSelector Given(Func selector) - { - if (continueAsserting) - { - return predecessor.Given(selector); - } - - return new GivenSelector(() => default, predecessor, continueAsserting: false); - } - - /// - public IAssertionScope ForCondition(bool condition) - { - if (continueAsserting) - { - return predecessor.ForCondition(condition); - } - - return this; - } - - /// - public IAssertionScope ForConstraint(OccurrenceConstraint constraint, int actualOccurrences) - { - if (continueAsserting) - { - return predecessor.ForConstraint(constraint, actualOccurrences); - } - - return this; - } - - /// - public Continuation FailWith(string message) - { - if (continueAsserting) - { - return predecessor.FailWith(message); - } - - return new Continuation(predecessor, continueAsserting: false); - } - - /// - public Continuation FailWith(string message, params Func[] argProviders) - { - if (continueAsserting) - { - return predecessor.FailWith(message, argProviders); - } - - return new Continuation(predecessor, continueAsserting: false); - } - - /// - public Continuation FailWith(Func failReasonFunc) - { - if (continueAsserting) - { - return predecessor.FailWith(failReasonFunc); - } - - return new Continuation(predecessor, continueAsserting: false); - } - - /// - public Continuation FailWith(string message, params object[] args) - { - if (continueAsserting) - { - return predecessor.FailWith(message, args); - } - - return new Continuation(predecessor, continueAsserting: false); - } - - /// - public IAssertionScope BecauseOf(string because, params object[] becauseArgs) - { - if (continueAsserting) - { - return predecessor.BecauseOf(because, becauseArgs); - } - - return this; - } - - /// - public Continuation ClearExpectation() - { - predecessor.ClearExpectation(); - - return new Continuation(predecessor, continueAsserting); - } - - /// - public IAssertionScope WithExpectation(string message, params object[] args) - { - if (continueAsserting) - { - return predecessor.WithExpectation(message, args); - } - - return this; - } - - /// - public IAssertionScope WithDefaultIdentifier(string identifier) - { - if (continueAsserting) - { - return predecessor.WithDefaultIdentifier(identifier); - } - - return this; - } - - /// - public IAssertionScope UsingLineBreaks => predecessor.UsingLineBreaks; - - public ContextDataItems ContextData { get; } - - public FormattingOptions FormattingOptions { get; } - - /// - public string[] Discard() - { - return predecessor.Discard(); - } - - public void AddPreFormattedFailure(string formattedFailureMessage) => throw new NotSupportedException(); - - public void AddReportable(string key, Func valueFunc) => throw new NotSupportedException(); - - public void AddReportable(string key, string value) => throw new NotSupportedException(); - - /// - public void Dispose() - { - predecessor.Dispose(); - } -} diff --git a/Src/FluentAssertions/Execution/GivenSelector.cs b/Src/FluentAssertions/Execution/GivenSelector.cs deleted file mode 100644 index b2d776fb26..0000000000 --- a/Src/FluentAssertions/Execution/GivenSelector.cs +++ /dev/null @@ -1,108 +0,0 @@ -using System; -using System.Linq; -using FluentAssertions.Common; - -namespace FluentAssertions.Execution; - -/// -/// Represents a chaining object returned from to continue the assertion using -/// an object returned by a selector. -/// -public class GivenSelector -{ - private readonly AssertionScope predecessor; - private readonly T subject; - - private bool continueAsserting; - - internal GivenSelector(Func selector, AssertionScope predecessor, bool continueAsserting) - { - this.predecessor = predecessor; - this.continueAsserting = continueAsserting; - - subject = continueAsserting ? selector() : default; - } - - /// - /// Specify the condition that must be satisfied upon the subject selected through a prior selector. - /// - /// - /// If the assertion will be treated as successful and no exceptions will be thrown. - /// - /// - /// The condition will not be evaluated if the prior assertion failed, - /// nor will throw any exceptions. - /// - /// is . - public GivenSelector ForCondition(Func predicate) - { - Guard.ThrowIfArgumentIsNull(predicate); - - if (continueAsserting) - { - predecessor.ForCondition(predicate(subject)); - } - - return this; - } - - /// - /// The will not be invoked if the prior assertion failed, - /// nor will throw any exceptions. - /// - /// - /// is . - public GivenSelector Given(Func selector) - { - Guard.ThrowIfArgumentIsNull(selector); - - return new GivenSelector(() => selector(subject), predecessor, continueAsserting); - } - - /// - public ContinuationOfGiven FailWith(string message) - { - return FailWith(message, Array.Empty()); - } - - /// - /// - /// The will not be invoked if the prior assertion failed, - /// nor will throw any exceptions. - /// - /// - public ContinuationOfGiven FailWith(string message, params Func[] args) - { - if (continueAsserting) - { - object[] mappedArguments = args.Select(a => a(subject)).ToArray(); - return FailWith(message, mappedArguments); - } - - return new ContinuationOfGiven(this, succeeded: false); - } - - /// - /// - /// The will not be invoked if the prior assertion failed, - /// nor will throw any exceptions. - /// - /// - public ContinuationOfGiven FailWith(string message, params object[] args) - { - if (continueAsserting) - { - continueAsserting = predecessor.FailWith(message, args); - return new ContinuationOfGiven(this, continueAsserting); - } - - return new ContinuationOfGiven(this, succeeded: false); - } - - /// - public ContinuationOfGiven ClearExpectation() - { - predecessor.ClearExpectation(); - return new ContinuationOfGiven(this, continueAsserting); - } -} diff --git a/Src/FluentAssertions/Execution/IAssertion.cs b/Src/FluentAssertions/Execution/IAssertion.cs deleted file mode 100644 index c94c1e6dcd..0000000000 --- a/Src/FluentAssertions/Execution/IAssertion.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; - -namespace FluentAssertions.Execution; - -public interface IAssertion -{ - Func GetCurrentScope { get; } - - bool Succeeded { get; } - - Func GetCallerIdentifier { get; } - - void ForCondition(bool predicate); - - void FailWith(string message, object[] args); - - Func Reason { get; } -} diff --git a/Src/FluentAssertions/Execution/IAssertionScope.cs b/Src/FluentAssertions/Execution/IAssertionScope.cs deleted file mode 100644 index 7dd4905972..0000000000 --- a/Src/FluentAssertions/Execution/IAssertionScope.cs +++ /dev/null @@ -1,210 +0,0 @@ -using System; -using FluentAssertions.Formatting; - -namespace FluentAssertions.Execution; - -public interface IAssertionScope : IDisposable -{ - /// - /// Allows to safely select the subject for successive assertions. - /// - /// - /// Selector which result is passed to successive calls to . - /// - GivenSelector Given(Func selector); - - /// - /// Specify the condition that must be satisfied. - /// - /// - /// If the assertion will be treated as successful and no exceptions will be thrown. - /// - IAssertionScope ForCondition(bool condition); - - /// - /// Makes assertion fail when does not match . - /// - /// The occurrence description in natural language could then be inserted in failure message by using - /// {expectedOccurrence} placeholder in message parameters of and its - /// overloaded versions. - /// - /// - /// defining the number of expected occurrences. - /// The number of actual occurrences. - IAssertionScope ForConstraint(OccurrenceConstraint constraint, int actualOccurrences); - - /// - /// Sets the failure message when the assertion is not met, or completes the failure message set to a prior call to - /// . - /// - /// - /// Messages may contain a few specialized placeholders. For instance, {reason} will be replaced with the reason - /// of the assertion as passed to . - /// - /// Other named placeholders will be replaced with the scope data passed through - /// and . - /// - /// - /// Finally, a description of the current subject can be passed through the {context:description} placeholder. - /// This is used in the message if no explicit context is specified through the constructor. - /// - /// - /// If an expectation was set through a prior call to , then the failure - /// message is appended to that expectation. - /// - /// - /// The format string that represents the failure message. - Continuation FailWith(string message); - - /// - /// Sets the failure message when the assertion is not met, or completes the failure message set to a prior call to - /// . - /// will not be called unless the assertion is not met. - /// - /// Function returning object on demand. Called only when the assertion is not met. - Continuation FailWith(Func failReasonFunc); - - /// - /// Sets the failure message when the assertion is not met, or completes the failure message set to a prior call to - /// . - /// - /// - /// In addition to the numbered -style placeholders, messages may contain a - /// few specialized placeholders as well. For instance, {reason} will be replaced with the reason of the - /// assertion as passed to . - /// - /// Other named placeholders will be replaced with the scope data passed through - /// and . - /// - /// - /// Finally, a description of the current subject can be passed through the {context:description} placeholder. - /// This is used in the message if no explicit context is specified through the constructor. - /// - /// - /// Note that only 10 are supported in combination with a {reason}. - /// - /// - /// If an expectation was set through a prior call to , then the failure - /// message is appended to that expectation. - /// - /// - /// The format string that represents the failure message. - /// Optional arguments to any numbered placeholders. - Continuation FailWith(string message, params object[] args); - - /// - /// Sets the failure message when the assertion is not met, or completes the failure message set to a prior call to - /// , - /// but postpones evaluation of the formatting arguments until the assertion really fails. - /// - /// - /// In addition to the numbered -style placeholders, messages may contain a - /// few specialized placeholders as well. For instance, {reason} will be replaced with the reason of the - /// assertion as passed to . - /// - /// Other named placeholders will be replaced with the scope data passed through - /// and . - /// - /// - /// Finally, a description of the current subject can be passed through the {context:description} placeholder. - /// This is used in the message if no explicit context is specified through the constructor. - /// - /// - /// Note that only 10 are supported in combination with a {reason}. - /// - /// - /// If an expectation was set through a prior call to , then the failure - /// message is appended to that expectation. - /// - /// - /// The format string that represents the failure message. - /// Optional lazily evaluated arguments to any numbered placeholders - public Continuation FailWith(string message, params Func[] argProviders); - - /// - /// Specify the reason why you expect the condition to be . - /// - /// - /// A formatted phrase compatible with explaining why the condition should - /// be satisfied. If the phrase does not start with the word because, it is prepended to the message. - /// - /// If the format of or is not compatible with - /// , then a warning message is returned instead. - /// - /// - /// - /// Zero or more values to use for filling in any compatible placeholders. - /// - IAssertionScope BecauseOf(string because, params object[] becauseArgs); - - /// - /// Clears the expectation set by . - /// - // SMELL: It would be better to give the expectation an explicit scope, but that would be a breaking change. - Continuation ClearExpectation(); - - /// - /// Sets the expectation part of the failure message when the assertion is not met. - /// - /// - /// In addition to the numbered -style placeholders, messages may contain a - /// few specialized placeholders as well. For instance, {reason} will be replaced with the reason of the - /// assertion as passed to . - /// - /// Other named placeholders will be replaced with the scope data passed through - /// and . - /// - /// - /// Finally, a description of the current subject can be passed through the {context:description} placeholder. - /// This is used in the message if no explicit context is specified through the constructor. - /// - /// - /// Note that only 10 are supported in combination with a {reason}. - /// - /// - /// The format string that represents the failure message. - /// Optional arguments to any numbered placeholders. - IAssertionScope WithExpectation(string message, params object[] args); - - /// - /// Defines the name of the subject in case this cannot be extracted from the source code. - /// - IAssertionScope WithDefaultIdentifier(string identifier); - - /// - /// Forces the formatters, that support it, to add the necessary line breaks. - /// - /// - /// This is just shorthand for modifying the property. - /// - IAssertionScope UsingLineBreaks { get; } - - ContextDataItems ContextData { get; } - - /// - /// Exposes the options the scope will use for formatting objects in case an assertion fails. - /// - FormattingOptions FormattingOptions { get; } - - /// - /// Discards and returns the failures that happened up to now. - /// - string[] Discard(); - - /// - /// Adds a pre-formatted failure message to the current scope. - /// - void AddPreFormattedFailure(string formattedFailureMessage); - - /// - /// Adds some information to the assertion scope that will be included in the message - /// that is emitted if an assertion fails. The value is only calculated on failure. - /// - void AddReportable(string key, Func valueFunc); - - /// - /// Adds some information to the assertion scope that will be included in the message - /// that is emitted if an assertion fails. - /// - void AddReportable(string key, string value); -} diff --git a/Src/FluentAssertions/Execution/NewContinuation.cs b/Src/FluentAssertions/Execution/NewContinuation.cs index fbf412f6c0..6e2d804f1f 100644 --- a/Src/FluentAssertions/Execution/NewContinuation.cs +++ b/Src/FluentAssertions/Execution/NewContinuation.cs @@ -4,23 +4,23 @@ /// Enables chaining multiple assertions on an . /// public class NewContinuation - where TAssertion : Assertion + where TAssertion : AssertionChain { - private readonly IAssertion assertion; + private readonly AssertionChain assertionChain; - internal NewContinuation(IAssertion assertion) + internal NewContinuation(AssertionChain assertionChain) { - this.assertion = assertion; + this.assertionChain = assertionChain; } /// /// Continuous the assertion chain if the previous assertion was successful. /// - public ContinuedAssertion Then + public AssertionChain Then { get { - return new ContinuedAssertion(assertion); + return assertionChain; } } } diff --git a/Src/FluentAssertions/Execution/NewContinuationOfGiven.cs b/Src/FluentAssertions/Execution/NewContinuationOfGiven.cs index ecb3042cc8..d1acf11998 100644 --- a/Src/FluentAssertions/Execution/NewContinuationOfGiven.cs +++ b/Src/FluentAssertions/Execution/NewContinuationOfGiven.cs @@ -1,7 +1,7 @@ namespace FluentAssertions.Execution; /// -/// Enables chaining multiple assertions from a call. +/// Enables chaining multiple assertions from a call. /// public class NewContinuationOfGiven { diff --git a/Src/FluentAssertions/Execution/NewGivenSelector.cs b/Src/FluentAssertions/Execution/NewGivenSelector.cs index 4790a2dcc8..32f4783274 100644 --- a/Src/FluentAssertions/Execution/NewGivenSelector.cs +++ b/Src/FluentAssertions/Execution/NewGivenSelector.cs @@ -5,22 +5,22 @@ namespace FluentAssertions.Execution; /// -/// Represents a chaining object returned from to continue the assertion using +/// Represents a chaining object returned from to continue the assertion using /// an object returned by a selector. /// public class NewGivenSelector { - private readonly IAssertion previousAssertion; + private readonly AssertionChain previousAssertionChain; private readonly T selector; - internal NewGivenSelector(Func selector, IAssertion previousAssertion) + internal NewGivenSelector(Func selector, AssertionChain previousAssertionChain) { - this.previousAssertion = previousAssertion; + this.previousAssertionChain = previousAssertionChain; - this.selector = previousAssertion.Succeeded ? selector() : default; + this.selector = previousAssertionChain.Succeeded ? selector() : default; } - public bool Succeeded => previousAssertion.Succeeded; + public bool Succeeded => previousAssertionChain.Succeeded; /// /// Specify the condition that must be satisfied upon the subject selected through a prior selector. @@ -37,42 +37,29 @@ public NewGivenSelector ForCondition(Func predicate) { Guard.ThrowIfArgumentIsNull(predicate); - if (previousAssertion.Succeeded) + if (previousAssertionChain.Succeeded) { - previousAssertion.ForCondition(predicate(selector)); + previousAssertionChain.ForCondition(predicate(selector)); } return this; } - /// - /// The will not be invoked if the prior assertion failed, - /// nor will throw any exceptions. - /// - /// - /// is . public NewGivenSelector Given(Func selector) { Guard.ThrowIfArgumentIsNull(selector); - return new NewGivenSelector(() => selector(this.selector), previousAssertion); + return new NewGivenSelector(() => selector(this.selector), previousAssertionChain); } - /// public NewContinuationOfGiven FailWith(string message) { return FailWith(message, Array.Empty()); } - /// - /// - /// The will not be invoked if the prior assertion failed, - /// nor will throw any exceptions. - /// - /// public NewContinuationOfGiven FailWith(string message, params Func[] args) { - if (previousAssertion.Succeeded) + if (previousAssertionChain.Succeeded) { object[] mappedArguments = args.Select(a => a(selector)).ToArray(); return FailWith(message, mappedArguments); @@ -81,17 +68,11 @@ public NewContinuationOfGiven FailWith(string message, params Func return new NewContinuationOfGiven(this); } - /// - /// - /// The will not be invoked if the prior assertion failed, - /// nor will throw any exceptions. - /// - /// public NewContinuationOfGiven FailWith(string message, params object[] args) { - if (previousAssertion.Succeeded) + if (previousAssertionChain.Succeeded) { - previousAssertion.FailWith(message, args); + previousAssertionChain.FailWith(message, args); return new NewContinuationOfGiven(this); } diff --git a/Src/FluentAssertions/Formatting/Formatter.cs b/Src/FluentAssertions/Formatting/Formatter.cs index c87add95ed..520715c6c0 100644 --- a/Src/FluentAssertions/Formatting/Formatter.cs +++ b/Src/FluentAssertions/Formatting/Formatter.cs @@ -212,7 +212,7 @@ public bool TryPush(string path, object value) string fullPath = GetFullPath(); var reference = new ObjectReference(value, fullPath); - return !tracker.IsCyclicReference(reference, CyclicReferenceHandling.Ignore); + return !tracker.IsCyclicReference(reference); } private string GetFullPath() => string.Join(".", pathStack.Reverse()); diff --git a/Src/FluentAssertions/Numeric/ByteAssertions.cs b/Src/FluentAssertions/Numeric/ByteAssertions.cs index 5d3dcf7ec5..ccd7399bcf 100644 --- a/Src/FluentAssertions/Numeric/ByteAssertions.cs +++ b/Src/FluentAssertions/Numeric/ByteAssertions.cs @@ -10,8 +10,8 @@ namespace FluentAssertions.Numeric; [DebuggerNonUserCode] internal class ByteAssertions : NumericAssertions { - internal ByteAssertions(byte value, Assertion assertion) - : base(value, assertion) + internal ByteAssertions(byte value, AssertionChain assertionChain) + : base(value, assertionChain) { } diff --git a/Src/FluentAssertions/Numeric/ComparableTypeAssertions.cs b/Src/FluentAssertions/Numeric/ComparableTypeAssertions.cs index 22b5601e10..7c859acb7e 100644 --- a/Src/FluentAssertions/Numeric/ComparableTypeAssertions.cs +++ b/Src/FluentAssertions/Numeric/ComparableTypeAssertions.cs @@ -15,8 +15,8 @@ namespace FluentAssertions.Numeric; [DebuggerNonUserCode] public class ComparableTypeAssertions : ComparableTypeAssertions> { - public ComparableTypeAssertions(IComparable value, Assertion assertion) - : base(value, assertion) + public ComparableTypeAssertions(IComparable value, AssertionChain assertionChain) + : base(value, assertionChain) { } } @@ -29,12 +29,12 @@ public class ComparableTypeAssertions : ReferenceTypeAssertions< where TAssertions : ComparableTypeAssertions { private const int Equal = 0; - private readonly Assertion assertion; + private readonly AssertionChain assertionChain; - public ComparableTypeAssertions(IComparable value, Assertion assertion) - : base(value, assertion) + public ComparableTypeAssertions(IComparable value, AssertionChain assertionChain) + : base(value, assertionChain) { - this.assertion = assertion; + this.assertionChain = assertionChain; } /// @@ -52,7 +52,7 @@ public ComparableTypeAssertions(IComparable value, Assertion assertion) /// public AndConstraint Be(T expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Equals(Subject, expected)) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:object} to be equal to {0}{reason}, but found {1}.", expected, Subject); @@ -146,7 +146,7 @@ public AndConstraint Be(T expected, string because = "", params obj /// public AndConstraint NotBe(T unexpected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(!Equals(Subject, unexpected)) .BecauseOf(because, becauseArgs) .FailWith("Did not expect {context:object} to be equal to {0}{reason}.", unexpected); @@ -170,7 +170,7 @@ public AndConstraint NotBe(T unexpected, string because = "", param /// public AndConstraint BeRankedEquallyTo(T expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject.CompareTo(expected) == Equal) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:object} {0} to be ranked as equal to {1}{reason}.", Subject, expected); @@ -194,7 +194,7 @@ public AndConstraint BeRankedEquallyTo(T expected, string because = /// public AndConstraint NotBeRankedEquallyTo(T unexpected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject.CompareTo(unexpected) != Equal) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:object} {0} not to be ranked as equal to {1}{reason}.", Subject, unexpected); @@ -217,7 +217,7 @@ public AndConstraint NotBeRankedEquallyTo(T unexpected, string beca /// public AndConstraint BeLessThan(T expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject.CompareTo(expected) < Equal) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:object} {0} to be less than {1}{reason}.", Subject, expected); @@ -240,7 +240,7 @@ public AndConstraint BeLessThan(T expected, string because = "", pa /// public AndConstraint BeLessThanOrEqualTo(T expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject.CompareTo(expected) <= Equal) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:object} {0} to be less than or equal to {1}{reason}.", Subject, expected); @@ -263,7 +263,7 @@ public AndConstraint BeLessThanOrEqualTo(T expected, string because /// public AndConstraint BeGreaterThan(T expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject.CompareTo(expected) > Equal) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:object} {0} to be greater than {1}{reason}.", Subject, expected); @@ -286,7 +286,7 @@ public AndConstraint BeGreaterThan(T expected, string because = "", /// public AndConstraint BeGreaterThanOrEqualTo(T expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject.CompareTo(expected) >= Equal) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:object} {0} to be greater than or equal to {1}{reason}.", Subject, expected); @@ -316,7 +316,7 @@ public AndConstraint BeGreaterThanOrEqualTo(T expected, string beca public AndConstraint BeInRange(T minimumValue, T maximumValue, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject.CompareTo(minimumValue) >= Equal && Subject.CompareTo(maximumValue) <= Equal) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:object} to be between {0} and {1}{reason}, but found {2}.", @@ -347,7 +347,7 @@ public AndConstraint BeGreaterThanOrEqualTo(T expected, string beca public AndConstraint NotBeInRange(T minimumValue, T maximumValue, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(!(Subject.CompareTo(minimumValue) >= Equal && Subject.CompareTo(maximumValue) <= Equal)) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:object} to not be between {0} and {1}{reason}, but found {2}.", @@ -383,7 +383,7 @@ public AndConstraint BeOneOf(params T[] validValues) public AndConstraint BeOneOf(IEnumerable validValues, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(validValues.Any(val => Equals(Subject, val))) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:object} to be one of {0}{reason}, but found {1}.", validValues, Subject); diff --git a/Src/FluentAssertions/Numeric/DecimalAssertions.cs b/Src/FluentAssertions/Numeric/DecimalAssertions.cs index 6e77d4dca1..aa31679f46 100644 --- a/Src/FluentAssertions/Numeric/DecimalAssertions.cs +++ b/Src/FluentAssertions/Numeric/DecimalAssertions.cs @@ -11,8 +11,8 @@ namespace FluentAssertions.Numeric; [DebuggerNonUserCode] internal class DecimalAssertions : NumericAssertions { - internal DecimalAssertions(decimal value, Assertion assertion) - : base(value, assertion) + internal DecimalAssertions(decimal value, AssertionChain assertionChain) + : base(value, assertionChain) { } diff --git a/Src/FluentAssertions/Numeric/DoubleAssertions.cs b/Src/FluentAssertions/Numeric/DoubleAssertions.cs index e73225f679..0596191408 100644 --- a/Src/FluentAssertions/Numeric/DoubleAssertions.cs +++ b/Src/FluentAssertions/Numeric/DoubleAssertions.cs @@ -10,8 +10,8 @@ namespace FluentAssertions.Numeric; [DebuggerNonUserCode] internal class DoubleAssertions : NumericAssertions { - internal DoubleAssertions(double value, Assertion assertion) - : base(value, assertion) + internal DoubleAssertions(double value, AssertionChain assertionChain) + : base(value, assertionChain) { } diff --git a/Src/FluentAssertions/Numeric/Int16Assertions.cs b/Src/FluentAssertions/Numeric/Int16Assertions.cs index 4a6ee0185d..7d7b9c2102 100644 --- a/Src/FluentAssertions/Numeric/Int16Assertions.cs +++ b/Src/FluentAssertions/Numeric/Int16Assertions.cs @@ -10,8 +10,8 @@ namespace FluentAssertions.Numeric; [DebuggerNonUserCode] internal class Int16Assertions : NumericAssertions { - internal Int16Assertions(short value, Assertion assertion) - : base(value, assertion) + internal Int16Assertions(short value, AssertionChain assertionChain) + : base(value, assertionChain) { } diff --git a/Src/FluentAssertions/Numeric/Int32Assertions.cs b/Src/FluentAssertions/Numeric/Int32Assertions.cs index ee155b6455..cfcb25f472 100644 --- a/Src/FluentAssertions/Numeric/Int32Assertions.cs +++ b/Src/FluentAssertions/Numeric/Int32Assertions.cs @@ -10,8 +10,8 @@ namespace FluentAssertions.Numeric; [DebuggerNonUserCode] internal class Int32Assertions : NumericAssertions { - internal Int32Assertions(int value, Assertion assertion) - : base(value, assertion) + internal Int32Assertions(int value, AssertionChain assertionChain) + : base(value, assertionChain) { } diff --git a/Src/FluentAssertions/Numeric/Int64Assertions.cs b/Src/FluentAssertions/Numeric/Int64Assertions.cs index 48207a2975..c733dd294e 100644 --- a/Src/FluentAssertions/Numeric/Int64Assertions.cs +++ b/Src/FluentAssertions/Numeric/Int64Assertions.cs @@ -10,8 +10,8 @@ namespace FluentAssertions.Numeric; [DebuggerNonUserCode] internal class Int64Assertions : NumericAssertions { - internal Int64Assertions(long value, Assertion assertion) - : base(value, assertion) + internal Int64Assertions(long value, AssertionChain assertionChain) + : base(value, assertionChain) { } diff --git a/Src/FluentAssertions/Numeric/NullableByteAssertions.cs b/Src/FluentAssertions/Numeric/NullableByteAssertions.cs index 8a1069d7f8..9fa6a4c4f0 100644 --- a/Src/FluentAssertions/Numeric/NullableByteAssertions.cs +++ b/Src/FluentAssertions/Numeric/NullableByteAssertions.cs @@ -10,8 +10,8 @@ namespace FluentAssertions.Numeric; [DebuggerNonUserCode] internal class NullableByteAssertions : NullableNumericAssertions { - internal NullableByteAssertions(byte? value, Assertion assertion) - : base(value, assertion) + internal NullableByteAssertions(byte? value, AssertionChain assertionChain) + : base(value, assertionChain) { } diff --git a/Src/FluentAssertions/Numeric/NullableDecimalAssertions.cs b/Src/FluentAssertions/Numeric/NullableDecimalAssertions.cs index ebfdaeb8c4..d5b27880c6 100644 --- a/Src/FluentAssertions/Numeric/NullableDecimalAssertions.cs +++ b/Src/FluentAssertions/Numeric/NullableDecimalAssertions.cs @@ -11,8 +11,8 @@ namespace FluentAssertions.Numeric; [DebuggerNonUserCode] internal class NullableDecimalAssertions : NullableNumericAssertions { - internal NullableDecimalAssertions(decimal? value, Assertion assertion) - : base(value, assertion) + internal NullableDecimalAssertions(decimal? value, AssertionChain assertionChain) + : base(value, assertionChain) { } diff --git a/Src/FluentAssertions/Numeric/NullableDoubleAssertions.cs b/Src/FluentAssertions/Numeric/NullableDoubleAssertions.cs index 5cb74f7fe5..97af5f97bc 100644 --- a/Src/FluentAssertions/Numeric/NullableDoubleAssertions.cs +++ b/Src/FluentAssertions/Numeric/NullableDoubleAssertions.cs @@ -10,8 +10,8 @@ namespace FluentAssertions.Numeric; [DebuggerNonUserCode] internal class NullableDoubleAssertions : NullableNumericAssertions { - internal NullableDoubleAssertions(double? value, Assertion assertion) - : base(value, assertion) + internal NullableDoubleAssertions(double? value, AssertionChain assertionChain) + : base(value, assertionChain) { } diff --git a/Src/FluentAssertions/Numeric/NullableInt16Assertions.cs b/Src/FluentAssertions/Numeric/NullableInt16Assertions.cs index 0c41497dd8..802d0c864d 100644 --- a/Src/FluentAssertions/Numeric/NullableInt16Assertions.cs +++ b/Src/FluentAssertions/Numeric/NullableInt16Assertions.cs @@ -10,8 +10,8 @@ namespace FluentAssertions.Numeric; [DebuggerNonUserCode] internal class NullableInt16Assertions : NullableNumericAssertions { - internal NullableInt16Assertions(short? value, Assertion assertion) - : base(value, assertion) + internal NullableInt16Assertions(short? value, AssertionChain assertionChain) + : base(value, assertionChain) { } diff --git a/Src/FluentAssertions/Numeric/NullableInt32Assertions.cs b/Src/FluentAssertions/Numeric/NullableInt32Assertions.cs index 0d8a9d65c4..7b2400568f 100644 --- a/Src/FluentAssertions/Numeric/NullableInt32Assertions.cs +++ b/Src/FluentAssertions/Numeric/NullableInt32Assertions.cs @@ -10,8 +10,8 @@ namespace FluentAssertions.Numeric; [DebuggerNonUserCode] internal class NullableInt32Assertions : NullableNumericAssertions { - internal NullableInt32Assertions(int? value, Assertion assertion) - : base(value, assertion) + internal NullableInt32Assertions(int? value, AssertionChain assertionChain) + : base(value, assertionChain) { } diff --git a/Src/FluentAssertions/Numeric/NullableInt64Assertions.cs b/Src/FluentAssertions/Numeric/NullableInt64Assertions.cs index 7aee2c88cf..1e5e04d386 100644 --- a/Src/FluentAssertions/Numeric/NullableInt64Assertions.cs +++ b/Src/FluentAssertions/Numeric/NullableInt64Assertions.cs @@ -10,8 +10,8 @@ namespace FluentAssertions.Numeric; [DebuggerNonUserCode] internal class NullableInt64Assertions : NullableNumericAssertions { - internal NullableInt64Assertions(long? value, Assertion assertion) - : base(value, assertion) + internal NullableInt64Assertions(long? value, AssertionChain assertionChain) + : base(value, assertionChain) { } diff --git a/Src/FluentAssertions/Numeric/NullableNumericAssertions.cs b/Src/FluentAssertions/Numeric/NullableNumericAssertions.cs index c7b85272dc..62de8b0cd3 100644 --- a/Src/FluentAssertions/Numeric/NullableNumericAssertions.cs +++ b/Src/FluentAssertions/Numeric/NullableNumericAssertions.cs @@ -10,8 +10,8 @@ namespace FluentAssertions.Numeric; public class NullableNumericAssertions : NullableNumericAssertions> where T : struct, IComparable { - public NullableNumericAssertions(T? value, Assertion assertion) - : base(value, assertion) + public NullableNumericAssertions(T? value, AssertionChain assertionChain) + : base(value, assertionChain) { } } @@ -21,12 +21,12 @@ public class NullableNumericAssertions : NumericAssertions where TAssertions : NullableNumericAssertions { - private readonly Assertion assertion; + private readonly AssertionChain assertionChain; - public NullableNumericAssertions(T? value, Assertion assertion) - : base(value, assertion) + public NullableNumericAssertions(T? value, AssertionChain assertionChain) + : base(value, assertionChain) { - this.assertion = assertion; + this.assertionChain = assertionChain; } /// @@ -41,7 +41,7 @@ public NullableNumericAssertions(T? value, Assertion assertion) /// public AndConstraint HaveValue(string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject.HasValue) .BecauseOf(because, becauseArgs) .FailWith("Expected a value{reason}."); @@ -76,7 +76,7 @@ public AndConstraint NotBeNull(string because = "", params object[] /// public AndConstraint NotHaveValue(string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(!Subject.HasValue) .BecauseOf(because, becauseArgs) .FailWith("Did not expect a value{reason}, but found {0}.", Subject); @@ -119,7 +119,7 @@ public AndConstraint BeNull(string because = "", params object[] be { Guard.ThrowIfArgumentIsNull(predicate); - assertion + assertionChain .ForCondition(predicate.Compile()(Subject)) .BecauseOf(because, becauseArgs) .FailWith("Expected value to match {0}{reason}, but found {1}.", predicate, Subject); diff --git a/Src/FluentAssertions/Numeric/NullableSByteAssertions.cs b/Src/FluentAssertions/Numeric/NullableSByteAssertions.cs index bbcff89c08..e83e756404 100644 --- a/Src/FluentAssertions/Numeric/NullableSByteAssertions.cs +++ b/Src/FluentAssertions/Numeric/NullableSByteAssertions.cs @@ -10,8 +10,8 @@ namespace FluentAssertions.Numeric; [DebuggerNonUserCode] internal class NullableSByteAssertions : NullableNumericAssertions { - internal NullableSByteAssertions(sbyte? value, Assertion assertion) - : base(value, assertion) + internal NullableSByteAssertions(sbyte? value, AssertionChain assertionChain) + : base(value, assertionChain) { } diff --git a/Src/FluentAssertions/Numeric/NullableSingleAssertions.cs b/Src/FluentAssertions/Numeric/NullableSingleAssertions.cs index caecdc838f..3a82df8969 100644 --- a/Src/FluentAssertions/Numeric/NullableSingleAssertions.cs +++ b/Src/FluentAssertions/Numeric/NullableSingleAssertions.cs @@ -10,8 +10,8 @@ namespace FluentAssertions.Numeric; [DebuggerNonUserCode] internal class NullableSingleAssertions : NullableNumericAssertions { - internal NullableSingleAssertions(float? value, Assertion assertion) - : base(value, assertion) + internal NullableSingleAssertions(float? value, AssertionChain assertionChain) + : base(value, assertionChain) { } diff --git a/Src/FluentAssertions/Numeric/NullableUInt16Assertions.cs b/Src/FluentAssertions/Numeric/NullableUInt16Assertions.cs index b7381f64a3..0df417d5e2 100644 --- a/Src/FluentAssertions/Numeric/NullableUInt16Assertions.cs +++ b/Src/FluentAssertions/Numeric/NullableUInt16Assertions.cs @@ -10,8 +10,8 @@ namespace FluentAssertions.Numeric; [DebuggerNonUserCode] internal class NullableUInt16Assertions : NullableNumericAssertions { - internal NullableUInt16Assertions(ushort? value, Assertion assertion) - : base(value, assertion) + internal NullableUInt16Assertions(ushort? value, AssertionChain assertionChain) + : base(value, assertionChain) { } diff --git a/Src/FluentAssertions/Numeric/NullableUInt32Assertions.cs b/Src/FluentAssertions/Numeric/NullableUInt32Assertions.cs index 3c270df9a9..69b94a8086 100644 --- a/Src/FluentAssertions/Numeric/NullableUInt32Assertions.cs +++ b/Src/FluentAssertions/Numeric/NullableUInt32Assertions.cs @@ -10,8 +10,8 @@ namespace FluentAssertions.Numeric; [DebuggerNonUserCode] internal class NullableUInt32Assertions : NullableNumericAssertions { - internal NullableUInt32Assertions(uint? value, Assertion assertion) - : base(value, assertion) + internal NullableUInt32Assertions(uint? value, AssertionChain assertionChain) + : base(value, assertionChain) { } diff --git a/Src/FluentAssertions/Numeric/NullableUInt64Assertions.cs b/Src/FluentAssertions/Numeric/NullableUInt64Assertions.cs index a41bac2641..6c36e3b703 100644 --- a/Src/FluentAssertions/Numeric/NullableUInt64Assertions.cs +++ b/Src/FluentAssertions/Numeric/NullableUInt64Assertions.cs @@ -10,8 +10,8 @@ namespace FluentAssertions.Numeric; [DebuggerNonUserCode] internal class NullableUInt64Assertions : NullableNumericAssertions { - internal NullableUInt64Assertions(ulong? value, Assertion assertion) - : base(value, assertion) + internal NullableUInt64Assertions(ulong? value, AssertionChain assertionChain) + : base(value, assertionChain) { } diff --git a/Src/FluentAssertions/Numeric/NumericAssertions.cs b/Src/FluentAssertions/Numeric/NumericAssertions.cs index 401292e762..d0f9ba70de 100644 --- a/Src/FluentAssertions/Numeric/NumericAssertions.cs +++ b/Src/FluentAssertions/Numeric/NumericAssertions.cs @@ -15,8 +15,8 @@ namespace FluentAssertions.Numeric; public class NumericAssertions : NumericAssertions> where T : struct, IComparable { - public NumericAssertions(T value, Assertion assertion) - : base(value, assertion) + public NumericAssertions(T value, AssertionChain assertionChain) + : base(value, assertionChain) { } } @@ -31,15 +31,15 @@ public class NumericAssertions where T : struct, IComparable where TAssertions : NumericAssertions { - public NumericAssertions(T value, Assertion assertion) - : this((T?)value, assertion) + public NumericAssertions(T value, AssertionChain assertionChain) + : this((T?)value, assertionChain) { } - private protected NumericAssertions(T? value, Assertion assertion) + private protected NumericAssertions(T? value, AssertionChain assertionChain) { Subject = value; - this.CurrentAssertion = assertion; + this.CurrentAssertionChain = assertionChain; } public T? Subject { get; } @@ -57,7 +57,7 @@ private protected NumericAssertions(T? value, Assertion assertion) /// public AndConstraint Be(T expected, string because = "", params object[] becauseArgs) { - CurrentAssertion + CurrentAssertionChain .ForCondition(Subject?.CompareTo(expected) == 0) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:value} to be {0}{reason}, but found {1}" + GenerateDifferenceMessage(expected), expected, @@ -79,7 +79,7 @@ public AndConstraint Be(T expected, string because = "", params obj /// public AndConstraint Be(T? expected, string because = "", params object[] becauseArgs) { - CurrentAssertion + CurrentAssertionChain .ForCondition(expected is { } value ? Subject?.CompareTo(value) == 0 : !Subject.HasValue) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:value} to be {0}{reason}, but found {1}" + GenerateDifferenceMessage(expected), expected, @@ -101,7 +101,7 @@ public AndConstraint Be(T? expected, string because = "", params ob /// public AndConstraint NotBe(T unexpected, string because = "", params object[] becauseArgs) { - CurrentAssertion + CurrentAssertionChain .ForCondition(Subject?.CompareTo(unexpected) != 0) .BecauseOf(because, becauseArgs) .FailWith("Did not expect {context:value} to be {0}{reason}.", unexpected); @@ -122,7 +122,7 @@ public AndConstraint NotBe(T unexpected, string because = "", param /// public AndConstraint NotBe(T? unexpected, string because = "", params object[] becauseArgs) { - CurrentAssertion + CurrentAssertionChain .ForCondition(unexpected is { } value ? Subject?.CompareTo(value) != 0 : Subject.HasValue) .BecauseOf(because, becauseArgs) .FailWith("Did not expect {context:value} to be {0}{reason}.", unexpected); @@ -142,7 +142,7 @@ public AndConstraint NotBe(T? unexpected, string because = "", para /// public AndConstraint BePositive(string because = "", params object[] becauseArgs) { - CurrentAssertion + CurrentAssertionChain .ForCondition(Subject?.CompareTo(default) > 0) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:value} to be positive{reason}, but found {0}.", Subject); @@ -162,7 +162,7 @@ public AndConstraint BePositive(string because = "", params object[ /// public AndConstraint BeNegative(string because = "", params object[] becauseArgs) { - CurrentAssertion + CurrentAssertionChain .ForCondition(Subject is { } value && !IsNaN(value) && value.CompareTo(default) < 0) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:value} to be negative{reason}, but found {0}.", Subject); @@ -188,7 +188,7 @@ public AndConstraint BeLessThan(T expected, string because = "", pa throw new ArgumentException("A value can never be less than NaN", nameof(expected)); } - CurrentAssertion + CurrentAssertionChain .ForCondition(Subject is { } value && !IsNaN(value) && value.CompareTo(expected) < 0) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:value} to be less than {0}{reason}, but found {1}" + GenerateDifferenceMessage(expected), @@ -216,7 +216,7 @@ public AndConstraint BeLessThan(T expected, string because = "", pa throw new ArgumentException("A value can never be less than or equal to NaN", nameof(expected)); } - CurrentAssertion + CurrentAssertionChain .ForCondition(Subject is { } value && !IsNaN(value) && value.CompareTo(expected) <= 0) .BecauseOf(because, becauseArgs) .FailWith( @@ -245,7 +245,7 @@ public AndConstraint BeLessThan(T expected, string because = "", pa throw new ArgumentException("A value can never be greater than NaN", nameof(expected)); } - CurrentAssertion + CurrentAssertionChain .ForCondition(Subject?.CompareTo(expected) > 0) .BecauseOf(because, becauseArgs) .FailWith( @@ -274,7 +274,7 @@ public AndConstraint BeLessThan(T expected, string because = "", pa throw new ArgumentException("A value can never be greater than or equal to a NaN", nameof(expected)); } - CurrentAssertion + CurrentAssertionChain .ForCondition(Subject?.CompareTo(expected) >= 0) .BecauseOf(because, becauseArgs) .FailWith( @@ -311,7 +311,7 @@ public AndConstraint BeLessThan(T expected, string because = "", pa throw new ArgumentException("A range cannot begin or end with NaN"); } - CurrentAssertion + CurrentAssertionChain .ForCondition(Subject is { } value && value.CompareTo(minimumValue) >= 0 && value.CompareTo(maximumValue) <= 0) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:value} to be between {0} and {1}{reason}, but found {2}.", @@ -347,7 +347,7 @@ public AndConstraint BeLessThan(T expected, string because = "", pa throw new ArgumentException("A range cannot begin or end with NaN"); } - CurrentAssertion + CurrentAssertionChain .ForCondition(Subject is { } value && !(value.CompareTo(minimumValue) >= 0 && value.CompareTo(maximumValue) <= 0)) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:value} to not be between {0} and {1}{reason}, but found {2}.", @@ -383,7 +383,7 @@ public AndConstraint BeOneOf(params T[] validValues) public AndConstraint BeOneOf(IEnumerable validValues, string because = "", params object[] becauseArgs) { - CurrentAssertion + CurrentAssertionChain .ForCondition(Subject is { } value && validValues.Contains(value)) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:value} to be one of {0}{reason}, but found {1}.", validValues, Subject); @@ -441,12 +441,12 @@ public AndConstraint NotBeOfType(Type unexpectedType, string becaus { Guard.ThrowIfArgumentIsNull(unexpectedType); - CurrentAssertion + CurrentAssertionChain .ForCondition(Subject.HasValue) .BecauseOf(because, becauseArgs) .FailWith("Expected type not to be " + unexpectedType + "{reason}, but found ."); - if (CurrentAssertion.Succeeded) + if (CurrentAssertionChain.Succeeded) { Subject.GetType().Should().NotBe(unexpectedType, because, becauseArgs); } @@ -474,7 +474,7 @@ public AndConstraint NotBeOfType(Type unexpectedType, string becaus { Guard.ThrowIfArgumentIsNull(predicate); - CurrentAssertion + CurrentAssertionChain .ForCondition(predicate.Compile()((T)Subject)) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:value} to match {0}{reason}, but found {1}.", predicate.Body, Subject); @@ -512,5 +512,5 @@ private string GenerateDifferenceMessage(T? expected) return difference is null ? noDifferenceMessage : $" (difference of {difference})."; } - public Assertion CurrentAssertion { get; } + public AssertionChain CurrentAssertionChain { get; } } diff --git a/Src/FluentAssertions/Numeric/SByteAssertions.cs b/Src/FluentAssertions/Numeric/SByteAssertions.cs index f1c796e7f2..7ac217e8a3 100644 --- a/Src/FluentAssertions/Numeric/SByteAssertions.cs +++ b/Src/FluentAssertions/Numeric/SByteAssertions.cs @@ -10,8 +10,8 @@ namespace FluentAssertions.Numeric; [DebuggerNonUserCode] internal class SByteAssertions : NumericAssertions { - internal SByteAssertions(sbyte value, Assertion assertion) - : base(value, assertion) + internal SByteAssertions(sbyte value, AssertionChain assertionChain) + : base(value, assertionChain) { } diff --git a/Src/FluentAssertions/Numeric/SingleAssertions.cs b/Src/FluentAssertions/Numeric/SingleAssertions.cs index 9f852ad1eb..2276b01334 100644 --- a/Src/FluentAssertions/Numeric/SingleAssertions.cs +++ b/Src/FluentAssertions/Numeric/SingleAssertions.cs @@ -10,8 +10,8 @@ namespace FluentAssertions.Numeric; [DebuggerNonUserCode] internal class SingleAssertions : NumericAssertions { - internal SingleAssertions(float value, Assertion assertion) - : base(value, assertion) + internal SingleAssertions(float value, AssertionChain assertionChain) + : base(value, assertionChain) { } diff --git a/Src/FluentAssertions/Numeric/UInt16Assertions.cs b/Src/FluentAssertions/Numeric/UInt16Assertions.cs index f6e4bb8786..c1672f1482 100644 --- a/Src/FluentAssertions/Numeric/UInt16Assertions.cs +++ b/Src/FluentAssertions/Numeric/UInt16Assertions.cs @@ -10,8 +10,8 @@ namespace FluentAssertions.Numeric; [DebuggerNonUserCode] internal class UInt16Assertions : NumericAssertions { - internal UInt16Assertions(ushort value, Assertion assertion) - : base(value, assertion) + internal UInt16Assertions(ushort value, AssertionChain assertionChain) + : base(value, assertionChain) { } diff --git a/Src/FluentAssertions/Numeric/UInt32Assertions.cs b/Src/FluentAssertions/Numeric/UInt32Assertions.cs index e158efcfc3..49bcaad48f 100644 --- a/Src/FluentAssertions/Numeric/UInt32Assertions.cs +++ b/Src/FluentAssertions/Numeric/UInt32Assertions.cs @@ -10,8 +10,8 @@ namespace FluentAssertions.Numeric; [DebuggerNonUserCode] internal class UInt32Assertions : NumericAssertions { - internal UInt32Assertions(uint value, Assertion assertion) - : base(value, assertion) + internal UInt32Assertions(uint value, AssertionChain assertionChain) + : base(value, assertionChain) { } diff --git a/Src/FluentAssertions/Numeric/UInt64Assertions.cs b/Src/FluentAssertions/Numeric/UInt64Assertions.cs index 9175bf0892..3060a1c012 100644 --- a/Src/FluentAssertions/Numeric/UInt64Assertions.cs +++ b/Src/FluentAssertions/Numeric/UInt64Assertions.cs @@ -10,8 +10,8 @@ namespace FluentAssertions.Numeric; [DebuggerNonUserCode] internal class UInt64Assertions : NumericAssertions { - internal UInt64Assertions(ulong value, Assertion assertion) - : base(value, assertion) + internal UInt64Assertions(ulong value, AssertionChain assertionChain) + : base(value, assertionChain) { } diff --git a/Src/FluentAssertions/NumericAssertionsExtensions.cs b/Src/FluentAssertions/NumericAssertionsExtensions.cs index b1f3443d84..0b514ea8f2 100644 --- a/Src/FluentAssertions/NumericAssertionsExtensions.cs +++ b/Src/FluentAssertions/NumericAssertionsExtensions.cs @@ -48,7 +48,7 @@ public static class NumericAssertionsExtensions maxValue = sbyte.MaxValue; } - FailIfValueOutsideBounds(parent.CurrentAssertion, + FailIfValueOutsideBounds(parent.CurrentAssertionChain, minValue <= actualValue && actualValue <= maxValue, nearbyValue, delta, actualValue, because, becauseArgs); @@ -91,7 +91,7 @@ public static class NumericAssertionsExtensions maxValue = byte.MaxValue; } - FailIfValueOutsideBounds(parent.CurrentAssertion, + FailIfValueOutsideBounds(parent.CurrentAssertionChain, minValue <= actualValue && actualValue <= maxValue, nearbyValue, delta, actualValue, because, becauseArgs); @@ -134,7 +134,7 @@ public static class NumericAssertionsExtensions maxValue = short.MaxValue; } - FailIfValueOutsideBounds(parent.CurrentAssertion, + FailIfValueOutsideBounds(parent.CurrentAssertionChain, minValue <= actualValue && actualValue <= maxValue, nearbyValue, delta, actualValue, because, becauseArgs); @@ -178,7 +178,7 @@ public static class NumericAssertionsExtensions maxValue = ushort.MaxValue; } - FailIfValueOutsideBounds(parent.CurrentAssertion, + FailIfValueOutsideBounds(parent.CurrentAssertionChain, minValue <= actualValue && actualValue <= maxValue, nearbyValue, delta, actualValue, because, becauseArgs); @@ -222,7 +222,7 @@ public static class NumericAssertionsExtensions maxValue = int.MaxValue; } - FailIfValueOutsideBounds(parent.CurrentAssertion, + FailIfValueOutsideBounds(parent.CurrentAssertionChain, minValue <= actualValue && actualValue <= maxValue, nearbyValue, delta, actualValue, because, @@ -268,7 +268,7 @@ public static class NumericAssertionsExtensions } FailIfValueOutsideBounds( - parent.CurrentAssertion, + parent.CurrentAssertionChain, minValue <= actualValue && actualValue <= maxValue, nearbyValue, delta, actualValue, because, becauseArgs); @@ -301,7 +301,7 @@ public static class NumericAssertionsExtensions long minValue = GetMinValue(nearbyValue, delta); long maxValue = GetMaxValue(nearbyValue, delta); - FailIfValueOutsideBounds(parent.CurrentAssertion, + FailIfValueOutsideBounds(parent.CurrentAssertionChain, minValue <= actualValue && actualValue <= maxValue, nearbyValue, delta, actualValue, because, becauseArgs); @@ -345,7 +345,7 @@ public static class NumericAssertionsExtensions maxValue = ulong.MaxValue; } - FailIfValueOutsideBounds(parent.CurrentAssertion, + FailIfValueOutsideBounds(parent.CurrentAssertionChain, minValue <= actualValue && actualValue <= maxValue, nearbyValue, delta, actualValue, because, becauseArgs); @@ -353,11 +353,11 @@ public static class NumericAssertionsExtensions return new AndConstraint>(parent); } - private static void FailIfValueOutsideBounds(Assertion assertion, bool valueWithinBounds, + private static void FailIfValueOutsideBounds(AssertionChain assertionChain, bool valueWithinBounds, TValue nearbyValue, TDelta delta, TValue actualValue, string because, object[] becauseArgs) { - assertion + assertionChain .ForCondition(valueWithinBounds) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:value} to be within {0} from {1}{reason}, but found {2}.", @@ -404,7 +404,7 @@ public static class NumericAssertionsExtensions maxValue = sbyte.MaxValue; } - FailIfValueInsideBounds(parent.CurrentAssertion, + FailIfValueInsideBounds(parent.CurrentAssertionChain, !(minValue <= actualValue && actualValue <= maxValue), distantValue, delta, actualValue, because, becauseArgs); @@ -449,7 +449,7 @@ public static class NumericAssertionsExtensions } FailIfValueInsideBounds( - parent.CurrentAssertion, + parent.CurrentAssertionChain, !(minValue <= actualValue && actualValue <= maxValue), distantValue, delta, actualValue, because, becauseArgs); @@ -494,7 +494,7 @@ public static class NumericAssertionsExtensions } FailIfValueInsideBounds( - parent.CurrentAssertion, + parent.CurrentAssertionChain, !(minValue <= actualValue && actualValue <= maxValue), distantValue, delta, actualValue, because, becauseArgs); @@ -538,7 +538,7 @@ public static class NumericAssertionsExtensions maxValue = ushort.MaxValue; } - FailIfValueInsideBounds(parent.CurrentAssertion, + FailIfValueInsideBounds(parent.CurrentAssertionChain, !(minValue <= actualValue && actualValue <= maxValue), distantValue, delta, actualValue, because, becauseArgs); @@ -583,7 +583,7 @@ public static class NumericAssertionsExtensions } FailIfValueInsideBounds( - parent.CurrentAssertion, + parent.CurrentAssertionChain, !(minValue <= actualValue && actualValue <= maxValue), distantValue, delta, actualValue, because, becauseArgs); @@ -627,7 +627,7 @@ public static class NumericAssertionsExtensions maxValue = uint.MaxValue; } - FailIfValueInsideBounds(parent.CurrentAssertion, + FailIfValueInsideBounds(parent.CurrentAssertionChain, !(minValue <= actualValue && actualValue <= maxValue), distantValue, delta, actualValue, because, becauseArgs); @@ -660,7 +660,7 @@ public static class NumericAssertionsExtensions long minValue = GetMinValue(distantValue, delta); long maxValue = GetMaxValue(distantValue, delta); - FailIfValueInsideBounds(parent.CurrentAssertion, + FailIfValueInsideBounds(parent.CurrentAssertionChain, !(minValue <= actualValue && actualValue <= maxValue), distantValue, delta, actualValue, because, becauseArgs); @@ -704,7 +704,7 @@ public static class NumericAssertionsExtensions maxValue = ulong.MaxValue; } - FailIfValueInsideBounds(parent.CurrentAssertion, + FailIfValueInsideBounds(parent.CurrentAssertionChain, !(minValue <= actualValue && actualValue <= maxValue), distantValue, delta, actualValue, @@ -715,12 +715,12 @@ public static class NumericAssertionsExtensions } private static void FailIfValueInsideBounds( - Assertion assertion, + AssertionChain assertionChain, bool valueOutsideBounds, TValue distantValue, TDelta delta, TValue actualValue, string because, object[] becauseArgs) { - assertion + assertionChain .ForCondition(valueOutsideBounds) .BecauseOf(because, becauseArgs) .FailWith("Did not expect {context:value} to be within {0} from {1}{reason}, but found {2}.", @@ -755,7 +755,7 @@ public static class NumericAssertionsExtensions { Guard.ThrowIfArgumentIsNegative(precision); - var assertion = parent.CurrentAssertion; + var assertion = parent.CurrentAssertionChain; assertion .ForCondition(parent.Subject is not null) @@ -802,7 +802,7 @@ public static class NumericAssertionsExtensions return new AndConstraint>(parent); } - var assertion = parent.CurrentAssertion; + var assertion = parent.CurrentAssertionChain; assertion .ForCondition(expectedValue is not null) @@ -893,7 +893,7 @@ public static class NumericAssertionsExtensions { Guard.ThrowIfArgumentIsNegative(precision); - var assertion = parent.CurrentAssertion; + var assertion = parent.CurrentAssertionChain; assertion .ForCondition(parent.Subject is not null) @@ -940,7 +940,7 @@ public static class NumericAssertionsExtensions return new AndConstraint>(parent); } - var assertion = parent.CurrentAssertion; + var assertion = parent.CurrentAssertionChain; assertion .ForCondition(expectedValue is not null) @@ -1032,7 +1032,7 @@ public static class NumericAssertionsExtensions { Guard.ThrowIfArgumentIsNegative(precision); - var assertion = parent.CurrentAssertion; + var assertion = parent.CurrentAssertionChain; assertion .ForCondition(parent.Subject is not null) @@ -1080,7 +1080,7 @@ public static class NumericAssertionsExtensions return new AndConstraint>(parent); } - var assertion = parent.CurrentAssertion; + var assertion = parent.CurrentAssertionChain; assertion .ForCondition(expectedValue is not null) @@ -1135,7 +1135,7 @@ public static class NumericAssertionsExtensions string because, object[] becauseArgs) where T : struct, IComparable { - var assertion = parent.CurrentAssertion; + var assertion = parent.CurrentAssertionChain; assertion .ForCondition(differenceWithinPrecision) @@ -1174,7 +1174,7 @@ public static class NumericAssertionsExtensions if (parent.Subject is not null) { - var nonNullableAssertions = new SingleAssertions(parent.Subject.Value, parent.CurrentAssertion); + var nonNullableAssertions = new SingleAssertions(parent.Subject.Value, parent.CurrentAssertionChain); nonNullableAssertions.NotBeApproximately(unexpectedValue, precision, because, becauseArgs); } @@ -1211,7 +1211,7 @@ public static class NumericAssertionsExtensions return new AndConstraint>(parent); } - var assertion = parent.CurrentAssertion; + var assertion = parent.CurrentAssertionChain; assertion .ForCondition(parent.Subject is not null && unexpectedValue is not null) @@ -1305,7 +1305,7 @@ public static class NumericAssertionsExtensions if (parent.Subject is not null) { - var nonNullableAssertions = new DoubleAssertions(parent.Subject.Value, parent.CurrentAssertion); + var nonNullableAssertions = new DoubleAssertions(parent.Subject.Value, parent.CurrentAssertionChain); nonNullableAssertions.NotBeApproximately(unexpectedValue, precision, because, becauseArgs); } @@ -1343,15 +1343,15 @@ public static class NumericAssertionsExtensions return new AndConstraint>(parent); } - Assertion assertion = parent.CurrentAssertion; + AssertionChain assertionChain = parent.CurrentAssertionChain; - assertion + assertionChain .ForCondition(parent.Subject is not null && unexpectedValue is not null) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:value} to not approximate {0} +/- {1}{reason}, but it was {2}.", unexpectedValue, precision, parent.Subject); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { // ReSharper disable once PossibleInvalidOperationException parent.NotBeApproximately(unexpectedValue.Value, precision, because, becauseArgs); @@ -1437,7 +1437,7 @@ public static class NumericAssertionsExtensions if (parent.Subject is not null) { - var nonNullableAssertions = new DecimalAssertions(parent.Subject.Value, parent.CurrentAssertion); + var nonNullableAssertions = new DecimalAssertions(parent.Subject.Value, parent.CurrentAssertionChain); NotBeApproximately(nonNullableAssertions, unexpectedValue, precision, because, becauseArgs); } @@ -1475,7 +1475,7 @@ public static class NumericAssertionsExtensions return new AndConstraint>(parent); } - var assertion = parent.CurrentAssertion; + var assertion = parent.CurrentAssertionChain; assertion .ForCondition(parent.Subject is not null && unexpectedValue is not null) @@ -1530,7 +1530,7 @@ public static class NumericAssertionsExtensions string because, object[] becauseArgs) where T : struct, IComparable { - parent.CurrentAssertion + parent.CurrentAssertionChain .ForCondition(differenceOutsidePrecision) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:value} to not approximate {1} +/- {2}{reason}, but {0} only differed by {3}.", diff --git a/Src/FluentAssertions/ObjectAssertionsExtensions.cs b/Src/FluentAssertions/ObjectAssertionsExtensions.cs index 55f6260c1f..cefd5a0f24 100644 --- a/Src/FluentAssertions/ObjectAssertionsExtensions.cs +++ b/Src/FluentAssertions/ObjectAssertionsExtensions.cs @@ -65,7 +65,7 @@ public static class ObjectAssertionsExtensions } catch (Exception exc) { - assertions.CurrentAssertion + assertions.CurrentAssertionChain .BecauseOf(because, becauseArgs) .FailWith("Expected {0} to be serializable{reason}, but serialization failed with:" + Environment.NewLine + Environment.NewLine + "{1}.", @@ -109,7 +109,7 @@ private static object CreateCloneUsingDataContractSerializer(object subject) } catch (Exception exc) { - assertions.CurrentAssertion + assertions.CurrentAssertionChain .BecauseOf(because, becauseArgs) .FailWith("Expected {0} to be serializable{reason}, but serialization failed with:" + Environment.NewLine + Environment.NewLine + "{1}.", diff --git a/Src/FluentAssertions/OccurrenceConstraint.cs b/Src/FluentAssertions/OccurrenceConstraint.cs index 393df0c95f..7d951dfb66 100644 --- a/Src/FluentAssertions/OccurrenceConstraint.cs +++ b/Src/FluentAssertions/OccurrenceConstraint.cs @@ -22,7 +22,7 @@ protected OccurrenceConstraint(int expectedCount) internal abstract bool Assert(int actual); - internal void RegisterReportables(IAssertionScope scope) + internal void RegisterReportables(AssertionChain scope) { scope.AddReportable("expectedOccurrence", $"{Mode} {ExpectedCount.Times()}"); } diff --git a/Src/FluentAssertions/Primitives/BooleanAssertions.cs b/Src/FluentAssertions/Primitives/BooleanAssertions.cs index 9997629992..35bbb488b4 100644 --- a/Src/FluentAssertions/Primitives/BooleanAssertions.cs +++ b/Src/FluentAssertions/Primitives/BooleanAssertions.cs @@ -11,8 +11,8 @@ namespace FluentAssertions.Primitives; public class BooleanAssertions : BooleanAssertions { - public BooleanAssertions(bool? value, Assertion assertion) - : base(value, assertion) + public BooleanAssertions(bool? value, AssertionChain assertionChain) + : base(value, assertionChain) { } } @@ -26,11 +26,11 @@ public BooleanAssertions(bool? value, Assertion assertion) public class BooleanAssertions where TAssertions : BooleanAssertions { - private readonly Assertion assertion; + private readonly AssertionChain assertionChain; - public BooleanAssertions(bool? value, Assertion assertion) + public BooleanAssertions(bool? value, AssertionChain assertionChain) { - this.assertion = assertion; + this.assertionChain = assertionChain; Subject = value; } @@ -51,7 +51,7 @@ public BooleanAssertions(bool? value, Assertion assertion) /// public AndConstraint BeFalse(string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject == false) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:boolean} to be {0}{reason}, but found {1}.", false, Subject); @@ -71,7 +71,7 @@ public AndConstraint BeFalse(string because = "", params object[] b /// public AndConstraint BeTrue(string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject == true) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:boolean} to be {0}{reason}, but found {1}.", true, Subject); @@ -92,7 +92,7 @@ public AndConstraint BeTrue(string because = "", params object[] be /// public AndConstraint Be(bool expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject == expected) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:boolean} to be {0}{reason}, but found {1}.", expected, Subject); @@ -113,7 +113,7 @@ public AndConstraint Be(bool expected, string because = "", params /// public AndConstraint NotBe(bool unexpected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject != unexpected) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:boolean} not to be {0}{reason}, but found {1}.", unexpected, Subject); @@ -138,7 +138,7 @@ public AndConstraint NotBe(bool unexpected, string because = "", pa { bool? antecedent = Subject; - assertion + assertionChain .ForCondition(antecedent is not null) .BecauseOf(because, becauseArgs) .WithExpectation("Expected {context:antecedent} ({0}) to imply consequent ({1}){reason}, ", antecedent, consequent) diff --git a/Src/FluentAssertions/Primitives/DateOnlyAssertions.cs b/Src/FluentAssertions/Primitives/DateOnlyAssertions.cs index 34f1b298da..2d66ce20f5 100644 --- a/Src/FluentAssertions/Primitives/DateOnlyAssertions.cs +++ b/Src/FluentAssertions/Primitives/DateOnlyAssertions.cs @@ -14,12 +14,12 @@ namespace FluentAssertions.Primitives; [DebuggerNonUserCode] public class DateOnlyAssertions : DateOnlyAssertions { - private readonly Assertion assertion; + private readonly AssertionChain assertionChain; - public DateOnlyAssertions(DateOnly? value, Assertion assertion) - : base(value, assertion) + public DateOnlyAssertions(DateOnly? value, AssertionChain assertionChain) + : base(value, assertionChain) { - this.assertion = assertion; + this.assertionChain = assertionChain; } } @@ -32,11 +32,11 @@ public DateOnlyAssertions(DateOnly? value, Assertion assertion) public class DateOnlyAssertions where TAssertions : DateOnlyAssertions { - private readonly Assertion assertion; + private readonly AssertionChain assertionChain; - public DateOnlyAssertions(DateOnly? value, Assertion assertion) + public DateOnlyAssertions(DateOnly? value, AssertionChain assertionChain) { - this.assertion = assertion; + this.assertionChain = assertionChain; Subject = value; } @@ -58,7 +58,7 @@ public DateOnlyAssertions(DateOnly? value, Assertion assertion) /// public AndConstraint Be(DateOnly expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject == expected) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:date} to be {0}{reason}, but found {1}.", @@ -80,7 +80,7 @@ public AndConstraint Be(DateOnly expected, string because = "", par /// public AndConstraint Be(DateOnly? expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject == expected) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:date} to be {0}{reason}, but found {1}.", @@ -103,7 +103,7 @@ public AndConstraint Be(DateOnly? expected, string because = "", pa public AndConstraint NotBe(DateOnly unexpected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject != unexpected) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:date} not to be {0}{reason}, but it is.", unexpected); @@ -125,7 +125,7 @@ public AndConstraint Be(DateOnly? expected, string because = "", pa public AndConstraint NotBe(DateOnly? unexpected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject != unexpected) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:date} not to be {0}{reason}, but it is.", unexpected); @@ -147,7 +147,7 @@ public AndConstraint Be(DateOnly? expected, string because = "", pa public AndConstraint BeBefore(DateOnly expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject < expected) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:date} to be before {0}{reason}, but found {1}.", expected, @@ -187,7 +187,7 @@ public AndConstraint Be(DateOnly? expected, string because = "", pa public AndConstraint BeOnOrBefore(DateOnly expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject <= expected) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:date} to be on or before {0}{reason}, but found {1}.", expected, @@ -227,7 +227,7 @@ public AndConstraint Be(DateOnly? expected, string because = "", pa public AndConstraint BeAfter(DateOnly expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject > expected) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:date} to be after {0}{reason}, but found {1}.", expected, @@ -267,7 +267,7 @@ public AndConstraint Be(DateOnly? expected, string because = "", pa public AndConstraint BeOnOrAfter(DateOnly expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject >= expected) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:date} to be on or after {0}{reason}, but found {1}.", expected, @@ -306,7 +306,7 @@ public AndConstraint Be(DateOnly? expected, string because = "", pa /// public AndConstraint HaveYear(int expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected the year part of {context:the date} to be {0}{reason}", expected) .ForCondition(Subject.HasValue) @@ -332,7 +332,7 @@ public AndConstraint HaveYear(int expected, string because = "", pa /// public AndConstraint NotHaveYear(int unexpected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject.HasValue) .FailWith("Did not expect the year part of {context:the date} to be {0}{reason}, but found a DateOnly.", @@ -358,7 +358,7 @@ public AndConstraint NotHaveYear(int unexpected, string because = " /// public AndConstraint HaveMonth(int expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected the month part of {context:the date} to be {0}{reason}", expected) .ForCondition(Subject.HasValue) @@ -383,7 +383,7 @@ public AndConstraint HaveMonth(int expected, string because = "", p /// public AndConstraint NotHaveMonth(int unexpected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Did not expect the month part of {context:the date} to be {0}{reason}", unexpected) .ForCondition(Subject.HasValue) @@ -408,7 +408,7 @@ public AndConstraint NotHaveMonth(int unexpected, string because = /// public AndConstraint HaveDay(int expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected the day part of {context:the date} to be {0}{reason}", expected) .ForCondition(Subject.HasValue) @@ -433,7 +433,7 @@ public AndConstraint HaveDay(int expected, string because = "", par /// public AndConstraint NotHaveDay(int unexpected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Did not expect the day part of {context:the date} to be {0}{reason}", unexpected) .ForCondition(Subject.HasValue) @@ -501,7 +501,7 @@ public AndConstraint BeOneOf(IEnumerable validValues, str public AndConstraint BeOneOf(IEnumerable validValues, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(validValues.Contains(Subject)) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:date} to be one of {0}{reason}, but found {1}.", validValues, Subject); diff --git a/Src/FluentAssertions/Primitives/DateTimeAssertions.cs b/Src/FluentAssertions/Primitives/DateTimeAssertions.cs index a6e54af4ad..1a5c88ac49 100644 --- a/Src/FluentAssertions/Primitives/DateTimeAssertions.cs +++ b/Src/FluentAssertions/Primitives/DateTimeAssertions.cs @@ -17,12 +17,12 @@ namespace FluentAssertions.Primitives; [DebuggerNonUserCode] public class DateTimeAssertions : DateTimeAssertions { - private readonly Assertion assertion; + private readonly AssertionChain assertionChain; - public DateTimeAssertions(DateTime? value, Assertion assertion) - : base(value, assertion) + public DateTimeAssertions(DateTime? value, AssertionChain assertionChain) + : base(value, assertionChain) { - this.assertion = assertion; + this.assertionChain = assertionChain; } } @@ -39,11 +39,11 @@ public DateTimeAssertions(DateTime? value, Assertion assertion) public class DateTimeAssertions where TAssertions : DateTimeAssertions { - private readonly Assertion assertion; + private readonly AssertionChain assertionChain; - public DateTimeAssertions(DateTime? value, Assertion assertion) + public DateTimeAssertions(DateTime? value, AssertionChain assertionChain) { - this.assertion = assertion; + this.assertionChain = assertionChain; Subject = value; } @@ -65,7 +65,7 @@ public DateTimeAssertions(DateTime? value, Assertion assertion) /// public AndConstraint Be(DateTime expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject == expected) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:date and time} to be {0}{reason}, but found {1}.", @@ -87,7 +87,7 @@ public AndConstraint Be(DateTime expected, string because = "", par /// public AndConstraint Be(DateTime? expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject == expected) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:date and time} to be {0}{reason}, but found {1}.", @@ -110,7 +110,7 @@ public AndConstraint Be(DateTime? expected, string because = "", pa public AndConstraint NotBe(DateTime unexpected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject != unexpected) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:date and time} not to be {0}{reason}, but it is.", unexpected); @@ -132,7 +132,7 @@ public AndConstraint Be(DateTime? expected, string because = "", pa public AndConstraint NotBe(DateTime? unexpected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject != unexpected) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:date and time} not to be {0}{reason}, but it is.", unexpected); @@ -175,7 +175,7 @@ public AndConstraint Be(DateTime? expected, string because = "", pa TimeSpan? difference = (Subject - nearbyTime)?.Duration(); - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected {context:the date and time} to be within {0} from {1}{reason}", precision, nearbyTime) .ForCondition(Subject is not null) @@ -220,7 +220,7 @@ public AndConstraint Be(DateTime? expected, string because = "", pa long distanceToMaxInTicks = (DateTime.MaxValue - distantTime).Ticks; DateTime maximumValue = distantTime.AddTicks(Math.Min(precision.Ticks, distanceToMaxInTicks)); - assertion + assertionChain .ForCondition(Subject < minimumValue || Subject > maximumValue) .BecauseOf(because, becauseArgs) .FailWith( @@ -245,7 +245,7 @@ public AndConstraint Be(DateTime? expected, string because = "", pa public AndConstraint BeBefore(DateTime expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject < expected) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:the date and time} to be before {0}{reason}, but found {1}.", expected, @@ -285,7 +285,7 @@ public AndConstraint Be(DateTime? expected, string because = "", pa public AndConstraint BeOnOrBefore(DateTime expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject <= expected) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:the date and time} to be on or before {0}{reason}, but found {1}.", expected, @@ -325,7 +325,7 @@ public AndConstraint Be(DateTime? expected, string because = "", pa public AndConstraint BeAfter(DateTime expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject > expected) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:the date and time} to be after {0}{reason}, but found {1}.", expected, @@ -365,7 +365,7 @@ public AndConstraint Be(DateTime? expected, string because = "", pa public AndConstraint BeOnOrAfter(DateTime expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject >= expected) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:the date and time} to be on or after {0}{reason}, but found {1}.", expected, @@ -404,7 +404,7 @@ public AndConstraint Be(DateTime? expected, string because = "", pa /// public AndConstraint HaveYear(int expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected the year part of {context:the date} to be {0}{reason}", expected) .ForCondition(Subject.HasValue) @@ -429,7 +429,7 @@ public AndConstraint HaveYear(int expected, string because = "", pa /// public AndConstraint NotHaveYear(int unexpected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject.HasValue) .FailWith("Did not expect the year part of {context:the date} to be {0}{reason}, but found a DateTime.", @@ -455,7 +455,7 @@ public AndConstraint NotHaveYear(int unexpected, string because = " /// public AndConstraint HaveMonth(int expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected the month part of {context:the date} to be {0}{reason}", expected) .ForCondition(Subject.HasValue) @@ -480,7 +480,7 @@ public AndConstraint HaveMonth(int expected, string because = "", p /// public AndConstraint NotHaveMonth(int unexpected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Did not expect the month part of {context:the date} to be {0}{reason}", unexpected) .ForCondition(Subject.HasValue) @@ -505,7 +505,7 @@ public AndConstraint NotHaveMonth(int unexpected, string because = /// public AndConstraint HaveDay(int expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected the day part of {context:the date} to be {0}{reason}", expected) .ForCondition(Subject.HasValue) @@ -531,7 +531,7 @@ public AndConstraint HaveDay(int expected, string because = "", par /// public AndConstraint NotHaveDay(int unexpected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Did not expect the day part of {context:the date} to be {0}{reason}", unexpected) .ForCondition(Subject.HasValue) @@ -557,7 +557,7 @@ public AndConstraint NotHaveDay(int unexpected, string because = "" /// public AndConstraint HaveHour(int expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected the hour part of {context:the time} to be {0}{reason}", expected) .ForCondition(Subject.HasValue) @@ -583,7 +583,7 @@ public AndConstraint HaveHour(int expected, string because = "", pa /// public AndConstraint NotHaveHour(int unexpected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Did not expect the hour part of {context:the time} to be {0}{reason}", unexpected) .ForCondition(Subject.HasValue) @@ -610,7 +610,7 @@ public AndConstraint NotHaveHour(int unexpected, string because = " public AndConstraint HaveMinute(int expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected the minute part of {context:the time} to be {0}{reason}", expected) .ForCondition(Subject.HasValue) @@ -637,7 +637,7 @@ public AndConstraint NotHaveHour(int unexpected, string because = " public AndConstraint NotHaveMinute(int unexpected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Did not expect the minute part of {context:the time} to be {0}{reason}", unexpected) .ForCondition(Subject.HasValue) @@ -664,7 +664,7 @@ public AndConstraint NotHaveHour(int unexpected, string because = " public AndConstraint HaveSecond(int expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected the seconds part of {context:the time} to be {0}{reason}", expected) .ForCondition(Subject.HasValue) @@ -691,7 +691,7 @@ public AndConstraint NotHaveHour(int unexpected, string because = " public AndConstraint NotHaveSecond(int unexpected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Did not expect the seconds part of {context:the time} to be {0}{reason}", unexpected) .ForCondition(Subject.HasValue) @@ -713,7 +713,7 @@ public AndConstraint NotHaveHour(int unexpected, string because = " /// public DateTimeRangeAssertions BeMoreThan(TimeSpan timeSpan) { - return new DateTimeRangeAssertions((TAssertions)this, assertion, Subject, TimeSpanCondition.MoreThan, timeSpan); + return new DateTimeRangeAssertions((TAssertions)this, assertionChain, Subject, TimeSpanCondition.MoreThan, timeSpan); } /// @@ -726,7 +726,7 @@ public DateTimeRangeAssertions BeMoreThan(TimeSpan timeSpan) /// public DateTimeRangeAssertions BeAtLeast(TimeSpan timeSpan) { - return new DateTimeRangeAssertions((TAssertions)this, assertion, Subject, TimeSpanCondition.AtLeast, timeSpan); + return new DateTimeRangeAssertions((TAssertions)this, assertionChain, Subject, TimeSpanCondition.AtLeast, timeSpan); } /// @@ -738,7 +738,7 @@ public DateTimeRangeAssertions BeAtLeast(TimeSpan timeSpan) /// public DateTimeRangeAssertions BeExactly(TimeSpan timeSpan) { - return new DateTimeRangeAssertions((TAssertions)this, assertion, Subject, TimeSpanCondition.Exactly, timeSpan); + return new DateTimeRangeAssertions((TAssertions)this, assertionChain, Subject, TimeSpanCondition.Exactly, timeSpan); } /// @@ -750,7 +750,7 @@ public DateTimeRangeAssertions BeExactly(TimeSpan timeSpan) /// public DateTimeRangeAssertions BeWithin(TimeSpan timeSpan) { - return new DateTimeRangeAssertions((TAssertions)this, assertion, Subject, TimeSpanCondition.Within, timeSpan); + return new DateTimeRangeAssertions((TAssertions)this, assertionChain, Subject, TimeSpanCondition.Within, timeSpan); } /// @@ -762,7 +762,7 @@ public DateTimeRangeAssertions BeWithin(TimeSpan timeSpan) /// public DateTimeRangeAssertions BeLessThan(TimeSpan timeSpan) { - return new DateTimeRangeAssertions((TAssertions)this, assertion, Subject, TimeSpanCondition.LessThan, timeSpan); + return new DateTimeRangeAssertions((TAssertions)this, assertionChain, Subject, TimeSpanCondition.LessThan, timeSpan); } /// @@ -781,7 +781,7 @@ public DateTimeRangeAssertions BeLessThan(TimeSpan timeSpan) { DateTime expectedDate = expected.Date; - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected the date part of {context:the date and time} to be {0}{reason}", expectedDate) .ForCondition(Subject.HasValue) @@ -810,7 +810,7 @@ public DateTimeRangeAssertions BeLessThan(TimeSpan timeSpan) { DateTime unexpectedDate = unexpected.Date; - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Did not expect the date part of {context:the date and time} to be {0}{reason}", unexpectedDate) .ForCondition(Subject.HasValue) @@ -879,7 +879,7 @@ public AndConstraint BeOneOf(IEnumerable validValues, str public AndConstraint BeOneOf(IEnumerable validValues, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(validValues.Contains(Subject)) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:date and time} to be one of {0}{reason}, but found {1}.", validValues, Subject); @@ -902,7 +902,7 @@ public AndConstraint BeOneOf(IEnumerable validValues, str /// public AndConstraint BeIn(DateTimeKind expectedKind, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected {context:the date and time} to be in " + expectedKind + "{reason}") .ForCondition(Subject.HasValue) diff --git a/Src/FluentAssertions/Primitives/DateTimeOffsetAssertions.cs b/Src/FluentAssertions/Primitives/DateTimeOffsetAssertions.cs index 13ad5b4679..4aa96945a2 100644 --- a/Src/FluentAssertions/Primitives/DateTimeOffsetAssertions.cs +++ b/Src/FluentAssertions/Primitives/DateTimeOffsetAssertions.cs @@ -18,12 +18,12 @@ namespace FluentAssertions.Primitives; public class DateTimeOffsetAssertions : DateTimeOffsetAssertions { - private readonly Assertion assertion; + private readonly AssertionChain assertionChain; - public DateTimeOffsetAssertions(DateTimeOffset? value, Assertion assertion) - : base(value, assertion) + public DateTimeOffsetAssertions(DateTimeOffset? value, AssertionChain assertionChain) + : base(value, assertionChain) { - this.assertion = assertion; + this.assertionChain = assertionChain; } } @@ -40,11 +40,11 @@ public DateTimeOffsetAssertions(DateTimeOffset? value, Assertion assertion) public class DateTimeOffsetAssertions where TAssertions : DateTimeOffsetAssertions { - private readonly Assertion assertion; + private readonly AssertionChain assertionChain; - public DateTimeOffsetAssertions(DateTimeOffset? value, Assertion assertion) + public DateTimeOffsetAssertions(DateTimeOffset? value, AssertionChain assertionChain) { - this.assertion = assertion; + this.assertionChain = assertionChain; Subject = value; } @@ -67,7 +67,7 @@ public DateTimeOffsetAssertions(DateTimeOffset? value, Assertion assertion) public AndConstraint Be(DateTimeOffset expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected {context:the date and time} to represent the same point in time as {0}{reason}, ", expected) @@ -97,14 +97,14 @@ public DateTimeOffsetAssertions(DateTimeOffset? value, Assertion assertion) { if (!expected.HasValue) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(!Subject.HasValue) .FailWith("Expected {context:the date and time} to be {reason}, but it was {0}.", Subject); } else { - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected {context:the date and time} to represent the same point in time as {0}{reason}, ", expected) @@ -132,7 +132,7 @@ public DateTimeOffsetAssertions(DateTimeOffset? value, Assertion assertion) public AndConstraint NotBe(DateTimeOffset unexpected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject != unexpected) .BecauseOf(because, becauseArgs) .FailWith( @@ -156,7 +156,7 @@ public DateTimeOffsetAssertions(DateTimeOffset? value, Assertion assertion) public AndConstraint NotBe(DateTimeOffset? unexpected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject != unexpected) .BecauseOf(because, becauseArgs) .FailWith( @@ -180,7 +180,7 @@ public DateTimeOffsetAssertions(DateTimeOffset? value, Assertion assertion) public AndConstraint BeExactly(DateTimeOffset expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected {context:the date and time} to be exactly {0}{reason}, ", expected) .ForCondition(Subject.HasValue) @@ -210,14 +210,14 @@ public DateTimeOffsetAssertions(DateTimeOffset? value, Assertion assertion) { if (!expected.HasValue) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(!Subject.HasValue) .FailWith("Expected {context:the date and time} to be {reason}, but it was {0}.", Subject); } else { - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected {context:the date and time} to be exactly {0}{reason}, ", expected) .ForCondition(Subject.HasValue) @@ -245,7 +245,7 @@ public DateTimeOffsetAssertions(DateTimeOffset? value, Assertion assertion) public AndConstraint NotBeExactly(DateTimeOffset unexpected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject?.EqualsExact(unexpected) != true) .BecauseOf(because, becauseArgs) .FailWith("Did not expect {context:the date and time} to be exactly {0}{reason}, but it was.", unexpected); @@ -267,7 +267,7 @@ public DateTimeOffsetAssertions(DateTimeOffset? value, Assertion assertion) public AndConstraint NotBeExactly(DateTimeOffset? unexpected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(!((Subject == null && unexpected == null) || (Subject != null && unexpected != null && Subject.Value.EqualsExact(unexpected.Value)))) .BecauseOf(because, becauseArgs) @@ -312,7 +312,7 @@ public DateTimeOffsetAssertions(DateTimeOffset? value, Assertion assertion) TimeSpan? difference = (Subject - nearbyTime)?.Duration(); - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected {context:the date and time} to be within {0} from {1}{reason}", precision, nearbyTime) .ForCondition(Subject is not null) @@ -358,7 +358,7 @@ public DateTimeOffsetAssertions(DateTimeOffset? value, Assertion assertion) long distanceToMaxInTicks = (DateTimeOffset.MaxValue - distantTime).Ticks; DateTimeOffset maximumValue = distantTime.AddTicks(Math.Min(precision.Ticks, distanceToMaxInTicks)); - assertion + assertionChain .ForCondition(Subject < minimumValue || Subject > maximumValue) .BecauseOf(because, becauseArgs) .FailWith( @@ -383,7 +383,7 @@ public DateTimeOffsetAssertions(DateTimeOffset? value, Assertion assertion) public AndConstraint BeBefore(DateTimeOffset expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject < expected) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:the date and time} to be before {0}{reason}, but it was {1}.", expected, @@ -423,7 +423,7 @@ public DateTimeOffsetAssertions(DateTimeOffset? value, Assertion assertion) public AndConstraint BeOnOrBefore(DateTimeOffset expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject <= expected) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:the date and time} to be on or before {0}{reason}, but it was {1}.", expected, @@ -463,7 +463,7 @@ public DateTimeOffsetAssertions(DateTimeOffset? value, Assertion assertion) public AndConstraint BeAfter(DateTimeOffset expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject > expected) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:the date and time} to be after {0}{reason}, but it was {1}.", expected, @@ -503,7 +503,7 @@ public DateTimeOffsetAssertions(DateTimeOffset? value, Assertion assertion) public AndConstraint BeOnOrAfter(DateTimeOffset expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject >= expected) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:the date and time} to be on or after {0}{reason}, but it was {1}.", expected, @@ -543,7 +543,7 @@ public DateTimeOffsetAssertions(DateTimeOffset? value, Assertion assertion) public AndConstraint HaveYear(int expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected the year part of {context:the date} to be {0}{reason}, ", expected) .ForCondition(Subject.HasValue) @@ -569,7 +569,7 @@ public DateTimeOffsetAssertions(DateTimeOffset? value, Assertion assertion) /// public AndConstraint NotHaveYear(int unexpected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Did not expect the year part of {context:the date} to be {0}{reason}, ", unexpected) .ForCondition(Subject.HasValue) @@ -596,7 +596,7 @@ public AndConstraint NotHaveYear(int unexpected, string because = " public AndConstraint HaveMonth(int expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected the month part of {context:the date} to be {0}{reason}, ", expected) .ForCondition(Subject.HasValue) @@ -622,7 +622,7 @@ public AndConstraint NotHaveYear(int unexpected, string because = " /// public AndConstraint NotHaveMonth(int unexpected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Did not expect the month part of {context:the date} to be {0}{reason}, ", unexpected) .ForCondition(Subject.HasValue) @@ -649,7 +649,7 @@ public AndConstraint NotHaveMonth(int unexpected, string because = public AndConstraint HaveDay(int expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected the day part of {context:the date} to be {0}{reason}, ", expected) .ForCondition(Subject.HasValue) @@ -675,7 +675,7 @@ public AndConstraint NotHaveMonth(int unexpected, string because = /// public AndConstraint NotHaveDay(int unexpected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Did not expect the day part of {context:the date} to be {0}{reason}, ", unexpected) .ForCondition(Subject.HasValue) @@ -702,7 +702,7 @@ public AndConstraint NotHaveDay(int unexpected, string because = "" public AndConstraint HaveHour(int expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected the hour part of {context:the time} to be {0}{reason}, ", expected) .ForCondition(Subject.HasValue) @@ -728,7 +728,7 @@ public AndConstraint NotHaveDay(int unexpected, string because = "" /// public AndConstraint NotHaveHour(int unexpected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Did not expect the hour part of {context:the time} to be {0}{reason}, ", unexpected) .ForCondition(Subject.HasValue) @@ -755,7 +755,7 @@ public AndConstraint NotHaveHour(int unexpected, string because = " public AndConstraint HaveMinute(int expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected the minute part of {context:the time} to be {0}{reason}, ", expected) .ForCondition(Subject.HasValue) @@ -782,7 +782,7 @@ public AndConstraint NotHaveHour(int unexpected, string because = " public AndConstraint NotHaveMinute(int unexpected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Did not expect the minute part of {context:the time} to be {0}{reason}, ", unexpected) .ForCondition(Subject.HasValue) @@ -809,7 +809,7 @@ public AndConstraint NotHaveHour(int unexpected, string because = " public AndConstraint HaveSecond(int expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected the seconds part of {context:the time} to be {0}{reason}, ", expected) .ForCondition(Subject.HasValue) @@ -836,7 +836,7 @@ public AndConstraint NotHaveHour(int unexpected, string because = " public AndConstraint NotHaveSecond(int unexpected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Did not expect the seconds part of {context:the time} to be {0}{reason}, ", unexpected) .ForCondition(Subject.HasValue) @@ -863,7 +863,7 @@ public AndConstraint NotHaveHour(int unexpected, string because = " public AndConstraint HaveOffset(TimeSpan expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected the offset of {context:the date} to be {0}{reason}, ", expected) .ForCondition(Subject.HasValue) @@ -890,7 +890,7 @@ public AndConstraint NotHaveHour(int unexpected, string because = " public AndConstraint NotHaveOffset(TimeSpan unexpected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Did not expect the offset of {context:the date} to be {0}{reason}, ", unexpected) .ForCondition(Subject.HasValue) @@ -912,7 +912,7 @@ public AndConstraint NotHaveHour(int unexpected, string because = " /// public DateTimeOffsetRangeAssertions BeMoreThan(TimeSpan timeSpan) { - return new DateTimeOffsetRangeAssertions((TAssertions)this, assertion, Subject, TimeSpanCondition.MoreThan, timeSpan); + return new DateTimeOffsetRangeAssertions((TAssertions)this, assertionChain, Subject, TimeSpanCondition.MoreThan, timeSpan); } /// @@ -925,7 +925,7 @@ public DateTimeOffsetRangeAssertions BeMoreThan(TimeSpan timeSpan) /// public DateTimeOffsetRangeAssertions BeAtLeast(TimeSpan timeSpan) { - return new DateTimeOffsetRangeAssertions((TAssertions)this, assertion, Subject, TimeSpanCondition.AtLeast, timeSpan); + return new DateTimeOffsetRangeAssertions((TAssertions)this, assertionChain, Subject, TimeSpanCondition.AtLeast, timeSpan); } /// @@ -937,7 +937,7 @@ public DateTimeOffsetRangeAssertions BeAtLeast(TimeSpan timeSpan) /// public DateTimeOffsetRangeAssertions BeExactly(TimeSpan timeSpan) { - return new DateTimeOffsetRangeAssertions((TAssertions)this, assertion, Subject, TimeSpanCondition.Exactly, timeSpan); + return new DateTimeOffsetRangeAssertions((TAssertions)this, assertionChain, Subject, TimeSpanCondition.Exactly, timeSpan); } /// @@ -949,7 +949,7 @@ public DateTimeOffsetRangeAssertions BeExactly(TimeSpan timeSpan) /// public DateTimeOffsetRangeAssertions BeWithin(TimeSpan timeSpan) { - return new DateTimeOffsetRangeAssertions((TAssertions)this, assertion, Subject, TimeSpanCondition.Within, timeSpan); + return new DateTimeOffsetRangeAssertions((TAssertions)this, assertionChain, Subject, TimeSpanCondition.Within, timeSpan); } /// @@ -961,7 +961,7 @@ public DateTimeOffsetRangeAssertions BeWithin(TimeSpan timeSpan) /// public DateTimeOffsetRangeAssertions BeLessThan(TimeSpan timeSpan) { - return new DateTimeOffsetRangeAssertions((TAssertions)this, assertion, Subject, TimeSpanCondition.LessThan, timeSpan); + return new DateTimeOffsetRangeAssertions((TAssertions)this, assertionChain, Subject, TimeSpanCondition.LessThan, timeSpan); } /// @@ -980,7 +980,7 @@ public DateTimeOffsetRangeAssertions BeLessThan(TimeSpan timeSpan) { DateTime expectedDate = expected.Date; - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected the date part of {context:the date and time} to be {0}{reason}, ", expectedDate) .ForCondition(Subject.HasValue) @@ -1009,7 +1009,7 @@ public DateTimeOffsetRangeAssertions BeLessThan(TimeSpan timeSpan) { DateTime unexpectedDate = unexpected.Date; - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Did not expect the date part of {context:the date and time} to be {0}{reason}, ", unexpectedDate) .ForCondition(Subject.HasValue) @@ -1079,7 +1079,7 @@ public AndConstraint BeOneOf(params DateTimeOffset[] validValues) public AndConstraint BeOneOf(IEnumerable validValues, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(validValues.Contains(Subject)) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:the date and time} to be one of {0}{reason}, but it was {1}.", validValues, Subject); diff --git a/Src/FluentAssertions/Primitives/DateTimeOffsetRangeAssertions.cs b/Src/FluentAssertions/Primitives/DateTimeOffsetRangeAssertions.cs index adf4aa21f7..295d2d00f3 100644 --- a/Src/FluentAssertions/Primitives/DateTimeOffsetRangeAssertions.cs +++ b/Src/FluentAssertions/Primitives/DateTimeOffsetRangeAssertions.cs @@ -22,7 +22,7 @@ public class DateTimeOffsetRangeAssertions #region Private Definitions private readonly TAssertions parentAssertions; - private readonly Assertion assertion; + private readonly AssertionChain assertionChain; private readonly TimeSpanPredicate predicate; private readonly Dictionary predicates = new() @@ -39,13 +39,13 @@ public class DateTimeOffsetRangeAssertions #endregion - protected internal DateTimeOffsetRangeAssertions(TAssertions parentAssertions, Assertion assertion, + protected internal DateTimeOffsetRangeAssertions(TAssertions parentAssertions, AssertionChain assertionChain, DateTimeOffset? subject, TimeSpanCondition condition, TimeSpan timeSpan) { this.parentAssertions = parentAssertions; - this.assertion = assertion; + this.assertionChain = assertionChain; this.subject = subject; this.timeSpan = timeSpan; @@ -68,17 +68,17 @@ public class DateTimeOffsetRangeAssertions public AndConstraint Before(DateTimeOffset target, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(subject.HasValue) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:the date and time} to be " + predicate.DisplayText + " {0} before {1}{reason}, but found a DateTime.", timeSpan, target); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { TimeSpan actual = target - subject.Value; - assertion + assertionChain .ForCondition(predicate.IsMatchedBy(actual, timeSpan)) .BecauseOf(because, becauseArgs) .FailWith( @@ -105,17 +105,17 @@ public class DateTimeOffsetRangeAssertions /// public AndConstraint After(DateTimeOffset target, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(subject.HasValue) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:the date and time} to be " + predicate.DisplayText + " {0} after {1}{reason}, but found a DateTime.", timeSpan, target); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { TimeSpan actual = subject.Value - target; - assertion + assertionChain .ForCondition(predicate.IsMatchedBy(actual, timeSpan)) .BecauseOf(because, becauseArgs) .FailWith( diff --git a/Src/FluentAssertions/Primitives/DateTimeRangeAssertions.cs b/Src/FluentAssertions/Primitives/DateTimeRangeAssertions.cs index 8858c48c4e..0aa325fa94 100644 --- a/Src/FluentAssertions/Primitives/DateTimeRangeAssertions.cs +++ b/Src/FluentAssertions/Primitives/DateTimeRangeAssertions.cs @@ -22,7 +22,7 @@ public class DateTimeRangeAssertions #region Private Definitions private readonly TAssertions parentAssertions; - private readonly Assertion assertion; + private readonly AssertionChain assertionChain; private readonly TimeSpanPredicate predicate; private readonly Dictionary predicates = new() @@ -39,13 +39,13 @@ public class DateTimeRangeAssertions #endregion - protected internal DateTimeRangeAssertions(TAssertions parentAssertions, Assertion assertion, + protected internal DateTimeRangeAssertions(TAssertions parentAssertions, AssertionChain assertionChain, DateTime? subject, TimeSpanCondition condition, TimeSpan timeSpan) { this.parentAssertions = parentAssertions; - this.assertion = assertion; + this.assertionChain = assertionChain; this.subject = subject; this.timeSpan = timeSpan; @@ -68,18 +68,18 @@ public class DateTimeRangeAssertions public AndConstraint Before(DateTime target, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(subject.HasValue) .BecauseOf(because, becauseArgs) .FailWith("Expected date and/or time {0} to be " + predicate.DisplayText + " {1} before {2}{reason}, but found a DateTime.", subject, timeSpan, target); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { TimeSpan actual = target - subject.Value; - assertion + assertionChain .ForCondition(predicate.IsMatchedBy(actual, timeSpan)) .BecauseOf(because, becauseArgs) .FailWith( @@ -107,18 +107,18 @@ public class DateTimeRangeAssertions public AndConstraint After(DateTime target, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(subject.HasValue) .BecauseOf(because, becauseArgs) .FailWith("Expected date and/or time {0} to be " + predicate.DisplayText + " {1} after {2}{reason}, but found a DateTime.", subject, timeSpan, target); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { TimeSpan actual = subject.Value - target; - assertion + assertionChain .ForCondition(predicate.IsMatchedBy(actual, timeSpan)) .BecauseOf(because, becauseArgs) .FailWith( diff --git a/Src/FluentAssertions/Primitives/EnumAssertions.cs b/Src/FluentAssertions/Primitives/EnumAssertions.cs index 50c591990b..356266ca62 100644 --- a/Src/FluentAssertions/Primitives/EnumAssertions.cs +++ b/Src/FluentAssertions/Primitives/EnumAssertions.cs @@ -14,8 +14,8 @@ namespace FluentAssertions.Primitives; public class EnumAssertions : EnumAssertions> where TEnum : struct, Enum { - public EnumAssertions(TEnum subject, Assertion assertion) - : base(subject, assertion) + public EnumAssertions(TEnum subject, AssertionChain assertionChain) + : base(subject, assertionChain) { } } @@ -29,16 +29,16 @@ public class EnumAssertions where TEnum : struct, Enum where TAssertions : EnumAssertions { - private readonly Assertion assertion; + private readonly AssertionChain assertionChain; - public EnumAssertions(TEnum subject, Assertion assertion) - : this((TEnum?)subject, assertion) + public EnumAssertions(TEnum subject, AssertionChain assertionChain) + : this((TEnum?)subject, assertionChain) { } - private protected EnumAssertions(TEnum? value, Assertion assertion) + private protected EnumAssertions(TEnum? value, AssertionChain assertionChain) { - this.assertion = assertion; + this.assertionChain = assertionChain; Subject = value; } @@ -57,7 +57,7 @@ private protected EnumAssertions(TEnum? value, Assertion assertion) /// public AndConstraint Be(TEnum expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject?.Equals(expected) == true) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:the enum} to be {0}{reason}, but found {1}.", @@ -79,7 +79,7 @@ public AndConstraint Be(TEnum expected, string because = "", params /// public AndConstraint Be(TEnum? expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Nullable.Equals(Subject, expected)) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:the enum} to be {0}{reason}, but found {1}.", @@ -102,7 +102,7 @@ public AndConstraint Be(TEnum? expected, string because = "", param public AndConstraint NotBe(TEnum unexpected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject?.Equals(unexpected) != true) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:the enum} not to be {0}{reason}, but it is.", unexpected); @@ -124,7 +124,7 @@ public AndConstraint Be(TEnum? expected, string because = "", param public AndConstraint NotBe(TEnum? unexpected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(!Nullable.Equals(Subject, unexpected)) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:the enum} not to be {0}{reason}, but it is.", unexpected); @@ -144,7 +144,7 @@ public AndConstraint Be(TEnum? expected, string because = "", param /// public AndConstraint BeDefined(string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected {context:the enum} to be defined in {0}{reason}, ", typeof(TEnum)) .ForCondition(Subject is not null) @@ -169,7 +169,7 @@ public AndConstraint BeDefined(string because = "", params object[] /// public AndConstraint NotBeDefined(string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Did not expect {context:the enum} to be defined in {0}{reason}, ", typeof(TEnum)) .ForCondition(Subject is not null) @@ -195,7 +195,7 @@ public AndConstraint NotBeDefined(string because = "", params objec /// public AndConstraint HaveValue(decimal expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject is { } value && GetValue(value) == expected) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:the enum} to have value {0}{reason}, but found {1}.", @@ -217,7 +217,7 @@ public AndConstraint HaveValue(decimal expected, string because = " /// public AndConstraint NotHaveValue(decimal unexpected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(!(Subject is { } value && GetValue(value) == unexpected)) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:the enum} to not have value {0}{reason}, but found {1}.", @@ -240,7 +240,7 @@ public AndConstraint NotHaveValue(decimal unexpected, string becaus public AndConstraint HaveSameValueAs(T expected, string because = "", params object[] becauseArgs) where T : struct, Enum { - assertion + assertionChain .ForCondition(Subject is { } value && GetValue(value) == GetValue(expected)) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:the enum} to have same value as {0}{reason}, but found {1}.", @@ -263,7 +263,7 @@ public AndConstraint HaveSameValueAs(T expected, string because public AndConstraint NotHaveSameValueAs(T unexpected, string because = "", params object[] becauseArgs) where T : struct, Enum { - assertion + assertionChain .ForCondition(!(Subject is { } value && GetValue(value) == GetValue(unexpected))) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:the enum} to not have same value as {0}{reason}, but found {1}.", @@ -286,7 +286,7 @@ public AndConstraint NotHaveSameValueAs(T unexpected, string bec public AndConstraint HaveSameNameAs(T expected, string because = "", params object[] becauseArgs) where T : struct, Enum { - assertion + assertionChain .ForCondition(Subject is { } value && GetName(value) == GetName(expected)) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:the enum} to have same name as {0}{reason}, but found {1}.", @@ -309,7 +309,7 @@ public AndConstraint HaveSameNameAs(T expected, string because = public AndConstraint NotHaveSameNameAs(T unexpected, string because = "", params object[] becauseArgs) where T : struct, Enum { - assertion + assertionChain .ForCondition(!(Subject is { } value && GetName(value) == GetName(unexpected))) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:the enum} to not have same name as {0}{reason}, but found {1}.", @@ -332,7 +332,7 @@ public AndConstraint NotHaveSameNameAs(T unexpected, string beca public AndConstraint HaveFlag(TEnum expectedFlag, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject?.HasFlag(expectedFlag) == true) .FailWith("Expected {context:the enum} to have flag {0}{reason}, but found {1}.", expectedFlag, Subject); @@ -354,7 +354,7 @@ public AndConstraint NotHaveSameNameAs(T unexpected, string beca public AndConstraint NotHaveFlag(TEnum unexpectedFlag, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject?.HasFlag(unexpectedFlag) != true) .FailWith("Expected {context:the enum} to not have flag {0}{reason}.", unexpectedFlag); @@ -382,7 +382,7 @@ public AndConstraint NotHaveSameNameAs(T unexpected, string beca { Guard.ThrowIfArgumentIsNull(predicate, nameof(predicate), "Cannot match an enum against a predicate."); - assertion + assertionChain .ForCondition(predicate.Compile()(Subject)) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:the enum} to match {1}{reason}, but found {0}.", Subject, predicate.Body); @@ -424,7 +424,7 @@ public AndConstraint BeOneOf(IEnumerable validValues, string Guard.ThrowIfArgumentIsEmpty(validValues, nameof(validValues), "Cannot assert that an enum is one of an empty list of enums"); - assertion + assertionChain .ForCondition(Subject is not null) .FailWith("Expected {context:the enum} to be one of {0}{reason}, but found ", validValues) .Then diff --git a/Src/FluentAssertions/Primitives/GuidAssertions.cs b/Src/FluentAssertions/Primitives/GuidAssertions.cs index 3d0868d297..6226bae093 100644 --- a/Src/FluentAssertions/Primitives/GuidAssertions.cs +++ b/Src/FluentAssertions/Primitives/GuidAssertions.cs @@ -10,8 +10,8 @@ namespace FluentAssertions.Primitives; [DebuggerNonUserCode] public class GuidAssertions : GuidAssertions { - public GuidAssertions(Guid? value, Assertion assertion) - : base(value, assertion) + public GuidAssertions(Guid? value, AssertionChain assertionChain) + : base(value, assertionChain) { } } @@ -25,11 +25,11 @@ public GuidAssertions(Guid? value, Assertion assertion) public class GuidAssertions where TAssertions : GuidAssertions { - private readonly Assertion assertion; + private readonly AssertionChain assertionChain; - public GuidAssertions(Guid? value, Assertion assertion) + public GuidAssertions(Guid? value, AssertionChain assertionChain) { - this.assertion = assertion; + this.assertionChain = assertionChain; Subject = value; } @@ -52,7 +52,7 @@ public GuidAssertions(Guid? value, Assertion assertion) /// public AndConstraint BeEmpty(string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject == Guid.Empty) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:Guid} to be empty{reason}, but found {0}.", Subject); @@ -72,7 +72,7 @@ public AndConstraint BeEmpty(string because = "", params object[] b /// public AndConstraint NotBeEmpty(string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject is { } value && value != Guid.Empty) .BecauseOf(because, becauseArgs) .FailWith("Did not expect {context:Guid} to be empty{reason}."); @@ -119,7 +119,7 @@ public AndConstraint Be(string expected, string because = "", param /// public AndConstraint Be(Guid expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject == expected) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:Guid} to be {0}{reason}, but found {1}.", expected, Subject); @@ -162,7 +162,7 @@ public AndConstraint NotBe(string unexpected, string because = "", /// public AndConstraint NotBe(Guid unexpected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject != unexpected) .BecauseOf(because, becauseArgs) .FailWith("Did not expect {context:Guid} to be {0}{reason}.", Subject); diff --git a/Src/FluentAssertions/Primitives/HttpResponseMessageAssertions.cs b/Src/FluentAssertions/Primitives/HttpResponseMessageAssertions.cs index eb4bffb539..c993a137ed 100644 --- a/Src/FluentAssertions/Primitives/HttpResponseMessageAssertions.cs +++ b/Src/FluentAssertions/Primitives/HttpResponseMessageAssertions.cs @@ -11,8 +11,8 @@ namespace FluentAssertions.Primitives; [DebuggerNonUserCode] public class HttpResponseMessageAssertions : HttpResponseMessageAssertions { - public HttpResponseMessageAssertions(HttpResponseMessage value, Assertion assertion) - : base(value, assertion) + public HttpResponseMessageAssertions(HttpResponseMessage value, AssertionChain assertionChain) + : base(value, assertionChain) { } } @@ -24,12 +24,12 @@ public HttpResponseMessageAssertions(HttpResponseMessage value, Assertion assert public class HttpResponseMessageAssertions : ObjectAssertions where TAssertions : HttpResponseMessageAssertions { - private readonly Assertion assertion; + private readonly AssertionChain assertionChain; - protected HttpResponseMessageAssertions(HttpResponseMessage value, Assertion assertion) - : base(value, assertion) + protected HttpResponseMessageAssertions(HttpResponseMessage value, AssertionChain assertionChain) + : base(value, assertionChain) { - this.assertion = assertion; + this.assertionChain = assertionChain; } /// @@ -44,14 +44,14 @@ protected HttpResponseMessageAssertions(HttpResponseMessage value, Assertion ass /// public AndConstraint BeSuccessful(string because = "", params object[] becauseArgs) { - var success = assertion + var success = assertionChain .ForCondition(Subject is not null) .BecauseOf(because, becauseArgs) .FailWith("Expected HttpStatusCode to be successful (2xx){reason}, but HttpResponseMessage was ."); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { - assertion + assertionChain .ForCondition(Subject!.IsSuccessStatusCode) .BecauseOf(because, becauseArgs) .FailWith("Expected HttpStatusCode to be successful (2xx){reason}, but found {0}.", Subject.StatusCode); @@ -72,14 +72,14 @@ public AndConstraint BeSuccessful(string because = "", params objec /// public AndConstraint BeRedirection(string because = "", params object[] becauseArgs) { - var success = assertion + var success = assertionChain .ForCondition(Subject is not null) .BecauseOf(because, becauseArgs) .FailWith("Expected HttpStatusCode to be redirection (3xx){reason}, but HttpResponseMessage was ."); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { - assertion + assertionChain .ForCondition((int)Subject!.StatusCode is >= 300 and <= 399) .BecauseOf(because, becauseArgs) .FailWith("Expected HttpStatusCode to be redirection (3xx){reason}, but found {0}.", Subject.StatusCode); @@ -100,14 +100,14 @@ public AndConstraint BeRedirection(string because = "", params obje /// public AndConstraint HaveError(string because = "", params object[] becauseArgs) { - var success = assertion + var success = assertionChain .ForCondition(Subject is not null) .BecauseOf(because, becauseArgs) .FailWith("Expected HttpStatusCode to be an error{reason}, but HttpResponseMessage was ."); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { - assertion + assertionChain .ForCondition(IsClientError() || IsServerError()) .BecauseOf(because, becauseArgs) .FailWith("Expected HttpStatusCode to be an error{reason}, but found {0}.", Subject.StatusCode); @@ -128,14 +128,14 @@ public AndConstraint HaveError(string because = "", params object[] /// public AndConstraint HaveClientError(string because = "", params object[] becauseArgs) { - var success = assertion + var success = assertionChain .ForCondition(Subject is not null) .BecauseOf(because, becauseArgs) .FailWith("Expected HttpStatusCode to be client error (4xx){reason}, but HttpResponseMessage was ."); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { - assertion + assertionChain .ForCondition(IsClientError()) .BecauseOf(because, becauseArgs) .FailWith("Expected HttpStatusCode to be client error (4xx){reason}, but found {0}.", Subject.StatusCode); @@ -156,14 +156,14 @@ public AndConstraint HaveClientError(string because = "", params ob /// public AndConstraint HaveServerError(string because = "", params object[] becauseArgs) { - var success = assertion + var success = assertionChain .ForCondition(Subject is not null) .BecauseOf(because, becauseArgs) .FailWith("Expected HttpStatusCode to be server error (5xx){reason}, but HttpResponseMessage was ."); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { - assertion + assertionChain .ForCondition(IsServerError()) .BecauseOf(because, becauseArgs) .FailWith("Expected HttpStatusCode to be server error (5xx){reason}, but found {0}.", Subject.StatusCode); @@ -185,14 +185,14 @@ public AndConstraint HaveServerError(string because = "", params ob /// public AndConstraint HaveStatusCode(HttpStatusCode expected, string because = "", params object[] becauseArgs) { - var success = assertion + var success = assertionChain .ForCondition(Subject is not null) .BecauseOf(because, becauseArgs) .FailWith("Expected HttpStatusCode to be {0}{reason}, but HttpResponseMessage was .", expected); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { - assertion + assertionChain .ForCondition(Subject!.StatusCode == expected) .BecauseOf(because, becauseArgs) .FailWith("Expected HttpStatusCode to be {0}{reason}, but found {1}.", expected, Subject.StatusCode); @@ -215,14 +215,14 @@ public AndConstraint HaveStatusCode(HttpStatusCode expected, string public AndConstraint NotHaveStatusCode(HttpStatusCode unexpected, string because = "", params object[] becauseArgs) { - var success = assertion + var success = assertionChain .ForCondition(Subject is not null) .BecauseOf(because, becauseArgs) .FailWith("Expected HttpStatusCode not to be {0}{reason}, but HttpResponseMessage was .", unexpected); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { - assertion + assertionChain .ForCondition(Subject!.StatusCode != unexpected) .BecauseOf(because, becauseArgs) .FailWith("Expected HttpStatusCode not to be {0}{reason}, but found {1}.", unexpected, Subject.StatusCode); diff --git a/Src/FluentAssertions/Primitives/IStringComparisonStrategy.cs b/Src/FluentAssertions/Primitives/IStringComparisonStrategy.cs index f72edf494e..6dffb8b1f4 100644 --- a/Src/FluentAssertions/Primitives/IStringComparisonStrategy.cs +++ b/Src/FluentAssertions/Primitives/IStringComparisonStrategy.cs @@ -15,5 +15,5 @@ internal interface IStringComparisonStrategy /// /// Asserts that the matches the value. /// - void ValidateAgainstMismatch(Assertion assertion, string subject, string expected); + void ValidateAgainstMismatch(AssertionChain assertionChain, string subject, string expected); } diff --git a/Src/FluentAssertions/Primitives/NegatedStringStartStrategy.cs b/Src/FluentAssertions/Primitives/NegatedStringStartStrategy.cs index 63e51a18d6..467b3aca16 100644 --- a/Src/FluentAssertions/Primitives/NegatedStringStartStrategy.cs +++ b/Src/FluentAssertions/Primitives/NegatedStringStartStrategy.cs @@ -24,9 +24,9 @@ public string ExpectationDescription private bool IgnoreCase => stringComparison == StringComparison.OrdinalIgnoreCase; - public void ValidateAgainstMismatch(Assertion assertion, string subject, string expected) + public void ValidateAgainstMismatch(AssertionChain assertionChain, string subject, string expected) { - assertion + assertionChain .ForCondition(!subject.StartsWith(expected, stringComparison)) .FailWith(ExpectationDescription + "{0}{reason}, but found {1}.", expected, subject); } diff --git a/Src/FluentAssertions/Primitives/NullableBooleanAssertions.cs b/Src/FluentAssertions/Primitives/NullableBooleanAssertions.cs index 41e648f167..ee741b3cf2 100644 --- a/Src/FluentAssertions/Primitives/NullableBooleanAssertions.cs +++ b/Src/FluentAssertions/Primitives/NullableBooleanAssertions.cs @@ -9,8 +9,8 @@ namespace FluentAssertions.Primitives; [DebuggerNonUserCode] public class NullableBooleanAssertions : NullableBooleanAssertions { - public NullableBooleanAssertions(bool? value, Assertion assertion) - : base(value, assertion) + public NullableBooleanAssertions(bool? value, AssertionChain assertionChain) + : base(value, assertionChain) { } } @@ -22,12 +22,12 @@ public NullableBooleanAssertions(bool? value, Assertion assertion) public class NullableBooleanAssertions : BooleanAssertions where TAssertions : NullableBooleanAssertions { - private readonly Assertion assertion; + private readonly AssertionChain assertionChain; - public NullableBooleanAssertions(bool? value, Assertion assertion) - : base(value, assertion) + public NullableBooleanAssertions(bool? value, AssertionChain assertionChain) + : base(value, assertionChain) { - this.assertion = assertion; + this.assertionChain = assertionChain; } /// @@ -42,7 +42,7 @@ public NullableBooleanAssertions(bool? value, Assertion assertion) /// public AndConstraint HaveValue(string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject.HasValue) .BecauseOf(because, becauseArgs) .FailWith("Expected a value{reason}."); @@ -77,7 +77,7 @@ public AndConstraint NotBeNull(string because = "", params object[] /// public AndConstraint NotHaveValue(string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(!Subject.HasValue) .BecauseOf(because, becauseArgs) .FailWith("Did not expect a value{reason}, but found {0}.", Subject); @@ -113,7 +113,7 @@ public AndConstraint BeNull(string because = "", params object[] be /// public AndConstraint Be(bool? expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject == expected) .BecauseOf(because, becauseArgs) .FailWith("Expected {0}{reason}, but found {1}.", expected, Subject); @@ -134,7 +134,7 @@ public AndConstraint Be(bool? expected, string because = "", params /// public AndConstraint NotBe(bool? unexpected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject != unexpected) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:nullable boolean} not to be {0}{reason}, but found {1}.", unexpected, Subject); @@ -154,7 +154,7 @@ public AndConstraint NotBe(bool? unexpected, string because = "", p /// public AndConstraint NotBeFalse(string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject is not false) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:nullable boolean} not to be {0}{reason}, but found {1}.", false, Subject); @@ -174,7 +174,7 @@ public AndConstraint NotBeFalse(string because = "", params object[ /// public AndConstraint NotBeTrue(string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject is not true) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:nullable boolean} not to be {0}{reason}, but found {1}.", true, Subject); diff --git a/Src/FluentAssertions/Primitives/NullableDateOnlyAssertions.cs b/Src/FluentAssertions/Primitives/NullableDateOnlyAssertions.cs index 3e1ade0473..2d3410b64a 100644 --- a/Src/FluentAssertions/Primitives/NullableDateOnlyAssertions.cs +++ b/Src/FluentAssertions/Primitives/NullableDateOnlyAssertions.cs @@ -12,8 +12,8 @@ namespace FluentAssertions.Primitives; [DebuggerNonUserCode] public class NullableDateOnlyAssertions : NullableDateOnlyAssertions { - public NullableDateOnlyAssertions(DateOnly? value, Assertion assertion) - : base(value, assertion) + public NullableDateOnlyAssertions(DateOnly? value, AssertionChain assertionChain) + : base(value, assertionChain) { } } @@ -25,12 +25,12 @@ public NullableDateOnlyAssertions(DateOnly? value, Assertion assertion) public class NullableDateOnlyAssertions : DateOnlyAssertions where TAssertions : NullableDateOnlyAssertions { - private readonly Assertion assertion; + private readonly AssertionChain assertionChain; - public NullableDateOnlyAssertions(DateOnly? value, Assertion assertion) - : base(value, assertion) + public NullableDateOnlyAssertions(DateOnly? value, AssertionChain assertionChain) + : base(value, assertionChain) { - this.assertion = assertion; + this.assertionChain = assertionChain; } /// @@ -45,7 +45,7 @@ public NullableDateOnlyAssertions(DateOnly? value, Assertion assertion) /// public AndConstraint HaveValue(string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject.HasValue) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:nullable date} to have a value{reason}, but found {0}.", Subject); @@ -80,7 +80,7 @@ public AndConstraint NotBeNull(string because = "", params object[] /// public AndConstraint NotHaveValue(string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(!Subject.HasValue) .BecauseOf(because, becauseArgs) .FailWith("Did not expect {context:nullable date} to have a value{reason}, but found {0}.", Subject); diff --git a/Src/FluentAssertions/Primitives/NullableDateTimeAssertions.cs b/Src/FluentAssertions/Primitives/NullableDateTimeAssertions.cs index 8870ee1952..d62ea4e94a 100644 --- a/Src/FluentAssertions/Primitives/NullableDateTimeAssertions.cs +++ b/Src/FluentAssertions/Primitives/NullableDateTimeAssertions.cs @@ -14,8 +14,8 @@ namespace FluentAssertions.Primitives; [DebuggerNonUserCode] public class NullableDateTimeAssertions : NullableDateTimeAssertions { - public NullableDateTimeAssertions(DateTime? expected, Assertion assertion) - : base(expected, assertion) + public NullableDateTimeAssertions(DateTime? expected, AssertionChain assertionChain) + : base(expected, assertionChain) { } } @@ -30,12 +30,12 @@ public NullableDateTimeAssertions(DateTime? expected, Assertion assertion) public class NullableDateTimeAssertions : DateTimeAssertions where TAssertions : NullableDateTimeAssertions { - private readonly Assertion assertion; + private readonly AssertionChain assertionChain; - public NullableDateTimeAssertions(DateTime? expected, Assertion assertion) - : base(expected, assertion) + public NullableDateTimeAssertions(DateTime? expected, AssertionChain assertionChain) + : base(expected, assertionChain) { - this.assertion = assertion; + this.assertionChain = assertionChain; } /// @@ -50,7 +50,7 @@ public NullableDateTimeAssertions(DateTime? expected, Assertion assertion) /// public AndConstraint HaveValue(string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject.HasValue) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:nullable date and time} to have a value{reason}, but found {0}.", Subject); @@ -85,7 +85,7 @@ public AndConstraint NotBeNull(string because = "", params object[] /// public AndConstraint NotHaveValue(string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(!Subject.HasValue) .BecauseOf(because, becauseArgs) .FailWith("Did not expect {context:nullable date and time} to have a value{reason}, but found {0}.", Subject); diff --git a/Src/FluentAssertions/Primitives/NullableDateTimeOffsetAssertions.cs b/Src/FluentAssertions/Primitives/NullableDateTimeOffsetAssertions.cs index 5e39c98762..340be6a253 100644 --- a/Src/FluentAssertions/Primitives/NullableDateTimeOffsetAssertions.cs +++ b/Src/FluentAssertions/Primitives/NullableDateTimeOffsetAssertions.cs @@ -14,12 +14,12 @@ namespace FluentAssertions.Primitives; [DebuggerNonUserCode] public class NullableDateTimeOffsetAssertions : NullableDateTimeOffsetAssertions { - private readonly Assertion assertion; + private readonly AssertionChain assertionChain; - public NullableDateTimeOffsetAssertions(DateTimeOffset? expected, Assertion assertion) - : base(expected, assertion) + public NullableDateTimeOffsetAssertions(DateTimeOffset? expected, AssertionChain assertionChain) + : base(expected, assertionChain) { - this.assertion = assertion; + this.assertionChain = assertionChain; } } @@ -34,12 +34,12 @@ public NullableDateTimeOffsetAssertions(DateTimeOffset? expected, Assertion asse public class NullableDateTimeOffsetAssertions : DateTimeOffsetAssertions where TAssertions : NullableDateTimeOffsetAssertions { - private readonly Assertion assertion; + private readonly AssertionChain assertionChain; - public NullableDateTimeOffsetAssertions(DateTimeOffset? expected, Assertion assertion) - : base(expected, assertion) + public NullableDateTimeOffsetAssertions(DateTimeOffset? expected, AssertionChain assertionChain) + : base(expected, assertionChain) { - this.assertion = assertion; + this.assertionChain = assertionChain; } /// @@ -54,7 +54,7 @@ public NullableDateTimeOffsetAssertions(DateTimeOffset? expected, Assertion asse /// public AndConstraint HaveValue(string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject.HasValue) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:variable} to have a value{reason}, but found {0}", Subject); @@ -90,7 +90,7 @@ public AndConstraint NotBeNull(string because = "", params object[] public AndConstraint NotHaveValue(string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(!Subject.HasValue) .BecauseOf(because, becauseArgs) .FailWith("Did not expect {context:variable} to have a value{reason}, but found {0}", Subject); diff --git a/Src/FluentAssertions/Primitives/NullableEnumAssertions.cs b/Src/FluentAssertions/Primitives/NullableEnumAssertions.cs index d8e6234106..c7bc5ed017 100644 --- a/Src/FluentAssertions/Primitives/NullableEnumAssertions.cs +++ b/Src/FluentAssertions/Primitives/NullableEnumAssertions.cs @@ -9,8 +9,8 @@ namespace FluentAssertions.Primitives; public class NullableEnumAssertions : NullableEnumAssertions> where TEnum : struct, Enum { - public NullableEnumAssertions(TEnum? subject, Assertion assertion) - : base(subject, assertion) + public NullableEnumAssertions(TEnum? subject, AssertionChain assertionChain) + : base(subject, assertionChain) { } } @@ -22,12 +22,12 @@ public class NullableEnumAssertions : EnumAssertions { - private readonly Assertion assertion; + private readonly AssertionChain assertionChain; - public NullableEnumAssertions(TEnum? subject, Assertion assertion) - : base(subject, assertion) + public NullableEnumAssertions(TEnum? subject, AssertionChain assertionChain) + : base(subject, assertionChain) { - this.assertion = assertion; + this.assertionChain = assertionChain; } /// @@ -42,7 +42,7 @@ public NullableEnumAssertions(TEnum? subject, Assertion assertion) /// public AndWhichConstraint HaveValue(string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject.HasValue) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:nullable enum} to have a value{reason}, but found {0}.", Subject); @@ -77,7 +77,7 @@ public NullableEnumAssertions(TEnum? subject, Assertion assertion) /// public AndConstraint NotHaveValue(string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(!Subject.HasValue) .BecauseOf(because, becauseArgs) .FailWith("Did not expect {context:nullable enum} to have a value{reason}, but found {0}.", Subject); diff --git a/Src/FluentAssertions/Primitives/NullableGuidAssertions.cs b/Src/FluentAssertions/Primitives/NullableGuidAssertions.cs index 5d1d616705..d37b04fc7c 100644 --- a/Src/FluentAssertions/Primitives/NullableGuidAssertions.cs +++ b/Src/FluentAssertions/Primitives/NullableGuidAssertions.cs @@ -10,8 +10,8 @@ namespace FluentAssertions.Primitives; [DebuggerNonUserCode] public class NullableGuidAssertions : NullableGuidAssertions { - public NullableGuidAssertions(Guid? value, Assertion assertion) - : base(value, assertion) + public NullableGuidAssertions(Guid? value, AssertionChain assertionChain) + : base(value, assertionChain) { } } @@ -23,12 +23,12 @@ public NullableGuidAssertions(Guid? value, Assertion assertion) public class NullableGuidAssertions : GuidAssertions where TAssertions : NullableGuidAssertions { - private readonly Assertion assertion; + private readonly AssertionChain assertionChain; - public NullableGuidAssertions(Guid? value, Assertion assertion) - : base(value, assertion) + public NullableGuidAssertions(Guid? value, AssertionChain assertionChain) + : base(value, assertionChain) { - this.assertion = assertion; + this.assertionChain = assertionChain; } /// @@ -43,7 +43,7 @@ public NullableGuidAssertions(Guid? value, Assertion assertion) /// public AndConstraint HaveValue(string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject.HasValue) .BecauseOf(because, becauseArgs) .FailWith("Expected a value{reason}."); @@ -78,7 +78,7 @@ public AndConstraint NotBeNull(string because = "", params object[] /// public AndConstraint NotHaveValue(string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(!Subject.HasValue) .BecauseOf(because, becauseArgs) .FailWith("Did not expect a value{reason}, but found {0}.", Subject); @@ -114,7 +114,7 @@ public AndConstraint BeNull(string because = "", params object[] be /// public AndConstraint Be(Guid? expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject == expected) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:Guid} to be {0}{reason}, but found {1}.", expected, Subject); diff --git a/Src/FluentAssertions/Primitives/NullableSimpleTimeSpanAssertions.cs b/Src/FluentAssertions/Primitives/NullableSimpleTimeSpanAssertions.cs index 730abb7c51..eac90cf891 100644 --- a/Src/FluentAssertions/Primitives/NullableSimpleTimeSpanAssertions.cs +++ b/Src/FluentAssertions/Primitives/NullableSimpleTimeSpanAssertions.cs @@ -14,8 +14,8 @@ namespace FluentAssertions.Primitives; [DebuggerNonUserCode] public class NullableSimpleTimeSpanAssertions : NullableSimpleTimeSpanAssertions { - public NullableSimpleTimeSpanAssertions(TimeSpan? value, Assertion assertion) - : base(value, assertion) + public NullableSimpleTimeSpanAssertions(TimeSpan? value, AssertionChain assertionChain) + : base(value, assertionChain) { } } @@ -31,12 +31,12 @@ public NullableSimpleTimeSpanAssertions(TimeSpan? value, Assertion assertion) public class NullableSimpleTimeSpanAssertions : SimpleTimeSpanAssertions where TAssertions : NullableSimpleTimeSpanAssertions { - private readonly Assertion assertion; + private readonly AssertionChain assertionChain; - public NullableSimpleTimeSpanAssertions(TimeSpan? value, Assertion assertion) - : base(value, assertion) + public NullableSimpleTimeSpanAssertions(TimeSpan? value, AssertionChain assertionChain) + : base(value, assertionChain) { - this.assertion = assertion; + this.assertionChain = assertionChain; } /// @@ -51,7 +51,7 @@ public NullableSimpleTimeSpanAssertions(TimeSpan? value, Assertion assertion) /// public AndConstraint HaveValue(string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject.HasValue) .BecauseOf(because, becauseArgs) .FailWith("Expected a value{reason}."); @@ -86,7 +86,7 @@ public AndConstraint NotBeNull(string because = "", params object[] /// public AndConstraint NotHaveValue(string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(!Subject.HasValue) .BecauseOf(because, becauseArgs) .FailWith("Did not expect a value{reason}, but found {0}.", Subject); @@ -123,7 +123,7 @@ public AndConstraint BeNull(string because = "", params object[] be public AndConstraint Be(TimeSpan? expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject == expected) .BecauseOf(because, becauseArgs) .FailWith("Expected {0}{reason}, but found {1}.", expected, Subject); diff --git a/Src/FluentAssertions/Primitives/NullableTimeOnlyAssertions.cs b/Src/FluentAssertions/Primitives/NullableTimeOnlyAssertions.cs index 8465c1ec15..0a6fbc7337 100644 --- a/Src/FluentAssertions/Primitives/NullableTimeOnlyAssertions.cs +++ b/Src/FluentAssertions/Primitives/NullableTimeOnlyAssertions.cs @@ -12,8 +12,8 @@ namespace FluentAssertions.Primitives; [DebuggerNonUserCode] public class NullableTimeOnlyAssertions : NullableTimeOnlyAssertions { - public NullableTimeOnlyAssertions(TimeOnly? value, Assertion assertion) - : base(value, assertion) + public NullableTimeOnlyAssertions(TimeOnly? value, AssertionChain assertionChain) + : base(value, assertionChain) { } } @@ -25,12 +25,12 @@ public NullableTimeOnlyAssertions(TimeOnly? value, Assertion assertion) public class NullableTimeOnlyAssertions : TimeOnlyAssertions where TAssertions : NullableTimeOnlyAssertions { - private readonly Assertion assertion; + private readonly AssertionChain assertionChain; - public NullableTimeOnlyAssertions(TimeOnly? value, Assertion assertion) - : base(value, assertion) + public NullableTimeOnlyAssertions(TimeOnly? value, AssertionChain assertionChain) + : base(value, assertionChain) { - this.assertion = assertion; + this.assertionChain = assertionChain; } /// @@ -45,7 +45,7 @@ public NullableTimeOnlyAssertions(TimeOnly? value, Assertion assertion) /// public AndConstraint HaveValue(string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject.HasValue) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:nullable time} to have a value{reason}, but found {0}.", Subject); @@ -80,7 +80,7 @@ public AndConstraint NotBeNull(string because = "", params object[] /// public AndConstraint NotHaveValue(string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(!Subject.HasValue) .BecauseOf(because, becauseArgs) .FailWith("Did not expect {context:nullable time} to have a value{reason}, but found {0}.", Subject); diff --git a/Src/FluentAssertions/Primitives/ObjectAssertions.cs b/Src/FluentAssertions/Primitives/ObjectAssertions.cs index d5faad3c25..4473430ee2 100644 --- a/Src/FluentAssertions/Primitives/ObjectAssertions.cs +++ b/Src/FluentAssertions/Primitives/ObjectAssertions.cs @@ -12,12 +12,12 @@ namespace FluentAssertions.Primitives; /// public class ObjectAssertions : ObjectAssertions { - private readonly Assertion assertion; + private readonly AssertionChain assertionChain; - public ObjectAssertions(object value, Assertion assertion) - : base(value, assertion) + public ObjectAssertions(object value, AssertionChain assertionChain) + : base(value, assertionChain) { - this.assertion = assertion; + this.assertionChain = assertionChain; } /// @@ -39,7 +39,7 @@ public AndConstraint Be(TExpectation expected, I { Guard.ThrowIfArgumentIsNull(comparer); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is TExpectation subject && comparer.Equals(subject, expected)) .WithDefaultIdentifier(Identifier) @@ -68,7 +68,7 @@ public AndConstraint NotBe(TExpectation unexpect { Guard.ThrowIfArgumentIsNull(comparer); - assertion + assertionChain .ForCondition(Subject is not TExpectation subject || !comparer.Equals(subject, unexpected)) .BecauseOf(because, becauseArgs) .WithDefaultIdentifier(Identifier) @@ -103,7 +103,7 @@ public AndConstraint NotBe(TExpectation unexpect Guard.ThrowIfArgumentIsNull(validValues); Guard.ThrowIfArgumentIsNull(comparer); - assertion + assertionChain .ForCondition(Subject is TExpectation subject && validValues.Contains(subject, comparer)) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:object} to be one of {0}{reason}, but found {1}.", validValues, Subject); @@ -120,12 +120,12 @@ public AndConstraint NotBe(TExpectation unexpect public class ObjectAssertions : ReferenceTypeAssertions where TAssertions : ObjectAssertions { - private readonly Assertion assertion; + private readonly AssertionChain assertionChain; - public ObjectAssertions(TSubject value, Assertion assertion) - : base(value, assertion) + public ObjectAssertions(TSubject value, AssertionChain assertionChain) + : base(value, assertionChain) { - this.assertion = assertion; + this.assertionChain = assertionChain; } /// @@ -141,7 +141,7 @@ public ObjectAssertions(TSubject value, Assertion assertion) /// public AndConstraint Be(TSubject expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(ObjectExtensions.GetComparer()(Subject, expected)) .WithDefaultIdentifier(Identifier) @@ -170,7 +170,7 @@ public AndConstraint Be(TSubject expected, IEqualityComparer Be(TSubject expected, IEqualityComparer public AndConstraint NotBe(TSubject unexpected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(!ObjectExtensions.GetComparer()(Subject, unexpected)) .BecauseOf(because, becauseArgs) .WithDefaultIdentifier(Identifier) @@ -221,7 +221,7 @@ public AndConstraint NotBe(TSubject unexpected, IEqualityComparer NotBe(TSubject unexpected, IEqualityComparer 0; } - assertion + assertionChain .ForCondition(hasMismatches) .BecauseOf(because, becauseArgs) .WithDefaultIdentifier(Identifier) @@ -407,7 +407,7 @@ public AndConstraint BeOneOf(params TSubject[] validValues) public AndConstraint BeOneOf(IEnumerable validValues, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(validValues.Contains(Subject)) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:object} to be one of {0}{reason}, but found {1}.", validValues, Subject); @@ -441,7 +441,7 @@ public AndConstraint BeOneOf(params TSubject[] validValues) Guard.ThrowIfArgumentIsNull(validValues); Guard.ThrowIfArgumentIsNull(comparer); - assertion + assertionChain .ForCondition(validValues.Contains(Subject, comparer)) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:object} to be one of {0}{reason}, but found {1}.", validValues, Subject); diff --git a/Src/FluentAssertions/Primitives/ReferenceTypeAssertions.cs b/Src/FluentAssertions/Primitives/ReferenceTypeAssertions.cs index 8bb0590218..6417fde60d 100644 --- a/Src/FluentAssertions/Primitives/ReferenceTypeAssertions.cs +++ b/Src/FluentAssertions/Primitives/ReferenceTypeAssertions.cs @@ -15,9 +15,9 @@ namespace FluentAssertions.Primitives; public abstract class ReferenceTypeAssertions where TAssertions : ReferenceTypeAssertions { - protected ReferenceTypeAssertions(TSubject subject, Assertion assertion) + protected ReferenceTypeAssertions(TSubject subject, AssertionChain assertionChain) { - this.CurrentAssertion = assertion; + this.CurrentAssertionChain = assertionChain; Subject = subject; } @@ -38,7 +38,7 @@ protected ReferenceTypeAssertions(TSubject subject, Assertion assertion) /// public AndConstraint BeNull(string because = "", params object[] becauseArgs) { - CurrentAssertion + CurrentAssertionChain .ForCondition(Subject is null) .BecauseOf(because, becauseArgs) .WithDefaultIdentifier(Identifier) @@ -59,7 +59,7 @@ public AndConstraint BeNull(string because = "", params object[] be /// public AndConstraint NotBeNull(string because = "", params object[] becauseArgs) { - CurrentAssertion + CurrentAssertionChain .ForCondition(Subject is not null) .BecauseOf(because, becauseArgs) .WithDefaultIdentifier(Identifier) @@ -81,7 +81,7 @@ public AndConstraint NotBeNull(string because = "", params object[] /// public AndConstraint BeSameAs(TSubject expected, string because = "", params object[] becauseArgs) { - CurrentAssertion + CurrentAssertionChain .UsingLineBreaks .ForCondition(ReferenceEquals(Subject, expected)) .BecauseOf(because, becauseArgs) @@ -104,7 +104,7 @@ public AndConstraint BeSameAs(TSubject expected, string because = " /// public AndConstraint NotBeSameAs(TSubject unexpected, string because = "", params object[] becauseArgs) { - CurrentAssertion + CurrentAssertionChain .UsingLineBreaks .ForCondition(!ReferenceEquals(Subject, unexpected)) .BecauseOf(because, becauseArgs) @@ -154,13 +154,13 @@ public AndConstraint BeOfType(Type expectedType, string because = " { Guard.ThrowIfArgumentIsNull(expectedType); - CurrentAssertion + CurrentAssertionChain .ForCondition(Subject is not null) .BecauseOf(because, becauseArgs) .WithDefaultIdentifier("type") .FailWith("Expected {context} to be {0}{reason}, but found .", expectedType); - if (CurrentAssertion.Succeeded) + if (CurrentAssertionChain.Succeeded) { Type subjectType = Subject.GetType(); @@ -213,13 +213,13 @@ public AndConstraint NotBeOfType(Type unexpectedType, string becaus { Guard.ThrowIfArgumentIsNull(unexpectedType); - CurrentAssertion + CurrentAssertionChain .ForCondition(Subject is not null) .BecauseOf(because, becauseArgs) .WithDefaultIdentifier("type") .FailWith("Expected {context} not to be {0}{reason}, but found .", unexpectedType); - if (CurrentAssertion.Succeeded) + if (CurrentAssertionChain.Succeeded) { Type subjectType = Subject.GetType(); @@ -250,15 +250,15 @@ public AndConstraint NotBeOfType(Type unexpectedType, string becaus /// An which can be used to chain assertions. public AndWhichConstraint BeAssignableTo(string because = "", params object[] becauseArgs) { - CurrentAssertion + CurrentAssertionChain .ForCondition(Subject is not null) .BecauseOf(because, becauseArgs) .WithDefaultIdentifier("type") .FailWith("Expected {context} to be assignable to {0}{reason}, but found .", typeof(T)); - if (CurrentAssertion.Succeeded) + if (CurrentAssertionChain.Succeeded) { - CurrentAssertion + CurrentAssertionChain .ForCondition(Subject is T) .BecauseOf(because, becauseArgs) .WithDefaultIdentifier(Identifier) @@ -289,19 +289,19 @@ public AndConstraint BeAssignableTo(Type type, string because = "", { Guard.ThrowIfArgumentIsNull(type); - CurrentAssertion + CurrentAssertionChain .ForCondition(Subject is not null) .BecauseOf(because, becauseArgs) .WithDefaultIdentifier("type") .FailWith("Expected {context} to be assignable to {0}{reason}, but found .", type); - if (CurrentAssertion.Succeeded) + if (CurrentAssertionChain.Succeeded) { bool isAssignable = type.IsGenericTypeDefinition ? Subject.GetType().IsAssignableToOpenGeneric(type) : type.IsAssignableFrom(Subject.GetType()); - CurrentAssertion + CurrentAssertionChain .ForCondition(isAssignable) .BecauseOf(because, becauseArgs) .WithDefaultIdentifier(Identifier) @@ -347,19 +347,19 @@ public AndConstraint NotBeAssignableTo(Type type, string because = { Guard.ThrowIfArgumentIsNull(type); - CurrentAssertion + CurrentAssertionChain .ForCondition(Subject is not null) .BecauseOf(because, becauseArgs) .WithDefaultIdentifier("type") .FailWith("Expected {context} to not be assignable to {0}{reason}, but found .", type); - if (CurrentAssertion.Succeeded) + if (CurrentAssertionChain.Succeeded) { bool isAssignable = type.IsGenericTypeDefinition ? Subject.GetType().IsAssignableToOpenGeneric(type) : type.IsAssignableFrom(Subject.GetType()); - CurrentAssertion + CurrentAssertionChain .ForCondition(!isAssignable) .BecauseOf(because, becauseArgs) .WithDefaultIdentifier(Identifier) @@ -408,7 +408,7 @@ public AndConstraint NotBeAssignableTo(Type type, string because = { Guard.ThrowIfArgumentIsNull(predicate, nameof(predicate), "Cannot match an object against a predicate."); - CurrentAssertion + CurrentAssertionChain .ForCondition(predicate.Compile()((T)Subject)) .BecauseOf(because, becauseArgs) .WithDefaultIdentifier(Identifier) @@ -427,5 +427,5 @@ public AndConstraint NotBeAssignableTo(Type type, string because = public override bool Equals(object obj) => throw new NotSupportedException("Equals is not part of Fluent Assertions. Did you mean BeSameAs() instead?"); - public Assertion CurrentAssertion { get; } + public AssertionChain CurrentAssertionChain { get; } } diff --git a/Src/FluentAssertions/Primitives/SimpleTimeSpanAssertions.cs b/Src/FluentAssertions/Primitives/SimpleTimeSpanAssertions.cs index 2114c591db..4eb9b60041 100644 --- a/Src/FluentAssertions/Primitives/SimpleTimeSpanAssertions.cs +++ b/Src/FluentAssertions/Primitives/SimpleTimeSpanAssertions.cs @@ -11,8 +11,8 @@ namespace FluentAssertions.Primitives; [DebuggerNonUserCode] public class SimpleTimeSpanAssertions : SimpleTimeSpanAssertions { - public SimpleTimeSpanAssertions(TimeSpan? value, Assertion assertion) - : base(value, assertion) + public SimpleTimeSpanAssertions(TimeSpan? value, AssertionChain assertionChain) + : base(value, assertionChain) { } } @@ -26,11 +26,11 @@ public SimpleTimeSpanAssertions(TimeSpan? value, Assertion assertion) public class SimpleTimeSpanAssertions where TAssertions : SimpleTimeSpanAssertions { - private readonly Assertion assertion; + private readonly AssertionChain assertionChain; - public SimpleTimeSpanAssertions(TimeSpan? value, Assertion assertion) + public SimpleTimeSpanAssertions(TimeSpan? value, AssertionChain assertionChain) { - this.assertion = assertion; + this.assertionChain = assertionChain; Subject = value; } @@ -51,7 +51,7 @@ public SimpleTimeSpanAssertions(TimeSpan? value, Assertion assertion) /// public AndConstraint BePositive(string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject > TimeSpan.Zero) .FailWith("Expected {context:time} to be positive{reason}, but found {0}.", Subject); @@ -71,7 +71,7 @@ public AndConstraint BePositive(string because = "", params object[ /// public AndConstraint BeNegative(string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject < TimeSpan.Zero) .FailWith("Expected {context:time} to be negative{reason}, but found {0}.", Subject); @@ -93,7 +93,7 @@ public AndConstraint BeNegative(string because = "", params object[ /// public AndConstraint Be(TimeSpan expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(expected == Subject) .FailWith("Expected {0}{reason}, but found {1}.", expected, Subject); @@ -115,7 +115,7 @@ public AndConstraint Be(TimeSpan expected, string because = "", par /// public AndConstraint NotBe(TimeSpan unexpected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(unexpected != Subject) .BecauseOf(because, becauseArgs) .FailWith("Did not expect {0}{reason}.", unexpected); @@ -137,7 +137,7 @@ public AndConstraint NotBe(TimeSpan unexpected, string because = "" /// public AndConstraint BeLessThan(TimeSpan expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject < expected) .FailWith("Expected {context:time} to be less than {0}{reason}, but found {1}.", expected, Subject); @@ -159,7 +159,7 @@ public AndConstraint BeLessThan(TimeSpan expected, string because = /// public AndConstraint BeLessThanOrEqualTo(TimeSpan expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject <= expected) .FailWith("Expected {context:time} to be less than or equal to {0}{reason}, but found {1}.", expected, Subject); @@ -181,7 +181,7 @@ public AndConstraint BeLessThanOrEqualTo(TimeSpan expected, string /// public AndConstraint BeGreaterThan(TimeSpan expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject > expected) .FailWith("Expected {context:time} to be greater than {0}{reason}, but found {1}.", expected, Subject); @@ -204,7 +204,7 @@ public AndConstraint BeGreaterThan(TimeSpan expected, string becaus public AndConstraint BeGreaterThanOrEqualTo(TimeSpan expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject >= expected) .FailWith("Expected {context:time} to be greater than or equal to {0}{reason}, but found {1}.", expected, Subject); @@ -242,7 +242,7 @@ public AndConstraint BeGreaterThan(TimeSpan expected, string becaus TimeSpan minimumValue = nearbyTime - precision; TimeSpan maximumValue = nearbyTime + precision; - assertion + assertionChain .ForCondition(Subject >= minimumValue && Subject.Value <= maximumValue) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:time} to be within {0} from {1}{reason}, but found {2}.", @@ -282,7 +282,7 @@ public AndConstraint BeGreaterThan(TimeSpan expected, string becaus TimeSpan minimumValue = distantTime - precision; TimeSpan maximumValue = distantTime + precision; - assertion + assertionChain .ForCondition(Subject < minimumValue || Subject > maximumValue) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:time} to not be within {0} from {1}{reason}, but found {2}.", diff --git a/Src/FluentAssertions/Primitives/StringAssertions.cs b/Src/FluentAssertions/Primitives/StringAssertions.cs index aa7c9f7968..49bfc1a6ad 100644 --- a/Src/FluentAssertions/Primitives/StringAssertions.cs +++ b/Src/FluentAssertions/Primitives/StringAssertions.cs @@ -19,8 +19,8 @@ public class StringAssertions : StringAssertions /// /// Initializes a new instance of the class. /// - public StringAssertions(string value, Assertion assertion) - : base(value, assertion) + public StringAssertions(string value, AssertionChain assertionChain) + : base(value, assertionChain) { } } @@ -32,15 +32,15 @@ public StringAssertions(string value, Assertion assertion) public class StringAssertions : ReferenceTypeAssertions where TAssertions : StringAssertions { - private readonly Assertion assertion; + private readonly AssertionChain assertionChain; /// /// Initializes a new instance of the class. /// - public StringAssertions(string value, Assertion assertion) - : base(value, assertion) + public StringAssertions(string value, AssertionChain assertionChain) + : base(value, assertionChain) { - this.assertion = assertion; + this.assertionChain = assertionChain; } /// @@ -56,7 +56,7 @@ public StringAssertions(string value, Assertion assertion) /// public AndConstraint Be(string expected, string because = "", params object[] becauseArgs) { - var stringEqualityValidator = new StringValidator(assertion, + var stringEqualityValidator = new StringValidator(assertionChain, new StringEqualityStrategy(StringComparison.Ordinal), because, becauseArgs); @@ -91,7 +91,7 @@ public AndConstraint BeOneOf(params string[] validValues) /// public AndConstraint BeOneOf(IEnumerable validValues, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(validValues.Contains(Subject)) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:string} to be one of {0}{reason}, but found {1}.", validValues, Subject); @@ -116,7 +116,7 @@ public AndConstraint BeOneOf(IEnumerable validValues, strin public AndConstraint BeEquivalentTo(string expected, string because = "", params object[] becauseArgs) { - var expectation = new StringValidator(assertion, + var expectation = new StringValidator(assertionChain, new StringEqualityStrategy(StringComparison.OrdinalIgnoreCase), because, becauseArgs); @@ -150,7 +150,7 @@ public AndConstraint BeOneOf(IEnumerable validValues, strin notEquivalent = scope.Discard().Length > 0; } - assertion + assertionChain .ForCondition(notEquivalent) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:string} not to be equivalent to {0}{reason}, but they are.", unexpected); @@ -172,7 +172,7 @@ public AndConstraint BeOneOf(IEnumerable validValues, strin /// public AndConstraint NotBe(string unexpected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject != unexpected) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:string} not to be {0}{reason}.", unexpected); @@ -223,7 +223,7 @@ public AndConstraint Match(string wildcardPattern, string because = Guard.ThrowIfArgumentIsEmpty(wildcardPattern, nameof(wildcardPattern), "Cannot match string against an empty string. Provide a wildcard pattern or use the BeEmpty method."); - var stringWildcardMatchingValidator = new StringValidator(assertion, + var stringWildcardMatchingValidator = new StringValidator(assertionChain, new StringWildcardMatchingStrategy(), because, becauseArgs); @@ -275,7 +275,7 @@ public AndConstraint NotMatch(string wildcardPattern, string becaus Guard.ThrowIfArgumentIsEmpty(wildcardPattern, nameof(wildcardPattern), "Cannot match string against an empty string. Provide a wildcard pattern or use the NotBeEmpty method."); - var stringWildcardMatchingValidator = new StringValidator(assertion, + var stringWildcardMatchingValidator = new StringValidator(assertionChain, new StringWildcardMatchingStrategy { Negate = true @@ -331,7 +331,7 @@ public AndConstraint NotMatch(string wildcardPattern, string becaus Guard.ThrowIfArgumentIsEmpty(wildcardPattern, nameof(wildcardPattern), "Cannot match string against an empty string. Provide a wildcard pattern or use the BeEmpty method."); - var stringWildcardMatchingValidator = new StringValidator(assertion, + var stringWildcardMatchingValidator = new StringValidator(assertionChain, new StringWildcardMatchingStrategy { IgnoreCase = true, @@ -388,7 +388,7 @@ public AndConstraint NotMatch(string wildcardPattern, string becaus Guard.ThrowIfArgumentIsEmpty(wildcardPattern, nameof(wildcardPattern), "Cannot match string against an empty string. Provide a wildcard pattern or use the NotBeEmpty method."); - var stringWildcardMatchingValidator = new StringValidator(assertion, + var stringWildcardMatchingValidator = new StringValidator(assertionChain, new StringWildcardMatchingStrategy { IgnoreCase = true, @@ -436,7 +436,7 @@ public AndConstraint NotMatch(string wildcardPattern, string becaus } catch (ArgumentException) { - assertion.FailWith("Cannot match {context:string} against {0} because it is not a valid regular expression.", + assertionChain.FailWith("Cannot match {context:string} against {0} because it is not a valid regular expression.", regularExpression); return new AndConstraint((TAssertions)this); @@ -473,7 +473,7 @@ public AndConstraint NotMatch(string wildcardPattern, string becaus } catch (ArgumentException) { - assertion.FailWith("Cannot match {context:string} against {0} because it is not a valid regular expression.", + assertionChain.FailWith("Cannot match {context:string} against {0} because it is not a valid regular expression.", regularExpression); return new AndConstraint((TAssertions)this); @@ -514,17 +514,17 @@ public AndConstraint NotMatch(string wildcardPattern, string becaus Guard.ThrowIfArgumentIsEmpty(regexStr, nameof(regularExpression), "Cannot match string against an empty string. Provide a regex pattern or use the BeEmpty method."); - assertion + assertionChain .ForCondition(Subject is not null) .UsingLineBreaks .BecauseOf(because, becauseArgs) .FailWith("Expected {context:string} to match regex {0}{reason}, but it was .", regexStr); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { int actual = regularExpression.Matches(Subject).Count; - assertion + assertionChain .ForConstraint(occurrenceConstraint, actual) .UsingLineBreaks .BecauseOf(because, becauseArgs) @@ -562,15 +562,15 @@ public AndConstraint NotMatch(string wildcardPattern, string becaus Guard.ThrowIfArgumentIsEmpty(regexStr, nameof(regularExpression), "Cannot match string against an empty string. Provide a regex pattern or use the BeEmpty method."); - assertion + assertionChain .ForCondition(Subject is not null) .UsingLineBreaks .BecauseOf(because, becauseArgs) .FailWith("Expected {context:string} to match regex {0}{reason}, but it was .", regexStr); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { - assertion + assertionChain .ForCondition(regularExpression.IsMatch(Subject)) .BecauseOf(because, becauseArgs) .UsingLineBreaks @@ -608,7 +608,7 @@ public AndConstraint NotMatch(string wildcardPattern, string becaus } catch (ArgumentException) { - assertion.FailWith("Cannot match {context:string} against {0} because it is not a valid regular expression.", + assertionChain.FailWith("Cannot match {context:string} against {0} because it is not a valid regular expression.", regularExpression); return new AndConstraint((TAssertions)this); @@ -642,15 +642,15 @@ public AndConstraint NotMatchRegex(Regex regularExpression, string Guard.ThrowIfArgumentIsEmpty(regexStr, nameof(regularExpression), "Cannot match string against an empty regex pattern. Provide a regex pattern or use the NotBeEmpty method."); - assertion + assertionChain .ForCondition(Subject is not null) .UsingLineBreaks .BecauseOf(because, becauseArgs) .FailWith("Expected {context:string} to not match regex {0}{reason}, but it was .", regexStr); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { - assertion + assertionChain .ForCondition(!regularExpression.IsMatch(Subject)) .BecauseOf(because, becauseArgs) .UsingLineBreaks @@ -677,7 +677,7 @@ public AndConstraint StartWith(string expected, string because = "" { Guard.ThrowIfArgumentIsNull(expected, nameof(expected), "Cannot compare start of string with ."); - var stringStartValidator = new StringValidator(assertion, + var stringStartValidator = new StringValidator(assertionChain, new StringStartStrategy(StringComparison.Ordinal), because, becauseArgs); @@ -703,7 +703,7 @@ public AndConstraint NotStartWith(string unexpected, string because { Guard.ThrowIfArgumentIsNull(unexpected, nameof(unexpected), "Cannot compare start of string with ."); - var negatedStringStartValidator = new StringValidator(assertion, + var negatedStringStartValidator = new StringValidator(assertionChain, new NegatedStringStartStrategy(StringComparison.Ordinal), because, becauseArgs); @@ -730,7 +730,7 @@ public AndConstraint NotStartWith(string unexpected, string because { Guard.ThrowIfArgumentIsNull(expected, nameof(expected), "Cannot compare string start equivalence with ."); - var stringStartValidator = new StringValidator(assertion, + var stringStartValidator = new StringValidator(assertionChain, new StringStartStrategy(StringComparison.OrdinalIgnoreCase), because, becauseArgs); @@ -757,7 +757,7 @@ public AndConstraint NotStartWith(string unexpected, string because { Guard.ThrowIfArgumentIsNull(unexpected, nameof(unexpected), "Cannot compare start of string with ."); - var negatedStringStartValidator = new StringValidator(assertion, + var negatedStringStartValidator = new StringValidator(assertionChain, new NegatedStringStartStrategy(StringComparison.OrdinalIgnoreCase), because, becauseArgs); @@ -783,21 +783,21 @@ public AndConstraint EndWith(string expected, string because = "", { Guard.ThrowIfArgumentIsNull(expected, nameof(expected), "Cannot compare string end with ."); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected {context:string} {0} to end with {1}{reason}.", Subject, expected); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject.Length >= expected.Length) .FailWith("Expected {context:string} to end with {0}{reason}, but {1} is too short.", expected, Subject); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { - assertion + assertionChain .ForCondition(Subject.EndsWith(expected, StringComparison.Ordinal)) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:string} {0} to end with {1}{reason}.", Subject, expected); @@ -824,14 +824,14 @@ public AndConstraint NotEndWith(string unexpected, string because = { Guard.ThrowIfArgumentIsNull(unexpected, nameof(unexpected), "Cannot compare end of string with ."); - assertion + assertionChain .ForCondition(Subject is not null) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:string} that does not end with {1}{reason}, but found {0}.", Subject, unexpected); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { - assertion + assertionChain .ForCondition(!Subject.EndsWith(unexpected, StringComparison.Ordinal)) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:string} {0} not to end with {1}{reason}.", Subject, unexpected); @@ -857,24 +857,24 @@ public AndConstraint EndWithEquivalentOf(string expected, string be { Guard.ThrowIfArgumentIsNull(expected, nameof(expected), "Cannot compare string end equivalence with ."); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith( "Expected {context:string} that ends with equivalent of {0}{reason}, but found {1}.", expected, Subject); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject.Length >= expected.Length) .FailWith( "Expected {context:string} to end with equivalent of {0}{reason}, but {1} is too short.", expected, Subject); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { - assertion + assertionChain .ForCondition(Subject.EndsWith(expected, StringComparison.OrdinalIgnoreCase)) .BecauseOf(because, becauseArgs) .FailWith( @@ -903,16 +903,16 @@ public AndConstraint NotEndWithEquivalentOf(string unexpected, stri { Guard.ThrowIfArgumentIsNull(unexpected, nameof(unexpected), "Cannot compare end of string with ."); - var success = assertion + var success = assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith( "Expected {context:string} that does not end with equivalent of {0}{reason}, but found {1}.", unexpected, Subject); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { - assertion + assertionChain .ForCondition(!Subject.EndsWith(unexpected, StringComparison.OrdinalIgnoreCase)) .BecauseOf(because, becauseArgs) .FailWith( @@ -943,7 +943,7 @@ public AndConstraint Contain(string expected, string because = "", Guard.ThrowIfArgumentIsNull(expected, nameof(expected), "Cannot assert string containment against ."); Guard.ThrowIfArgumentIsEmpty(expected, nameof(expected), "Cannot assert string containment against an empty string."); - assertion + assertionChain .ForCondition(Contains(Subject, expected, StringComparison.Ordinal)) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:string} {0} to contain {1}{reason}.", Subject, expected); @@ -980,7 +980,7 @@ public AndConstraint Contain(string expected, string because = "", int actual = Subject.CountSubstring(expected, StringComparison.Ordinal); - assertion + assertionChain .ForConstraint(occurrenceConstraint, actual) .BecauseOf(because, becauseArgs) .FailWith( @@ -1009,7 +1009,7 @@ public AndConstraint ContainEquivalentOf(string expected, string be Guard.ThrowIfArgumentIsNull(expected, nameof(expected), "Cannot assert string containment against ."); Guard.ThrowIfArgumentIsEmpty(expected, nameof(expected), "Cannot assert string containment against an empty string."); - assertion + assertionChain .ForCondition(Contains(Subject, expected, StringComparison.OrdinalIgnoreCase)) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:string} {0} to contain the equivalent of {1}{reason}.", Subject, expected); @@ -1047,7 +1047,7 @@ public AndConstraint ContainEquivalentOf(string expected, string be int actual = Subject.CountSubstring(expected, StringComparison.OrdinalIgnoreCase); - assertion + assertionChain .ForConstraint(occurrenceConstraint, actual) .BecauseOf(because, becauseArgs) .FailWith( @@ -1076,7 +1076,7 @@ public AndConstraint ContainAll(IEnumerable values, string IEnumerable missing = values.Where(v => !Contains(Subject, v, StringComparison.Ordinal)); - assertion + assertionChain .ForCondition(values.All(v => Contains(Subject, v, StringComparison.Ordinal))) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:string} {0} to contain the strings: {1}{reason}.", Subject, missing); @@ -1112,7 +1112,7 @@ public AndConstraint ContainAny(IEnumerable values, string { ThrowIfValuesNullOrEmpty(values); - assertion + assertionChain .ForCondition(values.Any(v => Contains(Subject, v, StringComparison.Ordinal))) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:string} {0} to contain at least one of the strings: {1}{reason}.", Subject, values); @@ -1152,7 +1152,7 @@ public AndConstraint ContainAny(params string[] values) Guard.ThrowIfArgumentIsNull(unexpected, nameof(unexpected), "Cannot assert string containment against ."); Guard.ThrowIfArgumentIsEmpty(unexpected, nameof(unexpected), "Cannot assert string containment against an empty string."); - assertion + assertionChain .ForCondition(!Contains(Subject, unexpected, StringComparison.Ordinal)) .BecauseOf(because, becauseArgs) .FailWith("Did not expect {context:string} {0} to contain {1}{reason}.", Subject, unexpected); @@ -1181,7 +1181,7 @@ public AndConstraint ContainAny(params string[] values) var matches = values.Count(v => Contains(Subject, v, StringComparison.Ordinal)); - assertion + assertionChain .ForCondition(matches != values.Count()) .BecauseOf(because, becauseArgs) .FailWith("Did not expect {context:string} {0} to contain all of the strings: {1}{reason}.", Subject, values); @@ -1221,7 +1221,7 @@ public AndConstraint NotContainAll(params string[] values) IEnumerable matches = values.Where(v => Contains(Subject, v, StringComparison.Ordinal)); - assertion + assertionChain .ForCondition(!matches.Any()) .BecauseOf(because, becauseArgs) .FailWith("Did not expect {context:string} {0} to contain any of the strings: {1}{reason}.", Subject, matches); @@ -1255,7 +1255,7 @@ public AndConstraint NotContainAny(params string[] values) public AndConstraint NotContainEquivalentOf(string unexpected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(!Contains(Subject, unexpected, StringComparison.OrdinalIgnoreCase)) .BecauseOf(because, becauseArgs) .FailWith("Did not expect {context:string} to contain equivalent of {0}{reason} but found {1}.", unexpected, Subject); @@ -1280,7 +1280,7 @@ private static bool Contains(string actual, string expected, StringComparison co /// public AndConstraint BeEmpty(string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject?.Length == 0) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:string} to be empty{reason}, but found {0}.", Subject); @@ -1300,7 +1300,7 @@ public AndConstraint BeEmpty(string because = "", params object[] b /// public AndConstraint NotBeEmpty(string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject is null || Subject.Length > 0) .BecauseOf(because, becauseArgs) .FailWith("Did not expect {context:string} to be empty{reason}."); @@ -1321,14 +1321,14 @@ public AndConstraint NotBeEmpty(string because = "", params object[ /// public AndConstraint HaveLength(int expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected {context:string} with length {0}{reason}, but found .", expected); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject.Length == expected) .FailWith("Expected {context:string} with length {0}{reason}, but found string {1} with length {2}.", @@ -1350,7 +1350,7 @@ public AndConstraint HaveLength(int expected, string because = "", /// public AndConstraint NotBeNullOrEmpty(string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(!string.IsNullOrEmpty(Subject)) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:string} not to be or empty{reason}, but found {0}.", Subject); @@ -1370,7 +1370,7 @@ public AndConstraint NotBeNullOrEmpty(string because = "", params o /// public AndConstraint BeNullOrEmpty(string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(string.IsNullOrEmpty(Subject)) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:string} to be or empty{reason}, but found {0}.", Subject); @@ -1390,7 +1390,7 @@ public AndConstraint BeNullOrEmpty(string because = "", params obje /// public AndConstraint NotBeNullOrWhiteSpace(string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(!string.IsNullOrWhiteSpace(Subject)) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:string} not to be or whitespace{reason}, but found {0}.", Subject); @@ -1410,7 +1410,7 @@ public AndConstraint NotBeNullOrWhiteSpace(string because = "", par /// public AndConstraint BeNullOrWhiteSpace(string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(string.IsNullOrWhiteSpace(Subject)) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:string} to be or whitespace{reason}, but found {0}.", Subject); @@ -1435,7 +1435,7 @@ public AndConstraint BeNullOrWhiteSpace(string because = "", params /// public AndConstraint BeUpperCased(string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject?.All(char.IsUpper) == true) .BecauseOf(because, becauseArgs) .FailWith("Expected all characters in {context:string} to be upper cased{reason}, but found {0}.", Subject); @@ -1455,7 +1455,7 @@ public AndConstraint BeUpperCased(string because = "", params objec /// public AndConstraint NotBeUpperCased(string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject is null || Subject.Any(ch => !char.IsUpper(ch))) .BecauseOf(because, becauseArgs) .FailWith("Did not expect any characters in {context:string} to be upper cased{reason}."); @@ -1480,7 +1480,7 @@ public AndConstraint NotBeUpperCased(string because = "", params ob /// public AndConstraint BeLowerCased(string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject?.All(char.IsLower) == true) .BecauseOf(because, becauseArgs) .FailWith("Expected all characters in {context:string} to be lower cased{reason}, but found {0}.", Subject); @@ -1500,7 +1500,7 @@ public AndConstraint BeLowerCased(string because = "", params objec /// public AndConstraint NotBeLowerCased(string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject is null || Subject.Any(ch => !char.IsLower(ch))) .BecauseOf(because, becauseArgs) .FailWith("Did not expect any characters in {context:string} to be lower cased{reason}."); diff --git a/Src/FluentAssertions/Primitives/StringEqualityStrategy.cs b/Src/FluentAssertions/Primitives/StringEqualityStrategy.cs index 7f27b4b899..22d28c8e99 100644 --- a/Src/FluentAssertions/Primitives/StringEqualityStrategy.cs +++ b/Src/FluentAssertions/Primitives/StringEqualityStrategy.cs @@ -15,9 +15,9 @@ public StringEqualityStrategy(StringComparison comparisonMode) this.comparisonMode = comparisonMode; } - public void ValidateAgainstMismatch(Assertion assertion, string subject, string expected) + public void ValidateAgainstMismatch(AssertionChain assertionChain, string subject, string expected) { - ValidateAgainstSuperfluousWhitespace(assertion, subject, expected); + ValidateAgainstSuperfluousWhitespace(assertionChain, subject, expected); if (expected.IsLongOrMultiline() || subject.IsLongOrMultiline()) { @@ -25,7 +25,7 @@ public void ValidateAgainstMismatch(Assertion assertion, string subject, string if (indexOfMismatch == -1) { - ValidateAgainstLengthDifferences(assertion, subject, expected); + ValidateAgainstLengthDifferences(assertionChain, subject, expected); return; } @@ -40,18 +40,18 @@ public void ValidateAgainstMismatch(Assertion assertion, string subject, string locationDescription = $"on line {lineNumber + 1} and column {column} (index {indexOfMismatch})"; } - assertion.FailWith( + assertionChain.FailWith( ExpectationDescription + "the same string{reason}, but they differ " + locationDescription + ":" + Environment.NewLine + GetMismatchSegmentForLongStrings(subject, expected, indexOfMismatch) + "."); } - else if (ValidateAgainstLengthDifferences(assertion, subject, expected)) + else if (ValidateAgainstLengthDifferences(assertionChain, subject, expected)) { int indexOfMismatch = subject.IndexOfFirstMismatch(expected, comparisonMode); if (indexOfMismatch != -1) { - assertion.FailWith( + assertionChain.FailWith( ExpectationDescription + "{0}{reason}, but {1} differs near " + subject.IndexedSegmentAt(indexOfMismatch) + ".", expected, subject); @@ -71,9 +71,9 @@ public string ExpectationDescription private bool IgnoreCase => comparisonMode == StringComparison.OrdinalIgnoreCase; - private void ValidateAgainstSuperfluousWhitespace(Assertion assertion, string subject, string expected) + private void ValidateAgainstSuperfluousWhitespace(AssertionChain assertionChain, string subject, string expected) { - assertion + assertionChain .ForCondition(!(expected.Length > subject.Length && expected.TrimEnd().Equals(subject, comparisonMode))) .FailWith(ExpectationDescription + "{0}{reason}, but it misses some extra whitespace at the end.", expected) .Then @@ -81,9 +81,9 @@ private void ValidateAgainstSuperfluousWhitespace(Assertion assertion, string su .FailWith(ExpectationDescription + "{0}{reason}, but it has unexpected whitespace at the end.", expected); } - private bool ValidateAgainstLengthDifferences(Assertion assertion, string subject, string expected) + private bool ValidateAgainstLengthDifferences(AssertionChain assertionChain, string subject, string expected) { - assertion + assertionChain .ForCondition(subject.Length == expected.Length) .FailWith(() => { @@ -95,7 +95,7 @@ private bool ValidateAgainstLengthDifferences(Assertion assertion, string subjec return new FailReason(message, expected, expected.Length, subject, subject.Length); }); - return assertion.Succeeded; + return assertionChain.Succeeded; } private string GetMismatchSegmentForStringsOfDifferentLengths(string subject, string expected) diff --git a/Src/FluentAssertions/Primitives/StringStartStrategy.cs b/Src/FluentAssertions/Primitives/StringStartStrategy.cs index c22818c21e..640cbb012f 100644 --- a/Src/FluentAssertions/Primitives/StringStartStrategy.cs +++ b/Src/FluentAssertions/Primitives/StringStartStrategy.cs @@ -25,13 +25,13 @@ public string ExpectationDescription private bool IgnoreCase => stringComparison == StringComparison.OrdinalIgnoreCase; - public void ValidateAgainstMismatch(Assertion assertion, string subject, string expected) + public void ValidateAgainstMismatch(AssertionChain assertionChain, string subject, string expected) { - assertion + assertionChain .ForCondition(subject.Length >= expected.Length) .FailWith(ExpectationDescription + "{0}{reason}, but {1} is too short.", expected, subject); - if (!assertion.Succeeded) + if (!assertionChain.Succeeded) { return; } @@ -43,7 +43,7 @@ public void ValidateAgainstMismatch(Assertion assertion, string subject, string int indexOfMismatch = subject.IndexOfFirstMismatch(expected, stringComparison); - assertion.FailWith( + assertionChain.FailWith( ExpectationDescription + "{0}{reason}, but {1} differs near " + subject.IndexedSegmentAt(indexOfMismatch) + ".", expected, subject); diff --git a/Src/FluentAssertions/Primitives/StringValidator.cs b/Src/FluentAssertions/Primitives/StringValidator.cs index b060f41d5f..e3402dde81 100644 --- a/Src/FluentAssertions/Primitives/StringValidator.cs +++ b/Src/FluentAssertions/Primitives/StringValidator.cs @@ -6,13 +6,13 @@ namespace FluentAssertions.Primitives; internal class StringValidator { private readonly IStringComparisonStrategy comparisonStrategy; - private Assertion assertion; + private AssertionChain assertionChain; - public StringValidator(Assertion assertion, IStringComparisonStrategy comparisonStrategy, string because, + public StringValidator(AssertionChain assertionChain, IStringComparisonStrategy comparisonStrategy, string because, object[] becauseArgs) { this.comparisonStrategy = comparisonStrategy; - this.assertion = assertion.BecauseOf(because, becauseArgs); + this.assertionChain = assertionChain.BecauseOf(because, becauseArgs); } public void Validate(string subject, string expected) @@ -29,10 +29,10 @@ public void Validate(string subject, string expected) if (expected.IsLongOrMultiline() || subject.IsLongOrMultiline()) { - assertion = assertion.UsingLineBreaks; + assertionChain = assertionChain.UsingLineBreaks; } - comparisonStrategy.ValidateAgainstMismatch(assertion, subject, expected); + comparisonStrategy.ValidateAgainstMismatch(assertionChain, subject, expected); } private bool ValidateAgainstNulls(string subject, string expected) @@ -42,7 +42,7 @@ private bool ValidateAgainstNulls(string subject, string expected) return true; } - assertion.FailWith(comparisonStrategy.ExpectationDescription + "{0}{reason}, but found {1}.", expected, subject); + assertionChain.FailWith(comparisonStrategy.ExpectationDescription + "{0}{reason}, but found {1}.", expected, subject); return false; } } diff --git a/Src/FluentAssertions/Primitives/StringWildcardMatchingStrategy.cs b/Src/FluentAssertions/Primitives/StringWildcardMatchingStrategy.cs index f4bd4e8e3a..99a10e1514 100644 --- a/Src/FluentAssertions/Primitives/StringWildcardMatchingStrategy.cs +++ b/Src/FluentAssertions/Primitives/StringWildcardMatchingStrategy.cs @@ -8,7 +8,7 @@ namespace FluentAssertions.Primitives; internal class StringWildcardMatchingStrategy : IStringComparisonStrategy { - public void ValidateAgainstMismatch(Assertion assertion, string subject, string expected) + public void ValidateAgainstMismatch(AssertionChain assertionChain, string subject, string expected) { bool isMatch = IsMatch(subject, expected); @@ -19,11 +19,11 @@ public void ValidateAgainstMismatch(Assertion assertion, string subject, string if (Negate) { - assertion.FailWith(ExpectationDescription + "but {1} matches.", expected, subject); + assertionChain.FailWith(ExpectationDescription + "but {1} matches.", expected, subject); } else { - assertion.FailWith(ExpectationDescription + "but {1} does not.", expected, subject); + assertionChain.FailWith(ExpectationDescription + "but {1} does not.", expected, subject); } } diff --git a/Src/FluentAssertions/Primitives/TimeOnlyAssertions.cs b/Src/FluentAssertions/Primitives/TimeOnlyAssertions.cs index d3841eefc3..b23a126d85 100644 --- a/Src/FluentAssertions/Primitives/TimeOnlyAssertions.cs +++ b/Src/FluentAssertions/Primitives/TimeOnlyAssertions.cs @@ -15,8 +15,8 @@ namespace FluentAssertions.Primitives; [DebuggerNonUserCode] public class TimeOnlyAssertions : TimeOnlyAssertions { - public TimeOnlyAssertions(TimeOnly? value, Assertion assertion) - : base(value, assertion) + public TimeOnlyAssertions(TimeOnly? value, AssertionChain assertionChain) + : base(value, assertionChain) { } } @@ -30,11 +30,11 @@ public TimeOnlyAssertions(TimeOnly? value, Assertion assertion) public class TimeOnlyAssertions where TAssertions : TimeOnlyAssertions { - private readonly Assertion assertion; + private readonly AssertionChain assertionChain; - public TimeOnlyAssertions(TimeOnly? value, Assertion assertion) + public TimeOnlyAssertions(TimeOnly? value, AssertionChain assertionChain) { - this.assertion = assertion; + this.assertionChain = assertionChain; Subject = value; } @@ -56,7 +56,7 @@ public TimeOnlyAssertions(TimeOnly? value, Assertion assertion) /// public AndConstraint Be(TimeOnly expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject == expected) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:time} to be {0}{reason}, but found {1}.", @@ -78,7 +78,7 @@ public AndConstraint Be(TimeOnly expected, string because = "", par /// public AndConstraint Be(TimeOnly? expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject == expected) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:time} to be {0}{reason}, but found {1}.", @@ -101,7 +101,7 @@ public AndConstraint Be(TimeOnly? expected, string because = "", pa public AndConstraint NotBe(TimeOnly unexpected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject != unexpected) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:time} not to be {0}{reason}, but it is.", unexpected); @@ -123,7 +123,7 @@ public AndConstraint Be(TimeOnly? expected, string because = "", pa public AndConstraint NotBe(TimeOnly? unexpected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject != unexpected) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:time} not to be {0}{reason}, but it is.", unexpected); @@ -158,7 +158,7 @@ public AndConstraint Be(TimeOnly? expected, string because = "", pa ? MinimumDifference(Subject.Value, nearbyTime) : null; - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected {context:the time} to be within {0} from {1}{reason}, ", precision, nearbyTime) .ForCondition(Subject is not null) @@ -201,7 +201,7 @@ public AndConstraint Be(TimeOnly? expected, string because = "", pa { Guard.ThrowIfArgumentIsNegative(precision); - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Did not expect {context:the time} to be within {0} from {1}{reason}, ", precision, distantTime) .ForCondition(Subject is not null) @@ -227,7 +227,7 @@ public AndConstraint Be(TimeOnly? expected, string because = "", pa public AndConstraint BeBefore(TimeOnly expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject < expected) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:time} to be before {0}{reason}, but found {1}.", expected, @@ -267,7 +267,7 @@ public AndConstraint Be(TimeOnly? expected, string because = "", pa public AndConstraint BeOnOrBefore(TimeOnly expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject <= expected) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:time} to be on or before {0}{reason}, but found {1}.", expected, @@ -307,7 +307,7 @@ public AndConstraint Be(TimeOnly? expected, string because = "", pa public AndConstraint BeAfter(TimeOnly expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject > expected) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:time} to be after {0}{reason}, but found {1}.", expected, @@ -347,7 +347,7 @@ public AndConstraint Be(TimeOnly? expected, string because = "", pa public AndConstraint BeOnOrAfter(TimeOnly expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject >= expected) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:time} to be on or after {0}{reason}, but found {1}.", expected, @@ -386,7 +386,7 @@ public AndConstraint Be(TimeOnly? expected, string because = "", pa /// public AndConstraint HaveHours(int expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected the hours part of {context:the time} to be {0}{reason}", expected) .ForCondition(Subject.HasValue) @@ -411,7 +411,7 @@ public AndConstraint HaveHours(int expected, string because = "", p /// public AndConstraint NotHaveHours(int unexpected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject.HasValue) .FailWith("Did not expect the hours part of {context:the time} to be {0}{reason}, but found a TimeOnly.", @@ -437,7 +437,7 @@ public AndConstraint NotHaveHours(int unexpected, string because = /// public AndConstraint HaveMinutes(int expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected the minutes part of {context:the time} to be {0}{reason}", expected) .ForCondition(Subject.HasValue) @@ -462,7 +462,7 @@ public AndConstraint HaveMinutes(int expected, string because = "", /// public AndConstraint NotHaveMinutes(int unexpected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Did not expect the minutes part of {context:the time} to be {0}{reason}", unexpected) .ForCondition(Subject.HasValue) @@ -487,7 +487,7 @@ public AndConstraint NotHaveMinutes(int unexpected, string because /// public AndConstraint HaveSeconds(int expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected the seconds part of {context:the time} to be {0}{reason}", expected) .ForCondition(Subject.HasValue) @@ -512,7 +512,7 @@ public AndConstraint HaveSeconds(int expected, string because = "", /// public AndConstraint NotHaveSeconds(int unexpected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Did not expect the seconds part of {context:the time} to be {0}{reason}", unexpected) .ForCondition(Subject.HasValue) @@ -537,7 +537,7 @@ public AndConstraint NotHaveSeconds(int unexpected, string because /// public AndConstraint HaveMilliseconds(int expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected the milliseconds part of {context:the time} to be {0}{reason}", expected) .ForCondition(Subject.HasValue) @@ -562,7 +562,7 @@ public AndConstraint HaveMilliseconds(int expected, string because /// public AndConstraint NotHaveMilliseconds(int unexpected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Did not expect the milliseconds part of {context:the time} to be {0}{reason}", unexpected) .ForCondition(Subject.HasValue) @@ -630,7 +630,7 @@ public AndConstraint BeOneOf(IEnumerable validValues, str public AndConstraint BeOneOf(IEnumerable validValues, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(validValues.Contains(Subject)) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:time} to be one of {0}{reason}, but found {1}.", validValues, Subject); diff --git a/Src/FluentAssertions/Specialized/ActionAssertions.cs b/Src/FluentAssertions/Specialized/ActionAssertions.cs index 1a30ef1ea8..db9ab06141 100644 --- a/Src/FluentAssertions/Specialized/ActionAssertions.cs +++ b/Src/FluentAssertions/Specialized/ActionAssertions.cs @@ -11,18 +11,18 @@ namespace FluentAssertions.Specialized; [DebuggerNonUserCode] public class ActionAssertions : DelegateAssertions { - private readonly Assertion assertion; + private readonly AssertionChain assertionChain; - public ActionAssertions(Action subject, IExtractExceptions extractor, Assertion assertion) - : base(subject, extractor, assertion) + public ActionAssertions(Action subject, IExtractExceptions extractor, AssertionChain assertionChain) + : base(subject, extractor, assertionChain) { - this.assertion = assertion; + this.assertionChain = assertionChain; } - public ActionAssertions(Action subject, IExtractExceptions extractor, Assertion assertion, IClock clock) - : base(subject, extractor, assertion, clock) + public ActionAssertions(Action subject, IExtractExceptions extractor, AssertionChain assertionChain, IClock clock) + : base(subject, extractor, assertionChain, clock) { - this.assertion = assertion; + this.assertionChain = assertionChain; } /// @@ -37,12 +37,12 @@ public ActionAssertions(Action subject, IExtractExceptions extractor, Assertion /// public AndConstraint NotThrow(string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject is not null) .BecauseOf(because, becauseArgs) .FailWith("Expected {context} not to throw{reason}, but found ."); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { FailIfSubjectIsAsyncVoid(); Exception exception = InvokeSubjectWithInterception(); @@ -81,12 +81,12 @@ public AndConstraint NotThrow(string because = "", params obje Guard.ThrowIfArgumentIsNegative(waitTime); Guard.ThrowIfArgumentIsNegative(pollInterval); - assertion + assertionChain .ForCondition(Subject is not null) .BecauseOf(because, becauseArgs) .FailWith("Expected {context} not to throw after {0}{reason}, but found .", waitTime); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { FailIfSubjectIsAsyncVoid(); @@ -107,7 +107,7 @@ public AndConstraint NotThrow(string because = "", params obje invocationEndTime = timer.Elapsed; } - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(exception is null) .FailWith("Did not expect any exceptions after {0}{reason}, but found {1}.", waitTime, exception); diff --git a/Src/FluentAssertions/Specialized/AsyncFunctionAssertions.cs b/Src/FluentAssertions/Specialized/AsyncFunctionAssertions.cs index d729645c1b..b76cf4bb86 100644 --- a/Src/FluentAssertions/Specialized/AsyncFunctionAssertions.cs +++ b/Src/FluentAssertions/Specialized/AsyncFunctionAssertions.cs @@ -18,12 +18,12 @@ public class AsyncFunctionAssertions : DelegateAssertionsBas where TTask : Task where TAssertions : AsyncFunctionAssertions { - private readonly Assertion assertion; + private readonly AssertionChain assertionChain; - protected AsyncFunctionAssertions(Func subject, IExtractExceptions extractor, Assertion assertion, IClock clock) - : base(subject, extractor, assertion, clock) + protected AsyncFunctionAssertions(Func subject, IExtractExceptions extractor, AssertionChain assertionChain, IClock clock) + : base(subject, extractor, assertionChain, clock) { - this.assertion = assertion; + this.assertionChain = assertionChain; } protected override string Identifier => "async function"; @@ -42,12 +42,12 @@ protected AsyncFunctionAssertions(Func subject, IExtractExceptions extrac public async Task> NotCompleteWithinAsync( TimeSpan timeSpan, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject is not null) .BecauseOf(because, becauseArgs) .FailWith("Did not expect {context:task} to complete within {0}{reason}, but found .", timeSpan); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { (Task task, TimeSpan remainingTime) = InvokeWithTimer(timeSpan); @@ -55,7 +55,7 @@ protected AsyncFunctionAssertions(Func subject, IExtractExceptions extrac { bool completesWithinTimeout = await CompletesWithinTimeoutAsync(task, remainingTime); - assertion + assertionChain .ForCondition(!completesWithinTimeout) .BecauseOf(because, becauseArgs) .FailWith("Did not expect {context:task} to complete within {0}{reason}.", timeSpan); @@ -85,29 +85,29 @@ protected AsyncFunctionAssertions(Func subject, IExtractExceptions extrac { Type expectedType = typeof(TException); - assertion + assertionChain .ForCondition(Subject is not null) .BecauseOf(because, becauseArgs) .FailWith("Expected {context} to throw exactly {0}{reason}, but found .", expectedType); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { Exception exception = await InvokeWithInterceptionAsync(Subject); - assertion + assertionChain .ForCondition(exception is not null) .BecauseOf(because, becauseArgs) .FailWith("Expected {0}{reason}, but no exception was thrown.", expectedType); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { exception.Should().BeOfType(expectedType, because, becauseArgs); } - return new ExceptionAssertions([exception as TException], assertion); + return new ExceptionAssertions([exception as TException], assertionChain); } - return new ExceptionAssertions([], assertion); + return new ExceptionAssertions([], assertionChain); } /// @@ -125,18 +125,18 @@ protected AsyncFunctionAssertions(Func subject, IExtractExceptions extrac params object[] becauseArgs) where TException : Exception { - assertion + assertionChain .ForCondition(Subject is not null) .BecauseOf(because, becauseArgs) .FailWith("Expected {context} to throw {0}{reason}, but found .", typeof(TException)); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { Exception exception = await InvokeWithInterceptionAsync(Subject); return ThrowInternal(exception, because, becauseArgs); } - return new ExceptionAssertions([], assertion); + return new ExceptionAssertions([], assertionChain); } /// @@ -156,19 +156,19 @@ protected AsyncFunctionAssertions(Func subject, IExtractExceptions extrac TimeSpan timeSpan, string because = "", params object[] becauseArgs) where TException : Exception { - assertion + assertionChain .ForCondition(Subject is not null) .BecauseOf(because, becauseArgs) .FailWith("Expected {context} to throw {0} within {1}{reason}, but found .", typeof(TException), timeSpan); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { Exception caughtException = await InvokeWithInterceptionAsync(timeSpan); return AssertThrows(caughtException, timeSpan, because, becauseArgs); } - return new ExceptionAssertions([], assertion); + return new ExceptionAssertions([], assertionChain); } private ExceptionAssertions AssertThrows( @@ -177,7 +177,7 @@ protected AsyncFunctionAssertions(Func subject, IExtractExceptions extrac { TException[] expectedExceptions = Extractor.OfType(exception).ToArray(); - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected a <{0}> to be thrown within {1}{reason}, ", typeof(TException), timeSpan) @@ -189,7 +189,7 @@ protected AsyncFunctionAssertions(Func subject, IExtractExceptions extrac exception?.GetType(), exception); - return new ExceptionAssertions(expectedExceptions, assertion); + return new ExceptionAssertions(expectedExceptions, assertionChain); } private async Task InvokeWithInterceptionAsync(TimeSpan timeout) @@ -250,12 +250,12 @@ private async Task InvokeWithInterceptionAsync(TimeSpan timeout) public async Task> NotThrowAsync(string because = "", params object[] becauseArgs) where TException : Exception { - assertion + assertionChain .ForCondition(Subject is not null) .BecauseOf(because, becauseArgs) .FailWith("Expected {context} not to throw{reason}, but found ."); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { try { diff --git a/Src/FluentAssertions/Specialized/DelegateAssertions.cs b/Src/FluentAssertions/Specialized/DelegateAssertions.cs index e0936b0f34..890dea6f08 100644 --- a/Src/FluentAssertions/Specialized/DelegateAssertions.cs +++ b/Src/FluentAssertions/Specialized/DelegateAssertions.cs @@ -15,18 +15,18 @@ public abstract class DelegateAssertions : DelegateAsser where TDelegate : Delegate where TAssertions : DelegateAssertions { - private readonly Assertion assertion; + private readonly AssertionChain assertionChain; - protected DelegateAssertions(TDelegate @delegate, IExtractExceptions extractor, Assertion assertion) - : base(@delegate, extractor, assertion, new Clock()) + protected DelegateAssertions(TDelegate @delegate, IExtractExceptions extractor, AssertionChain assertionChain) + : base(@delegate, extractor, assertionChain, new Clock()) { - this.assertion = assertion; + this.assertionChain = assertionChain; } - private protected DelegateAssertions(TDelegate @delegate, IExtractExceptions extractor, Assertion assertion, IClock clock) - : base(@delegate, extractor, assertion, clock) + private protected DelegateAssertions(TDelegate @delegate, IExtractExceptions extractor, AssertionChain assertionChain, IClock clock) + : base(@delegate, extractor, assertionChain, clock) { - this.assertion = assertion; + this.assertionChain = assertionChain; } /// @@ -42,19 +42,19 @@ private protected DelegateAssertions(TDelegate @delegate, IExtractExceptions ext public ExceptionAssertions Throw(string because = "", params object[] becauseArgs) where TException : Exception { - assertion + assertionChain .ForCondition(Subject is not null) .BecauseOf(because, becauseArgs) .FailWith("Expected {context} to throw {0}{reason}, but found .", typeof(TException)); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { FailIfSubjectIsAsyncVoid(); Exception exception = InvokeSubjectWithInterception(); return ThrowInternal(exception, because, becauseArgs); } - return new ExceptionAssertions([], assertion); + return new ExceptionAssertions([], assertionChain); } /// @@ -70,12 +70,12 @@ public ExceptionAssertions Throw(string because = "", pa public AndConstraint NotThrow(string because = "", params object[] becauseArgs) where TException : Exception { - assertion + assertionChain .ForCondition(Subject is not null) .BecauseOf(because, becauseArgs) .FailWith("Expected {context} not to throw {0}{reason}, but found .", typeof(TException)); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { FailIfSubjectIsAsyncVoid(); Exception exception = InvokeSubjectWithInterception(); @@ -105,32 +105,32 @@ public AndConstraint NotThrow(string because = "", para params object[] becauseArgs) where TException : Exception { - assertion + assertionChain .ForCondition(Subject is not null) .BecauseOf(because, becauseArgs) .FailWith("Expected {context} to throw exactly {0}{reason}, but found .", typeof(TException)); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { FailIfSubjectIsAsyncVoid(); Exception exception = InvokeSubjectWithInterception(); Type expectedType = typeof(TException); - assertion + assertionChain .ForCondition(exception is not null) .BecauseOf(because, becauseArgs) .FailWith("Expected {0}{reason}, but no exception was thrown.", expectedType); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { exception.Should().BeOfType(expectedType, because, becauseArgs); } - return new ExceptionAssertions([exception as TException], assertion); + return new ExceptionAssertions([exception as TException], assertionChain); } - return new ExceptionAssertions([], assertion); + return new ExceptionAssertions([], assertionChain); } protected abstract void InvokeSubject(); diff --git a/Src/FluentAssertions/Specialized/DelegateAssertionsBase.cs b/Src/FluentAssertions/Specialized/DelegateAssertionsBase.cs index 645b40bace..f302278cd8 100644 --- a/Src/FluentAssertions/Specialized/DelegateAssertionsBase.cs +++ b/Src/FluentAssertions/Specialized/DelegateAssertionsBase.cs @@ -17,15 +17,15 @@ public abstract class DelegateAssertionsBase where TDelegate : Delegate where TAssertions : DelegateAssertionsBase { - private readonly Assertion assertion; + private readonly AssertionChain assertionChain; private protected IExtractExceptions Extractor { get; } - private protected DelegateAssertionsBase(TDelegate @delegate, IExtractExceptions extractor, Assertion assertion, + private protected DelegateAssertionsBase(TDelegate @delegate, IExtractExceptions extractor, AssertionChain assertionChain, IClock clock) - : base(@delegate, assertion) + : base(@delegate, assertionChain) { - this.assertion = assertion; + this.assertionChain = assertionChain; Extractor = extractor ?? throw new ArgumentNullException(nameof(extractor)); Clock = clock ?? throw new ArgumentNullException(nameof(clock)); } @@ -38,7 +38,7 @@ public abstract class DelegateAssertionsBase { TException[] expectedExceptions = Extractor.OfType(exception).ToArray(); - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected a <{0}> to be thrown{reason}, ", typeof(TException)) .ForCondition(exception is not null) @@ -49,12 +49,12 @@ public abstract class DelegateAssertionsBase exception?.GetType(), exception); - return new ExceptionAssertions(expectedExceptions, assertion); + return new ExceptionAssertions(expectedExceptions, assertionChain); } protected AndConstraint NotThrowInternal(Exception exception, string because, object[] becauseArgs) { - assertion + assertionChain .ForCondition(exception is null) .BecauseOf(because, becauseArgs) .FailWith("Did not expect any exception{reason}, but found {0}.", exception); @@ -67,7 +67,7 @@ protected AndConstraint NotThrowInternal(Exception exce { IEnumerable exceptions = Extractor.OfType(exception); - assertion + assertionChain .ForCondition(!exceptions.Any()) .BecauseOf(because, becauseArgs) .FailWith("Did not expect {0}{reason}, but found {1}.", typeof(TException), exception); diff --git a/Src/FluentAssertions/Specialized/ExceptionAssertions.cs b/Src/FluentAssertions/Specialized/ExceptionAssertions.cs index 47b6de34ee..3f7334119c 100644 --- a/Src/FluentAssertions/Specialized/ExceptionAssertions.cs +++ b/Src/FluentAssertions/Specialized/ExceptionAssertions.cs @@ -18,12 +18,12 @@ namespace FluentAssertions.Specialized; public class ExceptionAssertions : ReferenceTypeAssertions, ExceptionAssertions> where TException : Exception { - private readonly Assertion assertion; + private readonly AssertionChain assertionChain; - public ExceptionAssertions(IEnumerable exceptions, Assertion assertion) - : base(exceptions, assertion) + public ExceptionAssertions(IEnumerable exceptions, AssertionChain assertionChain) + : base(exceptions, assertionChain) { - this.assertion = assertion; + this.assertionChain = assertionChain; } /// @@ -77,13 +77,13 @@ public ExceptionAssertions(IEnumerable exceptions, Assertion asserti public virtual ExceptionAssertions WithMessage(string expectedWildcardPattern, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .UsingLineBreaks .ForCondition(Subject.Any()) .FailWith("Expected exception with message {0}{reason}, but no exception was thrown.", expectedWildcardPattern); - ExceptionMessageAssertion.Execute(Subject.Select(exc => exc.Message), expectedWildcardPattern, because, + AssertExceptionMessage(Subject.Select(exc => exc.Message), expectedWildcardPattern, because, becauseArgs); return this; @@ -105,7 +105,7 @@ public ExceptionAssertions(IEnumerable exceptions, Assertion asserti where TInnerException : Exception { var expectedInnerExceptions = AssertInnerExceptions(typeof(TInnerException), because, becauseArgs); - return new ExceptionAssertions(expectedInnerExceptions.Cast(), assertion); + return new ExceptionAssertions(expectedInnerExceptions.Cast(), assertionChain); } /// @@ -124,7 +124,7 @@ public ExceptionAssertions(IEnumerable exceptions, Assertion asserti { Guard.ThrowIfArgumentIsNull(innerException); - return new ExceptionAssertions(AssertInnerExceptions(innerException, because, becauseArgs), assertion); + return new ExceptionAssertions(AssertInnerExceptions(innerException, because, becauseArgs), assertionChain); } /// @@ -143,7 +143,7 @@ public ExceptionAssertions(IEnumerable exceptions, Assertion asserti where TInnerException : Exception { var exceptionExpression = AssertInnerExceptionExactly(typeof(TInnerException), because, becauseArgs); - return new ExceptionAssertions(exceptionExpression.Cast(), assertion); + return new ExceptionAssertions(exceptionExpression.Cast(), assertionChain); } /// @@ -162,7 +162,7 @@ public ExceptionAssertions(IEnumerable exceptions, Assertion asserti { Guard.ThrowIfArgumentIsNull(innerException); - return new ExceptionAssertions(AssertInnerExceptionExactly(innerException, because, becauseArgs), assertion); + return new ExceptionAssertions(AssertInnerExceptionExactly(innerException, because, becauseArgs), assertionChain); } /// @@ -186,7 +186,7 @@ public ExceptionAssertions(IEnumerable exceptions, Assertion asserti Func condition = exceptionExpression.Compile(); - assertion + assertionChain .ForCondition(condition(SingleSubject)) .BecauseOf(because, becauseArgs) .FailWith("Expected exception where {0}{reason}, but the condition was not met by:" @@ -199,7 +199,7 @@ public ExceptionAssertions(IEnumerable exceptions, Assertion asserti private IEnumerable AssertInnerExceptionExactly(Type innerException, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject.Any(e => e.InnerException is not null)) .FailWith("Expected inner {0}{reason}, but the thrown exception has no inner exception.", innerException); @@ -208,7 +208,7 @@ public ExceptionAssertions(IEnumerable exceptions, Assertion asserti .Select(e => e.InnerException) .Where(e => e?.GetType() == innerException).ToArray(); - assertion + assertionChain .ForCondition(expectedExceptions.Length > 0) .BecauseOf(because, becauseArgs) .FailWith("Expected inner {0}{reason}, but found {1}.", innerException, SingleSubject.InnerException); @@ -219,7 +219,7 @@ public ExceptionAssertions(IEnumerable exceptions, Assertion asserti private IEnumerable AssertInnerExceptions(Type innerException, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject.Any(e => e.InnerException is not null)) .FailWith("Expected inner {0}{reason}, but the thrown exception has no inner exception.", innerException); @@ -229,7 +229,7 @@ public ExceptionAssertions(IEnumerable exceptions, Assertion asserti .Where(e => e != null && e.GetType().IsSameOrInherits(innerException)) .ToArray(); - assertion + assertionChain .ForCondition(expectedInnerExceptions.Length > 0) .BecauseOf(because, becauseArgs) .FailWith("Expected inner {0}{reason}, but found {1}.", innerException, SingleSubject.InnerException); @@ -261,39 +261,34 @@ private static string BuildExceptionsString(IEnumerable exceptions) "\t" + Formatter.ToString(exception))); } - private static class ExceptionMessageAssertion + private void AssertExceptionMessage(IEnumerable messages, string expectation, string because, params object[] becauseArgs) { - private const string Context = "exception message"; + using var _ = new AssertionScope(); + var results = new AssertionResultSet(); - public static void Execute(IEnumerable messages, string expectation, string because, params object[] becauseArgs) + foreach (string message in messages) { - using var _ = new AssertionScope(); - var results = new AssertionResultSet(); - - foreach (string message in messages) + using (var scope = new AssertionScope()) { - using (var scope = new AssertionScope()) - { - scope.Context = new Lazy(() => Context); - - message.Should().MatchEquivalentOf(expectation, because, becauseArgs); + scope.Context = new Lazy(() => "exception message"); - results.AddSet(message, scope.Discard()); - } + message.Should().MatchEquivalentOf(expectation, because, becauseArgs); - if (results.ContainsSuccessfulSet()) - { - break; - } + results.AddSet(message, scope.Discard()); } - foreach (string failure in results.SelectClosestMatchFor()) + if (results.ContainsSuccessfulSet()) { - string replacedCurlyBraces = - failure.EscapePlaceholders(); - - AssertionScope.Current.FailWith(replacedCurlyBraces); + break; } } + + foreach (string failure in results.SelectClosestMatchFor()) + { + string replacedCurlyBraces = + failure.EscapePlaceholders(); + + assertionChain.FailWith(replacedCurlyBraces); + } } } diff --git a/Src/FluentAssertions/Specialized/ExecutionTimeAssertions.cs b/Src/FluentAssertions/Specialized/ExecutionTimeAssertions.cs index 5f3d9616d4..997675d7b8 100644 --- a/Src/FluentAssertions/Specialized/ExecutionTimeAssertions.cs +++ b/Src/FluentAssertions/Specialized/ExecutionTimeAssertions.cs @@ -12,16 +12,16 @@ namespace FluentAssertions.Specialized; public class ExecutionTimeAssertions { private readonly ExecutionTime execution; - private readonly Assertion assertion; + private readonly AssertionChain assertionChain; /// /// Initializes a new instance of the class. /// /// The execution on which time must be asserted. - public ExecutionTimeAssertions(ExecutionTime executionTime, Assertion assertion) + public ExecutionTimeAssertions(ExecutionTime executionTime, AssertionChain assertionChain) { execution = executionTime ?? throw new ArgumentNullException(nameof(executionTime)); - this.assertion = assertion; + this.assertionChain = assertionChain; } /// @@ -75,7 +75,7 @@ public ExecutionTimeAssertions(ExecutionTime executionTime, Assertion assertion) { (bool isRunning, TimeSpan elapsed) = PollUntil(duration => duration <= maxDuration, expectedResult: false, rate: maxDuration); - assertion + assertionChain .ForCondition(elapsed <= maxDuration) .BecauseOf(because, becauseArgs) .FailWith("Execution of " + @@ -106,7 +106,7 @@ public ExecutionTimeAssertions(ExecutionTime executionTime, Assertion assertion) { (bool isRunning, TimeSpan elapsed) = PollUntil(duration => duration < maxDuration, expectedResult: false, rate: maxDuration); - assertion + assertionChain .ForCondition(elapsed < maxDuration) .BecauseOf(because, becauseArgs) .FailWith("Execution of " + @@ -136,7 +136,7 @@ public ExecutionTimeAssertions(ExecutionTime executionTime, Assertion assertion) { (bool isRunning, TimeSpan elapsed) = PollUntil(duration => duration >= minDuration, expectedResult: true, rate: minDuration); - assertion + assertionChain .ForCondition(elapsed >= minDuration) .BecauseOf(because, becauseArgs) .FailWith("Execution of " + @@ -167,7 +167,7 @@ public ExecutionTimeAssertions(ExecutionTime executionTime, Assertion assertion) { (bool isRunning, TimeSpan elapsed) = PollUntil(duration => duration > minDuration, expectedResult: true, rate: minDuration); - assertion + assertionChain .ForCondition(elapsed > minDuration) .BecauseOf(because, becauseArgs) .FailWith("Execution of " + @@ -209,7 +209,7 @@ public ExecutionTimeAssertions(ExecutionTime executionTime, Assertion assertion) // elapsed time didn't even get to the acceptable range (bool isRunning, TimeSpan elapsed) = PollUntil(duration => duration <= maximumValue, expectedResult: false, rate: maximumValue); - assertion + assertionChain .ForCondition(elapsed >= minimumValue && elapsed <= maximumValue) .BecauseOf(because, becauseArgs) .FailWith("Execution of " + execution.ActionDescription.EscapePlaceholders() + diff --git a/Src/FluentAssertions/Specialized/FunctionAssertions.cs b/Src/FluentAssertions/Specialized/FunctionAssertions.cs index ac9cb5dc02..3184620c3d 100644 --- a/Src/FluentAssertions/Specialized/FunctionAssertions.cs +++ b/Src/FluentAssertions/Specialized/FunctionAssertions.cs @@ -11,18 +11,18 @@ namespace FluentAssertions.Specialized; [DebuggerNonUserCode] public class FunctionAssertions : DelegateAssertions, FunctionAssertions> { - private readonly Assertion assertion; + private readonly AssertionChain assertionChain; - public FunctionAssertions(Func subject, IExtractExceptions extractor, Assertion assertion) - : base(subject, extractor, assertion) + public FunctionAssertions(Func subject, IExtractExceptions extractor, AssertionChain assertionChain) + : base(subject, extractor, assertionChain) { - this.assertion = assertion; + this.assertionChain = assertionChain; } - public FunctionAssertions(Func subject, IExtractExceptions extractor, Assertion assertion, IClock clock) - : base(subject, extractor, assertion, clock) + public FunctionAssertions(Func subject, IExtractExceptions extractor, AssertionChain assertionChain, IClock clock) + : base(subject, extractor, assertionChain, clock) { - this.assertion = assertion; + this.assertionChain = assertionChain; } protected override void InvokeSubject() @@ -44,14 +44,14 @@ protected override void InvokeSubject() /// public AndWhichConstraint, T> NotThrow(string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject is not null) .BecauseOf(because, becauseArgs) .FailWith("Expected {context} not to throw{reason}, but found ."); T result = default; - if (assertion.Succeeded) + if (assertionChain.Succeeded) { try { @@ -59,7 +59,7 @@ protected override void InvokeSubject() } catch (Exception exception) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .FailWith("Did not expect any exception{reason}, but found {0}.", exception); @@ -96,14 +96,14 @@ protected override void InvokeSubject() public AndWhichConstraint, T> NotThrowAfter(TimeSpan waitTime, TimeSpan pollInterval, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject is not null) .BecauseOf(because, becauseArgs) .FailWith("Expected {context} not to throw any exceptions after {0}{reason}, but found .", waitTime); T result = default; - if (assertion.Succeeded) + if (assertionChain.Succeeded) { result = NotThrowAfter(Subject, Clock, waitTime, pollInterval, because, becauseArgs); } @@ -136,7 +136,7 @@ protected override void InvokeSubject() invocationEndTime = timer.Elapsed; } - assertion + assertionChain .BecauseOf(because, becauseArgs) .FailWith("Did not expect any exceptions after {0}{reason}, but found {1}.", waitTime, exception); diff --git a/Src/FluentAssertions/Specialized/GenericAsyncFunctionAssertions.cs b/Src/FluentAssertions/Specialized/GenericAsyncFunctionAssertions.cs index 2557588c0b..8eff7aacb6 100644 --- a/Src/FluentAssertions/Specialized/GenericAsyncFunctionAssertions.cs +++ b/Src/FluentAssertions/Specialized/GenericAsyncFunctionAssertions.cs @@ -13,25 +13,25 @@ namespace FluentAssertions.Specialized; public class GenericAsyncFunctionAssertions : AsyncFunctionAssertions, GenericAsyncFunctionAssertions> { - private readonly Assertion assertion; + private readonly AssertionChain assertionChain; /// /// Initializes a new instance of the class. /// - public GenericAsyncFunctionAssertions(Func> subject, IExtractExceptions extractor, Assertion assertion) - : this(subject, extractor, assertion, new Clock()) + public GenericAsyncFunctionAssertions(Func> subject, IExtractExceptions extractor, AssertionChain assertionChain) + : this(subject, extractor, assertionChain, new Clock()) { - this.assertion = assertion; + this.assertionChain = assertionChain; } /// /// Initializes a new instance of the class with custom . /// - public GenericAsyncFunctionAssertions(Func> subject, IExtractExceptions extractor, Assertion assertion, + public GenericAsyncFunctionAssertions(Func> subject, IExtractExceptions extractor, AssertionChain assertionChain, IClock clock) - : base(subject, extractor, assertion, clock) + : base(subject, extractor, assertionChain, clock) { - this.assertion = assertion; + this.assertionChain = assertionChain; } /// @@ -48,32 +48,32 @@ public GenericAsyncFunctionAssertions(Func> subject, IExtractExcep public async Task, TResult>> CompleteWithinAsync( TimeSpan timeSpan, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject is not null) .BecauseOf(because, becauseArgs) .FailWith("Expected {context} to complete within {0}{reason}, but found .", timeSpan); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { (Task task, TimeSpan remainingTime) = InvokeWithTimer(timeSpan); - assertion + assertionChain .ForCondition(remainingTime >= TimeSpan.Zero) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:task} to complete within {0}{reason}.", timeSpan); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { bool completesWithinTimeout = await CompletesWithinTimeoutAsync(task, remainingTime); - assertion + assertionChain .ForCondition(completesWithinTimeout) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:task} to complete within {0}{reason}.", timeSpan); } #pragma warning disable CA1849 // Call async methods when in an async method - TResult result = assertion.Succeeded ? task.Result : default; + TResult result = assertionChain.Succeeded ? task.Result : default; #pragma warning restore CA1849 // Call async methods when in an async method return new AndWhichConstraint, TResult>(this, result); } @@ -94,12 +94,12 @@ public GenericAsyncFunctionAssertions(Func> subject, IExtractExcep public async Task, TResult>> NotThrowAsync( string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject is not null) .BecauseOf(because, becauseArgs) .FailWith("Expected {context} not to throw{reason}, but found ."); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { try { @@ -144,12 +144,12 @@ public GenericAsyncFunctionAssertions(Func> subject, IExtractExcep Guard.ThrowIfArgumentIsNegative(waitTime); Guard.ThrowIfArgumentIsNegative(pollInterval); - assertion + assertionChain .ForCondition(Subject is not null) .BecauseOf(because, becauseArgs) .FailWith("Expected {context} not to throw any exceptions after {0}{reason}, but found .", waitTime); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { return AssertionTaskAsync(); @@ -174,7 +174,7 @@ public GenericAsyncFunctionAssertions(Func> subject, IExtractExcep } } - assertion + assertionChain .BecauseOf(because, becauseArgs) .FailWith("Did not expect any exceptions after {0}{reason}, but found {1}.", waitTime, exception); diff --git a/Src/FluentAssertions/Specialized/NonGenericAsyncFunctionAssertions.cs b/Src/FluentAssertions/Specialized/NonGenericAsyncFunctionAssertions.cs index 1873342711..19da42c37d 100644 --- a/Src/FluentAssertions/Specialized/NonGenericAsyncFunctionAssertions.cs +++ b/Src/FluentAssertions/Specialized/NonGenericAsyncFunctionAssertions.cs @@ -11,22 +11,22 @@ namespace FluentAssertions.Specialized; /// public class NonGenericAsyncFunctionAssertions : AsyncFunctionAssertions { - private readonly Assertion assertion; + private readonly AssertionChain assertionChain; /// /// Initializes a new instance of the class. /// - public NonGenericAsyncFunctionAssertions(Func subject, IExtractExceptions extractor, Assertion assertion) - : this(subject, extractor, assertion, new Clock()) + public NonGenericAsyncFunctionAssertions(Func subject, IExtractExceptions extractor, AssertionChain assertionChain) + : this(subject, extractor, assertionChain, new Clock()) { - this.assertion = assertion; + this.assertionChain = assertionChain; } /// /// Initializes a new instance of the class with custom . /// - public NonGenericAsyncFunctionAssertions(Func subject, IExtractExceptions extractor, Assertion assertion, IClock clock) - : base(subject, extractor, assertion, clock) + public NonGenericAsyncFunctionAssertions(Func subject, IExtractExceptions extractor, AssertionChain assertionChain, IClock clock) + : base(subject, extractor, assertionChain, clock) { } @@ -44,25 +44,25 @@ public NonGenericAsyncFunctionAssertions(Func subject, IExtractExceptions public async Task> CompleteWithinAsync( TimeSpan timeSpan, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject is not null) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:task} to complete within {0}{reason}, but found .", timeSpan); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { (Task task, TimeSpan remainingTime) = InvokeWithTimer(timeSpan); - assertion + assertionChain .ForCondition(remainingTime >= TimeSpan.Zero) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:task} to complete within {0}{reason}.", timeSpan); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { bool completesWithinTimeout = await CompletesWithinTimeoutAsync(task, remainingTime); - assertion + assertionChain .ForCondition(completesWithinTimeout) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:task} to complete within {0}{reason}.", timeSpan); @@ -84,12 +84,12 @@ public NonGenericAsyncFunctionAssertions(Func subject, IExtractExceptions /// public async Task> NotThrowAsync(string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject is not null) .BecauseOf(because, becauseArgs) .FailWith("Expected {context} not to throw{reason}, but found ."); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { try { @@ -133,12 +133,12 @@ public async Task> NotThrowAsyn Guard.ThrowIfArgumentIsNegative(waitTime); Guard.ThrowIfArgumentIsNegative(pollInterval); - assertion + assertionChain .ForCondition(Subject is not null) .BecauseOf(because, becauseArgs) .FailWith("Expected {context} not to throw any exceptions after {0}{reason}, but found .", waitTime); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { return AssertionTaskAsync(); @@ -161,7 +161,7 @@ async Task> AssertionTaskAsync( invocationEndTime = timer.Elapsed; } - assertion + assertionChain .BecauseOf(because, becauseArgs) .FailWith("Did not expect any exceptions after {0}{reason}, but found {1}.", waitTime, exception); diff --git a/Src/FluentAssertions/Specialized/TaskCompletionSourceAssertions.cs b/Src/FluentAssertions/Specialized/TaskCompletionSourceAssertions.cs index ee1d7738ca..91e465caef 100644 --- a/Src/FluentAssertions/Specialized/TaskCompletionSourceAssertions.cs +++ b/Src/FluentAssertions/Specialized/TaskCompletionSourceAssertions.cs @@ -11,20 +11,20 @@ namespace FluentAssertions.Specialized; #if NET6_0_OR_GREATER public class TaskCompletionSourceAssertions : TaskCompletionSourceAssertionsBase { - private readonly Assertion assertion; + private readonly AssertionChain assertionChain; private readonly TaskCompletionSource subject; - public TaskCompletionSourceAssertions(TaskCompletionSource tcs, Assertion assertion) - : this(tcs, assertion, new Clock()) + public TaskCompletionSourceAssertions(TaskCompletionSource tcs, AssertionChain assertionChain) + : this(tcs, assertionChain, new Clock()) { - this.assertion = assertion; + this.assertionChain = assertionChain; } - public TaskCompletionSourceAssertions(TaskCompletionSource tcs, Assertion assertion, IClock clock) + public TaskCompletionSourceAssertions(TaskCompletionSource tcs, AssertionChain assertionChain, IClock clock) : base(clock) { subject = tcs; - this.assertion = assertion; + this.assertionChain = assertionChain; } /// @@ -41,15 +41,15 @@ public TaskCompletionSourceAssertions(TaskCompletionSource tcs, Assertion assert public async Task> CompleteWithinAsync( TimeSpan timeSpan, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(subject is not null) .BecauseOf(because, becauseArgs) .FailWith("Expected {context} to complete within {0}{reason}, but found .", timeSpan); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { bool completesWithinTimeout = await CompletesWithinTimeoutAsync(subject!.Task, timeSpan); - assertion + assertionChain .ForCondition(completesWithinTimeout) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:task} to complete within {0}{reason}.", timeSpan); @@ -72,15 +72,15 @@ public TaskCompletionSourceAssertions(TaskCompletionSource tcs, Assertion assert public async Task> NotCompleteWithinAsync( TimeSpan timeSpan, string because = "", params object[] becauseArgs) { - var success = assertion + var success = assertionChain .ForCondition(subject is not null) .BecauseOf(because, becauseArgs) .FailWith("Expected {context} to not complete within {0}{reason}, but found .", timeSpan); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { bool completesWithinTimeout = await CompletesWithinTimeoutAsync(subject!.Task, timeSpan); - assertion + assertionChain .ForCondition(!completesWithinTimeout) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:task} to not complete within {0}{reason}.", timeSpan); @@ -93,20 +93,20 @@ public TaskCompletionSourceAssertions(TaskCompletionSource tcs, Assertion assert public class TaskCompletionSourceAssertions : TaskCompletionSourceAssertionsBase { - private readonly Assertion assertion; + private readonly AssertionChain assertionChain; private readonly TaskCompletionSource subject; - public TaskCompletionSourceAssertions(TaskCompletionSource tcs, Assertion assertion) - : this(tcs, assertion, new Clock()) + public TaskCompletionSourceAssertions(TaskCompletionSource tcs, AssertionChain assertionChain) + : this(tcs, assertionChain, new Clock()) { - this.assertion = assertion; + this.assertionChain = assertionChain; } - public TaskCompletionSourceAssertions(TaskCompletionSource tcs, Assertion assertion, IClock clock) + public TaskCompletionSourceAssertions(TaskCompletionSource tcs, AssertionChain assertionChain, IClock clock) : base(clock) { subject = tcs; - this.assertion = assertion; + this.assertionChain = assertionChain; } /// @@ -123,16 +123,16 @@ public TaskCompletionSourceAssertions(TaskCompletionSource tcs, Assertion ass public async Task, T>> CompleteWithinAsync( TimeSpan timeSpan, string because = "", params object[] becauseArgs) { - var success = assertion + var success = assertionChain .ForCondition(subject is not null) .BecauseOf(because, becauseArgs) .FailWith("Expected {context} to complete within {0}{reason}, but found .", timeSpan); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { bool completesWithinTimeout = await CompletesWithinTimeoutAsync(subject!.Task, timeSpan); - assertion + assertionChain .ForCondition(completesWithinTimeout) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:task} to complete within {0}{reason}.", timeSpan); @@ -160,16 +160,16 @@ public TaskCompletionSourceAssertions(TaskCompletionSource tcs, Assertion ass public async Task>> NotCompleteWithinAsync( TimeSpan timeSpan, string because = "", params object[] becauseArgs) { - var success = assertion + var success = assertionChain .ForCondition(subject is not null) .BecauseOf(because, becauseArgs) .FailWith("Did not expect {context} to complete within {0}{reason}, but found .", timeSpan); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { bool completesWithinTimeout = await CompletesWithinTimeoutAsync(subject!.Task, timeSpan); - assertion + assertionChain .ForCondition(!completesWithinTimeout) .BecauseOf(because, becauseArgs) .FailWith("Did not expect {context:task} to complete within {0}{reason}.", timeSpan); diff --git a/Src/FluentAssertions/Streams/BufferedStreamAssertions.cs b/Src/FluentAssertions/Streams/BufferedStreamAssertions.cs index 29e868c237..d020326d18 100644 --- a/Src/FluentAssertions/Streams/BufferedStreamAssertions.cs +++ b/Src/FluentAssertions/Streams/BufferedStreamAssertions.cs @@ -11,24 +11,24 @@ namespace FluentAssertions.Streams; [DebuggerNonUserCode] public class BufferedStreamAssertions : BufferedStreamAssertions { - private readonly Assertion assertion; + private readonly AssertionChain assertionChain; - public BufferedStreamAssertions(BufferedStream stream, Assertion assertion) - : base(stream, assertion) + public BufferedStreamAssertions(BufferedStream stream, AssertionChain assertionChain) + : base(stream, assertionChain) { - this.assertion = assertion; + this.assertionChain = assertionChain; } } public class BufferedStreamAssertions : StreamAssertions where TAssertions : BufferedStreamAssertions { - private readonly Assertion assertion; + private readonly AssertionChain assertionChain; - public BufferedStreamAssertions(BufferedStream stream, Assertion assertion) - : base(stream, assertion) + public BufferedStreamAssertions(BufferedStream stream, AssertionChain assertionChain) + : base(stream, assertionChain) { - this.assertion = assertion; + this.assertionChain = assertionChain; } protected override string Identifier => "buffered stream"; @@ -47,15 +47,15 @@ public BufferedStreamAssertions(BufferedStream stream, Assertion assertion) /// public AndConstraint HaveBufferSize(int expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected the buffer size of {context:stream} to be {0}{reason}, but found a reference.", expected); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject!.BufferSize == expected) .FailWith("Expected the buffer size of {context:stream} to be {0}{reason}, but it was {1}.", @@ -78,15 +78,15 @@ public AndConstraint HaveBufferSize(int expected, string because = /// public AndConstraint NotHaveBufferSize(int unexpected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected the buffer size of {context:stream} not to be {0}{reason}, but found a reference.", unexpected); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject!.BufferSize != unexpected) .FailWith("Expected the buffer size of {context:stream} not to be {0}{reason}, but it was.", diff --git a/Src/FluentAssertions/Streams/StreamAssertions.cs b/Src/FluentAssertions/Streams/StreamAssertions.cs index c2b4b0f601..c8161ae870 100644 --- a/Src/FluentAssertions/Streams/StreamAssertions.cs +++ b/Src/FluentAssertions/Streams/StreamAssertions.cs @@ -12,8 +12,8 @@ namespace FluentAssertions.Streams; [DebuggerNonUserCode] public class StreamAssertions : StreamAssertions { - public StreamAssertions(Stream stream, Assertion assertion) - : base(stream, assertion) + public StreamAssertions(Stream stream, AssertionChain assertionChain) + : base(stream, assertionChain) { } } @@ -25,12 +25,12 @@ public class StreamAssertions : ReferenceTypeAssertions { - private readonly Assertion assertion; + private readonly AssertionChain assertionChain; - public StreamAssertions(TSubject stream, Assertion assertion) - : base(stream, assertion) + public StreamAssertions(TSubject stream, AssertionChain assertionChain) + : base(stream, assertionChain) { - this.assertion = assertion; + this.assertionChain = assertionChain; } protected override string Identifier => "stream"; @@ -47,14 +47,14 @@ public StreamAssertions(TSubject stream, Assertion assertion) /// public AndConstraint BeWritable(string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected {context:stream} to be writable{reason}, but found a reference."); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject!.CanWrite) .FailWith("Expected {context:stream} to be writable{reason}, but it was not."); @@ -75,14 +75,14 @@ public AndConstraint BeWritable(string because = "", params object[ /// public AndConstraint NotBeWritable(string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected {context:stream} not to be writable{reason}, but found a reference."); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(!Subject!.CanWrite) .FailWith("Expected {context:stream} not to be writable{reason}, but it was."); @@ -103,14 +103,14 @@ public AndConstraint NotBeWritable(string because = "", params obje /// public AndConstraint BeSeekable(string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected {context:stream} to be seekable{reason}, but found a reference."); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject!.CanSeek) .FailWith("Expected {context:stream} to be seekable{reason}, but it was not."); @@ -131,14 +131,14 @@ public AndConstraint BeSeekable(string because = "", params object[ /// public AndConstraint NotBeSeekable(string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected {context:stream} not to be seekable{reason}, but found a reference."); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(!Subject!.CanSeek) .FailWith("Expected {context:stream} not to be seekable{reason}, but it was."); @@ -159,14 +159,14 @@ public AndConstraint NotBeSeekable(string because = "", params obje /// public AndConstraint BeReadable(string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected {context:stream} to be readable{reason}, but found a reference."); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject!.CanRead) .FailWith("Expected {context:stream} to be readable{reason}, but it was not."); @@ -187,14 +187,14 @@ public AndConstraint BeReadable(string because = "", params object[ /// public AndConstraint NotBeReadable(string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected {context:stream} not to be readable{reason}, but found a reference."); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(!Subject!.CanRead) .FailWith("Expected {context:stream} not to be readable{reason}, but it was."); @@ -216,13 +216,13 @@ public AndConstraint NotBeReadable(string because = "", params obje /// public AndConstraint HavePosition(long expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected the position of {context:stream} to be {0}{reason}, but found a reference.", expected); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { long position; @@ -233,7 +233,7 @@ public AndConstraint HavePosition(long expected, string because = " catch (Exception exception) when (exception is IOException or NotSupportedException or ObjectDisposedException) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .FailWith("Expected the position of {context:stream} to be {0}{reason}, but it failed with:" + Environment.NewLine + "{1}", @@ -242,7 +242,7 @@ public AndConstraint HavePosition(long expected, string because = " return new AndConstraint((TAssertions)this); } - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(position == expected) .FailWith("Expected the position of {context:stream} to be {0}{reason}, but it was {1}.", @@ -265,13 +265,13 @@ public AndConstraint HavePosition(long expected, string because = " /// public AndConstraint NotHavePosition(long unexpected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected the position of {context:stream} not to be {0}{reason}, but found a reference.", unexpected); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { long position; @@ -282,7 +282,7 @@ public AndConstraint NotHavePosition(long unexpected, string becaus catch (Exception exception) when (exception is IOException or NotSupportedException or ObjectDisposedException) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .FailWith("Expected the position of {context:stream} not to be {0}{reason}, but it failed with:" + Environment.NewLine + "{1}", @@ -291,7 +291,7 @@ public AndConstraint NotHavePosition(long unexpected, string becaus return new AndConstraint((TAssertions)this); } - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(position != unexpected) .FailWith("Expected the position of {context:stream} not to be {0}{reason}, but it was.", @@ -314,13 +314,13 @@ public AndConstraint NotHavePosition(long unexpected, string becaus /// public AndConstraint HaveLength(long expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected the length of {context:stream} to be {0}{reason}, but found a reference.", expected); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { long length; @@ -331,7 +331,7 @@ public AndConstraint HaveLength(long expected, string because = "", catch (Exception exception) when (exception is IOException or NotSupportedException or ObjectDisposedException) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .FailWith("Expected the length of {context:stream} to be {0}{reason}, but it failed with:" + Environment.NewLine + "{1}", @@ -340,7 +340,7 @@ public AndConstraint HaveLength(long expected, string because = "", return new AndConstraint((TAssertions)this); } - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(length == expected) .FailWith("Expected the length of {context:stream} to be {0}{reason}, but it was {1}.", @@ -363,13 +363,13 @@ public AndConstraint HaveLength(long expected, string because = "", /// public AndConstraint NotHaveLength(long unexpected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected the length of {context:stream} not to be {0}{reason}, but found a reference.", unexpected); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { long length; @@ -380,7 +380,7 @@ public AndConstraint NotHaveLength(long unexpected, string because catch (Exception exception) when (exception is IOException or NotSupportedException or ObjectDisposedException) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .FailWith("Expected the length of {context:stream} not to be {0}{reason}, but it failed with:" + Environment.NewLine + "{1}", @@ -389,7 +389,7 @@ public AndConstraint NotHaveLength(long unexpected, string because return new AndConstraint((TAssertions)this); } - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(length != unexpected) .FailWith("Expected the length of {context:stream} not to be {0}{reason}, but it was.", @@ -411,14 +411,14 @@ public AndConstraint NotHaveLength(long unexpected, string because /// public AndConstraint BeReadOnly(string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected {context:stream} to be read-only{reason}, but found a reference."); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(!Subject!.CanWrite && Subject.CanRead) .FailWith("Expected {context:stream} to be read-only{reason}, but it was writable or not readable."); @@ -439,14 +439,14 @@ public AndConstraint BeReadOnly(string because = "", params object[ /// public AndConstraint NotBeReadOnly(string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected {context:stream} not to be read-only{reason}, but found a reference."); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject!.CanWrite || !Subject.CanRead) .FailWith("Expected {context:stream} not to be read-only{reason}, but it was."); @@ -467,14 +467,14 @@ public AndConstraint NotBeReadOnly(string because = "", params obje /// public AndConstraint BeWriteOnly(string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected {context:stream} to be write-only{reason}, but found a reference."); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject!.CanWrite && !Subject.CanRead) .FailWith("Expected {context:stream} to be write-only{reason}, but it was readable or not writable."); @@ -495,14 +495,14 @@ public AndConstraint BeWriteOnly(string because = "", params object /// public AndConstraint NotBeWriteOnly(string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected {context:stream} not to be write-only{reason}, but found a reference."); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(!Subject!.CanWrite || Subject.CanRead) .FailWith("Expected {context:stream} not to be write-only{reason}, but it was."); diff --git a/Src/FluentAssertions/Types/AssemblyAssertions.cs b/Src/FluentAssertions/Types/AssemblyAssertions.cs index 0c1d4d660f..cafad320c1 100644 --- a/Src/FluentAssertions/Types/AssemblyAssertions.cs +++ b/Src/FluentAssertions/Types/AssemblyAssertions.cs @@ -13,15 +13,15 @@ namespace FluentAssertions.Types; /// public class AssemblyAssertions : ReferenceTypeAssertions { - private readonly Assertion assertion; + private readonly AssertionChain assertionChain; /// /// Initializes a new instance of the class. /// - public AssemblyAssertions(Assembly assembly, Assertion assertion) - : base(assembly, assertion) + public AssemblyAssertions(Assembly assembly, AssertionChain assertionChain) + : base(assembly, assertionChain) { - this.assertion = assertion; + this.assertionChain = assertionChain; } /// @@ -42,19 +42,19 @@ public AndConstraint NotReference(Assembly assembly, string var assemblyName = assembly.GetName().Name; - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected assembly not to reference assembly {0}{reason}, but {context:assembly} is .", assemblyName); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { var subjectName = Subject!.GetName().Name; IEnumerable references = Subject.GetReferencedAssemblies().Select(x => x.Name); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(!references.Contains(assemblyName)) .FailWith("Expected assembly {0} not to reference assembly {1}{reason}.", subjectName, assemblyName); @@ -81,18 +81,18 @@ public AndConstraint Reference(Assembly assembly, string bec var assemblyName = assembly.GetName().Name; - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected assembly to reference assembly {0}{reason}, but {context:assembly} is .", assemblyName); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { var subjectName = Subject!.GetName().Name; IEnumerable references = Subject.GetReferencedAssemblies().Select(x => x.Name); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(references.Contains(assemblyName)) .FailWith("Expected assembly {0} to reference assembly {1}{reason}, but it does not.", subjectName, assemblyName); @@ -120,7 +120,7 @@ public AndConstraint Reference(Assembly assembly, string bec { Guard.ThrowIfArgumentIsNullOrEmpty(name); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected assembly to define type {0}.{1}{reason}, but {context:assembly} is .", @@ -128,11 +128,11 @@ public AndConstraint Reference(Assembly assembly, string bec Type foundType = null; - if (assertion.Succeeded) + if (assertionChain.Succeeded) { foundType = Subject!.GetTypes().SingleOrDefault(t => t.Namespace == @namespace && t.Name == name); - assertion + assertionChain .ForCondition(foundType is not null) .BecauseOf(because, becauseArgs) .FailWith("Expected assembly {0} to define type {1}.{2}{reason}, but it does not.", @@ -152,13 +152,13 @@ public AndConstraint Reference(Assembly assembly, string bec /// public AndConstraint BeUnsigned(string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject is not null) .FailWith("Can't check for assembly signing if {context:assembly} reference is ."); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject!.GetName().GetPublicKey() is not { Length: > 0 }) .FailWith( @@ -185,16 +185,16 @@ public AndConstraint BeSignedWithPublicKey(string publicKey, { Guard.ThrowIfArgumentIsNullOrEmpty(publicKey); - assertion + assertionChain .ForCondition(Subject is not null) .FailWith("Can't check for assembly signing if {context:assembly} reference is ."); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { var bytes = Subject!.GetName().GetPublicKey() ?? []; string assemblyKey = ToHexString(bytes); - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected assembly {0} to have public key {1} ", Subject.FullName, publicKey) .ForCondition(bytes.Length != 0) diff --git a/Src/FluentAssertions/Types/ConstructorInfoAssertions.cs b/Src/FluentAssertions/Types/ConstructorInfoAssertions.cs index dee2663ba0..975151318e 100644 --- a/Src/FluentAssertions/Types/ConstructorInfoAssertions.cs +++ b/Src/FluentAssertions/Types/ConstructorInfoAssertions.cs @@ -14,9 +14,9 @@ public class ConstructorInfoAssertions : MethodBaseAssertions class. /// /// The constructorInfo from which to select properties. - /// - public ConstructorInfoAssertions(ConstructorInfo constructorInfo, Assertion assertion) - : base(constructorInfo, assertion) + /// + public ConstructorInfoAssertions(ConstructorInfo constructorInfo, AssertionChain assertionChain) + : base(constructorInfo, assertionChain) { } diff --git a/Src/FluentAssertions/Types/MemberInfoAssertions.cs b/Src/FluentAssertions/Types/MemberInfoAssertions.cs index d1e3197a2a..01d91e62c5 100644 --- a/Src/FluentAssertions/Types/MemberInfoAssertions.cs +++ b/Src/FluentAssertions/Types/MemberInfoAssertions.cs @@ -18,12 +18,12 @@ public abstract class MemberInfoAssertions : ReferenceTyp where TSubject : MemberInfo where TAssertions : MemberInfoAssertions { - private readonly Assertion assertion; + private readonly AssertionChain assertionChain; - protected MemberInfoAssertions(TSubject subject, Assertion assertion) - : base(subject, assertion) + protected MemberInfoAssertions(TSubject subject, AssertionChain assertionChain) + : base(subject, assertionChain) { - this.assertion = assertion; + this.assertionChain = assertionChain; } /// @@ -82,7 +82,7 @@ protected MemberInfoAssertions(TSubject subject, Assertion assertion) { Guard.ThrowIfArgumentIsNull(isMatchingAttributePredicate); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith( @@ -91,11 +91,11 @@ protected MemberInfoAssertions(TSubject subject, Assertion assertion) IEnumerable attributes = []; - if (assertion.Succeeded) + if (assertionChain.Succeeded) { attributes = Subject.GetMatchingAttributes(isMatchingAttributePredicate); - assertion + assertionChain .ForCondition(attributes.Any()) .BecauseOf(because, becauseArgs) .FailWith( @@ -128,18 +128,18 @@ protected MemberInfoAssertions(TSubject subject, Assertion assertion) { Guard.ThrowIfArgumentIsNull(isMatchingAttributePredicate); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith( $"Expected {Identifier} to not be decorated with {typeof(TAttribute)}{{reason}}" + ", but {context:member} is ."); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { IEnumerable attributes = Subject.GetMatchingAttributes(isMatchingAttributePredicate); - assertion + assertionChain .ForCondition(!attributes.Any()) .BecauseOf(because, becauseArgs) .FailWith( diff --git a/Src/FluentAssertions/Types/MethodBaseAssertions.cs b/Src/FluentAssertions/Types/MethodBaseAssertions.cs index 44834043cd..89ec71e50a 100644 --- a/Src/FluentAssertions/Types/MethodBaseAssertions.cs +++ b/Src/FluentAssertions/Types/MethodBaseAssertions.cs @@ -16,12 +16,12 @@ public abstract class MethodBaseAssertions : MemberInfoAs where TSubject : MethodBase where TAssertions : MethodBaseAssertions { - private readonly Assertion assertion; + private readonly AssertionChain assertionChain; - protected MethodBaseAssertions(TSubject subject, Assertion assertion) - : base(subject, assertion) + protected MethodBaseAssertions(TSubject subject, AssertionChain assertionChain) + : base(subject, assertionChain) { - this.assertion = assertion; + this.assertionChain = assertionChain; } /// @@ -42,16 +42,16 @@ protected MethodBaseAssertions(TSubject subject, Assertion assertion) { Guard.ThrowIfArgumentIsOutOfRange(accessModifier); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith($"Expected method to be {accessModifier}{{reason}}, but {{context:member}} is ."); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { CSharpAccessModifier subjectAccessModifier = Subject.GetCSharpAccessModifier(); - assertion + assertionChain .ForCondition(accessModifier == subjectAccessModifier) .BecauseOf(because, becauseArgs) .FailWith( @@ -79,16 +79,16 @@ protected MethodBaseAssertions(TSubject subject, Assertion assertion) { Guard.ThrowIfArgumentIsOutOfRange(accessModifier); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith($"Expected method not to be {accessModifier}{{reason}}, but {{context:member}} is ."); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { CSharpAccessModifier subjectAccessModifier = Subject.GetCSharpAccessModifier(); - assertion + assertionChain .ForCondition(accessModifier != subjectAccessModifier) .BecauseOf(because, becauseArgs) .FailWith($"Expected method {Subject!.Name} not to be {accessModifier}{{reason}}, but it is."); diff --git a/Src/FluentAssertions/Types/MethodInfoAssertions.cs b/Src/FluentAssertions/Types/MethodInfoAssertions.cs index bf26fb5d6a..c29be79740 100644 --- a/Src/FluentAssertions/Types/MethodInfoAssertions.cs +++ b/Src/FluentAssertions/Types/MethodInfoAssertions.cs @@ -12,12 +12,12 @@ namespace FluentAssertions.Types; [DebuggerNonUserCode] public class MethodInfoAssertions : MethodBaseAssertions { - private readonly Assertion assertion; + private readonly AssertionChain assertionChain; - public MethodInfoAssertions(MethodInfo methodInfo, Assertion assertion) - : base(methodInfo, assertion) + public MethodInfoAssertions(MethodInfo methodInfo, AssertionChain assertionChain) + : base(methodInfo, assertionChain) { - this.assertion = assertion; + this.assertionChain = assertionChain; } /// @@ -32,14 +32,14 @@ public MethodInfoAssertions(MethodInfo methodInfo, Assertion assertion) /// public AndConstraint BeVirtual(string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected method to be virtual{reason}, but {context:member} is ."); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { - assertion + assertionChain .ForCondition(!Subject.IsNonVirtual()) .BecauseOf(because, becauseArgs) .FailWith("Expected method " + SubjectDescription + " to be virtual{reason}, but it is not virtual."); @@ -60,14 +60,14 @@ public AndConstraint BeVirtual(string because = "", params /// public AndConstraint NotBeVirtual(string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected method not to be virtual{reason}, but {context:member} is ."); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { - assertion + assertionChain .ForCondition(Subject.IsNonVirtual()) .BecauseOf(because, becauseArgs) .FailWith("Expected method " + SubjectDescription + " not to be virtual{reason}, but it is."); @@ -88,14 +88,14 @@ public AndConstraint NotBeVirtual(string because = "", par /// public AndConstraint BeAsync(string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected method to be async{reason}, but {context:member} is ."); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { - assertion + assertionChain .ForCondition(Subject.IsAsync()) .BecauseOf(because, becauseArgs) .FailWith("Expected method " + SubjectDescription + " to be async{reason}, but it is not."); @@ -116,14 +116,14 @@ public AndConstraint BeAsync(string because = "", params o /// public AndConstraint NotBeAsync(string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected method not to be async{reason}, but {context:member} is ."); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { - assertion + assertionChain .ForCondition(!Subject.IsAsync()) .BecauseOf(because, becauseArgs) .FailWith("Expected method " + SubjectDescription + " not to be async{reason}, but it is."); @@ -145,14 +145,14 @@ public AndConstraint NotBeAsync(string because = "", param public AndConstraint> ReturnVoid(string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected the return type of method to be void{reason}, but {context:member} is ."); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { - assertion + assertionChain .ForCondition(typeof(void) == Subject!.ReturnType) .BecauseOf(because, becauseArgs) .FailWith("Expected the return type of method " + Subject.Name + " to be void{reason}, but it is {0}.", @@ -179,14 +179,14 @@ public AndConstraint NotBeAsync(string because = "", param { Guard.ThrowIfArgumentIsNull(returnType); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected the return type of method to be {0}{reason}, but {context:member} is .", returnType); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { - assertion + assertionChain .ForCondition(returnType == Subject!.ReturnType) .BecauseOf(because, becauseArgs) .FailWith("Expected the return type of method " + Subject.Name + " to be {0}{reason}, but it is {1}.", @@ -226,14 +226,14 @@ public AndConstraint NotBeAsync(string because = "", param public AndConstraint> NotReturnVoid(string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected the return type of method not to be void{reason}, but {context:member} is ."); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { - assertion + assertionChain .ForCondition(typeof(void) != Subject!.ReturnType) .BecauseOf(because, becauseArgs) .FailWith("Expected the return type of method " + Subject.Name + " not to be void{reason}, but it is."); @@ -259,15 +259,15 @@ public AndConstraint NotBeAsync(string because = "", param { Guard.ThrowIfArgumentIsNull(returnType); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith( "Expected the return type of method not to be {0}{reason}, but {context:member} is .", returnType); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { - assertion + assertionChain .ForCondition(returnType != Subject!.ReturnType) .BecauseOf(because, becauseArgs) .FailWith( diff --git a/Src/FluentAssertions/Types/MethodInfoSelectorAssertions.cs b/Src/FluentAssertions/Types/MethodInfoSelectorAssertions.cs index 3169a2fdb0..9f7c17ea7c 100644 --- a/Src/FluentAssertions/Types/MethodInfoSelectorAssertions.cs +++ b/Src/FluentAssertions/Types/MethodInfoSelectorAssertions.cs @@ -17,16 +17,16 @@ namespace FluentAssertions.Types; [DebuggerNonUserCode] public class MethodInfoSelectorAssertions { - private readonly Assertion assertion; + private readonly AssertionChain assertionChain; /// /// Initializes a new instance of the class. /// /// The methods to assert. /// is . - public MethodInfoSelectorAssertions(Assertion assertion, params MethodInfo[] methods) + public MethodInfoSelectorAssertions(AssertionChain assertionChain, params MethodInfo[] methods) { - this.assertion = assertion; + this.assertionChain = assertionChain; Guard.ThrowIfArgumentIsNull(methods); SubjectMethods = methods; @@ -56,7 +56,7 @@ public AndConstraint BeVirtual(string because = "" Environment.NewLine + GetDescriptionsFor(nonVirtualMethods); - assertion + assertionChain .ForCondition(nonVirtualMethods.Length == 0) .BecauseOf(because, becauseArgs) .FailWith(failureMessage); @@ -83,7 +83,7 @@ public AndConstraint NotBeVirtual(string because = Environment.NewLine + GetDescriptionsFor(virtualMethods); - assertion + assertionChain .ForCondition(virtualMethods.Length == 0) .BecauseOf(because, becauseArgs) .FailWith(failureMessage); @@ -120,7 +120,7 @@ public AndConstraint BeAsync(string because = "", Environment.NewLine + GetDescriptionsFor(nonAsyncMethods); - assertion + assertionChain .ForCondition(nonAsyncMethods.Length == 0) .BecauseOf(because, becauseArgs) .FailWith(failureMessage); @@ -147,7 +147,7 @@ public AndConstraint NotBeAsync(string because = " Environment.NewLine + GetDescriptionsFor(asyncMethods); - assertion + assertionChain .ForCondition(asyncMethods.Length == 0) .BecauseOf(because, becauseArgs) .FailWith(failureMessage); @@ -200,7 +200,7 @@ public AndConstraint NotBeAsync(string because = " Environment.NewLine + GetDescriptionsFor(methodsWithoutAttribute); - assertion + assertionChain .ForCondition(methodsWithoutAttribute.Length == 0) .BecauseOf(because, becauseArgs) .FailWith(failureMessage, typeof(TAttribute)); @@ -253,7 +253,7 @@ public AndConstraint NotBeAsync(string because = " Environment.NewLine + GetDescriptionsFor(methodsWithAttribute); - assertion + assertionChain .ForCondition(methodsWithAttribute.Length == 0) .BecauseOf(because, becauseArgs) .FailWith(failureMessage, typeof(TAttribute)); @@ -280,7 +280,7 @@ public AndConstraint NotBeAsync(string because = " var message = $"Expected all selected methods to be {accessModifier}{{reason}}, but the following methods are not:" + Environment.NewLine + GetDescriptionsFor(methods); - assertion + assertionChain .ForCondition(methods.Length == 0) .BecauseOf(because, becauseArgs) .FailWith(message); @@ -307,7 +307,7 @@ public AndConstraint NotBeAsync(string because = " var message = $"Expected all selected methods to not be {accessModifier}{{reason}}, but the following methods are:" + Environment.NewLine + GetDescriptionsFor(methods); - assertion + assertionChain .ForCondition(methods.Length == 0) .BecauseOf(because, becauseArgs) .FailWith(message); diff --git a/Src/FluentAssertions/Types/PropertyInfoAssertions.cs b/Src/FluentAssertions/Types/PropertyInfoAssertions.cs index 472b566997..60cf0ebfd0 100644 --- a/Src/FluentAssertions/Types/PropertyInfoAssertions.cs +++ b/Src/FluentAssertions/Types/PropertyInfoAssertions.cs @@ -12,12 +12,12 @@ namespace FluentAssertions.Types; [DebuggerNonUserCode] public class PropertyInfoAssertions : MemberInfoAssertions { - private readonly Assertion assertion; + private readonly AssertionChain assertionChain; - public PropertyInfoAssertions(PropertyInfo propertyInfo, Assertion assertion) - : base(propertyInfo, assertion) + public PropertyInfoAssertions(PropertyInfo propertyInfo, AssertionChain assertionChain) + : base(propertyInfo, assertionChain) { - this.assertion = assertion; + this.assertionChain = assertionChain; } /// @@ -33,14 +33,14 @@ public PropertyInfoAssertions(PropertyInfo propertyInfo, Assertion assertion) public AndConstraint BeVirtual( string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected property to be virtual{reason}, but {context:property} is ."); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { - assertion + assertionChain .ForCondition(Subject.IsVirtual()) .BecauseOf(because, becauseArgs) .FailWith($"Expected property {GetDescriptionFor(Subject)} to be virtual{{reason}}, but it is not."); @@ -61,14 +61,14 @@ public PropertyInfoAssertions(PropertyInfo propertyInfo, Assertion assertion) /// public AndConstraint NotBeVirtual(string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected property not to be virtual{reason}, but {context:property} is ."); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { - assertion + assertionChain .ForCondition(!Subject.IsVirtual()) .BecauseOf(because, becauseArgs) .FailWith($"Expected property {GetDescriptionFor(Subject)} not to be virtual{{reason}}, but it is."); @@ -90,14 +90,14 @@ public AndConstraint NotBeVirtual(string because = "", p public AndConstraint BeWritable( string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected property to have a setter{reason}, but {context:property} is ."); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { - assertion + assertionChain .ForCondition(Subject!.CanWrite) .BecauseOf(because, becauseArgs) .FailWith( @@ -126,21 +126,21 @@ public AndConstraint NotBeVirtual(string because = "", p { Guard.ThrowIfArgumentIsOutOfRange(accessModifier); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith($"Expected {Identifier} to be {accessModifier}{{reason}}, but {{context:property}} is ."); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { - assertion + assertionChain .ForCondition(Subject!.CanWrite) .BecauseOf(because, becauseArgs) .FailWith( "Expected {context:property} {0} to have a setter{reason}.", Subject); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { Subject!.GetSetMethod(nonPublic: true).Should().HaveAccessModifier(accessModifier, because, becauseArgs); } @@ -162,14 +162,14 @@ public AndConstraint NotBeVirtual(string because = "", p public AndConstraint NotBeWritable( string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected property not to have a setter{reason}, but {context:property} is ."); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { - assertion + assertionChain .ForCondition(!Subject!.CanWrite) .BecauseOf(because, becauseArgs) .FailWith( @@ -192,14 +192,14 @@ public AndConstraint NotBeVirtual(string because = "", p /// public AndConstraint BeReadable(string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected property to have a getter{reason}, but {context:property} is ."); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { - assertion.ForCondition(Subject!.CanRead) + assertionChain.ForCondition(Subject!.CanRead) .BecauseOf(because, becauseArgs) .FailWith("Expected property " + Subject.Name + " to have a getter{reason}, but it does not."); } @@ -225,18 +225,18 @@ public AndConstraint BeReadable(string because = "", par { Guard.ThrowIfArgumentIsOutOfRange(accessModifier); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith($"Expected {Identifier} to be {accessModifier}{{reason}}, but {{context:property}} is ."); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { - assertion.ForCondition(Subject!.CanRead) + assertionChain.ForCondition(Subject!.CanRead) .BecauseOf(because, becauseArgs) .FailWith("Expected property " + Subject.Name + " to have a getter{reason}, but it does not."); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { Subject!.GetGetMethod(nonPublic: true).Should().HaveAccessModifier(accessModifier, because, becauseArgs); } @@ -258,14 +258,14 @@ public AndConstraint BeReadable(string because = "", par public AndConstraint NotBeReadable( string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected property not to have a getter{reason}, but {context:property} is ."); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { - assertion + assertionChain .ForCondition(!Subject!.CanRead) .BecauseOf(because, becauseArgs) .FailWith( @@ -293,14 +293,14 @@ public AndConstraint BeReadable(string because = "", par { Guard.ThrowIfArgumentIsNull(propertyType); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected type of property to be {0}{reason}, but {context:property} is .", propertyType); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { - assertion.ForCondition(Subject!.PropertyType == propertyType) + assertionChain.ForCondition(Subject!.PropertyType == propertyType) .BecauseOf(because, becauseArgs) .FailWith("Expected Type of property " + Subject.Name + " to be {0}{reason}, but it is {1}.", propertyType, Subject.PropertyType); @@ -341,14 +341,14 @@ public AndConstraint NotReturn(Type propertyType, string { Guard.ThrowIfArgumentIsNull(propertyType); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected type of property not to be {0}{reason}, but {context:property} is .", propertyType); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { - assertion + assertionChain .ForCondition(Subject!.PropertyType != propertyType) .BecauseOf(because, becauseArgs) .FailWith("Expected Type of property " + Subject.Name + " not to be {0}{reason}, but it is.", propertyType); diff --git a/Src/FluentAssertions/Types/PropertyInfoSelectorAssertions.cs b/Src/FluentAssertions/Types/PropertyInfoSelectorAssertions.cs index 31e31090aa..525e202bd4 100644 --- a/Src/FluentAssertions/Types/PropertyInfoSelectorAssertions.cs +++ b/Src/FluentAssertions/Types/PropertyInfoSelectorAssertions.cs @@ -16,7 +16,7 @@ namespace FluentAssertions.Types; [DebuggerNonUserCode] public class PropertyInfoSelectorAssertions { - private readonly Assertion assertion; + private readonly AssertionChain assertionChain; /// /// Gets the object whose value is being asserted. @@ -28,9 +28,9 @@ public class PropertyInfoSelectorAssertions /// /// The properties to assert. /// is . - public PropertyInfoSelectorAssertions(Assertion assertion, params PropertyInfo[] properties) + public PropertyInfoSelectorAssertions(AssertionChain assertionChain, params PropertyInfo[] properties) { - this.assertion = assertion; + this.assertionChain = assertionChain; Guard.ThrowIfArgumentIsNull(properties); SubjectProperties = properties; @@ -50,7 +50,7 @@ public AndConstraint BeVirtual(string because = { PropertyInfo[] nonVirtualProperties = GetAllNonVirtualPropertiesFromSelection(); - assertion + assertionChain .ForCondition(nonVirtualProperties.Length == 0) .BecauseOf(because, becauseArgs) .FailWith( @@ -74,7 +74,7 @@ public AndConstraint NotBeVirtual(string because { PropertyInfo[] virtualProperties = GetAllVirtualPropertiesFromSelection(); - assertion + assertionChain .ForCondition(virtualProperties.Length == 0) .BecauseOf(because, becauseArgs) .FailWith( @@ -98,7 +98,7 @@ public AndConstraint BeWritable(string because = { PropertyInfo[] readOnlyProperties = GetAllReadOnlyPropertiesFromSelection(); - assertion + assertionChain .ForCondition(readOnlyProperties.Length == 0) .BecauseOf(because, becauseArgs) .FailWith( @@ -122,7 +122,7 @@ public AndConstraint NotBeWritable(string becaus { PropertyInfo[] writableProperties = GetAllWritablePropertiesFromSelection(); - assertion + assertionChain .ForCondition(writableProperties.Length == 0) .BecauseOf(because, becauseArgs) .FailWith( @@ -168,7 +168,7 @@ private PropertyInfo[] GetAllVirtualPropertiesFromSelection() { PropertyInfo[] propertiesWithoutAttribute = GetPropertiesWithout(); - assertion + assertionChain .ForCondition(propertiesWithoutAttribute.Length == 0) .BecauseOf(because, becauseArgs) .FailWith( @@ -195,7 +195,7 @@ private PropertyInfo[] GetAllVirtualPropertiesFromSelection() { PropertyInfo[] propertiesWithAttribute = GetPropertiesWith(); - assertion + assertionChain .ForCondition(propertiesWithAttribute.Length == 0) .BecauseOf(because, becauseArgs) .FailWith( diff --git a/Src/FluentAssertions/Types/TypeAssertions.cs b/Src/FluentAssertions/Types/TypeAssertions.cs index 7463360a43..14fd5e4ea5 100644 --- a/Src/FluentAssertions/Types/TypeAssertions.cs +++ b/Src/FluentAssertions/Types/TypeAssertions.cs @@ -16,15 +16,15 @@ namespace FluentAssertions.Types; [DebuggerNonUserCode] public class TypeAssertions : ReferenceTypeAssertions { - private readonly Assertion assertion; + private readonly AssertionChain assertionChain; /// /// Initializes a new instance of the class. /// - public TypeAssertions(Type type, Assertion assertion) - : base(type, assertion) + public TypeAssertions(Type type, AssertionChain assertionChain) + : base(type, assertionChain) { - this.assertion = assertion; + this.assertionChain = assertionChain; } /// @@ -55,7 +55,7 @@ public AndConstraint Be(string because = "", params o /// public AndConstraint Be(Type expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject == expected) .FailWith(GetFailureMessageIfTypesAreDifferent(Subject, expected)); @@ -101,7 +101,7 @@ public new AndConstraint BeAssignableTo(Type type, string becaus ? Subject.IsAssignableToOpenGeneric(type) : type.IsAssignableFrom(Subject); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(isAssignable) .FailWith("Expected {context:type} {0} to be assignable to {1}{reason}, but it is not.", Subject, type); @@ -147,7 +147,7 @@ public new AndConstraint NotBeAssignableTo(Type type, string bec ? Subject.IsAssignableToOpenGeneric(type) : type.IsAssignableFrom(Subject); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(!isAssignable) .FailWith("Expected {context:type} {0} to not be assignable to {1}{reason}, but it is.", Subject, type); @@ -212,7 +212,7 @@ public AndConstraint NotBe(Type unexpected, string because = "", { string nameOfUnexpectedType = unexpected is not null ? $"[{unexpected.AssemblyQualifiedName}]" : ""; - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject != unexpected) .FailWith("Expected type not to be " + nameOfUnexpectedType + "{reason}, but it is."); @@ -236,7 +236,7 @@ public AndConstraint NotBe(Type unexpected, string because = "", { IEnumerable attributes = Subject.GetMatchingAttributes(); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(attributes.Any()) .FailWith("Expected type {0} to be decorated with {1}{reason}, but the attribute was not found.", @@ -270,7 +270,7 @@ public AndConstraint NotBe(Type unexpected, string because = "", IEnumerable attributes = Subject.GetMatchingAttributes(isMatchingAttributePredicate); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(attributes.Any()) .FailWith( @@ -296,7 +296,7 @@ public AndConstraint NotBe(Type unexpected, string because = "", { IEnumerable attributes = Subject.GetMatchingOrInheritedAttributes(); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(attributes.Any()) .FailWith("Expected type {0} to be decorated with or inherit {1}{reason}, but the attribute was not found.", @@ -330,7 +330,7 @@ public AndConstraint NotBe(Type unexpected, string because = "", IEnumerable attributes = Subject.GetMatchingOrInheritedAttributes(isMatchingAttributePredicate); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(attributes.Any()) .FailWith( @@ -353,7 +353,7 @@ public AndConstraint NotBe(Type unexpected, string because = "", public AndConstraint NotBeDecoratedWith(string because = "", params object[] becauseArgs) where TAttribute : Attribute { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(!Subject.IsDecoratedWith()) .FailWith("Expected type {0} to not be decorated with {1}{reason}, but the attribute was found.", @@ -383,7 +383,7 @@ public AndConstraint NotBeDecoratedWith(string becau { Guard.ThrowIfArgumentIsNull(isMatchingAttributePredicate); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(!Subject.IsDecoratedWith(isMatchingAttributePredicate)) .FailWith( @@ -408,7 +408,7 @@ public AndConstraint NotBeDecoratedWith(string becau string because = "", params object[] becauseArgs) where TAttribute : Attribute { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(!Subject.IsDecoratedWithOrInherit()) .FailWith("Expected type {0} to not be decorated with or inherit {1}{reason}, but the attribute was found.", @@ -439,7 +439,7 @@ public AndConstraint NotBeDecoratedWith(string becau { Guard.ThrowIfArgumentIsNull(isMatchingAttributePredicate); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(!Subject.IsDecoratedWithOrInherit(isMatchingAttributePredicate)) .FailWith( @@ -474,7 +474,7 @@ private bool AssertSubjectImplements(Type interfaceType, string because = "", pa { bool containsInterface = interfaceType.IsAssignableFrom(Subject) && interfaceType != Subject; - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected type {0} to implement interface {1}{reason}", Subject, interfaceType) .ForCondition(interfaceType.IsInterface) @@ -483,7 +483,7 @@ private bool AssertSubjectImplements(Type interfaceType, string because = "", pa .ForCondition(containsInterface) .FailWith(", but it does not."); - return assertion.Succeeded; + return assertionChain.Succeeded; } /// @@ -521,7 +521,7 @@ public AndConstraint NotImplement(Type interfaceType, string bec bool containsInterface = interfaceType.IsAssignableFrom(Subject) && interfaceType != Subject; - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected type {0} to not implement interface {1}{reason}", Subject, interfaceType) .ForCondition(interfaceType.IsInterface) @@ -571,7 +571,7 @@ public AndConstraint BeDerivedFrom(Type baseType, string because ? Subject.IsDerivedFromOpenGeneric(baseType) : Subject.IsSubclassOf(baseType); - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected type {0} to be derived from {1}{reason}", Subject, baseType) .ForCondition(!baseType.IsInterface) @@ -621,7 +621,7 @@ public AndConstraint NotBeDerivedFrom(Type baseType, string beca ? Subject.IsDerivedFromOpenGeneric(baseType) : Subject.IsSubclassOf(baseType); - assertion + assertionChain .BecauseOf(because, becauseArgs) .WithExpectation("Expected type {0} not to be derived from {1}{reason}", Subject, baseType) .ForCondition(!baseType.IsInterface) @@ -665,16 +665,16 @@ public AndConstraint NotBeDerivedFrom(string because /// is not a class. public AndConstraint BeSealed(string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected type to be sealed{reason}, but {context:type} is ."); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { AssertThatSubjectIsClass(); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject.IsCSharpSealed()) .FailWith("Expected type {0} to be sealed{reason}.", Subject); @@ -697,16 +697,16 @@ public AndConstraint BeSealed(string because = "", params object /// is not a class. public AndConstraint NotBeSealed(string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected type not to be sealed{reason}, but {context:type} is ."); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { AssertThatSubjectIsClass(); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(!Subject.IsCSharpSealed()) .FailWith("Expected type {0} not to be sealed{reason}.", Subject); @@ -729,16 +729,16 @@ public AndConstraint NotBeSealed(string because = "", params obj /// is not a class. public AndConstraint BeAbstract(string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected type to be abstract{reason}, but {context:type} is ."); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { AssertThatSubjectIsClass(); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject.IsCSharpAbstract()) .FailWith("Expected {context:type} {0} to be abstract{reason}.", Subject); @@ -761,16 +761,16 @@ public AndConstraint BeAbstract(string because = "", params obje /// is not a class. public AndConstraint NotBeAbstract(string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected type not to be abstract{reason}, but {context:type} is ."); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { AssertThatSubjectIsClass(); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(!Subject.IsCSharpAbstract()) .FailWith("Expected type {0} not to be abstract{reason}.", Subject); @@ -793,16 +793,16 @@ public AndConstraint NotBeAbstract(string because = "", params o /// is not a class. public AndConstraint BeStatic(string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected type to be static{reason}, but {context:type} is ."); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { AssertThatSubjectIsClass(); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject.IsCSharpStatic()) .FailWith("Expected type {0} to be static{reason}.", Subject); @@ -825,16 +825,16 @@ public AndConstraint BeStatic(string because = "", params object /// is not a class. public AndConstraint NotBeStatic(string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected type not to be static{reason}, but {context:type} is ."); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { AssertThatSubjectIsClass(); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(!Subject.IsCSharpStatic()) .FailWith("Expected type {0} not to be static{reason}.", Subject); @@ -865,7 +865,7 @@ public AndConstraint NotBeStatic(string because = "", params obj Guard.ThrowIfArgumentIsNull(propertyType); Guard.ThrowIfArgumentIsNullOrEmpty(name); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith( @@ -873,12 +873,12 @@ public AndConstraint NotBeStatic(string because = "", params obj PropertyInfo propertyInfo = null; - if (assertion.Succeeded) + if (assertionChain.Succeeded) { propertyInfo = Subject.FindPropertyByName(name); var propertyInfoDescription = PropertyInfoAssertions.GetDescriptionFor(propertyInfo); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(propertyInfo is not null) .FailWith($"Expected {propertyType.Name} {Subject}.{name} to exist{{reason}}, but it does not.") @@ -928,17 +928,17 @@ public AndConstraint NotHaveProperty(string name, string because { Guard.ThrowIfArgumentIsNullOrEmpty(name); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith($"Expected {{context:type}}.{name} to not exist{{reason}}, but {{context:type}} is ."); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { PropertyInfo propertyInfo = Subject.FindPropertyByName(name); var propertyInfoDescription = PropertyInfoAssertions.GetDescriptionFor(propertyInfo); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(propertyInfo is null) .FailWith($"Expected {propertyInfoDescription} to not exist{{reason}}, but it does."); @@ -969,18 +969,18 @@ public AndConstraint NotHaveProperty(string name, string because Guard.ThrowIfArgumentIsNull(interfaceType); Guard.ThrowIfArgumentIsNullOrEmpty(name); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith( $"Expected {{context:type}} to explicitly implement {interfaceType}.{name}{{reason}}" + ", but {context:type} is ."); - if (assertion.Succeeded && AssertSubjectImplements(interfaceType, because, becauseArgs)) + if (assertionChain.Succeeded && AssertSubjectImplements(interfaceType, because, becauseArgs)) { var explicitlyImplementsProperty = Subject.HasExplicitlyImplementedProperty(interfaceType, name); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(explicitlyImplementsProperty) .FailWith( @@ -1034,18 +1034,18 @@ public AndConstraint NotHaveProperty(string name, string because Guard.ThrowIfArgumentIsNull(interfaceType); Guard.ThrowIfArgumentIsNullOrEmpty(name); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith( $"Expected {{context:type}} to not explicitly implement {interfaceType}.{name}{{reason}}" + ", but {context:type} is ."); - if (assertion.Succeeded && AssertSubjectImplements(interfaceType, because, becauseArgs)) + if (assertionChain.Succeeded && AssertSubjectImplements(interfaceType, because, becauseArgs)) { var explicitlyImplementsProperty = Subject.HasExplicitlyImplementedProperty(interfaceType, name); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(!explicitlyImplementsProperty) .FailWith( @@ -1103,18 +1103,18 @@ public AndConstraint NotHaveProperty(string name, string because Guard.ThrowIfArgumentIsNullOrEmpty(name); Guard.ThrowIfArgumentIsNull(parameterTypes); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith( $"Expected {{context:type}} to explicitly implement {interfaceType}.{name}" + $"({GetParameterString(parameterTypes)}){{reason}}, but {{context:type}} is ."); - if (assertion.Succeeded && AssertSubjectImplements(interfaceType, because, becauseArgs)) + if (assertionChain.Succeeded && AssertSubjectImplements(interfaceType, because, becauseArgs)) { var explicitlyImplementsMethod = Subject.HasMethod($"{interfaceType}.{name}", parameterTypes); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(explicitlyImplementsMethod) .FailWith( @@ -1174,18 +1174,18 @@ public AndConstraint NotHaveProperty(string name, string because Guard.ThrowIfArgumentIsNullOrEmpty(name); Guard.ThrowIfArgumentIsNull(parameterTypes); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith( $"Expected {{context:type}} to not explicitly implement {interfaceType}.{name}" + $"({GetParameterString(parameterTypes)}){{reason}}, but {{context:type}} is ."); - if (assertion.Succeeded && AssertSubjectImplements(interfaceType, because, becauseArgs)) + if (assertionChain.Succeeded && AssertSubjectImplements(interfaceType, because, becauseArgs)) { var explicitlyImplementsMethod = Subject.HasMethod($"{interfaceType}.{name}", parameterTypes); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(!explicitlyImplementsMethod) .FailWith( @@ -1241,7 +1241,7 @@ public AndConstraint NotHaveProperty(string name, string because Guard.ThrowIfArgumentIsNull(indexerType); Guard.ThrowIfArgumentIsNull(parameterTypes); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith( @@ -1250,12 +1250,12 @@ public AndConstraint NotHaveProperty(string name, string because PropertyInfo propertyInfo = null; - if (assertion.Succeeded) + if (assertionChain.Succeeded) { propertyInfo = Subject.GetIndexerByParameterTypes(parameterTypes); var propertyInfoDescription = PropertyInfoAssertions.GetDescriptionFor(propertyInfo); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(propertyInfo is not null) .FailWith( @@ -1287,18 +1287,18 @@ public AndConstraint NotHaveProperty(string name, string because { Guard.ThrowIfArgumentIsNull(parameterTypes); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith( $"Expected indexer {{context:type}}[{GetParameterString(parameterTypes)}] to not exist{{reason}}" + ", but {context:type} is ."); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { PropertyInfo propertyInfo = Subject.GetIndexerByParameterTypes(parameterTypes); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(propertyInfo is null) .FailWith( @@ -1331,7 +1331,7 @@ public AndConstraint NotHaveProperty(string name, string because Guard.ThrowIfArgumentIsNullOrEmpty(name); Guard.ThrowIfArgumentIsNull(parameterTypes); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith( @@ -1340,11 +1340,11 @@ public AndConstraint NotHaveProperty(string name, string because MethodInfo methodInfo = null; - if (assertion.Succeeded) + if (assertionChain.Succeeded) { methodInfo = Subject.GetMethod(name, parameterTypes); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(methodInfo is not null) .FailWith( @@ -1377,19 +1377,19 @@ public AndConstraint NotHaveProperty(string name, string because Guard.ThrowIfArgumentIsNullOrEmpty(name); Guard.ThrowIfArgumentIsNull(parameterTypes); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith( $"Expected method {{context:type}}.{name}({GetParameterString(parameterTypes)}) to not exist{{reason}}" + ", but {context:type} is ."); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { MethodInfo methodInfo = Subject.GetMethod(name, parameterTypes); var methodInfoDescription = MethodInfoAssertions.GetDescriptionFor(methodInfo); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(methodInfo is null) .FailWith( @@ -1417,7 +1417,7 @@ public AndConstraint NotHaveProperty(string name, string because { Guard.ThrowIfArgumentIsNull(parameterTypes); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith( @@ -1426,11 +1426,11 @@ public AndConstraint NotHaveProperty(string name, string because ConstructorInfo constructorInfo = null; - if (assertion.Succeeded) + if (assertionChain.Succeeded) { constructorInfo = Subject.GetConstructor(parameterTypes); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(constructorInfo is not null) .FailWith( @@ -1474,7 +1474,7 @@ public AndConstraint NotHaveProperty(string name, string because { Guard.ThrowIfArgumentIsNull(parameterTypes); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith( @@ -1483,11 +1483,11 @@ public AndConstraint NotHaveProperty(string name, string because ConstructorInfo constructorInfo = null; - if (assertion.Succeeded) + if (assertionChain.Succeeded) { constructorInfo = Subject.GetConstructor(parameterTypes); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(constructorInfo is null) .FailWith( @@ -1537,16 +1537,16 @@ private static string GetParameterString(IEnumerable parameterTypes) { Guard.ThrowIfArgumentIsOutOfRange(accessModifier); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith($"Expected {{context:type}} to be {accessModifier}{{reason}}, but {{context:type}} is ."); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { CSharpAccessModifier subjectAccessModifier = Subject.GetCSharpAccessModifier(); - assertion.ForCondition(accessModifier == subjectAccessModifier) + assertionChain.ForCondition(accessModifier == subjectAccessModifier) .BecauseOf(because, becauseArgs) .ForCondition(accessModifier == subjectAccessModifier) .FailWith( @@ -1575,16 +1575,16 @@ private static string GetParameterString(IEnumerable parameterTypes) { Guard.ThrowIfArgumentIsOutOfRange(accessModifier); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith($"Expected {{context:type}} not to be {accessModifier}{{reason}}, but {{context:type}} is ."); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { CSharpAccessModifier subjectAccessModifier = Subject.GetCSharpAccessModifier(); - assertion + assertionChain .ForCondition(accessModifier != subjectAccessModifier) .BecauseOf(because, becauseArgs) .ForCondition(accessModifier != subjectAccessModifier) @@ -1634,7 +1634,7 @@ private static string GetParameterString(IEnumerable parameterTypes) Guard.ThrowIfArgumentIsNull(sourceType); Guard.ThrowIfArgumentIsNull(targetType); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected public static implicit {0}({1}) to exist{reason}, but {context:type} is .", @@ -1642,11 +1642,11 @@ private static string GetParameterString(IEnumerable parameterTypes) MethodInfo methodInfo = null; - if (assertion.Succeeded) + if (assertionChain.Succeeded) { methodInfo = Subject.GetImplicitConversionOperator(sourceType, targetType); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(methodInfo is not null) .FailWith("Expected public static implicit {0}({1}) to exist{reason}, but it does not.", @@ -1696,17 +1696,17 @@ private static string GetParameterString(IEnumerable parameterTypes) Guard.ThrowIfArgumentIsNull(sourceType); Guard.ThrowIfArgumentIsNull(targetType); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected public static implicit {0}({1}) to not exist{reason}, but {context:type} is .", targetType, sourceType); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { MethodInfo methodInfo = Subject.GetImplicitConversionOperator(sourceType, targetType); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(methodInfo is null) .FailWith("Expected public static implicit {0}({1}) to not exist{reason}, but it does.", @@ -1756,7 +1756,7 @@ private static string GetParameterString(IEnumerable parameterTypes) Guard.ThrowIfArgumentIsNull(sourceType); Guard.ThrowIfArgumentIsNull(targetType); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected public static explicit {0}({1}) to exist{reason}, but {context:type} is .", @@ -1764,11 +1764,11 @@ private static string GetParameterString(IEnumerable parameterTypes) MethodInfo methodInfo = null; - if (assertion.Succeeded) + if (assertionChain.Succeeded) { methodInfo = Subject.GetExplicitConversionOperator(sourceType, targetType); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(methodInfo is not null) .FailWith("Expected public static explicit {0}({1}) to exist{reason}, but it does not.", @@ -1818,17 +1818,17 @@ private static string GetParameterString(IEnumerable parameterTypes) Guard.ThrowIfArgumentIsNull(sourceType); Guard.ThrowIfArgumentIsNull(targetType); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected public static explicit {0}({1}) to not exist{reason}, but {context:type} is .", targetType, sourceType); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { MethodInfo methodInfo = Subject.GetExplicitConversionOperator(sourceType, targetType); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(methodInfo is null) .FailWith("Expected public static explicit {0}({1}) to not exist{reason}, but it does.", diff --git a/Src/FluentAssertions/Types/TypeSelectorAssertions.cs b/Src/FluentAssertions/Types/TypeSelectorAssertions.cs index 3a02e4f890..5bbe484a44 100644 --- a/Src/FluentAssertions/Types/TypeSelectorAssertions.cs +++ b/Src/FluentAssertions/Types/TypeSelectorAssertions.cs @@ -17,15 +17,15 @@ namespace FluentAssertions.Types; [DebuggerNonUserCode] public class TypeSelectorAssertions { - private readonly Assertion assertion; + private readonly AssertionChain assertionChain; /// /// Initializes a new instance of the class. /// /// is or contains . - public TypeSelectorAssertions(Assertion assertion, params Type[] types) + public TypeSelectorAssertions(AssertionChain assertionChain, params Type[] types) { - this.assertion = assertion; + this.assertionChain = assertionChain; Guard.ThrowIfArgumentIsNull(types); Guard.ThrowIfArgumentContainsNull(types); @@ -54,7 +54,7 @@ public AndConstraint BeDecoratedWith(string .Where(type => !type.IsDecoratedWith()) .ToArray(); - assertion + assertionChain .ForCondition(typesWithoutAttribute.Length == 0) .BecauseOf(because, becauseArgs) .FailWith("Expected all types to be decorated with {0}{reason}," + @@ -90,7 +90,7 @@ public AndConstraint BeDecoratedWith(string .Where(type => !type.IsDecoratedWith(isMatchingAttributePredicate)) .ToArray(); - assertion + assertionChain .ForCondition(typesWithoutMatchingAttribute.Length == 0) .BecauseOf(because, becauseArgs) .FailWith("Expected all types to be decorated with {0} that matches {1}{reason}," + @@ -120,7 +120,7 @@ public AndConstraint BeDecoratedWith(string .Where(type => !type.IsDecoratedWithOrInherit()) .ToArray(); - assertion + assertionChain .ForCondition(typesWithoutAttribute.Length == 0) .BecauseOf(because, becauseArgs) .FailWith("Expected all types to be decorated with or inherit {0}{reason}," + @@ -156,7 +156,7 @@ public AndConstraint BeDecoratedWith(string .Where(type => !type.IsDecoratedWithOrInherit(isMatchingAttributePredicate)) .ToArray(); - assertion + assertionChain .ForCondition(typesWithoutMatchingAttribute.Length == 0) .BecauseOf(because, becauseArgs) .FailWith("Expected all types to be decorated with or inherit {0} that matches {1}{reason}," + @@ -185,7 +185,7 @@ public AndConstraint NotBeDecoratedWith(stri .Where(type => type.IsDecoratedWith()) .ToArray(); - assertion + assertionChain .ForCondition(typesWithAttribute.Length == 0) .BecauseOf(because, becauseArgs) .FailWith("Expected all types to not be decorated with {0}{reason}," + @@ -221,7 +221,7 @@ public AndConstraint NotBeDecoratedWith(stri .Where(type => type.IsDecoratedWith(isMatchingAttributePredicate)) .ToArray(); - assertion + assertionChain .ForCondition(typesWithMatchingAttribute.Length == 0) .BecauseOf(because, becauseArgs) .FailWith("Expected all types to not be decorated with {0} that matches {1}{reason}," + @@ -251,7 +251,7 @@ public AndConstraint NotBeDecoratedWith(stri .Where(type => type.IsDecoratedWithOrInherit()) .ToArray(); - assertion + assertionChain .ForCondition(typesWithAttribute.Length == 0) .BecauseOf(because, becauseArgs) .FailWith("Expected all types to not be decorated with or inherit {0}{reason}," + @@ -287,7 +287,7 @@ public AndConstraint NotBeDecoratedWith(stri .Where(type => type.IsDecoratedWithOrInherit(isMatchingAttributePredicate)) .ToArray(); - assertion + assertionChain .ForCondition(typesWithMatchingAttribute.Length == 0) .BecauseOf(because, becauseArgs) .FailWith("Expected all types to not be decorated with or inherit {0} that matches {1}{reason}," + @@ -313,7 +313,7 @@ public AndConstraint BeSealed(string because = "", param { var notSealedTypes = Subject.Where(type => !type.IsCSharpSealed()).ToArray(); - assertion.ForCondition(notSealedTypes.Length == 0) + assertionChain.ForCondition(notSealedTypes.Length == 0) .BecauseOf(because, becauseArgs) .FailWith("Expected all types to be sealed{reason}, but the following types are not:" + Environment.NewLine + "{0}.", GetDescriptionsFor(notSealedTypes)); @@ -335,7 +335,7 @@ public AndConstraint NotBeSealed(string because = "", pa { var sealedTypes = Subject.Where(type => type.IsCSharpSealed()).ToArray(); - assertion.ForCondition(sealedTypes.Length == 0) + assertionChain.ForCondition(sealedTypes.Length == 0) .BecauseOf(because, becauseArgs) .FailWith("Expected all types not to be sealed{reason}, but the following types are:" + Environment.NewLine + "{0}.", GetDescriptionsFor(sealedTypes)); @@ -363,7 +363,7 @@ public AndConstraint NotBeSealed(string because = "", pa .Where(t => t.Namespace != @namespace) .ToArray(); - assertion + assertionChain .ForCondition(typesNotInNamespace.Length == 0) .BecauseOf(because, becauseArgs) .FailWith("Expected all types to be in namespace {0}{reason}," + @@ -394,7 +394,7 @@ public AndConstraint NotBeSealed(string because = "", pa .Where(t => t.Namespace == @namespace) .ToArray(); - assertion + assertionChain .ForCondition(typesInNamespace.Length == 0) .BecauseOf(because, becauseArgs) .FailWith("Expected no types to be in namespace {0}{reason}," + @@ -425,7 +425,7 @@ public AndConstraint NotBeSealed(string because = "", pa .Where(t => !t.IsUnderNamespace(@namespace)) .ToArray(); - assertion + assertionChain .ForCondition(typesNotUnderNamespace.Length == 0) .BecauseOf(because, becauseArgs) .FailWith("Expected the namespaces of all types to start with {0}{reason}," + @@ -457,7 +457,7 @@ public AndConstraint NotBeSealed(string because = "", pa .Where(t => t.IsUnderNamespace(@namespace)) .ToArray(); - assertion + assertionChain .ForCondition(typesUnderNamespace.Length == 0) .BecauseOf(because, becauseArgs) .FailWith("Expected the namespaces of all types to not start with {0}{reason}," + diff --git a/Src/FluentAssertions/WhichResult.cs b/Src/FluentAssertions/WhichResult.cs index 7b52747e6c..13273a1e6b 100644 --- a/Src/FluentAssertions/WhichResult.cs +++ b/Src/FluentAssertions/WhichResult.cs @@ -4,13 +4,13 @@ namespace FluentAssertions; public class WhichResult { - public WhichResult(T matchedElement, Assertion assertion) + public WhichResult(T matchedElement, AssertionChain assertionChain) { MatchedElement = matchedElement; - Assertion = assertion; + AssertionChain = assertionChain; } public T MatchedElement { get; } - public Assertion Assertion { get; } + public AssertionChain AssertionChain { get; } } diff --git a/Src/FluentAssertions/Xml/Equivalency/XmlReaderValidator.cs b/Src/FluentAssertions/Xml/Equivalency/XmlReaderValidator.cs index 6bd0b478f2..b82b4bba6f 100644 --- a/Src/FluentAssertions/Xml/Equivalency/XmlReaderValidator.cs +++ b/Src/FluentAssertions/Xml/Equivalency/XmlReaderValidator.cs @@ -8,16 +8,17 @@ namespace FluentAssertions.Xml.Equivalency; internal class XmlReaderValidator { - private readonly AssertionScope assertion; + private readonly AssertionChain assertionChain; private readonly XmlReader subjectReader; private readonly XmlReader expectationReader; private XmlIterator subjectIterator; private XmlIterator expectationIterator; private Node currentNode = Node.CreateRoot(); - public XmlReaderValidator(XmlReader subjectReader, XmlReader expectationReader, string because, object[] becauseArgs) + public XmlReaderValidator(AssertionChain assertionChain, XmlReader subjectReader, XmlReader expectationReader, string because, object[] becauseArgs) { - assertion = assertion.BecauseOf(because, becauseArgs); + this.assertionChain = assertionChain; + assertionChain.BecauseOf(because, becauseArgs); this.subjectReader = subjectReader; this.expectationReader = expectationReader; @@ -29,12 +30,12 @@ public void Validate(bool shouldBeEquivalent) if (shouldBeEquivalent && failure is not null) { - assertion.FailWith(failure.FormatString, failure.FormatParams); + assertionChain.FailWith(failure.FormatString, failure.FormatParams); } if (!shouldBeEquivalent && failure is null) { - assertion.FailWith("Did not expect {context:subject} to be equivalent{reason}, but it is."); + assertionChain.FailWith("Did not expect {context:subject} to be equivalent{reason}, but it is."); } } diff --git a/Src/FluentAssertions/Xml/XAttributeAssertions.cs b/Src/FluentAssertions/Xml/XAttributeAssertions.cs index 422aa4d87f..1f430deaa0 100644 --- a/Src/FluentAssertions/Xml/XAttributeAssertions.cs +++ b/Src/FluentAssertions/Xml/XAttributeAssertions.cs @@ -11,15 +11,15 @@ namespace FluentAssertions.Xml; [DebuggerNonUserCode] public class XAttributeAssertions : ReferenceTypeAssertions { - private readonly Assertion assertion; + private readonly AssertionChain assertionChain; /// /// Initializes a new instance of the class. /// - public XAttributeAssertions(XAttribute attribute, Assertion assertion) - : base(attribute, assertion) + public XAttributeAssertions(XAttribute attribute, AssertionChain assertionChain) + : base(attribute, assertionChain) { - this.assertion = assertion; + this.assertionChain = assertionChain; } /// @@ -35,7 +35,7 @@ public XAttributeAssertions(XAttribute attribute, Assertion assertion) /// public AndConstraint Be(XAttribute expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject?.Name == expected?.Name && Subject?.Value == expected?.Value) .BecauseOf(because, becauseArgs) .FailWith("Expected {context} to be {0}{reason}, but found {1}.", expected, Subject); @@ -57,7 +57,7 @@ public AndConstraint Be(XAttribute expected, string becaus /// public AndConstraint NotBe(XAttribute unexpected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(!(Subject?.Name == unexpected?.Name && Subject?.Value == unexpected?.Value)) .BecauseOf(because, becauseArgs) .FailWith("Did not expect {context} to be {0}{reason}.", unexpected); @@ -78,14 +78,14 @@ public AndConstraint NotBe(XAttribute unexpected, string b /// public AndConstraint HaveValue(string expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected the attribute to have value {0}{reason}, but {context:member} is .", expected); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { - assertion + assertionChain .ForCondition(Subject!.Value == expected) .BecauseOf(because, becauseArgs) .FailWith("Expected {context} \"{0}\" to have value {1}{reason}, but found {2}.", diff --git a/Src/FluentAssertions/Xml/XDocumentAssertions.cs b/Src/FluentAssertions/Xml/XDocumentAssertions.cs index 84a5901c23..d53857d38e 100644 --- a/Src/FluentAssertions/Xml/XDocumentAssertions.cs +++ b/Src/FluentAssertions/Xml/XDocumentAssertions.cs @@ -17,15 +17,15 @@ namespace FluentAssertions.Xml; [DebuggerNonUserCode] public class XDocumentAssertions : ReferenceTypeAssertions { - private readonly Assertion assertion; + private readonly AssertionChain assertionChain; /// /// Initializes a new instance of the class. /// - public XDocumentAssertions(XDocument document, Assertion assertion) - : base(document, assertion) + public XDocumentAssertions(XDocument document, AssertionChain assertionChain) + : base(document, assertionChain) { - this.assertion = assertion; + this.assertionChain = assertionChain; } /// @@ -42,7 +42,7 @@ public XDocumentAssertions(XDocument document, Assertion assertion) /// public AndConstraint Be(XDocument expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Equals(Subject, expected)) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:subject} to be {0}{reason}, but found {1}.", expected, Subject); @@ -64,7 +64,7 @@ public AndConstraint Be(XDocument expected, string because /// public AndConstraint NotBe(XDocument unexpected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(!Equals(Subject, unexpected)) .FailWith("Did not expect {context:subject} to be {0}{reason}.", unexpected); @@ -89,7 +89,7 @@ public AndConstraint BeEquivalentTo(XDocument expected, str using (XmlReader subjectReader = Subject?.CreateReader()) using (XmlReader otherReader = expected?.CreateReader()) { - var xmlReaderValidator = new XmlReaderValidator(subjectReader, otherReader, because, becauseArgs); + var xmlReaderValidator = new XmlReaderValidator(assertionChain, subjectReader, otherReader, because, becauseArgs); xmlReaderValidator.Validate(shouldBeEquivalent: true); } @@ -114,7 +114,7 @@ public AndConstraint BeEquivalentTo(XDocument expected, str using (XmlReader subjectReader = Subject?.CreateReader()) using (XmlReader otherReader = unexpected?.CreateReader()) { - var xmlReaderValidator = new XmlReaderValidator(subjectReader, otherReader, because, becauseArgs); + var xmlReaderValidator = new XmlReaderValidator(assertionChain, subjectReader, otherReader, because, becauseArgs); xmlReaderValidator.Validate(shouldBeEquivalent: false); } @@ -170,7 +170,7 @@ public AndConstraint BeEquivalentTo(XDocument expected, str XElement root = Subject.Root; - assertion + assertionChain .ForCondition(root is not null && root.Name == expected) .BecauseOf(because, becauseArgs) .FailWith( @@ -257,7 +257,7 @@ public AndConstraint BeEquivalentTo(XDocument expected, str Guard.ThrowIfArgumentIsNull(expected, nameof(expected), "Cannot assert the document has an element if the expected name is ."); - assertion + assertionChain .ForCondition(Subject.Root is not null) .BecauseOf(because, becauseArgs) .FailWith( @@ -266,11 +266,11 @@ public AndConstraint BeEquivalentTo(XDocument expected, str XElement xElement = null; - if (assertion.Succeeded) + if (assertionChain.Succeeded) { xElement = Subject.Root!.Element(expected); - assertion + assertionChain .ForCondition(xElement is not null) .BecauseOf(because, becauseArgs) .FailWith( @@ -306,30 +306,30 @@ public AndConstraint BeEquivalentTo(XDocument expected, str Guard.ThrowIfArgumentIsNull(expected, nameof(expected), "Cannot assert the document has an element count if the element name is ."); - assertion + assertionChain .ForCondition(Subject is not null) .BecauseOf(because, becauseArgs) .FailWith("Cannot assert the count if the document itself is ."); IEnumerable xElements = []; - if (assertion.Succeeded) + if (assertionChain.Succeeded) { var root = Subject!.Root; - assertion + assertionChain .ForCondition(root is not null) .BecauseOf(because, becauseArgs) .FailWith( "Expected {context:subject} to have root element containing a child {0}{reason}, but it has no root element.", expected.ToString()); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { xElements = root!.Elements(expected); int actual = xElements.Count(); - assertion + assertionChain .ForConstraint(occurrenceConstraint, actual) .BecauseOf(because, becauseArgs) .FailWith( diff --git a/Src/FluentAssertions/Xml/XElementAssertions.cs b/Src/FluentAssertions/Xml/XElementAssertions.cs index 8698f93804..b2e00d0702 100644 --- a/Src/FluentAssertions/Xml/XElementAssertions.cs +++ b/Src/FluentAssertions/Xml/XElementAssertions.cs @@ -17,15 +17,15 @@ namespace FluentAssertions.Xml; [DebuggerNonUserCode] public class XElementAssertions : ReferenceTypeAssertions { - private readonly Assertion assertion; + private readonly AssertionChain assertionChain; /// /// Initializes a new instance of the class. /// - public XElementAssertions(XElement xElement, Assertion assertion) - : base(xElement, assertion) + public XElementAssertions(XElement xElement, AssertionChain assertionChain) + : base(xElement, assertionChain) { - this.assertion = assertion; + this.assertionChain = assertionChain; } /// @@ -43,7 +43,7 @@ public XElementAssertions(XElement xElement, Assertion assertion) /// public AndConstraint Be(XElement expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(XNode.DeepEquals(Subject, expected)) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:subject} to be {0}{reason}, but found {1}.", expected, Subject); @@ -66,7 +66,7 @@ public AndConstraint Be(XElement expected, string because = /// public AndConstraint NotBe(XElement unexpected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition((Subject is null && unexpected is not null) || !XNode.DeepEquals(Subject, unexpected)) .BecauseOf(because, becauseArgs) .FailWith("Did not expect {context:subject} to be {0}{reason}.", unexpected); @@ -93,7 +93,7 @@ public AndConstraint NotBe(XElement unexpected, string becau using (XmlReader subjectReader = Subject?.CreateReader()) using (XmlReader expectedReader = expected?.CreateReader()) { - var xmlReaderValidator = new XmlReaderValidator(subjectReader, expectedReader, because, becauseArgs); + var xmlReaderValidator = new XmlReaderValidator(assertionChain, subjectReader, expectedReader, because, becauseArgs); xmlReaderValidator.Validate(shouldBeEquivalent: true); } @@ -119,7 +119,7 @@ public AndConstraint NotBe(XElement unexpected, string becau using (XmlReader subjectReader = Subject?.CreateReader()) using (XmlReader otherReader = unexpected?.CreateReader()) { - var xmlReaderValidator = new XmlReaderValidator(subjectReader, otherReader, because, becauseArgs); + var xmlReaderValidator = new XmlReaderValidator(assertionChain, subjectReader, otherReader, because, becauseArgs); xmlReaderValidator.Validate(shouldBeEquivalent: false); } @@ -139,14 +139,14 @@ public AndConstraint NotBe(XElement unexpected, string becau /// public AndConstraint HaveValue(string expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith("Expected the element to have value {0}{reason}, but {context:member} is .", expected); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { - assertion + assertionChain .ForCondition(Subject!.Value == expected) .BecauseOf(because, becauseArgs) .FailWith( @@ -201,18 +201,18 @@ public AndConstraint HaveValue(string expected, string becau string expectedText = expectedName.ToString(); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith( "Expected attribute {0} in element to have value {1}{reason}, but {context:member} is .", expectedText, expectedValue); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { XAttribute attribute = Subject!.Attribute(expectedName); - assertion + assertionChain .ForCondition(attribute is not null) .BecauseOf(because, becauseArgs) .FailWith( @@ -220,9 +220,9 @@ public AndConstraint HaveValue(string expected, string becau + " but found no such attribute in {2}", expectedText, expectedValue, Subject); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { - assertion + assertionChain .ForCondition(attribute!.Value == expectedValue) .BecauseOf(because, becauseArgs) .FailWith( @@ -274,7 +274,7 @@ public AndConstraint HaveValue(string expected, string becau { Guard.ThrowIfArgumentIsNull(expected); - assertion + assertionChain .BecauseOf(because, becauseArgs) .ForCondition(Subject is not null) .FailWith( @@ -283,11 +283,11 @@ public AndConstraint HaveValue(string expected, string becau XElement xElement = null; - if (assertion.Succeeded) + if (assertionChain.Succeeded) { xElement = Subject!.Element(expected); - assertion + assertionChain .ForCondition(xElement is not null) .BecauseOf(because, becauseArgs) .FailWith( @@ -323,7 +323,7 @@ public AndConstraint HaveValue(string expected, string becau Guard.ThrowIfArgumentIsNull(expected, nameof(expected), "Cannot assert the element has an element count if the element name is ."); - assertion + assertionChain .ForCondition(Subject is not null) .BecauseOf(because, becauseArgs) .FailWith( @@ -332,12 +332,12 @@ public AndConstraint HaveValue(string expected, string becau IEnumerable xElements = []; - if (assertion.Succeeded) + if (assertionChain.Succeeded) { xElements = Subject!.Elements(expected); int actual = xElements.Count(); - assertion + assertionChain .ForConstraint(occurrenceConstraint, actual) .BecauseOf(because, becauseArgs) .FailWith( diff --git a/Src/FluentAssertions/Xml/XmlElementAssertions.cs b/Src/FluentAssertions/Xml/XmlElementAssertions.cs index 5789765244..135775155d 100644 --- a/Src/FluentAssertions/Xml/XmlElementAssertions.cs +++ b/Src/FluentAssertions/Xml/XmlElementAssertions.cs @@ -12,16 +12,16 @@ namespace FluentAssertions.Xml; [DebuggerNonUserCode] public class XmlElementAssertions : XmlNodeAssertions { - private readonly Assertion assertion; + private readonly AssertionChain assertionChain; /// /// Initializes a new instance of the class. /// /// - public XmlElementAssertions(XmlElement xmlElement, Assertion assertion) - : base(xmlElement, assertion) + public XmlElementAssertions(XmlElement xmlElement, AssertionChain assertionChain) + : base(xmlElement, assertionChain) { - this.assertion = assertion; + this.assertionChain = assertionChain; } /// @@ -39,7 +39,7 @@ public XmlElementAssertions(XmlElement xmlElement, Assertion assertion) public AndConstraint HaveInnerText(string expected, string because = "", params object[] becauseArgs) { - assertion + assertionChain .ForCondition(Subject.InnerText == expected) .BecauseOf(because, becauseArgs) .FailWith( @@ -96,7 +96,7 @@ public XmlElementAssertions(XmlElement xmlElement, Assertion assertion) (string.IsNullOrEmpty(expectedNamespace) ? string.Empty : $"{{{expectedNamespace}}}") + expectedName; - assertion + assertionChain .ForCondition(attribute is not null) .BecauseOf(because, becauseArgs) .FailWith( @@ -104,9 +104,9 @@ public XmlElementAssertions(XmlElement xmlElement, Assertion assertion) + " with value {1}{reason}, but found no such attribute in {2}", expectedFormattedName, expectedValue, Subject); - if (assertion.Succeeded) + if (assertionChain.Succeeded) { - assertion + assertionChain .ForCondition(attribute!.Value == expectedValue) .BecauseOf(because, becauseArgs) .FailWith( @@ -162,7 +162,7 @@ public XmlElementAssertions(XmlElement xmlElement, Assertion assertion) (string.IsNullOrEmpty(expectedNamespace) ? string.Empty : $"{{{expectedNamespace}}}") + expectedName; - assertion + assertionChain .ForCondition(element is not null) .BecauseOf(because, becauseArgs) .FailWith( diff --git a/Src/FluentAssertions/Xml/XmlNodeAssertions.cs b/Src/FluentAssertions/Xml/XmlNodeAssertions.cs index 0dd896577d..d386aac982 100644 --- a/Src/FluentAssertions/Xml/XmlNodeAssertions.cs +++ b/Src/FluentAssertions/Xml/XmlNodeAssertions.cs @@ -12,8 +12,8 @@ namespace FluentAssertions.Xml; [DebuggerNonUserCode] public class XmlNodeAssertions : XmlNodeAssertions { - public XmlNodeAssertions(XmlNode xmlNode, Assertion assertion) - : base(xmlNode, assertion) + public XmlNodeAssertions(XmlNode xmlNode, AssertionChain assertionChain) + : base(xmlNode, assertionChain) { } } @@ -26,9 +26,12 @@ public class XmlNodeAssertions : ReferenceTypeAssertions< where TSubject : XmlNode where TAssertions : XmlNodeAssertions { - public XmlNodeAssertions(TSubject xmlNode, Assertion assertion) - : base(xmlNode, assertion) + private readonly AssertionChain assertionChain; + + public XmlNodeAssertions(TSubject xmlNode, AssertionChain assertionChain) + : base(xmlNode, assertionChain) { + this.assertionChain = assertionChain; } /// @@ -47,7 +50,7 @@ public AndConstraint BeEquivalentTo(XmlNode expected, string becaus using (var subjectReader = new XmlNodeReader(Subject)) using (var expectedReader = new XmlNodeReader(expected)) { - var xmlReaderValidator = new XmlReaderValidator(subjectReader, expectedReader, because, becauseArgs); + var xmlReaderValidator = new XmlReaderValidator(assertionChain, subjectReader, expectedReader, because, becauseArgs); xmlReaderValidator.Validate(shouldBeEquivalent: true); } @@ -71,7 +74,7 @@ public AndConstraint NotBeEquivalentTo(XmlNode unexpected, string b using (var subjectReader = new XmlNodeReader(Subject)) using (var unexpectedReader = new XmlNodeReader(unexpected)) { - var xmlReaderValidator = new XmlReaderValidator(subjectReader, unexpectedReader, because, becauseArgs); + var xmlReaderValidator = new XmlReaderValidator(assertionChain, subjectReader, unexpectedReader, because, becauseArgs); xmlReaderValidator.Validate(shouldBeEquivalent: false); } diff --git a/Src/FluentAssertions/XmlAssertionExtensions.cs b/Src/FluentAssertions/XmlAssertionExtensions.cs index 85f63377ce..c51fd3022a 100644 --- a/Src/FluentAssertions/XmlAssertionExtensions.cs +++ b/Src/FluentAssertions/XmlAssertionExtensions.cs @@ -10,13 +10,11 @@ public static class XmlAssertionExtensions { public static XmlNodeAssertions Should(this XmlNode actualValue) { - return new XmlNodeAssertions(actualValue, Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + return new XmlNodeAssertions(actualValue, AssertionChain.GetOrCreate()); } public static XmlElementAssertions Should(this XmlElement actualValue) { - return new XmlElementAssertions(actualValue, Assertion.GetOrCreate(() => AssertionScope.Current, - () => AssertionScope.Current.GetIdentifier())); + return new XmlElementAssertions(actualValue, AssertionChain.GetOrCreate()); } } diff --git a/Tests/Benchmarks/UsersOfGetClosedGenericInterfaces.cs b/Tests/Benchmarks/UsersOfGetClosedGenericInterfaces.cs index 8f8db45803..542926ff4c 100644 --- a/Tests/Benchmarks/UsersOfGetClosedGenericInterfaces.cs +++ b/Tests/Benchmarks/UsersOfGetClosedGenericInterfaces.cs @@ -152,7 +152,7 @@ public void GenericDictionaryEquivalencyStep_CanHandle() { for (int i = 0; i < values.Length; i++) { - dictionaryStep.Handle(new Comparands(values[i], values[0], typeof(object)), Assertion.GetOrCreate(), context, null); + dictionaryStep.Handle(new Comparands(values[i], values[0], typeof(object)), AssertionChain.GetOrCreate(), context, null); } } @@ -161,7 +161,7 @@ public void GenericEnumerableEquivalencyStep_CanHandle() { for (int i = 0; i < values.Length; i++) { - enumerableStep.Handle(new Comparands(values[i], values[0], typeof(object)), Assertion.GetOrCreate(), context, null); + enumerableStep.Handle(new Comparands(values[i], values[0], typeof(object)), AssertionChain.GetOrCreate(), context, null); } } } diff --git a/Tests/FluentAssertions.Equivalency.Specs/ExtensibilitySpecs.cs b/Tests/FluentAssertions.Equivalency.Specs/ExtensibilitySpecs.cs index 109f83d823..74d60975e6 100644 --- a/Tests/FluentAssertions.Equivalency.Specs/ExtensibilitySpecs.cs +++ b/Tests/FluentAssertions.Equivalency.Specs/ExtensibilitySpecs.cs @@ -142,7 +142,7 @@ public void When_a_matching_rule_is_added_it_should_appear_in_the_exception_mess internal class ForeignKeyMatchingRule : IMemberMatchingRule { public IMember Match(IMember expectedMember, object subject, INode parent, IEquivalencyOptions options, - Assertion assertion) + AssertionChain assertionChain) { string name = expectedMember.Name; @@ -627,7 +627,7 @@ public void When_multiple_steps_are_added_they_should_be_evaluated_first_to_last private class AlwaysFailOnDateTimesEquivalencyStep : IEquivalencyStep { - public EquivalencyResult Handle(Comparands comparands, Assertion assertion, IEquivalencyValidationContext context, + public EquivalencyResult Handle(Comparands comparands, AssertionChain assertionChain, IEquivalencyValidationContext context, IValidateChildNodeEquivalency nestedValidator) { if (comparands.Expectation is DateTime) @@ -641,7 +641,7 @@ private class AlwaysFailOnDateTimesEquivalencyStep : IEquivalencyStep private class RelaxingDateTimeEquivalencyStep : IEquivalencyStep { - public EquivalencyResult Handle(Comparands comparands, Assertion assertion, IEquivalencyValidationContext context, + public EquivalencyResult Handle(Comparands comparands, AssertionChain assertionChain, IEquivalencyValidationContext context, IValidateChildNodeEquivalency nestedValidator) { if (comparands.Expectation is DateTime time) @@ -812,7 +812,7 @@ public void When_multiple_equivalency_steps_are_added_they_should_be_executed_in private class ThrowExceptionEquivalencyStep : IEquivalencyStep where TException : Exception, new() { - public EquivalencyResult Handle(Comparands comparands, Assertion assertion, IEquivalencyValidationContext context, + public EquivalencyResult Handle(Comparands comparands, AssertionChain assertionChain, IEquivalencyValidationContext context, IValidateChildNodeEquivalency nestedValidator) { throw new TException(); @@ -821,7 +821,7 @@ private class ThrowExceptionEquivalencyStep : IEquivalencyStep private class AlwaysHandleEquivalencyStep : IEquivalencyStep { - public EquivalencyResult Handle(Comparands comparands, Assertion assertion, IEquivalencyValidationContext context, + public EquivalencyResult Handle(Comparands comparands, AssertionChain assertionChain, IEquivalencyValidationContext context, IValidateChildNodeEquivalency nestedValidator) { return EquivalencyResult.EquivalencyProven; @@ -830,7 +830,7 @@ private class AlwaysHandleEquivalencyStep : IEquivalencyStep private class NeverHandleEquivalencyStep : IEquivalencyStep { - public EquivalencyResult Handle(Comparands comparands, Assertion assertion, IEquivalencyValidationContext context, + public EquivalencyResult Handle(Comparands comparands, AssertionChain assertionChain, IEquivalencyValidationContext context, IValidateChildNodeEquivalency nestedValidator) { return EquivalencyResult.ContinueWithNext; @@ -839,7 +839,7 @@ private class NeverHandleEquivalencyStep : IEquivalencyStep private class EqualityEquivalencyStep : IEquivalencyStep { - public EquivalencyResult Handle(Comparands comparands, Assertion assertion, IEquivalencyValidationContext context, + public EquivalencyResult Handle(Comparands comparands, AssertionChain assertionChain, IEquivalencyValidationContext context, IValidateChildNodeEquivalency nestedValidator) { comparands.Subject.Should().Be(comparands.Expectation, context.Reason.FormattedMessage, context.Reason.Arguments); @@ -856,7 +856,7 @@ public DoEquivalencyStep(Action doAction) this.doAction = doAction; } - public EquivalencyResult Handle(Comparands comparands, Assertion assertion, IEquivalencyValidationContext context, + public EquivalencyResult Handle(Comparands comparands, AssertionChain assertionChain, IEquivalencyValidationContext context, IValidateChildNodeEquivalency nestedValidator) { doAction(); diff --git a/Tests/FluentAssertions.Specs/AssertionExtensions.cs b/Tests/FluentAssertions.Specs/AssertionExtensions.cs index ac45fd66f8..add27b751a 100644 --- a/Tests/FluentAssertions.Specs/AssertionExtensions.cs +++ b/Tests/FluentAssertions.Specs/AssertionExtensions.cs @@ -12,33 +12,33 @@ internal static class AssertionExtensions public static NonGenericAsyncFunctionAssertions Should(this Func action, IClock clock) { - return new NonGenericAsyncFunctionAssertions(action, Extractor, Assertion.GetOrCreate(), clock); + return new NonGenericAsyncFunctionAssertions(action, Extractor, AssertionChain.GetOrCreate(), clock); } public static GenericAsyncFunctionAssertions Should(this Func> action, IClock clock) { - return new GenericAsyncFunctionAssertions(action, Extractor, Assertion.GetOrCreate(), clock); + return new GenericAsyncFunctionAssertions(action, Extractor, AssertionChain.GetOrCreate(), clock); } public static ActionAssertions Should(this Action action, IClock clock) { - return new ActionAssertions(action, Extractor, Assertion.GetOrCreate(), clock); + return new ActionAssertions(action, Extractor, AssertionChain.GetOrCreate(), clock); } public static FunctionAssertions Should(this Func func, IClock clock) { - return new FunctionAssertions(func, Extractor, Assertion.GetOrCreate(), clock); + return new FunctionAssertions(func, Extractor, AssertionChain.GetOrCreate(), clock); } public static TaskCompletionSourceAssertions Should(this TaskCompletionSource tcs, IClock clock) { - return new TaskCompletionSourceAssertions(tcs, Assertion.GetOrCreate(), clock); + return new TaskCompletionSourceAssertions(tcs, AssertionChain.GetOrCreate(), clock); } #if NET6_0_OR_GREATER public static TaskCompletionSourceAssertions Should(this TaskCompletionSource tcs, IClock clock) { - return new TaskCompletionSourceAssertions(tcs, Assertion.GetOrCreate(), clock); + return new TaskCompletionSourceAssertions(tcs, AssertionChain.GetOrCreate(), clock); } #endif diff --git a/Tests/FluentAssertions.Specs/AssertionExtensionsSpecs.cs b/Tests/FluentAssertions.Specs/AssertionExtensionsSpecs.cs index b3b5d9ba90..c8e75947f1 100644 --- a/Tests/FluentAssertions.Specs/AssertionExtensionsSpecs.cs +++ b/Tests/FluentAssertions.Specs/AssertionExtensionsSpecs.cs @@ -40,24 +40,24 @@ private static bool OverridesEquals(Type t) public static TheoryData ClassesWithGuardEquals => new() { - new ObjectAssertions(default, Assertion.GetOrCreate()), - new BooleanAssertions(default, Assertion.GetOrCreate()), - new DateTimeAssertions(default, Assertion.GetOrCreate()), - new DateTimeRangeAssertions(default, Assertion.GetOrCreate(), default, default, default), - new DateTimeOffsetAssertions(default, Assertion.GetOrCreate()), - new DateTimeOffsetRangeAssertions(default, Assertion.GetOrCreate(), default, default, default), - new ExecutionTimeAssertions(new ExecutionTime(() => { }, () => new StopwatchTimer()), Assertion.GetOrCreate()), - new GuidAssertions(default, Assertion.GetOrCreate()), - new MethodInfoSelectorAssertions(Assertion.GetOrCreate()), - new NumericAssertions>(default, Assertion.GetOrCreate()), - new PropertyInfoSelectorAssertions(Assertion.GetOrCreate()), - new SimpleTimeSpanAssertions(default, Assertion.GetOrCreate()), - new TaskCompletionSourceAssertions(default, Assertion.GetOrCreate()), - new TypeSelectorAssertions(Assertion.GetOrCreate()), - new EnumAssertions>(default, Assertion.GetOrCreate()), + new ObjectAssertions(default, AssertionChain.GetOrCreate()), + new BooleanAssertions(default, AssertionChain.GetOrCreate()), + new DateTimeAssertions(default, AssertionChain.GetOrCreate()), + new DateTimeRangeAssertions(default, AssertionChain.GetOrCreate(), default, default, default), + new DateTimeOffsetAssertions(default, AssertionChain.GetOrCreate()), + new DateTimeOffsetRangeAssertions(default, AssertionChain.GetOrCreate(), default, default, default), + new ExecutionTimeAssertions(new ExecutionTime(() => { }, () => new StopwatchTimer()), AssertionChain.GetOrCreate()), + new GuidAssertions(default, AssertionChain.GetOrCreate()), + new MethodInfoSelectorAssertions(AssertionChain.GetOrCreate()), + new NumericAssertions>(default, AssertionChain.GetOrCreate()), + new PropertyInfoSelectorAssertions(AssertionChain.GetOrCreate()), + new SimpleTimeSpanAssertions(default, AssertionChain.GetOrCreate()), + new TaskCompletionSourceAssertions(default, AssertionChain.GetOrCreate()), + new TypeSelectorAssertions(AssertionChain.GetOrCreate()), + new EnumAssertions>(default, AssertionChain.GetOrCreate()), #if NET6_0_OR_GREATER - new DateOnlyAssertions(default, Assertion.GetOrCreate()), - new TimeOnlyAssertions(default, Assertion.GetOrCreate()), + new DateOnlyAssertions(default, AssertionChain.GetOrCreate()), + new TimeOnlyAssertions(default, AssertionChain.GetOrCreate()), #endif }; diff --git a/Tests/FluentAssertions.Specs/AssertionFailureSpecs.cs b/Tests/FluentAssertions.Specs/AssertionFailureSpecs.cs index e37491cd8b..ea98193f28 100644 --- a/Tests/FluentAssertions.Specs/AssertionFailureSpecs.cs +++ b/Tests/FluentAssertions.Specs/AssertionFailureSpecs.cs @@ -72,16 +72,16 @@ public void When_reason_does_not_start_with_because_but_is_prefixed_with_blanks_ internal class AssertionsTestSubClass : ReferenceTypeAssertions { - private static readonly Assertion Assertion = Assertion.GetOrCreate(); + private static readonly AssertionChain AssertionChain = AssertionChain.GetOrCreate(); public AssertionsTestSubClass() - : base(null, Assertion) + : base(null, AssertionChain) { } public void AssertFail(string because, params object[] becauseArgs) { - Assertion + AssertionChain .BecauseOf(because, becauseArgs) .FailWith("Expected it to fail{reason}"); } diff --git a/Tests/FluentAssertions.Specs/AssertionOptionsSpecs.cs b/Tests/FluentAssertions.Specs/AssertionOptionsSpecs.cs index f8dfc8858a..d793b2beac 100644 --- a/Tests/FluentAssertions.Specs/AssertionOptionsSpecs.cs +++ b/Tests/FluentAssertions.Specs/AssertionOptionsSpecs.cs @@ -418,10 +418,10 @@ protected override void Dispose(bool disposing) internal class MyEquivalencyStep : IEquivalencyStep { - public EquivalencyResult Handle(Comparands comparands, Assertion assertion, IEquivalencyValidationContext context, + public EquivalencyResult Handle(Comparands comparands, AssertionChain assertionChain, IEquivalencyValidationContext context, IValidateChildNodeEquivalency nestedValidator) { - assertion.FailWith(GetType().FullName); + assertionChain.FailWith(GetType().FullName); return EquivalencyResult.EquivalencyProven; } diff --git a/Tests/FluentAssertions.Specs/Execution/AssertionScope.ChainingApiSpecs.cs b/Tests/FluentAssertions.Specs/Execution/AssertionScope.ChainingApiSpecs.cs index e6d470ae89..348a2fe49d 100644 --- a/Tests/FluentAssertions.Specs/Execution/AssertionScope.ChainingApiSpecs.cs +++ b/Tests/FluentAssertions.Specs/Execution/AssertionScope.ChainingApiSpecs.cs @@ -18,7 +18,7 @@ public void When_the_previous_assertion_succeeded_it_should_not_affect_the_next_ // Act try { - Assertion.GetOrCreate() + AssertionChain.GetOrCreate() .ForCondition(condition: true) .FailWith("First assertion") .Then @@ -40,7 +40,7 @@ public void When_the_previous_assertion_succeeded_it_should_not_affect_the_next_ public void When_the_previous_assertion_succeeded_it_should_not_affect_the_next_one_with_arguments() { // Act - Action act = () => Assertion.GetOrCreate() + Action act = () => AssertionChain.GetOrCreate() .ForCondition(true) .FailWith("First assertion") .Then @@ -55,7 +55,7 @@ public void When_the_previous_assertion_succeeded_it_should_not_affect_the_next_ public void When_the_previous_assertion_succeeded_it_should_not_affect_the_next_one_with_argument_providers() { // Act - Action act = () => Assertion.GetOrCreate() + Action act = () => AssertionChain.GetOrCreate() .ForCondition(true) .FailWith("First assertion") .Then @@ -70,7 +70,7 @@ public void When_the_previous_assertion_succeeded_it_should_not_affect_the_next_ public void When_the_previous_assertion_succeeded_it_should_not_affect_the_next_one_with_a_fail_reason_function() { // Act - Action act = () => Assertion.GetOrCreate() + Action act = () => AssertionChain.GetOrCreate() .ForCondition(true) .FailWith("First assertion") .Then @@ -85,7 +85,7 @@ public void When_the_previous_assertion_succeeded_it_should_not_affect_the_next_ public void When_continuing_an_assertion_chain_the_reason_should_be_part_of_consecutive_failures() { // Act - Action act = () => Assertion.GetOrCreate() + Action act = () => AssertionChain.GetOrCreate() .ForCondition(true) .FailWith("First assertion") .Then @@ -101,7 +101,7 @@ public void When_continuing_an_assertion_chain_the_reason_should_be_part_of_cons public void When_continuing_an_assertion_chain_the_reason_with_arguments_should_be_part_of_consecutive_failures() { // Act - Action act = () => Assertion.GetOrCreate() + Action act = () => AssertionChain.GetOrCreate() .ForCondition(true) .FailWith("First assertion") .Then @@ -117,7 +117,7 @@ public void When_continuing_an_assertion_chain_the_reason_with_arguments_should_ public void Passing_a_null_value_as_reason_does_not_fail() { // Act - Action act = () => Assertion.GetOrCreate() + Action act = () => AssertionChain.GetOrCreate() .BecauseOf(null, "only because for method disambiguity") .ForCondition(false) .FailWith("First assertion"); @@ -131,7 +131,7 @@ public void Passing_a_null_value_as_reason_does_not_fail() public void When_a_given_is_used_before_an_assertion_then_the_result_should_be_available_for_evaluation() { // Act - Action act = () => Assertion.GetOrCreate() + Action act = () => AssertionChain.GetOrCreate() .Given(() => new[] { "a", "b" }) .ForCondition(collection => collection.Length > 0) .FailWith("First assertion"); @@ -147,7 +147,7 @@ public void When_the_previous_assertion_failed_it_should_not_evaluate_the_succee using var _ = new AssertionScope(new IgnoringFailuresAssertionStrategy()); // Act / Assert - Assertion.GetOrCreate() + AssertionChain.GetOrCreate() .ForCondition(false) .FailWith("First assertion") .Then @@ -165,7 +165,7 @@ public void When_the_previous_assertion_failed_it_should_not_evaluate_the_succee using var _ = new AssertionScope(); // Act - Assertion.GetOrCreate() + AssertionChain.GetOrCreate() .Given(() => (string)null) .ForCondition(s => s is not null) .FailWith("but is was null") @@ -189,7 +189,7 @@ public void When_the_previous_assertion_failed_it_should_not_execute_the_succeed using var scope = new AssertionScope(); // Act - Assertion.GetOrCreate() + AssertionChain.GetOrCreate() .ForCondition(false) .FailWith("First assertion") .Then @@ -211,7 +211,7 @@ public void When_the_previous_assertion_failed_it_should_not_execute_the_succeed { using var _ = new AssertionScope(); - Assertion.GetOrCreate() + AssertionChain.GetOrCreate() .ForCondition(false) .FailWith("First assertion") .Then @@ -231,7 +231,7 @@ public void When_the_previous_assertion_failed_it_should_not_execute_the_succeed { using var _ = new AssertionScope(); - Assertion.GetOrCreate() + AssertionChain.GetOrCreate() .ForCondition(false) .FailWith("First assertion") .Then @@ -251,7 +251,7 @@ public void When_the_previous_assertion_failed_it_should_not_execute_the_succeed { using var _ = new AssertionScope(); - Assertion.GetOrCreate() + AssertionChain.GetOrCreate() .ForCondition(false) .FailWith("First assertion") .Then @@ -271,7 +271,7 @@ public void When_the_previous_assertion_failed_it_should_not_execute_the_succeed { using var _ = new AssertionScope(); - Assertion.GetOrCreate() + AssertionChain.GetOrCreate() .WithExpectation("Expectations are the root ") .ForCondition(false) .FailWith("of disappointment") @@ -293,7 +293,7 @@ public void When_the_previous_assertion_failed_it_should_not_execute_the_succeed { using var _ = new AssertionScope(); - Assertion.GetOrCreate() + AssertionChain.GetOrCreate() .WithExpectation("Expectations are the {0} ", "root") .ForCondition(false) .FailWith("of disappointment") @@ -315,7 +315,7 @@ public void When_the_previous_assertion_failed_it_should_not_execute_the_succeed { using var _ = new AssertionScope(); - Assertion.GetOrCreate() + AssertionChain.GetOrCreate() .WithDefaultIdentifier("identifier") .ForCondition(false) .FailWith("Expected {context}") @@ -337,7 +337,7 @@ public void When_continuing_a_failed_assertion_chain_consecutive_resons_are_igno { using var _ = new AssertionScope(); - Assertion.GetOrCreate() + AssertionChain.GetOrCreate() .BecauseOf("because {0}", "whatever") .ForCondition(false) .FailWith("Expected{reason}") @@ -359,7 +359,7 @@ public void When_continuing_a_failed_assertion_chain_consecutive_resons_with_arg { using var _ = new AssertionScope(); - Assertion.GetOrCreate() + AssertionChain.GetOrCreate() .BecauseOf("because {0}", "whatever") .ForCondition(false) .FailWith("Expected{reason}") @@ -377,7 +377,7 @@ public void When_continuing_a_failed_assertion_chain_consecutive_resons_with_arg public void When_the_previous_assertion_succeeded_it_should_evaluate_the_succeeding_given_statement() { // Act - Action act = () => Assertion.GetOrCreate() + Action act = () => AssertionChain.GetOrCreate() .ForCondition(true) .FailWith("First assertion") .Then @@ -391,7 +391,7 @@ public void When_the_previous_assertion_succeeded_it_should_evaluate_the_succeed public void When_the_previous_assertion_succeeded_it_should_not_affect_the_succeeding_expectation() { // Act - Action act = () => Assertion.GetOrCreate() + Action act = () => AssertionChain.GetOrCreate() .WithExpectation("Expectations are the root ") .ForCondition(true) .FailWith("of disappointment") @@ -408,7 +408,7 @@ public void When_the_previous_assertion_succeeded_it_should_not_affect_the_succe public void When_the_previous_assertion_succeeded_it_should_not_affect_the_succeeding_expectation_with_arguments() { // Act - Action act = () => Assertion.GetOrCreate() + Action act = () => AssertionChain.GetOrCreate() .WithExpectation("Expectations are the {0} ", "root") .ForCondition(true) .FailWith("of disappointment") @@ -427,7 +427,7 @@ public void When_the_previous_assertion_succeeded_it_should_not_affect_the_succe // Act Action act = () => { - Assertion.GetOrCreate() + AssertionChain.GetOrCreate() .WithDefaultIdentifier("identifier") .ForCondition(true) .FailWith("Expected {context}") @@ -445,7 +445,7 @@ public void When_the_previous_assertion_succeeded_it_should_not_affect_the_succe public void Continuing_an_assertion_with_occurrence() { // Act - Action act = () => Assertion.GetOrCreate() + Action act = () => AssertionChain.GetOrCreate() .ForCondition(true) .FailWith("First assertion") .Then @@ -462,7 +462,7 @@ public void Continuing_an_assertion_with_occurrence() public void Continuing_an_assertion_with_occurrence_will_not_be_executed_when_first_assertion_fails() { // Act - Action act = () => Assertion.GetOrCreate() + Action act = () => AssertionChain.GetOrCreate() .ForCondition(false) .FailWith("First assertion") .Then @@ -479,7 +479,7 @@ public void Continuing_an_assertion_with_occurrence_will_not_be_executed_when_fi public void Continuing_an_assertion_with_occurrence_overrides_the_previous_defined_expectations() { // Act - Action act = () => Assertion.GetOrCreate() + Action act = () => AssertionChain.GetOrCreate() .WithExpectation("First expectation") .ForCondition(true) .FailWith("First assertion") @@ -497,7 +497,7 @@ public void Continuing_an_assertion_with_occurrence_overrides_the_previous_defin public void Continuing_an_assertion_after_occurrence_check_works() { // Act - Action act = () => Assertion.GetOrCreate() + Action act = () => AssertionChain.GetOrCreate() .WithExpectation("{expectedOccurrence} ") .ForConstraint(Exactly.Once(), 1) .FailWith("First assertion") @@ -515,7 +515,7 @@ public void Continuing_an_assertion_after_occurrence_check_works() public void Continuing_an_assertion_with_occurrence_check_before_defining_expectation_works() { // Act - Action act = () => Assertion.GetOrCreate() + Action act = () => AssertionChain.GetOrCreate() .ForCondition(true) .FailWith("First assertion") .Then @@ -535,7 +535,7 @@ public void Does_not_continue_a_chained_assertion_after_the_first_one_failed_the using var scope = new AssertionScope(); // Act - Assertion.GetOrCreate() + AssertionChain.GetOrCreate() .ForConstraint(Exactly.Once(), 2) .FailWith("First {0}", "assertion") .Then @@ -557,7 +557,7 @@ public void Discard_a_scope_after_continuing_chained_assertion() using var scope = new AssertionScope(); // Act - Assertion.GetOrCreate() + AssertionChain.GetOrCreate() .ForConstraint(Exactly.Once(), 2) .FailWith("First {0}", "assertion"); @@ -576,7 +576,7 @@ public void Get_info_about_line_breaks_from_parent_scope_after_continuing_chaine scope.FormattingOptions.UseLineBreaks = true; // Act - var innerScope = Assertion.GetOrCreate() + var innerScope = AssertionChain.GetOrCreate() .ForConstraint(Exactly.Once(), 1) .FailWith("First {0}", "assertion") .Then diff --git a/Tests/FluentAssertions.Specs/Execution/AssertionScope.MessageFormatingSpecs.cs b/Tests/FluentAssertions.Specs/Execution/AssertionScope.MessageFormatingSpecs.cs index 2fc686f140..cc394d1f5b 100644 --- a/Tests/FluentAssertions.Specs/Execution/AssertionScope.MessageFormatingSpecs.cs +++ b/Tests/FluentAssertions.Specs/Execution/AssertionScope.MessageFormatingSpecs.cs @@ -390,7 +390,7 @@ public void Message_should_have_named_placeholder_be_replaced_by_defered_reporta public void Message_should_start_with_the_defined_expectation() { // Act - Action act = () => Assertion.GetOrCreate() + Action act = () => AssertionChain.GetOrCreate() .WithExpectation("Expectations are the root ") .ForCondition(false) .FailWith("of disappointment"); @@ -404,7 +404,7 @@ public void Message_should_start_with_the_defined_expectation() public void Message_should_start_with_the_defined_expectation_and_arguments() { // Act - Action act = () => Assertion.GetOrCreate() + Action act = () => AssertionChain.GetOrCreate() .WithExpectation("Expectations are the {0} ", "root") .ForCondition(false) .FailWith("of disappointment"); @@ -418,7 +418,7 @@ public void Message_should_start_with_the_defined_expectation_and_arguments() public void Message_should_contain_object_as_context_if_identifier_can_not_be_resolved() { // Act - Action act = () => Assertion.GetOrCreate() + Action act = () => AssertionChain.GetOrCreate() .ForCondition(false) .FailWith("Expected {context}"); @@ -431,7 +431,7 @@ public void Message_should_contain_object_as_context_if_identifier_can_not_be_re public void Message_should_contain_the_fallback_value_as_context_if_identifier_can_not_be_resolved() { // Act - Action act = () => Assertion.GetOrCreate() + Action act = () => AssertionChain.GetOrCreate() .ForCondition(false) .FailWith("Expected {context:fallback}"); @@ -444,7 +444,7 @@ public void Message_should_contain_the_fallback_value_as_context_if_identifier_c public void Message_should_contain_the_default_identifier_as_context_if_identifier_can_not_be_resolved() { // Act - Action act = () => Assertion.GetOrCreate() + Action act = () => AssertionChain.GetOrCreate() .WithDefaultIdentifier("identifier") .ForCondition(false) .FailWith("Expected {context}"); @@ -458,7 +458,7 @@ public void Message_should_contain_the_default_identifier_as_context_if_identifi public void Message_should_contain_the_reason_as_defined() { // Act - Action act = () => Assertion.GetOrCreate() + Action act = () => AssertionChain.GetOrCreate() .BecauseOf("because reasons") .FailWith("Expected{reason}"); @@ -471,7 +471,7 @@ public void Message_should_contain_the_reason_as_defined() public void Message_should_contain_the_reason_as_defined_with_arguments() { // Act - Action act = () => Assertion.GetOrCreate() + Action act = () => AssertionChain.GetOrCreate() .BecauseOf("because {0}", "reasons") .FailWith("Expected{reason}"); diff --git a/Tests/FluentAssertions.Specs/Execution/AssertionScopeSpecs.cs b/Tests/FluentAssertions.Specs/Execution/AssertionScopeSpecs.cs index 931c352e65..87e6f770d2 100644 --- a/Tests/FluentAssertions.Specs/Execution/AssertionScopeSpecs.cs +++ b/Tests/FluentAssertions.Specs/Execution/AssertionScopeSpecs.cs @@ -69,7 +69,7 @@ public void When_lazy_version_is_not_disposed_it_should_not_execute_fail_reason_ var scope = new AssertionScope(); bool failReasonCalled = false; - AssertionScope.Current + AssertionChain.GetOrCreate() .ForCondition(true) .FailWith(() => { @@ -91,7 +91,9 @@ public void When_lazy_version_is_disposed_it_should_throw_any_failures_and_prope // Arrange var scope = new AssertionScope(); - AssertionScope.Current.FailWith(() => new FailReason("Failure{0}", 1)); + AssertionChain + .GetOrCreate() + .FailWith(() => new FailReason("Failure{0}", 1)); // Act Action act = scope.Dispose; diff --git a/Tests/FluentAssertions.Specs/Execution/GivenSelectorSpecs.cs b/Tests/FluentAssertions.Specs/Execution/GivenSelectorSpecs.cs index cc6794ba9b..bff2336058 100644 --- a/Tests/FluentAssertions.Specs/Execution/GivenSelectorSpecs.cs +++ b/Tests/FluentAssertions.Specs/Execution/GivenSelectorSpecs.cs @@ -14,7 +14,7 @@ public void A_consecutive_subject_should_be_selected() string value = string.Empty; // Act - Assertion.GetOrCreate() + AssertionChain.GetOrCreate() .ForCondition(true) .Given(() => "First selector") .Given(_ => value = "Second selector"); @@ -30,7 +30,7 @@ public void After_a_failed_condition_a_consecutive_subject_should_be_ignored() string value = string.Empty; // Act - Assertion.GetOrCreate() + AssertionChain.GetOrCreate() .ForCondition(false) .Given(() => "First selector") .Given(_ => value = "Second selector"); @@ -43,7 +43,7 @@ public void After_a_failed_condition_a_consecutive_subject_should_be_ignored() public void A_consecutive_condition_should_be_evaluated() { // Act / Assert - Assertion.GetOrCreate() + AssertionChain.GetOrCreate() .ForCondition(true) .Given(() => "Subject") .ForCondition(_ => true) @@ -54,7 +54,7 @@ public void A_consecutive_condition_should_be_evaluated() public void After_a_failed_condition_a_consecutive_condition_should_be_ignored() { // Act - Action act = () => Assertion.GetOrCreate() + Action act = () => AssertionChain.GetOrCreate() .ForCondition(false) .Given(() => "Subject") .ForCondition(_ => throw new ApplicationException()) @@ -68,7 +68,7 @@ public void After_a_failed_condition_a_consecutive_condition_should_be_ignored() public void When_continuing_an_assertion_chain_it_fails_with_a_message_after_selecting_the_subject() { // Act - Action act = () => Assertion.GetOrCreate() + Action act = () => AssertionChain.GetOrCreate() .ForCondition(true) .Given(() => "First") .FailWith("First selector") @@ -85,7 +85,7 @@ public void When_continuing_an_assertion_chain_it_fails_with_a_message_after_sel public void When_continuing_an_assertion_chain_it_fails_with_a_message_with_arguments_after_selecting_the_subject() { // Act - Action act = () => Assertion.GetOrCreate() + Action act = () => AssertionChain.GetOrCreate() .ForCondition(true) .Given(() => "First") .FailWith("{0} selector", "First") @@ -102,7 +102,7 @@ public void When_continuing_an_assertion_chain_it_fails_with_a_message_with_argu public void When_continuing_an_assertion_chain_it_fails_with_a_message_with_argument_selectors_after_selecting_the_subject() { // Act - Action act = () => Assertion.GetOrCreate() + Action act = () => AssertionChain.GetOrCreate() .ForCondition(true) .Given(() => "First") .FailWith("{0} selector", _ => "First") @@ -123,7 +123,7 @@ public void When_continuing_a_failed_assertion_chain_consecutive_failure_message { using var _ = new AssertionScope(); - Assertion.GetOrCreate() + AssertionChain.GetOrCreate() .Given(() => "First") .FailWith("First selector") .Then @@ -143,7 +143,7 @@ public void When_continuing_a_failed_assertion_chain_consecutive_failure_message { using var _ = new AssertionScope(); - Assertion.GetOrCreate() + AssertionChain.GetOrCreate() .Given(() => "First") .FailWith("{0} selector", "First") .Then @@ -163,7 +163,7 @@ public void When_continuing_a_failed_assertion_chain_consecutive_failure_message { using var _ = new AssertionScope(); - Assertion.GetOrCreate() + AssertionChain.GetOrCreate() .Given(() => "First") .FailWith("{0} selector", _ => "First") .Then @@ -179,7 +179,7 @@ public void When_continuing_a_failed_assertion_chain_consecutive_failure_message public void The_failure_message_should_be_preceded_by_the_expectation_after_selecting_a_subject() { // Act - Action act = () => Assertion.GetOrCreate() + Action act = () => AssertionChain.GetOrCreate() .WithExpectation("Expectation ") .Given(() => "Subject") .FailWith("Failure"); @@ -194,7 +194,7 @@ public void The_failure_message_should_not_be_preceded_by_the_expectation_after_selecting_a_subject_and_clearing_the_expectation() { // Act - Action act = () => Assertion.GetOrCreate() + Action act = () => AssertionChain.GetOrCreate() .WithExpectation("Expectation ") .Given(() => "Subject") .FailWith("Failure"); @@ -208,7 +208,7 @@ public void public void Clearing_the_expectation_does_not_affect_a_successful_assertion() { // Act - var assertion = Assertion.GetOrCreate() + var assertion = AssertionChain.GetOrCreate() .WithExpectation("Expectation ") .Given(() => "Don't care") .ForCondition(_ => true) @@ -224,7 +224,7 @@ public void Clearing_the_expectation_does_not_affect_a_failed_assertion() // Act using var scope = new AssertionScope(); - var assertion = Assertion.GetOrCreate() + var assertion = AssertionChain.GetOrCreate() .WithExpectation("Expectation ") .Given(() => "Don't care") .ForCondition(_ => false) diff --git a/Tests/FluentAssertions.Specs/OccurrenceConstraintSpecs.cs b/Tests/FluentAssertions.Specs/OccurrenceConstraintSpecs.cs index 0019d38e33..7024a699dd 100644 --- a/Tests/FluentAssertions.Specs/OccurrenceConstraintSpecs.cs +++ b/Tests/FluentAssertions.Specs/OccurrenceConstraintSpecs.cs @@ -49,7 +49,7 @@ public class OccurrenceConstraintSpecs public void Occurrence_constraint_passes(OccurrenceConstraint constraint, int occurrences) { // Act / Assert - Assertion.GetOrCreate() + AssertionChain.GetOrCreate() .ForConstraint(constraint, occurrences) .FailWith(""); } @@ -96,7 +96,7 @@ public void Occurrence_constraint_passes(OccurrenceConstraint constraint, int oc public void Occurrence_constraint_fails(OccurrenceConstraint constraint, int occurrences) { // Act - Action act = () => Assertion.GetOrCreate() + Action act = () => AssertionChain.GetOrCreate() .ForConstraint(constraint, occurrences) .FailWith($"Expected occurrence to be {constraint.Mode} {constraint.ExpectedCount}, but it was {occurrences}"); diff --git a/Tests/FluentAssertions.Specs/Primitives/ObjectAssertionSpecs.cs b/Tests/FluentAssertions.Specs/Primitives/ObjectAssertionSpecs.cs index cd57998d48..5eba64f113 100644 --- a/Tests/FluentAssertions.Specs/Primitives/ObjectAssertionSpecs.cs +++ b/Tests/FluentAssertions.Specs/Primitives/ObjectAssertionSpecs.cs @@ -78,7 +78,7 @@ internal class SomeClassEqualityComparer : IEqualityComparer internal class SomeClassAssertions : ObjectAssertions { public SomeClassAssertions(SomeClass value) - : base(value, Assertion.GetOrCreate()) + : base(value, AssertionChain.GetOrCreate()) { } } diff --git a/Tests/FluentAssertions.Specs/Primitives/ReferenceTypeAssertionsSpecs.cs b/Tests/FluentAssertions.Specs/Primitives/ReferenceTypeAssertionsSpecs.cs index 96a41e4a80..d27acc17b4 100644 --- a/Tests/FluentAssertions.Specs/Primitives/ReferenceTypeAssertionsSpecs.cs +++ b/Tests/FluentAssertions.Specs/Primitives/ReferenceTypeAssertionsSpecs.cs @@ -454,7 +454,7 @@ public void Should_throw_a_helpful_error_when_accidentally_using_equals() public class ReferenceTypeAssertionsDummy : ReferenceTypeAssertions { public ReferenceTypeAssertionsDummy(object subject) - : base(subject, Assertion.GetOrCreate()) + : base(subject, AssertionChain.GetOrCreate()) { } diff --git a/Tests/FluentAssertions.Specs/Primitives/SimpleTimeSpanAssertionSpecs.cs b/Tests/FluentAssertions.Specs/Primitives/SimpleTimeSpanAssertionSpecs.cs index 6eff752fbb..0cf1b14ae1 100644 --- a/Tests/FluentAssertions.Specs/Primitives/SimpleTimeSpanAssertionSpecs.cs +++ b/Tests/FluentAssertions.Specs/Primitives/SimpleTimeSpanAssertionSpecs.cs @@ -166,7 +166,7 @@ public void When_asserting_value_to_be_equal_to_different_value_it_should_fail() public void A_null_is_not_equal_to_another_value() { // Arrange - var subject = new SimpleTimeSpanAssertions(null, Assertion.GetOrCreate()); + var subject = new SimpleTimeSpanAssertions(null, AssertionChain.GetOrCreate()); TimeSpan expected = 2.Seconds(); // Act diff --git a/Tests/FluentAssertions.Specs/Specialized/ExecutionTimeAssertionsSpecs.cs b/Tests/FluentAssertions.Specs/Specialized/ExecutionTimeAssertionsSpecs.cs index 11aa1fef6c..d0f632baa4 100644 --- a/Tests/FluentAssertions.Specs/Specialized/ExecutionTimeAssertionsSpecs.cs +++ b/Tests/FluentAssertions.Specs/Specialized/ExecutionTimeAssertionsSpecs.cs @@ -581,7 +581,7 @@ public void When_asserting_on_null_execution_it_should_throw() ExecutionTime executionTime = null; // Act - Func act = () => new ExecutionTimeAssertions(executionTime, Assertion.GetOrCreate()); + Func act = () => new ExecutionTimeAssertions(executionTime, AssertionChain.GetOrCreate()); // Assert act.Should().Throw() diff --git a/Tests/FluentAssertions.Specs/Types/PropertyInfoSelectorAssertionSpecs.cs b/Tests/FluentAssertions.Specs/Types/PropertyInfoSelectorAssertionSpecs.cs index 7529627282..c3ab677b3b 100644 --- a/Tests/FluentAssertions.Specs/Types/PropertyInfoSelectorAssertionSpecs.cs +++ b/Tests/FluentAssertions.Specs/Types/PropertyInfoSelectorAssertionSpecs.cs @@ -296,7 +296,7 @@ public class Miscellaneous public void When_accidentally_using_equals_it_should_throw_a_helpful_error() { // Arrange - var someObject = new PropertyInfoSelectorAssertions(Assertion.GetOrCreate()); + var someObject = new PropertyInfoSelectorAssertions(AssertionChain.GetOrCreate()); // Act var action = () => someObject.Equals(null);