use of org.junit.Assert.assertTrue in project pravega by pravega.
the class StreamSegmentContainerTests method testForceFlush.
/**
* Tests the {@link SegmentContainer#flushToStorage} method.
*/
@Test
public void testForceFlush() throws Exception {
final AttributeId attributeReplace = AttributeId.randomUUID();
final long expectedAttributeValue = APPENDS_PER_SEGMENT + ATTRIBUTE_UPDATES_PER_SEGMENT;
final int entriesPerSegment = 10;
@Cleanup TestContext context = new TestContext(DEFAULT_CONFIG, NO_TRUNCATIONS_DURABLE_LOG_CONFIG, INFREQUENT_FLUSH_WRITER_CONFIG, null);
val durableLog = new AtomicReference<OperationLog>();
val durableLogFactory = new WatchableOperationLogFactory(context.operationLogFactory, durableLog::set);
@Cleanup val container = new StreamSegmentContainer(CONTAINER_ID, DEFAULT_CONFIG, durableLogFactory, context.readIndexFactory, context.attributeIndexFactory, context.writerFactory, context.storageFactory, context.getDefaultExtensions(), executorService());
container.startAsync().awaitRunning();
Assert.assertNotNull(durableLog.get());
val tableStore = container.getExtension(ContainerTableExtension.class);
// 1. Create the StreamSegments and Table Segments.
ArrayList<String> segmentNames = new ArrayList<>();
ArrayList<String> tableSegmentNames = new ArrayList<>();
ArrayList<CompletableFuture<Void>> opFutures = new ArrayList<>();
for (int i = 0; i < SEGMENT_COUNT; i++) {
String segmentName = getSegmentName(i);
segmentNames.add(segmentName);
opFutures.add(container.createStreamSegment(segmentName, getSegmentType(segmentName), null, TIMEOUT));
}
for (int i = 0; i < SEGMENT_COUNT; i++) {
String segmentName = getSegmentName(i) + "_Table";
tableSegmentNames.add(segmentName);
val type = SegmentType.builder(getSegmentType(segmentName)).tableSegment().build();
opFutures.add(tableStore.createSegment(segmentName, type, TIMEOUT));
}
// 1.1 Wait for all segments to be created prior to using them.
Futures.allOf(opFutures).join();
opFutures.clear();
// 2. Add some appends and update some of the attributes.
HashMap<String, Long> lengths = new HashMap<>();
HashMap<String, ByteArrayOutputStream> segmentContents = new HashMap<>();
for (String segmentName : segmentNames) {
for (int i = 0; i < APPENDS_PER_SEGMENT; i++) {
val attributeUpdates = AttributeUpdateCollection.from(new AttributeUpdate(attributeReplace, AttributeUpdateType.Replace, i + 1));
val appendData = getAppendData(segmentName, i);
long expectedLength = lengths.getOrDefault(segmentName, 0L) + appendData.getLength();
val append = (i % 2 == 0) ? container.append(segmentName, appendData, attributeUpdates, TIMEOUT) : container.append(segmentName, lengths.get(segmentName), appendData, attributeUpdates, TIMEOUT);
opFutures.add(Futures.toVoid(append));
lengths.put(segmentName, expectedLength);
recordAppend(segmentName, appendData, segmentContents, null);
}
for (int i = 0; i < ATTRIBUTE_UPDATES_PER_SEGMENT; i++) {
val attributeUpdates = AttributeUpdateCollection.from(new AttributeUpdate(attributeReplace, AttributeUpdateType.Replace, APPENDS_PER_SEGMENT + i + 1));
opFutures.add(container.updateAttributes(segmentName, attributeUpdates, TIMEOUT));
}
}
// 2.2 Add some entries to the table segments.
final BiFunction<String, Integer, TableEntry> createTableEntry = (segmentName, entryId) -> TableEntry.unversioned(new ByteArraySegment(String.format("Key_%s_%s", segmentName, entryId).getBytes()), new ByteArraySegment(String.format("Value_%s_%s", segmentName, entryId).getBytes()));
for (String segmentName : tableSegmentNames) {
for (int i = 0; i < entriesPerSegment; i++) {
opFutures.add(Futures.toVoid(tableStore.put(segmentName, Collections.singletonList(createTableEntry.apply(segmentName, i)), TIMEOUT)));
}
}
Futures.allOf(opFutures).join();
// 3. Instead of waiting for the Writer to move data to Storage, we invoke the flushToStorage to verify that all
// operations have been applied to Storage.
val forceFlush = container.flushToStorage(TIMEOUT);
forceFlush.get(TIMEOUT.toMillis(), TimeUnit.MILLISECONDS);
checkStorage(segmentContents, lengths, container, context.storage);
// 4. Truncate all the data in the DurableLog and immediately shut down the container.
val truncateSeqNo = container.metadata.getClosestValidTruncationPoint(container.metadata.getOperationSequenceNumber());
durableLog.get().truncate(truncateSeqNo, TIMEOUT).get(TIMEOUT.toMillis(), TimeUnit.MILLISECONDS);
container.close();
// 5. Create a new container instance (from the nearly empty DurableLog) and with an empty cache.
@Cleanup val container2 = new StreamSegmentContainer(CONTAINER_ID, DEFAULT_CONFIG, durableLogFactory, context.readIndexFactory, context.attributeIndexFactory, context.writerFactory, context.storageFactory, context.getDefaultExtensions(), executorService());
container2.startAsync().awaitRunning();
// 5.1 Verify Segment Data.
for (val sc : segmentContents.entrySet()) {
// Contents.
byte[] expectedData = sc.getValue().toByteArray();
byte[] actualData = new byte[expectedData.length];
container2.read(sc.getKey(), 0, actualData.length, TIMEOUT).join().readRemaining(actualData, TIMEOUT);
Assert.assertArrayEquals("Unexpected contents for " + sc.getKey(), expectedData, actualData);
// Length.
val si = container2.getStreamSegmentInfo(sc.getKey(), TIMEOUT).join();
Assert.assertEquals("Unexpected length for " + sc.getKey(), expectedData.length, si.getLength());
// Attributes.
val attributes = container2.getAttributes(sc.getKey(), Collections.singleton(attributeReplace), false, TIMEOUT).join();
Assert.assertEquals("Unexpected attribute for " + sc.getKey(), expectedAttributeValue, (long) attributes.get(attributeReplace));
}
// 5.2 Verify table segment data.
val tableStore2 = container2.getExtension(ContainerTableExtension.class);
for (String segmentName : tableSegmentNames) {
for (int i = 0; i < entriesPerSegment; i++) {
val expected = createTableEntry.apply(segmentName, i);
val actual = tableStore2.get(segmentName, Collections.singletonList(expected.getKey().getKey()), TIMEOUT).get(TIMEOUT.toMillis(), TimeUnit.MILLISECONDS).get(0);
Assert.assertTrue("Unexpected Table Entry for " + segmentName + " at position " + i, expected.getKey().getKey().equals(actual.getKey().getKey()) && expected.getValue().equals(actual.getValue()));
}
}
// Ending Note: if all the above tests passed, we have implicitly validated that the Container Metadata Segment has also
// been properly flushed.
}
use of org.junit.Assert.assertTrue in project pravega by pravega.
the class StreamSegmentContainerTests method checkAttributeIterators.
private void checkAttributeIterators(DirectSegmentAccess segment, List<AttributeId> sortedAttributes, Map<AttributeId, Long> allExpectedValues) throws Exception {
int skip = sortedAttributes.size() / 10;
for (int i = 0; i < sortedAttributes.size() / 2; i += skip) {
AttributeId fromId = sortedAttributes.get(i);
AttributeId toId = sortedAttributes.get(sortedAttributes.size() - i - 1);
val expectedValues = allExpectedValues.entrySet().stream().filter(e -> fromId.compareTo(e.getKey()) <= 0 && toId.compareTo(e.getKey()) >= 0).sorted(Comparator.comparing(Map.Entry::getKey)).collect(Collectors.toList());
val actualValues = new ArrayList<Map.Entry<AttributeId, Long>>();
val ids = new HashSet<AttributeId>();
val iterator = segment.attributeIterator(fromId, toId, TIMEOUT).get(TIMEOUT.toMillis(), TimeUnit.MILLISECONDS);
iterator.forEachRemaining(batch -> batch.forEach(attribute -> {
Assert.assertTrue("Duplicate key found.", ids.add(attribute.getKey()));
actualValues.add(attribute);
}), executorService()).get(TIMEOUT.toMillis(), TimeUnit.MILLISECONDS);
AssertExtensions.assertListEquals("Unexpected iterator result.", expectedValues, actualValues, (e1, e2) -> e1.getKey().equals(e2.getKey()) && e1.getValue().equals(e2.getValue()));
}
}
use of org.junit.Assert.assertTrue in project flow by vaadin.
the class BinderConverterValidatorTest method binderLoad_withCrossFieldValidation_clearsErrors.
@Test
public void binderLoad_withCrossFieldValidation_clearsErrors() {
TestTextField lastNameField = new TestTextField();
final SerializablePredicate<String> lengthPredicate = v -> v.length() > 2;
BindingBuilder<Person, String> firstNameBinding = binder.forField(nameField).withValidator(lengthPredicate, "length");
firstNameBinding.bind(Person::getFirstName, Person::setFirstName);
Binding<Person, String> lastNameBinding = binder.forField(lastNameField).withValidator(v -> !nameField.getValue().isEmpty() || lengthPredicate.test(v), "err").withValidator(lengthPredicate, "length").bind(Person::getLastName, Person::setLastName);
// this will be triggered as a new bean is bound with binder.bind(),
// causing a validation error to be visible until reset is done
nameField.addValueChangeListener(v -> lastNameBinding.validate());
Person person = new Person();
binder.setBean(person);
Assert.assertFalse(componentErrors.containsKey(nameField));
Assert.assertFalse(componentErrors.containsKey(lastNameField));
nameField.setValue("x");
Assert.assertTrue(componentErrors.containsKey(nameField));
Assert.assertTrue(componentErrors.containsKey(lastNameField));
binder.setBean(person);
Assert.assertFalse(componentErrors.containsKey(nameField));
Assert.assertFalse(componentErrors.containsKey(lastNameField));
}
use of org.junit.Assert.assertTrue in project flow by vaadin.
the class BinderTest method setValidationErrorHandler_handlerIsSet_handlerMethodsAreCalled.
@Test
public void setValidationErrorHandler_handlerIsSet_handlerMethodsAreCalled() {
TestTextField testField = new TestTextField();
class TestErrorHandler implements BinderValidationErrorHandler {
private ValidationResult result;
private boolean clearIsCalled;
@Override
public void handleError(HasValue<?, ?> field, ValidationResult result) {
Assert.assertSame(testField, field);
this.result = result;
clearIsCalled = false;
}
@Override
public void clearError(HasValue<?, ?> field) {
Assert.assertSame(testField, field);
result = null;
clearIsCalled = true;
}
}
;
TestErrorHandler handler = new TestErrorHandler();
binder.setValidationErrorHandler(handler);
binder.forField(testField).asRequired().withValidator((val, context) -> {
if ("bar".equals(val)) {
return ValidationResult.error("foo");
}
return ValidationResult.ok();
}).bind(Person::getFirstName, Person::setFirstName);
binder.setBean(new Person());
testField.setValue("bar");
Assert.assertTrue(handler.result.isError());
Assert.assertFalse(handler.clearIsCalled);
testField.setValue("foo");
Assert.assertNull(handler.result);
Assert.assertTrue(handler.clearIsCalled);
Assert.assertSame(handler, binder.getValidationErrorHandler());
}
use of org.junit.Assert.assertTrue in project flow by vaadin.
the class BootstrapHandlerTest method css_body_size_overrides_annotated_body_size.
@Test
public void css_body_size_overrides_annotated_body_size() throws InvalidRouteConfigurationException {
initUI(testUI, createVaadinRequest(), Collections.singleton(BodySizeAnnotatedAndCss.class));
Document page = pageBuilder.getBootstrapPage(new BootstrapContext(request, null, session, testUI, this::contextRootRelativePath));
Elements allElements = page.head().getAllElements();
Optional<Element> styleTag = allElements.stream().filter(element -> element.tagName().equals("style")).findFirst();
Assert.assertTrue("Expected a style element in head.", styleTag.isPresent());
Assert.assertTrue("The first style tag should start with body style from @BodySize", styleTag.get().toString().startsWith("<style type=\"text/css\">body {height:10px;width:20px;margin:0;}"));
Optional<Element> cssImportTag = allElements.stream().filter(element -> element.attr("href").contains("bodysize.css")).findFirst();
Assert.assertTrue("Expected import for bodysize.css in head.", cssImportTag.isPresent());
Assert.assertTrue("Styles defined with @BodySize should be imported before css-files in the head," + " so that body size defined in css overrides the annotated values.", allElements.indexOf(styleTag.get()) < allElements.indexOf(cssImportTag.get()));
}
Aggregations