Java Code Examples for rx.observers.TestSubscriber#create()

The following examples show how to use rx.observers.TestSubscriber#create() . 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: TransformerLimitSubscribersTest.java    From rxjava-extras with Apache License 2.0 6 votes vote down vote up
@Test
public void testThreeSubscribersNotOk() {
    TestSubscriber<Long> ts1 = TestSubscriber.create();
    TestSubscriber<Long> ts2 = TestSubscriber.create();
    TestSubscriber<Long> ts3 = TestSubscriber.create();
    Observable<Long> o = Observable.interval(100, TimeUnit.MILLISECONDS).take(3)
            .compose(Transformers.<Long> limitSubscribers(2))
            .onErrorResumeNext(Observable.<Long> empty());
    o.subscribe(ts1);
    o.subscribe(ts2);
    o.subscribe(ts3);
    ts1.awaitTerminalEvent(3, TimeUnit.SECONDS);
    ts2.awaitTerminalEvent(3, TimeUnit.SECONDS);
    ts3.awaitTerminalEvent(3, TimeUnit.SECONDS);
    ts3.assertNoValues();
    ts3.assertCompleted();
}
 
Example 2
Source File: OperatorBufferPredicateBoundaryTest.java    From rxjava-extras with Apache License 2.0 6 votes vote down vote up
@Test
public void bufferUntilBackpressureFullBuffer() {
    TestSubscriber<List<Integer>> ts = TestSubscriber.create(0);
    
    int count = RxRingBuffer.SIZE * 4;
    
    Observable.range(1, count)
    .compose(Transformers.bufferUntil(UtilityFunctions.<Integer>alwaysFalse()))
    .subscribe(ts);
    
    ts.assertNoValues();
    ts.assertNoErrors();
    ts.assertNotCompleted();
    
    ts.requestMore(1);
    
    ts.assertValueCount(1);
    ts.assertNoErrors();
    ts.assertCompleted();
    
    Assert.assertEquals(count, ts.getOnNextEvents().get(0).size());
}
 
Example 3
Source File: RxMathematicalOperatorsUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenRangeNumericObservable_whenCalculatingMin_ThenSuccessfullObtainingMinValue() {
    // given
    Observable<Integer> sourceObservable = Observable.range(1, 20);
    TestSubscriber<Integer> subscriber = TestSubscriber.create();

    // when
    MathObservable.min(sourceObservable)
        .subscribe(subscriber);

    // then
    subscriber.assertCompleted();
    subscriber.assertNoErrors();
    subscriber.assertValueCount(1);
    subscriber.assertValue(1);
}
 
Example 4
Source File: RetryWhenTest.java    From rxjava-extras with Apache License 2.0 6 votes vote down vote up
@Test
public void testRetryWhenSpecificExceptionAllowedUsePredicateReturnsFalse() {
    Exception ex = new IllegalArgumentException("boo");
    TestSubscriber<Integer> ts = TestSubscriber.create();
    TestScheduler scheduler = new TestScheduler();
    Func1<Throwable, Boolean> predicate = Functions.alwaysFalse();
    Observable.just(1, 2)
            // force error after 3 emissions
            .concatWith(Observable.<Integer> error(ex))
            // retry with backoff
            .retryWhen(
                    RetryWhen.maxRetries(2).action(log).exponentialBackoff(1, TimeUnit.MINUTES)
                            .scheduler(scheduler).retryIf(predicate).build())
            // go
            .subscribe(ts);
    ts.assertValues(1, 2);
    ts.assertError(ex);
}
 
Example 5
Source File: RxStringOperatorsUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenStringObservable_whenConcatenatingStrings_ThenSuccessfullObtainingSingleString()
{
    //given
    Observable<String> sourceObservable = Observable.just("Lorem ipsum loream","Lorem ipsum lore");
    TestSubscriber<String> subscriber = TestSubscriber.create();

    // when
    StringObservable.stringConcat(sourceObservable)
        .subscribe(subscriber);

    // then
    subscriber.assertCompleted();
    subscriber.assertNoErrors();
    subscriber.assertValueCount(1);
    subscriber.assertValues("Lorem ipsum loreamLorem ipsum lore");
}
 
Example 6
Source File: RxPaperBookTest.java    From RxPaper with MIT License 6 votes vote down vote up
@Test
public void testExists() throws Exception {
    RxPaperBook book = RxPaperBook.with("EXISTS", Schedulers.immediate());
    final String key = "hello";
    book.write(key, ComplexObject.random()).subscribe();
    final TestSubscriber<Boolean> foundSubscriber = TestSubscriber.create();
    book.exists(key).subscribe(foundSubscriber);
    foundSubscriber.awaitTerminalEvent();
    foundSubscriber.assertNoErrors();
    foundSubscriber.assertValueCount(1);
    foundSubscriber.assertValues(true);
    // notFoundSubscriber
    final TestSubscriber<Boolean> notFoundSubscriber = TestSubscriber.create();
    String noKey = ":(";
    book.exists(noKey).subscribe(notFoundSubscriber);
    notFoundSubscriber.awaitTerminalEvent();
    notFoundSubscriber.assertCompleted();
    notFoundSubscriber.assertValueCount(1);
    notFoundSubscriber.assertValues(false);
}
 
Example 7
Source File: RxAggregateOperatorsUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenTwoObservable_whenConcatenatingThem_thenSuccessfull() {
    // given
    List<Integer> listOne = Arrays.asList(1, 2, 3, 4);
    Observable<Integer> observableOne = Observable.from(listOne);

    List<Integer> listTwo = Arrays.asList(5, 6, 7, 8);
    Observable<Integer> observableTwo = Observable.from(listTwo);

    TestSubscriber<Integer> subscriber = TestSubscriber.create();

    // when
    Observable<Integer> concatObservable = observableOne.concatWith(observableTwo);

    concatObservable.subscribe(subscriber);

    // then
    subscriber.assertCompleted();
    subscriber.assertNoErrors();
    subscriber.assertValueCount(8);
    subscriber.assertValues(1, 2, 3, 4, 5, 6, 7, 8);
}
 
Example 8
Source File: StringSplitWithLimitTest.java    From rxjava-extras with Apache License 2.0 5 votes vote down vote up
@Test
public void testBackpressureOneByOneWithBufferEmissions() {
    Observable<String> o = Observable.just("boo:an", "d:you").compose(Transformers.split(":"));

    TestSubscriber<String> ts = TestSubscriber.create(0);
    o.subscribe(ts);
    ts.requestMore(1);
    ts.assertValues("boo");
    ts.requestMore(1);
    ts.assertValues("boo", "and");
    ts.requestMore(1);
    ts.assertValues("boo", "and", "you");
}
 
Example 9
Source File: ViewHandlerTest.java    From couchbase-jvm-core with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldHavePipeliningDisabled() {
    Subject<CouchbaseResponse,CouchbaseResponse> obs1 = AsyncSubject.create();
    ViewQueryRequest requestMock1 = mock(ViewQueryRequest.class);
    when(requestMock1.query()).thenReturn("{...}");
    when(requestMock1.bucket()).thenReturn("foo");
    when(requestMock1.username()).thenReturn("foo");
    when(requestMock1.password()).thenReturn("");
    when(requestMock1.observable()).thenReturn(obs1);
    when(requestMock1.isActive()).thenReturn(true);

    Subject<CouchbaseResponse,CouchbaseResponse> obs2 = AsyncSubject.create();
    ViewQueryRequest requestMock2 = mock(ViewQueryRequest.class);
    when(requestMock2.query()).thenReturn("{...}");
    when(requestMock2.bucket()).thenReturn("foo");
    when(requestMock2.username()).thenReturn("foo");
    when(requestMock2.password()).thenReturn("");
    when(requestMock2.observable()).thenReturn(obs2);
    when(requestMock2.isActive()).thenReturn(true);


    TestSubscriber<CouchbaseResponse> t1 = TestSubscriber.create();
    TestSubscriber<CouchbaseResponse> t2 = TestSubscriber.create();

    obs1.subscribe(t1);
    obs2.subscribe(t2);

    channel.writeOutbound(requestMock1, requestMock2);

    t1.assertNotCompleted();
    t2.assertError(RequestCancelledException.class);
}
 
Example 10
Source File: FileManagerTest.java    From aptoide-client-v8 with GNU General Public License v3.0 5 votes vote down vote up
@Test public void deleteCacheSizeGreaterZero() throws IOException {
  FileUtils fileUtils = mock(FileUtils.class);
  when(fileUtils.deleteFolder(folders[0])).thenReturn(Observable.just(10L));
  FileManager fileManager =
      new FileManager(cacheHelper, fileUtils, folders, downloadManager, mock(L2Cache.class));

  TestSubscriber<Long> subscriber = TestSubscriber.create();
  fileManager.deleteCache()
      .subscribe(subscriber);
  assertSubscriber(subscriber, 10L);
  verify(downloadManager, times(1)).invalidateDatabase();
}
 
Example 11
Source File: OrderedMergeTest.java    From rxjava-extras with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testErrorInMiddle() {
	Observable<Integer> o1 = Observable.just(1, 3, 5, 7);
	Observable<Integer> o2 = Observable.just(2).concatWith(Observable.<Integer> error(new TestException()));

	TestSubscriber<Integer> ts = TestSubscriber.create();
	OrderedMerge.create(Arrays.asList(o1, o2)).subscribe(ts);

	ts.assertError(TestException.class);
	ts.assertNotCompleted();
	ts.assertValues(1, 2);
}
 
Example 12
Source File: RxOkukiTest.java    From okuki with Apache License 2.0 5 votes vote down vote up
@Test
public void testBranchSubscription() throws Exception {
    TestSubscriber<Place> testObserver = TestSubscriber.create();
    RxOkuki.onBranch(okuki, TestPlace.class).subscribe(testObserver);
    verify(okuki).addBranchListener(isA(BranchListener.class));
    testObserver.unsubscribe();
    verify(okuki).removeBranchListener(isA(BranchListener.class));
}
 
Example 13
Source File: OperatorBufferToFileTest.java    From rxjava-extras with Apache License 2.0 5 votes vote down vote up
@Test
public void handlesUnsubscriptionDuringDrainLoop() throws InterruptedException {
    System.out.println("handlesUnsubscriptionDuringDrainLoop");
    Scheduler scheduler = createSingleThreadScheduler();
    TestSubscriber<String> ts = TestSubscriber.create(0);
    Observable.just("abc", "def", "ghi")
            //
            .compose(Transformers.onBackpressureBufferToFile(DataSerializers.string(),
                    scheduler))
            .doOnNext(new Action1<Object>() {

                @Override
                public void call(Object t) {
                    try {
                        // pauses drain loop
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                    }
                }
            }).subscribe(ts);
    ts.requestMore(2);
    TimeUnit.MILLISECONDS.sleep(250);
    ts.unsubscribe();
    TimeUnit.MILLISECONDS.sleep(500);
    ts.assertValues("abc");
    waitUntilWorkCompleted(scheduler);
}
 
Example 14
Source File: FileManagerTest.java    From aptoide-client-v8 with GNU General Public License v3.0 5 votes vote down vote up
@Test public void deleteCacheSizeEqualsZero() throws IOException {
  FileUtils fileUtils = mock(FileUtils.class);
  when(fileUtils.deleteFolder(folders[0])).thenReturn(Observable.just(0L));
  FileManager fileManager =
      new FileManager(cacheHelper, fileUtils, folders, downloadManager, mock(L2Cache.class));

  TestSubscriber<Long> subscriber = TestSubscriber.create();
  fileManager.deleteCache()
      .subscribe(subscriber);
  assertSubscriber(subscriber, 0L);
  verify(downloadManager, times(0)).invalidateDatabase();
}
 
Example 15
Source File: KeyValueHandlerTest.java    From couchbase-jvm-core with Apache License 2.0 5 votes vote down vote up
@Test
public void testUnSubscribedRequest() {
    String id = "key";
    GetRequest request = new GetRequest(id, BUCKET);

    TestSubscriber<CouchbaseResponse> ts = TestSubscriber.create();
    request.subscriber(ts);

    ts.unsubscribe();
    assertTrue(!request.isActive());
}
 
Example 16
Source File: NotificationsCleanerTest.java    From aptoide-client-v8 with GNU General Public License v3.0 5 votes vote down vote up
@Test public void cleanOtherUsersNotifications() throws Exception {
  Map<String, RoomNotification> list = new HashMap<>();
  Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
  long timeStamp = calendar.getTimeInMillis();
  RoomNotification notification = createNotification(timeStamp + 1000, timeStamp, "me", true);
  list.put(notification.getKey(), notification);
  timeStamp = System.currentTimeMillis();
  notification = createNotification(timeStamp + 1000, timeStamp - 1, "me", true);
  list.put(notification.getKey(), notification);
  timeStamp = System.currentTimeMillis();
  notification = createNotification(timeStamp + 2000, timeStamp - 2, "me", true);
  list.put(notification.getKey(), notification);
  RoomNotificationPersistence roomNotificationPersistence = new NotPersistenceRoom(list);

  NotificationsCleaner notificationsCleaner =
      new NotificationsCleaner(roomNotificationPersistence,
          Calendar.getInstance(TimeZone.getTimeZone("UTC")), getAptoideAccountManager(),
          getNotificationProvider(), CrashReport.getInstance());

  TestSubscriber<Object> objectTestSubscriber = TestSubscriber.create();
  notificationsCleaner.cleanOtherUsersNotifications("you")
      .subscribe(objectTestSubscriber);
  objectTestSubscriber.awaitTerminalEvent();
  objectTestSubscriber.assertCompleted();
  objectTestSubscriber.assertNoErrors();
  assertEquals(roomNotificationPersistence.getAllSortedDesc()
      .toBlocking()
      .first()
      .size(), 0);
}
 
Example 17
Source File: NotificationsCleanerTest.java    From aptoide-client-v8 with GNU General Public License v3.0 5 votes vote down vote up
@Test public void cleanLimitExceededNotificationsExceedingLimit() throws Exception {
  TestSubscriber<Object> objectTestSubscriber = TestSubscriber.create();

  Map<String, RoomNotification> list = new HashMap<>();
  long timeStamp = System.currentTimeMillis();
  RoomNotification notification = createNotification(timeStamp + 2000, timeStamp, "me", true);
  list.put(notification.getKey(), notification);
  timeStamp = System.currentTimeMillis();
  notification = createNotification(timeStamp + 2000, timeStamp - 1, "me", true);
  list.put(notification.getKey(), notification);
  timeStamp = System.currentTimeMillis();
  notification = createNotification(timeStamp + 2000, timeStamp - 2, "me", true);
  list.put(notification.getKey(), notification);
  RoomNotificationPersistence roomNotificationPersistence = new NotPersistenceRoom(list);
  NotificationsCleaner notificationsCleaner =
      new NotificationsCleaner(roomNotificationPersistence,
          Calendar.getInstance(TimeZone.getTimeZone("UTC")), getAptoideAccountManager(),
          getNotificationProvider(), CrashReport.getInstance());

  List<RoomNotification> notificationList = roomNotificationPersistence.getAllSortedDesc()
      .toBlocking()
      .first();
  notificationsCleaner.cleanLimitExceededNotifications(1)
      .subscribe(objectTestSubscriber);
  objectTestSubscriber.awaitTerminalEvent();
  objectTestSubscriber.assertCompleted();
  objectTestSubscriber.assertNoErrors();
  assertEquals(roomNotificationPersistence.getAllSortedDesc()
      .toBlocking()
      .first()
      .size(), 1);
  assertEquals(roomNotificationPersistence.getAllSortedDesc()
      .toBlocking()
      .first()
      .get(0)
      .getKey(), notificationList.get(0)
      .getKey());
}
 
Example 18
Source File: DbMigrationTest.java    From aptoide-client-v8 with GNU General Public License v3.0 4 votes vote down vote up
@Test public void scheduledDownloads() {
  // prepare
  final Table scheduleTable = tableBag.get(TableBag.TableName.SCHEDULED);
  final int nr_values = 5;
  final ContentValues[] insertedValues = new ContentValues[nr_values];
  final String[] md5s = new String[nr_values];
  final ScheduledAccessor accessor = AccessorFactory.getAccessorFor(
      ((V8Engine) InstrumentationRegistry.getTargetContext()
          .getApplicationContext()).getDatabase(), Scheduled.class);

  db.beginTransaction();
  try {

    for (int i = 0; i < insertedValues.length; i++) {
      insertedValues[i] = new ContentValues();

      putValues(scheduleTable, insertedValues, i);

      md5s[i] = ScheduledTable.md5.getName() + i;

      db.insertOrThrow(scheduleTable.getName(), null, insertedValues[i]);
    }

    db.setTransactionSuccessful();
  } catch (Exception e) {
    e.printStackTrace();
  } finally {
    db.endTransaction();
  }

  // trigger migration
  ManagerPreferences.setNeedsSqliteDbMigration(true,
      ((V8Engine) InstrumentationRegistry.getTargetContext()).getDefaultSharedPreferences());
  int newVersion = dbVersion.incrementAndGet();
  dbHelper.onUpgrade(db, newVersion - 1, newVersion);

  // main thread ID for asserting purposes
  final long mainThreadId = Looper.getMainLooper()
      .getThread()
      .getId();

  // evaluate
  for (int i = 0; i < nr_values; i++) {
    final int finalI = i;
    String currentMd5 = md5s[finalI];

    TestSubscriber<Scheduled> testSubscriber = TestSubscriber.create();
    accessor.get(currentMd5)
        .first()
        .subscribe(testSubscriber);
    testSubscriber.awaitTerminalEvent();
    testSubscriber.assertCompleted();
    Scheduled scheduled = testSubscriber.getOnNextEvents()
        .get(0);

    if (scheduled == null) {
      fail("Scheduled download is null");
      return;
    }

    assertNotEquals(mainThreadId, Thread.currentThread()
        .getId());

    // assert data fields
    assertEquals(scheduled.getName(), insertedValues[finalI].get(ScheduledTable.name.getName()));

    assertEquals(scheduled.getMd5(), insertedValues[finalI].get(ScheduledTable.md5.getName()));

    assertEquals(scheduled.getIcon(), insertedValues[finalI].get(ScheduledTable.icon.getName()));
  }
}
 
Example 19
Source File: OperatorBufferToFileTest.java    From rxjava-extras with Apache License 2.0 4 votes vote down vote up
@Test
public void testWithMultiSecondRangeAndCheckMemoryUsage() throws InterruptedException {
    Scheduler scheduler = createSingleThreadScheduler();
    final long startMem = displayMemory();
    TestSubscriber<Integer> ts = TestSubscriber.create();
    int maxSeconds = getMaxSeconds();
    Observable.range(1, Integer.MAX_VALUE)
            //
            .compose(onBackpressureBufferToFile(DataSerializers.integer(), scheduler,
                    Options.rolloverSizeMB(1).build()))
            .doOnNext(new Action1<Integer>() {
                int count = 0;

                @Override
                public void call(Integer t) {
                    count++;
                    if (t != count) {
                        throw new AssertionError(t + " != " + count);
                    }
                }
            }).sample(maxSeconds, TimeUnit.SECONDS).doOnNext(new Action1<Integer>() {
                @Override
                public void call(Integer n) {
                    try {
                        System.out.println("final value " + n);
                        long finishMem = displayMemory();
                        // normally 2MB used so we'll be conservative with
                        // this check
                        if (finishMem - startMem > 20 * (1 << 20))
                            System.out.println("memory used higher than expected");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).first().subscribe(ts);
    ts.awaitTerminalEvent();
    ts.assertNoErrors();
    ts.assertCompleted();
    displayMemory();
    waitUntilWorkCompleted(scheduler);
}
 
Example 20
Source File: TransformerOnTerminateResumeTest.java    From rxjava-extras with Apache License 2.0 3 votes vote down vote up
@Test
public void mainErrorsBackpressure() {
    
    Transformer<Integer, Integer> op = new TransformerOnTerminateResume<Integer>(new Func1<Throwable, Observable<Integer>>() {
        @Override
        public Observable<Integer> call(Throwable e) {
            return Observable.just(11);
        }
    }, Observable.just(12));
    
    TestSubscriber<Integer> ts = TestSubscriber.create(0);
    
    Observable.range(1, 10).concatWith(Observable.<Integer>error(new IOException()))
    .compose(op)
    .subscribe(ts);
    
    ts.assertNoValues();
    
    ts.requestMore(2);

    ts.assertValues(1, 2);

    ts.requestMore(5);

    ts.assertValues(1, 2, 3, 4, 5, 6, 7);

    ts.requestMore(3);

    ts.assertValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

    ts.requestMore(1);

    ts.assertValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
    ts.assertNoErrors();
    ts.assertCompleted();
}