Debian Codegraph @

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