Java Code Examples for io.reactivex.schedulers.TestScheduler#advanceTimeBy()

The following examples show how to use io.reactivex.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: NonBlockingPoolTest.java    From rxjava2-jdbc with Apache License 2.0 6 votes vote down vote up
@Test
public void testMemberAvailableAfterCreationScheduledIsUsedImmediately() throws InterruptedException {
    TestScheduler ts = new TestScheduler();
    Scheduler s = createScheduleToDelayCreation(ts);
    AtomicInteger count = new AtomicInteger();
    Pool<Integer> pool = NonBlockingPool //
            .factory(() -> count.incrementAndGet()) //
            .createRetryInterval(10, TimeUnit.MINUTES) //
            .maxSize(2) //
            .maxIdleTime(1, TimeUnit.HOURS) //
            .scheduler(s) //
            .build();
    List<Member<Integer>> list = new ArrayList<Member<Integer>>();
    pool.member().doOnSuccess(m -> list.add(m)).subscribe();
    assertEquals(0, list.size());
    ts.advanceTimeBy(1, TimeUnit.MINUTES);
    ts.triggerActions();
    assertEquals(1, list.size());
    pool.member().doOnSuccess(m -> list.add(m)).subscribe();
    list.get(0).checkin();
    ts.triggerActions();
    assertEquals(2, list.size());
}
 
Example 2
Source File: SingleConcatTest.java    From akarnokd-misc with Apache License 2.0 6 votes vote down vote up
@Test
public void test() {
  TestScheduler testScheduler = new TestScheduler();

  final Single<List<Integer>> first = Single.timer(2, TimeUnit.SECONDS, testScheduler)
          .map(u -> Arrays.asList(1, 2, 3));
  final Single<List<Integer>> second = Single.just(Collections.emptyList());
  final Single<List<Integer>> third = Single.just(Collections.singletonList(4));
  final Single<List<Integer>> fourth = Single.just(Collections.singletonList(5));

  Single<List<Integer>> subject = Observable
    .fromIterable(Arrays.asList(first, second, third, fourth))
    .concatMapSingle(single -> single)
    .reduce(new ArrayList<>(), (seed, items) -> {
      seed.addAll(items);
      return seed;
    });

    TestObserver<List<Integer>> testObserver = subject.test();
    testScheduler.advanceTimeBy(3, TimeUnit.SECONDS);

    System.out.println(testObserver.values());
    testObserver.assertValue(list -> list.equals(Arrays.asList(1, 2, 3, 4, 5))); 
    // 5 is currently missing ; fourth was never subscribed in the first place
}
 
Example 3
Source File: ThrottleSampleTest.java    From akarnokd-misc with Apache License 2.0 6 votes vote down vote up
@Test
public void test() {
    TestScheduler tsch = new TestScheduler();

    Flowable.fromArray(
            100,                // should emit 100 at T=100
            110, 120, 130, 150, // should emit 150 at T=200 
            250, 260,           // should emit 260 at T=300
            400                 // should emit 400 at T=400
    )
    .flatMap(v -> Flowable.timer(v, TimeUnit.MILLISECONDS, tsch).map(w -> v))
    .compose(throttleFirstSample(100, TimeUnit.MILLISECONDS, tsch))
    .subscribe(v -> System.out.println(v + " at T=" + tsch.now(TimeUnit.MILLISECONDS)));
    
    tsch.advanceTimeBy(1, TimeUnit.SECONDS);
}
 
Example 4
Source File: RxFlatmapAndSwitchmapUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenObservable_whenSwitchmap_shouldAssertLatestItemReturned() {
    //given
    List<String> actualOutput = new ArrayList<>();
    final TestScheduler scheduler = new TestScheduler();
    final List<String> keywordToSearch = Arrays.asList("b", "bo", "boo", "book", "books");

    //when
    Observable.fromIterable(keywordToSearch)
      .switchMap(s -> Observable
        .just(s + " FirstResult", s + " SecondResult")
        .delay(10, TimeUnit.SECONDS, scheduler))
      .toList()
      .doOnSuccess(s -> actualOutput.addAll(s))
      .subscribe();

    scheduler.advanceTimeBy(1, TimeUnit.MINUTES);

    //then
    assertEquals(2, actualOutput.size());
    assertThat(actualOutput, hasItems("books FirstResult", "books SecondResult"));
}
 
Example 5
Source File: TransformersTest.java    From rxjava2-extras with Apache License 2.0 6 votes vote down vote up
@Test
public void testInsertWithDelays() {
    TestScheduler s = new TestScheduler();
    TestSubscriber<Integer> ts = //
            Flowable.just(1).delay(1, TimeUnit.SECONDS, s) //
                    .concatWith(Flowable.just(2).delay(3, TimeUnit.SECONDS, s)) //
                    .compose(Transformers.insert(Maybe.just(3).delay(2, TimeUnit.SECONDS, s))) //
                    .test();
    ts.assertNoValues();
    s.advanceTimeBy(1, TimeUnit.SECONDS);
    ts.assertValues(1);
    s.advanceTimeBy(2, TimeUnit.SECONDS);
    ts.assertValues(1, 3);
    s.advanceTimeBy(1, TimeUnit.SECONDS);
    ts.assertValues(1, 3, 2);
    ts.assertComplete();
}
 
Example 6
Source File: RetryWhenTest.java    From rxjava2-extras with Apache License 2.0 6 votes vote down vote up
@Test
public void testWithScheduler() {
    Exception ex = new IllegalArgumentException("boo");
    TestSubscriber<Integer> ts = TestSubscriber.create();
    TestScheduler scheduler = new TestScheduler();
    Flowable.just(1, 2)
            // force error after 3 emissions
            .concatWith(Flowable.<Integer>error(ex))
            // retry with backoff
            .retryWhen(RetryWhen.maxRetries(2).action(log).exponentialBackoff(1, TimeUnit.MINUTES)
                    .scheduler(scheduler).build())
            // go
            .subscribe(ts);
    ts.assertValues(1, 2);
    ts.assertNotComplete();
    scheduler.advanceTimeBy(1, TimeUnit.MINUTES);
    ts.assertValues(1, 2, 1, 2);
    ts.assertNotComplete();
    // next wait is 2 seconds so advancing by 1 should do nothing
    scheduler.advanceTimeBy(1, TimeUnit.MINUTES);
    ts.assertValues(1, 2, 1, 2);
    ts.assertNotComplete();
    scheduler.advanceTimeBy(1, TimeUnit.MINUTES);
    ts.assertValues(1, 2, 1, 2, 1, 2);
    ts.assertError(ex);
}
 
Example 7
Source File: RxFlatmapAndSwitchmapUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenObservable_whenFlatmap_shouldAssertAllItemsReturned() {
    //given
    List<String> actualOutput = new ArrayList<>();
    final TestScheduler scheduler = new TestScheduler();
    final List<String> keywordToSearch = Arrays.asList("b", "bo", "boo", "book", "books");

    //when
    Observable.fromIterable(keywordToSearch)
      .flatMap(s -> Observable
        .just(s + " FirstResult", s + " SecondResult")
        .delay(10, TimeUnit.SECONDS, scheduler))
      .toList()
      .doOnSuccess(s -> actualOutput.addAll(s))
      .subscribe();

    scheduler.advanceTimeBy(1, TimeUnit.MINUTES);

    //then
    assertThat(actualOutput, hasItems("b FirstResult", "b SecondResult",
      "boo FirstResult", "boo SecondResult",
      "bo FirstResult", "bo SecondResult",
      "book FirstResult", "book SecondResult",
      "books FirstResult", "books SecondResult"));
}
 
Example 8
Source File: NonBlockingPoolTest.java    From rxjava2-jdbc with Apache License 2.0 6 votes vote down vote up
@Test
public void testMaxIdleTime() throws InterruptedException {
    TestScheduler s = new TestScheduler();
    AtomicInteger count = new AtomicInteger();
    AtomicInteger disposed = new AtomicInteger();
    Pool<Integer> pool = NonBlockingPool //
            .factory(() -> count.incrementAndGet()) //
            .healthCheck(n -> true) //
            .maxSize(3) //
            .maxIdleTime(1, TimeUnit.MINUTES) //
            .disposer(n -> disposed.incrementAndGet()) //
            .scheduler(s) //
            .build();
    TestSubscriber<Member<Integer>> ts = new FlowableSingleDeferUntilRequest<>( //
            pool.member()) //
                    .doOnNext(m -> m.checkin()) //
                    .doOnNext(System.out::println) //
                    .doOnRequest(t -> System.out.println("test request=" + t)) //
                    .test(1);
    s.triggerActions();
    ts.assertValueCount(1);
    assertEquals(0, disposed.get());
    s.advanceTimeBy(1, TimeUnit.MINUTES);
    s.triggerActions();
    assertEquals(1, disposed.get());
}
 
Example 9
Source File: Modern_Testing.java    From Reactive-Programming-With-Java-9 with MIT License 6 votes vote down vote up
@Test
public void test_interval()
{
	TestScheduler testScheduler=new TestScheduler();
	Observable<Long>observable=Observable.interval(1, TimeUnit.SECONDS,testScheduler).take(5);
	TestObserver<Long> testObserver=new TestObserver<>();

	
	observable.subscribeOn(testScheduler).subscribe(testObserver);
	
	testObserver.assertNoValues();
	testObserver.assertNotComplete();
	testObserver.assertNoErrors();
	
	testScheduler.advanceTimeBy(1, TimeUnit.SECONDS);
	testObserver.assertValueCount(1);
	testObserver.assertValues(0l);
	
	testScheduler.advanceTimeTo(6, TimeUnit.SECONDS);
	testObserver.assertValueCount(5);
	testObserver.assertValues(0l,1l,2l,3l,4l);
}
 
Example 10
Source File: RxJavaDemoTest.java    From reactive-streams-in-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testScheduler() {
    TestScheduler scheduler = new TestScheduler(); //1
    Observable<Long> tick = Observable
            .interval(1, TimeUnit.SECONDS, scheduler); //2
    Observable<String> observable =
            Observable.just("foo", "bar", "biz", "baz") //3
            .zipWith(tick, (string, index) -> index + "-" + string);//4
    TestObserver<String> testObserver = observable
            .subscribeOn(scheduler).test();//5

    scheduler.advanceTimeBy(2300, TimeUnit.MILLISECONDS);//6

    testObserver.assertNoErrors(); //7
    testObserver.assertValues("0-foo", "1-bar");
    testObserver.assertNotComplete();
}
 
Example 11
Source File: AdamantApiWrapperSwitchOnFailureTest.java    From adamant-android with GNU General Public License v3.0 6 votes vote down vote up
@Before
public void before() {
    initStubs();

    counter = new AtomicInteger(0);
    scheduler = new TestScheduler();

    when(apiBuilder.build())
            .thenReturn(
                    Flowable.defer(() -> buildMockedApiWithErrorChatLoading(testNameRule.getMethodName())).toObservable()
            );
    when(keyGenerator.getKeyPairFromPassPhrase(TestConstants.TEST_PASS_PHRASE))
            .thenReturn(new KeyPair(TestConstants.TEST_PUBLIC_KEY, TestConstants.TEST_SECRET_KEY));

    wrapper = new AdamantApiWrapper(apiBuilder, keyGenerator, scheduler);

    Disposable subscribe = wrapper
            .authorize(TestConstants.TEST_PASS_PHRASE)
            .subscribe();
    subscritions.add(subscribe);

    scheduler.advanceTimeBy(1, TimeUnit.SECONDS);
}
 
Example 12
Source File: TimeoutCancelv2Test.java    From akarnokd-misc with Apache License 2.0 5 votes vote down vote up
@Test
public void test4() throws Exception {
    TestScheduler sch = new TestScheduler();

    Subject<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;
    });

    TestObserver<Long> subscriber = new TestObserver<>();
    initialObservable
    .doOnDispose(() -> { 
        System.out.println("Unsubscribed"); 
        new Exception().printStackTrace(System.out);
    })
    .timeout(1, TimeUnit.SECONDS, sch, timeoutObservable).subscribe(subscriber);
    subject.onNext(5L);
    sch.advanceTimeBy(2, TimeUnit.SECONDS);
    subject.onNext(10L);
    subject.onComplete();

    subscriber.awaitTerminalEvent();
    subscriber.assertNoErrors();
    subscriber.assertValues(5L, 10L);
}
 
Example 13
Source File: NonBlockingPoolTest.java    From rxjava2-jdbc with Apache License 2.0 5 votes vote down vote up
@Test
public void testDirectSchedule() {
    TestScheduler s = new TestScheduler();
    AtomicBoolean b = new AtomicBoolean();
    s.scheduleDirect(() -> b.set(true), 1, TimeUnit.MINUTES);
    s.scheduleDirect(() -> b.set(false), 2, TimeUnit.MINUTES);
    s.advanceTimeBy(1, TimeUnit.MINUTES);
    assertTrue(b.get());
    s.advanceTimeBy(1, TimeUnit.MINUTES);
    assertFalse(b.get());
}
 
Example 14
Source File: NonBlockingPoolTest.java    From rxjava2-jdbc with Apache License 2.0 5 votes vote down vote up
@Test
public void testPoolFactoryWhenFailsThenRecovers() {
    AtomicReference<Throwable> ex = new AtomicReference<>();
    Consumer<? super Throwable> handler = RxJavaPlugins.getErrorHandler();
    RxJavaPlugins.setErrorHandler(t -> ex.set(t));
    try {
        TestScheduler s = new TestScheduler();
        AtomicInteger c = new AtomicInteger();
        NonBlockingPool<Integer> pool = NonBlockingPool.factory(() -> {
            if (c.getAndIncrement() == 0) {
                throw new TestException();
            } else {
                return c.get();
            }
        }) //
                .maxSize(1) //
                .scheduler(s) //
                .createRetryInterval(10, TimeUnit.SECONDS) //
                .build();
        TestObserver<Integer> ts = pool.member() //
                .map(m -> m.value()) //
                .test() //
                .assertNotTerminated() //
                .assertNoValues();
        s.triggerActions();
        assertTrue(ex.get() instanceof UndeliverableException);
        assertTrue(((UndeliverableException) ex.get()).getCause() instanceof TestException);
        s.advanceTimeBy(10, TimeUnit.SECONDS);
        s.triggerActions();
        ts.assertComplete();
        ts.assertValue(2);
    } finally {
        RxJavaPlugins.setErrorHandler(handler);
    }
}
 
Example 15
Source File: DatabaseTest.java    From rxjava2-jdbc with Apache License 2.0 5 votes vote down vote up
private void testHealthCheck(Predicate<Connection> healthy) throws InterruptedException {
    TestScheduler scheduler = new TestScheduler();

    NonBlockingConnectionPool pool = Pools //
            .nonBlocking() //
            .connectionProvider(DatabaseCreator.connectionProvider()) //
            .maxIdleTime(10, TimeUnit.MINUTES) //
            .idleTimeBeforeHealthCheck(0, TimeUnit.MINUTES) //
            .healthCheck(healthy) //
            .scheduler(scheduler) //
            .maxPoolSize(1) //
            .build();

    try (Database db = Database.from(pool)) {
        TestSubscriber<Integer> ts0 = db.select( //
                "select score from person where name=?") //
                .parameter("FRED") //
                .getAs(Integer.class) //
                .test();
        ts0.assertValueCount(0) //
                .assertNotComplete();
        scheduler.advanceTimeBy(1, TimeUnit.MINUTES);
        ts0.assertValueCount(1) //
                .assertComplete();
        TestSubscriber<Integer> ts = db.select( //
                "select score from person where name=?") //
                .parameter("FRED") //
                .getAs(Integer.class) //
                .test() //
                .assertValueCount(0);
        log.debug("done2");
        scheduler.advanceTimeBy(1, TimeUnit.MINUTES);
        Thread.sleep(200);
        ts.assertValueCount(1);
        Thread.sleep(200);
        ts.assertValue(21) //
                .assertComplete();
    }
}
 
Example 16
Source File: TimeoutCancelv2Test.java    From akarnokd-misc with Apache License 2.0 5 votes vote down vote up
@Test
public void test5() throws Exception {
    TestScheduler sch = new TestScheduler();

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

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

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

    subscriber.awaitTerminalEvent();
    subscriber.assertNoErrors();
    subscriber.assertValues(5L, 10L);
}
 
Example 17
Source File: ProcessorTest.java    From state-machine with Apache License 2.0 5 votes vote down vote up
@Test
public void testCancelSignal() {
    // special scheduler that we will use to schedule signals
    TestScheduler signalScheduler = new TestScheduler();

    Processor<String> processor = createProcessor(signalScheduler);

    // do some tests with the processor
    TestSubscriber<EntityStateMachine<?, String>> ts = TestSubscriber.create();
    processor.flowable().doOnNext(m -> System.out.println(m.state())).subscribe(ts);

    ClassId<Microwave, String> microwave = ClassId.create(Microwave.class, "1");

    // button is pressed
    processor.signal(microwave, new ButtonPressed());
    ts.assertValueCount(1);
    assertEquals(MicrowaveStateMachine.State.COOKING, ts.values().get(0).state());
    // advance by less time than the timeout
    signalScheduler.advanceTimeBy(10, TimeUnit.SECONDS);
    ts.assertValueCount(1);
    processor.cancelSignalToSelf(microwave);

    // cooking would time out by now if signal had not been cancelled
    signalScheduler.advanceTimeBy(30, TimeUnit.SECONDS);
    ts.assertValueCount(1);

    // now cancel a non-existent signal to get coverage
    processor.cancelSignalToSelf(microwave);
    ts.assertValueCount(1);

    processor.onCompleted();
    ts.assertNoErrors();
}
 
Example 18
Source File: BufferWithConditionAndTime.java    From akarnokd-misc with Apache License 2.0 5 votes vote down vote up
@Test
public void test() {
TestScheduler scheduler = new TestScheduler();
PublishProcessor<String> pp = PublishProcessor.create();

Function<Flowable<String>, Flowable<List<String>>> f = o -> 
        o.buffer(o.filter(v -> v.contains("Start")), 
                v -> Flowable.merge(o.filter(w -> w.contains("End")), 
                        Flowable.timer(5, TimeUnit.MINUTES, scheduler))); 

pp.publish(f)
.subscribe(System.out::println);

pp.onNext("Start");
pp.onNext("A");
pp.onNext("B");
pp.onNext("End");

pp.onNext("Start");
pp.onNext("C");

scheduler.advanceTimeBy(5, TimeUnit.MINUTES);

pp.onNext("Start");
pp.onNext("D");
pp.onNext("End");
pp.onComplete();
    
}
 
Example 19
Source File: NonBlockingPoolTest.java    From rxjava2-jdbc with Apache License 2.0 4 votes vote down vote up
@Test
public void testHealthCheckWhenFails() throws Exception {
    TestScheduler s = new TestScheduler();
    AtomicInteger count = new AtomicInteger();
    AtomicInteger disposed = new AtomicInteger();
    AtomicInteger healthChecks = new AtomicInteger();
    Pool<Integer> pool = NonBlockingPool //
            .factory(() -> count.incrementAndGet()) //
            .healthCheck(n -> {
                healthChecks.incrementAndGet();
                return false;
            }) //
            .createRetryInterval(10, TimeUnit.MINUTES) //
            .idleTimeBeforeHealthCheck(1, TimeUnit.MILLISECONDS) //
            .maxSize(1) //
            .maxIdleTime(1, TimeUnit.HOURS) //
            .disposer(n -> disposed.incrementAndGet()) //
            .scheduler(s) //
            .build();
    {
        TestSubscriber<Member<Integer>> ts = new FlowableSingleDeferUntilRequest<>(pool.member()) //
                .repeat() //
                .doOnNext(System.out::println) //
                .doOnNext(m -> m.checkin()) //
                .doOnRequest(t -> System.out.println("test request=" + t)) //
                .test(1);
        s.triggerActions();
        // health check doesn't get run on create
        ts.assertValueCount(1);
        assertEquals(0, disposed.get());
        assertEquals(0, healthChecks.get());
        // next request is immediate so health check does not run
        System.out.println("health check should not run because immediate");
        ts.request(1);
        s.triggerActions();
        ts.assertValueCount(2);
        assertEquals(0, disposed.get());
        assertEquals(0, healthChecks.get());

        // now try to trigger health check
        s.advanceTimeBy(1, TimeUnit.MILLISECONDS);
        s.triggerActions();
        System.out.println("trying to trigger health check");
        ts.request(1);
        s.triggerActions();
        ts.assertValueCount(2);
        assertEquals(1, disposed.get());
        assertEquals(1, healthChecks.get());

        // checkout retry should happen after interval
        s.advanceTimeBy(10, TimeUnit.MINUTES);
        ts.assertValueCount(3);

        // failing health check causes recreate to be scheduled
        ts.cancel();
        // already disposed so cancel has no effect
        assertEquals(1, disposed.get());
    }
}
 
Example 20
Source File: DebounceRailTest.java    From akarnokd-misc with Apache License 2.0 3 votes vote down vote up
@Test
public void test() {
    PublishSubject<String> subject = PublishSubject.create();
    
    TestScheduler sch = new TestScheduler();
    
    subject.compose(debounceOnly(v -> v.startsWith("A"), 100, TimeUnit.MILLISECONDS, sch))
    .subscribe(System.out::println, Throwable::printStackTrace, () -> System.out.println("Done"));
    
    subject.onNext("A1");
    
    sch.advanceTimeBy(100, TimeUnit.MILLISECONDS);
    
    subject.onNext("B1");
    sch.advanceTimeBy(1, TimeUnit.MILLISECONDS);

    subject.onNext("C1");
    sch.advanceTimeBy(1, TimeUnit.MILLISECONDS);

    subject.onNext("A2");
    sch.advanceTimeBy(50, TimeUnit.MILLISECONDS);

    subject.onNext("A3");
    sch.advanceTimeBy(100, TimeUnit.MILLISECONDS);

    subject.onNext("A4");
    sch.advanceTimeBy(50, TimeUnit.MILLISECONDS);

    subject.onNext("B2");
    sch.advanceTimeBy(100, TimeUnit.MILLISECONDS);

    subject.onNext("C2");
    sch.advanceTimeBy(100, TimeUnit.MILLISECONDS);
    
    subject.onComplete();
}