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

The following examples show how to use rx.observers.TestSubscriber#assertError() . 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: 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 2
Source File: RxFirebaseAuthTests.java    From RxFirebase with Apache License 2.0 6 votes vote down vote up
@Test
public void signInWithEmailAndPassword_AuthError()  {

    TestSubscriber<AuthResult> testSubscriber = new TestSubscriber<>();
    RxFirebaseAuth.signInWithEmailAndPassword(mockAuth, "email", "password")
            .subscribeOn(Schedulers.immediate())
            .subscribe(testSubscriber);

    Exception e = new Exception("something bad happened");
    testOnFailureListener.getValue().onFailure(e);

    verify(mockAuth).signInWithEmailAndPassword(eq("email"), eq("password"));

    testSubscriber.assertError(e);
    testSubscriber.assertNotCompleted();
    testSubscriber.unsubscribe();
}
 
Example 3
Source File: OperatorBufferPredicateBoundaryTest.java    From rxjava-extras with Apache License 2.0 6 votes vote down vote up
@Test
public void bufferUntilPredicateThrows() {
    TestSubscriber<List<Integer>> ts = new TestSubscriber<List<Integer>>();
    
    Observable.just(1, 2, 3, null, 4, 5)
    .compose(Transformers.bufferUntil(new Func1<Integer, Boolean>() {
        @Override
        public Boolean call(Integer v) {
            return v == 20;
        }
    }))
    .subscribe(ts);
    
    ts.assertNoValues();
    ts.assertError(NullPointerException.class);
    ts.assertNotCompleted();
}
 
Example 4
Source File: RxGcmTest.java    From RxGcm with Apache License 2.0 6 votes vote down vote up
@Test public void When_No_Saved_Token_And_Call_GcmServer_Error_Emit_Error_But_Try_3_Times() throws Exception {
    String errorMessage = "GCM not available";

    when(getGcmServerTokenMock.retrieve(applicationMock)).thenThrow(new RuntimeException(errorMessage));
    when(persistenceMock.getToken(applicationMock)).thenReturn(null);

    TestSubscriber<String> subscriberMock = new TestSubscriber<>();
    RxGcm.Notifications
            .register(applicationMock, GcmReceiverDataMock.class, GcmReceiverMockUIBackground.class)
            .subscribe(subscriberMock);
    subscriberMock.awaitTerminalEvent();

    subscriberMock.assertError(RuntimeException.class);
    verify(persistenceMock, times(0)).saveToken(MOCK_TOKEN, applicationMock);
    verify(getGcmServerTokenMock, times(3)).retrieve(applicationMock);
}
 
Example 5
Source File: RxJavaUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenTestObserver_whenExceptionWasThrowsOnObservable_observerShouldGetError() {
    // given
    List<String> letters = Arrays.asList("A", "B", "C", "D", "E");
    TestSubscriber<String> subscriber = new TestSubscriber<>();

    Observable<String> observable = Observable.from(letters)
      .zipWith(Observable.range(1, Integer.MAX_VALUE), ((string, index) -> index + "-" + string))
      .concatWith(Observable.error(new RuntimeException("error in Observable")));

    // when
    observable.subscribe(subscriber);

    // then
    subscriber.assertError(RuntimeException.class);
    subscriber.assertNotCompleted();
}
 
Example 6
Source File: OperatorBufferPredicateBoundaryTest.java    From rxjava-extras with Apache License 2.0 5 votes vote down vote up
@Test
public void errorSourceBufferUntil() {
    TestSubscriber<List<Integer>> ts = new TestSubscriber<List<Integer>>();

    Observable.<Integer>error(new IOException())
    .compose(Transformers.bufferUntil(UtilityFunctions.<Integer>alwaysTrue()))
    .subscribe(ts);
    
    ts.assertNoValues();
    ts.assertError(IOException.class);
    ts.assertNotCompleted();
}
 
Example 7
Source File: AptoideCredentialsValidatorTest.java    From aptoide-client-v8 with GNU General Public License v3.0 5 votes vote down vote up
@Test public void shouldNotValidateEmptyEmail() throws Exception {

    CredentialsValidator validator = new CredentialsValidator();

    final TestSubscriber testSubscriber = TestSubscriber.create();

    validator.validate(new AptoideCredentials("", "1aMarcelo", true, "", ""))
        .subscribe(testSubscriber);

    testSubscriber.assertError(AccountValidationException.class);
    assertEquals(1, ((AccountValidationException) testSubscriber.getOnErrorEvents()
        .get(0)).getCode());
    testSubscriber.assertNotCompleted();
  }
 
Example 8
Source File: OperatorWindowMinMaxTest.java    From rxjava-extras with Apache License 2.0 5 votes vote down vote up
@Test
public void testErrorPropagated() {
    TestSubscriber<Integer> ts = TestSubscriber.create();
    RuntimeException r = new RuntimeException();
    Observable.<Integer> error(r).compose(Transformers.<Integer> windowMax(2)).subscribe(ts);
    ts.assertError(r);
}
 
Example 9
Source File: OperatorBufferToFileTest.java    From rxjava-extras with Apache License 2.0 5 votes vote down vote up
@Test
public void handlesErrorSerialization() throws InterruptedException {
    Scheduler scheduler = createSingleThreadScheduler();
    for (int i = 0; i < loops(); i++) {
        TestSubscriber<String> ts = TestSubscriber.create();
        Observable.<String> error(new IOException("boo"))
                //
                .compose(Transformers.onBackpressureBufferToFile(DataSerializers.string(),
                        scheduler, Options.defaultInstance()))
                .subscribe(ts);
        ts.awaitTerminalEvent(10, TimeUnit.SECONDS);
        ts.assertError(IOException.class);
        waitUntilWorkCompleted(scheduler);
    }
}
 
Example 10
Source File: DataManagerTest.java    From ribot-app-android with Apache License 2.0 5 votes vote down vote up
@Test
public void checkInFail() {
    CheckInRequest request = CheckInRequest.fromLabel(MockModelFabric.randomString());
    doReturn(Observable.error(new RuntimeException()))
            .when(mMockRibotsService)
            .checkIn(anyString(), eq(request));

    TestSubscriber<CheckIn> testSubscriber = new TestSubscriber<>();
    mDataManager.checkIn(request).subscribe(testSubscriber);
    testSubscriber.assertError(RuntimeException.class);
    testSubscriber.assertNoValues();

    verify(mMockPreferencesHelper, never()).putLatestCheckIn(any(CheckIn.class));
}
 
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: 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 13
Source File: RestApiTest.java    From Mockery with Apache License 2.0 5 votes vote down vote up
@Test public void modelWithParamsFailsWhenInvalidRequestBody() {
  RequestBody requestBody = RequestBody
      .create(MediaType.parse("text/plain"), "{\"s1\":\"\"}");

  TestSubscriber<Model> subscriber = new TestSubscriber<>();
  restApi.modelWithParams(requestBody, 0).subscribe(subscriber);
  subscriber.awaitTerminalEvent();
  subscriber.assertNoValues();
  subscriber.assertError(HttpException.class);

  Throwable error = subscriber.getOnErrorEvents().get(0);
  assertThat(error.getMessage(), is("HTTP 404 null"));
}
 
Example 14
Source File: BaseClientTest.java    From android with Apache License 2.0 5 votes vote down vote up
protected  <O> Throwable assertError(Observable<O> o, Class<? extends Throwable> e) {
    TestSubscriber<O> ts = TestSubscriber.create();
    o.subscribe(ts);
    ts.assertError(e);

    return ts.getOnErrorEvents().get(0);
}
 
Example 15
Source File: TransformersTest.java    From rxjava-extras with Apache License 2.0 5 votes vote down vote up
@Test
public void testRepeatLastOfNoValuesThenError() {
    TestSubscriber<Integer> ts = TestSubscriber.create();
    Observable.<Integer> error(new IOException()).compose(Transformers.<Integer> repeatLast())
            .subscribe(ts);
    ts.assertNoValues();
    ts.assertError(IOException.class);
}
 
Example 16
Source File: AbstractCouchbaseRequestTest.java    From couchbase-jvm-core with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldCompleteResponseWithFailure() {
    SampleRequest sr = new SampleRequest();
    TestSubscriber<CouchbaseResponse> subs = new TestSubscriber<CouchbaseResponse>();
    sr.observable().subscribe(subs);
    subs.assertNotCompleted();

    Exception exception = new TimeoutException();
    sr.fail(exception);

    subs.awaitTerminalEvent();
    subs.assertError(exception);
}
 
Example 17
Source File: OrderedMergeTest.java    From rxjava-extras with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testErrorImmediatelyDelayed() {
	Observable<Integer> o1 = Observable.just(1, 3, 5, 7);
	Observable<Integer> o2 = Observable.<Integer> error(new TestException());

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

	ts.assertError(TestException.class);
	ts.assertNotCompleted();
	ts.assertValues(1, 3, 5, 7);
}
 
Example 18
Source File: UploaderTest.java    From RxUploader with Apache License 2.0 4 votes vote down vote up
@Test
public void testUploadFailed() throws Exception {
    final File file = getFile(TEST_FILE);
    final String jobId = "job-id";
    final Job job = Job.builder()
            .setId(jobId)
            .setStatus(Status.createQueued(jobId))
            .setMetadata(Collections.emptyMap())
            .setFilepath(file.getPath())
            .setMimeType("text/plain")
            .build();

    final List<Status> values = new ArrayList<>();

    final long total = file.length();
    long consumed = 0;
    while (consumed <= (0.5f * total)) {
        values.add(Status.createSending(jobId, (int) ((float) consumed * 100 / total)));
        consumed = Math.min(total, consumed + RxRequestBody.BUFFER_SIZE);
    }

    final Status[] expectedStatus = new Status[values.size()];
    values.toArray(expectedStatus);

    final BufferedSink sink = mock(BufferedSink.class);
    when(sink.write(any(Source.class), anyLong())).thenAnswer(new Answer<BufferedSink>() {
        long bytesRead = 0;

        @Override
        public BufferedSink answer(InvocationOnMock invocation) throws Throwable {
            bytesRead += (long) invocation.getArguments()[1];
            if (bytesRead > 0.5f * total) {
                throw new IOException("exception");
            }
            return sink;
        }
    });

    final UploadService service = (__, data) -> {
        try {
            data.body().writeTo(sink);
        } catch (@NonNull IOException e) {
            return Single.error(e);
        }
        return Single.just("complete");
    };

    final Uploader uploader = new Uploader(service, Schedulers.io());
    final TestSubscriber<Status> ts = TestSubscriber.create();
    uploader.upload(job, file).subscribe(ts);

    ts.awaitTerminalEvent(1, TimeUnit.SECONDS);
    ts.assertError(IOException.class);
    ts.assertValues(expectedStatus);
}
 
Example 19
Source File: FontInstallerTest.java    From fontster with Apache License 2.0 4 votes vote down vote up
@Test public void testGenerateCommands_installExceptionIfFilesNonexistent() throws Exception {
  TestSubscriber<String> testSubscriber = new TestSubscriber<>();
  FontInstaller.generateCommands(MOCK_FONT_PACK, null).subscribe(testSubscriber);
  testSubscriber.assertError(FontInstaller.InstallException.class);
}
 
Example 20
Source File: DocumentProducerTest.java    From azure-cosmosdb-java with MIT License 4 votes vote down vote up
@Test(groups = { "unit" }, timeOut = TIMEOUT)
public void retriesExhausted() {
    int initialPageSize = 7;
    int top = -1;

    String partitionKeyRangeId = "1";

    RequestCreator requestCreator = RequestCreator.simpleMock();

    List<FeedResponse<Document>> responsesBeforeThrottle = mockFeedResponses(partitionKeyRangeId, 1, 1, false);
    Exception throttlingException = mockThrottlingException(10);

    RequestExecutor.PartitionAnswer behaviourBeforeException = RequestExecutor.PartitionAnswer.just(partitionKeyRangeId, responsesBeforeThrottle);
    RequestExecutor.PartitionAnswer exceptionBehaviour = RequestExecutor.PartitionAnswer.errors(partitionKeyRangeId, Collections.nCopies(10, throttlingException));

    RequestExecutor requestExecutor = RequestExecutor.fromPartitionAnswer(behaviourBeforeException, exceptionBehaviour);

    PartitionKeyRange targetRange = mockPartitionKeyRange(partitionKeyRangeId);

    IDocumentQueryClient queryClient = Mockito.mock(IDocumentQueryClient.class);
    String initialContinuationToken = "initial-cp";
    DocumentProducer<Document> documentProducer = new DocumentProducer<>(
            queryClient,
            collectionRid,
            null,
            requestCreator,
            requestExecutor,
            targetRange,
            collectionRid,
            () -> mockDocumentClientIRetryPolicyFactory().getRequestPolicy(),
            Document.class,
            null,
            initialPageSize,
            initialContinuationToken,
            top);

    TestSubscriber<DocumentProducer.DocumentProducerFeedResponse> subscriber = new TestSubscriber<>();

    documentProducer.produceAsync().subscribe(subscriber);
    subscriber.awaitTerminalEvent();

    subscriber.assertError(throttlingException);
    subscriber.assertValueCount(responsesBeforeThrottle.size());
}