/
FuturesTest.java
3968 lines (3482 loc) · 144 KB
/
FuturesTest.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
/*
* Copyright (C) 2008 The Guava Authors
*
* 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.
*/
package com.google.common.util.concurrent;
import static com.google.common.base.Functions.constant;
import static com.google.common.base.Functions.identity;
import static com.google.common.base.Throwables.propagateIfInstanceOf;
import static com.google.common.collect.Iterables.getOnlyElement;
import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Sets.intersection;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
import static com.google.common.util.concurrent.Futures.allAsList;
import static com.google.common.util.concurrent.Futures.catching;
import static com.google.common.util.concurrent.Futures.catchingAsync;
import static com.google.common.util.concurrent.Futures.getDone;
import static com.google.common.util.concurrent.Futures.immediateCancelledFuture;
import static com.google.common.util.concurrent.Futures.immediateFailedFuture;
import static com.google.common.util.concurrent.Futures.immediateFuture;
import static com.google.common.util.concurrent.Futures.immediateVoidFuture;
import static com.google.common.util.concurrent.Futures.inCompletionOrder;
import static com.google.common.util.concurrent.Futures.lazyTransform;
import static com.google.common.util.concurrent.Futures.nonCancellationPropagating;
import static com.google.common.util.concurrent.Futures.scheduleAsync;
import static com.google.common.util.concurrent.Futures.submit;
import static com.google.common.util.concurrent.Futures.submitAsync;
import static com.google.common.util.concurrent.Futures.successfulAsList;
import static com.google.common.util.concurrent.Futures.transform;
import static com.google.common.util.concurrent.Futures.transformAsync;
import static com.google.common.util.concurrent.Futures.whenAllComplete;
import static com.google.common.util.concurrent.Futures.whenAllSucceed;
import static com.google.common.util.concurrent.MoreExecutors.directExecutor;
import static com.google.common.util.concurrent.TestPlatform.clearInterrupt;
import static com.google.common.util.concurrent.TestPlatform.getDoneFromTimeoutOverload;
import static com.google.common.util.concurrent.Uninterruptibles.awaitUninterruptibly;
import static com.google.common.util.concurrent.Uninterruptibles.getUninterruptibly;
import static com.google.common.util.concurrent.testing.TestingExecutors.noOpScheduledExecutor;
import static java.util.Arrays.asList;
import static java.util.concurrent.Executors.newSingleThreadExecutor;
import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.testing.ClassSanityTester;
import com.google.common.testing.GcFinalization;
import com.google.common.testing.TestLogHandler;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit tests for {@link Futures}.
*
* @author Nishant Thakkar
*/
@GwtCompatible(emulated = true)
public class FuturesTest extends TestCase {
private static final Logger aggregateFutureLogger =
Logger.getLogger(AggregateFuture.class.getName());
private final TestLogHandler aggregateFutureLogHandler = new TestLogHandler();
private static final String DATA1 = "data";
private static final String DATA2 = "more data";
private static final String DATA3 = "most data";
@Override
public void setUp() throws Exception {
super.setUp();
aggregateFutureLogger.addHandler(aggregateFutureLogHandler);
}
@Override
public void tearDown() throws Exception {
/*
* Clear interrupt for future tests.
*
* (Ideally we would perform interrupts only in threads that we create, but
* it's hard to imagine that anything will break in practice.)
*/
clearInterrupt();
aggregateFutureLogger.removeHandler(aggregateFutureLogHandler);
super.tearDown();
}
/*
* TODO(cpovirk): Use FutureSubject once it's part of core Truth. But be wary of using it when I'm
* really testing a Future implementation (e.g., in the case of immediate*Future()). But it's OK
* to use in the case of the majority of Futures that are AbstractFutures.
*/
public void testImmediateFuture() throws Exception {
ListenableFuture<String> future = immediateFuture(DATA1);
assertSame(DATA1, getDone(future));
assertSame(DATA1, getDoneFromTimeoutOverload(future));
assertThat(future.toString()).contains("[status=SUCCESS, result=[" + DATA1 + "]]");
}
public void testImmediateVoidFuture() throws Exception {
ListenableFuture<Void> voidFuture = immediateVoidFuture();
assertThat(getDone(voidFuture)).isNull();
assertThat(getDoneFromTimeoutOverload(voidFuture)).isNull();
assertThat(voidFuture.toString()).contains("[status=SUCCESS, result=[null]]");
}
public void testImmediateFailedFuture() throws Exception {
Exception exception = new Exception();
ListenableFuture<String> future = immediateFailedFuture(exception);
assertThat(future.toString()).endsWith("[status=FAILURE, cause=[" + exception + "]]");
try {
getDone(future);
fail();
} catch (ExecutionException expected) {
assertSame(exception, expected.getCause());
}
try {
getDoneFromTimeoutOverload(future);
fail();
} catch (ExecutionException expected) {
assertSame(exception, expected.getCause());
}
}
public void testImmediateFailedFuture_cancellationException() throws Exception {
CancellationException exception = new CancellationException();
ListenableFuture<String> future = immediateFailedFuture(exception);
assertFalse(future.isCancelled());
assertThat(future.toString()).endsWith("[status=FAILURE, cause=[" + exception + "]]");
try {
getDone(future);
fail();
} catch (ExecutionException expected) {
assertSame(exception, expected.getCause());
}
try {
getDoneFromTimeoutOverload(future);
fail();
} catch (ExecutionException expected) {
assertSame(exception, expected.getCause());
}
}
public void testImmediateCancelledFutureBasic() throws Exception {
ListenableFuture<String> future = CallerClass1.makeImmediateCancelledFuture();
assertTrue(future.isCancelled());
}
@GwtIncompatible
public void testImmediateCancelledFutureStack() throws Exception {
ListenableFuture<String> future = CallerClass1.makeImmediateCancelledFuture();
assertTrue(future.isCancelled());
try {
CallerClass2.get(future);
fail();
} catch (CancellationException expected) {
// There should be two CancellationException chained together. The outer one should have the
// stack trace of where the get() call was made, and the inner should have the stack trace of
// where the immediateCancelledFuture() call was made.
List<StackTraceElement> stackTrace = ImmutableList.copyOf(expected.getStackTrace());
assertFalse(Iterables.any(stackTrace, hasClassName(CallerClass1.class)));
assertTrue(Iterables.any(stackTrace, hasClassName(CallerClass2.class)));
// See AbstractFutureCancellationCauseTest for how to set causes.
assertThat(expected.getCause()).isNull();
}
}
@GwtIncompatible // used only in GwtIncompatible tests
private static Predicate<StackTraceElement> hasClassName(final Class<?> clazz) {
return new Predicate<StackTraceElement>() {
@Override
public boolean apply(StackTraceElement element) {
return element.getClassName().equals(clazz.getName());
}
};
}
private static final class CallerClass1 {
static ListenableFuture<String> makeImmediateCancelledFuture() {
return immediateCancelledFuture();
}
}
private static final class CallerClass2 {
@CanIgnoreReturnValue
static <V> V get(ListenableFuture<V> future) throws ExecutionException, InterruptedException {
return getDone(future);
}
}
private static class MyException extends Exception {}
// Class hierarchy for generics sanity checks
private static class Foo {}
private static class FooChild extends Foo {}
private static class Bar {}
private static class BarChild extends Bar {}
public void testTransform_genericsNull() throws Exception {
ListenableFuture<?> nullFuture = immediateFuture(null);
ListenableFuture<?> transformedFuture = transform(nullFuture, constant(null), directExecutor());
assertNull(getDone(transformedFuture));
}
public void testTransform_genericsHierarchy() throws Exception {
ListenableFuture<FooChild> future = immediateFuture(null);
final BarChild barChild = new BarChild();
Function<Foo, BarChild> function =
new Function<Foo, BarChild>() {
@Override
public BarChild apply(Foo unused) {
return barChild;
}
};
Bar bar = getDone(transform(future, function, directExecutor()));
assertSame(barChild, bar);
}
/*
* Android does not handle this stack overflow gracefully... though somehow some other
* stack-overflow tests work. It must depend on the exact place the error occurs.
*/
@AndroidIncompatible
@GwtIncompatible // StackOverflowError
public void testTransform_StackOverflow() throws Exception {
{
/*
* Initialize all relevant classes before running the test, which may otherwise poison any
* classes it is trying to load during its stack overflow.
*/
SettableFuture<Object> root = SettableFuture.create();
ListenableFuture<Object> unused = transform(root, identity(), directExecutor());
root.set("foo");
}
SettableFuture<Object> root = SettableFuture.create();
ListenableFuture<Object> output = root;
for (int i = 0; i < 10000; i++) {
output = transform(output, identity(), directExecutor());
}
try {
root.set("foo");
fail();
} catch (StackOverflowError expected) {
}
}
public void testTransform_ErrorAfterCancellation() throws Exception {
class Transformer implements Function<Object, Object> {
ListenableFuture<Object> output;
@Override
public Object apply(Object input) {
output.cancel(false);
throw new MyError();
}
}
Transformer transformer = new Transformer();
SettableFuture<Object> input = SettableFuture.create();
ListenableFuture<Object> output = transform(input, transformer, directExecutor());
transformer.output = output;
input.set("foo");
assertTrue(output.isCancelled());
}
public void testTransform_ExceptionAfterCancellation() throws Exception {
class Transformer implements Function<Object, Object> {
ListenableFuture<Object> output;
@Override
public Object apply(Object input) {
output.cancel(false);
throw new MyRuntimeException();
}
}
Transformer transformer = new Transformer();
SettableFuture<Object> input = SettableFuture.create();
ListenableFuture<Object> output = transform(input, transformer, directExecutor());
transformer.output = output;
input.set("foo");
assertTrue(output.isCancelled());
}
public void testTransform_getThrowsRuntimeException() throws Exception {
ListenableFuture<Object> input =
UncheckedThrowingFuture.throwingRuntimeException(new MyRuntimeException());
ListenableFuture<Object> output = transform(input, identity(), directExecutor());
try {
getDone(output);
fail();
} catch (ExecutionException expected) {
assertThat(expected.getCause()).isInstanceOf(MyRuntimeException.class);
}
}
public void testTransform_getThrowsError() throws Exception {
ListenableFuture<Object> input = UncheckedThrowingFuture.throwingError(new MyError());
ListenableFuture<Object> output = transform(input, identity(), directExecutor());
try {
getDone(output);
fail();
} catch (ExecutionException expected) {
assertThat(expected.getCause()).isInstanceOf(MyError.class);
}
}
public void testTransform_listenerThrowsError() throws Exception {
SettableFuture<Object> input = SettableFuture.create();
ListenableFuture<Object> output = transform(input, identity(), directExecutor());
output.addListener(
new Runnable() {
@Override
public void run() {
throw new MyError();
}
},
directExecutor());
try {
input.set("foo");
fail();
} catch (MyError expected) {
}
}
public void testTransformAsync_cancelPropagatesToInput() throws Exception {
SettableFuture<Foo> input = SettableFuture.create();
AsyncFunction<Foo, Bar> function =
new AsyncFunction<Foo, Bar>() {
@Override
public ListenableFuture<Bar> apply(Foo unused) {
throw new AssertionFailedError("Unexpeted call to apply.");
}
};
assertTrue(transformAsync(input, function, directExecutor()).cancel(false));
assertTrue(input.isCancelled());
assertFalse(input.wasInterrupted());
}
public void testTransformAsync_interruptPropagatesToInput() throws Exception {
SettableFuture<Foo> input = SettableFuture.create();
AsyncFunction<Foo, Bar> function =
new AsyncFunction<Foo, Bar>() {
@Override
public ListenableFuture<Bar> apply(Foo unused) {
throw new AssertionFailedError("Unexpeted call to apply.");
}
};
assertTrue(transformAsync(input, function, directExecutor()).cancel(true));
assertTrue(input.isCancelled());
assertTrue(input.wasInterrupted());
}
@GwtIncompatible // threads
public void testTransformAsync_interruptPropagatesToTransformingThread() throws Exception {
SettableFuture<String> input = SettableFuture.create();
final CountDownLatch inFunction = new CountDownLatch(1);
final CountDownLatch shouldCompleteFunction = new CountDownLatch(1);
final CountDownLatch gotException = new CountDownLatch(1);
AsyncFunction<String, String> function =
new AsyncFunction<String, String>() {
@Override
public ListenableFuture<String> apply(String s) throws Exception {
inFunction.countDown();
try {
shouldCompleteFunction.await();
} catch (InterruptedException expected) {
gotException.countDown();
throw expected;
}
return immediateFuture("a");
}
};
ListenableFuture<String> futureResult =
transformAsync(input, function, newSingleThreadExecutor());
input.set("value");
inFunction.await();
futureResult.cancel(true);
shouldCompleteFunction.countDown();
try {
futureResult.get();
fail();
} catch (CancellationException expected) {
}
// TODO(cpovirk): implement interruption, updating this test:
// https://github.com/google/guava/issues/1989
assertEquals(1, gotException.getCount());
// gotException.await();
}
public void testTransformAsync_cancelPropagatesToAsyncOutput() throws Exception {
ListenableFuture<Foo> immediate = immediateFuture(new Foo());
final SettableFuture<Bar> secondary = SettableFuture.create();
AsyncFunction<Foo, Bar> function =
new AsyncFunction<Foo, Bar>() {
@Override
public ListenableFuture<Bar> apply(Foo unused) {
return secondary;
}
};
assertTrue(transformAsync(immediate, function, directExecutor()).cancel(false));
assertTrue(secondary.isCancelled());
assertFalse(secondary.wasInterrupted());
}
public void testTransformAsync_interruptPropagatesToAsyncOutput() throws Exception {
ListenableFuture<Foo> immediate = immediateFuture(new Foo());
final SettableFuture<Bar> secondary = SettableFuture.create();
AsyncFunction<Foo, Bar> function =
new AsyncFunction<Foo, Bar>() {
@Override
public ListenableFuture<Bar> apply(Foo unused) {
return secondary;
}
};
assertTrue(transformAsync(immediate, function, directExecutor()).cancel(true));
assertTrue(secondary.isCancelled());
assertTrue(secondary.wasInterrupted());
}
public void testTransformAsync_inputCancelButNotInterruptPropagatesToOutput() throws Exception {
SettableFuture<Foo> f1 = SettableFuture.create();
final SettableFuture<Bar> secondary = SettableFuture.create();
AsyncFunction<Foo, Bar> function =
new AsyncFunction<Foo, Bar>() {
@Override
public ListenableFuture<Bar> apply(Foo unused) {
return secondary;
}
};
ListenableFuture<Bar> f2 = transformAsync(f1, function, directExecutor());
f1.cancel(true);
assertTrue(f2.isCancelled());
/*
* We might like to propagate interruption, too, but it's not clear that it matters. For now, we
* test for the behavior that we have today.
*/
assertFalse(((AbstractFuture<?>) f2).wasInterrupted());
}
/*
* Android does not handle this stack overflow gracefully... though somehow some other
* stack-overflow tests work. It must depend on the exact place the error occurs.
*/
@AndroidIncompatible
@GwtIncompatible // StackOverflowError
public void testTransformAsync_StackOverflow() throws Exception {
{
/*
* Initialize all relevant classes before running the test, which may otherwise poison any
* classes it is trying to load during its stack overflow.
*/
SettableFuture<Object> root = SettableFuture.create();
ListenableFuture<Object> unused = transformAsync(root, asyncIdentity(), directExecutor());
root.set("foo");
}
SettableFuture<Object> root = SettableFuture.create();
ListenableFuture<Object> output = root;
for (int i = 0; i < 10000; i++) {
output = transformAsync(output, asyncIdentity(), directExecutor());
}
try {
root.set("foo");
fail();
} catch (StackOverflowError expected) {
}
}
public void testTransformAsync_ErrorAfterCancellation() throws Exception {
class Transformer implements AsyncFunction<Object, Object> {
ListenableFuture<Object> output;
@Override
public ListenableFuture<Object> apply(Object input) {
output.cancel(false);
throw new MyError();
}
}
Transformer transformer = new Transformer();
SettableFuture<Object> input = SettableFuture.create();
ListenableFuture<Object> output = transformAsync(input, transformer, directExecutor());
transformer.output = output;
input.set("foo");
assertTrue(output.isCancelled());
}
public void testTransformAsync_ExceptionAfterCancellation() throws Exception {
class Transformer implements AsyncFunction<Object, Object> {
ListenableFuture<Object> output;
@Override
public ListenableFuture<Object> apply(Object input) {
output.cancel(false);
throw new MyRuntimeException();
}
}
Transformer transformer = new Transformer();
SettableFuture<Object> input = SettableFuture.create();
ListenableFuture<Object> output = transformAsync(input, transformer, directExecutor());
transformer.output = output;
input.set("foo");
assertTrue(output.isCancelled());
}
public void testTransformAsync_getThrowsRuntimeException() throws Exception {
ListenableFuture<Object> input =
UncheckedThrowingFuture.throwingRuntimeException(new MyRuntimeException());
ListenableFuture<Object> output = transformAsync(input, asyncIdentity(), directExecutor());
try {
getDone(output);
fail();
} catch (ExecutionException expected) {
assertThat(expected.getCause()).isInstanceOf(MyRuntimeException.class);
}
}
public void testTransformAsync_getThrowsError() throws Exception {
ListenableFuture<Object> input = UncheckedThrowingFuture.throwingError(new MyError());
ListenableFuture<Object> output = transformAsync(input, asyncIdentity(), directExecutor());
try {
getDone(output);
fail();
} catch (ExecutionException expected) {
assertThat(expected.getCause()).isInstanceOf(MyError.class);
}
}
public void testTransformAsync_listenerThrowsError() throws Exception {
SettableFuture<Object> input = SettableFuture.create();
ListenableFuture<Object> output = transformAsync(input, asyncIdentity(), directExecutor());
output.addListener(
new Runnable() {
@Override
public void run() {
throw new MyError();
}
},
directExecutor());
try {
input.set("foo");
fail();
} catch (MyError expected) {
}
}
public void testTransform_rejectionPropagatesToOutput() throws Exception {
SettableFuture<Foo> input = SettableFuture.create();
Function<Foo, Foo> identity = identity();
ListenableFuture<Foo> transformed = transform(input, identity, REJECTING_EXECUTOR);
input.set(new Foo());
try {
getDone(transformed);
fail();
} catch (ExecutionException expected) {
assertThat(expected.getCause()).isInstanceOf(RejectedExecutionException.class);
}
}
public void testTransformAsync_rejectionPropagatesToOutput() throws Exception {
SettableFuture<Foo> input = SettableFuture.create();
AsyncFunction<Foo, Foo> asyncIdentity = asyncIdentity();
ListenableFuture<Foo> transformed = transformAsync(input, asyncIdentity, REJECTING_EXECUTOR);
input.set(new Foo());
try {
getDone(transformed);
fail();
} catch (ExecutionException expected) {
assertThat(expected.getCause()).isInstanceOf(RejectedExecutionException.class);
}
}
/** Tests that the function is invoked only once, even if it throws an exception. */
public void testTransformValueRemainsMemoized() throws Exception {
class Holder {
int value = 2;
}
final Holder holder = new Holder();
// This function adds the holder's value to the input value.
Function<Integer, Integer> adder =
new Function<Integer, Integer>() {
@Override
public Integer apply(Integer from) {
return from + holder.value;
}
};
// Since holder.value is 2, applying 4 should yield 6.
assertEquals(6, adder.apply(4).intValue());
ListenableFuture<Integer> immediateFuture = immediateFuture(4);
Future<Integer> transformedFuture = transform(immediateFuture, adder, directExecutor());
// The composed future also yields 6.
assertEquals(6, getDone(transformedFuture).intValue());
// Repeated calls yield the same value even though the function's behavior
// changes
holder.value = 3;
assertEquals(6, getDone(transformedFuture).intValue());
assertEquals(7, adder.apply(4).intValue());
// Once more, with feeling.
holder.value = 4;
assertEquals(6, getDone(transformedFuture).intValue());
assertEquals(8, adder.apply(4).intValue());
// Memoized get also retains the value.
assertEquals(6, getDoneFromTimeoutOverload(transformedFuture).intValue());
// Unsurprisingly, recomposing the future will return an updated value.
assertEquals(8, getDone(transform(immediateFuture, adder, directExecutor())).intValue());
// Repeating, with the timeout version
assertEquals(
8,
getDoneFromTimeoutOverload(transform(immediateFuture, adder, directExecutor())).intValue());
}
static class MyError extends Error {}
static class MyRuntimeException extends RuntimeException {}
/**
* Test that the function is invoked only once, even if it throws an exception. Also, test that
* that function's result is wrapped in an ExecutionException.
*/
@GwtIncompatible // reflection
public void testTransformExceptionRemainsMemoized() throws Throwable {
// We need to test with two input futures since ExecutionList.execute
// doesn't catch Errors and we cannot depend on the order that our
// transformations run. (So it is possible that the Error being thrown
// could prevent our second transformations from running).
SettableFuture<Integer> exceptionInput = SettableFuture.create();
ListenableFuture<Integer> exceptionComposedFuture =
transform(exceptionInput, newOneTimeExceptionThrower(), directExecutor());
exceptionInput.set(0);
runGetIdempotencyTest(exceptionComposedFuture, MyRuntimeException.class);
SettableFuture<Integer> errorInput = SettableFuture.create();
ListenableFuture<Integer> errorComposedFuture =
transform(errorInput, newOneTimeErrorThrower(), directExecutor());
errorInput.set(0);
runGetIdempotencyTest(errorComposedFuture, MyError.class);
/*
* Try again when the input's value is already filled in, since the flow is
* slightly different in that case.
*/
exceptionComposedFuture =
transform(exceptionInput, newOneTimeExceptionThrower(), directExecutor());
runGetIdempotencyTest(exceptionComposedFuture, MyRuntimeException.class);
runGetIdempotencyTest(
transform(errorInput, newOneTimeErrorThrower(), directExecutor()), MyError.class);
runGetIdempotencyTest(errorComposedFuture, MyError.class);
}
@GwtIncompatible // reflection
private static void runGetIdempotencyTest(
Future<Integer> transformedFuture, Class<? extends Throwable> expectedExceptionClass)
throws Throwable {
for (int i = 0; i < 5; i++) {
try {
getDone(transformedFuture);
fail();
} catch (ExecutionException expected) {
if (!expectedExceptionClass.isInstance(expected.getCause())) {
throw expected.getCause();
}
}
}
}
@GwtIncompatible // used only in GwtIncompatible tests
private static Function<Integer, Integer> newOneTimeExceptionThrower() {
return new Function<Integer, Integer>() {
int calls = 0;
@Override
public Integer apply(Integer from) {
if (++calls > 1) {
fail();
}
throw new MyRuntimeException();
}
};
}
@GwtIncompatible // used only in GwtIncompatible tests
private static Function<Integer, Integer> newOneTimeErrorThrower() {
return new Function<Integer, Integer>() {
int calls = 0;
@Override
public Integer apply(Integer from) {
if (++calls > 1) {
fail();
}
throw new MyError();
}
};
}
// TODO(cpovirk): top-level class?
static class ExecutorSpy implements Executor {
Executor delegate;
boolean wasExecuted;
public ExecutorSpy(Executor delegate) {
this.delegate = delegate;
}
@Override
public void execute(Runnable command) {
delegate.execute(command);
wasExecuted = true;
}
}
public void testTransform_Executor() throws Exception {
Object value = new Object();
ExecutorSpy spy = new ExecutorSpy(directExecutor());
assertFalse(spy.wasExecuted);
ListenableFuture<Object> future = transform(immediateFuture(value), identity(), spy);
assertSame(value, getDone(future));
assertTrue(spy.wasExecuted);
}
@GwtIncompatible // Threads
public void testTransformAsync_functionToString() throws Exception {
final CountDownLatch functionCalled = new CountDownLatch(1);
final CountDownLatch functionBlocking = new CountDownLatch(1);
AsyncFunction<Object, Object> function =
tagged(
"Called my toString",
new AsyncFunction<Object, Object>() {
@Override
public ListenableFuture<Object> apply(Object input) throws Exception {
functionCalled.countDown();
functionBlocking.await();
return immediateFuture(null);
}
});
ExecutorService executor = Executors.newSingleThreadExecutor();
try {
ListenableFuture<?> output =
Futures.transformAsync(immediateFuture(null), function, executor);
functionCalled.await();
assertThat(output.toString()).contains(function.toString());
} finally {
functionBlocking.countDown();
executor.shutdown();
}
}
@GwtIncompatible // lazyTransform
public void testLazyTransform() throws Exception {
FunctionSpy<Object, String> spy = new FunctionSpy<>(constant("bar"));
Future<String> input = immediateFuture("foo");
Future<String> transformed = lazyTransform(input, spy);
spy.verifyCallCount(0);
assertEquals("bar", getDone(transformed));
spy.verifyCallCount(1);
assertEquals("bar", getDone(transformed));
spy.verifyCallCount(2);
}
@GwtIncompatible // lazyTransform
public void testLazyTransform_exception() throws Exception {
final RuntimeException exception = new RuntimeException("deliberate");
Function<Integer, String> function =
new Function<Integer, String>() {
@Override
public String apply(Integer input) {
throw exception;
}
};
Future<String> transformed = lazyTransform(immediateFuture(1), function);
try {
getDone(transformed);
fail();
} catch (ExecutionException expected) {
assertSame(exception, expected.getCause());
}
try {
getDoneFromTimeoutOverload(transformed);
fail();
} catch (ExecutionException expected) {
assertSame(exception, expected.getCause());
}
}
private static class FunctionSpy<I, O> implements Function<I, O> {
private int applyCount;
private final Function<I, O> delegate;
public FunctionSpy(Function<I, O> delegate) {
this.delegate = delegate;
}
@Override
public O apply(I input) {
applyCount++;
return delegate.apply(input);
}
void verifyCallCount(int expected) {
assertThat(applyCount).isEqualTo(expected);
}
}
private static <X extends Throwable, V> Function<X, V> unexpectedFunction() {
return new Function<X, V>() {
@Override
public V apply(X t) {
throw newAssertionError("Unexpected fallback", t);
}
};
}
private static class AsyncFunctionSpy<X extends Throwable, V> implements AsyncFunction<X, V> {
private int count;
private final AsyncFunction<X, V> delegate;
public AsyncFunctionSpy(AsyncFunction<X, V> delegate) {
this.delegate = delegate;
}
@Override
public final ListenableFuture<V> apply(X t) throws Exception {
count++;
return delegate.apply(t);
}
void verifyCallCount(int expected) {
assertThat(count).isEqualTo(expected);
}
}
private static <I, O> FunctionSpy<I, O> spy(Function<I, O> delegate) {
return new FunctionSpy<>(delegate);
}
private static <X extends Throwable, V> AsyncFunctionSpy<X, V> spy(AsyncFunction<X, V> delegate) {
return new AsyncFunctionSpy<>(delegate);
}
private static <X extends Throwable, V> AsyncFunction<X, V> unexpectedAsyncFunction() {
return new AsyncFunction<X, V>() {
@Override
public ListenableFuture<V> apply(X t) {
throw newAssertionError("Unexpected fallback", t);
}
};
}
/** Alternative to AssertionError(String, Throwable), which doesn't exist in GWT 2.6.1. */
private static AssertionError newAssertionError(String message, Throwable cause) {
AssertionError e = new AssertionError(message);
e.initCause(cause);
return e;
}
// catchingAsync tests cloned from the old withFallback tests:
public void testCatchingAsync_inputDoesNotRaiseException() throws Exception {
AsyncFunction<Throwable, Integer> fallback = unexpectedAsyncFunction();
ListenableFuture<Integer> originalFuture = immediateFuture(7);
ListenableFuture<Integer> faultTolerantFuture =
catchingAsync(originalFuture, Throwable.class, fallback, directExecutor());
assertEquals(7, getDone(faultTolerantFuture).intValue());
}
public void testCatchingAsync_inputRaisesException() throws Exception {
final RuntimeException raisedException = new RuntimeException();
AsyncFunctionSpy<Throwable, Integer> fallback =
spy(
new AsyncFunction<Throwable, Integer>() {
@Override
public ListenableFuture<Integer> apply(Throwable t) throws Exception {
assertThat(t).isSameInstanceAs(raisedException);
return immediateFuture(20);
}
});
ListenableFuture<Integer> failingFuture = immediateFailedFuture(raisedException);
ListenableFuture<Integer> faultTolerantFuture =
catchingAsync(failingFuture, Throwable.class, fallback, directExecutor());
assertEquals(20, getDone(faultTolerantFuture).intValue());
fallback.verifyCallCount(1);
}
@GwtIncompatible // non-Throwable exceptionType
public void testCatchingAsync_inputCancelledWithoutFallback() throws Exception {
AsyncFunction<Throwable, Integer> fallback = unexpectedAsyncFunction();
ListenableFuture<Integer> originalFuture = immediateCancelledFuture();
ListenableFuture<Integer> faultTolerantFuture =
catchingAsync(originalFuture, IOException.class, fallback, directExecutor());
assertTrue(faultTolerantFuture.isCancelled());
}
public void testCatchingAsync_fallbackGeneratesRuntimeException() throws Exception {
RuntimeException expectedException = new RuntimeException();
runExpectedExceptionCatchingAsyncTest(expectedException, false);
}
public void testCatchingAsync_fallbackGeneratesCheckedException() throws Exception {
Exception expectedException = new Exception() {};
runExpectedExceptionCatchingAsyncTest(expectedException, false);
}
public void testCatchingAsync_fallbackGeneratesError() throws Exception {
final Error error = new Error("deliberate");
AsyncFunction<Throwable, Integer> fallback =
new AsyncFunction<Throwable, Integer>() {
@Override
public ListenableFuture<Integer> apply(Throwable t) throws Exception {
throw error;
}
};
ListenableFuture<Integer> failingFuture = immediateFailedFuture(new RuntimeException());
try {
getDone(catchingAsync(failingFuture, Throwable.class, fallback, directExecutor()));