Debian Codegraph @

src/main/java/io/reactivex/rxjava3/subscribers/TestSubscriber.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.subscribers;
15
16 import java.util.concurrent.atomic.*;
17
18 import org.reactivestreams.*;
19
20 import io.reactivex.rxjava3.annotations.NonNull;
21 import io.reactivex.rxjava3.core.FlowableSubscriber;
22 import io.reactivex.rxjava3.internal.subscriptions.SubscriptionHelper;
23 import io.reactivex.rxjava3.observers.BaseTestConsumer;
24
25 /**
26 * A {@link Subscriber} implementation that records events and allows making assertions about them.
27 *
28 * <p>You can override the {@link #onSubscribe(Subscription)}, {@link #onNext(Object)}, {@link #onError(Throwable)} and
29 * {@link #onComplete()} methods but not the others (this is by design).
30 *
31 * <p>When calling the default request method, you are requesting on behalf of the
32 * wrapped actual {@link Subscriber} if any.
33 *
34 * @param <T> the value type
35 */
36 public class TestSubscriber<T>
37 extends BaseTestConsumer<T, TestSubscriber<T>>
38 implements FlowableSubscriber<T>, Subscription {
39 /** The actual subscriber to forward events to. */
40 private final Subscriber<? super T> downstream;
41
42 /** Makes sure the incoming Subscriptions get cancelled immediately. */
43 private volatile boolean cancelled;
44
45 /** Holds the current subscription if any. */
46 private final AtomicReference<Subscription> upstream;
47
48 /** Holds the requested amount until a subscription arrives. */
49 private final AtomicLong missedRequested;
50
51 /**
52 * Creates a {@code TestSubscriber} with {@link Long#MAX_VALUE} initial request amount.
53 * @param <T> the value type
54 * @return the new {@code TestSubscriber} instance.
55 * @see #create(long)
56 */
57 @NonNull
58 public static <T> TestSubscriber<T> create() {
59 return new TestSubscriber<>();
60 }
61
62 /**
63 * Creates a {@code TestSubscriber} with the given initial request amount.
64 * @param <T> the value type
65 * @param initialRequested the initial requested amount
66 * @return the new {@code TestSubscriber} instance.
67 */
68 @NonNull
69 public static <T> TestSubscriber<T> create(long initialRequested) {
70 return new TestSubscriber<>(initialRequested);
71 }
72
73 /**
74 * Constructs a forwarding {@code TestSubscriber}.
75 * @param <T> the value type received
76 * @param delegate the actual {@link Subscriber} to forward events to
77 * @return the new TestObserver instance
78 */
79 public static <T> TestSubscriber<T> create(@NonNull Subscriber<? super T> delegate) {
80 return new TestSubscriber<>(delegate);
81 }
82
83 /**
84 * Constructs a non-forwarding {@code TestSubscriber} with an initial request value of {@link Long#MAX_VALUE}.
85 */
86 public TestSubscriber() {
87 this(EmptySubscriber.INSTANCE, Long.MAX_VALUE);
88 }
89
90 /**
91 * Constructs a non-forwarding {@code TestSubscriber} with the specified initial request value.
92 * <p>The {@code TestSubscriber} doesn't validate the {@code initialRequest} amount so one can
93 * test sources with invalid values as well.
94 * @param initialRequest the initial request amount
95 */
96 public TestSubscriber(long initialRequest) {
97 this(EmptySubscriber.INSTANCE, initialRequest);
98 }
99
100 /**
101 * Constructs a forwarding {@code TestSubscriber} but leaves the requesting to the wrapped {@link Subscriber}.
102 * @param downstream the actual {@code Subscriber} to forward events to
103 */
104 public TestSubscriber(@NonNull Subscriber<? super T> downstream) {
105 this(downstream, Long.MAX_VALUE);
106 }
107
108 /**
109 * Constructs a forwarding {@code TestSubscriber} with the specified initial request amount
110 * and an actual {@link Subscriber} to forward events to.
111 * <p>The {@code TestSubscriber} doesn't validate the initialRequest value so one can
112 * test sources with invalid values as well.
113 * @param actual the actual {@code Subscriber} to forward events to
114 * @param initialRequest the initial request amount
115 */
116 public TestSubscriber(@NonNull Subscriber<? super T> actual, long initialRequest) {
117 super();
118 if (initialRequest < 0) {
119 throw new IllegalArgumentException("Negative initial request not allowed");
120 }
121 this.downstream = actual;
122 this.upstream = new AtomicReference<>();
123 this.missedRequested = new AtomicLong(initialRequest);
124 }
125
126 @Override
127 public void onSubscribe(@NonNull Subscription s) {
128 lastThread = Thread.currentThread();
129
130 if (s == null) {
131 errors.add(new NullPointerException("onSubscribe received a null Subscription"));
132 return;
133 }
134 if (!upstream.compareAndSet(null, s)) {
135 s.cancel();
136 if (upstream.get() != SubscriptionHelper.CANCELLED) {
137 errors.add(new IllegalStateException("onSubscribe received multiple subscriptions: " + s));
138 }
139 return;
140 }
141
142 downstream.onSubscribe(s);
143
144 long mr = missedRequested.getAndSet(0L);
145 if (mr != 0L) {
146 s.request(mr);
147 }
148
149 onStart();
150 }
151
152 /**
153 * Called after the onSubscribe is called and handled.
154 */
155 protected void onStart() {
156
157 }
158
159 @Override
160 public void onNext(@NonNull T t) {
161 if (!checkSubscriptionOnce) {
162 checkSubscriptionOnce = true;
163 if (upstream.get() == null) {
164 errors.add(new IllegalStateException("onSubscribe not called in proper order"));
165 }
166 }
167 lastThread = Thread.currentThread();
168
169 values.add(t);
170
171 if (t == null) {
172 errors.add(new NullPointerException("onNext received a null value"));
173 }
174
175 downstream.onNext(t);
176 }
177
178 @Override
179 public void onError(@NonNull Throwable t) {
180 if (!checkSubscriptionOnce) {
181 checkSubscriptionOnce = true;
182 if (upstream.get() == null) {
183 errors.add(new IllegalStateException("onSubscribe not called in proper order"));
184 }
185 }
186 try {
187 lastThread = Thread.currentThread();
188
189 if (t == null) {
190 errors.add(new NullPointerException("onError received a null Throwable"));
191 } else {
192 errors.add(t);
193 }
194
195 downstream.onError(t);
196 } finally {
197 done.countDown();
198 }
199 }
200
201 @Override
202 public void onComplete() {
203 if (!checkSubscriptionOnce) {
204 checkSubscriptionOnce = true;
205 if (upstream.get() == null) {
206 errors.add(new IllegalStateException("onSubscribe not called in proper order"));
207 }
208 }
209 try {
210 lastThread = Thread.currentThread();
211 completions++;
212
213 downstream.onComplete();
214 } finally {
215 done.countDown();
216 }
217 }
218
219 @Override
220 public final void request(long n) {
221 SubscriptionHelper.deferredRequest(upstream, missedRequested, n);
222 }
223
224 @Override
225 public final void cancel() {
226 if (!cancelled) {
227 cancelled = true;
228 SubscriptionHelper.cancel(upstream);
229 }
230 }
231
232 /**
233 * Returns true if this {@code TestSubscriber} has been cancelled.
234 * @return true if this {@code TestSubscriber} has been cancelled
235 */
236 public final boolean isCancelled() {
237 return cancelled;
238 }
239
240 @Override
241 protected final void dispose() {
242 cancel();
243 }
244
245 @Override
246 protected final boolean isDisposed() {
247 return cancelled;
248 }
249
250 // state retrieval methods
251
252 /**
253 * Returns true if this {@code TestSubscriber} received a {@link Subscription} via {@link #onSubscribe(Subscription)}.
254 * @return true if this {@code TestSubscriber} received a {@link Subscription} via {@link #onSubscribe(Subscription)}
255 */
256 public final boolean hasSubscription() {
257 return upstream.get() != null;
258 }
259
260 // assertion methods
261
262 /**
263 * Assert that the {@link #onSubscribe(Subscription)} method was called exactly once.
264 * @return this
265 */
266 @Override
267 protected final TestSubscriber<T> assertSubscribed() {
268 if (upstream.get() == null) {
269 throw fail("Not subscribed!");
270 }
271 return this;
272 }
273
274 /**
275 * Calls {@link #request(long)} and returns this.
276 * <p>History: 2.0.1 - experimental
277 * @param n the request amount
278 * @return this
279 * @since 2.1
280 */
281 public final TestSubscriber<T> requestMore(long n) {
282 request(n);
283 return this;
284 }
285
286 /**
287 * A subscriber that ignores all events and does not report errors.
288 */
289 enum EmptySubscriber implements FlowableSubscriber<Object> {
290 INSTANCE;
291
292 @Override
293 public void onSubscribe(Subscription s) {
294 }
295
296 @Override
297 public void onNext(Object t) {
298 }
299
300 @Override
301 public void onError(Throwable t) {
302 }
303
304 @Override
305 public void onComplete() {
306 }
307 }
308 }