Java Code Examples for rx.schedulers.TestScheduler#advanceTimeBy()

The following examples show how to use rx.schedulers.TestScheduler#advanceTimeBy() . 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: UnicastAutoReleaseSubjectTest.java    From couchbase-jvm-core with Apache License 2.0 6 votes vote down vote up
@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 2
Source File: RxJavaTimeFilteringOperatorsIntegrationTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenRangeObservable_whenThrottlingFirst_thenThrottledFirstItemsAreEmitted() {

    TestScheduler testScheduler = new TestScheduler();

    Observable<Integer> timedObservable =
            Observable.just(1, 2, 3, 4, 5, 6)
                    .zipWith(
                            Observable.interval(0, 1, TimeUnit.SECONDS, testScheduler),
                            (item, time) -> item
                    );

    TestSubscriber<Integer> subscriber = new TestSubscriber();

    Observable<Integer> filteredObservable =
            timedObservable.throttleFirst(4100L, TimeUnit.MILLISECONDS, testScheduler);

    filteredObservable.subscribe(subscriber);

    testScheduler.advanceTimeBy(7, TimeUnit.SECONDS);

    subscriber.assertCompleted();
    subscriber.assertNoErrors();
    subscriber.assertValues(1, 6);
}
 
Example 3
Source File: UnicastAutoReleaseSubjectTest.java    From couchbase-jvm-core with Apache License 2.0 6 votes vote down vote up
@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 4
Source File: RxJavaTimeFilteringOperatorsIntegrationTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenTimedObservable_whenThrottlingWithTimeout_thenLastItemIsEmitted() {

    TestScheduler testScheduler = new TestScheduler();

    Observable<Integer> timedObservable =
            Observable.just(1, 2, 3, 4, 5, 6)
                    .zipWith(
                            Observable.interval(0, 1, TimeUnit.SECONDS, testScheduler),
                            (item, time) -> item
                    );

    TestSubscriber<Integer> subscriber = new TestSubscriber();

    Observable<Integer> filteredObservable = timedObservable.throttleWithTimeout(2000L, TimeUnit.MILLISECONDS, testScheduler);

    filteredObservable.subscribe(subscriber);

    testScheduler.advanceTimeBy(7, TimeUnit.SECONDS);

    subscriber.assertCompleted();
    subscriber.assertNoErrors();
    subscriber.assertValue(6);
}
 
Example 5
Source File: DefaultEventBusTest.java    From couchbase-jvm-core with Apache License 2.0 6 votes vote down vote up
@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 6
Source File: RxJavaTimeFilteringOperatorsIntegrationTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenTimedObservable_whenThrottlingLast_thenThrottleLastItemsAreEmitted() {

    TestScheduler testScheduler = new TestScheduler();

    Observable<Integer> timedObservable =
            Observable.just(1, 2, 3, 4, 5, 6)
                    .zipWith(
                            Observable.interval(0, 1, TimeUnit.SECONDS, testScheduler),
                            (item, time) -> item
                    );

    TestSubscriber<Integer> subscriber = new TestSubscriber();

    Observable<Integer> filteredObservable = timedObservable.throttleLast(3100L, TimeUnit.MILLISECONDS, testScheduler);

    filteredObservable.subscribe(subscriber);

    testScheduler.advanceTimeBy(7, TimeUnit.SECONDS);

    subscriber.assertCompleted();
    subscriber.assertNoErrors();
    subscriber.assertValues(4, 6);
}
 
Example 7
Source File: TransformersTest.java    From rxjava-extras with Apache License 2.0 6 votes vote down vote up
@Test
public void testDelayWithPlayRate() {
    TestSubscriber<Object> ts = TestSubscriber.create();
    TestScheduler scheduler = new TestScheduler();
    Func1<Integer, Long> time = new Func1<Integer, Long>() {

        @Override
        public Long call(Integer t) {
            return (long) t;
        }
    };
    Observable //
            .just(1, 2, 3) //
            .compose(Transformers.delay(time, Functions.constant0(0.001), 0, scheduler)) //
            .subscribe(ts);
    ts.assertNoValues();
    scheduler.advanceTimeBy(1, TimeUnit.SECONDS);
    ts.assertValue(1);
    scheduler.advanceTimeBy(1, TimeUnit.SECONDS);
    ts.assertValues(1, 2);
    scheduler.advanceTimeBy(1, TimeUnit.SECONDS);
    ts.assertValues(1, 2, 3);
    ts.assertCompleted();
}
 
Example 8
Source File: DefaultEventBusTest.java    From couchbase-jvm-core with Apache License 2.0 6 votes vote down vote up
@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 9
Source File: ObsTest.java    From rxjava-extras with Apache License 2.0 6 votes vote down vote up
@Test
public void testCachedResetableScheduledReset() {
    TestScheduler scheduler = new TestScheduler();
    final AtomicInteger count = new AtomicInteger(0);
    Observable<Integer> o = Observable.defer(new Func0<Observable<Integer>>() {
        @Override
        public Observable<Integer> call() {
            return Observable.just(count.incrementAndGet());
        }
    });
    CloseableObservableWithReset<Integer> cached = Obs.cache(o, 5, TimeUnit.MINUTES, scheduler);
    assertEquals(1, (int) cached.observable().toBlocking().single());
    scheduler.advanceTimeBy(1, TimeUnit.MINUTES);
    assertEquals(1, (int) cached.observable().toBlocking().single());
    cached.reset();
    scheduler.advanceTimeBy(5, TimeUnit.MINUTES);
    assertEquals(2, (int) cached.observable().toBlocking().single());
    scheduler.advanceTimeBy(1, TimeUnit.MINUTES);
    assertEquals(2, (int) cached.observable().toBlocking().single());
    cached.reset();
    assertEquals(2, (int) cached.observable().toBlocking().single());
    scheduler.advanceTimeBy(5, TimeUnit.MINUTES);
    assertEquals(3, (int) cached.observable().toBlocking().single());
    cached.close();
}
 
Example 10
Source File: RxJavaTimeFilteringOperatorsIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenObservable_whenSkippingWhile_thenItemsAreEmittedUntilSecondObservableEmitsItems() {

    TestScheduler testScheduler = new TestScheduler();

    Observable<Integer> timedObservable =
            Observable.just(1, 2, 3, 4, 5, 6)
                    .zipWith(
                            Observable.interval(0, 1, TimeUnit.SECONDS, testScheduler),
                            (item, time) -> item
                    );

    TestSubscriber subscriber = new TestSubscriber();

    Observable<Integer> delayedObservable = Observable.just(1)
            .delay(3000, TimeUnit.MILLISECONDS, testScheduler);

    Observable<Integer> filteredObservable = timedObservable.takeUntil(delayedObservable);

    filteredObservable.subscribe(subscriber);

    testScheduler.advanceTimeBy(7, TimeUnit.SECONDS);

    subscriber.assertCompleted();
    subscriber.assertNoErrors();
    subscriber.assertValues(1, 2, 3);
}
 
Example 11
Source File: UnicastAutoReleaseSubjectTest.java    From couchbase-jvm-core with Apache License 2.0 5 votes vote down vote up
@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 12
Source File: UnicastAutoReleaseSubjectTest.java    From couchbase-jvm-core with Apache License 2.0 5 votes vote down vote up
@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 13
Source File: EurekaInterestManagerTest.java    From ocelli with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddRemoveInstances() {
    InstanceInfo i1 = createInstance(1);
    InstanceInfo i2 = createInstance(2);
    InstanceInfo i3 = createInstance(3);
    InstanceInfo i4 = createInstance(4);
    
    Mockito.when(client.getApplication("foo")).thenReturn(application);
    
    AtomicReference<List<InstanceInfo>> result = new AtomicReference<List<InstanceInfo>>();
    
    TestScheduler scheduler = new TestScheduler();
    EurekaInterestManager eureka = new EurekaInterestManager(client);
    eureka.newInterest()
        .forApplication("foo")
        .withRefreshInterval(1, TimeUnit.SECONDS)
        .withScheduler(scheduler)
        .asObservable()
        .compose(InstanceCollector.<InstanceInfo>create())
        .subscribe(RxUtil.set(result));

    Mockito.when(application.getInstances()).thenReturn(Arrays.asList(i1, i2));
    scheduler.advanceTimeBy(10, TimeUnit.SECONDS);
    Assert.assertEquals(Sets.newHashSet(i2, i1), Sets.newHashSet(result.get()));
    
    Mockito.when(application.getInstances()).thenReturn(Arrays.asList(i1, i2, i3));
    scheduler.advanceTimeBy(10, TimeUnit.SECONDS);
    Assert.assertEquals(Sets.newHashSet(i3, i2, i1), Sets.newHashSet(result.get()));
   
    Mockito.when(application.getInstances()).thenReturn(Arrays.asList(i3, i4));
    scheduler.advanceTimeBy(10, TimeUnit.SECONDS);
    Assert.assertEquals(Sets.newHashSet(i3, i4), Sets.newHashSet(result.get()));
    
    Mockito.when(application.getInstances()).thenReturn(Arrays.<InstanceInfo>asList());
    scheduler.advanceTimeBy(10, TimeUnit.SECONDS);
    Assert.assertEquals(Sets.newHashSet(), Sets.newHashSet(result.get()));
}
 
Example 14
Source File: ObsTest.java    From rxjava-extras with Apache License 2.0 5 votes vote down vote up
@Test
public void testIntervalLong() {
    TestSubscriber<Long> ts = TestSubscriber.create();
    TestScheduler sched = new TestScheduler();
    Obs.intervalLong(1, TimeUnit.SECONDS, sched).subscribe(ts);
    ts.assertNoValues();
    ts.assertNotCompleted();
    sched.advanceTimeBy(1, TimeUnit.SECONDS);
    ts.assertValue(0L);
    sched.advanceTimeBy(1, TimeUnit.SECONDS);
    ts.assertValues(0L, 1L);
    ts.assertNotCompleted();
}
 
Example 15
Source File: AptoideBiAnalyticsTest.java    From aptoide-client-v8 with GNU General Public License v3.0 5 votes vote down vote up
@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: TransformersTest.java    From rxjava-extras with Apache License 2.0 5 votes vote down vote up
@Test
// @org.junit.Ignore
public void testDelayFinalUnsubscribeForRefCount() {
    TestScheduler s = new TestScheduler();
    final AtomicInteger count = new AtomicInteger();
    Observable<Long> o = Observable //
            .interval(1, TimeUnit.SECONDS, s) //
            .doOnSubscribe(Actions.increment0(count)) //
            .publish() //
            .refCount() //
            .compose(Transformers.<Long> delayFinalUnsubscribe(2500, TimeUnit.MILLISECONDS, s));
    {
        TestSubscriber<Long> ts1 = TestSubscriber.create();
        o.subscribe(ts1);
        assertEquals(1, count.get());
        s.advanceTimeBy(1, TimeUnit.SECONDS);
        ts1.assertValues(0L);
        ts1.unsubscribe();
    }
    s.advanceTimeBy(1, TimeUnit.SECONDS);
    {
        TestSubscriber<Long> ts2 = TestSubscriber.create();
        o.subscribe(ts2);
        ts2.assertNoValues();
        s.advanceTimeBy(1, TimeUnit.SECONDS);
        ts2.assertValues(2L);
        ts2.unsubscribe();
    }
    assertEquals(1, count.get());
    s.advanceTimeBy(2500, TimeUnit.MILLISECONDS);
    {
        TestSubscriber<Long> ts3 = TestSubscriber.create();
        s.advanceTimeBy(1, TimeUnit.SECONDS);
        o.subscribe(ts3);
        assertEquals(2, count.get());
        s.advanceTimeBy(1, TimeUnit.SECONDS);
        ts3.assertValues(0L);
    }

}
 
Example 17
Source File: SchedulersLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@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: TimeoutCancelTest.java    From akarnokd-misc with Apache License 2.0 5 votes vote down vote up
@Test
public void test3() throws Exception {
    TestScheduler sch = new TestScheduler();

    Subject<Long, Long> subject = PublishSubject.create();
    Observable<Long> initialObservable = subject.share()
    .map(value -> {
        System.out.println("Received value " + value);
        //new Exception().printStackTrace(System.out);
        return value;
    });

    Observable<Long> timeoutObservable = initialObservable.map(value -> {
       System.out.println("Timeout received value " + value);
       return value;
    });

    TestSubscriber<Long> subscriber = new TestSubscriber<>();
    initialObservable
    .doOnUnsubscribe(() -> System.out.println("Unsubscribed"))
    .timeout(1, TimeUnit.SECONDS, timeoutObservable, sch).subscribe(subscriber);
    subject.onNext(5L);
    sch.advanceTimeBy(2, TimeUnit.SECONDS);
    subject.onNext(10L);
    subject.onCompleted();

    subscriber.awaitTerminalEvent();
    subscriber.assertNoErrors();
    subscriber.assertValues(5L, 10L);
}
 
Example 19
Source File: TimeoutCancelTest.java    From akarnokd-misc with Apache License 2.0 5 votes vote down vote up
@Test
    public void test() {
PublishSubject<Integer> ps = PublishSubject.create();
TestScheduler sch = new TestScheduler();

AssertableSubscriber<Integer> as = ps.timeout(1, TimeUnit.SECONDS, Observable.just(1), sch)
.test();

sch.advanceTimeBy(1, TimeUnit.SECONDS);

Assert.assertFalse(ps.hasObservers());

as.assertResult(1);
    }
 
Example 20
Source File: AptoideBiAnalyticsTest.java    From aptoide-client-v8 with GNU General Public License v3.0 5 votes vote down vote up
@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());
}