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());
}
}
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());
}
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());
}
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());
}
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();
}
Aggregations