Debian Codegraph @

src/main/java/io/reactivex/rxjava3/observers/BaseTestConsumer.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.observers;
15
16 import java.util.*;
17 import java.util.concurrent.*;
18
19 import io.reactivex.rxjava3.annotations.*;
20 import io.reactivex.rxjava3.exceptions.CompositeException;
21 import io.reactivex.rxjava3.functions.Predicate;
22 import io.reactivex.rxjava3.internal.functions.Functions;
23 import io.reactivex.rxjava3.internal.util.*;
24
25 /**
26 * Base class with shared infrastructure to support
27 * {@link io.reactivex.rxjava3.subscribers.TestSubscriber TestSubscriber} and {@link TestObserver}.
28 * @param <T> the value type consumed
29 * @param <U> the subclass of this {@code BaseTestConsumer}
30 */
31 public abstract class BaseTestConsumer<T, U extends BaseTestConsumer<T, U>> {
32 /** The latch that indicates an onError or onComplete has been called. */
33 protected final CountDownLatch done;
34 /** The list of values received. */
35 protected final List<T> values;
36 /** The list of errors received. */
37 protected final List<Throwable> errors;
38 /** The number of completions. */
39 protected long completions;
40 /** The last thread seen by the observer. */
41 protected Thread lastThread;
42
43 protected boolean checkSubscriptionOnce;
44
45 /**
46 * The optional tag associated with this test consumer.
47 * @since 2.0.7
48 */
49 protected CharSequence tag;
50
51 /**
52 * Indicates that one of the {@code awaitX} method has timed out.
53 * @since 2.0.7
54 */
55 protected boolean timeout;
56
57 /**
58 * Constructs a {@code BaseTestConsumer} with {@code CountDownLatch} set to 1.
59 */
60 public BaseTestConsumer() {
61 this.values = new VolatileSizeArrayList<>();
62 this.errors = new VolatileSizeArrayList<>();
63 this.done = new CountDownLatch(1);
64 }
65
66 /**
67 * Returns a shared list of received {@code onNext} values or the single {@code onSuccess} value.
68 * <p>
69 * Note that accessing the items via certain methods of the {@link List}
70 * interface while the upstream is still actively emitting
71 * more items may result in a {@code ConcurrentModificationException}.
72 * <p>
73 * The {@link List#size()} method will return the number of items
74 * already received by this {@code TestObserver}/{@code TestSubscriber} in a thread-safe
75 * manner that can be read via {@link List#get(int)}) method
76 * (index range of 0 to {@code List.size() - 1}).
77 * <p>
78 * A view of the returned List can be created via {@link List#subList(int, int)}
79 * by using the bounds 0 (inclusive) to {@link List#size()} (exclusive) which,
80 * when accessed in a read-only fashion, should be also thread-safe and not throw any
81 * {@code ConcurrentModificationException}.
82 * @return a list of received onNext values
83 */
84 @NonNull
85 public final List<T> values() {
86 return values;
87 }
88
89 /**
90 * Fail with the given message and add the sequence of errors as suppressed ones.
91 * <p>Note this is deliberately the only fail method. Most of the times an assertion
92 * would fail but it is possible it was due to an exception somewhere. This construct
93 * will capture those potential errors and report it along with the original failure.
94 *
95 * @param message the message to use
96 * @return AssertionError the prepared AssertionError instance
97 */
98 @NonNull
99 protected final AssertionError fail(@NonNull String message) {
100 StringBuilder b = new StringBuilder(64 + message.length());
101 b.append(message);
102
103 b.append(" (")
104 .append("latch = ").append(done.getCount()).append(", ")
105 .append("values = ").append(values.size()).append(", ")
106 .append("errors = ").append(errors.size()).append(", ")
107 .append("completions = ").append(completions)
108 ;
109
110 if (timeout) {
111 b.append(", timeout!");
112 }
113
114 if (isDisposed()) {
115 b.append(", disposed!");
116 }
117
118 CharSequence tag = this.tag;
119 if (tag != null) {
120 b.append(", tag = ")
121 .append(tag);
122 }
123
124 b
125 .append(')')
126 ;
127
128 AssertionError ae = new AssertionError(b.toString());
129 if (!errors.isEmpty()) {
130 if (errors.size() == 1) {
131 ae.initCause(errors.get(0));
132 } else {
133 CompositeException ce = new CompositeException(errors);
134 ae.initCause(ce);
135 }
136 }
137 return ae;
138 }
139
140 /**
141 * Awaits until this {@code TestObserver}/{@code TestSubscriber} receives an {@code onError} or {@code onComplete} events.
142 * @return this
143 * @throws InterruptedException if the current thread is interrupted while waiting
144 */
145 @SuppressWarnings("unchecked")
146 @NonNull
147 public final U await() throws InterruptedException {
148 if (done.getCount() == 0) {
149 return (U)this;
150 }
151
152 done.await();
153 return (U)this;
154 }
155
156 /**
157 * Awaits the specified amount of time or until this {@code TestObserver}/{@code TestSubscriber}
158 * receives an {@code onError} or {@code onComplete} events, whichever happens first.
159 * @param time the waiting time
160 * @param unit the time unit of the waiting time
161 * @return true if the {@code TestObserver}/{@code TestSubscriber} terminated, false if timeout happened
162 * @throws InterruptedException if the current thread is interrupted while waiting
163 */
164 public final boolean await(long time, @NonNull TimeUnit unit) throws InterruptedException {
165 boolean d = done.getCount() == 0 || (done.await(time, unit));
166 timeout = !d;
167 return d;
168 }
169
170 // assertion methods
171
172 /**
173 * Assert that this {@code TestObserver}/{@code TestSubscriber} received exactly one {@code onComplete} event.
174 * @return this
175 */
176 @SuppressWarnings("unchecked")
177 @NonNull
178 public final U assertComplete() {
179 long c = completions;
180 if (c == 0) {
181 throw fail("Not completed");
182 } else
183 if (c > 1) {
184 throw fail("Multiple completions: " + c);
185 }
186 return (U)this;
187 }
188
189 /**
190 * Assert that this {@code TestObserver}/{@code TestSubscriber} has not received an {@code onComplete} event.
191 * @return this
192 */
193 @SuppressWarnings("unchecked")
194 @NonNull
195 public final U assertNotComplete() {
196 long c = completions;
197 if (c == 1) {
198 throw fail("Completed!");
199 } else
200 if (c > 1) {
201 throw fail("Multiple completions: " + c);
202 }
203 return (U)this;
204 }
205
206 /**
207 * Assert that this {@code TestObserver}/{@code TestSubscriber} has not received an {@code onError} event.
208 * @return this
209 */
210 @SuppressWarnings("unchecked")
211 @NonNull
212 public final U assertNoErrors() {
213 int s = errors.size();
214 if (s != 0) {
215 throw fail("Error(s) present: " + errors);
216 }
217 return (U)this;
218 }
219
220 /**
221 * Assert that this {@code TestObserver}/{@code TestSubscriber} received exactly the specified {@code onError} event value.
222 *
223 * <p>The comparison is performed via {@link Objects#equals(Object, Object)}; since most exceptions don't
224 * implement equals(), this assertion may fail. Use the {@link #assertError(Class)}
225 * overload to test against the class of an error instead of an instance of an error
226 * or {@link #assertError(Predicate)} to test with different condition.
227 * @param error the error to check
228 * @return this
229 * @see #assertError(Class)
230 * @see #assertError(Predicate)
231 */
232 @NonNull
233 public final U assertError(@NonNull Throwable error) {
234 return assertError(Functions.equalsWith(error), true);
235 }
236
237 /**
238 * Asserts that this {@code TestObserver}/{@code TestSubscriber} received exactly one {@code onError} event which is an
239 * instance of the specified {@code errorClass} {@link Class}.
240 * @param errorClass the error {@code Class} to expect
241 * @return this
242 */
243 @SuppressWarnings({ "unchecked", "rawtypes" })
244 @NonNull
245 public final U assertError(@NonNull Class<? extends Throwable> errorClass) {
246 return (U)assertError((Predicate)Functions.isInstanceOf(errorClass), true);
247 }
248
249 /**
250 * Asserts that this {@code TestObserver}/{@code TestSubscriber} received exactly one {@code onError} event for which
251 * the provided predicate returns {@code true}.
252 * @param errorPredicate
253 * the predicate that receives the error {@link Throwable}
254 * and should return {@code true} for expected errors.
255 * @return this
256 */
257 @NonNull
258 public final U assertError(@NonNull Predicate<Throwable> errorPredicate) {
259 return assertError(errorPredicate, false);
260 }
261
262 @SuppressWarnings("unchecked")
263 @NonNull
264 private U assertError(@NonNull Predicate<Throwable> errorPredicate, boolean exact) {
265 int s = errors.size();
266 if (s == 0) {
267 throw fail("No errors");
268 }
269
270 boolean found = false;
271
272 for (Throwable e : errors) {
273 try {
274 if (errorPredicate.test(e)) {
275 found = true;
276 break;
277 }
278 } catch (Throwable ex) {
279 throw ExceptionHelper.wrapOrThrow(ex);
280 }
281 }
282
283 if (found) {
284 if (s != 1) {
285 if (exact) {
286 throw fail("Error present but other errors as well");
287 }
288 throw fail("One error passed the predicate but other errors are present as well");
289 }
290 } else {
291 if (exact) {
292 throw fail("Error not present");
293 }
294 throw fail("No error(s) passed the predicate");
295 }
296 return (U)this;
297 }
298
299 /**
300 * Assert that this {@code TestObserver}/{@code TestSubscriber} received exactly one {@code onNext} value which is equal to
301 * the given value with respect to {@link Objects#equals(Object, Object)}.
302 * @param value the value to expect
303 * @return this
304 */
305 @SuppressWarnings("unchecked")
306 @NonNull
307 public final U assertValue(@NonNull T value) {
308 int s = values.size();
309 if (s != 1) {
310 throw fail("\nexpected: " + valueAndClass(value) + "\ngot: " + values);
311 }
312 T v = values.get(0);
313 if (!Objects.equals(value, v)) {
314 throw fail("\nexpected: " + valueAndClass(value) + "\ngot: " + valueAndClass(v));
315 }
316 return (U)this;
317 }
318
319 /**
320 * Asserts that this {@code TestObserver}/{@code TestSubscriber} received exactly one {@code onNext} value for which
321 * the provided predicate returns {@code true}.
322 * @param valuePredicate
323 * the predicate that receives the {@code onNext} value
324 * and should return {@code true} for the expected value.
325 * @return this
326 */
327 @SuppressWarnings("unchecked")
328 @NonNull
329 public final U assertValue(@NonNull Predicate<T> valuePredicate) {
330 assertValueAt(0, valuePredicate);
331
332 if (values.size() > 1) {
333 throw fail("The first value passed the predicate but this consumer received more than one value");
334 }
335
336 return (U)this;
337 }
338
339 /**
340 * Asserts that this {@code TestObserver}/{@code TestSubscriber} received an {@code onNext} value at the given index
341 * which is equal to the given value with respect to {@code null}-safe {@link Objects#equals(Object, Object)}.
342 * <p>History: 2.1.3 - experimental
343 * @param index the position to assert on
344 * @param value the value to expect
345 * @return this
346 * @since 2.2
347 */
348 @SuppressWarnings("unchecked")
349 @NonNull
350 public final U assertValueAt(int index, @NonNull T value) {
351 int s = values.size();
352 if (s == 0) {
353 throw fail("No values");
354 }
355
356 if (index < 0 || index >= s) {
357 throw fail("Index " + index + " is out of range [0, " + s + ")");
358 }
359
360 T v = values.get(index);
361 if (!Objects.equals(value, v)) {
362 throw fail("\nexpected: " + valueAndClass(value) + "\ngot: " + valueAndClass(v)
363 + "; Value at position " + index + " differ");
364 }
365 return (U)this;
366 }
367
368 /**
369 * Asserts that this {@code TestObserver}/{@code TestSubscriber} received an {@code onNext} value at the given index
370 * for the provided predicate returns {@code true}.
371 * @param index the position to assert on
372 * @param valuePredicate
373 * the predicate that receives the {@code onNext} value
374 * and should return {@code true} for the expected value.
375 * @return this
376 */
377 @SuppressWarnings("unchecked")
378 @NonNull
379 public final U assertValueAt(int index, @NonNull Predicate<T> valuePredicate) {
380 int s = values.size();
381 if (s == 0) {
382 throw fail("No values");
383 }
384
385 if (index < 0 || index >= s) {
386 throw fail("Index " + index + " is out of range [0, " + s + ")");
387 }
388
389 boolean found = false;
390
391 T v = values.get(index);
392 try {
393 if (valuePredicate.test(v)) {
394 found = true;
395 }
396 } catch (Throwable ex) {
397 throw ExceptionHelper.wrapOrThrow(ex);
398 }
399
400 if (!found) {
401 throw fail("Value " + valueAndClass(v) + " at position " + index + " did not pass the predicate");
402 }
403 return (U)this;
404 }
405
406 /**
407 * Appends the class name to a non-{@code null} value or returns {@code "null"}.
408 * @param o the object
409 * @return the string representation
410 */
411 @NonNull
412 public static String valueAndClass(@Nullable Object o) {
413 if (o != null) {
414 return o + " (class: " + o.getClass().getSimpleName() + ")";
415 }
416 return "null";
417 }
418
419 /**
420 * Assert that this {@code TestObserver}/{@code TestSubscriber} received the specified number {@code onNext} events.
421 * @param count the expected number of {@code onNext} events
422 * @return this
423 */
424 @SuppressWarnings("unchecked")
425 @NonNull
426 public final U assertValueCount(int count) {
427 int s = values.size();
428 if (s != count) {
429 throw fail("\nexpected: " + count + "\ngot: " + s + "; Value counts differ");
430 }
431 return (U)this;
432 }
433
434 /**
435 * Assert that this {@code TestObserver}/{@code TestSubscriber} has not received any {@code onNext} events.
436 * @return this
437 */
438 @NonNull
439 public final U assertNoValues() {
440 return assertValueCount(0);
441 }
442
443 /**
444 * Assert that the {@code TestObserver}/{@code TestSubscriber} received only the specified values in the specified order.
445 * @param values the values expected
446 * @return this
447 */
448 @SuppressWarnings("unchecked")
449 @SafeVarargs
450 @NonNull
451 public final U assertValues(@NonNull T... values) {
452 int s = this.values.size();
453 if (s != values.length) {
454 throw fail("\nexpected: " + values.length + " " + Arrays.toString(values)
455 + "\ngot: " + s + " " + this.values + "; Value count differs");
456 }
457 for (int i = 0; i < s; i++) {
458 T v = this.values.get(i);
459 T u = values[i];
460 if (!Objects.equals(u, v)) {
461 throw fail("\nexpected: " + valueAndClass(u) + "\ngot: " + valueAndClass(v)
462 + "; Value at position " + i + " differ");
463 }
464 }
465 return (U)this;
466 }
467
468 /**
469 * Assert that the {@code TestObserver}/{@code TestSubscriber} received only the specified values in the specified order without terminating.
470 * <p>History: 2.1.4 - experimental
471 * @param values the values expected
472 * @return this
473 * @since 2.2
474 */
475 @SafeVarargs
476 @NonNull
477 public final U assertValuesOnly(@NonNull T... values) {
478 return assertSubscribed()
479 .assertValues(values)
480 .assertNoErrors()
481 .assertNotComplete();
482 }
483
484 /**
485 * Assert that the {@code TestObserver}/{@code TestSubscriber} received only the specified sequence of values in the same order.
486 * @param sequence the sequence of expected values in order
487 * @return this
488 */
489 @SuppressWarnings("unchecked")
490 @NonNull
491 public final U assertValueSequence(@NonNull Iterable<? extends T> sequence) {
492 int i = 0;
493 Iterator<T> actualIterator = values.iterator();
494 Iterator<? extends T> expectedIterator = sequence.iterator();
495 boolean actualNext;
496 boolean expectedNext;
497 for (;;) {
498 expectedNext = expectedIterator.hasNext();
499 actualNext = actualIterator.hasNext();
500
501 if (!actualNext || !expectedNext) {
502 break;
503 }
504
505 T u = expectedIterator.next();
506 T v = actualIterator.next();
507
508 if (!Objects.equals(u, v)) {
509 throw fail("\nexpected: " + valueAndClass(u) + "\ngot: " + valueAndClass(v)
510 + "; Value at position " + i + " differ");
511 }
512 i++;
513 }
514
515 if (actualNext) {
516 throw fail("More values received than expected (" + i + ")");
517 }
518 if (expectedNext) {
519 throw fail("Fewer values received than expected (" + i + ")");
520 }
521 return (U)this;
522 }
523
524 /**
525 * Assert that the {@code onSubscribe} method was called exactly once.
526 * @return this
527 */
528 @NonNull
529 protected abstract U assertSubscribed();
530
531 /**
532 * Assert that the upstream signaled the specified values in order and
533 * completed normally.
534 * @param values the expected values, asserted in order
535 * @return this
536 * @see #assertFailure(Class, Object...)
537 */
538 @SafeVarargs
539 @NonNull
540 public final U assertResult(@NonNull T... values) {
541 return assertSubscribed()
542 .assertValues(values)
543 .assertNoErrors()
544 .assertComplete();
545 }
546
547 /**
548 * Assert that the upstream signaled the specified values in order
549 * and then failed with a specific class or subclass of {@link Throwable}.
550 * @param error the expected exception (parent) {@link Class}
551 * @param values the expected values, asserted in order
552 * @return this
553 */
554 @SafeVarargs
555 @NonNull
556 public final U assertFailure(@NonNull Class<? extends Throwable> error, @NonNull T... values) {
557 return assertSubscribed()
558 .assertValues(values)
559 .assertError(error)
560 .assertNotComplete();
561 }
562
563 /**
564 * Awaits until the internal latch is counted down.
565 * <p>If the wait times out or gets interrupted, the {@code TestObserver}/{@code TestSubscriber} is cancelled.
566 * @param time the waiting time
567 * @param unit the time unit of the waiting time
568 * @return this
569 * @throws RuntimeException wrapping an {@link InterruptedException} if the wait is interrupted
570 */
571 @SuppressWarnings("unchecked")
572 @NonNull
573 public final U awaitDone(long time, @NonNull TimeUnit unit) {
574 try {
575 if (!done.await(time, unit)) {
576 timeout = true;
577 dispose();
578 }
579 } catch (InterruptedException ex) {
580 dispose();
581 throw ExceptionHelper.wrapOrThrow(ex);
582 }
583 return (U)this;
584 }
585
586 /**
587 * Assert that the {@code TestObserver}/{@code TestSubscriber} has received a
588 * {@link io.reactivex.rxjava3.disposables.Disposable Disposable}/{@link org.reactivestreams.Subscription Subscription}
589 * via {@code onSubscribe} but no other events.
590 * @return this
591 */
592 @NonNull
593 public final U assertEmpty() {
594 return assertSubscribed()
595 .assertNoValues()
596 .assertNoErrors()
597 .assertNotComplete();
598 }
599
600 /**
601 * Set the tag displayed along with an assertion failure's
602 * other state information.
603 * <p>History: 2.0.7 - experimental
604 * @param tag the string to display ({@code null} won't print any tag)
605 * @return this
606 * @since 2.1
607 */
608 @SuppressWarnings("unchecked")
609 @NonNull
610 public final U withTag(@Nullable CharSequence tag) {
611 this.tag = tag;
612 return (U)this;
613 }
614
615 /**
616 * Await until the {@code TestObserver}/{@code TestSubscriber} receives the given
617 * number of items or terminates by sleeping 10 milliseconds at a time
618 * up to 5000 milliseconds of timeout.
619 * <p>History: 2.0.7 - experimental
620 * @param atLeast the number of items expected at least
621 * @return this
622 * @since 2.1
623 */
624 @SuppressWarnings("unchecked")
625 @NonNull
626 public final U awaitCount(int atLeast) {
627 long start = System.currentTimeMillis();
628 long timeoutMillis = 5000;
629 for (;;) {
630 if (System.currentTimeMillis() - start >= timeoutMillis) {
631 timeout = true;
632 break;
633 }
634 if (done.getCount() == 0L) {
635 break;
636 }
637 if (values.size() >= atLeast) {
638 break;
639 }
640
641 try {
642 Thread.sleep(10);
643 } catch (InterruptedException ex) {
644 throw new RuntimeException(ex);
645 }
646 }
647 return (U)this;
648 }
649
650 /**
651 * Returns true if this test consumer was cancelled/disposed.
652 * @return true if this test consumer was cancelled/disposed.
653 */
654 protected abstract boolean isDisposed();
655
656 /**
657 * Cancel/dispose this test consumer.
658 */
659 protected abstract void dispose();
660 }