/
CollectionAssertions.cs
1595 lines (1434 loc) · 78.3 KB
/
CollectionAssertions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using FluentAssertions.Common;
using FluentAssertions.Equivalency;
using FluentAssertions.Execution;
using FluentAssertions.Primitives;
namespace FluentAssertions.Collections
{
/// <summary>
/// Contains a number of methods to assert that an <see cref="IEnumerable"/> is in the expected state.
/// </summary>
public abstract class CollectionAssertions<TSubject, TAssertions> : ReferenceTypeAssertions<TSubject, TAssertions>
where TSubject : IEnumerable
where TAssertions : CollectionAssertions<TSubject, TAssertions>
{
/// <summary>
/// Asserts that the collection does not contain any items.
/// </summary>
/// <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<TAssertions> BeEmpty(string because = "", params object[] becauseArgs)
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.WithExpectation("Expected {context:collection} to be empty{reason}, ")
.ForCondition(!ReferenceEquals(Subject, null))
.FailWith("but found {0}.", Subject)
.Then
.Given(() => Subject.Cast<object>())
.ForCondition(collection => !collection.Any())
.FailWith("but found {0}.", collection => collection);
return new AndConstraint<TAssertions>((TAssertions)this);
}
/// <summary>
/// Asserts that the collection contains at least 1 item.
/// </summary>
/// <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<TAssertions> NotBeEmpty(string because = "", params object[] becauseArgs)
{
if (ReferenceEquals(Subject, null))
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} not to be empty{reason}, but found {0}.", Subject);
}
IEnumerable<object> enumerable = Subject.Cast<object>();
Execute.Assertion
.ForCondition(enumerable.Any())
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} not to be empty{reason}.");
return new AndConstraint<TAssertions>((TAssertions)this);
}
/// <summary>
/// Asserts that the collection is null or does not contain any items.
/// </summary>
/// <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<TAssertions> BeNullOrEmpty(string because = "", params object[] becauseArgs)
{
var nullOrEmpty = ReferenceEquals(Subject, null) || !Subject.Cast<object>().Any();
Execute.Assertion.ForCondition(nullOrEmpty)
.BecauseOf(because, becauseArgs)
.FailWith(
"Expected {context:collection} to be null or empty{reason}, but found {0}.",
Subject);
return new AndConstraint<TAssertions>((TAssertions)this);
}
/// <summary>
/// Asserts that the collection is not null and contains at least 1 item.
/// </summary>
/// <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<TAssertions> NotBeNullOrEmpty(string because = "", params object[] becauseArgs)
{
return NotBeNull(because, becauseArgs)
.And.NotBeEmpty(because, becauseArgs);
}
/// <summary>
/// Asserts that the collection does not contain any duplicate items.
/// </summary>
/// <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<TAssertions> OnlyHaveUniqueItems(string because = "", params object[] becauseArgs)
{
if (ReferenceEquals(Subject, null))
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} to only have unique items{reason}, but found {0}.", Subject);
}
IEnumerable<object> groupWithMultipleItems = Subject.Cast<object>()
.GroupBy(o => o)
.Where(g => g.Count() > 1)
.Select(g => g.Key);
if (groupWithMultipleItems.Any())
{
if (groupWithMultipleItems.Count() > 1)
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} to only have unique items{reason}, but items {0} are not unique.",
groupWithMultipleItems);
}
else
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} to only have unique items{reason}, but item {0} is not unique.",
groupWithMultipleItems.First());
}
}
return new AndConstraint<TAssertions>((TAssertions)this);
}
/// <summary>
/// Asserts that the collection does not contain any <c>null</c> items.
/// </summary>
/// <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<TAssertions> NotContainNulls(string because = "", params object[] becauseArgs)
{
if (ReferenceEquals(Subject, null))
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} not to contain <null>s{reason}, but collection is <null>.");
}
int[] indices = Subject
.Cast<object>()
.Select((item, index) => new { Item = item, Index = index })
.Where(e => e.Item is null)
.Select(e => e.Index)
.ToArray();
if (indices.Length > 0)
{
if (indices.Length > 1)
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} not to contain <null>s{reason}, but found several at indices {0}.", indices);
}
else
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} not to contain <null>s{reason}, but found one at index {0}.", indices[0]);
}
}
return new AndConstraint<TAssertions>((TAssertions)this);
}
/// <summary>
/// Expects the current collection to contain all the same elements in the same order as the collection identified by
/// <paramref name="elements" />. Elements are compared using their <see cref="object.Equals(object)" />.
/// </summary>
/// <param name="elements">A params array with the expected elements.</param>
public AndConstraint<TAssertions> Equal(params object[] elements)
{
return Equal(elements, string.Empty);
}
/// <summary>
/// Expects the current collection to contain all the same elements in the same order as the collection identified by
/// <paramref name="expected" />. Elements are compared using their <see cref="object.Equals(object)" />.
/// </summary>
/// <param name="expected">An <see cref="IEnumerable"/> with the expected elements.</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<TAssertions> Equal(IEnumerable expected, string because = "", params object[] becauseArgs)
{
AssertSubjectEquality<object, object>(expected, (s, e) => s.IsSameOrEqualTo(e), because, becauseArgs);
return new AndConstraint<TAssertions>((TAssertions)this);
}
protected void AssertSubjectEquality<TActual, TExpected>(IEnumerable expectation, Func<TActual, TExpected, bool> equalityComparison,
string because = "", params object[] becauseArgs)
{
bool subjectIsNull = ReferenceEquals(Subject, null);
bool expectationIsNull = expectation is null;
if (subjectIsNull && expectationIsNull)
{
return;
}
if (expectation == null)
{
throw new ArgumentNullException(nameof(expectation), "Cannot compare collection with <null>.");
}
ICollection<TExpected> expectedItems = expectation.ConvertOrCastToCollection<TExpected>();
IAssertionScope assertion = Execute.Assertion.BecauseOf(because, becauseArgs);
if (subjectIsNull)
{
assertion.FailWith("Expected {context:collection} to be equal to {0}{reason}, but found <null>.", expectedItems);
}
assertion
.WithExpectation("Expected {context:collection} to be equal to {0}{reason}, ", expectedItems)
.Given(() => Subject.ConvertOrCastToCollection<TActual>())
.AssertCollectionsHaveSameCount(expectedItems.Count)
.Then
.AssertCollectionsHaveSameItems(expectedItems, (a, e) => a.IndexOfFirstDifferenceWith(e, equalityComparison));
}
/// <summary>
/// Expects the current collection not to contain all the same elements in the same order as the collection identified by
/// <paramref name="unexpected" />. Elements are compared using their <see cref="object.Equals(object)" />.
/// </summary>
/// <param name="unexpected">An <see cref="IEnumerable"/> with the elements that are not expected.</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<TAssertions> NotEqual(IEnumerable unexpected, string because = "", params object[] becauseArgs)
{
if (ReferenceEquals(Subject, null))
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected collections not to be equal{reason}, but found <null>.");
}
if (unexpected == null)
{
throw new ArgumentNullException(nameof(unexpected), "Cannot compare collection with <null>.");
}
if (ReferenceEquals(Subject, unexpected))
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected collections not to be equal{reason}, but they both reference the same object.");
}
ICollection<object> actualitems = Subject.ConvertOrCastToCollection<object>();
if (actualitems.SequenceEqual(unexpected.Cast<object>()))
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Did not expect collections {0} and {1} to be equal{reason}.", unexpected, actualitems);
}
return new AndConstraint<TAssertions>((TAssertions)this);
}
/// <summary>
/// Asserts that a collection of objects is equivalent to another collection of objects.
/// </summary>
/// <remarks>
/// Objects within the collections are equivalent 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 AndConstraint<TAssertions> BeEquivalentTo<TExpectation>(IEnumerable<TExpectation> expectation,
string because = "", params object[] becauseArgs)
{
BeEquivalentTo(expectation, config => config, because, becauseArgs);
return new AndConstraint<TAssertions>((TAssertions)this);
}
/// <summary>
/// Asserts that a collection of objects is equivalent to another collection of objects.
/// </summary>
/// <remarks>
/// Objects within the collections are equivalent 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>
public AndConstraint<TAssertions> BeEquivalentTo(params object[] expectations)
{
BeEquivalentTo(expectations, config => config, string.Empty);
return new AndConstraint<TAssertions>((TAssertions)this);
}
/// <summary>
/// Asserts that a collection of objects is equivalent to another collection of objects.
/// </summary>
/// <remarks>
/// Objects within the collections are equivalent 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 AndConstraint<TAssertions> BeEquivalentTo(IEnumerable expectation, string because = "", params object[] becauseArgs)
{
BeEquivalentTo(expectation, config => config, because, becauseArgs);
return new AndConstraint<TAssertions>((TAssertions)this);
}
/// <summary>
/// Asserts that a collection of objects is equivalent to another collection of objects.
/// </summary>
/// <remarks>
/// Objects within the collections are equivalent 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{TSubject}"/> 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 AndConstraint<TAssertions> BeEquivalentTo(IEnumerable expectation,
Func<EquivalencyAssertionOptions<IEnumerable>, EquivalencyAssertionOptions<IEnumerable>> config, string because = "",
params object[] becauseArgs)
{
EquivalencyAssertionOptions<IEnumerable> options = config(AssertionOptions.CloneDefaults<IEnumerable>());
var context = new EquivalencyValidationContext
{
Subject = Subject,
Expectation = expectation,
RootIsCollection = true,
CompileTimeType = typeof(IEnumerable),
Because = because,
BecauseArgs = becauseArgs,
Tracer = options.TraceWriter
};
var equivalencyValidator = new EquivalencyValidator(options);
equivalencyValidator.AssertEquality(context);
return new AndConstraint<TAssertions>((TAssertions)this);
}
/// <summary>
/// Asserts that a collection of objects is equivalent to another collection of objects.
/// </summary>
/// <remarks>
/// Objects within the collections are equivalent 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.
/// </remarks>
/// <param name="config">
/// A reference to the <see cref="EquivalencyAssertionOptions{TSubject}"/> 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 AndConstraint<TAssertions> BeEquivalentTo<TExpectation>(IEnumerable<TExpectation> expectation,
Func<EquivalencyAssertionOptions<TExpectation>, EquivalencyAssertionOptions<TExpectation>> config, string because = "",
params object[] becauseArgs)
{
EquivalencyAssertionOptions<IEnumerable<TExpectation>> options = config(AssertionOptions.CloneDefaults<TExpectation>()).AsCollection();
var context = new EquivalencyValidationContext
{
Subject = Subject,
Expectation = expectation,
RootIsCollection = true,
CompileTimeType = typeof(IEnumerable<TExpectation>),
Because = because,
BecauseArgs = becauseArgs,
Tracer = options.TraceWriter
};
var equivalencyValidator = new EquivalencyValidator(options);
equivalencyValidator.AssertEquality(context);
return new AndConstraint<TAssertions>((TAssertions)this);
}
/// <summary>
/// Expects the current collection not to contain all elements of the collection identified by <paramref name="unexpected" />,
/// regardless of the order. Elements are compared using their <see cref="object.Equals(object)" />.
/// </summary>
/// <param name="unexpected">An <see cref="IEnumerable"/> with the unexpected elements.</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<TAssertions> NotBeEquivalentTo(IEnumerable unexpected, string because = "",
params object[] becauseArgs)
{
if (unexpected == null)
{
throw new ArgumentNullException(nameof(unexpected), "Cannot verify inequivalence against a <null> collection.");
}
if (ReferenceEquals(Subject, null))
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} not to be equivalent{reason}, but found <null>.");
}
if (ReferenceEquals(Subject, unexpected))
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} {0} not to be equivalent with collection {1}{reason}, but they both reference the same object.",
Subject,
unexpected);
}
IEnumerable<object> actualItems = Subject.Cast<object>();
IEnumerable<object> unexpectedItems = unexpected.Cast<object>();
if (actualItems.Count() == unexpectedItems.Count())
{
List<object> missingItems = GetMissingItems(unexpectedItems, actualItems);
Execute.Assertion
.ForCondition(missingItems.Count > 0)
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} {0} not be equivalent with collection {1}{reason}.", Subject,
unexpected);
}
string[] failures;
using (var scope = new AssertionScope())
{
Subject.Should().BeEquivalentTo(unexpected);
failures = scope.Discard();
}
Execute.Assertion
.ForCondition(failures.Length > 0)
.FailWith("Expected {context:collection} {0} not to be equivalent to collection {1}{reason}.", Subject,
unexpected);
return new AndConstraint<TAssertions>((TAssertions)this);
}
/// <summary>
/// Asserts that the current collection only contains items that are assignable to the type <typeparamref name="T" />.
/// </summary>
/// <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<TAssertions> ContainItemsAssignableTo<T>(string because = "", params object[] becauseArgs)
{
if (ReferenceEquals(Subject, null))
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} to contain element assignable to type {0}{reason}, but found <null>.",
typeof(T));
}
int index = 0;
foreach (object item in Subject)
{
if (!(item is T))
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith(
"Expected {context:collection} to contain only items of type {0}{reason}, but item {1} at index {2} is of type {3}.",
typeof(T), item, index, item.GetType());
}
++index;
}
return new AndConstraint<TAssertions>((TAssertions)this);
}
private static List<T> GetMissingItems<T>(IEnumerable<T> expectedItems, IEnumerable<T> actualItems)
{
List<T> missingItems = new List<T>();
List<T> subject = actualItems.ToList();
foreach (T expectation in expectedItems)
{
if (subject.Contains(expectation))
{
subject.Remove(expectation);
}
else
{
missingItems.Add(expectation);
}
}
return missingItems;
}
/// <summary>
/// Expects the current collection to contain the specified elements in any order. Elements are compared
/// using their <see cref="object.Equals(object)" /> implementation.
/// </summary>
/// <param name="expected">An <see cref="IEnumerable"/> with the expected elements.</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<TAssertions> Contain(IEnumerable expected, string because = "", params object[] becauseArgs)
{
if (expected == null)
{
throw new ArgumentNullException(nameof(expected), "Cannot verify containment against a <null> collection");
}
ICollection<object> expectedObjects = expected.ConvertOrCastToCollection<object>();
if (!expectedObjects.Any())
{
throw new ArgumentException("Cannot verify containment against an empty collection",
nameof(expected));
}
if (ReferenceEquals(Subject, null))
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} to contain {0}{reason}, but found <null>.", expected);
}
if (expected is string)
{
if (!Subject.Cast<object>().Contains(expected))
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} {0} to contain {1}{reason}.", Subject, expected);
}
}
else
{
IEnumerable<object> missingItems = expectedObjects.Except(Subject.Cast<object>());
if (missingItems.Any())
{
if (expectedObjects.Count > 1)
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} {0} to contain {1}{reason}, but could not find {2}.", Subject,
expected, missingItems);
}
else
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} {0} to contain {1}{reason}.", Subject,
expected.Cast<object>().First());
}
}
}
return new AndConstraint<TAssertions>((TAssertions)this);
}
/// <summary>
/// Expects the current collection to contain the specified elements in the exact same order, not necessarily consecutive.
/// using their <see cref="object.Equals(object)" /> implementation.
/// </summary>
/// <param name="expected">An <see cref="IEnumerable"/> with the expected elements.</param>
public AndConstraint<TAssertions> ContainInOrder(params object[] expected)
{
return ContainInOrder(expected, "");
}
/// <summary>
/// Expects the current collection to contain the specified elements in the exact same order, not necessarily consecutive.
/// </summary>
/// <remarks>
/// Elements are compared using their <see cref="object.Equals(object)" /> implementation.
/// </remarks>
/// <param name="expected">An <see cref="IEnumerable"/> with the expected elements.</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<TAssertions> ContainInOrder(IEnumerable expected, string because = "",
params object[] becauseArgs)
{
if (expected == null)
{
throw new ArgumentNullException(nameof(expected), "Cannot verify ordered containment against a <null> collection.");
}
if (ReferenceEquals(Subject, null))
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} to contain {0} in order{reason}, but found <null>.", expected);
}
IList<object> expectedItems = expected.ConvertOrCastToList<object>();
IList<object> actualItems = Subject.ConvertOrCastToList<object>();
for (int index = 0; index < expectedItems.Count; index++)
{
object expectedItem = expectedItems[index];
actualItems = actualItems.SkipWhile(actualItem => !actualItem.IsSameOrEqualTo(expectedItem)).ToArray();
if (actualItems.Any())
{
actualItems = actualItems.Skip(1).ToArray();
}
else
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith(
"Expected {context:collection} {0} to contain items {1} in order{reason}, but {2} (index {3}) did not appear (in the right order).",
Subject, expected, expectedItem, index);
}
}
return new AndConstraint<TAssertions>((TAssertions)this);
}
/// <summary>
/// Expects the current collection to have all elements in ascending order. Elements are compared
/// using their <see cref="IComparable.CompareTo(object)" /> implementation.
/// </summary>
/// <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<TAssertions> BeInAscendingOrder(string because = "", params object[] becauseArgs)
{
return BeInAscendingOrder(Comparer<object>.Default, because, becauseArgs);
}
/// <summary>
/// Expects the current collection to have all elements in ascending order. Elements are compared
/// using the given <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="becauseArgs">
/// Zero or more objects to format using the placeholders in <see cref="because" />.
/// </param>
public AndConstraint<TAssertions> BeInAscendingOrder(IComparer<object> comparer, string because = "", params object[] becauseArgs)
{
return BeInOrder(comparer, SortOrder.Ascending, because, becauseArgs);
}
/// <summary>
/// Expects the current collection to have all elements in descending order. Elements are compared
/// using their <see cref="IComparable.CompareTo(object)" /> implementation.
/// </summary>
/// <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<TAssertions> BeInDescendingOrder(string because = "", params object[] becauseArgs)
{
return BeInDescendingOrder(Comparer<object>.Default, because, becauseArgs);
}
/// <summary>
/// Expects the current collection to have all elements in descending order. Elements are compared
/// using the given <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="becauseArgs">
/// Zero or more objects to format using the placeholders in <see cref="because" />.
/// </param>
public AndConstraint<TAssertions> BeInDescendingOrder(IComparer<object> comparer, string because = "", params object[] becauseArgs)
{
return BeInOrder(comparer, SortOrder.Descending, because, becauseArgs);
}
/// <summary>
/// Expects the current collection to have all elements in the specified <paramref name="expectedOrder"/>.
/// Elements are compared using their <see cref="object.Equals(object)" /> implementation.
/// </summary>
private AndConstraint<TAssertions> BeInOrder(
IComparer<object> comparer, SortOrder expectedOrder, string because = "", params object[] becauseArgs)
{
string sortOrder = (expectedOrder == SortOrder.Ascending) ? "ascending" : "descending";
if (ReferenceEquals(Subject, null))
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} to contain items in " + sortOrder + " order{reason}, but found {1}.",
Subject);
}
IList<object> actualItems = Subject.ConvertOrCastToList<object>();
object[] orderedItems = (expectedOrder == SortOrder.Ascending)
? actualItems.OrderBy(item => item, comparer).ToArray()
: actualItems.OrderByDescending(item => item, comparer).ToArray();
for (int index = 0; index < orderedItems.Length; index++)
{
Execute.Assertion
.ForCondition(actualItems[index].IsSameOrEqualTo(orderedItems[index]))
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} to contain items in " + sortOrder +
" order{reason}, but found {0} where item at index {1} is in wrong order.",
Subject, index);
}
return new AndConstraint<TAssertions>((TAssertions)this);
}
/// <summary>
/// Asserts the current collection does not have all elements in ascending order. Elements are compared
/// using their <see cref="IComparable.CompareTo(object)" /> implementation.
/// </summary>
/// <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<TAssertions> NotBeAscendingInOrder(string because = "", params object[] becauseArgs)
{
return NotBeAscendingInOrder(Comparer<object>.Default, because, becauseArgs);
}
/// <summary>
/// Asserts the current collection does not have all elements in ascending order. Elements are compared
/// using their <see cref="IComparable.CompareTo(object)" /> 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="becauseArgs">
/// Zero or more objects to format using the placeholders in <see cref="because" />.
/// </param>
public AndConstraint<TAssertions> NotBeAscendingInOrder(IComparer<object> comparer, string because = "", params object[] becauseArgs)
{
return NotBeInOrder(comparer, SortOrder.Ascending, because, becauseArgs);
}
/// <summary>
/// Asserts the current collection does not have all elements in descending order. Elements are compared
/// using their <see cref="IComparable.CompareTo(object)" /> implementation.
/// </summary>
/// <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<TAssertions> NotBeDescendingInOrder(string because = "", params object[] becauseArgs)
{
return NotBeDescendingInOrder(Comparer<object>.Default, because, becauseArgs);
}
/// <summary>
/// Asserts the current collection does not have all elements in descending order. Elements are compared
/// using their <see cref="IComparable.CompareTo(object)" /> 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="becauseArgs">
/// Zero or more objects to format using the placeholders in <see cref="because" />.
/// </param>
public AndConstraint<TAssertions> NotBeDescendingInOrder(IComparer<object> comparer, string because = "", params object[] becauseArgs)
{
return NotBeInOrder(comparer, SortOrder.Descending, because, becauseArgs);
}
/// <summary>
/// Asserts the current collection does not have all elements in ascending order. Elements are compared
/// using their <see cref="object.Equals(object)" /> implementation.
/// </summary>
private AndConstraint<TAssertions> NotBeInOrder(IComparer<object> comparer, SortOrder order, string because = "", params object[] becauseArgs)
{
string sortOrder = (order == SortOrder.Ascending) ? "ascending" : "descending";
if (ReferenceEquals(Subject, null))
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith(
"Did not expect {context:collection} to contain items in " + sortOrder + " order{reason}, but found {1}.",
Subject);
}
object[] orderedItems = (order == SortOrder.Ascending)
? Subject.Cast<object>().OrderBy(item => item, comparer).ToArray()
: Subject.Cast<object>().OrderByDescending(item => item, comparer).ToArray();
bool itemsAreUnordered = Subject
.Cast<object>()
.Where((actualItem, index) => !actualItem.IsSameOrEqualTo(orderedItems[index]))
.Any();
if (!itemsAreUnordered)
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith(
"Did not expect {context:collection} to contain items in " + sortOrder + " order{reason}, but found {0}.",
Subject);
}
return new AndConstraint<TAssertions>((TAssertions)this);
}
/// <summary>
/// Asserts that the collection is a subset of the <paramref name="expectedSuperset" />.
/// </summary>
/// <param name="expectedSuperset">An <see cref="IEnumerable"/> with the expected superset.</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<TAssertions> BeSubsetOf(IEnumerable expectedSuperset, string because = "",
params object[] becauseArgs)
{
if (expectedSuperset == null)
{
throw new ArgumentNullException(nameof(expectedSuperset), "Cannot verify a subset against a <null> collection.");
}
if (ReferenceEquals(Subject, null))
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} to be a subset of {0}{reason}, but found {1}.", expectedSuperset,
Subject);
}
IEnumerable<object> expectedItems = expectedSuperset.Cast<object>();
IEnumerable<object> actualItems = Subject.Cast<object>();
IEnumerable<object> excessItems = actualItems.Except(expectedItems);
if (excessItems.Any())
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith(
"Expected {context:collection} to be a subset of {0}{reason}, but items {1} are not part of the superset.",
expectedSuperset, excessItems);
}
return new AndConstraint<TAssertions>((TAssertions)this);
}
/// <summary>
/// Asserts that the collection is not a subset of the <paramref name="unexpectedSuperset" />.
/// </summary>
/// <param name="unexpectedSuperset">An <see cref="IEnumerable"/> with the unexpected superset.</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<TAssertions> NotBeSubsetOf(IEnumerable unexpectedSuperset, string because = "",
params object[] becauseArgs)
{
Execute.Assertion
.ForCondition(!ReferenceEquals(Subject, null))
.BecauseOf(because, becauseArgs)
.FailWith("Cannot assert a <null> collection against a subset.");