-
Notifications
You must be signed in to change notification settings - Fork 7.6k
/
Copy pathTestSubscriber.java
445 lines (387 loc) · 13.4 KB
/
TestSubscriber.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
/**
* Copyright (c) 2016-present, RxJava Contributors.
*
* 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 io.reactivex.subscribers;
import java.util.concurrent.atomic.*;
import org.reactivestreams.*;
import io.reactivex.FlowableSubscriber;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.internal.fuseable.QueueSubscription;
import io.reactivex.internal.subscriptions.SubscriptionHelper;
import io.reactivex.internal.util.ExceptionHelper;
import io.reactivex.observers.BaseTestConsumer;
/**
* A subscriber that records events and allows making assertions about them.
*
* <p>You can override the onSubscribe, onNext, onError, onComplete, request and
* cancel methods but not the others (this is by design).
*
* <p>The TestSubscriber implements Disposable for convenience where dispose calls cancel.
*
* <p>When calling the default request method, you are requesting on behalf of the
* wrapped actual subscriber.
*
* @param <T> the value type
*/
public class TestSubscriber<T>
extends BaseTestConsumer<T, TestSubscriber<T>>
implements FlowableSubscriber<T>, Subscription, Disposable {
/** The actual subscriber to forward events to. */
private final Subscriber<? super T> actual;
/** Makes sure the incoming Subscriptions get cancelled immediately. */
private volatile boolean cancelled;
/** Holds the current subscription if any. */
private final AtomicReference<Subscription> subscription;
/** Holds the requested amount until a subscription arrives. */
private final AtomicLong missedRequested;
private QueueSubscription<T> qs;
/**
* Creates a TestSubscriber with Long.MAX_VALUE initial request.
* @param <T> the value type
* @return the new TestSubscriber instance.
*/
public static <T> TestSubscriber<T> create() {
return new TestSubscriber<T>();
}
/**
* Creates a TestSubscriber with the given initial request.
* @param <T> the value type
* @param initialRequested the initial requested amount
* @return the new TestSubscriber instance.
*/
public static <T> TestSubscriber<T> create(long initialRequested) {
return new TestSubscriber<T>(initialRequested);
}
/**
* Constructs a forwarding TestSubscriber.
* @param <T> the value type received
* @param delegate the actual Subscriber to forward events to
* @return the new TestObserver instance
*/
public static <T> TestSubscriber<T> create(Subscriber<? super T> delegate) {
return new TestSubscriber<T>(delegate);
}
/**
* Constructs a non-forwarding TestSubscriber with an initial request value of Long.MAX_VALUE.
*/
public TestSubscriber() {
this(EmptySubscriber.INSTANCE, Long.MAX_VALUE);
}
/**
* Constructs a non-forwarding TestSubscriber with the specified initial request value.
* <p>The TestSubscriber doesn't validate the initialRequest value so one can
* test sources with invalid values as well.
* @param initialRequest the initial request value
*/
public TestSubscriber(long initialRequest) {
this(EmptySubscriber.INSTANCE, initialRequest);
}
/**
* Constructs a forwarding TestSubscriber but leaves the requesting to the wrapped subscriber.
* @param actual the actual Subscriber to forward events to
*/
public TestSubscriber(Subscriber<? super T> actual) {
this(actual, Long.MAX_VALUE);
}
/**
* Constructs a forwarding TestSubscriber with the specified initial request value.
* <p>The TestSubscriber doesn't validate the initialRequest value so one can
* test sources with invalid values as well.
* @param actual the actual Subscriber to forward events to
* @param initialRequest the initial request value
*/
public TestSubscriber(Subscriber<? super T> actual, long initialRequest) {
super();
if (initialRequest < 0) {
throw new IllegalArgumentException("Negative initial request not allowed");
}
this.actual = actual;
this.subscription = new AtomicReference<Subscription>();
this.missedRequested = new AtomicLong(initialRequest);
}
@SuppressWarnings("unchecked")
@Override
public void onSubscribe(Subscription s) {
lastThread = Thread.currentThread();
if (s == null) {
errors.add(new NullPointerException("onSubscribe received a null Subscription"));
return;
}
if (!subscription.compareAndSet(null, s)) {
s.cancel();
if (subscription.get() != SubscriptionHelper.CANCELLED) {
errors.add(new IllegalStateException("onSubscribe received multiple subscriptions: " + s));
}
return;
}
if (initialFusionMode != 0) {
if (s instanceof QueueSubscription) {
qs = (QueueSubscription<T>)s;
int m = qs.requestFusion(initialFusionMode);
establishedFusionMode = m;
if (m == QueueSubscription.SYNC) {
checkSubscriptionOnce = true;
lastThread = Thread.currentThread();
try {
T t;
while ((t = qs.poll()) != null) {
values.add(t);
}
completions++;
} catch (Throwable ex) {
// Exceptions.throwIfFatal(e); TODO add fatal exceptions?
errors.add(ex);
}
return;
}
}
}
actual.onSubscribe(s);
long mr = missedRequested.getAndSet(0L);
if (mr != 0L) {
s.request(mr);
}
onStart();
}
/**
* Called after the onSubscribe is called and handled.
*/
protected void onStart() {
}
@Override
public void onNext(T t) {
if (!checkSubscriptionOnce) {
checkSubscriptionOnce = true;
if (subscription.get() == null) {
errors.add(new IllegalStateException("onSubscribe not called in proper order"));
}
}
lastThread = Thread.currentThread();
if (establishedFusionMode == QueueSubscription.ASYNC) {
try {
while ((t = qs.poll()) != null) {
values.add(t);
}
} catch (Throwable ex) {
// Exceptions.throwIfFatal(e); TODO add fatal exceptions?
errors.add(ex);
qs.cancel();
}
return;
}
values.add(t);
if (t == null) {
errors.add(new NullPointerException("onNext received a null value"));
}
actual.onNext(t);
}
@Override
public void onError(Throwable t) {
if (!checkSubscriptionOnce) {
checkSubscriptionOnce = true;
if (subscription.get() == null) {
errors.add(new NullPointerException("onSubscribe not called in proper order"));
}
}
try {
lastThread = Thread.currentThread();
errors.add(t);
if (t == null) {
errors.add(new IllegalStateException("onError received a null Throwable"));
}
actual.onError(t);
} finally {
done.countDown();
}
}
@Override
public void onComplete() {
if (!checkSubscriptionOnce) {
checkSubscriptionOnce = true;
if (subscription.get() == null) {
errors.add(new IllegalStateException("onSubscribe not called in proper order"));
}
}
try {
lastThread = Thread.currentThread();
completions++;
actual.onComplete();
} finally {
done.countDown();
}
}
@Override
public final void request(long n) {
SubscriptionHelper.deferredRequest(subscription, missedRequested, n);
}
@Override
public final void cancel() {
if (!cancelled) {
cancelled = true;
SubscriptionHelper.cancel(subscription);
}
}
/**
* Returns true if this TestSubscriber has been cancelled.
* @return true if this TestSubscriber has been cancelled
*/
public final boolean isCancelled() {
return cancelled;
}
@Override
public final void dispose() {
cancel();
}
@Override
public final boolean isDisposed() {
return cancelled;
}
// state retrieval methods
/**
* Returns true if this TestSubscriber received a subscription.
* @return true if this TestSubscriber received a subscription
*/
public final boolean hasSubscription() {
return subscription.get() != null;
}
// assertion methods
/**
* Assert that the onSubscribe method was called exactly once.
* @return this
*/
@Override
public final TestSubscriber<T> assertSubscribed() {
if (subscription.get() == null) {
throw fail("Not subscribed!");
}
return this;
}
/**
* Assert that the onSubscribe method hasn't been called at all.
* @return this
*/
@Override
public final TestSubscriber<T> assertNotSubscribed() {
if (subscription.get() != null) {
throw fail("Subscribed!");
} else
if (!errors.isEmpty()) {
throw fail("Not subscribed but errors found");
}
return this;
}
/**
* Sets the initial fusion mode if the upstream supports fusion.
* <p>Package-private: avoid leaking the now internal fusion properties into the public API.
* Use SubscriberFusion to work with such tests.
* @param mode the mode to establish, see the {@link QueueSubscription} constants
* @return this
*/
final TestSubscriber<T> setInitialFusionMode(int mode) {
this.initialFusionMode = mode;
return this;
}
/**
* Asserts that the given fusion mode has been established
* <p>Package-private: avoid leaking the now internal fusion properties into the public API.
* Use SubscriberFusion to work with such tests.
* @param mode the expected mode
* @return this
*/
final TestSubscriber<T> assertFusionMode(int mode) {
int m = establishedFusionMode;
if (m != mode) {
if (qs != null) {
throw new AssertionError("Fusion mode different. Expected: " + fusionModeToString(mode)
+ ", actual: " + fusionModeToString(m));
} else {
throw fail("Upstream is not fuseable");
}
}
return this;
}
static String fusionModeToString(int mode) {
switch (mode) {
case QueueSubscription.NONE : return "NONE";
case QueueSubscription.SYNC : return "SYNC";
case QueueSubscription.ASYNC : return "ASYNC";
default: return "Unknown(" + mode + ")";
}
}
/**
* Assert that the upstream is a fuseable source.
* <p>Package-private: avoid leaking the now internal fusion properties into the public API.
* Use SubscriberFusion to work with such tests.
* @return this
*/
final TestSubscriber<T> assertFuseable() {
if (qs == null) {
throw new AssertionError("Upstream is not fuseable.");
}
return this;
}
/**
* Assert that the upstream is not a fuseable source.
* <p>Package-private: avoid leaking the now internal fusion properties into the public API.
* Use SubscriberFusion to work with such tests.
* @return this
*/
final TestSubscriber<T> assertNotFuseable() {
if (qs != null) {
throw new AssertionError("Upstream is fuseable.");
}
return this;
}
/**
* Run a check consumer with this TestSubscriber instance.
* @param check the check consumer to run
* @return this
*/
public final TestSubscriber<T> assertOf(Consumer<? super TestSubscriber<T>> check) {
try {
check.accept(this);
} catch (Throwable ex) {
throw ExceptionHelper.wrapOrThrow(ex);
}
return this;
}
/**
* Calls {@link #request(long)} and returns this.
* <p>History: 2.0.1 - experimental
* @param n the request amount
* @return this
* @since 2.1
*/
public final TestSubscriber<T> requestMore(long n) {
request(n);
return this;
}
/**
* A subscriber that ignores all events and does not report errors.
*/
enum EmptySubscriber implements FlowableSubscriber<Object> {
INSTANCE;
@Override
public void onSubscribe(Subscription s) {
}
@Override
public void onNext(Object t) {
}
@Override
public void onError(Throwable t) {
}
@Override
public void onComplete() {
}
}
}