@Test(timeout = 1000L)
  public void testSynchronousError() {
    final Observable<Observable<String>> o1 = Observable.error(new RuntimeException("unit test"));

    final CountDownLatch latch = new CountDownLatch(1);
    Observable.mergeDelayError(o1)
        .subscribe(
            new Observer<String>() {
              @Override
              public void onComplete() {
                fail("Expected onError path");
              }

              @Override
              public void onError(Throwable e) {
                latch.countDown();
              }

              @Override
              public void onNext(String s) {
                fail("Expected onError path");
              }
            });

    try {
      latch.await();
    } catch (InterruptedException ex) {
      fail("interrupted");
    }
  }
  @Test(description = "OPENDJ-1197")
  public void testClientSideConnectTimeout() throws Exception {
    // Use an non-local unreachable network address.
    final ConnectionFactory factory =
        new LDAPConnectionFactory(
            "10.20.30.40", 1389, new LDAPOptions().setConnectTimeout(1, TimeUnit.MILLISECONDS));
    try {
      for (int i = 0; i < ITERATIONS; i++) {
        final PromiseImpl<LdapException, NeverThrowsException> promise = PromiseImpl.create();
        final Promise<? extends Connection, LdapException> connectionPromise =
            factory.getConnectionAsync();
        connectionPromise.onFailure(getFailureHandler(promise));

        ConnectionException e =
            (ConnectionException) promise.getOrThrow(TEST_TIMEOUT, TimeUnit.SECONDS);
        assertThat(e.getResult().getResultCode()).isEqualTo(ResultCode.CLIENT_SIDE_CONNECT_ERROR);
        // Wait for the connect to timeout.
        try {
          connectionPromise.getOrThrow(TEST_TIMEOUT, TimeUnit.SECONDS);
          fail("The connect request succeeded unexpectedly");
        } catch (ConnectionException ce) {
          assertThat(ce.getResult().getResultCode())
              .isEqualTo(ResultCode.CLIENT_SIDE_CONNECT_ERROR);
        }
      }
    } finally {
      factory.close();
    }
  }
Пример #3
0
  @Test
  public void testTakeWithErrorInObserver() {
    final AtomicInteger count = new AtomicInteger();
    final AtomicReference<Throwable> error = new AtomicReference<>();
    Observable.just("1", "2", "three", "4")
        .take(3)
        .safeSubscribe(
            new Observer<String>() {

              @Override
              public void onComplete() {
                System.out.println("completed");
              }

              @Override
              public void onError(Throwable e) {
                error.set(e);
                System.out.println("error");
                e.printStackTrace();
              }

              @Override
              public void onNext(String v) {
                int num = Integer.parseInt(v);
                System.out.println(num);
                // doSomething(num);
                count.incrementAndGet();
              }
            });
    assertEquals(2, count.get());
    assertNotNull(error.get());
    if (!(error.get() instanceof NumberFormatException)) {
      fail("It should be a NumberFormatException");
    }
  }
Пример #4
0
  @SuppressWarnings("deprecation")
  @Test
  public void shouldStubStringVarargs() {
    when(mock.withStringVarargsReturningString(1)).thenReturn("1");
    when(mock.withStringVarargsReturningString(2, "1", "2", "3")).thenReturn("2");

    RuntimeException expected = new RuntimeException();
    stubVoid(mock).toThrow(expected).on().withStringVarargs(3, "1", "2", "3", "4");

    assertEquals("1", mock.withStringVarargsReturningString(1));
    assertEquals(null, mock.withStringVarargsReturningString(2));

    assertEquals("2", mock.withStringVarargsReturningString(2, "1", "2", "3"));
    assertEquals(null, mock.withStringVarargsReturningString(2, "1", "2"));
    assertEquals(null, mock.withStringVarargsReturningString(2, "1", "2", "3", "4"));
    assertEquals(null, mock.withStringVarargsReturningString(2, "1", "2", "9999"));

    mock.withStringVarargs(3, "1", "2", "3", "9999");
    mock.withStringVarargs(9999, "1", "2", "3", "4");

    try {
      mock.withStringVarargs(3, "1", "2", "3", "4");
      fail();
    } catch (Exception e) {
      assertEquals(expected, e);
    }
  }
Пример #5
0
    @Test
    public void testUnsubscribeAfterTake() {
      Subscription s = mock(Subscription.class);
      TestObservable w = new TestObservable(s, "one", "two", "three");

      @SuppressWarnings("unchecked")
      Observer<String> aObserver = mock(Observer.class);
      Observable<String> take = Observable.create(take(w, 1));
      take.subscribe(aObserver);

      // wait for the Observable to complete
      try {
        w.t.join();
      } catch (Throwable e) {
        e.printStackTrace();
        fail(e.getMessage());
      }

      System.out.println("TestObservable thread finished");
      verify(aObserver, times(1)).onNext("one");
      verify(aObserver, never()).onNext("two");
      verify(aObserver, never()).onNext("three");
      verify(aObserver, times(1)).onCompleted();
      verify(s, times(1)).unsubscribe();
      verifyNoMoreInteractions(aObserver);
    }
Пример #6
0
 /**
  * Set up the {@link ClientSession} to throw an exception when {@link
  * ClientSession#createProducer(String)} is called. Make sure, we throw up our hands saying "I am
  * not dealing with this".
  *
  * @throws Exception
  */
 @Test(expected = RuntimeException.class)
 public void eventSinkShouldThrowExceptionWhenProducerCreationFailsInConstructor()
     throws Exception {
   doThrow(new HornetQException()).when(mockClientSession.createProducer(anyString()));
   createEventSink(mockSessionFactory);
   fail("Runtime exception should have been thrown.");
 }
  @Test
  public void testResumeNext() {
    Subscription s = mock(Subscription.class);
    // Trigger failure on second element
    TestObservable f = new TestObservable(s, "one", "fail", "two", "three");
    Observable<String> w = Observable.create(f);
    Observable<String> resume = Observable.from("twoResume", "threeResume");
    Observable<String> observable = Observable.create(onErrorResumeNextViaObservable(w, resume));

    @SuppressWarnings("unchecked")
    Observer<String> observer = mock(Observer.class);
    observable.subscribe(observer);

    try {
      f.t.join();
    } catch (InterruptedException e) {
      fail(e.getMessage());
    }

    verify(observer, Mockito.never()).onError(any(Throwable.class));
    verify(observer, times(1)).onCompleted();
    verify(observer, times(1)).onNext("one");
    verify(observer, Mockito.never()).onNext("two");
    verify(observer, Mockito.never()).onNext("three");
    verify(observer, times(1)).onNext("twoResume");
    verify(observer, times(1)).onNext("threeResume");
  }
Пример #8
0
  /**
   * The error from the user provided Observable is handled by the subscribe try/catch because this
   * is synchronous
   *
   * <p>Result: Passes
   */
  @Test
  public void testCustomObservableWithErrorInObservableSynchronous() {
    final AtomicInteger count = new AtomicInteger();
    final AtomicReference<Throwable> error = new AtomicReference<>();
    // FIXME custom built???
    Observable.just("1", "2")
        .concatWith(Observable.error(() -> new NumberFormatException()))
        .subscribe(
            new Observer<String>() {

              @Override
              public void onComplete() {
                System.out.println("completed");
              }

              @Override
              public void onError(Throwable e) {
                error.set(e);
                System.out.println("error");
                e.printStackTrace();
              }

              @Override
              public void onNext(String v) {
                System.out.println(v);
                count.incrementAndGet();
              }
            });
    assertEquals(2, count.get());
    assertNotNull(error.get());
    if (!(error.get() instanceof NumberFormatException)) {
      fail("It should be a NumberFormatException");
    }
  }
Пример #9
0
 /**
  * Set up the {@link ClientSessionFactory} to throw an exception when {@link
  * ClientSessionFactory#createSession()} is called. Make sure, we throw up our hands saying "I am
  * not dealing with this".
  *
  * @throws Exception
  */
 @Test(expected = RuntimeException.class)
 public void eventSinkShouldThrowExceptionWhenSessionCreationFailsInConstructor()
     throws Exception {
   final ClientSessionFactory csFactory = mock(ClientSessionFactory.class);
   doThrow(new HornetQException()).when(csFactory.createSession());
   createEventSink(csFactory);
   fail("Runtime exception should have been thrown.");
 }
 @Test
 public void shouldSayUnfinishedVerificationButNotInvalidUseOfMatchers() {
   verify(withFinal).finalMethod(anyObject());
   try {
     verify(withFinal);
     fail();
   } catch (UnfinishedVerificationException e) {
   }
 }
Пример #11
0
 /**
  * https://github.com/ReactiveX/RxJava/issues/198
  *
  * <p>Rx Design Guidelines 5.2
  *
  * <p>"when calling the Subscribe method that only has an onNext argument, the OnError behavior
  * will be to rethrow the exception on the thread that the message comes out from the Observable.
  * The OnCompleted behavior in this case is to do nothing."
  */
 @Test
 @Ignore("Subscribers can't throw")
 public void testErrorThrownWithoutErrorHandlerSynchronous() {
   try {
     Observable.error(new RuntimeException("failure")).subscribe();
     fail("expected exception");
   } catch (Throwable e) {
     assertEquals("failure", e.getMessage());
   }
 }
 @Test
 public void shouldFailFastWhenArgumentMatchersAbused() {
   misplacedArgumentMatcher();
   try {
     mock(IMethods.class);
     fail();
   } catch (InvalidUseOfMatchersException e) {
     assertContains("Misplaced argument matcher", e.getMessage());
   }
 }
Пример #13
0
 @Test
 public void physicalOnly() throws Exception {
   String expected = "Pool is restricted to physical systems: 'pool10'.";
   try {
     bindByPoolErrorTest("rulefailed.physical.only");
     fail();
   } catch (ForbiddenException e) {
     assertEquals(expected, e.getMessage());
   }
 }
Пример #14
0
 @Test
 public void virtOnly() {
   String expected = "Pool is restricted to virtual guests: 'pool10'.";
   try {
     bindByPoolErrorTest("rulefailed.virt.only");
     fail();
   } catch (ForbiddenException e) {
     assertEquals(expected, e.getMessage());
   }
 }
Пример #15
0
 @Test
 public void consumerDoesntSupportDerived() {
   String expected = "Unit does not support derived products " + "data required by pool 'pool10'";
   try {
     bindByPoolErrorTest("rulefailed.derivedproduct.unsupported.by.consumer");
     fail();
   } catch (ForbiddenException e) {
     assertEquals(expected, e.getMessage());
   }
 }
Пример #16
0
 @Test
 public void consumerDoesntSupportRam() {
   String expected = "Unit does not support RAM " + "calculation required by pool 'pool10'";
   try {
     bindByPoolErrorTest("rulefailed.ram.unsupported.by.consumer");
     fail();
   } catch (ForbiddenException e) {
     assertEquals(expected, e.getMessage());
   }
 }
Пример #17
0
  @Test
  public void shouldValidateStateWhenResetting() {
    // invalid verify:
    verify(mock);

    try {
      reset(mockTwo);
      fail();
    } catch (UnfinishedVerificationException e) {
    }
  }
Пример #18
0
 @Test
 public void shouldResetOngoingStubbingSoThatMoreMeaningfulExceptionsAreRaised() {
   mock(IMethods.class);
   mock.booleanReturningMethod();
   reset(mock);
   try {
     when(null).thenReturn("anything");
     fail();
   } catch (MissingMethodInvocationException e) {
   }
 }
  @Test
  public void testValidateSingleInvalid() {
    when(config.getBoolean(eq(ConfigProperties.STANDALONE))).thenReturn(false);
    ContentOverride override = new ContentOverride("label", "baseurl", "value");

    try {
      validator.validate(override);
      fail("Expected exception was \"BadRequestException\" not thrown.");
    } catch (BadRequestException bre) {
      assertEquals("Not allowed to override values for: baseurl", bre.getMessage());
    }
  }
Пример #20
0
 private void bindByProductErrorTest(String msg) throws Exception {
   try {
     String[] pids = {"prod1", "prod2", "prod3"};
     Map<String, ValidationResult> fakeResult = new HashMap<String, ValidationResult>();
     fakeResult.put("blah", fakeOutResult(msg));
     EntitlementRefusedException ere = new EntitlementRefusedException(fakeResult);
     AutobindData data = AutobindData.create(consumer).forProducts(pids);
     when(pm.entitleByProducts(data)).thenThrow(ere);
     entitler.bindByProducts(data);
   } catch (EntitlementRefusedException e) {
     fail(msg + ": threw unexpected error");
   }
 }
Пример #21
0
  /** A reduce should fail with an NoSuchElementException if done on an empty Observable. */
  @Test(expected = NoSuchElementException.class)
  public void testReduceWithEmptyObservable() {
    Observable<Integer> observable = Observable.range(1, 0);
    observable
        .reduce((t1, t2) -> t1 + t2)
        .toBlocking()
        .forEach(
            t1 -> {
              // do nothing ... we expect an exception instead
            });

    fail("Expected an exception to be thrown");
  }
Пример #22
0
  @Test
  public void shouldVerifyBooleanVarargs() {
    mock.withBooleanVarargs(1);
    mock.withBooleanVarargs(2, true, false, true);
    mock.withBooleanVarargs(3, true, true, true);

    verify(mock).withBooleanVarargs(1);
    verify(mock).withBooleanVarargs(2, true, false, true);
    try {
      verify(mock).withBooleanVarargs(3, true, true, true, true);
      fail();
    } catch (ArgumentsAreDifferent e) {
    }
  }
Пример #23
0
  @Test
  public void shouldVerifyStringVarargs() {
    mock.withStringVarargs(1);
    mock.withStringVarargs(2, "1", "2", "3");
    mock.withStringVarargs(3, "1", "2", "3", "4");

    verify(mock).withStringVarargs(1);
    verify(mock).withStringVarargs(2, "1", "2", "3");
    try {
      verify(mock).withStringVarargs(2, "1", "2", "79", "4");
      fail();
    } catch (ArgumentsAreDifferent e) {
    }
  }
Пример #24
0
  @Test
  public void shouldVerifyObjectVarargs() {
    mock.withObjectVarargs(1);
    mock.withObjectVarargs(2, "1", new ArrayList<Object>(), new Integer(1));
    mock.withObjectVarargs(3, new Integer(1));

    verify(mock).withObjectVarargs(1);
    verify(mock).withObjectVarargs(2, "1", new ArrayList<Object>(), new Integer(1));
    try {
      verifyNoMoreInteractions(mock);
      fail();
    } catch (NoInteractionsWanted e) {
    }
  }
Пример #25
0
  @Test
  public void testReplay() throws InterruptedException {
    final AtomicInteger counter = new AtomicInteger();
    ConnectableObservable<String> o =
        Observable.<String>create(
                observer -> {
                  observer.onSubscribe(EmptySubscription.INSTANCE);
                  new Thread(
                          new Runnable() {

                            @Override
                            public void run() {
                              counter.incrementAndGet();
                              observer.onNext("one");
                              observer.onComplete();
                            }
                          })
                      .start();
                })
            .replay();

    // we connect immediately and it will emit the value
    Disposable s = o.connect();
    try {

      // we then expect the following 2 subscriptions to get that same value
      final CountDownLatch latch = new CountDownLatch(2);

      // subscribe once
      o.subscribe(
          v -> {
            assertEquals("one", v);
            latch.countDown();
          });

      // subscribe again
      o.subscribe(
          v -> {
            assertEquals("one", v);
            latch.countDown();
          });

      if (!latch.await(1000, TimeUnit.MILLISECONDS)) {
        fail("subscriptions did not receive values");
      }
      assertEquals(1, counter.get());
    } finally {
      s.dispose();
    }
  }
  @Test
  public void testValidateCollectionBothInvalid() {
    when(config.getBoolean(eq(ConfigProperties.STANDALONE))).thenReturn(false);
    List<ContentOverride> overrides = new LinkedList<ContentOverride>();
    overrides.add(new ContentOverride("label", "baseurl", "value"));
    overrides.add(new ContentOverride("other label", "name", "other value"));

    try {
      validator.validate(overrides);
      fail("Expected exception \"BadRequestException\" was not thrown.");
    } catch (BadRequestException bre) {
      assertTrue(
          bre.getMessage()
              .matches("^Not allowed to override values for: (?:baseurl, name|name, baseurl)"));
    }
  }
Пример #27
0
  @Test
  @SuppressWarnings("unchecked")
  public void testSimple() throws InterruptedException {
    final ExecutorService exec = Executors.newCachedThreadPool();
    try {
      final CountDownLatch ready = new CountDownLatch(1);

      Func0<Future<Observable<Integer>>> func =
          new Func0<Future<Observable<Integer>>>() {
            @Override
            public Future<Observable<Integer>> call() {
              return exec.submit(
                  new Callable<Observable<Integer>>() {
                    @Override
                    public Observable<Integer> call() throws Exception {
                      if (!ready.await(1000, TimeUnit.MILLISECONDS)) {
                        throw new IllegalStateException("Not started in time");
                      }
                      return Observable.from(1);
                    }
                  });
            }
          };

      Observable<Integer> result = Async.deferFuture(func, Schedulers.threadPoolForComputation());

      final Observer<Integer> observer = mock(Observer.class);

      final CountDownLatch done = new CountDownLatch(1);

      result.subscribe(new OperationStartFutureTest.MockHelper<Integer>(observer, done));

      ready.countDown();

      if (!done.await(1000, TimeUnit.MILLISECONDS)) {
        fail("Not completed in time!");
      }

      InOrder inOrder = inOrder(observer);

      inOrder.verify(observer).onNext(1);
      inOrder.verify(observer).onCompleted();
      verify(observer, never()).onError(any(Throwable.class));
    } finally {
      exec.shutdown();
    }
  }
  /**
   * Unit test for OPENDJ-1247: as per previous test, except this time verify that the connection
   * failure removes the connection from a connection pool.
   */
  @Test
  public void testClientSideTimeoutForBindRequestInConnectionPool() throws Exception {
    resetState();
    registerBindEvent();
    registerCloseEvent();

    for (int i = 0; i < ITERATIONS; i++) {
      final Connection connection = pool.getConnection();
      try {
        waitForConnect();
        final MockConnectionEventListener listener = new MockConnectionEventListener();
        connection.addConnectionEventListener(listener);

        // Now bind with timeout.
        final PromiseImpl<LdapException, NeverThrowsException> promise = PromiseImpl.create();
        final LdapPromise<BindResult> bindPromise = connection.bindAsync(newSimpleBindRequest());
        bindPromise.onFailure(getFailureHandler(promise));
        waitForBind();

        // Wait for the request to timeout and check the handler was invoked.
        TimeoutResultException e = (TimeoutResultException) promise.getOrThrow(5, TimeUnit.SECONDS);
        verifyResultCodeIsClientSideTimeout(e);

        // Now check the promise was completed as expected.
        try {
          bindPromise.getOrThrow(5, TimeUnit.SECONDS);
          fail("The bind request succeeded unexpectedly");
        } catch (TimeoutResultException te) {
          verifyResultCodeIsClientSideTimeout(te);
        }

        /*
         * The connection should no longer be valid, the event listener
         * should have been notified, but no abandon should have been
         * sent.
         */
        listener.awaitError(TEST_TIMEOUT, TimeUnit.SECONDS);
        assertThat(connection.isValid()).isFalse();
        verifyResultCodeIsClientSideTimeout(listener.getError());
        connection.close();
        waitForClose();
        verifyNoAbandonSent();
      } finally {
        connection.close();
      }
    }
  }
Пример #29
0
  @Test
  public void testNoDryBindWhenAutobindDisabledForOwner() throws Exception {
    Consumer consumer = createConsumer();
    consumer.getOwner().setAutobindDisabled(true);
    when(mockedConsumerCurator.verifyAndLookupConsumer(eq(consumer.getUuid())))
        .thenReturn(consumer);
    ManifestManager manifestManager = mock(ManifestManager.class);
    ConsumerResource consumerResource =
        new ConsumerResource(
            mockedConsumerCurator,
            null,
            null,
            null,
            null,
            null,
            null,
            i18n,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            mockedOwnerCurator,
            null,
            null,
            null,
            null,
            null,
            null,
            new CandlepinCommonTestConfig(),
            null,
            null,
            null,
            null,
            productCurator,
            manifestManager);

    try {
      consumerResource.dryBind(consumer.getUuid(), "some-sla");
      fail("Should have thrown a BadRequestException.");
    } catch (BadRequestException e) {
      assertEquals("Owner has autobind disabled.", e.getMessage());
    }
  }
Пример #30
0
  private void bindByPoolErrorTest(String msg) {
    try {
      String poolid = "pool10";
      Pool pool = mock(Pool.class);
      Map<String, ValidationResult> fakeResult = new HashMap<String, ValidationResult>();
      fakeResult.put(poolid, fakeOutResult(msg));
      EntitlementRefusedException ere = new EntitlementRefusedException(fakeResult);

      when(pool.getId()).thenReturn(poolid);
      when(poolCurator.find(eq(poolid))).thenReturn(pool);
      Map<String, Integer> pQs = new HashMap<String, Integer>();
      pQs.put(poolid, 1);
      when(pm.entitleByPools(eq(consumer), eq(pQs))).thenThrow(ere);
      entitler.bindByPoolQuantity(consumer, poolid, 1);
    } catch (EntitlementRefusedException e) {
      fail(msg + ": threw unexpected error");
    }
  }