forked from fluentassertions/fluentassertions
/
GenericCollectionAssertions.cs
373 lines (339 loc) · 18.7 KB
/
GenericCollectionAssertions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using FluentAssertions.Common;
using FluentAssertions.Equivalency;
using FluentAssertions.Execution;
namespace FluentAssertions.Collections
{
[DebuggerNonUserCode]
public class GenericCollectionAssertions<T> :
SelfReferencingCollectionAssertions<T, GenericCollectionAssertions<T>>
{
public GenericCollectionAssertions(IEnumerable<T> actualValue)
: base(actualValue)
{
}
/// <summary>
/// Asserts that the collection does not contain any <c>null</c> items.
/// </summary>
/// <param name="predicate">The predicate when evaluated should not be null.</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <see cref="because" />.
/// </param>
public AndConstraint<GenericCollectionAssertions<T>> NotContainNulls<TKey>(Expression<Func<T, TKey>> predicate, string because = "", params object[] becauseArgs)
where TKey : class
{
if (Subject is null)
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} not to contain <null>s{reason}, but collection is <null>.");
}
Func<T, TKey> compiledPredicate = predicate.Compile();
var values = Subject
.Where(e => compiledPredicate(e) is null)
.ToArray();
if (values.Length > 0)
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} not to contain <null>s on {0}{reason}, but found {1}.",
predicate.Body,
values);
}
return new AndConstraint<GenericCollectionAssertions<T>>(this);
}
/// <summary>
/// Asserts that the collection does not contain any duplicate items.
/// </summary>
/// <param name="predicate">The predicate to group the items by.</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <see cref="because" />.
/// </param>
public AndConstraint<GenericCollectionAssertions<T>> OnlyHaveUniqueItems<TKey>(Expression<Func<T, TKey>> predicate, string because = "", params object[] becauseArgs)
{
if (Subject is null)
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} to only have unique items{reason}, but found {0}.", Subject);
}
Func<T, TKey> compiledPredicate = predicate.Compile();
IGrouping<TKey, T>[] groupWithMultipleItems = Subject
.GroupBy(compiledPredicate)
.Where(g => g.Count() > 1)
.ToArray();
if (groupWithMultipleItems.Length > 0)
{
if (groupWithMultipleItems.Length > 1)
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} to only have unique items on {0}{reason}, but items {1} are not unique.",
predicate.Body,
groupWithMultipleItems.SelectMany(g => g));
}
else
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} to only have unique items on {0}{reason}, but item {1} is not unique.",
predicate.Body,
groupWithMultipleItems[0].First());
}
}
return new AndConstraint<GenericCollectionAssertions<T>>(this);
}
/// <summary>
/// Asserts that a collection is ordered in ascending order according to the value of the specified
/// <paramref name="propertyExpression"/>.
/// </summary>
/// <param name="propertyExpression">
/// A lambda expression that references the property that should be used to determine the expected ordering.
/// </param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])"/> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="args">
/// Zero or more objects to format using the placeholders in <see cref="because"/>.
/// </param>
public AndConstraint<GenericCollectionAssertions<T>> BeInAscendingOrder<TSelector>(
Expression<Func<T, TSelector>> propertyExpression, string because = "", params object[] args)
{
return BeInAscendingOrder(propertyExpression, Comparer<TSelector>.Default, because, args);
}
/// <summary>
/// Asserts that a collection is ordered in ascending order according to the value of the specified
/// <see cref="IComparer{T}"/> implementation.
/// </summary>
/// <param name="comparer">
/// The object that should be used to determine the expected ordering.
/// </param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])"/> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="args">
/// Zero or more objects to format using the placeholders in <see cref="because"/>.
/// </param>
public AndConstraint<GenericCollectionAssertions<T>> BeInAscendingOrder(
IComparer<T> comparer, string because = "", params object[] args)
{
return BeInAscendingOrder(item => item, comparer, because, args);
}
/// <summary>
/// Asserts that a collection is ordered in ascending order according to the value of the specified
/// <paramref name="propertyExpression"/> and <see cref="IComparer{T}"/> implementation.
/// </summary>
/// <param name="propertyExpression">
/// A lambda expression that references the property that should be used to determine the expected ordering.
/// </param>
/// <param name="comparer">
/// The object that should be used to determine the expected ordering.
/// </param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])"/> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="args">
/// Zero or more objects to format using the placeholders in <see cref="because"/>.
/// </param>
public AndConstraint<GenericCollectionAssertions<T>> BeInAscendingOrder<TSelector>(
Expression<Func<T, TSelector>> propertyExpression, IComparer<TSelector> comparer, string because = "", params object[] args)
{
return BeOrderedBy(propertyExpression, comparer, SortOrder.Ascending, because, args);
}
/// <summary>
/// Asserts that a collection is ordered in descending order according to the value of the specified
/// <paramref name="propertyExpression"/>.
/// </summary>
/// <param name="propertyExpression">
/// A lambda expression that references the property that should be used to determine the expected ordering.
/// </param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])"/> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="args">
/// Zero or more objects to format using the placeholders in <see cref="because"/>.
/// </param>
public AndConstraint<GenericCollectionAssertions<T>> BeInDescendingOrder<TSelector>(
Expression<Func<T, TSelector>> propertyExpression, string because = "", params object[] args)
{
return BeInDescendingOrder(propertyExpression, Comparer<TSelector>.Default, because, args);
}
/// <summary>
/// Asserts that a collection is ordered in descending order according to the value of the specified
/// <see cref="IComparer{T}"/> implementation.
/// </summary>
/// <param name="comparer">
/// The object that should be used to determine the expected ordering.
/// </param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])"/> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="args">
/// Zero or more objects to format using the placeholders in <see cref="because"/>.
/// </param>
public AndConstraint<GenericCollectionAssertions<T>> BeInDescendingOrder(
IComparer<T> comparer, string because = "", params object[] args)
{
return BeInDescendingOrder(item => item, comparer, because, args);
}
/// <summary>
/// Asserts that a collection is ordered in descending order according to the value of the specified
/// <paramref name="propertyExpression"/> and <see cref="IComparer{T}"/> implementation.
/// </summary>
/// <param name="propertyExpression">
/// A lambda expression that references the property that should be used to determine the expected ordering.
/// </param>
/// <param name="comparer">
/// The object that should be used to determine the expected ordering.
/// </param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])"/> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="args">
/// Zero or more objects to format using the placeholders in <see cref="because"/>.
/// </param>
public AndConstraint<GenericCollectionAssertions<T>> BeInDescendingOrder<TSelector>(
Expression<Func<T, TSelector>> propertyExpression, IComparer<TSelector> comparer, string because = "", params object[] args)
{
return BeOrderedBy(propertyExpression, comparer, SortOrder.Descending, because, args);
}
private AndConstraint<GenericCollectionAssertions<T>> BeOrderedBy<TSelector>(
Expression<Func<T, TSelector>> propertyExpression, IComparer<TSelector> comparer, SortOrder direction, string because, object[] args)
{
if (comparer == null)
{
throw new ArgumentNullException(nameof(comparer),
"Cannot assert collection ordering without specifying a comparer.");
}
if (IsValidProperty(propertyExpression, because, args))
{
ICollection<T> unordered = Subject.ConvertOrCastToCollection();
Func<T, TSelector> keySelector = propertyExpression.Compile();
IOrderedEnumerable<T> expectation = (direction == SortOrder.Ascending)
? unordered.OrderBy(keySelector, comparer)
: unordered.OrderByDescending(keySelector, comparer);
var orderString = propertyExpression.GetMemberPath();
orderString = orderString == "\"\"" ? string.Empty : " by " + orderString;
Execute.Assertion
.ForCondition(unordered.SequenceEqual(expectation))
.BecauseOf(because, args)
.FailWith("Expected {context:collection} {0} to be ordered{1}{reason} and result in {2}.",
Subject, orderString, expectation);
}
return new AndConstraint<GenericCollectionAssertions<T>>(this);
}
private bool IsValidProperty<TSelector>(Expression<Func<T, TSelector>> propertyExpression, string because, object[] args)
{
if (propertyExpression == null)
{
throw new ArgumentNullException(nameof(propertyExpression),
"Cannot assert collection ordering without specifying a property.");
}
return Execute.Assertion
.ForCondition(!(Subject is null))
.BecauseOf(because, args)
.FailWith("Expected {context:collection} to be ordered by {0}{reason} but found <null>.",
propertyExpression.GetMemberPath());
}
/// <summary>
/// Asserts that all elements in a collection of objects are equivalent to a given object.
/// </summary>
/// <remarks>
/// Objects within the collection are equivalent to given object when both object graphs have equally named properties with the same
/// value, irrespective of the type of those objects. Two properties are also equal if one type can be converted to another
/// and the result is equal.
/// The type of a collection property is ignored as long as the collection implements <see cref="IEnumerable"/> and all
/// items in the collection are structurally equal.
/// Notice that actual behavior is determined by the global defaults managed by <see cref="AssertionOptions"/>.
/// </remarks>
/// <param name="because">
/// An optional formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the
/// assertion is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <see cref="because" />.
/// </param>
public void AllBeEquivalentTo<TExpectation>(TExpectation expectation,
string because = "", params object[] becauseArgs)
{
AllBeEquivalentTo(expectation, options => options, because, becauseArgs);
}
/// <summary>
/// Asserts that all elements in a collection of objects are equivalent to a given object.
/// </summary>
/// <remarks>
/// Objects within the collection are equivalent to given object when both object graphs have equally named properties with the same
/// value, irrespective of the type of those objects. Two properties are also equal if one type can be converted to another
/// and the result is equal.
/// The type of a collection property is ignored as long as the collection implements <see cref="IEnumerable"/> and all
/// items in the collection are structurally equal.
/// Notice that actual behavior is determined by the global defaults managed by <see cref="AssertionOptions"/>.
/// </remarks>
/// <param name="config">
/// A reference to the <see cref="EquivalencyAssertionOptions{TExpectation}"/> configuration object that can be used
/// to influence the way the object graphs are compared. You can also provide an alternative instance of the
/// <see cref="EquivalencyAssertionOptions{TSubject}"/> class. The global defaults are determined by the
/// <see cref="AssertionOptions"/> class.
/// </param>
/// <param name="because">
/// An optional formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the
/// assertion is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <see cref="because" />.
/// </param>
public void AllBeEquivalentTo<TExpectation>(TExpectation expectation,
Func<EquivalencyAssertionOptions<TExpectation>, EquivalencyAssertionOptions<TExpectation>> config,
string because = "",
params object[] becauseArgs)
{
TExpectation[] repeatedExpectation = RepeatAsManyAs(expectation, Subject).ToArray();
// Because we have just manually created the collection based on single element
// we are sure that we can force string ordering, because ordering does not matter in terms
// of correctness. On the other hand we do not want to change ordering rules for nested objects
// in case user needs to use them. Strict ordering improves algorithmic complexity
// from O(n^2) to O(n). For bigger tables it is necessary in order to achieve acceptable
// execution times.
Func<EquivalencyAssertionOptions<TExpectation>, EquivalencyAssertionOptions<TExpectation>> forceStringOrderingConfig =
x => config(x).WithStrictOrderingFor(s => s.SelectedMemberPath == "");
BeEquivalentTo(repeatedExpectation, forceStringOrderingConfig, because, becauseArgs);
}
private static IEnumerable<TExpectation> RepeatAsManyAs<TExpectation>(TExpectation value, IEnumerable<T> enumerable)
{
if (enumerable == null)
{
return Enumerable.Empty<TExpectation>();
}
return RepeatAsManyAsIterator(value, enumerable);
}
private static IEnumerable<TExpectation> RepeatAsManyAsIterator<TExpectation>(TExpectation value, IEnumerable<T> enumerable)
{
using (IEnumerator<T> enumerator = enumerable.GetEnumerator())
{
while (enumerator.MoveNext())
{
yield return value;
}
}
}
}
}