Search in sources :

Example 46 with Assert.assertEquals

use of org.junit.Assert.assertEquals in project flow by vaadin.

the class BinderConverterValidatorTest method save_beanValidationErrorsWithConverter.

@Test(expected = ValidationException.class)
public void save_beanValidationErrorsWithConverter() throws ValidationException {
    Binder<Person> binder = new Binder<>();
    binder.forField(ageField).withConverter(new StringToIntegerConverter("Can't convert")).bind(Person::getAge, Person::setAge);
    binder.withValidator(Validator.from(person -> false, "b"));
    Person person = new Person();
    ageField.setValue("1");
    try {
        binder.writeBean(person);
    } finally {
        // Bean should have been updated for item validation but reverted
        Assert.assertEquals(0, person.getAge());
    }
}
Also used : HasValue(com.vaadin.flow.component.HasValue) CurrentInstance(com.vaadin.flow.internal.CurrentInstance) Person(com.vaadin.flow.tests.data.bean.Person) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) Assert.assertThat(org.junit.Assert.assertThat) HasValidation(com.vaadin.flow.component.HasValidation) Map(java.util.Map) BindingBuilder(com.vaadin.flow.data.binder.Binder.BindingBuilder) Matchers.hasSize(org.hamcrest.Matchers.hasSize) SerializablePredicate(com.vaadin.flow.function.SerializablePredicate) Before(org.junit.Before) StringToIntegerConverter(com.vaadin.flow.data.converter.StringToIntegerConverter) Assert.assertNotNull(org.junit.Assert.assertNotNull) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) Matchers.isEmptyString(org.hamcrest.Matchers.isEmptyString) Serializable(java.io.Serializable) List(java.util.List) Assert.assertNull(org.junit.Assert.assertNull) Assert.assertFalse(org.junit.Assert.assertFalse) NotEmptyValidator(com.vaadin.flow.data.validator.NotEmptyValidator) TestLabel(com.vaadin.flow.data.binder.testcomponents.TestLabel) Assert(org.junit.Assert) Binding(com.vaadin.flow.data.binder.Binder.Binding) TestTextField(com.vaadin.flow.data.binder.testcomponents.TestTextField) Assert.assertEquals(org.junit.Assert.assertEquals) StringToIntegerConverter(com.vaadin.flow.data.converter.StringToIntegerConverter) Person(com.vaadin.flow.tests.data.bean.Person) Test(org.junit.Test)

Example 47 with Assert.assertEquals

use of org.junit.Assert.assertEquals in project flow by vaadin.

the class BinderConverterValidatorTest method saveIfValid_beanValidationErrors.

@Test
public void saveIfValid_beanValidationErrors() {
    Binder<Person> binder = new Binder<>();
    binder.forField(nameField).bind(Person::getFirstName, Person::setFirstName);
    String msg = "foo";
    binder.withValidator(Validator.from(prsn -> prsn.getAddress() != null || prsn.getEmail() != null, msg));
    Person person = new Person();
    person.setFirstName("foo");
    nameField.setValue("");
    Assert.assertFalse(binder.writeBeanIfValid(person));
    Assert.assertEquals("foo", person.getFirstName());
}
Also used : HasValue(com.vaadin.flow.component.HasValue) CurrentInstance(com.vaadin.flow.internal.CurrentInstance) Person(com.vaadin.flow.tests.data.bean.Person) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) Assert.assertThat(org.junit.Assert.assertThat) HasValidation(com.vaadin.flow.component.HasValidation) Map(java.util.Map) BindingBuilder(com.vaadin.flow.data.binder.Binder.BindingBuilder) Matchers.hasSize(org.hamcrest.Matchers.hasSize) SerializablePredicate(com.vaadin.flow.function.SerializablePredicate) Before(org.junit.Before) StringToIntegerConverter(com.vaadin.flow.data.converter.StringToIntegerConverter) Assert.assertNotNull(org.junit.Assert.assertNotNull) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) Matchers.isEmptyString(org.hamcrest.Matchers.isEmptyString) Serializable(java.io.Serializable) List(java.util.List) Assert.assertNull(org.junit.Assert.assertNull) Assert.assertFalse(org.junit.Assert.assertFalse) NotEmptyValidator(com.vaadin.flow.data.validator.NotEmptyValidator) TestLabel(com.vaadin.flow.data.binder.testcomponents.TestLabel) Assert(org.junit.Assert) Binding(com.vaadin.flow.data.binder.Binder.Binding) TestTextField(com.vaadin.flow.data.binder.testcomponents.TestTextField) Assert.assertEquals(org.junit.Assert.assertEquals) Matchers.isEmptyString(org.hamcrest.Matchers.isEmptyString) Person(com.vaadin.flow.tests.data.bean.Person) Test(org.junit.Test)

Example 48 with Assert.assertEquals

use of org.junit.Assert.assertEquals in project flow by vaadin.

the class BootstrapHandlerTest method uiInitialization_changingListenersOnEventWorks.

// UIInitListeners
@Test
public void uiInitialization_changingListenersOnEventWorks() {
    BootstrapHandler bootstrapHandler = new BootstrapHandler();
    VaadinResponse response = Mockito.mock(VaadinResponse.class);
    AtomicReference<UI> uiReference = new AtomicReference<>();
    Registration registration = service.addUIInitListener(event -> service.addUIInitListener(laterEvent -> uiReference.compareAndSet(null, laterEvent.getUI())));
    bootstrapHandler.createAndInitUI(TestUI.class, createVaadinRequest(), response, session);
    Assert.assertEquals("Event UI didn't match initialized UI instance.", null, uiReference.get());
    // unregister listener
    registration.remove();
    service.addUIInitListener(event -> registration.remove());
    final BootstrapContext secondInit = bootstrapHandler.createAndInitUI(TestUI.class, createVaadinRequest(), response, session);
    Assert.assertEquals("Event UI didn't match initialized UI instance.", secondInit.getUI(), uiReference.get());
}
Also used : CoreMatchers(org.hamcrest.CoreMatchers) Arrays(java.util.Arrays) Component(com.vaadin.flow.component.Component) JavaScript(com.vaadin.flow.component.dependency.JavaScript) Inline(com.vaadin.flow.component.page.Inline) BootstrapContext(com.vaadin.flow.server.BootstrapHandler.BootstrapContext) URL(java.net.URL) TargetElement(com.vaadin.flow.component.page.TargetElement) Registration(com.vaadin.flow.shared.Registration) INDEX_HTML(com.vaadin.flow.server.frontend.FrontendUtils.INDEX_HTML) PageTitle(com.vaadin.flow.router.PageTitle) Router(com.vaadin.flow.router.Router) Route(com.vaadin.flow.router.Route) RouteAlias(com.vaadin.flow.router.RouteAlias) VAADIN_WEBAPP_RESOURCES(com.vaadin.flow.server.Constants.VAADIN_WEBAPP_RESOURCES) PushMode(com.vaadin.flow.shared.communication.PushMode) ByteArrayInputStream(java.io.ByteArrayInputStream) Locale(java.util.Locale) Element(org.jsoup.nodes.Element) After(org.junit.After) Lookup(com.vaadin.flow.di.Lookup) UI(com.vaadin.flow.component.UI) VAADIN_MAPPING(com.vaadin.flow.server.Constants.VAADIN_MAPPING) Set(java.util.Set) StandardCharsets(java.nio.charset.StandardCharsets) IOUtils(org.apache.commons.io.IOUtils) List(java.util.List) ApplicationConfiguration(com.vaadin.flow.server.startup.ApplicationConfiguration) MatcherAssert(org.hamcrest.MatcherAssert) Assert.assertFalse(org.junit.Assert.assertFalse) Document(org.jsoup.nodes.Document) LoadMode(com.vaadin.flow.shared.ui.LoadMode) BodySize(com.vaadin.flow.component.page.BodySize) Optional(java.util.Optional) Elements(org.jsoup.select.Elements) ApplicationConstants(com.vaadin.flow.shared.ApplicationConstants) MockDeploymentConfiguration(com.vaadin.tests.util.MockDeploymentConfiguration) TestRouteRegistry(com.vaadin.flow.router.TestRouteRegistry) VaadinUriResolver(com.vaadin.flow.shared.VaadinUriResolver) Dependency(com.vaadin.flow.shared.ui.Dependency) AtomicReference(java.util.concurrent.atomic.AtomicReference) LinkedHashMap(java.util.LinkedHashMap) HttpServletRequest(javax.servlet.http.HttpServletRequest) Tag(com.vaadin.flow.component.Tag) Location(com.vaadin.flow.router.Location) Before(org.junit.Before) QueryParameters(com.vaadin.flow.router.QueryParameters) Text(com.vaadin.flow.component.Text) RouterLayout(com.vaadin.flow.router.RouterLayout) Html(com.vaadin.flow.component.Html) StyleSheet(com.vaadin.flow.component.dependency.StyleSheet) Meta(com.vaadin.flow.component.page.Meta) TestVaadinServletService(com.vaadin.flow.server.MockServletServiceSessionSetup.TestVaadinServletService) FileOutputStream(java.io.FileOutputStream) Assert.assertTrue(org.junit.Assert.assertTrue) IOException(java.io.IOException) Test(org.junit.Test) ResourceProvider(com.vaadin.flow.di.ResourceProvider) Mockito.when(org.mockito.Mockito.when) File(java.io.File) Mockito(org.mockito.Mockito) Rule(org.junit.Rule) RouteConfiguration(com.vaadin.flow.router.RouteConfiguration) FeatureFlags(com.vaadin.experimental.FeatureFlags) Assert(org.junit.Assert) Collections(java.util.Collections) Viewport(com.vaadin.flow.component.page.Viewport) TemporaryFolder(org.junit.rules.TemporaryFolder) ParentLayout(com.vaadin.flow.router.ParentLayout) Assert.assertEquals(org.junit.Assert.assertEquals) InputStream(java.io.InputStream) UI(com.vaadin.flow.component.UI) Registration(com.vaadin.flow.shared.Registration) AtomicReference(java.util.concurrent.atomic.AtomicReference) BootstrapContext(com.vaadin.flow.server.BootstrapHandler.BootstrapContext) Test(org.junit.Test)

Example 49 with Assert.assertEquals

use of org.junit.Assert.assertEquals in project pravega by pravega.

the class StreamTransactionMetadataTasksTest method failOverTests.

@Test(timeout = 60000)
public void failOverTests() throws Exception {
    // Create mock writer objects.
    EventStreamWriterMock<CommitEvent> commitWriter = new EventStreamWriterMock<>();
    EventStreamWriterMock<AbortEvent> abortWriter = new EventStreamWriterMock<>();
    EventStreamReader<CommitEvent> commitReader = commitWriter.getReader();
    EventStreamReader<AbortEvent> abortReader = abortWriter.getReader();
    txnTasks = new StreamTransactionMetadataTasks(streamStore, segmentHelperMock, executor, "host", GrpcAuthHelper.getDisabledAuthHelper());
    txnTasks.initializeStreamWriters(commitWriter, abortWriter);
    consumer = new ControllerService(kvtStore, kvtMetadataTasks, streamStore, bucketStore, streamMetadataTasks, txnTasks, segmentHelperMock, executor, null, requestTracker);
    // Create test scope and stream.
    final ScalingPolicy policy1 = ScalingPolicy.fixed(2);
    final StreamConfiguration configuration1 = StreamConfiguration.builder().scalingPolicy(policy1).build();
    Assert.assertEquals(Controller.CreateScopeStatus.Status.SUCCESS, consumer.createScope(SCOPE, 0L).join().getStatus());
    Assert.assertEquals(Controller.CreateStreamStatus.Status.SUCCESS, streamMetadataTasks.createStream(SCOPE, STREAM, configuration1, System.currentTimeMillis(), 0L).join());
    // Set up txn task for creating transactions from a failedHost.
    @Cleanup StreamTransactionMetadataTasks failedTxnTasks = new StreamTransactionMetadataTasks(streamStore, segmentHelperMock, executor, "failedHost", GrpcAuthHelper.getDisabledAuthHelper());
    failedTxnTasks.initializeStreamWriters(new EventStreamWriterMock<>(), new EventStreamWriterMock<>());
    // Create 3 transactions from failedHost.
    VersionedTransactionData tx1 = failedTxnTasks.createTxn(SCOPE, STREAM, 10000, 0L, 0L).join().getKey();
    VersionedTransactionData tx2 = failedTxnTasks.createTxn(SCOPE, STREAM, 10000, 0L, 0L).join().getKey();
    VersionedTransactionData tx3 = failedTxnTasks.createTxn(SCOPE, STREAM, 10000, 0L, 0L).join().getKey();
    VersionedTransactionData tx4 = failedTxnTasks.createTxn(SCOPE, STREAM, 10000, 0L, 0L).join().getKey();
    // Ping another txn from failedHost.
    PingTxnStatus pingStatus = failedTxnTasks.pingTxn(SCOPE, STREAM, tx4.getId(), 10000, 0L).join();
    VersionedTransactionData tx4get = streamStore.getTransactionData(SCOPE, STREAM, tx4.getId(), null, executor).join();
    // Validate versions of all txn
    Assert.assertEquals(0, tx1.getVersion().asIntVersion().getIntValue());
    Assert.assertEquals(0, tx2.getVersion().asIntVersion().getIntValue());
    Assert.assertEquals(0, tx3.getVersion().asIntVersion().getIntValue());
    Assert.assertEquals(1, tx4get.getVersion().asIntVersion().getIntValue());
    Assert.assertEquals(PingTxnStatus.Status.OK, pingStatus.getStatus());
    // Validate the txn index.
    Assert.assertEquals(1, streamStore.listHostsOwningTxn().join().size());
    // Change state of one txn to COMMITTING.
    TxnStatus txnStatus2 = streamStore.sealTransaction(SCOPE, STREAM, tx2.getId(), true, Optional.empty(), "", Long.MIN_VALUE, null, executor).thenApply(AbstractMap.SimpleEntry::getKey).join();
    Assert.assertEquals(TxnStatus.COMMITTING, txnStatus2);
    // Change state of another txn to ABORTING.
    TxnStatus txnStatus3 = streamStore.sealTransaction(SCOPE, STREAM, tx3.getId(), false, Optional.empty(), "", Long.MIN_VALUE, null, executor).thenApply(AbstractMap.SimpleEntry::getKey).join();
    Assert.assertEquals(TxnStatus.ABORTING, txnStatus3);
    // Create transaction tasks for sweeping txns from failedHost.
    txnTasks = new StreamTransactionMetadataTasks(streamStore, segmentHelperMock, executor, "host", GrpcAuthHelper.getDisabledAuthHelper());
    TxnSweeper txnSweeper = new TxnSweeper(streamStore, txnTasks, 100, executor);
    // Before initializing, txnSweeper.sweepFailedHosts would throw an error
    AssertExtensions.assertFutureThrows("IllegalStateException before initialization", txnSweeper.sweepFailedProcesses(() -> Collections.singleton("host")), ex -> ex instanceof IllegalStateException);
    // Initialize stream writers.
    txnTasks.initializeStreamWriters(commitWriter, abortWriter);
    // Validate that txnTasks is ready.
    assertTrue(txnTasks.isReady());
    // Sweep txns that were being managed by failedHost.
    txnSweeper.sweepFailedProcesses(() -> Collections.singleton("host")).join();
    // Validate that sweeping completes correctly.
    Set<String> listOfHosts = streamStore.listHostsOwningTxn().join();
    Assert.assertEquals(1, listOfHosts.size());
    Assert.assertTrue(listOfHosts.contains("host"));
    Assert.assertEquals(TxnStatus.OPEN, streamStore.transactionStatus(SCOPE, STREAM, tx1.getId(), null, executor).join());
    Assert.assertEquals(TxnStatus.COMMITTING, streamStore.transactionStatus(SCOPE, STREAM, tx2.getId(), null, executor).join());
    Assert.assertEquals(TxnStatus.ABORTING, streamStore.transactionStatus(SCOPE, STREAM, tx3.getId(), null, executor).join());
    Assert.assertEquals(TxnStatus.OPEN, streamStore.transactionStatus(SCOPE, STREAM, tx4.getId(), null, executor).join());
    VersionedTransactionData txnData = streamStore.getTransactionData(SCOPE, STREAM, tx1.getId(), null, executor).join();
    Assert.assertEquals(1, txnData.getVersion().asIntVersion().getIntValue());
    txnData = streamStore.getTransactionData(SCOPE, STREAM, tx4.getId(), null, executor).join();
    Assert.assertEquals(2, txnData.getVersion().asIntVersion().getIntValue());
    // Create commit and abort event processors.
    BlockingQueue<CommitEvent> processedCommitEvents = new LinkedBlockingQueue<>();
    BlockingQueue<AbortEvent> processedAbortEvents = new LinkedBlockingQueue<>();
    createEventProcessor("commitRG", "commitStream", commitReader, commitWriter, () -> new ConcurrentEventProcessor<>(new CommitRequestHandler(streamStore, streamMetadataTasks, txnTasks, bucketStore, executor, processedCommitEvents), executor));
    createEventProcessor("abortRG", "abortStream", abortReader, abortWriter, () -> new ConcurrentEventProcessor<>(new AbortRequestHandler(streamStore, streamMetadataTasks, executor, processedAbortEvents), executor));
    // Wait until the commit event is processed and ensure that the txn state is COMMITTED.
    CommitEvent commitEvent = processedCommitEvents.take();
    assertEquals(tx2.getEpoch(), commitEvent.getEpoch());
    assertEquals(TxnStatus.COMMITTED, streamStore.transactionStatus(SCOPE, STREAM, tx2.getId(), null, executor).join());
    // Wait until 3 abort events are processed and ensure that the txn state is ABORTED.
    Predicate<AbortEvent> predicate = event -> event.getTxid().equals(tx1.getId()) || event.getTxid().equals(tx3.getId()) || event.getTxid().equals(tx4.getId());
    AbortEvent abortEvent1 = processedAbortEvents.take();
    assertTrue(predicate.test(abortEvent1));
    AbortEvent abortEvent2 = processedAbortEvents.take();
    assertTrue(predicate.test(abortEvent2));
    AbortEvent abortEvent3 = processedAbortEvents.take();
    assertTrue(predicate.test(abortEvent3));
    assertEquals(TxnStatus.ABORTED, streamStore.transactionStatus(SCOPE, STREAM, tx1.getId(), null, executor).join());
    assertEquals(TxnStatus.ABORTED, streamStore.transactionStatus(SCOPE, STREAM, tx3.getId(), null, executor).join());
    assertEquals(TxnStatus.ABORTED, streamStore.transactionStatus(SCOPE, STREAM, tx4.getId(), null, executor).join());
}
Also used : EventStreamWriter(io.pravega.client.stream.EventStreamWriter) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) Cleanup(lombok.Cleanup) StreamConfiguration(io.pravega.client.stream.StreamConfiguration) CheckpointConfig(io.pravega.controller.eventProcessor.CheckpointConfig) StoreException(io.pravega.controller.store.stream.StoreException) Pair(org.apache.commons.lang3.tuple.Pair) TaskMetadataStore(io.pravega.controller.store.task.TaskMetadataStore) Duration(java.time.Duration) Mockito.doAnswer(org.mockito.Mockito.doAnswer) CancellationException(java.util.concurrent.CancellationException) Set(java.util.Set) BlockingQueue(java.util.concurrent.BlockingQueue) RequestTracker(io.pravega.common.tracing.RequestTracker) ControllerEvent(io.pravega.shared.controller.event.ControllerEvent) KVTableMetadataStore(io.pravega.controller.store.kvtable.KVTableMetadataStore) Slf4j(lombok.extern.slf4j.Slf4j) EventProcessorSystemImpl(io.pravega.controller.eventProcessor.impl.EventProcessorSystemImpl) Assert.assertFalse(org.junit.Assert.assertFalse) StreamMetadataStore(io.pravega.controller.store.stream.StreamMetadataStore) EventStreamWriterMock(io.pravega.controller.mocks.EventStreamWriterMock) Futures(io.pravega.common.concurrent.Futures) GrpcAuthHelper(io.pravega.controller.server.security.auth.GrpcAuthHelper) Mockito.mock(org.mockito.Mockito.mock) CuratorFrameworkFactory(org.apache.curator.framework.CuratorFrameworkFactory) StreamMetrics(io.pravega.controller.metrics.StreamMetrics) StreamStoreFactory(io.pravega.controller.store.stream.StreamStoreFactory) TransactionMetrics(io.pravega.controller.metrics.TransactionMetrics) ConnectionFactory(io.pravega.client.connection.impl.ConnectionFactory) Mock(org.mockito.Mock) Exceptions(io.pravega.common.Exceptions) Mockito.spy(org.mockito.Mockito.spy) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) Answer(org.mockito.stubbing.Answer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) TestingServerStarter(io.pravega.test.common.TestingServerStarter) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) TestingServer(org.apache.curator.test.TestingServer) Before(org.junit.Before) SegmentHelperMock(io.pravega.controller.mocks.SegmentHelperMock) lombok.val(lombok.val) Assert.assertTrue(org.junit.Assert.assertTrue) EventStreamReader(io.pravega.client.stream.EventStreamReader) Test(org.junit.Test) Mockito.times(org.mockito.Mockito.times) TableMetadataTasks(io.pravega.controller.task.KeyValueTable.TableMetadataTasks) TaskStoreFactory(io.pravega.controller.store.task.TaskStoreFactory) Version(io.pravega.controller.store.Version) HostControllerStore(io.pravega.controller.store.host.HostControllerStore) CommitRequestHandler(io.pravega.controller.server.eventProcessor.requesthandlers.CommitRequestHandler) Assert(org.junit.Assert) ScalingPolicy(io.pravega.client.stream.ScalingPolicy) Assert.assertEquals(org.junit.Assert.assertEquals) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) CommitEvent(io.pravega.shared.controller.event.CommitEvent) StreamSegmentRecord(io.pravega.controller.store.stream.records.StreamSegmentRecord) SneakyThrows(lombok.SneakyThrows) AssertExtensions(io.pravega.test.common.AssertExtensions) ReaderGroup(io.pravega.client.stream.ReaderGroup) CheckpointStoreException(io.pravega.controller.store.checkpoint.CheckpointStoreException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ReaderGroupManager(io.pravega.client.admin.ReaderGroupManager) AbortRequestHandler(io.pravega.controller.server.eventProcessor.requesthandlers.AbortRequestHandler) After(org.junit.After) Controller(io.pravega.controller.stream.api.grpc.v1.Controller) ExceptionHandler(io.pravega.controller.eventProcessor.ExceptionHandler) EventProcessorConfig(io.pravega.controller.eventProcessor.EventProcessorConfig) Predicate(java.util.function.Predicate) UUID(java.util.UUID) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) List(java.util.List) CuratorFramework(org.apache.curator.framework.CuratorFramework) ConcurrentEventProcessor(io.pravega.controller.eventProcessor.impl.ConcurrentEventProcessor) Config(io.pravega.controller.util.Config) TxnStatus(io.pravega.controller.store.stream.TxnStatus) VersionedTransactionData(io.pravega.controller.store.stream.VersionedTransactionData) Optional(java.util.Optional) PingTxnStatus(io.pravega.controller.stream.api.grpc.v1.Controller.PingTxnStatus) NotImplementedException(org.apache.commons.lang3.NotImplementedException) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) ArgumentMatchers.anyLong(org.mockito.ArgumentMatchers.anyLong) SegmentHelper(io.pravega.controller.server.SegmentHelper) EventProcessor(io.pravega.controller.eventProcessor.impl.EventProcessor) CheckpointStoreFactory(io.pravega.controller.store.checkpoint.CheckpointStoreFactory) EventProcessorGroupConfigImpl(io.pravega.controller.eventProcessor.impl.EventProcessorGroupConfigImpl) CompletableFuture(java.util.concurrent.CompletableFuture) BucketStore(io.pravega.controller.store.stream.BucketStore) AbortEvent(io.pravega.shared.controller.event.AbortEvent) EventSerializer(io.pravega.controller.eventProcessor.EventSerializer) ExponentialBackoffRetry(org.apache.curator.retry.ExponentialBackoffRetry) EventStreamClientFactory(io.pravega.client.EventStreamClientFactory) HostMonitorConfigImpl(io.pravega.controller.store.host.impl.HostMonitorConfigImpl) EventWriterConfig(io.pravega.client.stream.EventWriterConfig) ControllerService(io.pravega.controller.server.ControllerService) Iterator(java.util.Iterator) ControllerEventProcessorConfig(io.pravega.controller.server.eventProcessor.ControllerEventProcessorConfig) HostStoreFactory(io.pravega.controller.store.host.HostStoreFactory) ImmutablePair(org.apache.commons.lang3.tuple.ImmutablePair) Mockito.verify(org.mockito.Mockito.verify) EventProcessorGroupConfig(io.pravega.controller.eventProcessor.EventProcessorGroupConfig) Mockito(org.mockito.Mockito) AbstractMap(java.util.AbstractMap) State(io.pravega.controller.store.stream.State) ExecutorServiceHelpers(io.pravega.common.concurrent.ExecutorServiceHelpers) Collections(java.util.Collections) PingTxnStatus(io.pravega.controller.stream.api.grpc.v1.Controller.PingTxnStatus) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) VersionedTransactionData(io.pravega.controller.store.stream.VersionedTransactionData) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) ControllerService(io.pravega.controller.server.ControllerService) Cleanup(lombok.Cleanup) AbstractMap(java.util.AbstractMap) StreamConfiguration(io.pravega.client.stream.StreamConfiguration) CommitEvent(io.pravega.shared.controller.event.CommitEvent) AbortEvent(io.pravega.shared.controller.event.AbortEvent) ScalingPolicy(io.pravega.client.stream.ScalingPolicy) EventStreamWriterMock(io.pravega.controller.mocks.EventStreamWriterMock) CommitRequestHandler(io.pravega.controller.server.eventProcessor.requesthandlers.CommitRequestHandler) AbortRequestHandler(io.pravega.controller.server.eventProcessor.requesthandlers.AbortRequestHandler) TxnStatus(io.pravega.controller.store.stream.TxnStatus) PingTxnStatus(io.pravega.controller.stream.api.grpc.v1.Controller.PingTxnStatus) Test(org.junit.Test)

Example 50 with Assert.assertEquals

use of org.junit.Assert.assertEquals in project pravega by pravega.

the class StreamSegmentContainerTests method testEventProcessorDurableQueueAndSwitchToConsumer.

/**
 * Test the EventProcessor in durable queue mode (no handler). Then, close it and recreate another one on the same
 * internal Segment (same name) that actually consumes the events stored previously.
 *
 * @throws Exception
 */
@Test(timeout = 10000)
public void testEventProcessorDurableQueueAndSwitchToConsumer() throws Exception {
    @Cleanup TestContext context = createContext();
    val container = (StreamSegmentContainer) context.container;
    container.startAsync().awaitRunning();
    int allEventsToProcess = 100;
    @Cleanup ContainerEventProcessorImpl containerEventProcessor = new ContainerEventProcessorImpl(container, container.metadataStore, TIMEOUT_EVENT_PROCESSOR_ITERATION, TIMEOUT_EVENT_PROCESSOR_ITERATION, this.executorService());
    ContainerEventProcessor.EventProcessor processor = containerEventProcessor.forDurableQueue("testDurableQueue").get(TIMEOUT_FUTURE.toSeconds(), TimeUnit.SECONDS);
    // At this point, we can only add events, but not consuming them as the EventProcessor works in durable queue mode.
    for (int i = 0; i < allEventsToProcess; i++) {
        BufferView event = new ByteArraySegment(ByteBuffer.allocate(Integer.BYTES).putInt(i).array());
        processor.add(event, TIMEOUT_FUTURE).join();
    }
    Assert.assertEquals("Event processor object not matching", processor, containerEventProcessor.forDurableQueue("testDurableQueue").get(TIMEOUT_FUTURE.toSeconds(), TimeUnit.SECONDS));
    // Close the processor and unregister it.
    processor.close();
    // Make sure that EventProcessor eventually terminates.
    ((ContainerEventProcessorImpl.EventProcessorImpl) processor).awaitTerminated();
    // Now, re-create the Event Processor with a handler to consume the events.
    ContainerEventProcessor.EventProcessorConfig eventProcessorConfig = new ContainerEventProcessor.EventProcessorConfig(EVENT_PROCESSOR_EVENTS_AT_ONCE, EVENT_PROCESSOR_MAX_OUTSTANDING_BYTES, EVENT_PROCESSOR_TRUNCATE_SIZE_BYTES);
    List<Integer> processorResults = new ArrayList<>();
    Function<List<BufferView>, CompletableFuture<Void>> handler = l -> {
        l.forEach(b -> {
            try {
                processorResults.add(ByteBuffer.wrap(b.getReader().readNBytes(Integer.BYTES)).getInt());
            } catch (IOException e) {
                throw new CompletionException(e);
            }
        });
        return CompletableFuture.completedFuture(null);
    };
    processor = containerEventProcessor.forConsumer("testDurableQueue", handler, eventProcessorConfig).get(TIMEOUT_FUTURE.toSeconds(), TimeUnit.SECONDS);
    // Wait for all items to be processed.
    AssertExtensions.assertEventuallyEquals(true, () -> processorResults.size() == allEventsToProcess, 10000);
    Assert.assertArrayEquals(processorResults.toArray(), IntStream.iterate(0, v -> v + 1).limit(allEventsToProcess).boxed().toArray());
    // Just check failure callback.
    ((ContainerEventProcessorImpl.EventProcessorImpl) processor).failureCallback(new IntentionalException());
    // Close the processor and unregister it.
    processor.close();
    // Make sure that EventProcessor eventually terminates.
    ((ContainerEventProcessorImpl.EventProcessorImpl) processor).awaitTerminated();
}
Also used : lombok.val(lombok.val) Arrays(java.util.Arrays) Storage(io.pravega.segmentstore.storage.Storage) StreamSegmentInformation(io.pravega.segmentstore.contracts.StreamSegmentInformation) StreamSegmentNotExistsException(io.pravega.segmentstore.contracts.StreamSegmentNotExistsException) ContainerEventProcessor(io.pravega.segmentstore.server.ContainerEventProcessor) Cleanup(lombok.Cleanup) StorageWriterFactory(io.pravega.segmentstore.server.writer.StorageWriterFactory) UpdateableSegmentMetadata(io.pravega.segmentstore.server.UpdateableSegmentMetadata) Future(java.util.concurrent.Future) ContainerTableExtensionImpl(io.pravega.segmentstore.server.tables.ContainerTableExtensionImpl) InMemoryStorageFactory(io.pravega.segmentstore.storage.mocks.InMemoryStorageFactory) Duration(java.time.Duration) Map(java.util.Map) CachePolicy(io.pravega.segmentstore.server.CachePolicy) Operation(io.pravega.segmentstore.server.logs.operations.Operation) WriterFlushResult(io.pravega.segmentstore.server.WriterFlushResult) AsyncReadResultProcessor(io.pravega.segmentstore.server.reading.AsyncReadResultProcessor) ContainerReadIndexFactory(io.pravega.segmentstore.server.reading.ContainerReadIndexFactory) InMemoryDurableDataLogFactory(io.pravega.segmentstore.storage.mocks.InMemoryDurableDataLogFactory) DurableLogFactory(io.pravega.segmentstore.server.logs.DurableLogFactory) Attributes(io.pravega.segmentstore.contracts.Attributes) DurableLogConfig(io.pravega.segmentstore.server.logs.DurableLogConfig) Writer(io.pravega.segmentstore.server.Writer) StandardCharsets(java.nio.charset.StandardCharsets) Stream(java.util.stream.Stream) SegmentContainerFactory(io.pravega.segmentstore.server.SegmentContainerFactory) ContainerTableExtension(io.pravega.segmentstore.server.tables.ContainerTableExtension) ThreadPooledTestSuite(io.pravega.test.common.ThreadPooledTestSuite) SyncStorage(io.pravega.segmentstore.storage.SyncStorage) DirectMemoryCache(io.pravega.segmentstore.storage.cache.DirectMemoryCache) TestUtils(io.pravega.test.common.TestUtils) Futures(io.pravega.common.concurrent.Futures) CacheManager(io.pravega.segmentstore.server.CacheManager) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IllegalContainerStateException(io.pravega.segmentstore.server.IllegalContainerStateException) TooManyActiveSegmentsException(io.pravega.segmentstore.contracts.TooManyActiveSegmentsException) EntrySerializerTests(io.pravega.segmentstore.server.tables.EntrySerializerTests) Exceptions(io.pravega.common.Exceptions) StorageFactory(io.pravega.segmentstore.storage.StorageFactory) BadAttributeUpdateException(io.pravega.segmentstore.contracts.BadAttributeUpdateException) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) UpdateableContainerMetadata(io.pravega.segmentstore.server.UpdateableContainerMetadata) SegmentType(io.pravega.segmentstore.contracts.SegmentType) Runnables(com.google.common.util.concurrent.Runnables) AttributeIndexConfig(io.pravega.segmentstore.server.attributes.AttributeIndexConfig) ReadIndexConfig(io.pravega.segmentstore.server.reading.ReadIndexConfig) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) BiConsumer(java.util.function.BiConsumer) Timeout(org.junit.rules.Timeout) WriterTableProcessor(io.pravega.segmentstore.server.tables.WriterTableProcessor) ConfigurationException(io.pravega.common.util.ConfigurationException) SegmentContainerExtension(io.pravega.segmentstore.server.SegmentContainerExtension) WriterFactory(io.pravega.segmentstore.server.WriterFactory) Properties(java.util.Properties) DurableDataLog(io.pravega.segmentstore.storage.DurableDataLog) Executor(java.util.concurrent.Executor) AttributeId(io.pravega.segmentstore.contracts.AttributeId) lombok.val(lombok.val) Assert.assertTrue(org.junit.Assert.assertTrue) OperationLog(io.pravega.segmentstore.server.OperationLog) TableExtensionConfig(io.pravega.segmentstore.server.tables.TableExtensionConfig) IOException(java.io.IOException) Test(org.junit.Test) SystemJournal(io.pravega.segmentstore.storage.chunklayer.SystemJournal) Service(com.google.common.util.concurrent.Service) AtomicLong(java.util.concurrent.atomic.AtomicLong) DirectSegmentAccess(io.pravega.segmentstore.server.DirectSegmentAccess) ContainerAttributeIndex(io.pravega.segmentstore.server.attributes.ContainerAttributeIndex) AttributeUpdateCollection(io.pravega.segmentstore.contracts.AttributeUpdateCollection) OperationLogFactory(io.pravega.segmentstore.server.OperationLogFactory) SegmentContainer(io.pravega.segmentstore.server.SegmentContainer) Assert(org.junit.Assert) TableEntry(io.pravega.segmentstore.contracts.tables.TableEntry) Assert.assertEquals(org.junit.Assert.assertEquals) DynamicAttributeValue(io.pravega.segmentstore.contracts.DynamicAttributeValue) OperationPriority(io.pravega.segmentstore.server.logs.operations.OperationPriority) WriterConfig(io.pravega.segmentstore.server.writer.WriterConfig) SneakyThrows(lombok.SneakyThrows) AssertExtensions(io.pravega.test.common.AssertExtensions) BiFunction(java.util.function.BiFunction) RequiredArgsConstructor(lombok.RequiredArgsConstructor) TimeoutException(java.util.concurrent.TimeoutException) ByteBuffer(java.nio.ByteBuffer) SegmentProperties(io.pravega.segmentstore.contracts.SegmentProperties) ReadIndexFactory(io.pravega.segmentstore.server.ReadIndexFactory) AttributeUpdate(io.pravega.segmentstore.contracts.AttributeUpdate) StreamSegmentSealedException(io.pravega.segmentstore.contracts.StreamSegmentSealedException) ContainerAttributeIndexFactoryImpl(io.pravega.segmentstore.server.attributes.ContainerAttributeIndexFactoryImpl) AttributeIndexFactory(io.pravega.segmentstore.server.attributes.AttributeIndexFactory) SegmentHandle(io.pravega.segmentstore.storage.SegmentHandle) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) BufferView(io.pravega.common.util.BufferView) AbstractService(com.google.common.util.concurrent.AbstractService) AttributeIdLengthMismatchException(io.pravega.segmentstore.server.logs.AttributeIdLengthMismatchException) ServiceListeners(io.pravega.segmentstore.server.ServiceListeners) ContainerOfflineException(io.pravega.segmentstore.server.ContainerOfflineException) Predicate(java.util.function.Predicate) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) CompletionException(java.util.concurrent.CompletionException) ReadResultEntryType(io.pravega.segmentstore.contracts.ReadResultEntryType) UUID(java.util.UUID) DataLogWriterNotPrimaryException(io.pravega.segmentstore.storage.DataLogWriterNotPrimaryException) DynamicAttributeUpdate(io.pravega.segmentstore.contracts.DynamicAttributeUpdate) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) SegmentMetadataComparer(io.pravega.segmentstore.server.SegmentMetadataComparer) List(java.util.List) ByteArraySegment(io.pravega.common.util.ByteArraySegment) BadOffsetException(io.pravega.segmentstore.contracts.BadOffsetException) WriterSegmentProcessor(io.pravega.segmentstore.server.WriterSegmentProcessor) DurableDataLogFactory(io.pravega.segmentstore.storage.DurableDataLogFactory) ReadResult(io.pravega.segmentstore.contracts.ReadResult) IntStream(java.util.stream.IntStream) ObjectClosedException(io.pravega.common.ObjectClosedException) Setter(lombok.Setter) Getter(lombok.Getter) AsyncStorageWrapper(io.pravega.segmentstore.storage.AsyncStorageWrapper) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) CacheStorage(io.pravega.segmentstore.storage.cache.CacheStorage) HashSet(java.util.HashSet) SegmentMetadata(io.pravega.segmentstore.server.SegmentMetadata) ReadResultEntry(io.pravega.segmentstore.contracts.ReadResultEntry) ExecutorService(java.util.concurrent.ExecutorService) NameUtils(io.pravega.shared.NameUtils) ExecutorServiceHelpers.newScheduledThreadPool(io.pravega.common.concurrent.ExecutorServiceHelpers.newScheduledThreadPool) TimeoutTimer(io.pravega.common.TimeoutTimer) RollingStorage(io.pravega.segmentstore.storage.rolling.RollingStorage) IntentionalException(io.pravega.test.common.IntentionalException) StreamSegmentMergedException(io.pravega.segmentstore.contracts.StreamSegmentMergedException) TestReadResultHandler(io.pravega.segmentstore.server.reading.TestReadResultHandler) SnapshotInfo(io.pravega.segmentstore.storage.chunklayer.SnapshotInfo) TestDurableDataLogFactory(io.pravega.segmentstore.server.TestDurableDataLogFactory) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) Rule(org.junit.Rule) SegmentOperation(io.pravega.segmentstore.server.SegmentOperation) CachedStreamSegmentAppendOperation(io.pravega.segmentstore.server.logs.operations.CachedStreamSegmentAppendOperation) TypedProperties(io.pravega.common.util.TypedProperties) AttributeUpdateType(io.pravega.segmentstore.contracts.AttributeUpdateType) ReadIndex(io.pravega.segmentstore.server.ReadIndex) Comparator(java.util.Comparator) Collections(java.util.Collections) StreamSegmentSealOperation(io.pravega.segmentstore.server.logs.operations.StreamSegmentSealOperation) InputStream(java.io.InputStream) ByteArraySegment(io.pravega.common.util.ByteArraySegment) ArrayList(java.util.ArrayList) IOException(java.io.IOException) Cleanup(lombok.Cleanup) IntentionalException(io.pravega.test.common.IntentionalException) ContainerEventProcessor(io.pravega.segmentstore.server.ContainerEventProcessor) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) CompletableFuture(java.util.concurrent.CompletableFuture) BufferView(io.pravega.common.util.BufferView) CompletionException(java.util.concurrent.CompletionException) ArrayList(java.util.ArrayList) List(java.util.List) Test(org.junit.Test)

Aggregations

Assert.assertEquals (org.junit.Assert.assertEquals)282 Assert (org.junit.Assert)277 Test (org.junit.Test)276 List (java.util.List)233 Assert.assertTrue (org.junit.Assert.assertTrue)191 Before (org.junit.Before)166 ArrayList (java.util.ArrayList)134 Assert.assertNotNull (org.junit.Assert.assertNotNull)133 Map (java.util.Map)121 Assert.assertFalse (org.junit.Assert.assertFalse)116 Arrays (java.util.Arrays)113 UUID (java.util.UUID)108 Autowired (org.springframework.beans.factory.annotation.Autowired)105 Collections (java.util.Collections)102 After (org.junit.After)99 HashMap (java.util.HashMap)96 Assert.assertNull (org.junit.Assert.assertNull)94 Collectors (java.util.stream.Collectors)93 IdmIdentityDto (eu.bcvsolutions.idm.core.api.dto.IdmIdentityDto)91 IOException (java.io.IOException)85