Debian Codegraph @

src/test/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableUsingTest.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.internal.operators.flowable;
15
16 import static org.junit.Assert.*;
17 import static org.mockito.Mockito.*;
18
19 import java.util.*;
20 import java.util.concurrent.atomic.AtomicInteger;
21
22 import org.junit.*;
23 import org.mockito.InOrder;
24 import org.reactivestreams.*;
25
26 import io.reactivex.rxjava3.core.*;
27 import io.reactivex.rxjava3.disposables.*;
28 import io.reactivex.rxjava3.exceptions.*;
29 import io.reactivex.rxjava3.functions.*;
30 import io.reactivex.rxjava3.internal.functions.Functions;
31 import io.reactivex.rxjava3.internal.subscriptions.BooleanSubscription;
32 import io.reactivex.rxjava3.plugins.RxJavaPlugins;
33 import io.reactivex.rxjava3.subscribers.TestSubscriber;
34 import io.reactivex.rxjava3.testsupport.*;
35
36 public class FlowableUsingTest extends RxJavaTest {
37
38 private interface Resource {
39 String getTextFromWeb();
40
41 void dispose();
42 }
43
44 private static class DisposeAction implements Consumer<Resource> {
45
46 @Override
47 public void accept(Resource r) {
48 r.dispose();
49 }
50
51 }
52
53 private final Consumer<Disposable> disposeSubscription = new Consumer<Disposable>() {
54
55 @Override
56 public void accept(Disposable d) {
57 d.dispose();
58 }
59
60 };
61
62 @Test
63 public void using() {
64 performTestUsing(false);
65 }
66
67 @Test
68 public void usingEagerly() {
69 performTestUsing(true);
70 }
71
72 private void performTestUsing(boolean disposeEagerly) {
73 final Resource resource = mock(Resource.class);
74 when(resource.getTextFromWeb()).thenReturn("Hello world!");
75
76 Supplier<Resource> resourceFactory = new Supplier<Resource>() {
77 @Override
78 public Resource get() {
79 return resource;
80 }
81 };
82
83 Function<Resource, Flowable<String>> observableFactory = new Function<Resource, Flowable<String>>() {
84 @Override
85 public Flowable<String> apply(Resource res) {
86 return Flowable.fromArray(res.getTextFromWeb().split(" "));
87 }
88 };
89
90 Subscriber<String> subscriber = TestHelper.mockSubscriber();
91
92 Flowable<String> flowable = Flowable.using(resourceFactory, observableFactory,
93 new DisposeAction(), disposeEagerly);
94 flowable.subscribe(subscriber);
95
96 InOrder inOrder = inOrder(subscriber);
97 inOrder.verify(subscriber, times(1)).onNext("Hello");
98 inOrder.verify(subscriber, times(1)).onNext("world!");
99 inOrder.verify(subscriber, times(1)).onComplete();
100 inOrder.verifyNoMoreInteractions();
101
102 // The resouce should be closed
103 verify(resource, times(1)).dispose();
104 }
105
106 @Test
107 public void usingWithSubscribingTwice() {
108 performTestUsingWithSubscribingTwice(false);
109 }
110
111 @Test
112 public void usingWithSubscribingTwiceDisposeEagerly() {
113 performTestUsingWithSubscribingTwice(true);
114 }
115
116 private void performTestUsingWithSubscribingTwice(boolean disposeEagerly) {
117 // When subscribe is called, a new resource should be created.
118 Supplier<Resource> resourceFactory = new Supplier<Resource>() {
119 @Override
120 public Resource get() {
121 return new Resource() {
122
123 boolean first = true;
124
125 @Override
126 public String getTextFromWeb() {
127 if (first) {
128 first = false;
129 return "Hello world!";
130 }
131 return "Nothing";
132 }
133
134 @Override
135 public void dispose() {
136 // do nothing
137 }
138
139 };
140 }
141 };
142
143 Function<Resource, Flowable<String>> observableFactory = new Function<Resource, Flowable<String>>() {
144 @Override
145 public Flowable<String> apply(Resource res) {
146 return Flowable.fromArray(res.getTextFromWeb().split(" "));
147 }
148 };
149
150 Subscriber<String> subscriber = TestHelper.mockSubscriber();
151
152 Flowable<String> flowable = Flowable.using(resourceFactory, observableFactory,
153 new DisposeAction(), disposeEagerly);
154 flowable.subscribe(subscriber);
155 flowable.subscribe(subscriber);
156
157 InOrder inOrder = inOrder(subscriber);
158
159 inOrder.verify(subscriber, times(1)).onNext("Hello");
160 inOrder.verify(subscriber, times(1)).onNext("world!");
161 inOrder.verify(subscriber, times(1)).onComplete();
162
163 inOrder.verify(subscriber, times(1)).onNext("Hello");
164 inOrder.verify(subscriber, times(1)).onNext("world!");
165 inOrder.verify(subscriber, times(1)).onComplete();
166 inOrder.verifyNoMoreInteractions();
167 }
168
169 @Test(expected = TestException.class)
170 public void usingWithResourceFactoryError() {
171 performTestUsingWithResourceFactoryError(false);
172 }
173
174 @Test(expected = TestException.class)
175 public void usingWithResourceFactoryErrorDisposeEagerly() {
176 performTestUsingWithResourceFactoryError(true);
177 }
178
179 private void performTestUsingWithResourceFactoryError(boolean disposeEagerly) {
180 Supplier<Disposable> resourceFactory = new Supplier<Disposable>() {
181 @Override
182 public Disposable get() {
183 throw new TestException();
184 }
185 };
186
187 Function<Disposable, Flowable<Integer>> observableFactory = new Function<Disposable, Flowable<Integer>>() {
188 @Override
189 public Flowable<Integer> apply(Disposable d) {
190 return Flowable.empty();
191 }
192 };
193
194 Flowable.using(resourceFactory, observableFactory, disposeSubscription)
195 .blockingLast();
196 }
197
198 @Test
199 public void usingWithFlowableFactoryError() {
200 performTestUsingWithFlowableFactoryError(false);
201 }
202
203 @Test
204 public void usingWithFlowableFactoryErrorDisposeEagerly() {
205 performTestUsingWithFlowableFactoryError(true);
206 }
207
208 private void performTestUsingWithFlowableFactoryError(boolean disposeEagerly) {
209 final Runnable unsubscribe = mock(Runnable.class);
210 Supplier<Disposable> resourceFactory = new Supplier<Disposable>() {
211 @Override
212 public Disposable get() {
213 return Disposable.fromRunnable(unsubscribe);
214 }
215 };
216
217 Function<Disposable, Flowable<Integer>> observableFactory = new Function<Disposable, Flowable<Integer>>() {
218 @Override
219 public Flowable<Integer> apply(Disposable subscription) {
220 throw new TestException();
221 }
222 };
223
224 try {
225 Flowable.using(resourceFactory, observableFactory, disposeSubscription).blockingLast();
226 fail("Should throw a TestException when the observableFactory throws it");
227 } catch (TestException e) {
228 // Make sure that unsubscribe is called so that users can close
229 // the resource if some error happens.
230 verify(unsubscribe, times(1)).run();
231 }
232 }
233
234 @Test
235 public void usingDisposesEagerlyBeforeCompletion() {
236 final List<String> events = new ArrayList<>();
237 Supplier<Resource> resourceFactory = createResourceFactory(events);
238 final Action completion = createOnCompletedAction(events);
239 final Action unsub = createUnsubAction(events);
240
241 Function<Resource, Flowable<String>> observableFactory = new Function<Resource, Flowable<String>>() {
242 @Override
243 public Flowable<String> apply(Resource resource) {
244 return Flowable.fromArray(resource.getTextFromWeb().split(" "));
245 }
246 };
247
248 Subscriber<String> subscriber = TestHelper.mockSubscriber();
249
250 Flowable<String> flowable = Flowable.using(resourceFactory, observableFactory,
251 new DisposeAction(), true)
252 .doOnCancel(unsub)
253 .doOnComplete(completion);
254
255 flowable.safeSubscribe(subscriber);
256
257 assertEquals(Arrays.asList("disposed", "completed"), events);
258
259 }
260
261 @Test
262 public void usingDoesNotDisposesEagerlyBeforeCompletion() {
263 final List<String> events = new ArrayList<>();
264 Supplier<Resource> resourceFactory = createResourceFactory(events);
265 final Action completion = createOnCompletedAction(events);
266 final Action unsub = createUnsubAction(events);
267
268 Function<Resource, Flowable<String>> observableFactory = new Function<Resource, Flowable<String>>() {
269 @Override
270 public Flowable<String> apply(Resource resource) {
271 return Flowable.fromArray(resource.getTextFromWeb().split(" "));
272 }
273 };
274
275 Subscriber<String> subscriber = TestHelper.mockSubscriber();
276
277 Flowable<String> flowable = Flowable.using(resourceFactory, observableFactory,
278 new DisposeAction(), false)
279 .doOnCancel(unsub)
280 .doOnComplete(completion);
281
282 flowable.safeSubscribe(subscriber);
283
284 assertEquals(Arrays.asList("completed", "disposed"), events);
285
286 }
287
288 @Test
289 public void usingDisposesEagerlyBeforeError() {
290 final List<String> events = new ArrayList<>();
291 Supplier<Resource> resourceFactory = createResourceFactory(events);
292 final Consumer<Throwable> onError = createOnErrorAction(events);
293 final Action unsub = createUnsubAction(events);
294
295 Function<Resource, Flowable<String>> observableFactory = new Function<Resource, Flowable<String>>() {
296 @Override
297 public Flowable<String> apply(Resource resource) {
298 return Flowable.fromArray(resource.getTextFromWeb().split(" "))
299 .concatWith(Flowable.<String>error(new RuntimeException()));
300 }
301 };
302
303 Subscriber<String> subscriber = TestHelper.mockSubscriber();
304
305 Flowable<String> flowable = Flowable.using(resourceFactory, observableFactory,
306 new DisposeAction(), true)
307 .doOnCancel(unsub)
308 .doOnError(onError);
309
310 flowable.safeSubscribe(subscriber);
311
312 assertEquals(Arrays.asList("disposed", "error"), events);
313
314 }
315
316 @Test
317 public void usingDoesNotDisposesEagerlyBeforeError() {
318 final List<String> events = new ArrayList<>();
319 final Supplier<Resource> resourceFactory = createResourceFactory(events);
320 final Consumer<Throwable> onError = createOnErrorAction(events);
321 final Action unsub = createUnsubAction(events);
322
323 Function<Resource, Flowable<String>> observableFactory = new Function<Resource, Flowable<String>>() {
324 @Override
325 public Flowable<String> apply(Resource resource) {
326 return Flowable.fromArray(resource.getTextFromWeb().split(" "))
327 .concatWith(Flowable.<String>error(new RuntimeException()));
328 }
329 };
330
331 Subscriber<String> subscriber = TestHelper.mockSubscriber();
332
333 Flowable<String> flowable = Flowable.using(resourceFactory, observableFactory,
334 new DisposeAction(), false)
335 .doOnCancel(unsub)
336 .doOnError(onError);
337
338 flowable.safeSubscribe(subscriber);
339
340 assertEquals(Arrays.asList("error", "disposed"), events);
341 }
342
343 private static Action createUnsubAction(final List<String> events) {
344 return new Action() {
345 @Override
346 public void run() {
347 events.add("unsub");
348 }
349 };
350 }
351
352 private static Consumer<Throwable> createOnErrorAction(final List<String> events) {
353 return new Consumer<Throwable>() {
354 @Override
355 public void accept(Throwable t) {
356 events.add("error");
357 }
358 };
359 }
360
361 private static Supplier<Resource> createResourceFactory(final List<String> events) {
362 return new Supplier<Resource>() {
363 @Override
364 public Resource get() {
365 return new Resource() {
366
367 @Override
368 public String getTextFromWeb() {
369 return "hello world";
370 }
371
372 @Override
373 public void dispose() {
374 events.add("disposed");
375 }
376 };
377 }
378 };
379 }
380
381 private static Action createOnCompletedAction(final List<String> events) {
382 return new Action() {
383 @Override
384 public void run() {
385 events.add("completed");
386 }
387 };
388 }
389
390 @Test
391 public void factoryThrows() {
392
393 TestSubscriber<Integer> ts = TestSubscriber.create();
394
395 final AtomicInteger count = new AtomicInteger();
396
397 Flowable.<Integer, Integer>using(
398 new Supplier<Integer>() {
399 @Override
400 public Integer get() {
401 return 1;
402 }
403 },
404 new Function<Integer, Flowable<Integer>>() {
405 @Override
406 public Flowable<Integer> apply(Integer v) {
407 throw new TestException("forced failure");
408 }
409 },
410 new Consumer<Integer>() {
411 @Override
412 public void accept(Integer c) {
413 count.incrementAndGet();
414 }
415 }
416 )
417 .subscribe(ts);
418
419 ts.assertError(TestException.class);
420
421 Assert.assertEquals(1, count.get());
422 }
423
424 @Test
425 public void nonEagerTermination() {
426
427 TestSubscriber<Integer> ts = TestSubscriber.create();
428
429 final AtomicInteger count = new AtomicInteger();
430
431 Flowable.<Integer, Integer>using(
432 new Supplier<Integer>() {
433 @Override
434 public Integer get() {
435 return 1;
436 }
437 },
438 new Function<Integer, Flowable<Integer>>() {
439 @Override
440 public Flowable<Integer> apply(Integer v) {
441 return Flowable.just(v);
442 }
443 },
444 new Consumer<Integer>() {
445 @Override
446 public void accept(Integer c) {
447 count.incrementAndGet();
448 }
449 }, false
450 )
451 .subscribe(ts);
452
453 ts.assertValue(1);
454 ts.assertNoErrors();
455 ts.assertComplete();
456
457 Assert.assertEquals(1, count.get());
458 }
459
460 @Test
461 public void dispose() {
462 TestHelper.checkDisposed(Flowable.using(
463 new Supplier<Object>() {
464 @Override
465 public Object get() throws Exception {
466 return 1;
467 }
468 },
469 new Function<Object, Flowable<Object>>() {
470 @Override
471 public Flowable<Object> apply(Object v) throws Exception {
472 return Flowable.never();
473 }
474 },
475 Functions.emptyConsumer()
476 ));
477 }
478
479 @Test
480 public void supplierDisposerCrash() {
481 TestSubscriberEx<Object> ts = Flowable.using(new Supplier<Object>() {
482 @Override
483 public Object get() throws Exception {
484 return 1;
485 }
486 }, new Function<Object, Flowable<Object>>() {
487 @Override
488 public Flowable<Object> apply(Object v) throws Exception {
489 throw new TestException("First");
490 }
491 }, new Consumer<Object>() {
492 @Override
493 public void accept(Object e) throws Exception {
494 throw new TestException("Second");
495 }
496 })
497 .to(TestHelper.<Object>testConsumer())
498 .assertFailure(CompositeException.class);
499
500 List<Throwable> errors = TestHelper.compositeList(ts.errors().get(0));
501
502 TestHelper.assertError(errors, 0, TestException.class, "First");
503 TestHelper.assertError(errors, 1, TestException.class, "Second");
504 }
505
506 @Test
507 public void eagerOnErrorDisposerCrash() {
508 TestSubscriberEx<Object> ts = Flowable.using(new Supplier<Object>() {
509 @Override
510 public Object get() throws Exception {
511 return 1;
512 }
513 }, new Function<Object, Flowable<Object>>() {
514 @Override
515 public Flowable<Object> apply(Object v) throws Exception {
516 return Flowable.error(new TestException("First"));
517 }
518 }, new Consumer<Object>() {
519 @Override
520 public void accept(Object e) throws Exception {
521 throw new TestException("Second");
522 }
523 })
524 .to(TestHelper.<Object>testConsumer())
525 .assertFailure(CompositeException.class);
526
527 List<Throwable> errors = TestHelper.compositeList(ts.errors().get(0));
528
529 TestHelper.assertError(errors, 0, TestException.class, "First");
530 TestHelper.assertError(errors, 1, TestException.class, "Second");
531 }
532
533 @Test
534 public void eagerOnCompleteDisposerCrash() {
535 Flowable.using(new Supplier<Object>() {
536 @Override
537 public Object get() throws Exception {
538 return 1;
539 }
540 }, new Function<Object, Flowable<Object>>() {
541 @Override
542 public Flowable<Object> apply(Object v) throws Exception {
543 return Flowable.empty();
544 }
545 }, new Consumer<Object>() {
546 @Override
547 public void accept(Object e) throws Exception {
548 throw new TestException("Second");
549 }
550 })
551 .to(TestHelper.<Object>testConsumer())
552 .assertFailureAndMessage(TestException.class, "Second");
553 }
554
555 @Test
556 public void nonEagerDisposerCrash() {
557 List<Throwable> errors = TestHelper.trackPluginErrors();
558 try {
559 Flowable.using(new Supplier<Object>() {
560 @Override
561 public Object get() throws Exception {
562 return 1;
563 }
564 }, new Function<Object, Flowable<Object>>() {
565 @Override
566 public Flowable<Object> apply(Object v) throws Exception {
567 return Flowable.empty();
568 }
569 }, new Consumer<Object>() {
570 @Override
571 public void accept(Object e) throws Exception {
572 throw new TestException("Second");
573 }
574 }, false)
575 .test()
576 .assertResult();
577
578 TestHelper.assertUndeliverable(errors, 0, TestException.class, "Second");
579 } finally {
580 RxJavaPlugins.reset();
581 }
582 }
583
584 @Test
585 public void sourceSupplierReturnsNull() {
586 Flowable.using(Functions.justSupplier(1),
587 Functions.justFunction((Publisher<Object>)null),
588 Functions.emptyConsumer())
589 .to(TestHelper.<Object>testConsumer())
590 .assertFailureAndMessage(NullPointerException.class, "The sourceSupplier returned a null Publisher")
591 ;
592 }
593
594 @Test
595 public void doubleOnSubscribe() {
596 TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Flowable<Object>>() {
597 @Override
598 public Flowable<Object> apply(Flowable<Object> f)
599 throws Exception {
600 return Flowable.using(Functions.justSupplier(1), Functions.justFunction(f), Functions.emptyConsumer());
601 }
602 });
603 }
604
605 @Test
606 public void eagerDisposedOnComplete() {
607 final TestSubscriber<Integer> ts = new TestSubscriber<>();
608
609 Flowable.using(Functions.justSupplier(1), Functions.justFunction(new Flowable<Integer>() {
610 @Override
611 protected void subscribeActual(Subscriber<? super Integer> subscriber) {
612 subscriber.onSubscribe(new BooleanSubscription());
613 ts.cancel();
614 subscriber.onComplete();
615 }
616 }), Functions.emptyConsumer(), true)
617 .subscribe(ts);
618 }
619
620 @Test
621 public void eagerDisposedOnError() {
622 final TestSubscriber<Integer> ts = new TestSubscriber<>();
623
624 Flowable.using(Functions.justSupplier(1), Functions.justFunction(new Flowable<Integer>() {
625 @Override
626 protected void subscribeActual(Subscriber<? super Integer> subscriber) {
627 subscriber.onSubscribe(new BooleanSubscription());
628 ts.cancel();
629 subscriber.onError(new TestException());
630 }
631 }), Functions.emptyConsumer(), true)
632 .subscribe(ts);
633 }
634
635 @Test
636 public void eagerDisposeResourceThenDisposeUpstream() {
637 final StringBuilder sb = new StringBuilder();
638
639 Flowable.using(Functions.justSupplier(1),
640 new Function<Integer, Flowable<Integer>>() {
641 @Override
642 public Flowable<Integer> apply(Integer t) throws Throwable {
643 return Flowable.range(1, 2)
644 .doOnCancel(new Action() {
645 @Override
646 public void run() throws Throwable {
647 sb.append("Cancel");
648 }
649 })
650 ;
651 }
652 }, new Consumer<Integer>() {
653 @Override
654 public void accept(Integer t) throws Throwable {
655 sb.append("Resource");
656 }
657 }, true)
658 .take(1)
659 .test()
660 .assertResult(1);
661
662 assertEquals("ResourceCancel", sb.toString());
663 }
664
665 @Test
666 public void nonEagerDisposeUpstreamThenDisposeResource() {
667 final StringBuilder sb = new StringBuilder();
668
669 Flowable.using(Functions.justSupplier(1),
670 new Function<Integer, Flowable<Integer>>() {
671 @Override
672 public Flowable<Integer> apply(Integer t) throws Throwable {
673 return Flowable.range(1, 2)
674 .doOnCancel(new Action() {
675 @Override
676 public void run() throws Throwable {
677 sb.append("Cancel");
678 }
679 });
680 }
681 }, new Consumer<Integer>() {
682 @Override
683 public void accept(Integer t) throws Throwable {
684 sb.append("Resource");
685 }
686 }, false)
687 .take(1)
688 .test()
689 .assertResult(1);
690
691 assertEquals("CancelResource", sb.toString());
692 }
693 }