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

The following examples show how to use rx.observers.TestSubscriber#awaitTerminalEvent() . 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: UserRepositoryImplTest.java    From GithubUsersSearchApp with Apache License 2.0 6 votes vote down vote up
@Test
public void searchUsers_OtherHttpError_SearchTerminatedWithError() {
    //Given
    when(githubUserRestService.searchGithubUsers(anyString())).thenReturn(get403ForbiddenError());

    //When
    TestSubscriber<List<User>> subscriber = new TestSubscriber<>();
    userRepository.searchUsers(USER_LOGIN_RIGGAROO).subscribe(subscriber);

    //Then
    subscriber.awaitTerminalEvent();
    subscriber.assertError(HttpException.class);

    verify(githubUserRestService).searchGithubUsers(USER_LOGIN_RIGGAROO);

    verify(githubUserRestService, never()).getUser(USER_LOGIN_RIGGAROO);
    verify(githubUserRestService, never()).getUser(USER_LOGIN_2_REBECCA);
}
 
Example 2
Source File: CacheHelperTest.java    From aptoide-client-v8 with GNU General Public License v3.0 6 votes vote down vote up
@Test public void shouldReturnZeroBytesWhenCacheFoldersHasNoFilesEmpty() {
  List<CacheHelper.FolderToManage> folders = new LinkedList<>();
  CacheHelper.FolderToManage mockedFolder = mock(CacheHelper.FolderToManage.class);
  File mockedFile = mock(File.class);
  when(mockedFolder.getFolder()).thenReturn(mockedFile);
  folders.add(mockedFolder);
  FileUtils fileUtilsMock = mock(FileUtils.class);
  when(fileUtilsMock.dirSize(mockedFile)).thenReturn(0L);
  cacheHelper = new CacheHelper(0, folders, fileUtilsMock);

  TestSubscriber subscriber = TestSubscriber.create();
  cacheHelper.cleanCache()
      .subscribe(subscriber);
  subscriber.awaitTerminalEvent();
  subscriber.assertCompleted();
  subscriber.assertNoErrors();
  subscriber.assertValueCount(1);
  subscriber.assertValue(0L);
}
 
Example 3
Source File: ProblemTestCase.java    From akarnokd-misc with Apache License 2.0 6 votes vote down vote up
@Test
public void testB() {
    AtomicBoolean isRxJavaHooksSetOnErrorCalled = new AtomicBoolean(false);
    RxJavaHooks.setOnError(throwable -> {
        isRxJavaHooksSetOnErrorCalled.set(true);
    });
    TestSubscriber<Object> ts = new TestSubscriber<>();

    createProblematicObservable().subscribe(ts);

    ts.awaitTerminalEvent();

    // We assert that RxJavaHooks.onError was *not* called, because Observable.onErrorResumeNext
    // should have been called.
    Assert.assertFalse(isRxJavaHooksSetOnErrorCalled.get());

    ts.assertNoErrors();
    ts.assertValue("OK");
    ts.assertCompleted();
}
 
Example 4
Source File: AMQPObservableQueueTest.java    From conductor with Apache License 2.0 6 votes vote down vote up
void runObserve(Channel channel, AMQPObservableQueue observableQueue, String queueName, boolean useWorkingChannel,
		int batchSize) throws IOException {

	final List<Message> found = new ArrayList<>(batchSize);
	TestSubscriber<Message> subscriber = TestSubscriber.create(Subscribers.create(found::add));
	rx.Observable<Message> observable = observableQueue.observe().take(pollTimeMs * 2, TimeUnit.MILLISECONDS);
	assertNotNull(observable);
	observable.subscribe(subscriber);
	subscriber.awaitTerminalEvent();
	subscriber.assertNoErrors();
	subscriber.assertCompleted();
	if (useWorkingChannel) {
		verify(channel, atLeast(1)).basicConsume(eq(queueName), Mockito.anyBoolean(),(Consumer)Mockito.any(Consumer.class));
		Mockito.doNothing().when(channel).basicAck(Mockito.anyLong(), eq(false));
		Mockito.doAnswer(DoesNothing.doesNothing()).when(channel).basicAck(Mockito.anyLong(), eq(false));
		observableQueue.ack(Collections.synchronizedList(found));
	} else {
		assertNotNull(found);
		assertTrue(found.isEmpty());
	}
	observableQueue.close();
}
 
Example 5
Source File: GetCitiesUseCaseTest.java    From LittleFreshWeather with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetCitysUseCase() throws Exception {
    assertNotNull(mUseCase);
    TestSubscriber<List<CityEntity>> testSubscriber = TestSubscriber.create(new GetCitysUseCaseDelegate());
    mUseCase.execute(testSubscriber);
    testSubscriber.awaitTerminalEvent();
    //testSubscriber.assertError(Exception.class);
    testSubscriber.assertNoErrors();
}
 
Example 6
Source File: SimpleUploadDataStoreTest.java    From RxUploader with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetAllEmpty() throws Exception {
    final TestSubscriber<Job> ts = TestSubscriber.create();
    dataStore.getAll().subscribe(ts);

    ts.awaitTerminalEvent(1, TimeUnit.SECONDS);
    ts.assertNoErrors();
    ts.assertNoValues();
    ts.assertCompleted();
}
 
Example 7
Source File: ConsistencyReaderTest.java    From azure-cosmosdb-java with MIT License 5 votes vote down vote up
public static void validateSuccess(Single<StoreResponse> single,
                                   StoreResponseValidator validator,
                                   long timeout) {
    TestSubscriber<StoreResponse> testSubscriber = new TestSubscriber<>();

    single.toObservable().subscribe(testSubscriber);
    testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS);
    testSubscriber.assertNoErrors();
    testSubscriber.assertCompleted();
    testSubscriber.assertValueCount(1);
    validator.validate(testSubscriber.getOnNextEvents().get(0));
}
 
Example 8
Source File: ServicesManagerTest.java    From LittleFreshWeather with Apache License 2.0 5 votes vote down vote up
@Test
public void testServicesManagerGetCitys() throws Exception {
    assertNotNull(mServicesManger);
    TestSubscriber<List<CityEntity>> testSubscriber = TestSubscriber.create(new GetCitysDelegate());
    mServicesManger.getCityEntities().subscribe(testSubscriber);
    testSubscriber.awaitTerminalEvent();
    testSubscriber.assertNoErrors();

    /*final Logger logger = Logger.getLogger("testServicesManagerGetCitys");
    assertNotNull(mServicesManger);
    mServicesManger.getCitys()
            .subscribe(new Subscriber<List<CityEntity>>() {
                @Override
                public void onCompleted() {
                    logger.info("onCompleted");
                }

                @Override
                public void onError(Throwable e) {
                    logger.info("onError");
                }

                @Override
                public void onNext(List<CityEntity> cityEntities) {
                    logger.info("onNext");
                    mCitys = cityEntities;
                    for (CityEntity city :
                            cityEntities) {
                        logger.info(city.toString());
                    }
                }
            });
    assertNotNull(mCitys);
    assertFalse(mCitys.isEmpty());*/
}
 
Example 9
Source File: UploadInteractorImplTest.java    From RxUploader with Apache License 2.0 5 votes vote down vote up
@Test
public void testUploadError() throws Exception {
    final String jobId = "job-id";
    final File file = getFile(TEST_FILE);
    final Job job = Job.builder()
            .setId(jobId)
            .setFilepath(file.getPath())
            .setMetadata(Collections.emptyMap())
            .setMimeType("text/plain")
            .setStatus(Status.createQueued(jobId))
            .build();

    when(dataStore.get(jobId)).thenReturn(Observable.just(job));

    final Status[] statuses = new Status[] {
            Status.createSending(jobId, 0), Status.createSending(jobId, 10),
            Status.createSending(jobId, 20), Status.createSending(jobId, 30),
    };

    when(uploader.upload(eq(job), any(File.class))).thenReturn(
            Observable.from(statuses).concatWith(Observable.error(new IOException("error"))));

    final TestSubscriber<Status> ts = TestSubscriber.create();
    uploadInteractor.upload(jobId).subscribe(ts);

    testScheduler.triggerActions();

    ts.awaitTerminalEvent(1, TimeUnit.SECONDS);

    ts.assertValues(statuses);
    ts.assertError(IOException.class);
}
 
Example 10
Source File: RxGcmTest.java    From RxGcm with Apache License 2.0 5 votes vote down vote up
@Test public void When_Call_Current_Token_And_There_Is_A_Token_Emit_It() {
    when(persistenceMock.getToken(applicationMock)).thenReturn(MOCK_TOKEN);

    TestSubscriber<String> subscriberMock = new TestSubscriber<>();
    RxGcm.Notifications.currentToken().subscribe(subscriberMock);
    subscriberMock.awaitTerminalEvent();

    subscriberMock.assertValue(MOCK_TOKEN);
    subscriberMock.assertNoErrors();
}
 
Example 11
Source File: GatewayAddressCacheTest.java    From azure-cosmosdb-java with MIT License 5 votes vote down vote up
public static<T> T getSuccessResult(Single<T> observable, long timeout) {
    TestSubscriber<T> testSubscriber = new TestSubscriber<>();
    observable.subscribe(testSubscriber);
    testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS);
    testSubscriber.assertNoErrors();
    testSubscriber.assertCompleted();
    testSubscriber.assertValueCount(1);
    return testSubscriber.getOnNextEvents().get(0);
}
 
Example 12
Source File: BaseITest.java    From hawkular-metrics with Apache License 2.0 5 votes vote down vote up
/**
 * This method takes a function that produces an Observable. The method blocks up to
 * five seconds until the Observable emits a terminal event. The items that the
 * Observable emits are then returned.
 *
 * @param fn A function that produces an Observable
 * @param <T> The type of items emitted by the Observable
 * @return A list of the items emitted by the Observable
 */
protected <T> List<T> getOnNextEvents(Supplier<Observable<T>> fn) {
    TestSubscriber<T> subscriber = new TestSubscriber<>();
    Observable<T> observable = fn.get();
    observable.doOnError(Throwable::printStackTrace)
            .subscribe(subscriber);
    subscriber.awaitTerminalEvent(5, SECONDS);
    subscriber.assertNoErrors();
    subscriber.assertCompleted();

    return subscriber.getOnNextEvents();
}
 
Example 13
Source File: AwsLoadBalancerConnectorTest.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
@Ignore("AWS dependencies")
@Test
public void validateIpTargetGroupTest() {
    TestSubscriber testSubscriber = new TestSubscriber();
    awsLoadBalancerConnector.isValid(validIpTargetGroup).subscribe(testSubscriber);

    testSubscriber.awaitTerminalEvent();
    testSubscriber.assertCompleted();
    testSubscriber.assertNoErrors();
}
 
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 cleanCacheAndInvalidateDatabase() {
  FileManager fileManager =
      new FileManager(cacheHelper, fileUtils, folders, downloadManager, mock(L2Cache.class));

  TestSubscriber<Long> subscriber = TestSubscriber.create();
  fileManager.purgeCache()
      .subscribe(subscriber);
  subscriber.awaitTerminalEvent();
  assertSubscriber(subscriber, 10L);
  verify(cacheHelper, times(1)).cleanCache();
  verify(downloadManager, times(1)).invalidateDatabase();
}
 
Example 15
Source File: ProblemTestCase.java    From akarnokd-misc with Apache License 2.0 5 votes vote down vote up
@Test
public void testA() {
    TestSubscriber<Object> ts = new TestSubscriber<>();

    createProblematicObservable().subscribe(ts);

    ts.awaitTerminalEvent();

    ts.assertNoErrors();
    ts.assertValue("OK");
    ts.assertCompleted();
}
 
Example 16
Source File: CacheHelperTest.java    From aptoide-client-v8 with GNU General Public License v3.0 5 votes vote down vote up
@Test public void shouldReturnZeroBytesWhenCacheFoldersEmpty() {
  List<CacheHelper.FolderToManage> folders = new LinkedList<>();
  FileUtils fileUtilsMock = mock(FileUtils.class);
  cacheHelper = new CacheHelper(0, folders, fileUtilsMock);

  TestSubscriber subscriber = TestSubscriber.create();
  cacheHelper.cleanCache()
      .subscribe(subscriber);
  subscriber.awaitTerminalEvent();
  subscriber.assertCompleted();
  subscriber.assertNoErrors();
  subscriber.assertValueCount(1);
  subscriber.assertValue(0L);
}
 
Example 17
Source File: ObservablesTest.java    From couchbase-jvm-core with Apache License 2.0 5 votes vote down vote up
/**
 * Heper method to test fail-safe functionality.
 *
 * @param scheduler the scheduler to test against. if null, it will be failed on the current thread.
 * @param threadName the part of a thread name to match against for additional verification.
 */
private static void testFailSafe(final Scheduler scheduler, final String threadName) {
    Subject<CouchbaseResponse, CouchbaseResponse> subject = AsyncSubject.create();
    TestSubscriber<CouchbaseResponse> subscriber = TestSubscriber.create();
    subject.subscribe(subscriber);
    Exception failure = new CouchbaseException("Some Error");

    Observables.failSafe(scheduler, scheduler != null, subject, failure);

    subscriber.awaitTerminalEvent();
    subscriber.assertError(failure);
    assertTrue(subscriber.getLastSeenThread().getName().contains(threadName));
}
 
Example 18
Source File: ConfigurationServiceTest.java    From hawkular-metrics with Apache License 2.0 5 votes vote down vote up
/**
 * This method take a function that produces an Observable that has side effects, like
 * inserting rows into the database. A {@link TestSubscriber} is subscribed to the
 * Observable. The subscriber blocks up to five seconds waiting for a terminal event
 * from the Observable.
 *
 * @param fn A function that produces an Observable with side effects
 */
protected void doAction(Supplier<Observable<Void>> fn) {
    TestSubscriber<Void> subscriber = new TestSubscriber<>();
    Observable<Void> observable = fn.get();
    observable.subscribe(subscriber);
    subscriber.awaitTerminalEvent(5, TimeUnit.SECONDS);
    subscriber.assertNoErrors();
    subscriber.assertCompleted();
}
 
Example 19
Source File: OrderbyDocumentQueryTest.java    From azure-cosmosdb-java with MIT License 4 votes vote down vote up
@Test(groups = { "simple" }, timeOut = TIMEOUT)
public void queryScopedToSinglePartition_StartWithContinuationToken() throws Exception {
    String query = "SELECT * FROM r ORDER BY r.propScopedPartitionInt ASC";
    FeedOptions options = new FeedOptions();
    options.setPartitionKey(new PartitionKey("duplicateParitionKeyValue"));
    options.setMaxItemCount(3);
    Observable<FeedResponse<Document>> queryObservable = client
        .queryDocuments(getCollectionLink(), query, options);


    TestSubscriber<FeedResponse<Document>> subscriber = new TestSubscriber<>();
    queryObservable.first().subscribe(subscriber);

    subscriber.awaitTerminalEvent();
    subscriber.assertCompleted();
    subscriber.assertNoErrors();
    assertThat(subscriber.getValueCount()).isEqualTo(1);
    FeedResponse<Document> page = subscriber.getOnNextEvents().get(0);
    assertThat(page.getResults()).hasSize(3);

    assertThat(page.getResponseContinuation()).isNotEmpty();


    options.setRequestContinuation(page.getResponseContinuation());
    queryObservable = client
        .queryDocuments(getCollectionLink(), query, options);


    List<Document> expectedDocs = createdDocuments.stream()
        .filter(d -> (StringUtils.equals("duplicateParitionKeyValue", d.getString("mypk"))))
        .filter(d -> (d.getInt("propScopedPartitionInt") > 2)).collect(Collectors.toList());
    int expectedPageSize = (expectedDocs.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount();

    assertThat(expectedDocs).hasSize(10 - 3);

    FeedResponseListValidator<Document> validator = null;

    validator = new FeedResponseListValidator.Builder<Document>()
        .containsExactly(expectedDocs.stream()
            .sorted((e1, e2) -> Integer.compare(e1.getInt("propScopedPartitionInt"), e2.getInt("propScopedPartitionInt")))
            .map(d -> d.getResourceId()).collect(Collectors.toList()))
        .numberOfPages(expectedPageSize)
        .allPagesSatisfy(new FeedResponseValidator.Builder<Document>()
            .requestChargeGreaterThanOrEqualTo(1.0).build())
        .build();
    
    validateQuerySuccess(queryObservable, validator);
}
 
Example 20
Source File: SinglePartitionDocumentQueryTest.java    From azure-cosmosdb-java with MIT License 4 votes vote down vote up
@Test(groups = { "simple" }, timeOut = TIMEOUT * 1000)
public void continuationToken() throws Exception {
    String query = "SELECT * FROM r ORDER BY r.prop ASC";
    FeedOptions options = new FeedOptions();
    options.setEnableCrossPartitionQuery(true);
    options.setMaxItemCount(3);
    Observable<FeedResponse<Document>> queryObservable = client
            .queryDocuments(getCollectionLink(), query, options);

    
    TestSubscriber<FeedResponse<Document>> subscriber = new TestSubscriber<>();
    queryObservable.first().subscribe(subscriber);
    
    subscriber.awaitTerminalEvent();
    subscriber.assertCompleted();
    subscriber.assertNoErrors();
    assertThat(subscriber.getValueCount()).isEqualTo(1);
    FeedResponse<Document> page = subscriber.getOnNextEvents().get(0);
    assertThat(page.getResults()).hasSize(3);
    
    assertThat(page.getResponseContinuation()).isNotEmpty();
    
    
    options.setRequestContinuation(page.getResponseContinuation());
    queryObservable = client
            .queryDocuments(getCollectionLink(), query, options);
    

    List<Document> expectedDocs = createdDocuments.stream().filter(d -> (d.getInt("prop") > 2)).collect(Collectors.toList());
    int expectedPageSize = (expectedDocs.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount();

    assertThat(expectedDocs).hasSize(createdDocuments.size() -3);
    
    FeedResponseListValidator<Document> validator = new FeedResponseListValidator.Builder<Document>()
            .containsExactly(expectedDocs.stream()
                    .sorted((e1, e2) -> Integer.compare(e1.getInt("prop"), e2.getInt("prop")))
                    .map(d -> d.getResourceId()).collect(Collectors.toList()))
            .numberOfPages(expectedPageSize)
            .allPagesSatisfy(new FeedResponseValidator.Builder<Document>()
                    .requestChargeGreaterThanOrEqualTo(1.0).build())
            .build();
    validateQuerySuccess(queryObservable, validator);
}