Debian Codegraph @

src/test/java/io/reactivex/rxjava3/testsupport/TestSubscriberEx.java

raw
1 /*
2 * Copyright (c) 2016-present, RxJava Contributors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
5 * compliance with the License. You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software distributed under the License is
10 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
11 * the License for the specific language governing permissions and limitations under the License.
12 */
13
14 package io.reactivex.rxjava3.testsupport;
15
16 import java.util.concurrent.atomic.*;
17
18 import org.reactivestreams.*;
19
20 import io.reactivex.rxjava3.core.FlowableSubscriber;
21 import io.reactivex.rxjava3.internal.subscriptions.SubscriptionHelper;
22 import io.reactivex.rxjava3.operators.QueueFuseable;
23 import io.reactivex.rxjava3.operators.QueueSubscription;
24
25 /**
26 * An extended test subscriber that records events and allows making assertions about them.
27 *
28 * <p>You can override the onSubscribe, onNext, onError, onComplete, request and
29 * cancel methods but not the others (this is by design).
30 *
31 * <p>The TestSubscriber implements Disposable for convenience where dispose calls cancel.
32 *
33 * <p>When calling the default request method, you are requesting on behalf of the
34 * wrapped actual subscriber.
35 *
36 * @param <T> the value type
37 */
38 public class TestSubscriberEx<T>
39 extends BaseTestConsumerEx<T, TestSubscriberEx<T>>
40 implements FlowableSubscriber<T>, Subscription {
41 /** The actual subscriber to forward events to. */
42 private final Subscriber<? super T> downstream;
43
44 /** Makes sure the incoming Subscriptions get cancelled immediately. */
45 private volatile boolean cancelled;
46
47 /** Holds the current subscription if any. */
48 private final AtomicReference<Subscription> upstream;
49
50 /** Holds the requested amount until a subscription arrives. */
51 private final AtomicLong missedRequested;
52
53 private QueueSubscription<T> qs;
54
55 /**
56 * Constructs a non-forwarding TestSubscriber with an initial request value of {@link Long#MAX_VALUE}.
57 */
58 public TestSubscriberEx() {
59 this(EmptySubscriber.INSTANCE, Long.MAX_VALUE);
60 }
61
62 /**
63 * Constructs a non-forwarding TestSubscriber with the specified initial request value.
64 * <p>The TestSubscriber doesn't validate the initialRequest value so one can
65 * test sources with invalid values as well.
66 * @param initialRequest the initial request value
67 */
68 public TestSubscriberEx(long initialRequest) {
69 this(EmptySubscriber.INSTANCE, initialRequest);
70 }
71
72 /**
73 * Constructs a forwarding TestSubscriber but leaves the requesting to the wrapped subscriber.
74 * @param downstream the actual Subscriber to forward events to
75 */
76 public TestSubscriberEx(Subscriber<? super T> downstream) {
77 this(downstream, Long.MAX_VALUE);
78 }
79
80 /**
81 * Constructs a forwarding TestSubscriber with the specified initial request value.
82 * <p>The TestSubscriber doesn't validate the initialRequest value so one can
83 * test sources with invalid values as well.
84 * @param actual the actual Subscriber to forward events to
85 * @param initialRequest the initial request value
86 */
87 public TestSubscriberEx(Subscriber<? super T> actual, long initialRequest) {
88 super();
89 if (initialRequest < 0) {
90 throw new IllegalArgumentException("Negative initial request not allowed");
91 }
92 this.downstream = actual;
93 this.upstream = new AtomicReference<>();
94 this.missedRequested = new AtomicLong(initialRequest);
95 }
96
97 @SuppressWarnings("unchecked")
98 @Override
99 public void onSubscribe(Subscription s) {
100 lastThread = Thread.currentThread();
101
102 if (s == null) {
103 errors.add(new NullPointerException("onSubscribe received a null Subscription"));
104 return;
105 }
106 if (!upstream.compareAndSet(null, s)) {
107 s.cancel();
108 if (upstream.get() != SubscriptionHelper.CANCELLED) {
109 errors.add(new IllegalStateException("onSubscribe received multiple subscriptions: " + s));
110 }
111 return;
112 }
113
114 if (initialFusionMode != 0) {
115 if (s instanceof QueueSubscription) {
116 qs = (QueueSubscription<T>)s;
117
118 int m = qs.requestFusion(initialFusionMode);
119 establishedFusionMode = m;
120
121 if (m == QueueFuseable.SYNC) {
122 checkSubscriptionOnce = true;
123 lastThread = Thread.currentThread();
124 try {
125 T t;
126 while ((t = qs.poll()) != null) {
127 values.add(t);
128 }
129 completions++;
130 } catch (Throwable ex) {
131 // Exceptions.throwIfFatal(e); TODO add fatal exceptions?
132 errors.add(ex);
133 }
134 return;
135 }
136 }
137 }
138
139 downstream.onSubscribe(s);
140
141 long mr = missedRequested.getAndSet(0L);
142 if (mr != 0L) {
143 s.request(mr);
144 }
145
146 onStart();
147 }
148
149 /**
150 * Called after the onSubscribe is called and handled.
151 */
152 protected void onStart() {
153
154 }
155
156 @Override
157 public void onNext(T t) {
158 if (!checkSubscriptionOnce) {
159 checkSubscriptionOnce = true;
160 if (upstream.get() == null) {
161 errors.add(new IllegalStateException("onSubscribe not called in proper order"));
162 }
163 }
164 lastThread = Thread.currentThread();
165
166 if (establishedFusionMode == QueueFuseable.ASYNC) {
167 try {
168 while ((t = qs.poll()) != null) {
169 values.add(t);
170 }
171 } catch (Throwable ex) {
172 // Exceptions.throwIfFatal(e); TODO add fatal exceptions?
173 errors.add(ex);
174 qs.cancel();
175 }
176 return;
177 }
178
179 values.add(t);
180
181 if (t == null) {
182 errors.add(new NullPointerException("onNext received a null value"));
183 }
184
185 downstream.onNext(t);
186 }
187
188 @Override
189 public void onError(Throwable t) {
190 if (!checkSubscriptionOnce) {
191 checkSubscriptionOnce = true;
192 if (upstream.get() == null) {
193 errors.add(new NullPointerException("onSubscribe not called in proper order"));
194 }
195 }
196 try {
197 lastThread = Thread.currentThread();
198 errors.add(t);
199
200 if (t == null) {
201 errors.add(new IllegalStateException("onError received a null Throwable"));
202 }
203
204 downstream.onError(t);
205 } finally {
206 done.countDown();
207 }
208 }
209
210 @Override
211 public void onComplete() {
212 if (!checkSubscriptionOnce) {
213 checkSubscriptionOnce = true;
214 if (upstream.get() == null) {
215 errors.add(new IllegalStateException("onSubscribe not called in proper order"));
216 }
217 }
218 try {
219 lastThread = Thread.currentThread();
220 completions++;
221
222 downstream.onComplete();
223 } finally {
224 done.countDown();
225 }
226 }
227
228 @Override
229 public final void request(long n) {
230 SubscriptionHelper.deferredRequest(upstream, missedRequested, n);
231 }
232
233 @Override
234 public final void cancel() {
235 if (!cancelled) {
236 cancelled = true;
237 SubscriptionHelper.cancel(upstream);
238 }
239 }
240
241 /**
242 * Returns true if this TestSubscriber has been cancelled.
243 * @return true if this TestSubscriber has been cancelled
244 */
245 public final boolean isCancelled() {
246 return cancelled;
247 }
248
249 @Override
250 protected final void dispose() {
251 cancel();
252 }
253
254 @Override
255 protected final boolean isDisposed() {
256 return cancelled;
257 }
258
259 // state retrieval methods
260
261 /**
262 * Returns true if this TestSubscriber received a subscription.
263 * @return true if this TestSubscriber received a subscription
264 */
265 public final boolean hasSubscription() {
266 return upstream.get() != null;
267 }
268
269 // assertion methods
270
271 /**
272 * Assert that the onSubscribe method was called exactly once.
273 * @return this
274 */
275 @Override
276 public final TestSubscriberEx<T> assertSubscribed() {
277 if (upstream.get() == null) {
278 throw fail("Not subscribed!");
279 }
280 return this;
281 }
282
283 /**
284 * Assert that the onSubscribe method hasn't been called at all.
285 * @return this
286 */
287 public final TestSubscriberEx<T> assertNotSubscribed() {
288 if (upstream.get() != null) {
289 throw fail("Subscribed!");
290 } else
291 if (!errors.isEmpty()) {
292 throw fail("Not subscribed but errors found");
293 }
294 return this;
295 }
296
297 /**
298 * Sets the initial fusion mode if the upstream supports fusion.
299 * <p>Package-private: avoid leaking the now internal fusion properties into the public API.
300 * Use SubscriberFusion to work with such tests.
301 * @param mode the mode to establish, see the {@link QueueSubscription} constants
302 * @return this
303 */
304 public final TestSubscriberEx<T> setInitialFusionMode(int mode) {
305 this.initialFusionMode = mode;
306 return this;
307 }
308
309 /**
310 * Asserts that the given fusion mode has been established
311 * <p>Package-private: avoid leaking the now internal fusion properties into the public API.
312 * Use SubscriberFusion to work with such tests.
313 * @param mode the expected mode
314 * @return this
315 */
316 public final TestSubscriberEx<T> assertFusionMode(int mode) {
317 int m = establishedFusionMode;
318 if (m != mode) {
319 if (qs != null) {
320 throw new AssertionError("\nexpected: " + fusionModeToString(mode)
321 + "\ngot: " + fusionModeToString(m) + "; Fusion mode different");
322 } else {
323 throw fail("Upstream is not fuseable");
324 }
325 }
326 return this;
327 }
328
329 /**
330 * Assert that the upstream is a fuseable source.
331 * <p>Package-private: avoid leaking the now internal fusion properties into the public API.
332 * Use SubscriberFusion to work with such tests.
333 * @return this
334 */
335 public final TestSubscriberEx<T> assertFuseable() {
336 if (qs == null) {
337 throw new AssertionError("Upstream is not fuseable.");
338 }
339 return this;
340 }
341
342 /**
343 * Assert that the upstream is not a fuseable source.
344 * <p>Package-private: avoid leaking the now internal fusion properties into the public API.
345 * Use SubscriberFusion to work with such tests.
346 * @return this
347 */
348 public final TestSubscriberEx<T> assertNotFuseable() {
349 if (qs != null) {
350 throw new AssertionError("Upstream is fuseable.");
351 }
352 return this;
353 }
354
355 /**
356 * Calls {@link #request(long)} and returns this.
357 * <p>History: 2.0.1 - experimental
358 * @param n the request amount
359 * @return this
360 * @since 2.1
361 */
362 public final TestSubscriberEx<T> requestMore(long n) {
363 request(n);
364 return this;
365 }
366
367 /**
368 * A subscriber that ignores all events and does not report errors.
369 */
370 enum EmptySubscriber implements FlowableSubscriber<Object> {
371 INSTANCE;
372
373 @Override
374 public void onSubscribe(Subscription s) {
375 }
376
377 @Override
378 public void onNext(Object t) {
379 }
380
381 @Override
382 public void onError(Throwable t) {
383 }
384
385 @Override
386 public void onComplete() {
387 }
388 }
389 }