Search in sources :

Example 1 with AssertExtensions.assertThrows

use of io.pravega.test.common.AssertExtensions.assertThrows in project pravega by pravega.

the class SegmentOutputStreamTest method testExceptionSealedCallback.

@Test(timeout = 10000)
public void testExceptionSealedCallback() throws Exception {
    UUID cid = UUID.randomUUID();
    PravegaNodeUri uri = new PravegaNodeUri("endpoint", SERVICE_PORT);
    MockConnectionFactoryImpl cf = new MockConnectionFactoryImpl();
    ScheduledExecutorService executor = mock(ScheduledExecutorService.class);
    // Ensure task submitted to executor is run inline.
    implementAsDirectExecutor(executor);
    cf.setExecutor(executor);
    MockController controller = new MockController(uri.getEndpoint(), uri.getPort(), cf, true);
    ClientConnection connection = mock(ClientConnection.class);
    cf.provideConnection(uri, connection);
    AtomicBoolean shouldThrow = new AtomicBoolean(true);
    // call back which throws an exception.
    Consumer<Segment> exceptionCallback = s -> {
        if (shouldThrow.getAndSet(false)) {
            throw new IllegalStateException();
        }
    };
    @SuppressWarnings("resource") SegmentOutputStreamImpl output = new SegmentOutputStreamImpl(SEGMENT, true, controller, cf, cid, exceptionCallback, RETRY_SCHEDULE, DelegationTokenProviderFactory.createWithEmptyToken());
    output.reconnect();
    verify(connection).send(new SetupAppend(output.getRequestId(), cid, SEGMENT, ""));
    cf.getProcessor(uri).appendSetup(new AppendSetup(output.getRequestId(), SEGMENT, cid, 0));
    ByteBuffer data = getBuffer("test");
    CompletableFuture<Void> ack = new CompletableFuture<>();
    output.write(PendingEvent.withoutHeader(null, data, ack));
    assertEquals(false, ack.isDone());
    Mockito.doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            cf.getProcessor(uri).appendSetup(new AppendSetup(output.getRequestId(), SEGMENT, cid, 0));
            return null;
        }
    }).when(connection).send(new SetupAppend(3, cid, SEGMENT, ""));
    AssertExtensions.assertBlocks(() -> {
        AssertExtensions.assertThrows(SegmentSealedException.class, () -> output.flush());
    }, () -> {
        cf.getProcessor(uri).segmentIsSealed(new WireCommands.SegmentIsSealed(output.getRequestId(), SEGMENT, "SomeException", 1));
        output.getUnackedEventsOnSeal();
    });
    verify(connection).send(new WireCommands.KeepAlive());
    verify(connection).send(new Append(SEGMENT, cid, 1, 1, Unpooled.wrappedBuffer(data), null, output.getRequestId()));
    assertEquals(false, ack.isDone());
}
Also used : ArgumentMatchers(org.mockito.ArgumentMatchers) Retry(io.pravega.common.util.Retry) AssertExtensions(io.pravega.test.common.AssertExtensions) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) Cleanup(lombok.Cleanup) ByteBuffer(java.nio.ByteBuffer) Unpooled(io.netty.buffer.Unpooled) Mockito.doThrow(org.mockito.Mockito.doThrow) MockController(io.pravega.client.stream.mock.MockController) ClientConnection(io.pravega.client.connection.impl.ClientConnection) Mockito.verifyNoMoreInteractions(org.mockito.Mockito.verifyNoMoreInteractions) AccessOperation(io.pravega.shared.security.auth.AccessOperation) Mockito.doAnswer(org.mockito.Mockito.doAnswer) PravegaNodeUri(io.pravega.shared.protocol.netty.PravegaNodeUri) Assert.fail(org.junit.Assert.fail) LeakDetectorTestSuite(io.pravega.test.common.LeakDetectorTestSuite) AppendSetup(io.pravega.shared.protocol.netty.WireCommands.AppendSetup) AssertExtensions.assertThrows(io.pravega.test.common.AssertExtensions.assertThrows) DelegationTokenProviderFactory(io.pravega.client.security.auth.DelegationTokenProviderFactory) UUID(java.util.UUID) RetriesExhaustedException(io.pravega.common.util.RetriesExhaustedException) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Assert.assertFalse(org.junit.Assert.assertFalse) Mockito.inOrder(org.mockito.Mockito.inOrder) Futures(io.pravega.common.concurrent.Futures) ReplyProcessor(io.pravega.shared.protocol.netty.ReplyProcessor) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) ConnectionFailedException(io.pravega.shared.protocol.netty.ConnectionFailedException) Exceptions(io.pravega.common.Exceptions) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Callable(java.util.concurrent.Callable) CompletableFuture(java.util.concurrent.CompletableFuture) Mockito.spy(org.mockito.Mockito.spy) PendingEvent(io.pravega.client.stream.impl.PendingEvent) Append(io.pravega.shared.protocol.netty.Append) Answer(org.mockito.stubbing.Answer) SetupAppend(io.pravega.shared.protocol.netty.WireCommands.SetupAppend) InvocationOnMock(org.mockito.invocation.InvocationOnMock) ImmutableList(com.google.common.collect.ImmutableList) CompletedCallback(io.pravega.client.connection.impl.ClientConnection.CompletedCallback) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) ReusableLatch(io.pravega.common.util.ReusableLatch) RetryWithBackoff(io.pravega.common.util.Retry.RetryWithBackoff) InOrder(org.mockito.InOrder) ConnectionPool(io.pravega.client.connection.impl.ConnectionPool) MockConnectionFactoryImpl(io.pravega.client.stream.mock.MockConnectionFactoryImpl) lombok.val(lombok.val) Assert.assertTrue(org.junit.Assert.assertTrue) IOException(java.io.IOException) Test(org.junit.Test) Mockito.times(org.mockito.Mockito.times) WireCommands(io.pravega.shared.protocol.netty.WireCommands) Mockito.verify(org.mockito.Mockito.verify) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) Mockito(org.mockito.Mockito) Mockito.never(org.mockito.Mockito.never) InlineExecutor(io.pravega.test.common.InlineExecutor) ExecutorServiceHelpers(io.pravega.common.concurrent.ExecutorServiceHelpers) Collections(java.util.Collections) Mockito.reset(org.mockito.Mockito.reset) Assert.assertEquals(org.junit.Assert.assertEquals) CompletableFuture(java.util.concurrent.CompletableFuture) PravegaNodeUri(io.pravega.shared.protocol.netty.PravegaNodeUri) MockConnectionFactoryImpl(io.pravega.client.stream.mock.MockConnectionFactoryImpl) SetupAppend(io.pravega.shared.protocol.netty.WireCommands.SetupAppend) ClientConnection(io.pravega.client.connection.impl.ClientConnection) UUID(java.util.UUID) WireCommands(io.pravega.shared.protocol.netty.WireCommands) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) ByteBuffer(java.nio.ByteBuffer) AppendSetup(io.pravega.shared.protocol.netty.WireCommands.AppendSetup) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Append(io.pravega.shared.protocol.netty.Append) SetupAppend(io.pravega.shared.protocol.netty.WireCommands.SetupAppend) InvocationOnMock(org.mockito.invocation.InvocationOnMock) MockController(io.pravega.client.stream.mock.MockController) Test(org.junit.Test)

Example 2 with AssertExtensions.assertThrows

use of io.pravega.test.common.AssertExtensions.assertThrows in project pravega by pravega.

the class SegmentOutputStreamTest method testFlushIsBlockedUntilCallBackInvoked.

/**
 * This test ensures that the flush() on a segment is released only after sealed segment callback is invoked.
 * The callback implemented in EventStreamWriter appends this segment to its sealedSegmentQueue.
 */
@Test(timeout = 10000)
public void testFlushIsBlockedUntilCallBackInvoked() throws Exception {
    // Segment sealed callback will finish execution only when the latch is released;
    ReusableLatch latch = new ReusableLatch(false);
    final Consumer<Segment> segmentSealedCallback = segment -> Exceptions.handleInterrupted(() -> latch.await());
    UUID cid = UUID.randomUUID();
    PravegaNodeUri uri = new PravegaNodeUri("endpoint", SERVICE_PORT);
    MockConnectionFactoryImpl cf = new MockConnectionFactoryImpl();
    cf.setExecutor(executorService());
    MockController controller = new MockController(uri.getEndpoint(), uri.getPort(), cf, true);
    ClientConnection connection = mock(ClientConnection.class);
    cf.provideConnection(uri, connection);
    InOrder order = Mockito.inOrder(connection);
    @SuppressWarnings("resource") SegmentOutputStreamImpl output = new SegmentOutputStreamImpl(SEGMENT, true, controller, cf, cid, segmentSealedCallback, RETRY_SCHEDULE, DelegationTokenProviderFactory.createWithEmptyToken());
    output.reconnect();
    order.verify(connection).send(new SetupAppend(output.getRequestId(), cid, SEGMENT, ""));
    cf.getProcessor(uri).appendSetup(new AppendSetup(output.getRequestId(), SEGMENT, cid, 0));
    ByteBuffer data = getBuffer("test");
    CompletableFuture<Void> ack = new CompletableFuture<>();
    output.write(PendingEvent.withoutHeader(null, data, ack));
    order.verify(connection).send(new Append(SEGMENT, cid, 1, 1, Unpooled.wrappedBuffer(data), null, output.getRequestId()));
    assertEquals(false, ack.isDone());
    @Cleanup("shutdownNow") ScheduledExecutorService executor = ExecutorServiceHelpers.newScheduledThreadPool(1, "netty-callback");
    // simulate a SegmentIsSealed WireCommand from SegmentStore.
    executor.submit(() -> cf.getProcessor(uri).segmentIsSealed(new WireCommands.SegmentIsSealed(output.getRequestId(), SEGMENT, "SomeException", 1)));
    AssertExtensions.assertBlocks(() -> {
        AssertExtensions.assertThrows(SegmentSealedException.class, () -> output.flush());
    }, () -> latch.release());
    AssertExtensions.assertThrows(SegmentSealedException.class, () -> output.flush());
}
Also used : ArgumentMatchers(org.mockito.ArgumentMatchers) Retry(io.pravega.common.util.Retry) AssertExtensions(io.pravega.test.common.AssertExtensions) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) Cleanup(lombok.Cleanup) ByteBuffer(java.nio.ByteBuffer) Unpooled(io.netty.buffer.Unpooled) Mockito.doThrow(org.mockito.Mockito.doThrow) MockController(io.pravega.client.stream.mock.MockController) ClientConnection(io.pravega.client.connection.impl.ClientConnection) Mockito.verifyNoMoreInteractions(org.mockito.Mockito.verifyNoMoreInteractions) AccessOperation(io.pravega.shared.security.auth.AccessOperation) Mockito.doAnswer(org.mockito.Mockito.doAnswer) PravegaNodeUri(io.pravega.shared.protocol.netty.PravegaNodeUri) Assert.fail(org.junit.Assert.fail) LeakDetectorTestSuite(io.pravega.test.common.LeakDetectorTestSuite) AppendSetup(io.pravega.shared.protocol.netty.WireCommands.AppendSetup) AssertExtensions.assertThrows(io.pravega.test.common.AssertExtensions.assertThrows) DelegationTokenProviderFactory(io.pravega.client.security.auth.DelegationTokenProviderFactory) UUID(java.util.UUID) RetriesExhaustedException(io.pravega.common.util.RetriesExhaustedException) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Assert.assertFalse(org.junit.Assert.assertFalse) Mockito.inOrder(org.mockito.Mockito.inOrder) Futures(io.pravega.common.concurrent.Futures) ReplyProcessor(io.pravega.shared.protocol.netty.ReplyProcessor) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) ConnectionFailedException(io.pravega.shared.protocol.netty.ConnectionFailedException) Exceptions(io.pravega.common.Exceptions) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Callable(java.util.concurrent.Callable) CompletableFuture(java.util.concurrent.CompletableFuture) Mockito.spy(org.mockito.Mockito.spy) PendingEvent(io.pravega.client.stream.impl.PendingEvent) Append(io.pravega.shared.protocol.netty.Append) Answer(org.mockito.stubbing.Answer) SetupAppend(io.pravega.shared.protocol.netty.WireCommands.SetupAppend) InvocationOnMock(org.mockito.invocation.InvocationOnMock) ImmutableList(com.google.common.collect.ImmutableList) CompletedCallback(io.pravega.client.connection.impl.ClientConnection.CompletedCallback) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) ReusableLatch(io.pravega.common.util.ReusableLatch) RetryWithBackoff(io.pravega.common.util.Retry.RetryWithBackoff) InOrder(org.mockito.InOrder) ConnectionPool(io.pravega.client.connection.impl.ConnectionPool) MockConnectionFactoryImpl(io.pravega.client.stream.mock.MockConnectionFactoryImpl) lombok.val(lombok.val) Assert.assertTrue(org.junit.Assert.assertTrue) IOException(java.io.IOException) Test(org.junit.Test) Mockito.times(org.mockito.Mockito.times) WireCommands(io.pravega.shared.protocol.netty.WireCommands) Mockito.verify(org.mockito.Mockito.verify) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) Mockito(org.mockito.Mockito) Mockito.never(org.mockito.Mockito.never) InlineExecutor(io.pravega.test.common.InlineExecutor) ExecutorServiceHelpers(io.pravega.common.concurrent.ExecutorServiceHelpers) Collections(java.util.Collections) Mockito.reset(org.mockito.Mockito.reset) Assert.assertEquals(org.junit.Assert.assertEquals) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) InOrder(org.mockito.InOrder) ByteBuffer(java.nio.ByteBuffer) Cleanup(lombok.Cleanup) AppendSetup(io.pravega.shared.protocol.netty.WireCommands.AppendSetup) CompletableFuture(java.util.concurrent.CompletableFuture) ReusableLatch(io.pravega.common.util.ReusableLatch) Append(io.pravega.shared.protocol.netty.Append) SetupAppend(io.pravega.shared.protocol.netty.WireCommands.SetupAppend) PravegaNodeUri(io.pravega.shared.protocol.netty.PravegaNodeUri) MockConnectionFactoryImpl(io.pravega.client.stream.mock.MockConnectionFactoryImpl) SetupAppend(io.pravega.shared.protocol.netty.WireCommands.SetupAppend) MockController(io.pravega.client.stream.mock.MockController) ClientConnection(io.pravega.client.connection.impl.ClientConnection) UUID(java.util.UUID) Test(org.junit.Test)

Example 3 with AssertExtensions.assertThrows

use of io.pravega.test.common.AssertExtensions.assertThrows in project pravega by pravega.

the class FuturesTests method testDoWhileLoopWithCondition.

@Test
public void testDoWhileLoopWithCondition() {
    final int maxLoops = 10;
    final int expectedResult = maxLoops * (maxLoops - 1) / 2;
    AtomicInteger loopCounter = new AtomicInteger();
    AtomicInteger accumulator = new AtomicInteger();
    // 1. Verify this is actually a do-while loop vs a regular while loop.
    Futures.doWhileLoop(() -> {
        accumulator.incrementAndGet();
        return CompletableFuture.completedFuture(0);
    }, // Only one iteration.
    x -> false, ForkJoinPool.commonPool()).join();
    Assert.assertEquals("Unexpected result for loop without a specific accumulator.", 1, accumulator.get());
    // 2. Successful execution.
    loopCounter.set(0);
    accumulator.set(0);
    Futures.doWhileLoop(() -> {
        int i = loopCounter.get();
        accumulator.addAndGet(i);
        return CompletableFuture.completedFuture(loopCounter.incrementAndGet());
    }, x -> x < maxLoops, ForkJoinPool.commonPool()).join();
    Assert.assertEquals("Unexpected result for loop without a specific accumulator.", expectedResult, accumulator.get());
    // 3. With exceptions.
    loopCounter.set(0);
    accumulator.set(0);
    CompletableFuture<Void> loopFuture = Futures.doWhileLoop(() -> {
        if (loopCounter.incrementAndGet() % 3 == 0) {
            throw new IntentionalException();
        } else {
            accumulator.addAndGet(loopCounter.get());
            return CompletableFuture.completedFuture(loopCounter.get());
        }
    }, x -> x < maxLoops, ForkJoinPool.commonPool());
    AssertExtensions.assertThrows("doWhileLoop() did not return a failed Future when one of the loopBody calls returned a failed Future.", loopFuture::join, ex -> ex instanceof IntentionalException);
    Assert.assertEquals("Unexpected value accumulated until loop was interrupted.", 3, accumulator.get());
}
Also used : IntStream(java.util.stream.IntStream) Arrays(java.util.Arrays) AssertExtensions(io.pravega.test.common.AssertExtensions) CompletableFuture.completedFuture(java.util.concurrent.CompletableFuture.completedFuture) Exceptions(io.pravega.common.Exceptions) TimeoutException(java.util.concurrent.TimeoutException) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) Supplier(java.util.function.Supplier) Futures.exceptionallyExpecting(io.pravega.common.concurrent.Futures.exceptionallyExpecting) ArrayList(java.util.ArrayList) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Duration(java.time.Duration) Map(java.util.Map) Futures.getThrowingException(io.pravega.common.concurrent.Futures.getThrowingException) Assert.fail(org.junit.Assert.fail) Futures.getAndHandleExceptions(io.pravega.common.concurrent.Futures.getAndHandleExceptions) Predicate(java.util.function.Predicate) Collection(java.util.Collection) IntentionalException(io.pravega.test.common.IntentionalException) lombok.val(lombok.val) AssertExtensions.assertThrows(io.pravega.test.common.AssertExtensions.assertThrows) Test(org.junit.Test) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) Collectors(java.util.stream.Collectors) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) ThreadPooledTestSuite(io.pravega.test.common.ThreadPooledTestSuite) ForkJoinPool(java.util.concurrent.ForkJoinPool) Assert.assertFalse(org.junit.Assert.assertFalse) RandomFactory(io.pravega.common.hash.RandomFactory) Assert(org.junit.Assert) Collections(java.util.Collections) Futures.exceptionallyComposeExpecting(io.pravega.common.concurrent.Futures.exceptionallyComposeExpecting) Assert.assertEquals(org.junit.Assert.assertEquals) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) IntentionalException(io.pravega.test.common.IntentionalException) Test(org.junit.Test)

Aggregations

Exceptions (io.pravega.common.Exceptions)3 AssertExtensions (io.pravega.test.common.AssertExtensions)3 AssertExtensions.assertThrows (io.pravega.test.common.AssertExtensions.assertThrows)3 Collections (java.util.Collections)3 List (java.util.List)3 CompletableFuture (java.util.concurrent.CompletableFuture)3 TimeUnit (java.util.concurrent.TimeUnit)3 lombok.val (lombok.val)3 Assert.assertEquals (org.junit.Assert.assertEquals)3 Assert.assertFalse (org.junit.Assert.assertFalse)3 Assert.fail (org.junit.Assert.fail)3 Test (org.junit.Test)3 ImmutableList (com.google.common.collect.ImmutableList)2 Unpooled (io.netty.buffer.Unpooled)2 ClientConnection (io.pravega.client.connection.impl.ClientConnection)2 CompletedCallback (io.pravega.client.connection.impl.ClientConnection.CompletedCallback)2 ConnectionPool (io.pravega.client.connection.impl.ConnectionPool)2 DelegationTokenProviderFactory (io.pravega.client.security.auth.DelegationTokenProviderFactory)2 PendingEvent (io.pravega.client.stream.impl.PendingEvent)2 MockConnectionFactoryImpl (io.pravega.client.stream.mock.MockConnectionFactoryImpl)2