forked from reactive-streams/reactive-streams-jvm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAsyncSubscriberTest.java
67 lines (55 loc) · 2.12 KB
/
AsyncSubscriberTest.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
package org.reactivestreams.example.unicast;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.reactivestreams.tck.SubscriberBlackboxVerification;
import org.reactivestreams.tck.TestEnvironment;
import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.AfterClass;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.TimeUnit;
@Test // Must be here for TestNG to find and run this, do not remove
public class AsyncSubscriberTest extends SubscriberBlackboxVerification<Integer> {
final static long DEFAULT_TIMEOUT_MILLIS = 100;
private ExecutorService e;
@BeforeClass void before() { e = Executors.newFixedThreadPool(4); }
@AfterClass void after() { if (e != null) e.shutdown(); }
public AsyncSubscriberTest() {
super(new TestEnvironment(DEFAULT_TIMEOUT_MILLIS));
}
@Override public Subscriber<Integer> createSubscriber() {
return new AsyncSubscriber<Integer>(e) {
@Override protected boolean whenNext(final Integer element) {
return true;
}
};
}
@Test public void testAccumulation() throws InterruptedException {
final AtomicLong i = new AtomicLong(Long.MIN_VALUE);
final CountDownLatch latch = new CountDownLatch(1);
final Subscriber<Integer> sub = new AsyncSubscriber<Integer>(e) {
private long acc;
@Override protected boolean whenNext(final Integer element) {
acc += element;
return true;
}
@Override protected void whenComplete() {
i.set(acc);
latch.countDown();
}
};
new NumberIterablePublisher(0, 10, e).subscribe(sub);
latch.await(DEFAULT_TIMEOUT_MILLIS * 10, TimeUnit.MILLISECONDS);
assertEquals(i.get(), 45);
}
@Override public Integer createElement(int element) {
return element;
}
@Override public Publisher<Integer> createHelperPublisher(long elements) {
return super.createHelperPublisher(elements);
}
}