forked from assertj/assertj
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Iterables.java
1442 lines (1319 loc) · 71.4 KB
/
Iterables.java
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
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* Copyright 2012-2022 the original author or authors.
*/
package org.assertj.core.internal;
import static java.util.Arrays.stream;
import static java.util.Objects.requireNonNull;
import static java.util.stream.Collectors.toCollection;
import static java.util.stream.Collectors.toList;
import static org.assertj.core.error.AnyElementShouldMatch.anyElementShouldMatch;
import static org.assertj.core.error.ConditionAndGroupGenericParameterTypeShouldBeTheSame.shouldBeSameGenericBetweenIterableAndCondition;
import static org.assertj.core.error.ElementsShouldBe.elementsShouldBe;
import static org.assertj.core.error.ElementsShouldBeAtLeast.elementsShouldBeAtLeast;
import static org.assertj.core.error.ElementsShouldBeAtMost.elementsShouldBeAtMost;
import static org.assertj.core.error.ElementsShouldBeExactly.elementsShouldBeExactly;
import static org.assertj.core.error.ElementsShouldHave.elementsShouldHave;
import static org.assertj.core.error.ElementsShouldHaveAtLeast.elementsShouldHaveAtLeast;
import static org.assertj.core.error.ElementsShouldHaveAtMost.elementsShouldHaveAtMost;
import static org.assertj.core.error.ElementsShouldHaveExactly.elementsShouldHaveExactly;
import static org.assertj.core.error.ElementsShouldMatch.elementsShouldMatch;
import static org.assertj.core.error.ElementsShouldNotBe.elementsShouldNotBe;
import static org.assertj.core.error.ElementsShouldNotHave.elementsShouldNotHave;
import static org.assertj.core.error.ElementsShouldSatisfy.elementsShouldSatisfy;
import static org.assertj.core.error.ElementsShouldSatisfy.elementsShouldSatisfyAny;
import static org.assertj.core.error.ElementsShouldSatisfy.elementsShouldSatisfyExactly;
import static org.assertj.core.error.NoElementsShouldMatch.noElementsShouldMatch;
import static org.assertj.core.error.NoElementsShouldSatisfy.noElementsShouldSatisfy;
import static org.assertj.core.error.ShouldBeEmpty.shouldBeEmpty;
import static org.assertj.core.error.ShouldBeNullOrEmpty.shouldBeNullOrEmpty;
import static org.assertj.core.error.ShouldBeSubsetOf.shouldBeSubsetOf;
import static org.assertj.core.error.ShouldContain.shouldContain;
import static org.assertj.core.error.ShouldContainAnyOf.shouldContainAnyOf;
import static org.assertj.core.error.ShouldContainExactly.shouldContainExactlyWithIndexes;
import static org.assertj.core.error.ShouldContainExactly.shouldContainExactly;
import static org.assertj.core.error.ShouldContainExactlyInAnyOrder.shouldContainExactlyInAnyOrder;
import static org.assertj.core.error.ShouldContainNull.shouldContainNull;
import static org.assertj.core.error.ShouldContainOnly.shouldContainOnly;
import static org.assertj.core.error.ShouldContainOnlyNulls.shouldContainOnlyNulls;
import static org.assertj.core.error.ShouldContainSequence.shouldContainSequence;
import static org.assertj.core.error.ShouldContainSubsequence.actualDoesNotHaveEnoughElementsToContainSubsequence;
import static org.assertj.core.error.ShouldContainSubsequence.shouldContainSubsequence;
import static org.assertj.core.error.ShouldContainsOnlyOnce.shouldContainsOnlyOnce;
import static org.assertj.core.error.ShouldEndWith.shouldEndWith;
import static org.assertj.core.error.ShouldNotBeEmpty.shouldNotBeEmpty;
import static org.assertj.core.error.ShouldNotContain.shouldNotContain;
import static org.assertj.core.error.ShouldNotContainNull.shouldNotContainNull;
import static org.assertj.core.error.ShouldNotContainSequence.shouldNotContainSequence;
import static org.assertj.core.error.ShouldNotContainSubsequence.shouldNotContainSubsequence;
import static org.assertj.core.error.ShouldNotHaveDuplicates.shouldNotHaveDuplicates;
import static org.assertj.core.error.ShouldSatisfy.shouldSatisfyExactlyInAnyOrder;
import static org.assertj.core.error.ShouldSatisfyOnlyOnce.shouldSatisfyOnlyOnce;
import static org.assertj.core.error.ShouldStartWith.shouldStartWith;
import static org.assertj.core.error.ZippedElementsShouldSatisfy.zippedElementsShouldSatisfy;
import static org.assertj.core.internal.Arrays.assertIsArray;
import static org.assertj.core.internal.CommonValidations.checkIsNotNull;
import static org.assertj.core.internal.CommonValidations.checkIsNotNullAndNotEmpty;
import static org.assertj.core.internal.CommonValidations.checkIterableIsNotNull;
import static org.assertj.core.internal.CommonValidations.checkSizeBetween;
import static org.assertj.core.internal.CommonValidations.checkSizeGreaterThan;
import static org.assertj.core.internal.CommonValidations.checkSizeGreaterThanOrEqualTo;
import static org.assertj.core.internal.CommonValidations.checkSizeLessThan;
import static org.assertj.core.internal.CommonValidations.checkSizeLessThanOrEqualTo;
import static org.assertj.core.internal.CommonValidations.checkSizes;
import static org.assertj.core.internal.CommonValidations.failIfEmptySinceActualIsNotEmpty;
import static org.assertj.core.internal.CommonValidations.hasSameSizeAsCheck;
import static org.assertj.core.internal.ErrorMessages.emptySequence;
import static org.assertj.core.internal.ErrorMessages.emptySubsequence;
import static org.assertj.core.internal.ErrorMessages.nullSequence;
import static org.assertj.core.internal.ErrorMessages.nullSubsequence;
import static org.assertj.core.internal.IterableDiff.diff;
import static org.assertj.core.util.Arrays.asList;
import static org.assertj.core.util.Arrays.prepend;
import static org.assertj.core.util.IterableUtil.isNullOrEmpty;
import static org.assertj.core.util.IterableUtil.sizeOf;
import static org.assertj.core.util.Lists.list;
import static org.assertj.core.util.Lists.newArrayList;
import static org.assertj.core.util.Streams.stream;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Deque;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Queue;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Predicate;
import org.assertj.core.api.AssertionInfo;
import org.assertj.core.api.Condition;
import org.assertj.core.configuration.Configuration;
import org.assertj.core.error.UnsatisfiedRequirement;
import org.assertj.core.error.ZippedElementsShouldSatisfy.ZipSatisfyError;
import org.assertj.core.presentation.PredicateDescription;
import org.assertj.core.util.VisibleForTesting;
/**
* Reusable assertions for <code>{@link Iterable}</code>s.
*
* @author Alex Ruiz
* @author Yvonne Wang
* @author Maciej Jaskowski
* @author Nicolas François
* @author Joel Costigliola
* @author Florent Biville
*/
public class Iterables {
private static final Iterables INSTANCE = new Iterables();
private final ComparisonStrategy comparisonStrategy;
@VisibleForTesting
Failures failures = Failures.instance();
@VisibleForTesting
Conditions conditions = Conditions.instance();
@VisibleForTesting
Predicates predicates = Predicates.instance();
/**
* Returns the singleton instance of this class based on {@link StandardComparisonStrategy}.
*
* @return the singleton instance of this class based on {@link StandardComparisonStrategy}.
*/
public static Iterables instance() {
return INSTANCE;
}
@VisibleForTesting
Iterables() {
this(StandardComparisonStrategy.instance());
}
public Iterables(ComparisonStrategy comparisonStrategy) {
this.comparisonStrategy = comparisonStrategy;
}
@VisibleForTesting
public Comparator<?> getComparator() {
if (comparisonStrategy instanceof ComparatorBasedComparisonStrategy) {
return ((ComparatorBasedComparisonStrategy) comparisonStrategy).getComparator();
}
return null;
}
@VisibleForTesting
public ComparisonStrategy getComparisonStrategy() {
return comparisonStrategy;
}
/**
* Asserts that the given <code>{@link Iterable}</code> is {@code null} or empty.
*
* @param info contains information about the assertion.
* @param actual the given {@code Iterable}.
* @throws AssertionError if the given {@code Iterable} is not {@code null} *and* contains one or more elements.
*/
public void assertNullOrEmpty(AssertionInfo info, Iterable<?> actual) {
if (!isNullOrEmpty(actual)) throw failures.failure(info, shouldBeNullOrEmpty(actual));
}
/**
* Asserts that the given {@code Iterable} is empty.
*
* @param info contains information about the assertion.
* @param actual the given {@code Iterable}.
* @throws AssertionError if the given {@code Iterable} is {@code null}.
* @throws AssertionError if the given {@code Iterable} is not empty.
*/
public void assertEmpty(AssertionInfo info, Iterable<?> actual) {
assertNotNull(info, actual);
if (!isNullOrEmpty(actual)) throw failures.failure(info, shouldBeEmpty(actual));
}
/**
* Asserts that the given {@code Iterable} is not empty.
*
* @param info contains information about the assertion.
* @param actual the given {@code Iterable}.
* @throws AssertionError if the given {@code Iterable} is {@code null}.
* @throws AssertionError if the given {@code Iterable} is empty.
*/
public void assertNotEmpty(AssertionInfo info, Iterable<?> actual) {
assertNotNull(info, actual);
if (isNullOrEmpty(actual)) throw failures.failure(info, shouldNotBeEmpty());
}
/**
* Asserts that the number of elements in the given {@code Iterable} is equal to the expected one.
*
* @param info contains information about the assertion.
* @param actual the given {@code Iterable}.
* @param expectedSize the expected size of {@code actual}.
* @throws AssertionError if the given {@code Iterable} is {@code null}.
* @throws AssertionError if the number of elements in the given {@code Iterable} is different than the expected one.
*/
public void assertHasSize(AssertionInfo info, Iterable<?> actual, int expectedSize) {
assertNotNull(info, actual);
checkSizes(actual, sizeOf(actual), expectedSize, info);
}
/**
* Asserts that the unique element of the {@link Iterable} satisfies the given assertions expressed as a {@link Consumer},
*
* @param <T> the type of elements in actual.
* @param info contains information about the assertion.
* @param actual the given {@code Iterable}.
* @param consumer the given requirements.
* @throws AssertionError if the {@link Iterable} does not have a unique element.
* @throws AssertionError if the {@link Iterable}'s unique element does not satisfies the given assertions.
*/
public <T> void assertHasOnlyOneElementSatisfying(AssertionInfo info, Iterable<? extends T> actual,
Consumer<? super T> consumer) {
assertHasSize(info, actual, 1);
consumer.accept(actual.iterator().next());
}
/**
* Asserts that the number of elements in the given {@code Iterable} is greater than the boundary.
*
* @param info contains information about the assertion.
* @param actual the given {@code Iterable}.
* @param boundary the given value to compare the size of {@code actual} to.
* @throws AssertionError if the given {@code Iterable} is {@code null}.
* @throws AssertionError if the number of elements in the given {@code Iterable} is greater than the boundary.
*/
public void assertHasSizeGreaterThan(AssertionInfo info, Iterable<?> actual, int boundary) {
assertNotNull(info, actual);
checkSizeGreaterThan(actual, boundary, sizeOf(actual), info);
}
/**
* Asserts that the number of elements in the given {@code Iterable} is greater than or equal to the boundary.
*
* @param info contains information about the assertion.
* @param actual the given {@code Iterable}.
* @param boundary the given value to compare the size of {@code actual} to.
* @throws AssertionError if the given {@code Iterable} is {@code null}.
* @throws AssertionError if the number of elements in the given {@code Iterable} is greater than or equal to the boundary.
*/
public void assertHasSizeGreaterThanOrEqualTo(AssertionInfo info, Iterable<?> actual, int boundary) {
assertNotNull(info, actual);
checkSizeGreaterThanOrEqualTo(actual, boundary, sizeOf(actual), info);
}
/**
* Asserts that the number of elements in the given {@code Iterable} is less than the boundary.
*
* @param info contains information about the assertion.
* @param actual the given {@code Iterable}.
* @param boundary the given value to compare the size of {@code actual} to.
* @throws AssertionError if the given {@code Iterable} is {@code null}.
* @throws AssertionError if the number of elements in the given {@code Iterable} is less than the expected one.
*/
public void assertHasSizeLessThan(AssertionInfo info, Iterable<?> actual, int boundary) {
assertNotNull(info, actual);
checkSizeLessThan(actual, boundary, sizeOf(actual), info);
}
/**
* Asserts that the number of elements in the given {@code Iterable} is less than or equal to the boundary.
*
* @param info contains information about the assertion.
* @param actual the given {@code Iterable}.
* @param boundary the given value to compare the size of {@code actual} to.
* @throws AssertionError if the given {@code Iterable} is {@code null}.
* @throws AssertionError if the number of elements in the given {@code Iterable} is less than or equal to the boundary.
*/
public void assertHasSizeLessThanOrEqualTo(AssertionInfo info, Iterable<?> actual, int boundary) {
assertNotNull(info, actual);
checkSizeLessThanOrEqualTo(actual, boundary, sizeOf(actual), info);
}
/**
* Asserts that the number of elements in the given {@code Iterable} is between the given lower and higher boundary (inclusive).
*
* @param info contains information about the assertion.
* @param actual the given {@code Iterable}.
* @param lowerBoundary the lower boundary compared to which actual size should be greater than or equal to.
* @param higherBoundary the higher boundary compared to which actual size should be less than or equal to.
* @throws AssertionError if the given array is {@code null}.
* @throws AssertionError if the number of elements in the given array is not between the boundaries.
*/
public void assertHasSizeBetween(AssertionInfo info, Iterable<?> actual, int lowerBoundary, int higherBoundary) {
assertNotNull(info, actual);
checkSizeBetween(actual, lowerBoundary, higherBoundary, sizeOf(actual), info);
}
/**
* Assert that the actual {@code Iterable} has the same size as the other array.
*
* @param info contains information about the assertion.
* @param actual the given {@code Iterable}.
* @param other the given array to compare.
* @throws AssertionError if the actual group is {@code null}.
* @throws AssertionError if the other group is {@code null}.
* @throws AssertionError if actual {@code Iterable} and other array don't have the same size.
*/
public void assertHasSameSizeAs(AssertionInfo info, Iterable<?> actual, Object other) {
assertNotNull(info, actual);
assertIsArray(info, other);
hasSameSizeAsCheck(info, actual, other, sizeOf(actual));
}
/**
* Assert that the actual {@code Iterable} has the same size as the other {@code Iterable}.
*
* @param info contains information about the assertion.
* @param actual the given {@code Iterable}.
* @param other the given {@code Iterable}.
* @throws AssertionError if the actual group is {@code null}.
* @throws AssertionError if the other group is {@code null}.
* @throws AssertionError if actual and other {@code Iterable} don't have the same size.
*/
public void assertHasSameSizeAs(AssertionInfo info, Iterable<?> actual, Iterable<?> other) {
assertNotNull(info, actual);
hasSameSizeAsCheck(info, actual, other, sizeOf(actual));
}
/**
* Asserts that the given {@code Iterable} contains the given values, in any order.
*
* @param info contains information about the assertion.
* @param actual the given {@code Iterable}.
* @param values the values that are expected to be in the given {@code Iterable}.
* @throws NullPointerException if the array of values is {@code null}.
* @throws IllegalArgumentException if the array of values is empty.
* @throws AssertionError if the given {@code Iterable} is {@code null}.
* @throws AssertionError if the given {@code Iterable} does not contain the given values.
*/
public void assertContains(AssertionInfo info, Iterable<?> actual, Object[] values) {
final List<?> actualAsList = newArrayList(actual);
if (commonCheckThatIterableAssertionSucceeds(info, actualAsList, values)) return;
// check for elements in values that are missing in actual.
assertIterableContainsGivenValues(actual.getClass(), actualAsList, values, info);
}
private void assertIterableContainsGivenValues(@SuppressWarnings("rawtypes") Class<? extends Iterable> clazz,
Iterable<?> actual, Object[] values, AssertionInfo info) {
Set<Object> notFound = stream(values).filter(value -> !iterableContains(actual, value))
.collect(toCollection(LinkedHashSet::new));
if (notFound.isEmpty())
return;
throw failures.failure(info, shouldContain(clazz, actual, values, notFound, comparisonStrategy));
}
private boolean iterableContains(Iterable<?> actual, Object value) {
return comparisonStrategy.iterableContains(actual, value);
}
private void iterablesRemoveFirst(Iterable<?> actual, Object value) {
comparisonStrategy.iterablesRemoveFirst(actual, value);
}
private void iterablesRemove(Iterable<?> actual, Object value) {
comparisonStrategy.iterableRemoves(actual, value);
}
/**
* Asserts that the given {@code Iterable} contains only the given values and nothing else, in any order.
*
* @param info contains information about the assertion.
* @param actual the given {@code Iterable}.
* @param expectedValues the values that are expected to be in the given {@code Iterable}.
* @throws NullPointerException if the array of values is {@code null}.
* @throws IllegalArgumentException if the array of values is empty.
* @throws AssertionError if the given {@code Iterable} is {@code null}.
* @throws AssertionError if the given {@code Iterable} does not contain the given values or if the given
* {@code Iterable} contains values that are not in the given array.
*/
public void assertContainsOnly(AssertionInfo info, Iterable<?> actual, Object[] expectedValues) {
final List<?> actualAsList = newArrayList(actual);
// don't use commonCheckThatIterableAssertionSucceeds to get a better error message when actual is not empty and
// expectedValues is
checkNotNullIterables(info, actualAsList, expectedValues);
// if both actual and values are empty, then assertion passes.
if (actualAsList.isEmpty() && expectedValues.length == 0) return;
// after the for loop, unexpected = expectedValues - actual
List<Object> unexpectedValues = newArrayList(actualAsList);
// after the for loop, missing = actual - expectedValues
List<Object> missingValues = newArrayList(expectedValues);
for (Object expected : expectedValues) {
if (iterableContains(actualAsList, expected)) {
// since expected was found in actual:
// -- it does not belong to the missing elements
iterablesRemove(missingValues, expected);
// -- it does not belong to the unexpected elements
iterablesRemove(unexpectedValues, expected);
}
}
if (!unexpectedValues.isEmpty() || !missingValues.isEmpty()) {
throw failures.failure(info, shouldContainOnly(actualAsList, expectedValues,
missingValues, unexpectedValues,
comparisonStrategy));
}
}
/**
* Asserts that the given {@code Iterable} contains the given values and only once.
*
* @param info contains information about the assertion.
* @param actual the given {@code Iterable}.
* @param values the values that are expected to be in the given {@code Iterable}.
* @throws NullPointerException if the array of values is {@code null}.
* @throws IllegalArgumentException if the array of values is empty.
* @throws AssertionError if the given {@code Iterable} is {@code null}.
* @throws AssertionError if the given {@code Iterable} does not contain the given values or if the given
* {@code Iterable} contains values that are not in the given array.
*/
public void assertContainsOnlyOnce(AssertionInfo info, Iterable<?> actual, Object[] values) {
if (commonCheckThatIterableAssertionSucceeds(info, actual, values)) return;
// check for elements in values that are missing in actual.
Set<Object> notFound = new LinkedHashSet<>();
Set<Object> notOnlyOnce = new LinkedHashSet<>();
Iterable<?> actualDuplicates = comparisonStrategy.duplicatesFrom(actual);
for (Object expectedOnlyOnce : values) {
if (!iterableContains(actual, expectedOnlyOnce)) {
notFound.add(expectedOnlyOnce);
} else if (iterableContains(actualDuplicates, expectedOnlyOnce)) {
notOnlyOnce.add(expectedOnlyOnce);
}
}
if (!notFound.isEmpty() || !notOnlyOnce.isEmpty())
throw failures.failure(info, shouldContainsOnlyOnce(actual, values, notFound, notOnlyOnce, comparisonStrategy));
// assertion succeeded
}
/**
* Asserts that the given {@code Iterable} contains only null elements and nothing else.
*
* @param info contains information about the assertion.
* @param actual the given {@code Iterable}.
* @throws AssertionError if the given {@code Iterable} is {@code null}.
* @throws AssertionError if the given {@code Iterable} does not contain at least a null element or if the given
* {@code Iterable} contains values that are not null elements.
*/
public void assertContainsOnlyNulls(AssertionInfo info, Iterable<?> actual) {
assertNotNull(info, actual);
// empty => no null elements => failure
if (sizeOf(actual) == 0) throw failures.failure(info, shouldContainOnlyNulls(actual));
// look for any non null elements
List<Object> nonNullElements = stream(actual).filter(java.util.Objects::nonNull).collect(toList());
if (nonNullElements.size() > 0) throw failures.failure(info, shouldContainOnlyNulls(actual, nonNullElements));
}
/**
* Verifies that the given <code>{@link Iterable}</code> contains the given sequence of objects, without any other
* objects between them.
*
* @param info contains information about the assertion.
* @param actual the given {@code Iterable}.
* @param sequence the sequence of objects to look for.
* @throws AssertionError if the given {@code Iterable} is {@code null}.
* @throws NullPointerException if the given sequence is {@code null}.
* @throws IllegalArgumentException if the given sequence is empty.
* @throws AssertionError if the given {@code Iterable} does not contain the given sequence of objects.
*/
public void assertContainsSequence(AssertionInfo info, Iterable<?> actual, Object[] sequence) {
// perform the checks that would have been done in commonCheckThatIterableAssertionSucceeds but do them explicitly without
// having to create a new iterator on actual - which would break if actual were only singly-traversable.
checkNotNullIterables(info, actual, sequence);
// store the elements from actual that have been visited (because we don't know we can look ahead - the 'actual'
// might be singly-traversable) in a fixed-length LIFO having what is in effect a sliding window.
// So we store each element and slide for each new element until a match is found or until the 'actual' is
// exhausted. Of course if 'actual' really is infinite then this could take a while :-D
final Iterator<?> actualIterator = actual.iterator();
if (!actualIterator.hasNext() && sequence.length == 0) return;
failIfEmptySinceActualIsNotEmpty(sequence);
// we only store sequence.length entries from actual in the LIFO, no need for more.
Lifo lifo = new Lifo(sequence.length);
while (actualIterator.hasNext()) {
lifo.add(actualIterator.next());
if (lifo.matchesExactly(sequence)) return;
}
throw actualDoesNotContainSequence(info, actual, sequence);
}
private class Lifo {
private int maxSize;
private LinkedList<Object> stack;
Lifo(int maxSize) {
this.maxSize = maxSize;
stack = new LinkedList<>();
}
void add(final Object element) {
if (stack.size() == maxSize) stack.removeFirst();
stack.addLast(element);
}
boolean matchesExactly(Object[] sequence) {
if (stack.size() != sequence.length) return false;
for (int i = 0; i < sequence.length; i++) {
if (!areEqual(stack.get(i), sequence[i])) return false;
}
return true;
}
}
/**
* Verifies that the given <code>{@link Iterable}</code> does not contain the given sequence of objects in order.
*
* @param info contains information about the assertion.
* @param actual the given {@code Iterable}.
* @param sequence the sequence of objects to look for.
* @throws AssertionError if the given {@code Iterable} is {@code null}.
* @throws NullPointerException if the given sequence is {@code null}.
* @throws IllegalArgumentException if the given sequence is empty.
* @throws AssertionError if the given {@code Iterable} does contain the given sequence of objects.
*/
public void assertDoesNotContainSequence(AssertionInfo info, Iterable<?> actual, Object[] sequence) {
requireNonNull(sequence, nullSequence());
checkIsNotEmptySequence(sequence);
assertNotNull(info, actual);
// check for elements in values that are missing in actual.
List<?> actualAsList = newArrayList(actual);
for (int index = 0; index < actualAsList.size(); index++) {
// look for given sequence in actual starting from current index (i)
if (containsSequenceAtGivenIndex(actualAsList, sequence, index)) {
throw actualDoesContainSequence(info, actual, sequence, index);
}
}
}
/**
* Verifies that the given <code>{@link Iterable}</code> contains the given subsequence of objects (possibly with
* other values between them).
*
* @param info contains information about the assertion.
* @param actual the given {@code Iterable}.
* @param subsequence the subsequence of objects to look for.
* @throws AssertionError if the given {@code Iterable} is {@code null}.
* @throws NullPointerException if the given sequence is {@code null}.
* @throws IllegalArgumentException if the given subsequence is empty.
* @throws AssertionError if the given {@code Iterable} does not contain the given subsequence of objects.
*/
public void assertContainsSubsequence(AssertionInfo info, Iterable<?> actual, Object[] subsequence) {
if (commonCheckThatIterableAssertionSucceeds(info, actual, subsequence)) return;
if (sizeOf(actual) < subsequence.length) {
throw failures.failure(info, actualDoesNotHaveEnoughElementsToContainSubsequence(actual, subsequence));
}
Iterator<?> actualIterator = actual.iterator();
int subsequenceIndex = 0;
while (actualIterator.hasNext() && subsequenceIndex < subsequence.length) {
Object actualNext = actualIterator.next();
Object subsequenceNext = subsequence[subsequenceIndex];
if (areEqual(actualNext, subsequenceNext)) subsequenceIndex++;
}
if (subsequenceIndex < subsequence.length) throw actualDoesNotContainSubsequence(info, actual, subsequence, subsequenceIndex);
}
/**
* Verifies that the given <code>{@link Iterable}</code> does not contain the given subsequence of objects (possibly
* with other values between them).
*
* @param info contains information about the assertion.
* @param actual the given {@code Iterable}.
* @param subsequence the subsequence of objects to look for.
* @throws AssertionError if the given {@code Iterable} is {@code null}.
* @throws NullPointerException if the given sequence is {@code null}.
* @throws IllegalArgumentException if the given subsequence is empty.
* @throws AssertionError if the given {@code Iterable} contains the given subsequence of objects.
*/
public void assertDoesNotContainSubsequence(AssertionInfo info, Iterable<?> actual, Object[] subsequence) {
requireNonNull(subsequence, nullSubsequence());
checkIsNotEmptySubsequence(subsequence);
assertNotNull(info, actual);
int subsequenceIndex = 0;
int subsequenceStartIndex = 0;
List<?> actualAsList = newArrayList(actual);
for (int index = 0; index < actualAsList.size(); index++) {
Object actualNext = actualAsList.get(index);
Object subsequenceNext = subsequence[subsequenceIndex];
if (areEqual(actualNext, subsequenceNext)) {
if (subsequenceIndex == 0) subsequenceStartIndex = index;
subsequenceIndex++;
}
if (subsequenceIndex == subsequence.length) {
throw actualContainsSubsequence(info, actual, subsequence, subsequenceStartIndex);
}
}
}
/**
* Verifies that the actual <code>Iterable</code> is a subset of values <code>Iterable</code>. <br>
* Both actual and given iterable are treated as sets, therefore duplicates on either of them are ignored.
*
* @param info contains information about the assertion.
* @param actual the actual {@code Iterable}.
* @param values the {@code Iterable} that should contain all actual elements.
* @throws AssertionError if the actual {@code Iterable} is {@code null}.
* @throws NullPointerException if the given Iterable is {@code null}.
* @throws AssertionError if the actual {@code Iterable} is not subset of set <code>{@link Iterable}</code>
*/
public void assertIsSubsetOf(AssertionInfo info, Iterable<?> actual, Iterable<?> values) {
assertNotNull(info, actual);
checkIterableIsNotNull(values);
List<Object> extra = stream(actual).filter(actualElement -> !iterableContains(values, actualElement))
.collect(toList());
if (extra.size() > 0) throw failures.failure(info, shouldBeSubsetOf(actual, values, extra, comparisonStrategy));
}
/**
* Return true if actualAsList contains exactly the given sequence at given starting index, false otherwise.
*
* @param actualAsList the list to look sequence in
* @param sequence the sequence to look for
* @param startingIndex the index of actual list at which we start looking for sequence.
* @return true if actualAsList contains exactly the given sequence at given starting index, false otherwise.
*/
private boolean containsSequenceAtGivenIndex(List<?> actualAsList, Object[] sequence, int startingIndex) {
// check that, starting from given index, actualAsList has enough remaining elements to contain sequence
if (actualAsList.size() - startingIndex < sequence.length) return false;
for (int i = 0; i < sequence.length; i++) {
if (!areEqual(actualAsList.get(startingIndex + i), sequence[i])) return false;
}
return true;
}
private boolean areEqual(Object actual, Object other) {
return comparisonStrategy.areEqual(actual, other);
}
private AssertionError actualDoesNotContainSequence(AssertionInfo info, Iterable<?> actual, Object[] sequence) {
return failures.failure(info, shouldContainSequence(actual, sequence, comparisonStrategy));
}
private AssertionError actualDoesContainSequence(AssertionInfo info, Iterable<?> actual, Object[] sequence, int index) {
return failures.failure(info, shouldNotContainSequence(actual, sequence, index, comparisonStrategy));
}
private AssertionError actualDoesNotContainSubsequence(AssertionInfo info, Iterable<?> actual, Object[] subsequence,
int subsequenceIndex) {
return failures.failure(info, shouldContainSubsequence(actual, subsequence, subsequenceIndex, comparisonStrategy));
}
private AssertionError actualContainsSubsequence(AssertionInfo info, Iterable<?> actual, Object[] subsequence,
int index) {
return failures.failure(info, shouldNotContainSubsequence(actual, subsequence, comparisonStrategy, index));
}
/**
* Asserts that the given {@code Iterable} does not contain the given values.
*
* @param info contains information about the assertion.
* @param actual the given {@code Iterable}.
* @param values the values that are expected not to be in the given {@code Iterable}.
* @throws NullPointerException if the array of values is {@code null}.
* @throws IllegalArgumentException if the array of values is empty.
* @throws AssertionError if the given {@code Iterable} is {@code null}.
* @throws AssertionError if the given {@code Iterable} contains any of given values.
*/
public void assertDoesNotContain(AssertionInfo info, Iterable<?> actual, Object[] values) {
checkIsNotNullAndNotEmpty(values);
assertNotNull(info, actual);
Set<Object> found = new LinkedHashSet<>();
for (Object o : values) {
if (iterableContains(actual, o)) found.add(o);
}
if (!found.isEmpty()) throw failures.failure(info, shouldNotContain(actual, values, found, comparisonStrategy));
}
/**
* Asserts that the given {@code Iterable} does not contain the given values.
*
* @param <T> the type of actual elements
* @param info contains information about the assertion.
* @param actual the given {@code Iterable}.
* @param iterable the values that are expected not to be in the given {@code Iterable}.
* @throws NullPointerException if the array of values is {@code null}.
* @throws IllegalArgumentException if the array of values is empty.
* @throws AssertionError if the given {@code Iterable} is {@code null}.
* @throws AssertionError if the given {@code Iterable} contains any of given values.
*/
public <T> void assertDoesNotContainAnyElementsOf(AssertionInfo info, Iterable<? extends T> actual,
Iterable<? extends T> iterable) {
checkIsNotNullAndNotEmpty(iterable);
List<T> values = newArrayList(iterable);
assertDoesNotContain(info, actual, values.toArray());
}
/**
* Asserts that the given {@code Iterable} does not have duplicate values.
*
* @param info contains information about the assertion.
* @param actual the given {@code Iterable}.
* @throws NullPointerException if the array of values is {@code null}.
* @throws IllegalArgumentException if the array of values is empty.
* @throws AssertionError if the given {@code Iterable} is {@code null}.
* @throws AssertionError if the given {@code Iterable} contains duplicate values.
*/
public void assertDoesNotHaveDuplicates(AssertionInfo info, Iterable<?> actual) {
assertNotNull(info, actual);
Iterable<?> duplicates = comparisonStrategy.duplicatesFrom(actual);
if (!isNullOrEmpty(duplicates))
throw failures.failure(info, shouldNotHaveDuplicates(actual, duplicates, comparisonStrategy));
}
/**
* Verifies that the given {@code Iterable} starts with the given sequence of objects, without any other objects
* between them. Similar to <code>{@link #assertContainsSequence(AssertionInfo, Iterable, Object[])}</code>, but it
* also verifies that the first element in the sequence is also the first element of the given {@code Iterable}.
*
* @param info contains information about the assertion.
* @param actual the given {@code Iterable}.
* @param sequence the sequence of objects to look for.
* @throws NullPointerException if the given argument is {@code null}.
* @throws IllegalArgumentException if the given argument is an empty array.
* @throws AssertionError if the given {@code Iterable} is {@code null}.
* @throws AssertionError if the given {@code Iterable} does not start with the given sequence of objects.
*/
public void assertStartsWith(AssertionInfo info, Iterable<?> actual, Object[] sequence) {
if (commonCheckThatIterableAssertionSucceeds(info, actual, sequence)) return;
int i = 0;
for (Object actualCurrentElement : actual) {
if (i >= sequence.length) break;
if (areEqual(actualCurrentElement, sequence[i++])) continue;
throw actualDoesNotStartWithSequence(info, actual, sequence);
}
if (sequence.length > i) {
// sequence has more elements than actual
throw actualDoesNotStartWithSequence(info, actual, sequence);
}
}
private AssertionError actualDoesNotStartWithSequence(AssertionInfo info, Iterable<?> actual, Object[] sequence) {
return failures.failure(info, shouldStartWith(actual, sequence, comparisonStrategy));
}
/**
* Verifies that the given {@code Iterable} ends with the given sequence of objects, without any other objects between
* them. Similar to <code>{@link #assertContainsSequence(AssertionInfo, Iterable, Object[])}</code>, but it also
* verifies that the last element in the sequence is also the last element of the given {@code Iterable}.
*
* @param info contains information about the assertion.
* @param actual the given {@code Iterable}.
* @param first the first element of the end sequence.
* @param rest the optional next elements of the end sequence.
* @throws NullPointerException if the given argument is {@code null}.
* @throws IllegalArgumentException if the given argument is an empty array.
* @throws AssertionError if the given {@code Iterable} is {@code null}.
* @throws AssertionError if the given {@code Iterable} does not end with the given sequence of objects.
*/
public void assertEndsWith(AssertionInfo info, Iterable<?> actual, Object first, Object[] rest) {
Object[] sequence = prepend(first, rest);
assertEndsWith(info, actual, sequence);
}
/**
* Verifies that the given {@code Iterable} ends with the given sequence of objects, without any other objects between
* them. Similar to <code>{@link #assertContainsSequence(AssertionInfo, Iterable, Object[])}</code>, but it also
* verifies that the last element in the sequence is also the last element of the given {@code Iterable}.
*
* @param info contains information about the assertion.
* @param actual the given {@code Iterable}.
* @param sequence the sequence of objects to look for.
* @throws NullPointerException if the given argument is {@code null}.
* @throws IllegalArgumentException if the given argument is an empty array.
* @throws AssertionError if the given {@code Iterable} is {@code null}.
* @throws AssertionError if the given {@code Iterable} does not end with the given sequence of objects.
*/
public void assertEndsWith(AssertionInfo info, Iterable<?> actual, Object[] sequence) {
checkNotNullIterables(info, actual, sequence);
int sizeOfActual = sizeOf(actual);
if (sizeOfActual < sequence.length) throw actualDoesNotEndWithSequence(info, actual, sequence);
int start = sizeOfActual - sequence.length;
int sequenceIndex = 0, indexOfActual = 0;
for (Object actualElement : actual) {
if (indexOfActual++ < start) continue;
if (areEqual(actualElement, sequence[sequenceIndex++])) continue;
throw actualDoesNotEndWithSequence(info, actual, sequence);
}
}
private boolean commonCheckThatIterableAssertionSucceeds(AssertionInfo info, Iterable<?> actual, Object[] sequence) {
checkNotNullIterables(info, actual, sequence);
// if both actual and values are empty, then assertion passes.
if (!actual.iterator().hasNext() && sequence.length == 0) return true;
failIfEmptySinceActualIsNotEmpty(sequence);
return false;
}
private void checkNotNullIterables(AssertionInfo info, Iterable<?> actual, Object[] sequence) {
checkIsNotNull(sequence);
assertNotNull(info, actual);
}
/**
* Asserts that the given {@code Iterable} contains at least a null element.
*
* @param info contains information about the assertion.
* @param actual the given {@code Iterable}.
* @throws AssertionError if the given {@code Iterable} is {@code null}.
* @throws AssertionError if the given {@code Iterable} does not contain at least a null element.
*/
public void assertContainsNull(AssertionInfo info, Iterable<?> actual) {
assertNotNull(info, actual);
if (!iterableContains(actual, null)) throw failures.failure(info, shouldContainNull(actual));
}
/**
* Asserts that the given {@code Iterable} does not contain null elements.
*
* @param info contains information about the assertion.
* @param actual the given {@code Iterable}.
* @throws AssertionError if the given {@code Iterable} is {@code null}.
* @throws AssertionError if the given {@code Iterable} contains a null element.
*/
public void assertDoesNotContainNull(AssertionInfo info, Iterable<?> actual) {
assertNotNull(info, actual);
if (iterableContains(actual, null)) throw failures.failure(info, shouldNotContainNull(actual));
}
/**
* Assert that each element of given {@code Iterable} satisfies the given condition.
*
* @param <T> the type of actual elements
* @param info contains information about the assertion.
* @param actual the given {@code Iterable}.
* @param condition the given {@code Condition}.
* @throws NullPointerException if the given condition is {@code null}.
* @throws AssertionError if an element cannot be cast to T.
* @throws AssertionError if one or more elements do not satisfy the given condition.
*/
public <T> void assertAre(AssertionInfo info, Iterable<? extends T> actual, Condition<? super T> condition) {
assertNotNull(info, actual);
conditions.assertIsNotNull(condition);
try {
List<T> notSatisfiesCondition = notSatisfyingCondition(actual, condition);
if (!notSatisfiesCondition.isEmpty())
throw failures.failure(info, elementsShouldBe(actual, notSatisfiesCondition, condition));
} catch (ClassCastException e) {
throw failures.failure(info, shouldBeSameGenericBetweenIterableAndCondition(actual, condition));
}
}
/**
* Assert that each element of given {@code Iterable} not satisfies the given condition.
*
* @param <E> the type of actual elements
* @param info contains information about the assertion.
* @param actual the given {@code Iterable}.
* @param condition the given {@code Condition}.
* @throws NullPointerException if the given condition is {@code null}.
* @throws AssertionError if an element cannot be cast to E.
* @throws AssertionError if one or more elements satisfy the given condition.
*/
public <E> void assertAreNot(AssertionInfo info, Iterable<? extends E> actual, Condition<? super E> condition) {
assertNotNull(info, actual);
conditions.assertIsNotNull(condition);
try {
List<E> satisfiesCondition = satisfiesCondition(actual, condition);
if (!satisfiesCondition.isEmpty())
throw failures.failure(info, elementsShouldNotBe(actual, satisfiesCondition, condition));
} catch (ClassCastException e) {
throw failures.failure(info, shouldBeSameGenericBetweenIterableAndCondition(actual, condition));
}
}
/**
* Assert that each element of given {@code Iterable} satisfies the given condition.
*
* @param <E> the type of actual elements
* @param info contains information about the assertion.
* @param actual the given {@code Iterable}.
* @param condition the given {@code Condition}.
* @throws NullPointerException if the given condition is {@code null}.
* @throws AssertionError if an element cannot be cast to E.
* @throws AssertionError if one or more elements do not satisfy the given condition.
*/
public <E> void assertHave(AssertionInfo info, Iterable<? extends E> actual, Condition<? super E> condition) {
assertNotNull(info, actual);
conditions.assertIsNotNull(condition);
try {
List<E> notSatisfiesCondition = notSatisfyingCondition(actual, condition);
if (!notSatisfiesCondition.isEmpty())
throw failures.failure(info, elementsShouldHave(actual, notSatisfiesCondition, condition));
} catch (ClassCastException e) {
throw failures.failure(info, shouldBeSameGenericBetweenIterableAndCondition(actual, condition));
}
}
/**
* Assert that each element of given {@code Iterable} not satisfies the given condition.
*
* @param <E> the type of actual elements
* @param info contains information about the assertion.
* @param actual the given {@code Iterable}.
* @param condition the given {@code Condition}.
* @throws NullPointerException if the given condition is {@code null}.
* @throws AssertionError if an element cannot be cast to E.
* @throws AssertionError if one or more elements satisfy the given condition.
*/
public <E> void assertDoNotHave(AssertionInfo info, Iterable<? extends E> actual, Condition<? super E> condition) {
assertNotNull(info, actual);
conditions.assertIsNotNull(condition);
try {
List<E> satisfiesCondition = satisfiesCondition(actual, condition);
if (!satisfiesCondition.isEmpty())
throw failures.failure(info, elementsShouldNotHave(actual, satisfiesCondition, condition));
} catch (ClassCastException e) {
throw failures.failure(info, shouldBeSameGenericBetweenIterableAndCondition(actual, condition));
}
}
/**
* Assert that there are <b>at least</b> <i>n</i> elements in the actual {@code Iterable} satisfying the given
* condition.
*
* @param <E> the type of actual elements
* @param info contains information about the assertion.
* @param actual the given {@code Iterable}.
* @param times the minimum number of times the condition should be verified.
* @param condition the given {@code Condition}.
* @throws NullPointerException if the given condition is {@code null}.
* @throws AssertionError if an element cannot be cast to E.
* @throws AssertionError if the number of elements satisfying the given condition is < n.
*/
public <E> void assertAreAtLeast(AssertionInfo info, Iterable<? extends E> actual, int times,
Condition<? super E> condition) {
assertNotNull(info, actual);
conditions.assertIsNotNull(condition);
try {
if (!conditionIsSatisfiedAtLeastNTimes(actual, times, condition))
throw failures.failure(info, elementsShouldBeAtLeast(actual, times, condition));
} catch (ClassCastException e) {
throw failures.failure(info, shouldBeSameGenericBetweenIterableAndCondition(actual, condition));
}
}
private <E> boolean conditionIsSatisfiedAtLeastNTimes(Iterable<? extends E> actual, int n,
Condition<? super E> condition) {
List<E> satisfiesCondition = satisfiesCondition(actual, condition);
return satisfiesCondition.size() >= n;
}
/**
* Assert that there are <b>at most</b> <i>n</i> elements in the actual {@code Iterable} satisfying the given
* condition.
*
* @param <E> the type of actual elements
* @param info contains information about the assertion.
* @param actual the given {@code Iterable}.
* @param n the number of times the condition should be at most verified.
* @param condition the given {@code Condition}.
* @throws NullPointerException if the given condition is {@code null}.
* @throws AssertionError if an element cannot be cast to E.
* @throws AssertionError if the number of elements satisfying the given condition is > n.
*/
public <E> void assertAreAtMost(AssertionInfo info, Iterable<? extends E> actual, int n,
Condition<? super E> condition) {
assertNotNull(info, actual);
conditions.assertIsNotNull(condition);
try {
if (!conditionIsSatisfiedAtMostNTimes(actual, condition, n))
throw failures.failure(info, elementsShouldBeAtMost(actual, n, condition));
} catch (ClassCastException e) {
throw failures.failure(info, shouldBeSameGenericBetweenIterableAndCondition(actual, condition));
}
}
private <E> boolean conditionIsSatisfiedAtMostNTimes(Iterable<? extends E> actual, Condition<? super E> condition,
int n) {
List<E> satisfiesCondition = satisfiesCondition(actual, condition);
return satisfiesCondition.size() <= n;
}
/**
* Verifies that there are <b>exactly</b> <i>n</i> elements in the actual {@code Iterable} satisfying the given
* condition.
*
* @param <E> the type of actual elements
* @param info contains information about the assertion.
* @param actual the given {@code Iterable}.
* @param times the exact number of times the condition should be verified.
* @param condition the given {@code Condition}.
* @throws NullPointerException if the given condition is {@code null}.