Search in sources :

Example 26 with TestCircuitBreaker

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

the class HystrixObservableCommandTest method testRequestContextOnTimeoutWithFallback.

private RequestContextTestResults testRequestContextOnTimeoutWithFallback(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).withExecutionTimeoutInMilliseconds(50))) {

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

                @Override
                public void call(Subscriber<? super Boolean> s) {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                    // ignore the interrupted exception
                    }
                }
            }).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) {
            System.out.println("timeoutWithFallback notification: " + n + "   " + Thread.currentThread());
            results.isContextInitializedObserveOn.set(HystrixRequestContext.isCurrentThreadInitialized());
            results.observeOnThread.set(Thread.currentThread());
        }
    }).subscribe(results.ts);
    results.ts.awaitTerminalEvent();
    System.out.println("Fallback => Initialized: " + results.isContextInitialized.get() + "  Thread: " + results.originThread.get());
    System.out.println("Observed => Initialized: " + results.isContextInitializedObserveOn.get() + "  Thread: " + results.observeOnThread.get());
    assertEquals(1, results.ts.getOnNextEvents().size());
    assertEquals(false, results.ts.getOnNextEvents().get(0));
    assertTrue(command.getExecutionTimeInMilliseconds() > -1);
    assertFalse(command.isSuccessfulExecution());
    assertTrue(command.isResponseTimedOut());
    assertCommandExecutionEvents(command, HystrixEventType.TIMEOUT, 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) TestSubscriber(rx.observers.TestSubscriber) OnSubscribe(rx.Observable.OnSubscribe) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean)

Example 27 with TestCircuitBreaker

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

the class HystrixObservableCommandTest method testRequestContextOnFailureWithFallback.

private RequestContextTestResults testRequestContextOnFailureWithFallback(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))) {

        @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.isFailedExecution());
    assertCommandExecutionEvents(command, HystrixEventType.FAILURE, 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 28 with TestCircuitBreaker

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

the class HystrixObservableCommandTest method testCacheKeyExecutionRequiresRequestVariable.

/**
 * Test that if we try and execute a command with a cacheKey without initializing RequestVariable that it gives an error.
 */
@Test
public void testCacheKeyExecutionRequiresRequestVariable() {
    try {
        /* force the RequestVariable to not be initialized */
        HystrixRequestContext.setContextOnCurrentThread(null);
        TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
        SuccessfulCacheableCommand<String> command = new SuccessfulCacheableCommand<String>(circuitBreaker, true, "one");
        assertEquals("one", command.observe().toBlocking().single());
        SuccessfulCacheableCommand<String> command2 = new SuccessfulCacheableCommand<String>(circuitBreaker, true, "two");
        assertEquals("two", command2.observe().toBlocking().toFuture().get());
        fail("We expect an exception because cacheKey requires RequestVariable.");
        // semaphore isolated
        assertFalse(command.isExecutedInThread());
        assertNull(command.getExecutionException());
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : TestCircuitBreaker(com.netflix.hystrix.HystrixCircuitBreakerTest.TestCircuitBreaker) 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 29 with TestCircuitBreaker

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

the class HystrixObservableCommandTest method testRequestCache3UsingThreadIsolation.

/**
 * Test Request scoped caching with a mixture of commands
 */
@Test
public void testRequestCache3UsingThreadIsolation() {
    TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
    SuccessfulCacheableCommand<String> command1 = new SuccessfulCacheableCommand<String>(circuitBreaker, true, "A");
    SuccessfulCacheableCommand<String> command2 = new SuccessfulCacheableCommand<String>(circuitBreaker, true, "B");
    SuccessfulCacheableCommand<String> command3 = new SuccessfulCacheableCommand<String>(circuitBreaker, true, "A");
    assertTrue(command1.isCommandRunningInThread());
    Future<String> f1 = command1.observe().toBlocking().toFuture();
    Future<String> f2 = command2.observe().toBlocking().toFuture();
    Future<String> f3 = command3.observe().toBlocking().toFuture();
    try {
        assertEquals("A", f1.get());
        assertEquals("B", f2.get());
        assertEquals("A", f3.get());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    assertTrue(command1.executed);
    // both should execute as they are different
    assertTrue(command2.executed);
    // but the 3rd should come from cache
    assertFalse(command3.executed);
    assertCommandExecutionEvents(command1, HystrixEventType.EMIT, HystrixEventType.SUCCESS);
    assertCommandExecutionEvents(command2, HystrixEventType.EMIT, HystrixEventType.SUCCESS);
    assertCommandExecutionEvents(command3, HystrixEventType.EMIT, HystrixEventType.SUCCESS, HystrixEventType.RESPONSE_FROM_CACHE);
    assertTrue(command3.getExecutionTimeInMilliseconds() == -1);
    assertTrue(command3.isResponseFromCache());
    assertEquals(0, circuitBreaker.metrics.getCurrentConcurrentExecutionCount());
    assertSaneHystrixRequestLog(3);
}
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)

Example 30 with TestCircuitBreaker

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

the class HystrixObservableCommandTest method testExecutionFailureWithFallbackImplementedButDisabled.

/**
 ********************* END HystrixObservableCommand-specific SEMAPHORE-ISOLATED Execution Hook Tests ***********************************
 */
/**
 * Test a command execution that fails but has a fallback.
 */
@Test
public void testExecutionFailureWithFallbackImplementedButDisabled() {
    TestHystrixObservableCommand<Boolean> commandEnabled = new KnownFailureTestCommandWithFallback(new TestCircuitBreaker(), true, true);
    try {
        assertEquals(false, commandEnabled.observe().toBlocking().single());
    } catch (Exception e) {
        e.printStackTrace();
        fail("We should have received a response from the fallback.");
    }
    TestHystrixObservableCommand<Boolean> commandDisabled = new KnownFailureTestCommandWithFallback(new TestCircuitBreaker(), false, true);
    try {
        assertEquals(false, commandDisabled.observe().toBlocking().single());
        fail("expect exception thrown");
    } catch (Exception e) {
    // expected
    }
    assertEquals("we failed with a simulated issue", commandDisabled.getFailedExecutionException().getMessage());
    assertTrue(commandDisabled.isFailedExecution());
    assertNotNull(commandDisabled.getExecutionException());
    assertCommandExecutionEvents(commandEnabled, HystrixEventType.FAILURE, HystrixEventType.FALLBACK_EMIT, HystrixEventType.FALLBACK_SUCCESS);
    assertCommandExecutionEvents(commandDisabled, HystrixEventType.FAILURE);
    assertEquals(0, commandDisabled.metrics.getCurrentConcurrentExecutionCount());
    assertSaneHystrixRequestLog(2);
}
Also used : TestCircuitBreaker(com.netflix.hystrix.HystrixCircuitBreakerTest.TestCircuitBreaker) 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)

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