Search in sources :

Example 21 with TestCircuitBreaker

use of com.netflix.hystrix.HystrixCircuitBreakerTest.TestCircuitBreaker in project Hystrix by Netflix.

the class HystrixObservableCommandTest method testRequestContextOnShortCircuitedWithFallback.

private RequestContextTestResults testRequestContextOnShortCircuitedWithFallback(ExecutionIsolationStrategy isolation, final Scheduler userScheduler) {
    final RequestContextTestResults results = new RequestContextTestResults();
    TestHystrixObservableCommand<Boolean> command = new TestHystrixObservableCommand<Boolean>(TestHystrixObservableCommand.testPropsBuilder(new TestCircuitBreaker()).setCommandPropertiesDefaults(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter().withExecutionIsolationStrategy(isolation)).setCircuitBreaker(new TestCircuitBreaker().setForceShortCircuit(true))) {

        @Override
        protected Observable<Boolean> construct() {
            return Observable.create(new OnSubscribe<Boolean>() {

                @Override
                public void call(Subscriber<? super Boolean> s) {
                    s.onError(new RuntimeException("onError"));
                }
            }).subscribeOn(userScheduler);
        }

        @Override
        protected Observable<Boolean> resumeWithFallback() {
            return Observable.create(new OnSubscribe<Boolean>() {

                @Override
                public void call(Subscriber<? super Boolean> s) {
                    results.isContextInitialized.set(HystrixRequestContext.isCurrentThreadInitialized());
                    results.originThread.set(Thread.currentThread());
                    s.onNext(false);
                    s.onCompleted();
                }
            }).subscribeOn(userScheduler);
        }
    };
    results.command = command;
    command.toObservable().doOnEach(new Action1<Notification<? super Boolean>>() {

        @Override
        public void call(Notification<? super Boolean> n) {
            results.isContextInitializedObserveOn.set(HystrixRequestContext.isCurrentThreadInitialized());
            results.observeOnThread.set(Thread.currentThread());
        }
    }).subscribe(results.ts);
    results.ts.awaitTerminalEvent();
    System.out.println("Run => Initialized: " + results.isContextInitialized.get() + "  Thread: " + results.originThread.get());
    System.out.println("Observed => Initialized: " + results.isContextInitializedObserveOn.get() + "  Thread: " + results.observeOnThread.get());
    assertEquals(0, results.ts.getOnErrorEvents().size());
    assertEquals(1, results.ts.getOnNextEvents().size());
    assertEquals(false, results.ts.getOnNextEvents().get(0));
    assertTrue(command.getExecutionTimeInMilliseconds() == -1);
    assertFalse(command.isSuccessfulExecution());
    assertTrue(command.isResponseShortCircuited());
    assertCommandExecutionEvents(command, HystrixEventType.SHORT_CIRCUITED, HystrixEventType.FALLBACK_EMIT, HystrixEventType.FALLBACK_SUCCESS);
    assertEquals(0, command.metrics.getCurrentConcurrentExecutionCount());
    assertSaneHystrixRequestLog(1);
    return results;
}
Also used : TestCircuitBreaker(com.netflix.hystrix.HystrixCircuitBreakerTest.TestCircuitBreaker) HystrixRuntimeException(com.netflix.hystrix.exception.HystrixRuntimeException) Action1(rx.functions.Action1) TestSubscriber(rx.observers.TestSubscriber) OnSubscribe(rx.Observable.OnSubscribe) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean)

Example 22 with TestCircuitBreaker

use of com.netflix.hystrix.HystrixCircuitBreakerTest.TestCircuitBreaker in project Hystrix by Netflix.

the class HystrixObservableCommandTest method testCheckedExceptionViaObserve.

/**
 * Test a java.lang.Error being thrown
 *
 * @throws InterruptedException
 */
@Test
public void testCheckedExceptionViaObserve() throws InterruptedException {
    TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
    CommandWithCheckedException command = new CommandWithCheckedException(circuitBreaker);
    final AtomicReference<Throwable> t = new AtomicReference<Throwable>();
    final CountDownLatch latch = new CountDownLatch(1);
    try {
        command.observe().subscribe(new Observer<Boolean>() {

            @Override
            public void onCompleted() {
                latch.countDown();
            }

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

            @Override
            public void onNext(Boolean args) {
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
        fail("we should not get anything thrown, it should be emitted via the Observer#onError method");
    }
    latch.await(1, TimeUnit.SECONDS);
    assertNotNull(t.get());
    t.get().printStackTrace();
    assertTrue(t.get() instanceof HystrixRuntimeException);
    assertEquals("simulated checked exception message", t.get().getCause().getMessage());
    assertEquals("simulated checked exception message", command.getFailedExecutionException().getMessage());
    assertTrue(command.getExecutionTimeInMilliseconds() > -1);
    assertTrue(command.isFailedExecution());
    assertCommandExecutionEvents(command, HystrixEventType.FAILURE, HystrixEventType.FALLBACK_MISSING);
    assertNotNull(command.getExecutionException());
    // semaphore isolated
    assertFalse(command.isExecutedInThread());
    assertSaneHystrixRequestLog(1);
}
Also used : TestCircuitBreaker(com.netflix.hystrix.HystrixCircuitBreakerTest.TestCircuitBreaker) AtomicReference(java.util.concurrent.atomic.AtomicReference) HystrixRuntimeException(com.netflix.hystrix.exception.HystrixRuntimeException) CountDownLatch(java.util.concurrent.CountDownLatch) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) TimeoutException(java.util.concurrent.TimeoutException) HystrixRuntimeException(com.netflix.hystrix.exception.HystrixRuntimeException) HystrixBadRequestException(com.netflix.hystrix.exception.HystrixBadRequestException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) Test(org.junit.Test)

Example 23 with TestCircuitBreaker

use of com.netflix.hystrix.HystrixCircuitBreakerTest.TestCircuitBreaker in project Hystrix by Netflix.

the class HystrixObservableCommandTest method testRequestContextOnRejectionWithFallback.

private RequestContextTestResults testRequestContextOnRejectionWithFallback(ExecutionIsolationStrategy isolation, final Scheduler userScheduler) {
    final RequestContextTestResults results = new RequestContextTestResults();
    TestHystrixObservableCommand<Boolean> command = new TestHystrixObservableCommand<Boolean>(TestHystrixObservableCommand.testPropsBuilder(new TestCircuitBreaker()).setCommandPropertiesDefaults(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter().withExecutionIsolationStrategy(isolation).withExecutionIsolationSemaphoreMaxConcurrentRequests(0)).setThreadPool(new HystrixThreadPool() {

        @Override
        public ThreadPoolExecutor getExecutor() {
            return null;
        }

        @Override
        public void markThreadExecution() {
        }

        @Override
        public void markThreadCompletion() {
        }

        @Override
        public void markThreadRejection() {
        }

        @Override
        public boolean isQueueSpaceAvailable() {
            // always return false so we reject everything
            return false;
        }

        @Override
        public Scheduler getScheduler() {
            return new HystrixContextScheduler(HystrixPlugins.getInstance().getConcurrencyStrategy(), this);
        }

        @Override
        public Scheduler getScheduler(Func0<Boolean> shouldInterruptThread) {
            return new HystrixContextScheduler(HystrixPlugins.getInstance().getConcurrencyStrategy(), this, shouldInterruptThread);
        }
    })) {

        @Override
        protected Observable<Boolean> construct() {
            return Observable.create(new OnSubscribe<Boolean>() {

                @Override
                public void call(Subscriber<? super Boolean> s) {
                    s.onError(new RuntimeException("onError"));
                }
            }).subscribeOn(userScheduler);
        }

        @Override
        protected Observable<Boolean> resumeWithFallback() {
            return Observable.create(new OnSubscribe<Boolean>() {

                @Override
                public void call(Subscriber<? super Boolean> s) {
                    results.isContextInitialized.set(HystrixRequestContext.isCurrentThreadInitialized());
                    results.originThread.set(Thread.currentThread());
                    s.onNext(false);
                    s.onCompleted();
                }
            }).subscribeOn(userScheduler);
        }
    };
    results.command = command;
    command.toObservable().doOnEach(new Action1<Notification<? super Boolean>>() {

        @Override
        public void call(Notification<? super Boolean> n) {
            results.isContextInitializedObserveOn.set(HystrixRequestContext.isCurrentThreadInitialized());
            results.observeOnThread.set(Thread.currentThread());
        }
    }).subscribe(results.ts);
    results.ts.awaitTerminalEvent();
    System.out.println("Run => Initialized: " + results.isContextInitialized.get() + "  Thread: " + results.originThread.get());
    System.out.println("Observed => Initialized: " + results.isContextInitializedObserveOn.get() + "  Thread: " + results.observeOnThread.get());
    assertEquals(0, results.ts.getOnErrorEvents().size());
    assertEquals(1, results.ts.getOnNextEvents().size());
    assertEquals(false, results.ts.getOnNextEvents().get(0));
    assertFalse(command.isSuccessfulExecution());
    assertTrue(command.isResponseRejected());
    if (isolation == ExecutionIsolationStrategy.SEMAPHORE) {
        assertCommandExecutionEvents(command, HystrixEventType.SEMAPHORE_REJECTED, HystrixEventType.FALLBACK_EMIT, HystrixEventType.FALLBACK_SUCCESS);
    } else {
        assertCommandExecutionEvents(command, HystrixEventType.THREAD_POOL_REJECTED, HystrixEventType.FALLBACK_EMIT, HystrixEventType.FALLBACK_SUCCESS);
    }
    assertEquals(0, command.metrics.getCurrentConcurrentExecutionCount());
    assertSaneHystrixRequestLog(1);
    return results;
}
Also used : TestCircuitBreaker(com.netflix.hystrix.HystrixCircuitBreakerTest.TestCircuitBreaker) Action1(rx.functions.Action1) HystrixContextScheduler(com.netflix.hystrix.strategy.concurrency.HystrixContextScheduler) OnSubscribe(rx.Observable.OnSubscribe) HystrixRuntimeException(com.netflix.hystrix.exception.HystrixRuntimeException) TestSubscriber(rx.observers.TestSubscriber) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Func0(rx.functions.Func0)

Example 24 with TestCircuitBreaker

use of com.netflix.hystrix.HystrixCircuitBreakerTest.TestCircuitBreaker in project Hystrix by Netflix.

the class HystrixObservableCommandTest method testRequestContextOnGracefulFailure.

private RequestContextTestResults testRequestContextOnGracefulFailure(ExecutionIsolationStrategy isolation, final Scheduler userScheduler) {
    final RequestContextTestResults results = new RequestContextTestResults();
    final TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
    TestHystrixObservableCommand<Boolean> command = new TestHystrixObservableCommand<Boolean>(TestHystrixObservableCommand.testPropsBuilder(circuitBreaker).setCommandPropertiesDefaults(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter().withExecutionIsolationStrategy(isolation))) {

        @Override
        protected Observable<Boolean> construct() {
            return Observable.create(new OnSubscribe<Boolean>() {

                @Override
                public void call(Subscriber<? super Boolean> s) {
                    results.isContextInitialized.set(HystrixRequestContext.isCurrentThreadInitialized());
                    results.originThread.set(Thread.currentThread());
                    s.onError(new RuntimeException("graceful onError"));
                }
            }).subscribeOn(userScheduler);
        }
    };
    results.command = command;
    command.toObservable().doOnEach(new Action1<Notification<? super Boolean>>() {

        @Override
        public void call(Notification<? super Boolean> n) {
            results.isContextInitializedObserveOn.set(HystrixRequestContext.isCurrentThreadInitialized());
            results.observeOnThread.set(Thread.currentThread());
        }
    }).subscribe(results.ts);
    results.ts.awaitTerminalEvent();
    System.out.println("Run => Initialized: " + results.isContextInitialized.get() + "  Thread: " + results.originThread.get());
    System.out.println("Observed => Initialized: " + results.isContextInitializedObserveOn.get() + "  Thread: " + results.observeOnThread.get());
    assertEquals(1, results.ts.getOnErrorEvents().size());
    assertTrue(command.getExecutionTimeInMilliseconds() > -1);
    assertFalse(command.isSuccessfulExecution());
    assertTrue(command.isFailedExecution());
    assertCommandExecutionEvents(command, HystrixEventType.FAILURE, HystrixEventType.FALLBACK_MISSING);
    assertEquals(0, command.metrics.getCurrentConcurrentExecutionCount());
    assertSaneHystrixRequestLog(1);
    return results;
}
Also used : TestCircuitBreaker(com.netflix.hystrix.HystrixCircuitBreakerTest.TestCircuitBreaker) HystrixRuntimeException(com.netflix.hystrix.exception.HystrixRuntimeException) Action1(rx.functions.Action1) TestSubscriber(rx.observers.TestSubscriber) OnSubscribe(rx.Observable.OnSubscribe) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean)

Example 25 with TestCircuitBreaker

use of com.netflix.hystrix.HystrixCircuitBreakerTest.TestCircuitBreaker in project Hystrix by Netflix.

the class HystrixObservableCommandTest method testRequestCache2UsingThreadIsolation.

/**
 * Test Request scoped caching doesn't prevent different ones from executing
 */
@Test
public void testRequestCache2UsingThreadIsolation() {
    TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
    SuccessfulCacheableCommand<String> command1 = new SuccessfulCacheableCommand<String>(circuitBreaker, true, "A");
    SuccessfulCacheableCommand<String> command2 = new SuccessfulCacheableCommand<String>(circuitBreaker, true, "B");
    assertTrue(command1.isCommandRunningInThread());
    Future<String> f1 = command1.observe().toBlocking().toFuture();
    Future<String> f2 = command2.observe().toBlocking().toFuture();
    try {
        assertEquals("A", f1.get());
        assertEquals("B", f2.get());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    assertTrue(command1.executed);
    // both should execute as they are different
    assertTrue(command2.executed);
    assertCommandExecutionEvents(command1, HystrixEventType.EMIT, HystrixEventType.SUCCESS);
    assertCommandExecutionEvents(command2, HystrixEventType.EMIT, HystrixEventType.SUCCESS);
    assertTrue(command2.getExecutionTimeInMilliseconds() > -1);
    assertFalse(command2.isResponseFromCache());
    assertEquals(0, circuitBreaker.metrics.getCurrentConcurrentExecutionCount());
    assertSaneHystrixRequestLog(2);
}
Also used : TestCircuitBreaker(com.netflix.hystrix.HystrixCircuitBreakerTest.TestCircuitBreaker) HystrixRuntimeException(com.netflix.hystrix.exception.HystrixRuntimeException) TimeoutException(java.util.concurrent.TimeoutException) HystrixRuntimeException(com.netflix.hystrix.exception.HystrixRuntimeException) HystrixBadRequestException(com.netflix.hystrix.exception.HystrixBadRequestException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) Test(org.junit.Test)

Aggregations

TestCircuitBreaker (com.netflix.hystrix.HystrixCircuitBreakerTest.TestCircuitBreaker)82 Test (org.junit.Test)70 HystrixRuntimeException (com.netflix.hystrix.exception.HystrixRuntimeException)46 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)43 ExecutionException (java.util.concurrent.ExecutionException)40 HystrixBadRequestException (com.netflix.hystrix.exception.HystrixBadRequestException)37 IOException (java.io.IOException)33 TimeoutException (java.util.concurrent.TimeoutException)33 RejectedExecutionException (java.util.concurrent.RejectedExecutionException)18 CancellationException (java.util.concurrent.CancellationException)17 HystrixContextRunnable (com.netflix.hystrix.strategy.concurrency.HystrixContextRunnable)10 CountDownLatch (java.util.concurrent.CountDownLatch)10 OnSubscribe (rx.Observable.OnSubscribe)7 Action1 (rx.functions.Action1)7 TestSubscriber (rx.observers.TestSubscriber)7 TryableSemaphoreActual (com.netflix.hystrix.AbstractCommand.TryableSemaphoreActual)6 ArrayBlockingQueue (java.util.concurrent.ArrayBlockingQueue)6 AtomicReference (java.util.concurrent.atomic.AtomicReference)5 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)4 TryableSemaphore (com.netflix.hystrix.AbstractCommand.TryableSemaphore)2