/
That.java
752 lines (670 loc) · 22.7 KB
/
That.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
package io.immutables.that;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.function.DoublePredicate;
import java.util.function.IntPredicate;
import java.util.function.LongPredicate;
import java.util.function.Predicate;
import java.util.regex.PatternSyntaxException;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import javax.annotation.Nullable;
/**
* Wrapper around test subject providing assertion check methods.
* @see Assert
* @see That.Condition
* @see That.Object
* @see That.Runnable
* @see That.Iterable
* @see That.Optional
* @see That.String
* @see That.Int
* @see That.Long
* @see That.Double
* @see That.Boolean
* @param <T> object under test type
* @param <S> matcher type
*/
public interface That<T, S extends That<T, S>> {
/**
* This is not a matcher method. Always throws {@link UnsupportedOperationException}.
* @deprecated Use {@link Object#equalTo(java.lang.Object)} instead.
*/
@Deprecated
@Override
boolean equals(java.lang.Object obj);
/**
* This is not a matcher method. Always throws {@link UnsupportedOperationException}.
* @deprecated don't use this method.
*/
@Deprecated
@Override
int hashCode();
/**
* Turns any matcher into a plain object matcher. If some matcher (like {@link That.Iterable})
* streamlines matchers for iterable types, if you wish to resort to object matchers, you can
* always call {@link #just()} to rewrap actual value into just plain object matcher.
* Primitive types are considered auto-wrapped in corresponing boxed types.
*/
default Object<T> just() {
return Assert.that(What.getNullable(this));
}
/** Tests for certain conditions without wrapped actual value. */
public interface Condition extends That<Void, Condition> {
/**
* Fails if condition is {@code false}.
* @param condition to check
*/
default void is(boolean condition) {
if (!condition) throw What.newAssertionError("expected true condition", "actual false");
}
/**
* Fails if condition is {@code true}
* @param condition to check
*/
default void not(boolean condition) {
if (condition) throw What.newAssertionError("expected false condition", "actual true");
}
/**
* Fails if invoked. Should be used for unreachable during successful pass test code.
*
* <pre>
* try {
* somethingThatThrows();
* that().unreachable();
* } catch (Exception ex) {
* </pre>
*
* @see Assert#that(Runnable)
*/
default void unreachable() {
throw What.newAssertionError("expected unreachable", "...and yet we are here");
}
}
/** That runnable or lambda/block. */
public interface Runnable extends That<java.lang.Runnable, Runnable> {
/**
* Fails if that runnable doesn't throw exception of expected type (or subtype of
* expected type) when called.
* @param thrownType type of expected throwable
* @return that exception checker
*/
default <E extends Throwable> That.Object<E> thrown(Class<E> thrownType) {
try {
java.lang.Runnable runnable = What.get(this);
runnable.run();
throw What.newAssertionError(
"expected thrown " + thrownType.getCanonicalName(),
"actual nothing thrown");
} catch (Throwable throwable) {
if (thrownType.isInstance(throwable)) {
return Assert.that(thrownType.cast(throwable));
}
throw What.newAssertionError(
"expected thrown " + thrownType.getCanonicalName(),
"actual: " + throwable.getClass().getCanonicalName() + ": " + throwable.getMessage());
}
}
}
/**
* Checks that string.
*/
interface String extends That<java.lang.String, String> {
/**
* Fails if that string doesn't equal expected value
* @param expected value
*/
default void is(java.lang.String expected) {
java.lang.String actual = What.get(this);
if (!expected.equals(actual)) {
List<java.lang.String> diff = Diff.diff(expected, actual);
throw What.newAssertionError("expected: " + diff.get(0), "actual: " + diff.get(1));
}
}
/** Fails if that string is not empty */
default void isEmpty() {
java.lang.String actual = What.get(this);
if (!actual.isEmpty()) {
throw What.newAssertionError("expected empty string", "actual: " + Diff.trim(actual));
}
}
/** Fails if that string is empty */
default void notEmpty() {
java.lang.String actual = What.get(this);
if (actual.isEmpty()) {
throw What.newAssertionError("expected nonempty string", "actual empty");
}
}
/**
* Fails if that string has length other thans
* @param expectedLength expected length
*/
default void hasLength(int expectedLength) {
java.lang.String actual = What.get(this);
if (actual.length() != expectedLength) {
throw What.newAssertionError(
"expected length: " + expectedLength,
"actual length: " + actual.length() + " — " + Diff.trim(What.get(this)));
}
}
/**
* Fails if that string doesn't contain substring.
* @param expected substring
*/
default void contains(java.lang.String substring) {
java.lang.String actual = What.get(this);
if (!actual.contains(substring)) {
throw What.newAssertionError(
"expected string containing: " + Diff.trim(substring),
"actual: " + Diff.trim(actual));
}
}
/**
* Fails if that string doesn't start with prefix
* @param prefix expected prefix
*/
default void startsWith(java.lang.String prefix) {
java.lang.String actual = What.get(this);
if (!actual.startsWith(prefix)) {
throw What.newAssertionError(
"expected string starts with: " + Diff.trim(prefix),
"actual: " + Diff.diff(actual, prefix).get(0));
}
}
/**
* Fails if that string doesn't start with suffix
* @param suffix expected suffix
*/
default void endsWith(java.lang.String suffix) {
java.lang.String actual = What.get(this);
if (!actual.endsWith(suffix)) {
throw What.newAssertionError(
"expected string starts with: " + Diff.trim(suffix),
"actual: " + Diff.diff(actual, suffix).get(0));
}
}
/**
* Fails if that string doesn't matches regex pattern
* @param regex expected pattern
*/
default void matches(java.lang.String regex) {
java.lang.String actual = What.get(this);
try {
if (!actual.matches(regex)) {
throw What.newAssertionError(
"expected string to match /" + regex + "/",
"actual: " + actual);
}
} catch (PatternSyntaxException ex) {
throw What.newAssertionError(
"expected string to match /" + regex + "/",
"pattern syntax error: " + ex.getMessage().split("\\n"));
}
}
}
/**
* Checks that boolean
*/
interface Boolean extends That<java.lang.Boolean, Boolean> {
/**
* Failes if that is not of expected boolean value or if null.
* @param expected value
*/
default void is(boolean trueOfFalse) {
java.lang.Boolean b = What.get(this);
if (trueOfFalse != b) {
throw What.newAssertionError("expected: " + trueOfFalse, "actual: " + b);
}
}
/**
* Fails if that is {@code false} with specified message.
* @param assertion error message
*/
default void orFail(java.lang.String message) {
if (!What.get(this)) {
throw What.newAssertionError(message);
}
}
}
/** Checks that object */
interface Object<T> extends That<T, Object<T>> {
/**
* @deprecated Already regular object matcher.
* @return always {@code this}
*/
@Override
@Deprecated
default Object<T> just() {
return this;
}
/** Fails if that object referece is not {@code null} */
default void isNull() {
@Nullable T actual = What.getNullable(this);
if (actual != null) {
throw What.newAssertionError("expected: null", "actual: " + actual);
}
}
/** Fails if that object referece is {@code null} */
default Object<T> notNull() {
What.get(this);
return this;
}
/**
* Fails if object is not of expected type (or subtype).
* @param <C> expected type
* @param type expected class object
* @return check that downcasted object
*/
default <C extends T> Object<C> instanceOf(Class<C> type) {
T actualRef = What.get(this);
if (!type.isInstance(actualRef)) {
throw What.newAssertionError(
"expected instance of " + type.getCanonicalName(),
"actual: " + What.showReference(actualRef) + What.showToStringDetail(actualRef));
}
@SuppressWarnings("unchecked") // safe cast after runtime check
Object<C> that = (Object<C>) this;
return that;
}
/**
* Fails if that object is not predicated by expression
* @param predicate predicate expression
* @return check that object
*/
default Object<T> is(Predicate<T> predicate) {
@Nullable T actual = What.getNullable(this);
if (!predicate.test(actual)) {
throw What.newAssertionError(
"expected matching predicate " + What.showNonDefault(predicate),
"actual: " + actual);
}
return this;
}
/**
* Fails if that object reference doesn't refers to the exact same expected reference
* @param expected object reference (allows null)
*/
default void same(@Nullable T expected) {
@Nullable T actual = What.getNullable(this);
if (actual != expected) {
throw What.newAssertionError(
"expected: "
+ What.showReference(expected)
+ What.showToStringDetail(expected),
"actual: " + What.showReference(actual) + What.showToStringDetail(actual));
}
}
/**
* Fails if that object reference refers to the exact same expected reference.
* @param expected not same reference (allows null)
*/
default void notSame(@Nullable T expected) {
@Nullable T actual = What.getNullable(this);
if (actual == expected) {
throw What.newAssertionError(
"expected not same: " + What.showReference(expected) + What.showToStringDetail(expected),
"actually was the same reference");
}
}
/**
* Fails if that object's result of calling {@code toString()} doesn't equal to expected string
* @param expectedToString expected {@code toString} value
*/
default void hasToString(java.lang.String expectedToString) {
Objects.requireNonNull(expectedToString);
java.lang.String actual = What.get(this).toString();
if (!actual.equals(expectedToString)) {
List<java.lang.String> diff = Diff.diff(expectedToString, actual);
throw What.newAssertionError("expected: " + diff.get(0), "actual: " + diff.get(1));
}
}
/**
* Fails if that object is not equivalent (via
* {@link java.lang.Object#equals(java.lang.Object)}) to the expected object.
* @param expected equivalent object
*/
default void equalTo(T expected) {
Objects.requireNonNull(expected);
T actual = What.get(this);
if (!actual.equals(expected)) {
java.lang.String as = actual.toString();
java.lang.String es = expected.toString();
if (as.equals(es)) {
throw What.newAssertionError(
"expected: " + What.showReference(expected) + What.showToStringDetail(expected),
"actual: " + What.showReference(actual) + What.showToStringDetail(actual));
}
List<java.lang.String> diff = Diff.diff(es, as);
throw What.newAssertionError("expected: " + diff.get(0), "actual: " + diff.get(1));
}
}
/**
* Fails if that object is equivalent (via
* {@link java.lang.Object#equals(java.lang.Object)}) to the expected object.
* @param expected not equivalent object
*/
default void notEqual(T expectedEquivalent) {
Objects.requireNonNull(expectedEquivalent);
T actual = What.get(this);
if (actual.equals(expectedEquivalent)) {
if (actual == expectedEquivalent) {
throw What.newAssertionError(
"expected not equal: "
+ What.showReference(expectedEquivalent)
+ What.showToStringDetail(expectedEquivalent),
"actual was the same object");
}
java.lang.String as = actual.toString();
java.lang.String es = expectedEquivalent.toString();
if (as.equals(es)) {
throw What.newAssertionError(
What.showReference(expectedEquivalent) + What.showToStringDetail(expectedEquivalent),
What.showReference(actual) + What.showToStringDetail(actual));
}
throw What.newAssertionError(
What.showReference(expectedEquivalent) + What.showToStringDetail(expectedEquivalent),
What.showReference(actual) + What.showToStringDetail(actual));
}
}
}
interface Optional<T> extends That<java.util.Optional<T>, Optional<T>> {
default void isEmpty() {
java.util.Optional<T> actual = What.get(this);
if (actual.isPresent()) {
throw What.newAssertionError(
"expected: Optional.empty()",
"actual: Optional.of(" + actual.get() + ")");
}
}
default void isPresent() {
java.util.Optional<T> actual = What.get(this);
if (!actual.isPresent()) {
throw What.newAssertionError(
"expected: expected present Optional",
"actual: Optional.empty()");
}
}
default void isOf(T expected) {
java.util.Optional<T> actualOptional = What.get(this);
java.util.Optional<T> expectedOptional = java.util.Optional.of(expected);
if (!actualOptional.equals(expectedOptional)) {
throw What.newAssertionError(
"expected: Optional.of(" + expected + ")",
"actual: " + (actualOptional.isPresent()
? "Optional.of(" + actualOptional.get() + ")"
: "Optional.empty()"));
}
}
}
/** Checks that iterable (collection, collection view, array or any iterable) */
interface Iterable<T> extends That<java.lang.Iterable<T>, Iterable<T>> {
default void notEmpty() {
List<T> list = What.getList(this);
if (list.isEmpty()) {
throw What.newAssertionError("expected non empty", "actual: " + Diff.trim(What.get(this)));
}
}
default void isEmpty() {
List<T> list = What.getList(this);
if (!list.isEmpty()) {
throw What.newAssertionError("expected empty", "actual: " + Diff.trim(What.get(this)));
}
}
default void hasSize(int expectedSize) {
List<T> list = What.getList(this);
if (list.size() != expectedSize) {
throw What.newAssertionError(
"expected size: " + expectedSize,
"actual size: " + list.size() + " — " + Diff.trim(What.get(this)));
}
}
default void has(T expectedElement) {
List<T> list = What.getList(this);
if (!list.contains(expectedElement)) {
throw What.newAssertionError(
"expected element: " + expectedElement,
"actual none — " + Diff.trim(What.get(this)));
}
}
default void isOf(java.lang.Iterable<T> expectedElements) {
List<T> actualList = What.getList(this);
List<T> expectedList = new ArrayList<>();
expectedElements.forEach(expectedList::add);
if (!actualList.equals(expectedList)) {
List<java.lang.String> diff = Diff.diff(
What.showElements(expectedList),
What.showElements(actualList));
throw What.newAssertionError(
"expected elements: " + diff.get(0),
"actual elements: " + diff.get(1));
}
}
@SuppressWarnings("unchecked")
default void isOf(T... expectedElements) {
isOf(Arrays.asList(expectedElements));
}
@SuppressWarnings("unchecked")
default void hasAll(T... expectedElements) {
hasAll(Arrays.asList(expectedElements));
}
@SuppressWarnings("unchecked")
default void hasOnly(T... expectedElements) {
hasOnly(Arrays.asList(expectedElements));
}
default void hasAll(java.lang.Iterable<T> expectedElements) {
List<T> actualElements = What.getList(this);
List<T> missingElements = new ArrayList<>();
for (T e : expectedElements) {
if (!actualElements.contains(e)) {
missingElements.add(e);
}
}
if (!missingElements.isEmpty()) {
throw What.newAssertionError(
"expected has all: " + What.showElements(expectedElements),
"actual: missing " + What.showElements(missingElements) + " — " + Diff.trim(actualElements));
}
}
default void hasOnly(java.lang.Iterable<T> elements) {
List<T> remainingElements = What.getList(this);
List<T> expectedElements = new ArrayList<>();
List<T> missingElements = new ArrayList<>();
for (T e : elements) {
expectedElements.add(e);
if (!remainingElements.contains(e)) {
missingElements.add(e);
} else {
remainingElements.remove(e);
}
}
if (!missingElements.isEmpty() || !remainingElements.isEmpty()) {
java.lang.String actual = "";
if (!missingElements.isEmpty()) {
actual += "missing " + What.showElements(missingElements) + "; ";
}
if (!remainingElements.isEmpty()) {
actual += "extra " + What.showElements(remainingElements);
}
throw What.newAssertionError(
"expected only: " + What.showElements(expectedElements),
"actual: " + actual);
}
}
}
interface Double extends That<java.lang.Double, Double> {
default void bitwiseIs(double expected) {
double actual = What.get(this);
if (java.lang.Double.doubleToRawLongBits(actual) != java.lang.Double.doubleToRawLongBits(expected)) {
throw What.newAssertionError("expected: " + expected, "actual: " + actual);
}
}
default void is(DoublePredicate predicate) {
double actual = What.get(this);
if (!predicate.test(actual)) {
throw What.newAssertionError(
"expected matching predicate " + What.showNonDefault(predicate),
"actual: " + actual);
}
}
default void withinOf(double epsilon, double expected) {
double actual = What.get(this);
if (Math.abs(actual - expected) > epsilon) {
throw What.newAssertionError(
"expected within ±" + epsilon + " of " + expected,
"actual: " + actual);
}
}
default void isNaN() {
double actual = What.get(this);
if (!java.lang.Double.isNaN(actual)) {
throw What.newAssertionError("expected NaN", "actual: " + actual);
}
}
default void isFinite() {
double actual = What.get(this);
if (!java.lang.Double.isFinite(actual)) {
throw What.newAssertionError("expected finite double", "actual: " + actual);
}
}
default void isInfinite() {
double actual = What.get(this);
if (!java.lang.Double.isInfinite(actual)) {
throw What.newAssertionError("expected infinite double", "actual: " + actual);
}
}
}
interface Int extends That<java.lang.Integer, Int> {
default void is(IntPredicate predicate) {
int actual = What.get(this);
if (!predicate.test(actual)) {
throw What.newAssertionError(
"expected matching predicate " + What.showNonDefault(predicate),
"actual: " + actual);
}
}
default void is(int expected) {
int actual = What.get(this);
if (actual != expected) {
throw What.newAssertionError("expected: " + expected, "actual: " + actual);
}
}
}
interface Long extends That<java.lang.Long, Long> {
default void is(LongPredicate predicate) {
long actual = What.get(this);
if (!predicate.test(actual)) {
throw What.newAssertionError(
"expected matching predicate " + What.showNonDefault(predicate),
"actual: " + actual);
}
}
default void is(long expected) {
long actual = What.get(this);
if (actual != expected) {
throw What.newAssertionError("expected: " + expected, "actual: " + actual);
}
}
}
/**
* This support class is mandatory to extend and decorate with any {@link That} interfaces
* (providing default methods). Implementing classes are usually private or local, but
* {@link That}-interfaces are public.
* @param <T> type of value to check
* @param <S> self-type of checker.
*/
public abstract class What<T, S extends That<T, S>> implements That<T, S> {
private @Nullable T value;
private boolean isSet;
/**
* Set value under test
* @param value to be tested
* @return this for chained invokation
*/
@SuppressWarnings("unchecked")
public final S set(@Nullable T value) {
this.value = value;
this.isSet = true;
return (S) this;
}
private @Nullable T get() {
if (!isSet) throw new IllegalStateException("What.set(value) must be called on wrapper");
return value;
}
@Deprecated
@Override
public final boolean equals(java.lang.Object obj) {
throw new UnsupportedOperationException();
}
@Deprecated
@Override
public final int hashCode() {
throw new UnsupportedOperationException();
}
@Override
public final java.lang.String toString() {
return "that(" + value + ")";
}
/**
* Extracts actual value from wrapper. Trips on {@code null} immediately: raises assertion
* error. It is mandatory that input argument extends {@link That.What}.
* @see #getNullable(That) to allow nullable values
* @param <T> type of value
* @param <S> type of checker.
* @param that wrapper user to extract actual value
* @return unwrapped actual value
*/
protected static <T, S extends That<T, S>> T get(That<T, S> that) {
@Nullable T value = ((What<T, S>) that).get();
if (value != null) return value;
throw newAssertionError("non-null expected");
}
/**
* The same as {@link #get(That that)}, but allows actual value to be {@code null}
* @param <T> type of value
* @param <S> type of checker which extends {@link That}.
* @param that wrapper user to extract actual value
* @return unwrapped actual value
*/
protected static <T, S extends That<T, S>> T getNullable(That<T, S> that) {
return ((What<T, S>) that).get();
}
/**
* Factory for well-suited assertion error. Typical usage is to format via 2 strings, one for
* actuall value. While it is not mandatory to use this factory method to create assertion
* errors, if you choose to use it, this will provide very pretty stack trace filtering and
* source code extraction (if test sources are available as resources on the classpath).
* @param linesDescribingMismatch message lines
* @return properly constructed instance of {@link java.lang.AssertionError}
*/
protected static java.lang.AssertionError newAssertionError(java.lang.String... linesDescribingMismatch) {
return new AssertionError(linesDescribingMismatch);
}
private static <T, S extends That<java.lang.Iterable<T>, S>> List<T> getList(That<java.lang.Iterable<T>, S> that) {
java.lang.Iterable<T> actual = get(that);
List<T> list = new ArrayList<>();
actual.forEach(list::add);
return list;
}
private static java.lang.String showElements(java.lang.Iterable<?> iterable) {
return StreamSupport.stream(iterable.spliterator(), false)
.map(Objects::toString)
.collect(Collectors.joining(", "));
}
private static java.lang.String showNonDefault(java.lang.Object ref) {
java.lang.String string = ref.toString();
if (string.endsWith(identityHashCodeSuffix(ref))) return "";
return string;
}
private static java.lang.String showReference(java.lang.Object ref) {
return ref == null ? "null" : (ref.getClass().getSimpleName() + identityHashCodeSuffix(ref));
}
private static java.lang.String identityHashCodeSuffix(java.lang.Object ref) {
return "@" + Integer.toHexString(System.identityHashCode(ref));
}
private static java.lang.String showToStringDetail(java.lang.Object ref) {
return ref == null ? "" : (" — " + ref);
}
}
}