-
Notifications
You must be signed in to change notification settings - Fork 534
/
Copy pathPublisherVerificationTest.java
796 lines (691 loc) · 32.3 KB
/
PublisherVerificationTest.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
package org.reactivestreams.tck;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import org.reactivestreams.tck.support.TCKVerificationSupport;
import org.reactivestreams.tck.support.TestException;
import org.testng.annotations.Test;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Validates that the TCK's {@link org.reactivestreams.tck.PublisherVerification} fails with nice human readable errors.
* <b>Important: Please note that all Publishers implemented in this file are *wrong*!</b>
*/
public class PublisherVerificationTest extends TCKVerificationSupport {
@Test
public void required_spec101_subscriptionRequestMustResultInTheCorrectNumberOfProducedElements_shouldFailBy_ExpectingOnError() throws Throwable {
requireTestFailure(new ThrowingRunnable() {
@Override public void run() throws Throwable {
noopPublisherVerification().required_spec101_subscriptionRequestMustResultInTheCorrectNumberOfProducedElements();
}
}, "produced no element after first");
}
@Test
public void required_spec102_maySignalLessThanRequestedAndTerminateSubscription_shouldFailBy_notReceivingAnyElement() throws Throwable {
requireTestFailure(new ThrowingRunnable() {
@Override public void run() throws Throwable {
noopPublisherVerification().required_spec102_maySignalLessThanRequestedAndTerminateSubscription();
}
}, "Did not receive expected element");
}
@Test
public void required_spec102_maySignalLessThanRequestedAndTerminateSubscription_shouldFailBy_receivingTooManyElements() throws Throwable {
requireTestFailure(new ThrowingRunnable() {
@Override public void run() throws Throwable {
demandIgnoringSynchronousPublisherVerification().required_spec102_maySignalLessThanRequestedAndTerminateSubscription();
}
}, "Expected end-of-stream but got element [3]");
}
@Test
public void stochastic_spec103_mustSignalOnMethodsSequentially_shouldFailBy_concurrentlyAccessingOnNext() throws Throwable {
final AtomicInteger startedSignallingThreads = new AtomicInteger(0);
// this is an arbitrary number, we just need "many threads" to try to force an concurrent access scenario
final int maxSignallingThreads = 10;
final ExecutorService signallersPool = Executors.newFixedThreadPool(maxSignallingThreads);
final AtomicBoolean concurrentAccessCaused = new AtomicBoolean(false);
// highly specialised threadpool driven publisher which aims to FORCE concurrent access,
// so that we can confirm the test is able to catch this.
final Publisher<Integer> concurrentAccessPublisher = new Publisher<Integer>() {
@Override public void subscribe(final Subscriber<? super Integer> s) {
s.onSubscribe(new NoopSubscription() {
@Override public void request(final long n) {
Runnable signalling = new Runnable() {
@Override public void run() {
for (long i = 0; i < n; i++) {
try {
// shutdown cleanly in when the threadpool is shutting down
if (Thread.interrupted()) {
return;
}
s.onNext((int) i);
} catch (Exception ex) {
// signal others to shut down
signallersPool.shutdownNow();
if (ex instanceof TestEnvironment.Latch.ExpectedOpenLatchException) {
if (!concurrentAccessCaused.getAndSet(true)) {
throw new RuntimeException("Concurrent access detected", ex);
} else {
// error signalled once already, stop more errors from propagating
return;
}
} else {
throw new RuntimeException(ex);
}
}
}
}
};
// must be guarded like this in case a Subscriber triggers request() synchronously from it's onNext()
while (startedSignallingThreads.getAndAdd(1) < maxSignallingThreads && !signallersPool.isShutdown()) {
try {
signallersPool.execute(signalling);
} catch (RejectedExecutionException ex) {
// ignore, should be safe as it means the pool is shutting down -> which means we triggered the problem we wanted to
return;
}
}
}
});
}
};
try {
requireTestFailure(new ThrowingRunnable() {
@Override public void run() throws Throwable {
customPublisherVerification(concurrentAccessPublisher).stochastic_spec103_mustSignalOnMethodsSequentially();
}
}, "Illegal concurrent access detected");
} finally {
signallersPool.shutdownNow();
signallersPool.awaitTermination(1, TimeUnit.SECONDS);
}
}
@Test
public void stochastic_spec103_mustSignalOnMethodsSequentially_shouldPass_forSynchronousPublisher() throws Throwable {
customPublisherVerification(new Publisher<Integer>() {
@Override public void subscribe(final Subscriber<? super Integer> s) {
s.onSubscribe(new NoopSubscription() {
int element = 0;
@Override public void request(long n) {
for (int i = 0; i < n; i++) {
s.onNext(element++);
}
s.onComplete();
}
});
}
}).stochastic_spec103_mustSignalOnMethodsSequentially();
}
@Test
public void optional_spec104_mustSignalOnErrorWhenFails_shouldFail() throws Throwable {
final Publisher<Integer> invalidErrorPublisher = new Publisher<Integer>() {
@Override public void subscribe(Subscriber<? super Integer> s) {
throw new RuntimeException("It is not valid to throw here!");
}
};
requireTestFailure(new ThrowingRunnable() {
@Override public void run() throws Throwable {
customPublisherVerification(SKIP, invalidErrorPublisher).optional_spec104_mustSignalOnErrorWhenFails();
}
}, "Publisher threw exception (It is not valid to throw here!) instead of signalling error via onError!");
}
@Test
public void optional_spec104_mustSignalOnErrorWhenFails_shouldBeSkippedWhenNoErrorPublisherGiven() throws Throwable {
requireTestSkip(new ThrowingRunnable() {
@Override public void run() throws Throwable {
noopPublisherVerification().optional_spec104_mustSignalOnErrorWhenFails();
}
}, PublisherVerification.SKIPPING_NO_ERROR_PUBLISHER_AVAILABLE);
}
@Test
public void required_spec105_mustSignalOnCompleteWhenFiniteStreamTerminates_shouldFail() throws Throwable {
final Publisher<Integer> forgotToSignalCompletionPublisher = new Publisher<Integer>() {
@Override public void subscribe(final Subscriber<? super Integer> s) {
s.onSubscribe(new NoopSubscription() {
int signal = 0;
@Override public void request(long n) {
for (int i = 0; i < n; i++) {
s.onNext(signal);
signal += 1;
}
// intentional omission of onComplete
}
});
}
};
requireTestFailure(new ThrowingRunnable() {
@Override public void run() throws Throwable {
customPublisherVerification(forgotToSignalCompletionPublisher).required_spec105_mustSignalOnCompleteWhenFiniteStreamTerminates();
}
}, "Expected end-of-stream but got element [3]");
}
@Test
public void optional_spec105_emptyStreamMustTerminateBySignallingOnComplete_shouldNotAllowEagerOnComplete() throws Throwable {
final Publisher<Integer> illegalEmptyEagerOnCompletePublisher = new Publisher<Integer>() {
@Override public void subscribe(final Subscriber<? super Integer> s) {
s.onComplete();
}
};
requireTestFailure(new ThrowingRunnable() {
@Override public void run() throws Throwable {
PublisherVerification<Integer> verification = new PublisherVerification<Integer>(newTestEnvironment()) {
@Override public Publisher<Integer> createPublisher(long elements) {
return illegalEmptyEagerOnCompletePublisher;
}
@Override public long maxElementsFromPublisher() {
return 0; // it is an "empty" Publisher
}
@Override public Publisher<Integer> createErrorStatePublisher() {
return null;
}
};
verification.optional_spec105_emptyStreamMustTerminateBySignallingOnComplete();
}
}, "Subscriber::onComplete() called before Subscriber::onSubscribe");
}
@Test
public void required_spec107_mustNotEmitFurtherSignalsOnceOnCompleteHasBeenSignalled_shouldFailForNotCompletingPublisher() throws Throwable {
requireTestFailure(new ThrowingRunnable() {
@Override public void run() throws Throwable {
demandIgnoringSynchronousPublisherVerification().required_spec107_mustNotEmitFurtherSignalsOnceOnCompleteHasBeenSignalled();
}
}, "Expected end-of-stream but got element [" /* element which should not have been signalled */);
}
@Test
public void required_spec107_mustNotEmitFurtherSignalsOnceOnCompleteHasBeenSignalled_shouldFailForPublisherWhichCompletesButKeepsServingData() throws Throwable {
requireTestFailure(new ThrowingRunnable() {
@Override public void run() throws Throwable {
customPublisherVerification(new Publisher<Integer>() {
@Override public void subscribe(final Subscriber<? super Integer> s) {
s.onSubscribe(new NoopSubscription() {
boolean completed = false;
@Override public void request(long n) {
// emit one element
s.onNext(0);
// and "complete"
// but keep signalling data if more demand comes in anyway!
if (!completed) {
s.onComplete();
}
}
});
}
}).required_spec107_mustNotEmitFurtherSignalsOnceOnCompleteHasBeenSignalled();
}
}, "Unexpected element 0 received after stream completed");
}
@Test
public void required_spec109_subscribeThrowNPEOnNullSubscriber_shouldFailIfDoesntThrowNPE() throws Throwable {
requireTestFailure(new ThrowingRunnable() {
@Override public void run() throws Throwable {
customPublisherVerification(new Publisher<Integer>() {
@Override public void subscribe(final Subscriber<? super Integer> s) {
}
}).required_spec109_subscribeThrowNPEOnNullSubscriber();
}
}, "Publisher did not throw a NullPointerException when given a null Subscribe in subscribe");
}
@Test
public void optional_spec109_mayRejectCallsToSubscribeIfPublisherIsUnableOrUnwillingToServeThemRejectionMustTriggerOnErrorAfterOnSubscribe_actuallyPass() throws Throwable {
customPublisherVerification(SKIP, new Publisher<Integer>() {
@Override public void subscribe(Subscriber<? super Integer> s) {
s.onSubscribe(new NoopSubscription());
s.onError(new RuntimeException("Sorry, I'm busy now. Call me later."));
}
}).required_spec109_mayRejectCallsToSubscribeIfPublisherIsUnableOrUnwillingToServeThemRejectionMustTriggerOnErrorAfterOnSubscribe();
}
@Test
public void required_spec109_mustIssueOnSubscribeForNonNullSubscriber_mustFailIfOnCompleteHappensFirst() throws Throwable {
requireTestFailure(new ThrowingRunnable() {
@Override public void run() throws Throwable {
customPublisherVerification(new Publisher<Integer>() {
@Override
public void subscribe(Subscriber<? super Integer> s) {
s.onComplete();
}
}).required_spec109_mustIssueOnSubscribeForNonNullSubscriber();
}
}, "onSubscribe should be called prior to onComplete always");
}
@Test
public void required_spec109_mustIssueOnSubscribeForNonNullSubscriber_mustFailIfOnNextHappensFirst() throws Throwable {
requireTestFailure(new ThrowingRunnable() {
@Override public void run() throws Throwable {
customPublisherVerification(new Publisher<Integer>() {
@Override public void subscribe(Subscriber<? super Integer> s) {
s.onNext(1337);
}
}).required_spec109_mustIssueOnSubscribeForNonNullSubscriber();
}
}, "onSubscribe should be called prior to onNext always");
}
@Test
public void required_spec109_mustIssueOnSubscribeForNonNullSubscriber_mustFailIfOnErrorHappensFirst() throws Throwable {
requireTestFailure(new ThrowingRunnable() {
@Override public void run() throws Throwable {
customPublisherVerification(new Publisher<Integer>() {
@Override public void subscribe(Subscriber<? super Integer> s) {
s.onError(new TestException());
}
}).required_spec109_mustIssueOnSubscribeForNonNullSubscriber();
}
}, "onSubscribe should be called prior to onError always");
}
@Test
public void required_spec109_mayRejectCallsToSubscribeIfPublisherIsUnableOrUnwillingToServeThemRejectionMustTriggerOnErrorAfterOnSubscribe_shouldFail() throws Throwable {
requireTestFailure(new ThrowingRunnable() {
@Override
public void run() throws Throwable {
customPublisherVerification(SKIP, new Publisher<Integer>() {
@Override
public void subscribe(Subscriber<? super Integer> s) {
s.onSubscribe(new NoopSubscription());
}
}).required_spec109_mayRejectCallsToSubscribeIfPublisherIsUnableOrUnwillingToServeThemRejectionMustTriggerOnErrorAfterOnSubscribe();
}
}, "Should have received onError");
}
@Test
public void required_spec109_mayRejectCallsToSubscribeIfPublisherIsUnableOrUnwillingToServeThemRejectionMustTriggerOnErrorAfterOnSubscribe_beSkippedForNoGivenErrorPublisher() throws Throwable {
requireTestSkip(new ThrowingRunnable() {
@Override public void run() throws Throwable {
noopPublisherVerification().required_spec109_mayRejectCallsToSubscribeIfPublisherIsUnableOrUnwillingToServeThemRejectionMustTriggerOnErrorAfterOnSubscribe();
}
}, PublisherVerification.SKIPPING_NO_ERROR_PUBLISHER_AVAILABLE);
}
@Test
public void untested_spec110_rejectASubscriptionRequestIfTheSameSubscriberSubscribesTwice_shouldFailBy_skippingSinceOptional() throws Throwable {
requireTestFailure(new ThrowingRunnable() {
@Override public void run() throws Throwable {
noopPublisherVerification().untested_spec110_rejectASubscriptionRequestIfTheSameSubscriberSubscribesTwice();
}
}, "Not verified by this TCK.");
}
@Test
public void optional_spec111_maySupportMultiSubscribe_shouldFailBy_actuallyPass() throws Throwable {
noopPublisherVerification().optional_spec111_maySupportMultiSubscribe();
}
@Test
public void optional_spec111_multicast_mustProduceTheSameElementsInTheSameSequenceToAllOfItsSubscribersWhenRequestingManyUpfront_shouldFailBy_expectingOnError() throws Throwable {
requireTestFailure(new ThrowingRunnable() {
@Override public void run() throws Throwable {
customPublisherVerification(new Publisher<Integer>() {
@Override public void subscribe(final Subscriber<? super Integer> s) {
s.onSubscribe(new Subscription() {
final Random rnd = new Random();
@Override public void request(long n) {
for (int i = 0; i < n; i++) {
s.onNext(rnd.nextInt());
}
}
@Override public void cancel() {
}
});
}
}).optional_spec111_multicast_mustProduceTheSameElementsInTheSameSequenceToAllOfItsSubscribersWhenRequestingManyUpfront();
}
}, "Expected elements to be signaled in the same sequence to 1st and 2nd subscribers: Lists differ at element ");
}
@Test
public void required_spec302_mustAllowSynchronousRequestCallsFromOnNextAndOnSubscribe_shouldFailBy_reportingAsyncError() throws Throwable {
requireTestFailure(new ThrowingRunnable() {
@Override public void run() throws Throwable {
onErroringPublisherVerification().required_spec302_mustAllowSynchronousRequestCallsFromOnNextAndOnSubscribe();
}
}, "Async error during test execution: Test Exception: Boom!");
}
@Test
public void required_spec303_mustNotAllowUnboundedRecursion_shouldFailBy_informingAboutTooDeepStack() throws Throwable {
requireTestFailure(new ThrowingRunnable() {
@Override public void run() throws Throwable {
customPublisherVerification(new Publisher<Integer>() {
@Override public void subscribe(final Subscriber<? super Integer> s) {
s.onSubscribe(new Subscription() {
@Override public void request(long n) {
s.onNext(0); // naive reccursive call, would explode with StackOverflowException
}
@Override public void cancel() {
// noop
}
});
}
}).required_spec303_mustNotAllowUnboundedRecursion();
}
}, /* Got 2 onNext calls within thread: ... */ "yet expected recursive bound was 1");
}
@Test
public void required_spec306_afterSubscriptionIsCancelledRequestMustBeNops_shouldFailBy_unexpectedElement() throws Throwable {
requireTestFailure(new ThrowingRunnable() {
@Override public void run() throws Throwable {
demandIgnoringSynchronousPublisherVerification().required_spec306_afterSubscriptionIsCancelledRequestMustBeNops();
}
}, "Did not expect an element but got element [0]");
}
@Test
public void required_spec307_afterSubscriptionIsCancelledAdditionalCancelationsMustBeNops_shouldPass() throws Throwable {
demandIgnoringSynchronousPublisherVerification().required_spec307_afterSubscriptionIsCancelledAdditionalCancelationsMustBeNops();
}
@Test
public void required_spec307_afterSubscriptionIsCancelledAdditionalCancelationsMustBeNops_shouldFailBy_unexpectedErrorInCancelling() throws Throwable {
requireTestFailure(new ThrowingRunnable() {
@Override public void run() throws Throwable {
customPublisherVerification(new Publisher<Integer>() {
@Override public void subscribe(final Subscriber<? super Integer> s) {
s.onSubscribe(new Subscription() {
@Override public void request(long n) {
// noop
}
@Override public void cancel() {
s.onError(new TestException()); // illegal error signalling!
}
});
}
}).required_spec307_afterSubscriptionIsCancelledAdditionalCancelationsMustBeNops();
}
}, "Async error during test execution: Test Exception: Boom!");
}
@Test
public void required_spec309_requestZeroMustSignalIllegalArgumentException_shouldFailBy_expectingOnError() throws Throwable {
requireTestFailure(new ThrowingRunnable() {
@Override public void run() throws Throwable {
noopPublisherVerification().required_spec309_requestZeroMustSignalIllegalArgumentException();
}
}, "Expected onError");
}
@Test
public void required_spec309_requestNegativeNumberMustSignalIllegalArgumentException_shouldFailBy_expectingOnError() throws Throwable {
requireTestFailure(new ThrowingRunnable() {
@Override public void run() throws Throwable {
noopPublisherVerification().required_spec309_requestNegativeNumberMustSignalIllegalArgumentException();
}
}, "Expected onError");
}
@Test
public void required_spec312_cancelMustMakeThePublisherToEventuallyStopSignaling_shouldFailBy_havingEmitedMoreThanRequested() throws Throwable {
final ExecutorService pool = Executors.newFixedThreadPool(2);
try {
requireTestFailure(new ThrowingRunnable() {
@Override public void run() throws Throwable {
demandIgnoringAsynchronousPublisherVerification(pool).required_spec312_cancelMustMakeThePublisherToEventuallyStopSignaling();
}
}, /*Publisher signalled [...] */ ", which is more than the signalled demand: ");
} finally {
pool.shutdownNow();
pool.awaitTermination(1, TimeUnit.SECONDS);
}
}
@Test
public void required_spec313_cancelMustMakeThePublisherEventuallyDropAllReferencesToTheSubscriber_shouldFailBy_keepingTheReferenceLongerThanNeeded() throws Throwable {
requireTestFailure(new ThrowingRunnable() {
@Override public void run() throws Throwable {
customPublisherVerification(new Publisher<Integer>() {
Subscriber subs = null;
@Override public void subscribe(final Subscriber<? super Integer> s) {
subs = s; // keep the reference
s.onSubscribe(new Subscription() {
@Override public void request(long n) {
for (int i = 0; i < n; i++) {
s.onNext((int) n);
}
}
@Override public void cancel() {
// noop, we still keep the reference!
}
});
}
}).required_spec313_cancelMustMakeThePublisherEventuallyDropAllReferencesToTheSubscriber();
}
}, "did not drop reference to test subscriber after subscription cancellation");
}
@Test
public void required_spec317_mustSupportAPendingElementCountUpToLongMaxValue_shouldFail_onAsynchDemandIgnoringPublisher() throws Throwable {
// 10 is arbitrary here, we just need a "larger number" to get into concurrent access scenarios, anything more than 2
// should work, but getting up to 10 should be safer and doesn't hurt to play safe here
final ExecutorService pool = Executors.newFixedThreadPool(10);
try {
requireTestFailure(new ThrowingRunnable() {
@Override public void run() throws Throwable {
demandIgnoringAsynchronousPublisherVerification(pool).required_spec317_mustSupportAPendingElementCountUpToLongMaxValue();
}
}, "Expected end-of-stream but got");
} finally {
pool.shutdownNow();
pool.awaitTermination(1, TimeUnit.SECONDS);
}
}
@Test
public void required_spec317_mustSupportAPendingElementCountUpToLongMaxValue_shouldFail_onSynchDemandIgnoringPublisher() throws Throwable {
requireTestFailure(new ThrowingRunnable() {
@Override public void run() throws Throwable {
demandIgnoringSynchronousPublisherVerification().required_spec317_mustSupportAPendingElementCountUpToLongMaxValue();
}
}, "Received more than bufferSize (32) onNext signals. The Publisher probably emited more signals than expected!");
}
@Test
public void required_spec317_mustNotSignalOnErrorWhenPendingAboveLongMaxValue_shouldFail_onSynchOverflowingPublisher() throws Throwable {
requireTestFailure(new ThrowingRunnable() {
@Override public void run() throws Throwable {
customPublisherVerification(new Publisher<Integer>() {
long demand = 0;
@Override public void subscribe(final Subscriber<? super Integer> s) {
s.onSubscribe(new Subscription() {
@Override public void request(long n) {
// it does not protect from demand overflow!
demand += n;
if (demand < 0) {
// overflow
s.onError(new IllegalStateException("Illegally signalling onError (violates rule 3.17)")); // Illegally signal error
} else {
s.onNext(0);
}
}
@Override public void cancel() {
// noop
}
});
}
}).required_spec317_mustNotSignalOnErrorWhenPendingAboveLongMaxValue();
}
}, "Async error during test execution: Illegally signalling onError (violates rule 3.17)");
}
@Test
public void required_spec317_mustSupportACumulativePendingElementCountUpToLongMaxValue_shouldFailWhenErrorSignalledOnceMaxValueReached() throws Throwable {
requireTestFailure(new ThrowingRunnable() {
@Override public void run() throws Throwable {
customPublisherVerification(new Publisher<Integer>() {
long demand = 0;
@Override public void subscribe(final Subscriber<? super Integer> s) {
s.onSubscribe(new NoopSubscription() {
@Override public void request(long n) {
demand += n;
// this is a mistake, it should still be able to accumulate such demand
if (demand == Long.MAX_VALUE)
s.onError(new IllegalStateException("Illegally signalling onError too soon! " +
"Cumulative demand equal to Long.MAX_VALUE is legal."));
s.onNext(0);
}
});
}
}).required_spec317_mustSupportACumulativePendingElementCountUpToLongMaxValue();
}
}, "Async error during test execution: Illegally signalling onError too soon!");
}
// FAILING IMPLEMENTATIONS //
final Publisher<Integer> SKIP = null;
/** Subscription which does nothing. */
static class NoopSubscription implements Subscription {
@Override public void request(long n) {
// noop
}
@Override public void cancel() {
// noop
}
}
/**
* Verification using a Publisher that never publishes any element.
* Skips the error state publisher tests.
*/
final PublisherVerification<Integer> noopPublisherVerification() {
return new PublisherVerification<Integer>(newTestEnvironment()) {
@Override public Publisher<Integer> createPublisher(long elements) {
return new Publisher<Integer>() {
@Override public void subscribe(Subscriber<? super Integer> s) {
s.onSubscribe(new NoopSubscription());
}
};
}
@Override public Publisher<Integer> createErrorStatePublisher() {
return SKIP;
}
};
}
/**
* Verification using a Publisher that never publishes any element
*/
final PublisherVerification<Integer> onErroringPublisherVerification() {
return new PublisherVerification<Integer>(newTestEnvironment()) {
@Override public Publisher<Integer> createPublisher(long elements) {
return new Publisher<Integer>() {
@Override public void subscribe(final Subscriber<? super Integer> s) {
s.onSubscribe(new NoopSubscription() {
@Override public void request(long n) {
s.onError(new TestException());
}
});
}
};
}
@Override public Publisher<Integer> createErrorStatePublisher() {
return SKIP;
}
};
}
/**
* Custom Verification using given Publishers
*/
final PublisherVerification<Integer> customPublisherVerification(final Publisher<Integer> pub) {
return customPublisherVerification(pub, SKIP);
}
/**
* Custom Verification using given Publishers
*/
final PublisherVerification<Integer> customPublisherVerification(final Publisher<Integer> pub, final Publisher<Integer> errorPub) {
return new PublisherVerification<Integer>(newTestEnvironment()) {
@Override public Publisher<Integer> createPublisher(long elements) {
return pub;
}
@Override public Publisher<Integer> createErrorStatePublisher() {
return errorPub;
}
};
}
/**
* Verification using a Publisher that publishes elements even with no demand available
*/
final PublisherVerification<Integer> demandIgnoringSynchronousPublisherVerification() {
return new PublisherVerification<Integer>(newTestEnvironment()) {
@Override public Publisher<Integer> createPublisher(long elements) {
return new Publisher<Integer>() {
@Override public void subscribe(final Subscriber<? super Integer> s) {
s.onSubscribe(new NoopSubscription() {
@Override public void request(long n) {
for (long i = 0; i <= n; i++) {
// one too much
s.onNext((int) i);
}
}
});
}
};
}
@Override public Publisher<Integer> createErrorStatePublisher() {
return SKIP;
}
};
}
/**
* Verification using a Publisher that publishes elements even with no demand available, from multiple threads (!).
*
* Please note that exceptions thrown from onNext *will be swallowed* – reason being this verification is used to check
* very specific things about error reporting - from the "TCK Tests", we do not have any assertions on thrown exceptions.
*/
final PublisherVerification<Integer> demandIgnoringAsynchronousPublisherVerification(final ExecutorService signallersPool) {
return demandIgnoringAsynchronousPublisherVerification(signallersPool, true);
}
/**
* Verification using a Publisher that publishes elements even with no demand available, from multiple threads (!).
*/
final PublisherVerification<Integer> demandIgnoringAsynchronousPublisherVerification(final ExecutorService signallersPool, final boolean swallowOnNextExceptions) {
final AtomicInteger startedSignallingThreads = new AtomicInteger(0);
final int maxSignallingThreads = 2;
final AtomicBoolean concurrentAccessCaused = new AtomicBoolean(false);
return new PublisherVerification<Integer>(newTestEnvironment()) {
@Override public Publisher<Integer> createPublisher(long elements) {
return new Publisher<Integer>() {
@Override public void subscribe(final Subscriber<? super Integer> s) {
s.onSubscribe(new NoopSubscription() {
@Override public void request(final long n) {
Runnable signalling = new Runnable() {
@Override public void run() {
for (long i = 0; i <= n; i++) {
// one signal too much
try {
final long signal = i;
signallersPool.execute(new Runnable() {
@Override public void run() {
try {
s.onNext((int) signal);
} catch (Exception ex) {
if (!swallowOnNextExceptions) {
throw new RuntimeException("onNext threw an exception!", ex);
} else {
// yes, swallow the exception, we're not asserting and they'd just end up being logged (stdout),
// which we do not need in this specific PublisherVerificationTest
}
}
}
});
} catch (Exception ex) {
if (ex instanceof TestEnvironment.Latch.ExpectedOpenLatchException) {
if (concurrentAccessCaused.compareAndSet(false, true)) {
throw new RuntimeException("Concurrent access detected", ex);
} else {
// error signalled once already, stop more errors from propagating
return;
}
} else if (ex instanceof RejectedExecutionException) {
// ignore - this may happen since one thread may have already gotten into a concurrent access
// problem and initiated the pool's shutdown. It will then throw RejectedExecutionException.
} else {
if (concurrentAccessCaused.get()) {
return;
} else {
throw new RuntimeException(ex);
}
}
}
}
}
};
// must be guarded like this in case a Subscriber triggers request() synchronously from it's onNext()
while (startedSignallingThreads.getAndAdd(1) < maxSignallingThreads) {
signallersPool.execute(signalling);
}
}
});
}
};
}
@Override public Publisher<Integer> createErrorStatePublisher() {
return SKIP;
}
};
}
private TestEnvironment newTestEnvironment() {
return new TestEnvironment();
}
}