Java Code Examples for rx.schedulers.Schedulers#test()
The following examples show how to use
rx.schedulers.Schedulers#test() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DefaultEventBusTest.java From couchbase-jvm-core with Apache License 2.0 | 6 votes |
@Test public void shouldPublishToSubscriber() throws Exception { TestScheduler testScheduler = Schedulers.test(); EventBus eventBus = new DefaultEventBus(testScheduler); TestSubscriber<CouchbaseEvent> subscriber = new TestSubscriber<CouchbaseEvent>(); assertFalse(eventBus.hasSubscribers()); eventBus.get().subscribe(subscriber); assertTrue(eventBus.hasSubscribers()); CouchbaseEvent event1 = mock(CouchbaseEvent.class); CouchbaseEvent event2 = mock(CouchbaseEvent.class); eventBus.publish(event1); eventBus.publish(event2); testScheduler.advanceTimeBy(1, TimeUnit.SECONDS); assertEquals(2, subscriber.getOnNextEvents().size()); assertEquals(0, subscriber.getOnErrorEvents().size()); assertEquals(0, subscriber.getOnCompletedEvents().size()); }
Example 2
Source File: UnicastAutoReleaseSubjectTest.java From couchbase-jvm-core with Apache License 2.0 | 6 votes |
@Test public void testByteBufReleaseWithTimeout() throws Exception { TestScheduler testScheduler = Schedulers.test(); UnicastAutoReleaseSubject<ByteBuf> subject = UnicastAutoReleaseSubject.create(100, TimeUnit.MILLISECONDS, testScheduler); ByteBuf buffer = Unpooled.buffer(); subject.onNext(buffer); Assert.assertEquals("Byte buffer not retained on buffering by subject.", 1, buffer.refCnt()); subject.onCompleted(); testScheduler.advanceTimeBy(100, TimeUnit.MILLISECONDS); Assert.assertEquals("Byte buffer not fully released", 0, buffer.refCnt()); }
Example 3
Source File: AwsObservableExtTest.java From titus-control-plane with Apache License 2.0 | 6 votes |
@Test public void asyncActionSingle() throws Exception { AmazonWebServiceRequest someRequest = AmazonWebServiceRequest.NOOP; final MockAsyncClient<AmazonWebServiceRequest, String> client = new MockAsyncClient<>(someRequest, "some response"); Single<String> single = AwsObservableExt.asyncActionSingle(supplier -> client.someAsyncOperation(supplier.handler())); TestScheduler testScheduler = Schedulers.test(); final AssertableSubscriber<String> subscriber = single.subscribeOn(testScheduler).test(); testScheduler.triggerActions(); subscriber.assertNoValues(); subscriber.assertNotCompleted(); client.run(); testScheduler.triggerActions(); subscriber.assertValueCount(1); subscriber.assertValue("some response"); subscriber.assertCompleted(); }
Example 4
Source File: UnicastAutoReleaseSubjectTest.java From couchbase-jvm-core with Apache License 2.0 | 6 votes |
@Test public void testTraceIdAppearsWhenNoSubscription() throws Exception { TestScheduler testScheduler = Schedulers.test(); OnUnsubscribeAction onUnsub = new OnUnsubscribeAction(); UnicastAutoReleaseSubject<String> subject = UnicastAutoReleaseSubject.create(1, TimeUnit.DAYS, testScheduler, onUnsub); subject.withTraceIdentifier("noSub"); subject.onNext("Start the timeout now."); // Since the timeout is scheduled only after content arrival. testScheduler.advanceTimeBy(1, TimeUnit.DAYS); try { subject.toBlocking().last(); // Should immediately throw an error. fail("Expected IllegalStateException"); } catch (IllegalStateException e) { assertThat(e).hasMessageStartingWith("The content of this Observable (noSub)"); } }
Example 5
Source File: MulticastEventStreamClientTest.java From MarketData with Apache License 2.0 | 6 votes |
@Test public void Should_transmit_events_from_the_target_client() { // given TestScheduler scheduler = Schedulers.test(); PublishSubject<String> subject = PublishSubject.create(); EventStreamClient targetClient = mock(EventStreamClient.class); when(targetClient.readServerSideEvents()).thenReturn(subject); MulticastEventStreamClient multicastEventStreamClient = new MulticastEventStreamClient(targetClient, scheduler); Observable<String> events = multicastEventStreamClient.readServerSideEvents(); // when TestSubscriber<String> subscriber = new TestSubscriber<>(); events.subscribe(subscriber); subject.onNext("Hello!"); // then assertThat(subscriber.getOnNextEvents()).hasSize(1).contains("Hello!"); }
Example 6
Source File: MulticastEventStreamClientTest.java From MarketData with Apache License 2.0 | 6 votes |
/** * Test 21 */ @Test @Ignore public void Should_generate_only_one_subscription_side_effect_with_multiple_subscribers() { // given Observable<String> source = Observable.create(subscriber -> { subscriber.onNext("open"); }); TestScheduler scheduler = Schedulers.test(); EventStreamClient targetClient = mock(EventStreamClient.class); when(targetClient.readServerSideEvents()).thenReturn(source); MulticastEventStreamClient multicastEventStreamClient = new MulticastEventStreamClient(targetClient, scheduler); Observable<String> events = multicastEventStreamClient.readServerSideEvents(); // when TestSubscriber<String> subscriber1 = new TestSubscriber<>(); TestSubscriber<String> subscriber2 = new TestSubscriber<>(); events.subscribe(subscriber1); events.subscribe(subscriber2); // then assertThat(subscriber1.getOnNextEvents()).hasSize(1); assertThat(subscriber2.getOnNextEvents()).isEmpty(); }
Example 7
Source File: DefaultEventBusTest.java From couchbase-jvm-core with Apache License 2.0 | 6 votes |
@Test public void shouldNotBufferEventsBeforeSubscribe() throws Exception { TestScheduler testScheduler = Schedulers.test(); EventBus eventBus = new DefaultEventBus(testScheduler); TestSubscriber<CouchbaseEvent> subscriber = new TestSubscriber<CouchbaseEvent>(); CouchbaseEvent event1 = mock(CouchbaseEvent.class); CouchbaseEvent event2 = mock(CouchbaseEvent.class); eventBus.publish(event1); assertFalse(eventBus.hasSubscribers()); eventBus.get().subscribe(subscriber); assertTrue(eventBus.hasSubscribers()); eventBus.publish(event2); testScheduler.advanceTimeBy(1, TimeUnit.SECONDS); assertEquals(1, subscriber.getOnNextEvents().size()); assertEquals(0, subscriber.getOnErrorEvents().size()); assertEquals(0, subscriber.getOnCompletedEvents().size()); }
Example 8
Source File: AptoideBiAnalyticsTest.java From aptoide-client-v8 with GNU General Public License v3.0 | 6 votes |
@Test public void logNotTimeReached() throws Exception { AptoideBiEventService aptoideBiEventService = mock(AptoideBiEventService.class); EventsPersistence eventPersistenceMock = mock(EventsPersistence.class); SessionPersistence sessionPersistence = mock(SessionPersistence.class); CrashLogger crashReport = mock(CrashLogger.class); AnalyticsLogger debugLogger = mock(AnalyticsLogger.class); String eventName = "test event"; String context = "test context"; Map<String, Object> data = new HashMap<>(); Event event = new Event(eventName, data, AnalyticsManager.Action.OPEN, context, 0); TestScheduler scheduler = Schedulers.test(); AptoideBiAnalytics analytics = new AptoideBiAnalytics(eventPersistenceMock, sessionPersistence, aptoideBiEventService, new CompositeSubscription(), scheduler, 200000, 20000, crashReport, debugLogger); when(aptoideBiEventService.send(any())).thenReturn(Completable.complete()); List<Event> eventList = setupPersistence(eventPersistenceMock); analytics.setup(); Thread.sleep(19); analytics.log(event.getEventName(), event.getData(), event.getAction(), event.getContext()); scheduler.advanceTimeBy(1, TimeUnit.SECONDS); verify(aptoideBiEventService, times(0)).send(any()); verify(eventPersistenceMock, times(1)).save(Matchers.<Event>any()); Assert.assertEquals(1, eventList.size()); }
Example 9
Source File: UnicastAutoReleaseSubjectTest.java From couchbase-jvm-core with Apache License 2.0 | 5 votes |
@Test public void testNoTimeoutPostSubscription() throws Exception { TestScheduler testScheduler = Schedulers.test(); UnicastAutoReleaseSubject<String> subject = UnicastAutoReleaseSubject.create(1, TimeUnit.DAYS, testScheduler); subject.onNext("Start the timeout now."); // Since the timeout is scheduled only after content arrival. final AtomicReference<Throwable> errorOnSubscribe = new AtomicReference<Throwable>(); final CountDownLatch latch = new CountDownLatch(1); subject.subscribe(Actions.empty(), new Action1<Throwable>() { @Override public void call(Throwable throwable) { errorOnSubscribe.set(throwable); latch.countDown(); } }, new Action0() { @Override public void call() { latch.countDown(); } }); testScheduler.advanceTimeBy(1, TimeUnit.DAYS); subject.onCompleted(); latch.await(1, TimeUnit.MINUTES); Assert.assertNull("Subscription got an error.", errorOnSubscribe.get()); }
Example 10
Source File: UnicastAutoReleaseSubjectTest.java From couchbase-jvm-core with Apache License 2.0 | 5 votes |
@Test(expected = IllegalStateException.class) public void testNoSubscriptionsWithOnUnsubscribeAction() throws Exception { TestScheduler testScheduler = Schedulers.test(); OnUnsubscribeAction onUnsub = new OnUnsubscribeAction(); UnicastAutoReleaseSubject<String> subject = UnicastAutoReleaseSubject.create(1, TimeUnit.DAYS, testScheduler, onUnsub); subject.onNext("Start the timeout now."); // Since the timeout is scheduled only after content arrival. testScheduler.advanceTimeBy(1, TimeUnit.DAYS); subject.toBlocking().last(); // Should immediately throw an error. }
Example 11
Source File: UnicastAutoReleaseSubjectTest.java From couchbase-jvm-core with Apache License 2.0 | 5 votes |
@Test(expected = IllegalStateException.class) public void testNoSubscriptions() throws Exception { TestScheduler testScheduler = Schedulers.test(); UnicastAutoReleaseSubject<String> subject = UnicastAutoReleaseSubject.create(1, TimeUnit.DAYS, testScheduler); subject.onNext("Start the timeout now."); // Since the timeout is scheduled only after content arrival. testScheduler.advanceTimeBy(1, TimeUnit.DAYS); subject.toBlocking().last(); // Should immediately throw an error. }
Example 12
Source File: TestScheduler.java From hawkular-metrics with Apache License 2.0 | 5 votes |
private void initTickScheduler() { DateTimeService.now = DateTime::now; tickScheduler = Schedulers.test(); tickScheduler.advanceTimeTo(currentMinute().getMillis(), TimeUnit.MILLISECONDS); DateTimeService.now = () -> new DateTime(tickScheduler.now()); }
Example 13
Source File: Example16Test.java From AnDevCon-RxPatterns with Apache License 2.0 | 5 votes |
@Test public void test_anomalous_network_event() { // TestScheduler lets you advance time by hand TestScheduler scheduler = Schedulers.test(); TestSubscriber<NetworkResponse> subscriber = new TestSubscriber<>(); // Scheduler.Worker lets you schedule events in time Scheduler.Worker worker = scheduler.createWorker(); // Subjects allow both input and output, so they can be swapped in for // Retrofit calls to unit test your code. final PublishSubject<NetworkResponse> networkSubject = PublishSubject.create(); // schedule a first observable event to occur at 1000 ms worker.schedule(new Action0() { @Override public void call() { networkSubject.onError(new TimeoutException()); } }, 10000, TimeUnit.MILLISECONDS); // subscribing so events appear networkSubject .subscribeOn(scheduler) .subscribe(subscriber); scheduler.advanceTimeBy(20000, TimeUnit.MILLISECONDS); subscriber.awaitTerminalEvent(); // we use the class-based assertError method, since it's easier to match subscriber.assertError(TimeoutException.class); subscriber.assertValueCount(0); subscriber.assertUnsubscribed(); }
Example 14
Source File: AptoideBiAnalyticsTest.java From aptoide-client-v8 with GNU General Public License v3.0 | 5 votes |
@Test public void logTimeReachedThenAddButNotSend() throws Exception { AptoideBiEventService aptoideBiEventService = mock(AptoideBiEventService.class); EventsPersistence eventPersistenceMock = mock(EventsPersistence.class); SessionPersistence sessionPersistence = mock(SessionPersistence.class); CrashLogger crashReport = mock(CrashLogger.class); AnalyticsLogger debugLogger = mock(AnalyticsLogger.class); String eventName = "test event"; String context = "test context"; Map<String, Object> data = new HashMap<>(); Event event = new Event(eventName, data, AnalyticsManager.Action.OPEN, context, 0); TestScheduler scheduler = Schedulers.test(); AptoideBiAnalytics analytics = new AptoideBiAnalytics(eventPersistenceMock, sessionPersistence, aptoideBiEventService, new CompositeSubscription(), scheduler, 0, 200, crashReport, debugLogger); when(aptoideBiEventService.send(any())).thenReturn(Completable.complete()); List<Event> eventList = setupPersistence(eventPersistenceMock); analytics.setup(); analytics.log(event.getEventName(), event.getData(), event.getAction(), event.getContext()); analytics.log(event.getEventName(), event.getData(), event.getAction(), event.getContext()); analytics.log(event.getEventName(), event.getData(), event.getAction(), event.getContext()); analytics.log(event.getEventName(), event.getData(), event.getAction(), event.getContext()); scheduler.advanceTimeBy(200, TimeUnit.SECONDS); analytics.log(event.getEventName(), event.getData(), event.getAction(), event.getContext()); verify(aptoideBiEventService, times(4)).send(any()); verify(eventPersistenceMock, times(5)).save(Matchers.<Event>any()); Assert.assertEquals(1, eventList.size()); }
Example 15
Source File: AptoideBiAnalyticsTest.java From aptoide-client-v8 with GNU General Public License v3.0 | 5 votes |
@Test public void logTimeReached() throws Exception { AptoideBiEventService aptoideBiEventService = mock(AptoideBiEventService.class); EventsPersistence eventPersistenceMock = mock(EventsPersistence.class); SessionPersistence sessionPersistence = mock(SessionPersistence.class); AnalyticsLogger debugLogger = mock(AnalyticsLogger.class); CrashLogger crashReport = mock(CrashLogger.class); String eventName = "test event"; String context = "test context"; Map<String, Object> data = new HashMap<>(); Event event = new Event(eventName, data, AnalyticsManager.Action.OPEN, context, 0); TestScheduler scheduler = Schedulers.test(); AptoideBiAnalytics analytics = new AptoideBiAnalytics(eventPersistenceMock, sessionPersistence, aptoideBiEventService, new CompositeSubscription(), scheduler, 0, 200, crashReport, debugLogger); when(aptoideBiEventService.send(any())).thenReturn(Completable.complete()); List<Event> eventList = setupPersistence(eventPersistenceMock); analytics.setup(); analytics.log(event.getEventName(), event.getData(), event.getAction(), event.getContext()); analytics.log(event.getEventName(), event.getData(), event.getAction(), event.getContext()); analytics.log(event.getEventName(), event.getData(), event.getAction(), event.getContext()); analytics.log(event.getEventName(), event.getData(), event.getAction(), event.getContext()); scheduler.advanceTimeBy(200, TimeUnit.SECONDS); verify(aptoideBiEventService, times(4)).send(any()); verify(eventPersistenceMock, times(4)).save(Matchers.<Event>any()); Assert.assertEquals(0, eventList.size()); }
Example 16
Source File: SubscriptionTimeoutTest.java From titus-control-plane with Apache License 2.0 | 5 votes |
@Before public void setUp() throws Exception { this.source = PublishSubject.<String>create().toSerialized(); this.testScheduler = Schedulers.test(); this.subscriber = source .lift(new SubscriptionTimeout<>(TEST_TIMEOUT_MS, TimeUnit.MILLISECONDS, testScheduler)) .test(); }
Example 17
Source File: SchedulersLiveTest.java From tutorials with MIT License | 5 votes |
@Test public void givenLetters_whenTestScheduling_thenReturnValuesControllingAdvanceTime() throws InterruptedException { List<String> letters = Arrays.asList("A", "B", "C"); TestScheduler scheduler = Schedulers.test(); TestSubscriber<String> subscriber = new TestSubscriber<>(); Observable<Long> tick = Observable.interval(1, TimeUnit.SECONDS, scheduler); Observable.from(letters) .zipWith(tick, (string, index) -> index + "-" + string) .subscribeOn(scheduler) .subscribe(subscriber); subscriber.assertNoValues(); subscriber.assertNotCompleted(); scheduler.advanceTimeBy(1, TimeUnit.SECONDS); subscriber.assertNoErrors(); subscriber.assertValueCount(1); subscriber.assertValues("0-A"); scheduler.advanceTimeTo(3, TimeUnit.SECONDS); subscriber.assertCompleted(); subscriber.assertNoErrors(); subscriber.assertValueCount(3); assertThat(subscriber.getOnNextEvents(), hasItems("0-A", "1-B", "2-C")); }
Example 18
Source File: AwsObservableExtTest.java From titus-control-plane with Apache License 2.0 | 5 votes |
@Test public void asyncActionCompletableErrors() { AmazonWebServiceRequest someRequest = AmazonWebServiceRequest.NOOP; final MockAsyncClient<AmazonWebServiceRequest, String> client = new MockAsyncClient<>(someRequest, "some response"); RuntimeException exception = new RuntimeException("error when initiating an async operation"); final Completable completable = AwsObservableExt.asyncActionCompletable(factory -> client.throwException(exception)); TestScheduler testScheduler = Schedulers.test(); final AssertableSubscriber<Void> subscriber = completable.subscribeOn(testScheduler).test(); testScheduler.triggerActions(); subscriber.assertError(exception); }
Example 19
Source File: Example16Test.java From AnDevCon-RxPatterns with Apache License 2.0 | 4 votes |
@Test public void using_testscheduler_to_simulate_network_events() { // TestScheduler lets you advance time by hand TestScheduler scheduler = Schedulers.test(); TestSubscriber<NetworkResponse> subscriber = new TestSubscriber<>(); // Scheduler.Worker lets you schedule events in time Scheduler.Worker worker = scheduler.createWorker(); // Subjects allow both input and output, so they can be swapped in for // Retrofit calls to unit test your code. final PublishSubject<NetworkResponse> networkSubject = PublishSubject.create(); // schedule a first observable event to occur at 1000 ms worker.schedule(new Action0() { @Override public void call() { // explicitly calling onNext in a worker allows one to // create a very specific test of timed events networkSubject.onNext(new NetworkResponse(401)); } }, 1000, TimeUnit.MILLISECONDS); // schedule a second observable event to occur at 2000 ms worker.schedule(new Action0() { @Override public void call() { networkSubject.onNext(new NetworkResponse(200)); networkSubject.onCompleted(); } }, 2000, TimeUnit.MILLISECONDS); // we must subscribe before anticipating results networkSubject .subscribeOn(scheduler) .subscribe(subscriber); // we can manually advance time using the scheduler and check assertions scheduler.advanceTimeBy(1500, TimeUnit.MILLISECONDS); subscriber.assertReceivedOnNext(Arrays.asList( new NetworkResponse(401))); // awaitTerminalEvent will wait forever if we don't advance time enough scheduler.advanceTimeBy(500, TimeUnit.MILLISECONDS); subscriber.awaitTerminalEvent(); subscriber.assertReceivedOnNext(Arrays.asList( new NetworkResponse(401), new NetworkResponse(200))); // TestSubscriber provides many useful methods subscriber.assertNoErrors(); subscriber.assertValueCount(2); subscriber.assertUnsubscribed(); }
Example 20
Source File: LargestPerTimeBucketTest.java From titus-control-plane with Apache License 2.0 | 4 votes |
@Before public void setUp() { testScheduler = Schedulers.test(); }