method2testcases
stringlengths
118
3.08k
### Question: PdfVersionCompatibilityChecker { public boolean isVersionUpgradeRequired() { return pdfVersionOfDocumentToBeSigned < getMinimumCompatiblePdfVersion(); } PdfVersionCompatibilityChecker(String pPdfVersionOfDocumentToBeSigned, String pSignatureDigestAlgorithm); int getPdfVersionOfDocumentToBeSigned(); boolean isVersionUpgradeRequired(); int getMinimumCompatiblePdfVersion(); }### Answer: @Test public void versionUpgradeRequiredForSha256_PdfVersionIs_0() { PdfVersionCompatibilityChecker checker = new PdfVersionCompatibilityChecker("0", "SHA-256"); boolean upgradeRequired = checker.isVersionUpgradeRequired(); assertTrue(upgradeRequired); } @Test public void versionUpgradeNotRequiredForSha256_PdfVersionIs_6() { PdfVersionCompatibilityChecker checker = new PdfVersionCompatibilityChecker("6", "SHA-256"); boolean upgradeRequired = checker.isVersionUpgradeRequired(); assertFalse(upgradeRequired); } @Test public void versionUpgradeRequiredForSha256_PdfVersionIs_NotNumeric() { PdfVersionCompatibilityChecker checker = new PdfVersionCompatibilityChecker("XXXX", "SHA-256"); boolean upgradeRequired = checker.isVersionUpgradeRequired(); assertTrue(upgradeRequired); } @Test public void versionUpgradeRequiredForSha384_PdfVersionIs_6() { PdfVersionCompatibilityChecker checker = new PdfVersionCompatibilityChecker("6", "SHA-384"); boolean upgradeRequired = checker.isVersionUpgradeRequired(); assertTrue(upgradeRequired); } @Test public void versionUpgradeNotRequiredForSha384_PdfVersionIs_7() { PdfVersionCompatibilityChecker checker = new PdfVersionCompatibilityChecker("7", "SHA-384"); boolean upgradeRequired = checker.isVersionUpgradeRequired(); assertFalse(upgradeRequired); }
### Question: VirtualMetric extends AbstractMetric<V> { @Override public int getCardinality() { return cardinality; } VirtualMetric( String name, String description, String valueDisplayName, ImmutableSet<LabelDescriptor> labels, Supplier<ImmutableMap<ImmutableList<String>, V>> valuesSupplier, Class<V> valueClass); @Override ImmutableList<MetricPoint<V>> getTimestampedValues(); @Override int getCardinality(); }### Answer: @Test public void testGetCardinality_beforeGetTimestampedValues_returnsZero() { assertThat(metric.getCardinality()).isEqualTo(0); }
### Question: MetricReporter extends AbstractScheduledService { @Override protected void runOneIteration() { logger.fine("Running background metric push"); if (metricExporter.state() == State.FAILED) { startMetricExporter(); } ImmutableList.Builder<MetricPoint<?>> points = new ImmutableList.Builder<>(); for (Metric<?> metric : metricRegistry.getRegisteredMetrics()) { points.addAll(metric.getTimestampedValues()); logger.fine(String.format("Enqueued metric %s", metric)); MetricMetrics.pushedPoints.increment( metric.getMetricSchema().kind().name(), metric.getValueClass().toString()); } if (!writeQueue.offer(Optional.of(points.build()))) { logger.severe("writeQueue full, dropped a reporting interval of points"); } MetricMetrics.pushIntervals.increment(); } MetricReporter( MetricWriter metricWriter, long writeInterval, ThreadFactory threadFactory); @VisibleForTesting MetricReporter( MetricWriter metricWriter, long writeInterval, ThreadFactory threadFactory, MetricRegistry metricRegistry, BlockingQueue<Optional<ImmutableList<MetricPoint<?>>>> writeQueue); }### Answer: @Test public void testRunOneIteration_enqueuesBatch() throws Exception { Metric<?> metric = new Counter("/name", "description", "vdn", ImmutableSet.<LabelDescriptor>of()); when(registry.getRegisteredMetrics()).thenReturn(ImmutableList.of(metric, metric)); MetricReporter reporter = new MetricReporter(writer, 10L, threadFactory, registry, writeQueue); reporter.runOneIteration(); verify(writeQueue).offer(Optional.of(ImmutableList.<MetricPoint<?>>of())); }
### Question: VirtualMetric extends AbstractMetric<V> { @Override public ImmutableList<MetricPoint<V>> getTimestampedValues() { return getTimestampedValues(Instant.now()); } VirtualMetric( String name, String description, String valueDisplayName, ImmutableSet<LabelDescriptor> labels, Supplier<ImmutableMap<ImmutableList<String>, V>> valuesSupplier, Class<V> valueClass); @Override ImmutableList<MetricPoint<V>> getTimestampedValues(); @Override int getCardinality(); }### Answer: @Test public void testGetTimestampedValues_returnsValues() { assertThat(metric.getTimestampedValues(Instant.ofEpochMilli(1337))) .containsExactly( MetricPoint.create( metric, ImmutableList.of("label_value1"), Instant.ofEpochMilli(1337), "value1"), MetricPoint.create( metric, ImmutableList.of("label_value2"), Instant.ofEpochMilli(1337), "value2")); }
### Question: MutableDistribution implements Distribution { public void add(double value) { add(value, 1L); } MutableDistribution(DistributionFitter distributionFitter); void add(double value); void add(double value, long numSamples); @Override double mean(); @Override double sumOfSquaredDeviation(); @Override long count(); @Override ImmutableRangeMap<Double, Long> intervalCounts(); @Override DistributionFitter distributionFitter(); }### Answer: @Test public void testAdd_negativeZero_throwsException() { IllegalArgumentException thrown = assertThrows( IllegalArgumentException.class, () -> distribution.add(Double.longBitsToDouble(0x80000000))); assertThat(thrown).hasMessageThat().contains("value must be finite, not NaN, and not -0.0"); } @Test public void testAdd_NaN_throwsException() { IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, () -> distribution.add(Double.NaN)); assertThat(thrown).hasMessageThat().contains("value must be finite, not NaN, and not -0.0"); } @Test public void testAdd_positiveInfinity_throwsException() { IllegalArgumentException thrown = assertThrows( IllegalArgumentException.class, () -> distribution.add(Double.POSITIVE_INFINITY)); assertThat(thrown).hasMessageThat().contains("value must be finite, not NaN, and not -0.0"); } @Test public void testAdd_negativeInfinity_throwsException() { IllegalArgumentException thrown = assertThrows( IllegalArgumentException.class, () -> distribution.add(Double.NEGATIVE_INFINITY)); assertThat(thrown).hasMessageThat().contains("value must be finite, not NaN, and not -0.0"); }
### Question: LabelDescriptor { public static LabelDescriptor create(String name, String description) { checkArgument(!name.isEmpty(), "Name must not be empty"); checkArgument(!description.isEmpty(), "Description must not be empty"); checkArgument( ALLOWED_LABEL_PATTERN.matches(name), "Label name must match the regex %s", ALLOWED_LABEL_PATTERN); return new AutoValue_LabelDescriptor(name, description); } LabelDescriptor(); static LabelDescriptor create(String name, String description); abstract String name(); abstract String description(); }### Answer: @Test public void testCreate_invalidLabel_throwsException() { IllegalArgumentException thrown = assertThrows( IllegalArgumentException.class, () -> LabelDescriptor.create("@", "description")); assertThat(thrown).hasMessageThat().contains("Label name must match the regex"); } @Test public void testCreate_blankNameField_throwsException() { IllegalArgumentException thrown = assertThrows( IllegalArgumentException.class, () -> LabelDescriptor.create("", "description")); assertThat(thrown).hasMessageThat().contains("Name must not be empty"); } @Test public void testCreate_blankDescriptionField_throwsException() { IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, () -> LabelDescriptor.create("name", "")); assertThat(thrown).hasMessageThat().contains("Description must not be empty"); }
### Question: Counter extends AbstractMetric<Long> implements SettableMetric<Long>, IncrementableMetric { @Override public final void increment(String... labelValues) { MetricsUtils.checkLabelValuesLength(this, labelValues); incrementBy(1L, Instant.now(), ImmutableList.copyOf(labelValues)); } Counter( String name, String description, String valueDisplayName, ImmutableSet<LabelDescriptor> labels); @Override final void incrementBy(long offset, String... labelValues); @Override final void increment(String... labelValues); @Override final ImmutableList<MetricPoint<Long>> getTimestampedValues(); @Override final int getCardinality(); @Override final void set(Long value, String... labelValues); @Override final void reset(); @Override final void reset(String... labelValues); }### Answer: @Test public void testIncrementBy_wrongLabelValueCount_throwsException() { Counter counter = new Counter( "/metric", "description", "vdn", ImmutableSet.of( LabelDescriptor.create("label1", "bar"), LabelDescriptor.create("label2", "bar"))); IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, () -> counter.increment("blah")); assertThat(thrown) .hasMessageThat() .contains( "The count of labelValues must be equal to the underlying Metric's count of labels."); }
### Question: StoredMetric extends AbstractMetric<V> implements SettableMetric<V> { @VisibleForTesting final void set(V value, ImmutableList<String> labelValues) { this.values.put(labelValues, value); } StoredMetric( String name, String description, String valueDisplayName, ImmutableSet<LabelDescriptor> labels, Class<V> valueClass); @Override final void set(V value, String... labelValues); @Override final ImmutableList<MetricPoint<V>> getTimestampedValues(); @Override final int getCardinality(); }### Answer: @Test public void testSet_wrongNumberOfLabels_throwsException() { StoredMetric<Boolean> dimensionalMetric = new StoredMetric<>( "/metric", "description", "vdn", ImmutableSet.of( LabelDescriptor.create("label1", "bar"), LabelDescriptor.create("label2", "bar")), Boolean.class); IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, () -> dimensionalMetric.set(true, "foo")); assertThat(thrown) .hasMessageThat() .contains( "The count of labelValues must be equal to the underlying Metric's count of labels."); }
### Question: EventMetric extends AbstractMetric<Distribution> { public void record(double sample, String... labelValues) { MetricsUtils.checkLabelValuesLength(this, labelValues); recordMultiple(sample, 1, Instant.now(), ImmutableList.copyOf(labelValues)); } EventMetric( String name, String description, String valueDisplayName, DistributionFitter distributionFitter, ImmutableSet<LabelDescriptor> labels); @Override final int getCardinality(); @Override final ImmutableList<MetricPoint<Distribution>> getTimestampedValues(); void record(double sample, String... labelValues); void record(double sample, int count, String... labelValues); void reset(); void reset(String... labelValues); static final DistributionFitter DEFAULT_FITTER; }### Answer: @Test public void testIncrementBy_wrongLabelValueCount_throwsException() { IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, () -> metric.record(1.0, "blah", "blah")); assertThat(thrown) .hasMessageThat() .contains( "The count of labelValues must be equal to the underlying Metric's count of labels."); }
### Question: CustomFitter implements DistributionFitter { public static CustomFitter create(ImmutableSet<Double> boundaries) { checkArgument(boundaries.size() > 0, "boundaries must not be empty"); checkArgument(Ordering.natural().isOrdered(boundaries), "boundaries must be sorted"); for (Double d : boundaries) { checkDouble(d); } return new AutoValue_CustomFitter(ImmutableSortedSet.copyOf(boundaries)); } static CustomFitter create(ImmutableSet<Double> boundaries); @Override abstract ImmutableSortedSet<Double> boundaries(); }### Answer: @Test public void testCreateCustomFitter_emptyBounds_throwsException() throws Exception { IllegalArgumentException thrown = assertThrows( IllegalArgumentException.class, () -> CustomFitter.create(ImmutableSet.<Double>of())); assertThat(thrown).hasMessageThat().contains("boundaries must not be empty"); } @Test public void testCreateCustomFitter_outOfOrderBounds_throwsException() throws Exception { IllegalArgumentException thrown = assertThrows( IllegalArgumentException.class, () -> CustomFitter.create(ImmutableSet.of(2.0, 0.0))); assertThat(thrown).hasMessageThat().contains("boundaries must be sorted"); }
### Question: StackdriverWriter implements MetricWriter { @Override public <V> void write(com.google.monitoring.metrics.MetricPoint<V> point) throws IOException { checkNotNull(point); TimeSeries timeSeries = getEncodedTimeSeries(point); timeSeriesBuffer.add(timeSeries); logger.fine(String.format("Enqueued metric %s for writing", timeSeries.getMetric().getType())); if (timeSeriesBuffer.size() == maxPointsPerRequest) { flush(); } } StackdriverWriter( Monitoring monitoringClient, String project, MonitoredResource monitoredResource, int maxQps, int maxPointsPerRequest); @Override void write(com.google.monitoring.metrics.MetricPoint<V> point); @Override void flush(); }### Answer: @Test public void testWrite_invalidMetricType_throwsException() throws Exception { when(metric.getValueClass()).thenAnswer((Answer<Class<?>>) invocation -> Object.class); StackdriverWriter writer = new StackdriverWriter(client, PROJECT, MONITORED_RESOURCE, MAX_QPS, MAX_POINTS_PER_REQUEST); for (MetricPoint<?> point : metric.getTimestampedValues()) { assertThrows(IOException.class, () -> writer.write(point)); } }
### Question: Counter extends AbstractMetric<Long> implements SettableMetric<Long>, IncrementableMetric { @VisibleForTesting void incrementBy(long offset, Instant startTimestamp, ImmutableList<String> labelValues) { Lock lock = valueLocks.get(labelValues); lock.lock(); try { values.addAndGet(labelValues, offset); valueStartTimestamps.putIfAbsent(labelValues, startTimestamp); } finally { lock.unlock(); } } Counter( String name, String description, String valueDisplayName, ImmutableSet<LabelDescriptor> labels); @Override final void incrementBy(long offset, String... labelValues); @Override final void increment(String... labelValues); @Override final ImmutableList<MetricPoint<Long>> getTimestampedValues(); @Override final int getCardinality(); @Override final void set(Long value, String... labelValues); @Override final void reset(); @Override final void reset(String... labelValues); }### Answer: @Test public void testIncrementBy_negativeOffset_throwsException() { Counter counter = new Counter( "/metric", "description", "vdn", ImmutableSet.of(LabelDescriptor.create("label1", "bar"))); IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, () -> counter.incrementBy(-1L, "foo")); assertThat(thrown).hasMessageThat().contains("The offset provided must be non-negative"); }
### Question: StackdriverWriter implements MetricWriter { @VisibleForTesting static MetricDescriptor encodeMetricDescriptor(com.google.monitoring.metrics.Metric<?> metric) { return new MetricDescriptor() .setType(METRIC_DOMAIN + metric.getMetricSchema().name()) .setDescription(metric.getMetricSchema().description()) .setDisplayName(metric.getMetricSchema().valueDisplayName()) .setValueType(ENCODED_METRIC_TYPES.get(metric.getValueClass())) .setLabels(encodeLabelDescriptors(metric.getMetricSchema().labels())) .setMetricKind(ENCODED_METRIC_KINDS.get(metric.getMetricSchema().kind().name())); } StackdriverWriter( Monitoring monitoringClient, String project, MonitoredResource monitoredResource, int maxQps, int maxPointsPerRequest); @Override void write(com.google.monitoring.metrics.MetricPoint<V> point); @Override void flush(); }### Answer: @Test public void encodeMetricDescriptor_simpleMetric_encodes() { MetricDescriptor descriptor = StackdriverWriter.encodeMetricDescriptor(metric); assertThat(descriptor.getType()).isEqualTo("custom.googleapis.com/name"); assertThat(descriptor.getValueType()).isEqualTo("INT64"); assertThat(descriptor.getDescription()).isEqualTo("desc"); assertThat(descriptor.getDisplayName()).isEqualTo("vdn"); assertThat(descriptor.getLabels()) .containsExactly( new com.google.api.services.monitoring.v3.model.LabelDescriptor() .setValueType("STRING") .setKey("label1") .setDescription("desc1")); }
### Question: StackdriverWriter implements MetricWriter { @VisibleForTesting static ImmutableList<LabelDescriptor> encodeLabelDescriptors( ImmutableSet<com.google.monitoring.metrics.LabelDescriptor> labelDescriptors) { List<LabelDescriptor> stackDriverLabelDescriptors = new ArrayList<>(labelDescriptors.size()); for (com.google.monitoring.metrics.LabelDescriptor labelDescriptor : labelDescriptors) { stackDriverLabelDescriptors.add( new LabelDescriptor() .setKey(labelDescriptor.name()) .setDescription(labelDescriptor.description()) .setValueType(LABEL_VALUE_TYPE)); } return ImmutableList.copyOf(stackDriverLabelDescriptors); } StackdriverWriter( Monitoring monitoringClient, String project, MonitoredResource monitoredResource, int maxQps, int maxPointsPerRequest); @Override void write(com.google.monitoring.metrics.MetricPoint<V> point); @Override void flush(); }### Answer: @Test public void encodeLabelDescriptors_simpleLabels_encodes() { ImmutableSet<LabelDescriptor> descriptors = ImmutableSet.of( LabelDescriptor.create("label1", "description1"), LabelDescriptor.create("label2", "description2")); ImmutableList<com.google.api.services.monitoring.v3.model.LabelDescriptor> encodedDescritors = StackdriverWriter.encodeLabelDescriptors(descriptors); assertThat(encodedDescritors) .containsExactly( new com.google.api.services.monitoring.v3.model.LabelDescriptor() .setValueType("STRING") .setKey("label1") .setDescription("description1"), new com.google.api.services.monitoring.v3.model.LabelDescriptor() .setValueType("STRING") .setKey("label2") .setDescription("description2")); }
### Question: LongMetricSubject extends AbstractMetricSubject<Long, LongMetricSubject> { public static LongMetricSubject assertThat(@Nullable Metric<Long> metric) { return assertAbout(LongMetricSubject::new).that(metric); } private LongMetricSubject(FailureMetadata metadata, Metric<Long> actual); static LongMetricSubject assertThat(@Nullable Metric<Long> metric); And<LongMetricSubject> hasValueForLabels(long value, String... labels); }### Answer: @Test public void testDoesNotHaveWrongNumberOfLabels_succeeds() { assertThat(metric).doesNotHaveAnyValueForLabels("Domestic"); } @Test public void testHasAnyValueForLabels_success() { assertThat(metric) .hasAnyValueForLabels("Domestic", "Green") .and() .hasAnyValueForLabels("Bighorn", "Blue") .and() .hasNoOtherValues(); } @Test public void testDoesNotHaveValueForLabels_success() { assertThat(metric).doesNotHaveAnyValueForLabels("Domestic", "Blue"); } @Test public void testDoesNotHaveValueForLabels_failure() { AssertionError e = assertThrows( AssertionError.class, () -> assertThat(metric).doesNotHaveAnyValueForLabels("Domestic", "Green")); assertThat(e) .hasMessageThat() .isEqualTo( "Not true that </test/incrementable/sheep> has no value for labels <Domestic:Green>." + " It has a value of <1>"); }
### Question: HiveTables extends BaseMetastoreTables { @Override public Table create(Schema schema, String tableIdentifier) { return create(schema, PartitionSpec.unpartitioned(), tableIdentifier); } HiveTables(Configuration conf); @Override Table create(Schema schema, String tableIdentifier); @Override Table create(Schema schema, PartitionSpec spec, Map<String, String> properties, String tableIdentifier); @Override Table load(String tableIdentifier); @Override BaseMetastoreTableOperations newTableOps(Configuration conf, String database, String table); }### Answer: @Test public void testCreate() throws TException { final Table table = metastoreClient.getTable(DB_NAME, TABLE_NAME); final Map<String, String> parameters = table.getParameters(); Assert.assertNotNull(parameters); Assert.assertTrue(ICEBERG_TABLE_TYPE_VALUE.equalsIgnoreCase(parameters.get(TABLE_TYPE_PROP))); Assert.assertTrue(ICEBERG_TABLE_TYPE_VALUE.equalsIgnoreCase(table.getTableType())); Assert.assertEquals(getTableLocation(TABLE_NAME) , table.getSd().getLocation()); Assert.assertEquals(0 , table.getPartitionKeysSize()); Assert.assertEquals(1, metadataVersionFiles(TABLE_NAME).size()); Assert.assertEquals(0, manifestFiles(TABLE_NAME).size()); final com.netflix.iceberg.Table icebergTable = new HiveTables(hiveConf).load(DB_NAME, TABLE_NAME); Assert.assertEquals(schema.asStruct(), icebergTable.schema().asStruct()); }
### Question: SchemaUtil { public static ResourceSchema convert(Schema icebergSchema) throws IOException { ResourceSchema result = new ResourceSchema(); result.setFields(convertFields(icebergSchema.columns())); return result; } static ResourceSchema convert(Schema icebergSchema); static Schema project(Schema schema, List<String> requiredFields); }### Answer: @Test public void testPrimitive() throws IOException { Schema icebergSchema = new Schema( optional(1, "b", BooleanType.get()), optional(1, "i", IntegerType.get()), optional(2, "l", LongType.get()), optional(3, "f", FloatType.get()), optional(4, "d", DoubleType.get()), optional(5, "dec", DecimalType.of(0,2)), optional(5, "s", StringType.get()), optional(6,"bi", BinaryType.get()) ); ResourceSchema pigSchema = SchemaUtil.convert(icebergSchema); assertEquals("b:boolean,i:int,l:long,f:float,d:double,dec:bigdecimal,s:chararray,bi:bytearray", pigSchema.toString()); } @Test public void testTupleInMap() throws IOException { Schema icebergSchema = new Schema( optional( 1, "nested_list", MapType.ofOptional( 2, 3, StringType.get(), ListType.ofOptional( 4, StructType.of( required(5, "id", LongType.get()), optional(6, "data", StringType.get())))))); ResourceSchema pigSchema = SchemaUtil.convert(icebergSchema); assertEquals("nested_list:[{(id:long,data:chararray)}]", pigSchema.toString()); } @Test public void testLongInBag() throws IOException { Schema icebergSchema = new Schema( optional( 1, "nested_list", MapType.ofOptional( 2, 3, StringType.get(), ListType.ofRequired(5, LongType.get())))); SchemaUtil.convert(icebergSchema); }
### Question: Listeners { @SuppressWarnings("unchecked") public static <E> void notifyAll(E event) { Preconditions.checkNotNull(event, "Cannot notify listeners for a null event."); List<Listener<?>> list = listeners.get(event.getClass()); if (list != null) { Iterator<Listener<?>> iter = list.iterator(); while (iter.hasNext()) { Listener<E> listener = (Listener<E>) iter.next(); listener.notify(event); } } } private Listeners(); static void register(Listener<E> listener, Class<E> eventType); @SuppressWarnings("unchecked") static void notifyAll(E event); }### Answer: @Test public void testEvent1() { Event1 e1 = new Event1(); Listeners.notifyAll(e1); Assert.assertEquals(e1, TestListener.get().e1); } @Test public void testEvent2() { Event2 e2 = new Event2(); Listeners.notifyAll(e2); Assert.assertEquals(e2, TestListener.get().e2); }
### Question: ScanSummary { static long toMillis(long timestamp) { if (timestamp < 10000000000L) { return timestamp * 1000; } else if (timestamp < 10000000000000L) { return timestamp; } return timestamp / 1000; } private ScanSummary(); static ScanSummary.Builder of(TableScan scan); }### Answer: @Test public void testToMillis() { long millis = 1542750947417L; Assert.assertEquals(1542750947000L, toMillis(millis / 1000)); Assert.assertEquals(1542750947417L, toMillis(millis)); Assert.assertEquals(1542750947417L, toMillis(millis * 1000 + 918)); }
### Question: SchemaUpdate implements UpdateSchema { @Override public Schema apply() { return applyChanges(schema, deletes, updates, adds); } SchemaUpdate(TableOperations ops); SchemaUpdate(Schema schema, int lastColumnId); @Override UpdateSchema addColumn(String name, Type type); @Override UpdateSchema addColumn(String parent, String name, Type type); @Override UpdateSchema deleteColumn(String name); @Override UpdateSchema renameColumn(String name, String newName); @Override UpdateSchema updateColumn(String name, Type.PrimitiveType newType); @Override Schema apply(); @Override void commit(); }### Answer: @Test public void testNoChanges() { Schema identical = new SchemaUpdate(SCHEMA, SCHEMA_LAST_COLUMN_ID).apply(); Assert.assertEquals("Should not include any changes", SCHEMA.asStruct(), identical.asStruct()); }
### Question: SchemaUpdate implements UpdateSchema { @Override public UpdateSchema addColumn(String name, Type type) { Preconditions.checkArgument(!name.contains("."), "Cannot add column with ambiguous name: %s, use addColumn(parent, name, type)", name); return addColumn(null, name, type); } SchemaUpdate(TableOperations ops); SchemaUpdate(Schema schema, int lastColumnId); @Override UpdateSchema addColumn(String name, Type type); @Override UpdateSchema addColumn(String parent, String name, Type type); @Override UpdateSchema deleteColumn(String name); @Override UpdateSchema renameColumn(String name, String newName); @Override UpdateSchema updateColumn(String name, Type.PrimitiveType newType); @Override Schema apply(); @Override void commit(); }### Answer: @Test public void testAmbiguousAdd() { AssertHelpers.assertThrows("Should reject ambiguous column name", IllegalArgumentException.class, "ambiguous name: preferences.booleans", () -> { UpdateSchema update = new SchemaUpdate(SCHEMA, SCHEMA_LAST_COLUMN_ID); update.addColumn("preferences.booleans", Types.BooleanType.get()); } ); } @Test public void testAddAlreadyExists() { AssertHelpers.assertThrows("Should reject column name that already exists", IllegalArgumentException.class, "already exists: preferences.feature1", () -> { UpdateSchema update = new SchemaUpdate(SCHEMA, SCHEMA_LAST_COLUMN_ID); update.addColumn("preferences", "feature1", Types.BooleanType.get()); } ); AssertHelpers.assertThrows("Should reject column name that already exists", IllegalArgumentException.class, "already exists: preferences", () -> { UpdateSchema update = new SchemaUpdate(SCHEMA, SCHEMA_LAST_COLUMN_ID); update.addColumn("preferences", Types.BooleanType.get()); } ); }
### Question: SchemaUpdate implements UpdateSchema { @Override public UpdateSchema deleteColumn(String name) { Types.NestedField field = schema.findField(name); Preconditions.checkArgument(field != null, "Cannot delete missing column: %s", name); Preconditions.checkArgument(!adds.containsKey(field.fieldId()), "Cannot delete a column that has additions: %s", name); Preconditions.checkArgument(!updates.containsKey(field.fieldId()), "Cannot delete a column that has updates: %s", name); deletes.add(field.fieldId()); return this; } SchemaUpdate(TableOperations ops); SchemaUpdate(Schema schema, int lastColumnId); @Override UpdateSchema addColumn(String name, Type type); @Override UpdateSchema addColumn(String parent, String name, Type type); @Override UpdateSchema deleteColumn(String name); @Override UpdateSchema renameColumn(String name, String newName); @Override UpdateSchema updateColumn(String name, Type.PrimitiveType newType); @Override Schema apply(); @Override void commit(); }### Answer: @Test public void testDeleteMissingColumn() { AssertHelpers.assertThrows("Should reject delete missing column", IllegalArgumentException.class, "missing column: col", () -> { UpdateSchema update = new SchemaUpdate(SCHEMA, SCHEMA_LAST_COLUMN_ID); update.deleteColumn("col"); } ); }
### Question: SchemaUpdate implements UpdateSchema { @Override public UpdateSchema renameColumn(String name, String newName) { Types.NestedField field = schema.findField(name); Preconditions.checkArgument(field != null, "Cannot rename missing column: %s", name); Preconditions.checkArgument(!deletes.contains(field.fieldId()), "Cannot rename a column that will be deleted: %s", field.name()); int fieldId = field.fieldId(); Types.NestedField update = updates.get(fieldId); if (update != null) { updates.put(fieldId, Types.NestedField.required(fieldId, newName, update.type())); } else { updates.put(fieldId, Types.NestedField.required(fieldId, newName, field.type())); } return this; } SchemaUpdate(TableOperations ops); SchemaUpdate(Schema schema, int lastColumnId); @Override UpdateSchema addColumn(String name, Type type); @Override UpdateSchema addColumn(String parent, String name, Type type); @Override UpdateSchema deleteColumn(String name); @Override UpdateSchema renameColumn(String name, String newName); @Override UpdateSchema updateColumn(String name, Type.PrimitiveType newType); @Override Schema apply(); @Override void commit(); }### Answer: @Test public void testRenameMissingColumn() { AssertHelpers.assertThrows("Should reject rename missing column", IllegalArgumentException.class, "missing column: col", () -> { UpdateSchema update = new SchemaUpdate(SCHEMA, SCHEMA_LAST_COLUMN_ID); update.renameColumn("col", "fail"); } ); }
### Question: SchemaUpdate implements UpdateSchema { @Override public UpdateSchema updateColumn(String name, Type.PrimitiveType newType) { Types.NestedField field = schema.findField(name); Preconditions.checkArgument(field != null, "Cannot update missing column: %s", name); Preconditions.checkArgument(!deletes.contains(field.fieldId()), "Cannot update a column that will be deleted: %s", field.name()); Preconditions.checkArgument(TypeUtil.isPromotionAllowed(field.type(), newType), "Cannot change column type: %s: %s -> %s", name, field.type(), newType); int fieldId = field.fieldId(); Types.NestedField rename = updates.get(fieldId); if (rename != null) { updates.put(fieldId, Types.NestedField.required(fieldId, rename.name(), newType)); } else { updates.put(fieldId, Types.NestedField.required(fieldId, field.name(), newType)); } return this; } SchemaUpdate(TableOperations ops); SchemaUpdate(Schema schema, int lastColumnId); @Override UpdateSchema addColumn(String name, Type type); @Override UpdateSchema addColumn(String parent, String name, Type type); @Override UpdateSchema deleteColumn(String name); @Override UpdateSchema renameColumn(String name, String newName); @Override UpdateSchema updateColumn(String name, Type.PrimitiveType newType); @Override Schema apply(); @Override void commit(); }### Answer: @Test public void testUpdateMissingColumn() { AssertHelpers.assertThrows("Should reject rename missing column", IllegalArgumentException.class, "missing column: col", () -> { UpdateSchema update = new SchemaUpdate(SCHEMA, SCHEMA_LAST_COLUMN_ID); update.updateColumn("col", Types.DateType.get()); } ); }
### Question: StringUtils { public static boolean isEmpty(String str) { return str == null || str.length() == 0; } static boolean isEmpty(String str); static String leftPad(String str, int size); static String leftPad(String str, int size, char padChar); static String leftPad(String str, int size, String padStr); static String padding(int repeat, char padChar); }### Answer: @Test public void isEmpty() { Assert.assertTrue(StringUtils.isEmpty(null)); Assert.assertTrue(StringUtils.isEmpty("")); Assert.assertFalse(StringUtils.isEmpty(" ")); Assert.assertFalse(StringUtils.isEmpty("bob")); Assert.assertFalse(StringUtils.isEmpty(" bob ")); }
### Question: FlakeEncodingProvider implements EncodingProvider { @Override public long encodeAsLong(long time, int sequence) { throw new UnsupportedOperationException("Long value not supported"); } FlakeEncodingProvider(long machineId); @Override byte[] encodeAsBytes(long time, int sequence); @Override long encodeAsLong(long time, int sequence); @Override String encodeAsString(long time, int sequence); @Override int maxSequenceNumbers(); }### Answer: @Test public void notImplemented() { try { new FlakeEncodingProvider(1).encodeAsLong(1, 1); Assert.fail("Expected UnsupportedOperationException"); } catch (UnsupportedOperationException e) { Assert.assertTrue(e.getMessage().contains("Long value not supported")); } }
### Question: StringUtils { public static String leftPad(String str, int size) { return leftPad(str, size, ' '); } static boolean isEmpty(String str); static String leftPad(String str, int size); static String leftPad(String str, int size, char padChar); static String leftPad(String str, int size, String padStr); static String padding(int repeat, char padChar); }### Answer: @Test public void leftPad() { Assert.assertNull(StringUtils.leftPad(null, 9)); Assert.assertEquals(" ", StringUtils.leftPad("", 3)); Assert.assertEquals("bat", StringUtils.leftPad("bat", 3)); Assert.assertEquals(" bat", StringUtils.leftPad("bat", 5)); Assert.assertEquals("bat", StringUtils.leftPad("bat", 1)); Assert.assertEquals("bat", StringUtils.leftPad("bat", -1)); Assert.assertEquals(8193, StringUtils.leftPad("", 8193).length()); Assert.assertNull(StringUtils.leftPad(null, 9, "ddd")); Assert.assertEquals("zzz", StringUtils.leftPad("", 3, "z")); Assert.assertEquals("bat", StringUtils.leftPad("bat", 3, "yz")); Assert.assertEquals("yzbat", StringUtils.leftPad("bat", 5, "yz")); Assert.assertEquals("yzyzybat", StringUtils.leftPad("bat", 8, "yz")); Assert.assertEquals("bat", StringUtils.leftPad("bat", 1, "yz")); Assert.assertEquals("bat", StringUtils.leftPad("bat", -1, "yz")); Assert.assertEquals(" bat", StringUtils.leftPad("bat", 5, null)); Assert.assertEquals(" bat", StringUtils.leftPad("bat", 5, "")); }
### Question: StringUtils { public static String padding(int repeat, char padChar) throws IndexOutOfBoundsException { if (repeat < 0) { throw new IndexOutOfBoundsException("Cannot pad a negative amount: " + repeat); } final char[] buf = new char[repeat]; for (int i = 0; i < buf.length; i++) { buf[i] = padChar; } return new String(buf); } static boolean isEmpty(String str); static String leftPad(String str, int size); static String leftPad(String str, int size, char padChar); static String leftPad(String str, int size, String padStr); static String padding(int repeat, char padChar); }### Answer: @Test public void padding() { Assert.assertEquals("", padding(0, 'e')); Assert.assertEquals("eee", padding(3, 'e')); try { padding(-2, 'e'); Assert.fail("Expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { Assert.assertTrue(e.getMessage().contains("Cannot pad a negative amount:")); } }
### Question: PidUtils { public static int pid() { int localPID = 0; try { String name = ManagementFactory.getRuntimeMXBean().getName(); String[] nameSplit = name.split("@"); if(nameSplit.length > 1) { localPID = Integer.parseInt(nameSplit[0]); } return localPID; } catch(Throwable t) { throw new UnsupportedOperationException("An error occurred while getting the PID: " + t.getMessage()) ; } } static int pid(); }### Answer: @Test public void verifyPid() { int pid = PidUtils.pid(); Assert.assertTrue("Could not retrieve PID", pid != 0); Assert.assertTrue("Negative PID", pid > 0); }
### Question: MacUtils { public static byte[] macAddress() { byte[] override = getOverride(); return override != null ? override : realMacAddress(); } static byte[] getOverride(); static byte[] realMacAddress(); static byte[] macAddress(); static final String OVERRIDE_MAC_PROP; }### Answer: @Test public void verifyMac() { byte[] mac; try { mac = MacUtils.macAddress(); } catch(UnsupportedOperationException e) { e.printStackTrace(); System.setProperty(MacUtils.OVERRIDE_MAC_PROP, "00:DE:AD:BE:EF:00"); mac = MacUtils.macAddress(); } Assert.assertNotNull("Could not retrieve MAC", mac); Assert.assertTrue("Invalid MAC address", mac.length == 6); } @Test public void verifyOverride() { System.setProperty(MacUtils.OVERRIDE_MAC_PROP, "00:DE:AD:BE:EF:11"); byte[] mac = MacUtils.macAddress(); Assert.assertNotNull("Could not retrieve MAC", mac); Assert.assertTrue("Invalid MAC address", mac.length == 6); Assert.assertEquals("Unexpected MAC address", "[0, -34, -83, -66, -17, 17]", Arrays.toString(mac)); System.clearProperty(MacUtils.OVERRIDE_MAC_PROP); }
### Question: MacUtils { public static byte[] getOverride() { String overrideMac = System.getProperty(OVERRIDE_MAC_PROP); byte[] macBytes = null; if (overrideMac != null) { ByteArrayOutputStream out = new ByteArrayOutputStream(); String[] rawBytes = overrideMac.split(":"); if (rawBytes.length == 6) { try { for (String b : rawBytes) { out.write(Integer.parseInt(b, 16)); } macBytes = out.toByteArray(); } catch (NumberFormatException e) { } } } return macBytes; } static byte[] getOverride(); static byte[] realMacAddress(); static byte[] macAddress(); static final String OVERRIDE_MAC_PROP; }### Answer: @Test public void bogusOverride() { System.setProperty(MacUtils.OVERRIDE_MAC_PROP, "totally not a MAC"); byte[] mac = MacUtils.getOverride(); Assert.assertNull("Retrieved a bogus MAC", mac); System.clearProperty(MacUtils.OVERRIDE_MAC_PROP); } @Test public void slightlyBogusOverride() { System.setProperty(MacUtils.OVERRIDE_MAC_PROP, "00:DE:AD:BE:EF:QQ"); byte[] mac = MacUtils.getOverride(); Assert.assertNull("Retrieved a bogus MAC", mac); System.clearProperty(MacUtils.OVERRIDE_MAC_PROP); }
### Question: MacMachineIdProvider implements MachineIdProvider { @Override public long getMachineId() { return machineId; } MacMachineIdProvider(); @Override long getMachineId(); }### Answer: @Test public void validateProvider() { Assert.assertEquals("Machine id's are not deterministic", new MacMachineIdProvider().getMachineId(), new MacMachineIdProvider().getMachineId()); if(new MacMachineIdProvider().getMachineId() == 0L) { System.err.println("Could not detect MAC address"); } }
### Question: MacPidMachineIdProvider implements MachineIdProvider { @Override public long getMachineId() { return machineId; } MacPidMachineIdProvider(); @Override long getMachineId(); }### Answer: @Test public void validateProvider() { Assert.assertEquals("Machine id's are not deterministic", new MacPidMachineIdProvider().getMachineId(), new MacPidMachineIdProvider().getMachineId()); if(new MacPidMachineIdProvider().getMachineId() == 0L) { System.err.println("Could not detect MAC address"); } }
### Question: SPPDecoder implements MALDecoder { @Override public Duration decodeNullableDuration() throws MALException { return isNull() ? null : decodeDuration(); } SPPDecoder(final InputStream inputStream, final Map properties); @Override Boolean decodeBoolean(); @Override Boolean decodeNullableBoolean(); @Override Float decodeFloat(); @Override Float decodeNullableFloat(); @Override Double decodeDouble(); @Override Double decodeNullableDouble(); @Override Byte decodeOctet(); @Override Byte decodeNullableOctet(); @Override UOctet decodeUOctet(); @Override UOctet decodeNullableUOctet(); @Override Short decodeShort(); @Override Short decodeNullableShort(); @Override UShort decodeUShort(); @Override UShort decodeNullableUShort(); @Override Integer decodeInteger(); @Override Integer decodeNullableInteger(); @Override UInteger decodeUInteger(); @Override UInteger decodeNullableUInteger(); @Override Long decodeLong(); @Override Long decodeNullableLong(); @Override ULong decodeULong(); @Override ULong decodeNullableULong(); @Override String decodeString(); @Override String decodeNullableString(); @Override Blob decodeBlob(); @Override Blob decodeNullableBlob(); @Override Duration decodeDuration(); @Override Duration decodeNullableDuration(); @Override FineTime decodeFineTime(); @Override FineTime decodeNullableFineTime(); @Override Identifier decodeIdentifier(); @Override Identifier decodeNullableIdentifier(); @Override Time decodeTime(); @Override Time decodeNullableTime(); @Override URI decodeURI(); @Override URI decodeNullableURI(); @Override Element decodeElement(final Element element); @Override Element decodeNullableElement(final Element element); @Override Attribute decodeAttribute(); @Override Attribute decodeNullableAttribute(); @Override MALListDecoder createListDecoder(final List list); }### Answer: @Test public void testDecodeNullableDuration() throws Exception { newBuffer(new byte[]{ 0, 1, 0 }); setTimeProperties("DURATION", "00100000", "9999-01-23T21:43:56", null); assertEquals(null, decoder.decodeNullableDuration()); assertEquals(new Duration(0), decoder.decodeNullableDuration()); }
### Question: SPPElementStreamFactory extends MALElementStreamFactory { @Override protected void init(final String protocol, final Map properties) throws IllegalArgumentException, MALException { if (protocol == null) { throw new IllegalArgumentException(ILLEGAL_NULL_ARGUMENT); } this.properties = properties; } @Override MALElementInputStream createInputStream(final InputStream is); @Override MALElementInputStream createInputStream(final byte[] bytes, final int offset); @Override MALElementOutputStream createOutputStream(final OutputStream os); @Override Blob encode(final Object[] elements, final MALEncodingContext ctx); }### Answer: @Test public void testInit() throws Exception { String protocol = ""; Map properties = null; SPPElementStreamFactory instance = new SPPElementStreamFactory(); instance.init(protocol, properties); } @Test(expected = IllegalArgumentException.class) public void testInitExpectedExcpetion() throws Exception { String protocol = null; Map properties = null; SPPElementStreamFactory instance = new SPPElementStreamFactory(); instance.init(protocol, properties); }
### Question: RequestSignature implements HttpRequestInterceptor { @Override public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { try { this.messageSigner.sign(new Request(request)); } catch (GeneralSecurityException e) { throw new HttpException("Can't sign HTTP request '" + request + "'", e); } } RequestSignature(HttpMessageSigner messageSigner); @Override void process(HttpRequest request, HttpContext context); }### Answer: @Test public void testInterceptor() throws GeneralSecurityException, HttpException, IOException { HttpMessageSigner httpSignature = HttpMessageSigner.builder() .algorithm(Algorithm.RSA_SHA256) .keyMap(HashKeyMap.INSTANCE) .addHeaderToSign(HttpMessageSigner.REQUEST_TARGET) .addHeaderToSign("Date") .addHeaderToSign("Content-Length") .addHeaderToSign("Digest") .keyId("myKeyId").build(); HttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("GET", "http: request.setEntity(new StringEntity("Hello World!")); createHttpProcessor(httpSignature).process(request, new BasicHttpContext()); SignatureHeaderVerifier signatureVerifier = SignatureHeaderVerifier.builder().keyMap(HashKeyMap.INSTANCE).build(); assertTrue(signatureVerifier.verify(new Request(request))); }
### Question: LinearTranslation { public LinearTranslation(double in1, double out1, double in2, double out2) { if (Math.abs(in1 - in2) < EQUALITY_TOLERANCE) { throw new IllegalArgumentException("in1 and in2 are approximately equal"); } double divisor = in1 - in2; this.m = (out1 - out2) / divisor; this.b = (in1 * out2 - in2 * out1) / divisor; } LinearTranslation(double in1, double out1, double in2, double out2); double translate(double in); }### Answer: @Test public void linearTranslation() { LinearTranslation ctof = new LinearTranslation(0, 32, 100, 212); assertEquals(32, ctof.translate(0), CLOSE_ENOUGH); assertEquals(212, ctof.translate(100), CLOSE_ENOUGH); assertEquals(98.6, ctof.translate(37), CLOSE_ENOUGH); assertEquals(-40, ctof.translate(-40), CLOSE_ENOUGH); LinearTranslation reversed = new LinearTranslation(5, 42, 69, 0); assertEquals(-21, reversed.translate(101), CLOSE_ENOUGH); }
### Question: ParsedOptions implements CaliperOptions { public static ParsedOptions from(String[] args) throws InvalidCommandException { ParsedOptions options = new ParsedOptions(); CommandLineParser<ParsedOptions> parser = CommandLineParser.forClass(ParsedOptions.class); try { parser.parseAndInject(args, options); } catch (InvalidCommandException e) { e.setUsage(USAGE); throw e; } return options; } private ParsedOptions(); static ParsedOptions from(String[] args); @Override boolean dryRun(); @Override ImmutableSet<String> benchmarkMethodNames(); @Override boolean verbose(); @Override boolean printConfiguration(); @Override int trialsPerScenario(); @Override ShortDuration timeLimit(); @Override String runName(); @Override ImmutableSet<String> vmNames(); @Override ImmutableSet<String> instrumentNames(); @Override ImmutableSetMultimap<String, String> userParameters(); @Override ImmutableSetMultimap<String, String> vmArguments(); @Override ImmutableMap<String, String> configProperties(); @Override File caliperDirectory(); @Override File caliperConfigFile(); @Override String benchmarkClassName(); @Override String toString(); }### Answer: @Test public void testNoOptions() { try { ParsedOptions.from(new String[] {}); fail(); } catch (InvalidCommandException expected) { assertEquals("No benchmark class specified", expected.getMessage()); } } @Test public void testHelp() throws InvalidCommandException { try { ParsedOptions.from(new String[] {"--help"}); fail(); } catch (DisplayUsageException expected) { } }
### Question: RuntimeWorker extends Worker { @VisibleForTesting static long calculateTargetReps(long reps, long nanos, long targetNanos, double gaussian) { double targetReps = (((double) reps) / nanos) * targetNanos; return Math.max(1L, Math.round((gaussian * (targetReps / 5)) + targetReps)); } RuntimeWorker(Object benchmark, Method method, Random random, Ticker ticker, Map<String, String> workerOptions); @Override void bootstrap(); @Override void preMeasure(); @Override Iterable<Measurement> measure(); }### Answer: @Test public void testCalculateTargetReps_tinyBenchmark() { ShortDuration oneCycle = ShortDuration.of(new BigDecimal("2.0e-10"), SECONDS); long targetReps = calculateTargetReps(INITIAL_REPS, oneCycle.times(INITIAL_REPS).to(NANOSECONDS), TIMING_INTERVAL.to(NANOSECONDS), 0.0); long expectedReps = TIMING_INTERVAL.toPicos() / oneCycle.toPicos(); assertEquals(expectedReps, targetReps); } @Test public void testCalculateTargetReps_hugeBenchmark() { long targetReps = calculateTargetReps(INITIAL_REPS, HOURS.toNanos(1), TIMING_INTERVAL.to(NANOSECONDS), 0.0); assertEquals(1, targetReps); } @Test public void testCalculateTargetReps_applyRandomness() { long targetReps = calculateTargetReps(INITIAL_REPS, MILLISECONDS.toNanos(100), TIMING_INTERVAL.to(NANOSECONDS), 0.5); assertEquals(110, targetReps); }
### Question: CaliperConfigLoader { public CaliperConfig loadOrCreate() throws InvalidConfigurationException { File configFile = options.caliperConfigFile(); ImmutableMap<String, String> defaults; try { defaults = Util.loadProperties( Util.resourceSupplier(CaliperConfig.class, "global-config.properties")); } catch (IOException impossible) { throw new AssertionError(impossible); } if (configFile.exists()) { try { ImmutableMap<String, String> user = Util.loadProperties(Files.asByteSource(configFile)); return new CaliperConfig(mergeProperties(options.configProperties(), user, defaults)); } catch (IOException keepGoing) { } } ByteSource supplier = Util.resourceSupplier(CaliperConfig.class, "default-config.properties"); tryCopyIfNeeded(supplier, configFile); ImmutableMap<String, String> user; try { user = Util.loadProperties(supplier); } catch (IOException e) { throw new AssertionError(e); } return new CaliperConfig(mergeProperties(options.configProperties(), user, defaults)); } @Inject CaliperConfigLoader(CaliperOptions options); CaliperConfig loadOrCreate(); }### Answer: @Test public void loadOrCreate_configFileExistsNoOverride() throws Exception { when(optionsMock.caliperConfigFile()).thenReturn(tempConfigFile); when(optionsMock.configProperties()).thenReturn(ImmutableMap.<String, String>of()); CaliperConfigLoader loader = new CaliperConfigLoader(optionsMock); CaliperConfig config = loader.loadOrCreate(); assertEquals("franklin", config.properties.get("some.property")); } @Test public void loadOrCreate_configFileExistsWithOverride() throws Exception { when(optionsMock.caliperConfigFile()).thenReturn(tempConfigFile); when(optionsMock.configProperties()).thenReturn(ImmutableMap.of( "some.property", "tacos")); CaliperConfigLoader loader = new CaliperConfigLoader(optionsMock); CaliperConfig config = loader.loadOrCreate(); assertEquals("tacos", config.properties.get("some.property")); }
### Question: LoggingConfigLoader { @VisibleForTesting void maybeLoadDefaultLogConfiguration(LogManager logManager) throws SecurityException, IOException { logManager.reset(); File logDirectory = new File(caliperDirectory, "log"); logDirectory.mkdirs(); FileHandler fileHandler = new FileHandler(String.format("%s%c%s.%s.log", logDirectory.getAbsolutePath(), File.separatorChar, run.startTime(), run.id())); fileHandler.setEncoding(Charsets.UTF_8.name()); fileHandler.setFormatter(new SimpleFormatter()); Logger globalLogger = logManager.getLogger(""); globalLogger.addHandler(fileHandler); } @Inject LoggingConfigLoader(@CaliperDirectory File caliperDirectory, LogManager logManager, Run run); }### Answer: @Test public void testLoadDefaultLogConfiguration() throws SecurityException, IOException { when(logManager.getLogger("")).thenReturn(logger); loader.maybeLoadDefaultLogConfiguration(logManager); verify(logManager).reset(); verify(logger).addHandler(handlerCaptor.capture()); FileHandler fileHandler = (FileHandler) handlerCaptor.getValue(); assertEquals(UTF_8.name(), fileHandler.getEncoding()); assertTrue(fileHandler.getFormatter() instanceof SimpleFormatter); fileHandler.publish(new LogRecord(INFO, "some message")); File logFile = new File(new File(caliperDirectory, "log"), startTime.toString() + "." + runId + ".log"); assertTrue(logFile.isFile()); assertTrue(Files.toString(logFile, UTF_8).contains("some message")); }
### Question: VmConfig { public File javaExecutable() { return new File(javaHome, "bin/java"); } private VmConfig(Builder builder); File javaHome(); File javaExecutable(); ImmutableList<String> options(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void testExecutable() { assertEquals(new File("/some/home/dir/bin/java"), new VmConfig.Builder(new File("/some/home/dir")).build().javaExecutable()); }
### Question: CaliperConfig { public VmConfig getDefaultVmConfig() { return new Builder(new File(System.getProperty("java.home"))) .addAllOptions(ManagementFactory.getRuntimeMXBean().getInputArguments()) .addAllOptions(getArgs(subgroupMap(properties, "vm"))) .build(); } @VisibleForTesting CaliperConfig(ImmutableMap<String, String> properties); ImmutableMap<String, String> properties(); VmConfig getDefaultVmConfig(); VmConfig getVmConfig(String name); ImmutableSet<String> getConfiguredInstruments(); InstrumentConfig getInstrumentConfig(String name); ImmutableSet<Class<? extends ResultProcessor>> getConfiguredResultProcessors(); ResultProcessorConfig getResultProcessorConfig( Class<? extends ResultProcessor> resultProcessorClass); @Override String toString(); }### Answer: @Test public void getDefaultVmConfig() throws Exception { CaliperConfig configuration = new CaliperConfig( ImmutableMap.of("vm.args", "-very -special=args")); VmConfig defaultVmConfig = configuration.getDefaultVmConfig(); assertEquals(new File(System.getProperty("java.home")), defaultVmConfig.javaHome()); ImmutableList<String> expectedArgs = new ImmutableList.Builder<String>() .addAll(ManagementFactory.getRuntimeMXBean().getInputArguments()) .add("-very") .add("-special=args") .build(); assertEquals(expectedArgs, defaultVmConfig.options()); }
### Question: CaliperConfig { public InstrumentConfig getInstrumentConfig(String name) { checkNotNull(name); ImmutableMap<String, String> instrumentGroupMap = subgroupMap(properties, "instrument"); ImmutableMap<String, String> insrumentMap = subgroupMap(instrumentGroupMap, name); @Nullable String className = insrumentMap.get("class"); checkArgument(className != null, "no instrument configured named %s", name); return new InstrumentConfig.Builder() .className(className) .addAllOptions(subgroupMap(insrumentMap, "options")) .build(); } @VisibleForTesting CaliperConfig(ImmutableMap<String, String> properties); ImmutableMap<String, String> properties(); VmConfig getDefaultVmConfig(); VmConfig getVmConfig(String name); ImmutableSet<String> getConfiguredInstruments(); InstrumentConfig getInstrumentConfig(String name); ImmutableSet<Class<? extends ResultProcessor>> getConfiguredResultProcessors(); ResultProcessorConfig getResultProcessorConfig( Class<? extends ResultProcessor> resultProcessorClass); @Override String toString(); }### Answer: @Test public void getInstrumentConfig() throws Exception { CaliperConfig configuration = new CaliperConfig(ImmutableMap.of( "instrument.test.class", "test.ClassName", "instrument.test.options.a", "1", "instrument.test.options.b", "excited b b excited")); assertEquals( new InstrumentConfig.Builder() .className("test.ClassName") .addOption("a", "1") .addOption("b", "excited b b excited") .build(), configuration.getInstrumentConfig("test")); } @Test public void getInstrumentConfig_notConfigured() throws Exception { CaliperConfig configuration = new CaliperConfig(ImmutableMap.of( "instrument.test.options.a", "1", "instrument.test.options.b", "excited b b excited")); try { configuration.getInstrumentConfig("test"); fail(); } catch (IllegalArgumentException expected) {} }
### Question: CaliperConfig { public ImmutableSet<String> getConfiguredInstruments() { ImmutableSet.Builder<String> resultBuilder = ImmutableSet.builder(); for (String key : subgroupMap(properties, "instrument").keySet()) { Matcher matcher = INSTRUMENT_CLASS_PATTERN.matcher(key); if (matcher.matches()) { resultBuilder.add(matcher.group(1)); } } return resultBuilder.build(); } @VisibleForTesting CaliperConfig(ImmutableMap<String, String> properties); ImmutableMap<String, String> properties(); VmConfig getDefaultVmConfig(); VmConfig getVmConfig(String name); ImmutableSet<String> getConfiguredInstruments(); InstrumentConfig getInstrumentConfig(String name); ImmutableSet<Class<? extends ResultProcessor>> getConfiguredResultProcessors(); ResultProcessorConfig getResultProcessorConfig( Class<? extends ResultProcessor> resultProcessorClass); @Override String toString(); }### Answer: @Test public void getConfiguredInstruments() throws Exception { CaliperConfig configuration = new CaliperConfig(ImmutableMap.of( "instrument.test.class", "test.ClassName", "instrument.test2.class", "test.ClassName", "instrument.test3.options.a", "1", "instrument.test4.class", "test.ClassName", "instrument.test4.options.b", "excited b b excited")); assertEquals(ImmutableSet.of("test", "test2", "test4"), configuration.getConfiguredInstruments()); }
### Question: CaliperConfig { public ImmutableSet<Class<? extends ResultProcessor>> getConfiguredResultProcessors() { return resultProcessorConfigs.keySet(); } @VisibleForTesting CaliperConfig(ImmutableMap<String, String> properties); ImmutableMap<String, String> properties(); VmConfig getDefaultVmConfig(); VmConfig getVmConfig(String name); ImmutableSet<String> getConfiguredInstruments(); InstrumentConfig getInstrumentConfig(String name); ImmutableSet<Class<? extends ResultProcessor>> getConfiguredResultProcessors(); ResultProcessorConfig getResultProcessorConfig( Class<? extends ResultProcessor> resultProcessorClass); @Override String toString(); }### Answer: @Test public void getConfiguredResultProcessors() throws Exception { assertEquals(ImmutableSet.of(), new CaliperConfig(ImmutableMap.<String, String>of()).getConfiguredResultProcessors()); CaliperConfig configuration = new CaliperConfig(ImmutableMap.of( "results.test.class", TestResultProcessor.class.getName())); assertEquals(ImmutableSet.of(TestResultProcessor.class), configuration.getConfiguredResultProcessors()); }
### Question: CaliperConfig { public ResultProcessorConfig getResultProcessorConfig( Class<? extends ResultProcessor> resultProcessorClass) { return resultProcessorConfigs.get(resultProcessorClass); } @VisibleForTesting CaliperConfig(ImmutableMap<String, String> properties); ImmutableMap<String, String> properties(); VmConfig getDefaultVmConfig(); VmConfig getVmConfig(String name); ImmutableSet<String> getConfiguredInstruments(); InstrumentConfig getInstrumentConfig(String name); ImmutableSet<Class<? extends ResultProcessor>> getConfiguredResultProcessors(); ResultProcessorConfig getResultProcessorConfig( Class<? extends ResultProcessor> resultProcessorClass); @Override String toString(); }### Answer: @Test public void getResultProcessorConfig() throws Exception { CaliperConfig configuration = new CaliperConfig(ImmutableMap.of( "results.test.class", TestResultProcessor.class.getName(), "results.test.options.g", "ak", "results.test.options.c", "aliper")); assertEquals( new ResultProcessorConfig.Builder() .className(TestResultProcessor.class.getName()) .addOption("g", "ak") .addOption("c", "aliper") .build(), configuration.getResultProcessorConfig(TestResultProcessor.class)); }
### Question: WorkerProcess extends Process { @Override public int waitFor() throws InterruptedException { int waitFor = delegate.waitFor(); shutdownHookRegistrar.removeShutdownHook(shutdownHook); return waitFor; } WorkerProcess(ProcessBuilder processBuilder); @VisibleForTesting WorkerProcess(ShutdownHookRegistrar shutdownHookRegistrar, Process process); @Override OutputStream getOutputStream(); @Override InputStream getInputStream(); @Override InputStream getErrorStream(); @Override int waitFor(); @Override int exitValue(); @Override void destroy(); }### Answer: @Test public void shutdownHook_waitFor() throws Exception { verify(registrar).addShutdownHook(hookCaptor.capture()); when(delegate.waitFor()).thenReturn(0); workerProcess.waitFor(); verify(registrar).removeShutdownHook(hookCaptor.getValue()); }
### Question: WorkerProcess extends Process { @Override public int exitValue() { int exitValue = delegate.exitValue(); shutdownHookRegistrar.removeShutdownHook(shutdownHook); return exitValue; } WorkerProcess(ProcessBuilder processBuilder); @VisibleForTesting WorkerProcess(ShutdownHookRegistrar shutdownHookRegistrar, Process process); @Override OutputStream getOutputStream(); @Override InputStream getInputStream(); @Override InputStream getErrorStream(); @Override int waitFor(); @Override int exitValue(); @Override void destroy(); }### Answer: @Test public void shutdownHook_exitValueThrows() throws Exception { verify(registrar).addShutdownHook(hookCaptor.capture()); when(delegate.exitValue()).thenThrow(new IllegalThreadStateException()); try { workerProcess.exitValue(); fail(); } catch (IllegalThreadStateException expected) {} verify(registrar, never()).removeShutdownHook(hookCaptor.getValue()); } @Test public void shutdownHook_exitValue() throws Exception { verify(registrar).addShutdownHook(hookCaptor.capture()); when(delegate.exitValue()).thenReturn(0); workerProcess.exitValue(); verify(registrar).removeShutdownHook(hookCaptor.getValue()); }
### Question: WorkerProcess extends Process { @Override public void destroy() { delegate.destroy(); shutdownHookRegistrar.removeShutdownHook(shutdownHook); } WorkerProcess(ProcessBuilder processBuilder); @VisibleForTesting WorkerProcess(ShutdownHookRegistrar shutdownHookRegistrar, Process process); @Override OutputStream getOutputStream(); @Override InputStream getInputStream(); @Override InputStream getErrorStream(); @Override int waitFor(); @Override int exitValue(); @Override void destroy(); }### Answer: @Test public void shutdownHook_destroy() throws Exception { verify(registrar).addShutdownHook(hookCaptor.capture()); workerProcess.destroy(); verify(delegate).destroy(); verify(registrar).removeShutdownHook(hookCaptor.getValue()); }
### Question: AllocationInstrument extends Instrument { @Override ImmutableSet<String> getExtraCommandLineArgs() { String agentJar = options.get(ALLOCATION_AGENT_JAR_OPTION); if (Strings.isNullOrEmpty(agentJar)) { try { Optional<File> instrumentJar = findAllocationInstrumentJarOnClasspath(); if (instrumentJar.isPresent()) { agentJar = instrumentJar.get().getAbsolutePath(); } } catch (IOException e) { logger.log(SEVERE, "An exception occurred trying to locate the allocation agent jar on the classpath", e); } } if (Strings.isNullOrEmpty(agentJar) || !new File(agentJar).exists()) { throw new IllegalStateException("Can't find required allocationinstrumenter agent jar"); } return new ImmutableSet.Builder<String>() .addAll(super.getExtraCommandLineArgs()) .add("-javaagent:" + agentJar) .add("-Xbootclasspath/a:" + agentJar) .build(); } @Override boolean isBenchmarkMethod(Method method); @Override Instrumentation createInstrumentation(Method benchmarkMethod); @Override ImmutableSet<String> instrumentOptions(); }### Answer: @Test public void testGetExtraCommandLineArgs() throws Exception { AllocationInstrument instrument = new AllocationInstrument(); File fakeJar = File.createTempFile("fake", "jar"); fakeJar.deleteOnExit(); instrument.setOptions(ImmutableMap.of("allocationAgentJar", fakeJar.getAbsolutePath())); ImmutableSet<String> expected = new ImmutableSet.Builder<String>() .addAll(Instrument.JVM_ARGS) .add("-javaagent:" + fakeJar.getAbsolutePath()) .add("-Xbootclasspath/a:" + fakeJar.getAbsolutePath()) .add("-Dsun.reflect.inflationThreshold=0") .build(); assertEquals(expected, instrument.getExtraCommandLineArgs()); fakeJar.delete(); }
### Question: RuntimeInstrument extends Instrument { @Override public boolean isBenchmarkMethod(Method method) { return method.isAnnotationPresent(Benchmark.class) || BenchmarkMethods.isTimeMethod(method) || method.isAnnotationPresent(Macrobenchmark.class); } @Inject RuntimeInstrument(@NanoTimeGranularity ShortDuration nanoTimeGranularity, @Stdout PrintWriter stdout, @Stderr PrintWriter stderr); @Override boolean isBenchmarkMethod(Method method); @Override Instrumentation createInstrumentation(Method benchmarkMethod); }### Answer: @Test public void isBenchmarkMethod() { assertEquals( ImmutableSet.of("macrobenchmark", "microbenchmark", "picobenchmark", "integerParam"), FluentIterable.from(Arrays.asList(RuntimeBenchmark.class.getDeclaredMethods())) .filter(new Predicate<Method>() { @Override public boolean apply(Method input) { return instrument.isBenchmarkMethod(input); } }) .transform(new Function<Method, String>() { @Override public String apply(Method input) { return input.getName(); } }) .toSet()); }
### Question: BenchmarkClass { static BenchmarkClass forClass(Class<?> theClass) throws InvalidBenchmarkException { Class<com.google.caliper.legacy.Benchmark> legacyBenchmarkClass = com.google.caliper.legacy.Benchmark.class; if (legacyBenchmarkClass.isAssignableFrom(theClass)) { return new BenchmarkSubclass(legacyBenchmarkClass, theClass.asSubclass(legacyBenchmarkClass)); } else { return new AnnotatedBenchmark(theClass); } } private BenchmarkClass(Class<?> theClass); ParameterSet userParameters(); ImmutableSet<String> vmOptions(); void setUpBenchmark(Object benchmarkInstance); void cleanup(Object benchmark); String name(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void forClass_inheritenceThrows() throws Exception { try { BenchmarkClass.forClass(MalformedBenhcmark.class); fail(); } catch (InvalidBenchmarkException expected) {} try { BenchmarkClass.forClass(MalformedLegacyBenchmark.class); fail(); } catch (InvalidBenchmarkException expected) {} }
### Question: ScreenshotFileProvider { String cleanseTag(@NonNull String tag) { final String originalTag = tag; tag = tag.toLowerCase().replaceAll(" ", "_").replaceAll("[^A-Za-z0-9_]", ""); if (!originalTag.equals(tag)) { log("Cleansed Tag: [" + originalTag + "] -> [" + tag + "]"); } return tag; } File getScreenshotFile(@NonNull String tag); abstract void clearPreviousScreenshots(); }### Answer: @Test public void testCleanseTag() { String cleansed = new ScreenshotFileProviderNoOp().cleanseTag("a b c * $ ! d"); assertThat(cleansed).isEqualTo("a_b_c____d"); }
### Question: CryptoCompareService implements CryptoService { public static <T> Flux<T> provideCaching(Flux<T> input) { return input; } CryptoCompareService(); Flux<Map<String, Object>> eventsStream(); static Flux<T> provideResilience(Flux<T> input); static Flux<T> provideCaching(Flux<T> input); static final int CACHE_SIZE; }### Answer: @Test public void verifyThatSupportMultiSubscribers() { AtomicInteger subscribtions = new AtomicInteger(0); Flux<Object> source = DirectProcessor .create() .doOnSubscribe(s -> subscribtions.incrementAndGet()); Flux<Object> cachedFlux = CryptoCompareService.provideCaching(source); cachedFlux.subscribe(System.out::println); cachedFlux.subscribe(System.out::println); Assert.assertEquals(1, subscribtions.get()); } @Test public void verifyThatSupportReplayMode() { UnicastProcessor<String> source = UnicastProcessor.create(); ReplayProcessor<String> consumer1 = ReplayProcessor.create(10); ReplayProcessor<String> consumer2 = ReplayProcessor.create(10); Publisher<String> publisher = CryptoCompareService.provideCaching(source); source.onNext("A"); source.onNext("B"); source.onNext("C"); publisher.subscribe(consumer1); source.onNext("D"); source.onNext("E"); source.onNext("F"); publisher.subscribe(consumer2); source.onNext("G"); source.onComplete(); StepVerifier.create(consumer1) .expectSubscription() .expectNext("A", "B", "C", "D", "E", "F", "G") .verifyComplete(); StepVerifier.create(consumer2) .expectSubscription() .expectNext("D", "E", "F", "G") .verifyComplete(); }
### Question: Part2ExtraExercises_Optional { @Optional @Complexity(EASY) public static Publisher<String> concatSeveralSourcesOrdered(Publisher<String>... sources) { throw new RuntimeException("Not implemented"); } @Optional @Complexity(EASY) static String firstElementFromSource(Flux<String> source); @Optional @Complexity(EASY) static Publisher<String> mergeSeveralSourcesSequential(Publisher<String>... sources); @Optional @Complexity(EASY) static Publisher<String> concatSeveralSourcesOrdered(Publisher<String>... sources); @Optional @Complexity(HARD) static Publisher<String> readFile(String filename); }### Answer: @Test public void concatSeveralSourcesOrderedTest() { PublisherProbe[] probes = new PublisherProbe[2]; StepVerifier .withVirtualTime(() -> { PublisherProbe<String> probeA = PublisherProbe.of(Mono.fromCallable(() -> "VANILLA").delaySubscription(Duration.ofSeconds(1))); PublisherProbe<String> probeB = PublisherProbe.of(Mono.fromCallable(() -> "CHOCOLATE")); probes[0] = probeA; probes[1] = probeB; return concatSeveralSourcesOrdered( probeA.mono(), probeB.mono() ); }, 0) .expectSubscription() .then(() -> probes[0].assertWasSubscribed()) .then(() -> probes[1].assertWasNotSubscribed()) .thenRequest(1) .then(() -> probes[0].assertWasRequested()) .then(() -> probes[1].assertWasNotSubscribed()) .expectNoEvent(Duration.ofSeconds(1)) .expectNext("VANILLA") .thenRequest(1) .then(() -> probes[1].assertWasSubscribed()) .then(() -> probes[1].assertWasRequested()) .expectNext("CHOCOLATE") .verifyComplete(); }
### Question: Part2ExtraExercises_Optional { @Optional @Complexity(HARD) public static Publisher<String> readFile(String filename) { throw new RuntimeException("Not implemented"); } @Optional @Complexity(EASY) static String firstElementFromSource(Flux<String> source); @Optional @Complexity(EASY) static Publisher<String> mergeSeveralSourcesSequential(Publisher<String>... sources); @Optional @Complexity(EASY) static Publisher<String> concatSeveralSourcesOrdered(Publisher<String>... sources); @Optional @Complexity(HARD) static Publisher<String> readFile(String filename); }### Answer: @Test public void readFileTest() throws URISyntaxException { URI resourceUri = ClassLoader.getSystemResource("logging.properties").toURI(); StepVerifier.create(readFile(Paths.get(resourceUri).toAbsolutePath().toString())) .expectSubscription() .expectNextCount(5) .verifyComplete(); }
### Question: MediaService { @Optional @Complexity(MEDIUM) public Mono<Video> findVideo(String videoName) { throw new RuntimeException("Not implemented"); } @Optional @Complexity(MEDIUM) Mono<Video> findVideo(String videoName); }### Answer: @Test @SuppressWarnings("unchecked") public void findVideoTest() { List<Server> servers = Servers.list() .stream() .map(MockableServer::new) .collect(Collectors.toList()); PowerMockito.mockStatic(Servers.class); PowerMockito.when(Servers.list()) .thenReturn(servers); MediaService service = new MediaService(); StepVerifier.create(service.findVideo("test")) .expectSubscription() .expectNextCount(1) .verifyComplete(); long count = servers.stream() .map(MockableServer.class::cast) .map(MockableServer::getProbe) .filter(PublisherProbe::wasCancelled) .count(); Assert.assertEquals(servers.size() - 1, count); }
### Question: Part2CreationTransformationTermination { @Complexity(EASY) public static Mono<List<String>> collectAllItemsToList(Flux<String> source) { throw new RuntimeException("Not implemented"); } @Complexity(EASY) static Mono<List<String>> collectAllItemsToList(Flux<String> source); @Complexity(EASY) static String lastElementFromSource(Flux<String> source); @Complexity(EASY) static Publisher<String> mergeSeveralSources(Publisher<String>... sources); @Complexity(EASY) static Publisher<String> fromFirstEmitted(Publisher<String>... sources); @Complexity(EASY) static Publisher<GroupedFlux<Character, String>> groupWordsByFirstLatter(Flux<String> words); @Complexity(MEDIUM) static Mono<String> executeLazyTerminationOperationAndSendHello(Flux<String> source); @Complexity(MEDIUM) static Publisher<String> zipSeveralSources(Publisher<String> prefix, Publisher<String> word, Publisher<String> suffix); @Complexity(HARD) static Publisher<String> combineSeveralSources(Publisher<String> prefix, Publisher<String> word, Publisher<String> suffix); @Complexity(HARD) static Flux<IceCreamBall> fillIceCreamWaffleBowl( Flux<IceCreamType> clientPreferences, Flux<IceCreamBall> vanillaIceCreamStream, Flux<IceCreamBall> chocolateIceCreamStream ); }### Answer: @Test public void collectToListTest() { StepVerifier .create(collectAllItemsToList(Flux.just("A", "B", "C"))) .expectSubscription() .expectNext(Arrays.asList("A", "B", "C")) .verifyComplete(); }
### Question: Part2CreationTransformationTermination { @Complexity(EASY) public static String lastElementFromSource(Flux<String> source) { throw new RuntimeException("Not implemented"); } @Complexity(EASY) static Mono<List<String>> collectAllItemsToList(Flux<String> source); @Complexity(EASY) static String lastElementFromSource(Flux<String> source); @Complexity(EASY) static Publisher<String> mergeSeveralSources(Publisher<String>... sources); @Complexity(EASY) static Publisher<String> fromFirstEmitted(Publisher<String>... sources); @Complexity(EASY) static Publisher<GroupedFlux<Character, String>> groupWordsByFirstLatter(Flux<String> words); @Complexity(MEDIUM) static Mono<String> executeLazyTerminationOperationAndSendHello(Flux<String> source); @Complexity(MEDIUM) static Publisher<String> zipSeveralSources(Publisher<String> prefix, Publisher<String> word, Publisher<String> suffix); @Complexity(HARD) static Publisher<String> combineSeveralSources(Publisher<String> prefix, Publisher<String> word, Publisher<String> suffix); @Complexity(HARD) static Flux<IceCreamBall> fillIceCreamWaffleBowl( Flux<IceCreamType> clientPreferences, Flux<IceCreamBall> vanillaIceCreamStream, Flux<IceCreamBall> chocolateIceCreamStream ); }### Answer: @Test public void lastElementFromSourceTest() { String element = lastElementFromSource(Flux.just("Hello", "World")); Assert.assertEquals("Expected 'World' but was [" + element + "]", "World", element); }
### Question: Part2CreationTransformationTermination { @Complexity(EASY) public static Publisher<String> mergeSeveralSources(Publisher<String>... sources) { throw new RuntimeException("Not implemented"); } @Complexity(EASY) static Mono<List<String>> collectAllItemsToList(Flux<String> source); @Complexity(EASY) static String lastElementFromSource(Flux<String> source); @Complexity(EASY) static Publisher<String> mergeSeveralSources(Publisher<String>... sources); @Complexity(EASY) static Publisher<String> fromFirstEmitted(Publisher<String>... sources); @Complexity(EASY) static Publisher<GroupedFlux<Character, String>> groupWordsByFirstLatter(Flux<String> words); @Complexity(MEDIUM) static Mono<String> executeLazyTerminationOperationAndSendHello(Flux<String> source); @Complexity(MEDIUM) static Publisher<String> zipSeveralSources(Publisher<String> prefix, Publisher<String> word, Publisher<String> suffix); @Complexity(HARD) static Publisher<String> combineSeveralSources(Publisher<String> prefix, Publisher<String> word, Publisher<String> suffix); @Complexity(HARD) static Flux<IceCreamBall> fillIceCreamWaffleBowl( Flux<IceCreamType> clientPreferences, Flux<IceCreamBall> vanillaIceCreamStream, Flux<IceCreamBall> chocolateIceCreamStream ); }### Answer: @Test public void mergeSeveralSourcesTest() { StepVerifier .withVirtualTime(() ->mergeSeveralSources( Flux.just("A").delaySubscription(Duration.ofSeconds(1)), Flux.just("B") )) .expectSubscription() .expectNext("B") .expectNoEvent(Duration.ofSeconds(1)) .expectNext("A") .verifyComplete(); }
### Question: Part2CreationTransformationTermination { @Complexity(MEDIUM) public static Mono<String> executeLazyTerminationOperationAndSendHello(Flux<String> source) { throw new RuntimeException("Not implemented"); } @Complexity(EASY) static Mono<List<String>> collectAllItemsToList(Flux<String> source); @Complexity(EASY) static String lastElementFromSource(Flux<String> source); @Complexity(EASY) static Publisher<String> mergeSeveralSources(Publisher<String>... sources); @Complexity(EASY) static Publisher<String> fromFirstEmitted(Publisher<String>... sources); @Complexity(EASY) static Publisher<GroupedFlux<Character, String>> groupWordsByFirstLatter(Flux<String> words); @Complexity(MEDIUM) static Mono<String> executeLazyTerminationOperationAndSendHello(Flux<String> source); @Complexity(MEDIUM) static Publisher<String> zipSeveralSources(Publisher<String> prefix, Publisher<String> word, Publisher<String> suffix); @Complexity(HARD) static Publisher<String> combineSeveralSources(Publisher<String> prefix, Publisher<String> word, Publisher<String> suffix); @Complexity(HARD) static Flux<IceCreamBall> fillIceCreamWaffleBowl( Flux<IceCreamType> clientPreferences, Flux<IceCreamBall> vanillaIceCreamStream, Flux<IceCreamBall> chocolateIceCreamStream ); }### Answer: @Test public void executeLazyTerminationOperationAndSendHelloTest() { StepVerifier .withVirtualTime(() -> executeLazyTerminationOperationAndSendHello( Flux.just("A").delaySubscription(Duration.ofSeconds(1)) )) .expectSubscription() .expectNoEvent(Duration.ofSeconds(1)) .expectNext("Hello") .verifyComplete(); }
### Question: CryptoCompareService implements CryptoService { public static <T> Flux<T> provideResilience(Flux<T> input) { return input; } CryptoCompareService(); Flux<Map<String, Object>> eventsStream(); static Flux<T> provideResilience(Flux<T> input); static Flux<T> provideCaching(Flux<T> input); static final int CACHE_SIZE; }### Answer: @Test public void verifyThatSupportIsolationAndResilience() { Flux<String> source = Flux.defer(() -> Flux.just("1", "2", "3") .mergeWith(Flux.error(new RuntimeException()))); StepVerifier.withVirtualTime(() -> CryptoCompareService.provideResilience(source) .take(6) ) .expectSubscription() .thenAwait(Duration.ofDays(10)) .expectNext("1", "2", "3") .expectNext("1", "2", "3") .expectComplete() .verify(); }
### Question: Part6HotTransformationAndProcession { @Complexity(MEDIUM) public static Publisher<String> transformToHot(Flux<String> coldSource) { throw new RuntimeException("Not implemented"); } @Complexity(MEDIUM) static Publisher<String> transformToHot(Flux<String> coldSource); @Complexity(MEDIUM) static Publisher<String> replayLast3ElementsInHotFashion(Flux<String> coldSource); @Complexity(MEDIUM) static Publisher<String> transformToHotUsingProcessor(Flux<String> coldSource); @Complexity(MEDIUM) static Flux<String> processEachSubscriberOnSeparateThread(Flux<String> coldSource); }### Answer: @Test public void transformToHotTest() { UnicastProcessor<String> source = UnicastProcessor.create(); ReplayProcessor<String> consumer1 = ReplayProcessor.create(10); ReplayProcessor<String> consumer2 = ReplayProcessor.create(10); Publisher<String> publisher = transformToHot(source); publisher.subscribe(consumer1); source.onNext("A"); source.onNext("B"); source.onNext("C"); publisher.subscribe(consumer2); source.onNext("D"); source.onNext("E"); source.onNext("F"); source.onComplete(); StepVerifier.create(consumer1) .expectSubscription() .expectNext("A", "B", "C", "D", "E", "F") .verifyComplete(); StepVerifier.create(consumer2) .expectSubscription() .expectNext("D", "E", "F") .verifyComplete(); }
### Question: Part6HotTransformationAndProcession { @Complexity(MEDIUM) public static Publisher<String> replayLast3ElementsInHotFashion(Flux<String> coldSource) { throw new RuntimeException("Not implemented"); } @Complexity(MEDIUM) static Publisher<String> transformToHot(Flux<String> coldSource); @Complexity(MEDIUM) static Publisher<String> replayLast3ElementsInHotFashion(Flux<String> coldSource); @Complexity(MEDIUM) static Publisher<String> transformToHotUsingProcessor(Flux<String> coldSource); @Complexity(MEDIUM) static Flux<String> processEachSubscriberOnSeparateThread(Flux<String> coldSource); }### Answer: @Test public void replayLast3ElementsInHotFashionTest() { UnicastProcessor<String> source = UnicastProcessor.create(); ReplayProcessor<String> consumer1 = ReplayProcessor.create(10); ReplayProcessor<String> consumer2 = ReplayProcessor.create(10); Publisher<String> publisher = replayLast3ElementsInHotFashion(source); source.onNext("A"); source.onNext("B"); source.onNext("C"); publisher.subscribe(consumer1); source.onNext("D"); source.onNext("E"); source.onNext("F"); publisher.subscribe(consumer2); source.onNext("G"); source.onComplete(); StepVerifier.create(consumer1) .expectSubscription() .expectNext("A", "B", "C", "D", "E", "F", "G") .verifyComplete(); StepVerifier.create(consumer2) .expectSubscription() .expectNext("D", "E", "F", "G") .verifyComplete(); }
### Question: Part6HotTransformationAndProcession { @Complexity(MEDIUM) public static Publisher<String> transformToHotUsingProcessor(Flux<String> coldSource) { throw new RuntimeException("Not implemented"); } @Complexity(MEDIUM) static Publisher<String> transformToHot(Flux<String> coldSource); @Complexity(MEDIUM) static Publisher<String> replayLast3ElementsInHotFashion(Flux<String> coldSource); @Complexity(MEDIUM) static Publisher<String> transformToHotUsingProcessor(Flux<String> coldSource); @Complexity(MEDIUM) static Flux<String> processEachSubscriberOnSeparateThread(Flux<String> coldSource); }### Answer: @Test public void transformToHotUsingProcessorTest() { UnicastProcessor<String> source = UnicastProcessor.create(); ReplayProcessor<String> consumer1 = ReplayProcessor.create(10); ReplayProcessor<String> consumer2 = ReplayProcessor.create(10); Publisher<String> publisher = transformToHotUsingProcessor(source); publisher.subscribe(consumer1); source.onNext("A"); source.onNext("B"); source.onNext("C"); publisher.subscribe(consumer2); source.onNext("D"); source.onNext("E"); source.onNext("F"); source.onComplete(); StepVerifier.create(consumer1) .expectSubscription() .expectNext("A", "B", "C", "D", "E", "F") .verifyComplete(); StepVerifier.create(consumer2) .expectSubscription() .expectNext("D", "E", "F") .verifyComplete(); }
### Question: Part6HotTransformationAndProcession { @Complexity(MEDIUM) public static Flux<String> processEachSubscriberOnSeparateThread(Flux<String> coldSource) { throw new RuntimeException("Not implemented"); } @Complexity(MEDIUM) static Publisher<String> transformToHot(Flux<String> coldSource); @Complexity(MEDIUM) static Publisher<String> replayLast3ElementsInHotFashion(Flux<String> coldSource); @Complexity(MEDIUM) static Publisher<String> transformToHotUsingProcessor(Flux<String> coldSource); @Complexity(MEDIUM) static Flux<String> processEachSubscriberOnSeparateThread(Flux<String> coldSource); }### Answer: @Test public void processEachSubscriberOnSeparateThreadTest() { UnicastProcessor<String> source = UnicastProcessor.create(); ReplayProcessor<String> consumer1 = ReplayProcessor.create(10); ReplayProcessor<String> consumer2 = ReplayProcessor.create(10); Thread[] forConsumers = new Thread[2]; Flux<String> publisher = processEachSubscriberOnSeparateThread(source); publisher .doOnComplete(() -> forConsumers[0] = Thread.currentThread()) .subscribe(consumer1); source.onNext("A"); source.onNext("B"); source.onNext("C"); publisher .doOnComplete(() -> forConsumers[1] = Thread.currentThread()) .subscribe(consumer2); source.onNext("D"); source.onNext("E"); source.onNext("F"); source.onComplete(); StepVerifier.create(consumer1) .expectSubscription() .expectNext("A", "B", "C", "D", "E", "F") .verifyComplete(); StepVerifier.create(consumer2) .expectSubscription() .expectNext("D", "E", "F") .verifyComplete(); Assert.assertTrue( "Expected execution on different Threads", !forConsumers[0].equals(forConsumers[1]) ); }
### Question: ServiceImpl implements Service { @Override public Flux<String> doStaff() { return serviceA .cast(IServiceA.class) .flatMapMany(IServiceA::sourceA) .concatWith(serviceB.flatMapMany(IServiceB::sourceB)); } @Override Flux<String> doStaff(); }### Answer: @Test public void doStaff() { Service proxy = Injector.proxy(new ServiceImpl(), Service.class); StepVerifier.create(proxy.doStaff()) .expectSubscription() .expectAccessibleContext().hasKey(Injector.HOLDER_KEY).then() .expectNextCount(15) .verifyComplete(); }
### Question: Part7Context { @Complexity(EASY) public static Mono<String> grabDataFromTheGivenContext(Object key) { throw new RuntimeException("Not implemented"); } @Complexity(EASY) static Mono<String> grabDataFromTheGivenContext(Object key); @Complexity(EASY) static Mono<String> provideCorrectContext(Mono<String> source, Object key, Object value); @Complexity(EASY) static Flux<String> provideCorrectContext( Publisher<String> sourceA, Context contextA, Publisher<String> sourceB, Context contextB); }### Answer: @Test public void grabDataFromTheGivenContextTest() { StepVerifier.create( grabDataFromTheGivenContext("Test") .subscriberContext(Context.of("Test", "Test")) ) .expectSubscription() .expectNext("Test") .verifyComplete(); }
### Question: Part7Context { @Complexity(EASY) public static Mono<String> provideCorrectContext(Mono<String> source, Object key, Object value) { throw new RuntimeException("Not implemented"); } @Complexity(EASY) static Mono<String> grabDataFromTheGivenContext(Object key); @Complexity(EASY) static Mono<String> provideCorrectContext(Mono<String> source, Object key, Object value); @Complexity(EASY) static Flux<String> provideCorrectContext( Publisher<String> sourceA, Context contextA, Publisher<String> sourceB, Context contextB); }### Answer: @Test public void provideCorrectContextTest() { StepVerifier.create( provideCorrectContext(Mono.just("Test"), "Key", "Value") ) .expectSubscription() .expectAccessibleContext().contains("Key", "Value").then() .expectNext("Test") .verifyComplete(); } @Test public void provideCorrectContext1() { Mono<String> a = Mono.subscriberContext() .filter( context -> context.hasKey("a") && !context.hasKey("b")) .map(context -> context.get("a")); Mono<String> b = Mono.subscriberContext() .filter( context -> context.hasKey("b") && !context.hasKey("a")) .map(context -> context.get("b")); Flux<String> flux = provideCorrectContext(a, Context.of("a", "a"), b, Context.of("b", "b")); StepVerifier.create(flux) .expectSubscription() .expectNext("a") .expectNext("b") .verifyComplete(); }
### Question: Part3MultithreadingParallelization { @Complexity(EASY) public static Publisher<String> publishOnParallelThreadScheduler(Flux<String> source) { throw new RuntimeException("Not implemented"); } @Complexity(EASY) static Publisher<String> publishOnParallelThreadScheduler(Flux<String> source); @Complexity(EASY) static Publisher<String> subscribeOnSingleThreadScheduler(Callable<String> blockingCall); @Complexity(EASY) static ParallelFlux<String> paralellizeWorkOnDifferentThreads(Flux<String> source); @Complexity(HARD) static Publisher<String> paralellizeLongRunningWorkOnUnboundedAmountOfThread(Flux<Callable<String>> streamOfLongRunningSources); }### Answer: @Test public void publishOnParallelThreadSchedulerTest() { Thread[] threads = new Thread[2]; StepVerifier .create(publishOnParallelThreadScheduler(Flux.defer(() -> { threads[0] = Thread.currentThread(); return Flux.just("Hello"); }))) .expectSubscription() .expectNext("Hello") .verifyComplete(); Assert.assertTrue( "Expected execution on different Threads", !threads[0].equals(threads[1]) ); }
### Question: Part3MultithreadingParallelization { @Complexity(EASY) public static Publisher<String> subscribeOnSingleThreadScheduler(Callable<String> blockingCall) { throw new RuntimeException("Not implemented"); } @Complexity(EASY) static Publisher<String> publishOnParallelThreadScheduler(Flux<String> source); @Complexity(EASY) static Publisher<String> subscribeOnSingleThreadScheduler(Callable<String> blockingCall); @Complexity(EASY) static ParallelFlux<String> paralellizeWorkOnDifferentThreads(Flux<String> source); @Complexity(HARD) static Publisher<String> paralellizeLongRunningWorkOnUnboundedAmountOfThread(Flux<Callable<String>> streamOfLongRunningSources); }### Answer: @Test public void subscribeOnSingleThreadSchedulerTest() { Thread[] threads = new Thread[1]; StepVerifier .create(subscribeOnSingleThreadScheduler(() -> { System.out.println("Threads:" + Thread.currentThread().getName()); threads[0] = Thread.currentThread(); return "Hello"; })) .expectSubscription() .expectNext("Hello") .verifyComplete(); Assert.assertTrue( "Expected execution on different Threads", !threads[0].equals(Thread.currentThread()) ); }
### Question: Part3MultithreadingParallelization { @Complexity(EASY) public static ParallelFlux<String> paralellizeWorkOnDifferentThreads(Flux<String> source) { throw new RuntimeException("Not implemented"); } @Complexity(EASY) static Publisher<String> publishOnParallelThreadScheduler(Flux<String> source); @Complexity(EASY) static Publisher<String> subscribeOnSingleThreadScheduler(Callable<String> blockingCall); @Complexity(EASY) static ParallelFlux<String> paralellizeWorkOnDifferentThreads(Flux<String> source); @Complexity(HARD) static Publisher<String> paralellizeLongRunningWorkOnUnboundedAmountOfThread(Flux<Callable<String>> streamOfLongRunningSources); }### Answer: @Test public void paralellizeWorkOnDifferentThreadsTest() { StepVerifier .create(paralellizeWorkOnDifferentThreads( Flux.just("Hello", "Hello", "Hello") )) .expectSubscription() .expectNext("Hello", "Hello", "Hello") .expectComplete() .verify(); }
### Question: Part3MultithreadingParallelization { @Complexity(HARD) public static Publisher<String> paralellizeLongRunningWorkOnUnboundedAmountOfThread(Flux<Callable<String>> streamOfLongRunningSources) { throw new RuntimeException("Not implemented"); } @Complexity(EASY) static Publisher<String> publishOnParallelThreadScheduler(Flux<String> source); @Complexity(EASY) static Publisher<String> subscribeOnSingleThreadScheduler(Callable<String> blockingCall); @Complexity(EASY) static ParallelFlux<String> paralellizeWorkOnDifferentThreads(Flux<String> source); @Complexity(HARD) static Publisher<String> paralellizeLongRunningWorkOnUnboundedAmountOfThread(Flux<Callable<String>> streamOfLongRunningSources); }### Answer: @Test public void paralellizeLongRunningWorkOnUnboundedAmountOfThreadTest() { Thread[] threads = new Thread[3]; StepVerifier .create(paralellizeLongRunningWorkOnUnboundedAmountOfThread(Flux.<Callable<String>>just( () -> { threads[0] = Thread.currentThread(); Thread.sleep(300); return "Hello"; }, () -> { threads[1] = Thread.currentThread(); Thread.sleep(300); return "Hello"; }, () -> { threads[2] = Thread.currentThread(); Thread.sleep(300); return "Hello"; } ).repeat(20))) .expectSubscription() .expectNext("Hello", "Hello", "Hello") .expectNextCount(60) .expectComplete() .verify(Duration.ofMillis(600)); Assert.assertTrue( "Expected execution on different Threads", !threads[0].equals(threads[1]) ); Assert.assertTrue( "Expected execution on different Threads", !threads[1].equals(threads[2]) ); Assert.assertTrue( "Expected execution on different Threads", !threads[0].equals(threads[2]) ); }
### Question: PaymentService { public Flux<Payment> findPayments(Flux<String> userIds) { return userIds.flatMap(repository::findAllByUserId); } PaymentService(); Flux<Payment> findPayments(Flux<String> userIds); }### Answer: @Test public void findPayments() { PaymentService service = new PaymentService(); StepVerifier.create(service.findPayments(Flux.range(1, 100) .map(String::valueOf)) .then()) .expectSubscription() .verifyComplete(); }
### Question: Part5ResilienceResponsive_Optional { @Complexity(HARD) public static Publisher<Integer> provideSupportOfContinuation(Flux<Integer> values) { return values; } @Complexity(HARD) static Publisher<Integer> provideSupportOfContinuation(Flux<Integer> values); @Complexity(HARD) static Publisher<Integer> provideSupportOfContinuationWithoutErrorStrategy(Flux<Integer> values, Function<Integer, Integer> mapping); }### Answer: @Test public void provideSupportOfContinuationTest() { Flux<Integer> range = Flux.range(0, 6) .map(i -> 10 / i); StepVerifier.create(provideSupportOfContinuation(range)) .expectSubscription() .expectNextCount(5) .expectComplete() .verify(); }
### Question: Part5ResilienceResponsive_Optional { @Complexity(HARD) public static Publisher<Integer> provideSupportOfContinuationWithoutErrorStrategy(Flux<Integer> values, Function<Integer, Integer> mapping) { return values.map(mapping); } @Complexity(HARD) static Publisher<Integer> provideSupportOfContinuation(Flux<Integer> values); @Complexity(HARD) static Publisher<Integer> provideSupportOfContinuationWithoutErrorStrategy(Flux<Integer> values, Function<Integer, Integer> mapping); }### Answer: @Test public void provideSupportOfContinuationWithoutErrorStrategyTest() { Function<Integer, Integer> mapping = i -> 10 / i; Flux<Integer> range = Flux.range(0, 6); StepVerifier.create(provideSupportOfContinuationWithoutErrorStrategy(range, mapping)) .expectSubscription() .expectNextCount(5) .expectComplete() .verifyThenAssertThat() .hasNotDroppedErrors(); }
### Question: Part5ResilienceResponsive { @Complexity(EASY) public static Publisher<String> fallbackHelloOnEmpty(Flux<String> emptyPublisher) { throw new RuntimeException("Not implemented"); } @Complexity(EASY) static Publisher<String> fallbackHelloOnEmpty(Flux<String> emptyPublisher); @Complexity(EASY) static Publisher<String> fallbackHelloOnError(Flux<String> failurePublisher); @Complexity(EASY) static Publisher<String> retryOnError(Mono<String> failurePublisher); @Complexity(MEDIUM) static Publisher<String> timeoutLongOperation(CompletableFuture<String> longRunningCall); @Complexity(HARD) static Publisher<String> timeoutLongOperation(Callable<String> longRunningCall); }### Answer: @Test public void fallbackHelloOnEmptyTest() { StepVerifier .create(fallbackHelloOnEmpty(Flux.empty())) .expectSubscription() .expectNext("Hello") .verifyComplete(); }
### Question: Part5ResilienceResponsive { @Complexity(EASY) public static Publisher<String> fallbackHelloOnError(Flux<String> failurePublisher) { throw new RuntimeException("Not implemented"); } @Complexity(EASY) static Publisher<String> fallbackHelloOnEmpty(Flux<String> emptyPublisher); @Complexity(EASY) static Publisher<String> fallbackHelloOnError(Flux<String> failurePublisher); @Complexity(EASY) static Publisher<String> retryOnError(Mono<String> failurePublisher); @Complexity(MEDIUM) static Publisher<String> timeoutLongOperation(CompletableFuture<String> longRunningCall); @Complexity(HARD) static Publisher<String> timeoutLongOperation(Callable<String> longRunningCall); }### Answer: @Test public void fallbackHelloOnErrorTest() { StepVerifier .create(fallbackHelloOnError(Flux.error(new RuntimeException()))) .expectSubscription() .expectNext("Hello") .verifyComplete(); }
### Question: Part5ResilienceResponsive { @Complexity(EASY) public static Publisher<String> retryOnError(Mono<String> failurePublisher) { throw new RuntimeException("Not implemented"); } @Complexity(EASY) static Publisher<String> fallbackHelloOnEmpty(Flux<String> emptyPublisher); @Complexity(EASY) static Publisher<String> fallbackHelloOnError(Flux<String> failurePublisher); @Complexity(EASY) static Publisher<String> retryOnError(Mono<String> failurePublisher); @Complexity(MEDIUM) static Publisher<String> timeoutLongOperation(CompletableFuture<String> longRunningCall); @Complexity(HARD) static Publisher<String> timeoutLongOperation(Callable<String> longRunningCall); }### Answer: @Test public void retryOnErrorTest() throws Exception { Callable<String> callable = Mockito.mock(Callable.class); Mockito.when(callable.call()) .thenThrow(new RuntimeException()) .thenReturn("Hello"); StepVerifier .create(retryOnError(Mono.fromCallable(callable))) .expectSubscription() .expectNext("Hello") .expectComplete() .verify(); }
### Question: DefaultPriceService implements PriceService { Flux<Map<String, Object>> selectOnlyPriceUpdateEvents(Flux<Map<String, Object>> input) { return Flux.never(); } DefaultPriceService(CryptoService cryptoService); Flux<MessageDTO<Float>> pricesStream(Flux<Long> intervalPreferencesStream); }### Answer: @Test public void verifyBuildingCurrentPriceEvents() { StepVerifier.create( new DefaultPriceService(cryptoService).selectOnlyPriceUpdateEvents( Flux.just( map().put("Invalid", "A").build(), map().put(TYPE_KEY, "1").build(), map().put(TYPE_KEY, "5").build(), map().put(TYPE_KEY, "5") .put(PRICE_KEY, 0.1F) .put(CURRENCY_KEY, "USD") .put(MARKET_KEY, "External").build() ) ) ) .expectNext( map().put(TYPE_KEY, "5") .put(PRICE_KEY, 0.1F) .put(CURRENCY_KEY, "USD") .put(MARKET_KEY, "External").build() ) .expectComplete() .verify(Duration.ofSeconds(2)); }
### Question: Part5ResilienceResponsive { @Complexity(MEDIUM) public static Publisher<String> timeoutLongOperation(CompletableFuture<String> longRunningCall) { throw new RuntimeException("Not implemented"); } @Complexity(EASY) static Publisher<String> fallbackHelloOnEmpty(Flux<String> emptyPublisher); @Complexity(EASY) static Publisher<String> fallbackHelloOnError(Flux<String> failurePublisher); @Complexity(EASY) static Publisher<String> retryOnError(Mono<String> failurePublisher); @Complexity(MEDIUM) static Publisher<String> timeoutLongOperation(CompletableFuture<String> longRunningCall); @Complexity(HARD) static Publisher<String> timeoutLongOperation(Callable<String> longRunningCall); }### Answer: @Test public void timeoutLongOperationWithCompletableFutureTest() { StepVerifier .withVirtualTime(() -> timeoutLongOperation(CompletableFuture.supplyAsync(() -> { try { Thread.sleep(1000000); } catch (InterruptedException e) { return null; } return "Toooooo long"; }))) .expectSubscription() .expectNoEvent(Duration.ofSeconds(1)) .expectNext("Hello") .expectComplete() .verify(Duration.ofSeconds(1)); } @Test public void timeoutLongOperationWithCallableTest() { StepVerifier .create(timeoutLongOperation(() -> { try { Thread.sleep(1000000); } catch (InterruptedException e) { return null; } return "Toooooo long"; })) .expectSubscription() .expectNext("Hello") .expectComplete() .verify(Duration.ofSeconds(2)); }
### Question: Part4Backpressure { @Complexity(EASY) public static Flux<String> dropElementsOnBackpressure(Flux<String> upstream) { throw new RuntimeException("Not implemented"); } @Complexity(EASY) static Flux<String> dropElementsOnBackpressure(Flux<String> upstream); @Complexity(MEDIUM) static Flux<List<Long>> backpressureByBatching(Flux<Long> upstream); }### Answer: @Test public void dropElementsOnBackpressureTest() { DirectProcessor<String> processor = DirectProcessor.create(); StepVerifier .create(dropElementsOnBackpressure(processor), 0) .expectSubscription() .then(() -> processor.onNext("")) .then(() -> processor.onNext("")) .thenRequest(1) .then(() -> processor.onNext("0")) .expectNext("0") .then(() -> processor.onNext("0")) .then(() -> processor.onNext("0")) .thenRequest(1) .then(() -> processor.onNext("10")) .expectNext("10") .thenRequest(1) .then(() -> processor.onNext("20")) .expectNext("20") .then(() -> processor.onNext("40")) .then(() -> processor.onNext("30")) .then(processor::onComplete) .expectComplete() .verify(); }
### Question: Part4Backpressure { @Complexity(MEDIUM) public static Flux<List<Long>> backpressureByBatching(Flux<Long> upstream) { throw new RuntimeException("Not implemented"); } @Complexity(EASY) static Flux<String> dropElementsOnBackpressure(Flux<String> upstream); @Complexity(MEDIUM) static Flux<List<Long>> backpressureByBatching(Flux<Long> upstream); }### Answer: @Test public void backpressureByBatchingTest() { StepVerifier .withVirtualTime(() -> backpressureByBatching(Flux.interval(Duration.ofMillis(1))), 0) .expectSubscription() .thenRequest(1) .expectNoEvent(Duration.ofSeconds(1)) .expectNextCount(1) .thenRequest(1) .expectNoEvent(Duration.ofSeconds(1)) .expectNextCount(1) .thenCancel() .verify(); }
### Question: Part4ExtraBackpressure_Optional { @Complexity(MEDIUM) public static Publisher<String> handleBackpressureWithBuffering(StringEventPublisher stringEventPublisher) { throw new RuntimeException("Not implemented"); } @Complexity(MEDIUM) static Publisher<String> handleBackpressureWithBuffering(StringEventPublisher stringEventPublisher); @Optional @Complexity(MEDIUM) static void dynamicDemand(Flux<String> source, CountDownLatch countDownOnComplete); }### Answer: @Test public void handleBackpressureWithBufferingTest() { TestStringEventPublisher stringEmitter = new TestStringEventPublisher(); StepVerifier .create( handleBackpressureWithBuffering(stringEmitter), 0 ) .expectSubscription() .then(() -> stringEmitter.consumer.accept("A")) .then(() -> stringEmitter.consumer.accept("B")) .then(() -> stringEmitter.consumer.accept("C")) .then(() -> stringEmitter.consumer.accept("D")) .then(() -> stringEmitter.consumer.accept("E")) .then(() -> stringEmitter.consumer.accept("F")) .expectNoEvent(Duration.ofMillis(300)) .thenRequest(6) .expectNext("A", "B", "C", "D", "E", "F") .thenCancel() .verify(); }
### Question: Part4ExtraBackpressure_Optional { @Optional @Complexity(MEDIUM) public static void dynamicDemand(Flux<String> source, CountDownLatch countDownOnComplete) { throw new RuntimeException("Not implemented"); } @Complexity(MEDIUM) static Publisher<String> handleBackpressureWithBuffering(StringEventPublisher stringEventPublisher); @Optional @Complexity(MEDIUM) static void dynamicDemand(Flux<String> source, CountDownLatch countDownOnComplete); }### Answer: @Test public void dynamicDemandTest() throws InterruptedException { int size = 100000; long requests = (long) Math.ceil((Math.log(size) / Math.log(2) + 1e-10)); CountDownLatch latch = new CountDownLatch(1); AtomicInteger iterations = new AtomicInteger(); dynamicDemand( Flux.range(0, size) .map(String::valueOf) .publishOn(Schedulers.single()) .doOnRequest(r -> iterations.incrementAndGet()), latch ); latch.await(5, TimeUnit.SECONDS); assertEquals(requests, iterations.get()); }
### Question: DataUploaderService { @Optional @Complexity(HARD) public Mono<Void> upload(Flux<OrderedByteBuffer> input) { throw new RuntimeException("Not implemented"); } DataUploaderService(HttpClient client); @Optional @Complexity(HARD) Mono<Void> upload(Flux<OrderedByteBuffer> input); }### Answer: @Test public void uploadTest() { TrickyHttpClient client = new TrickyHttpClient(); DataUploaderService service = new DataUploaderService(client); StepVerifier.withVirtualTime(() -> service.upload( Flux.range(0, 1000) .map(i -> new OrderedByteBuffer(i, ByteBuffer.allocate(i))) .window(100) .delayElements(Duration.ofMillis(1500)) .flatMap(Function.identity()) )) .expectSubscription() .thenAwait(Duration.ofSeconds(1000)) .verifyComplete(); verifyOrdered(client); verifyTimeout(client); }
### Question: DefaultPriceService implements PriceService { Flux<MessageDTO<Float>> averagePrice( Flux<Long> requestedInterval, Flux<MessageDTO<Float>> priceData ) { return Flux.never(); } DefaultPriceService(CryptoService cryptoService); Flux<MessageDTO<Float>> pricesStream(Flux<Long> intervalPreferencesStream); }### Answer: @Test @SuppressWarnings("unchecked") public void verifyBuildingAveragePriceEvents() { StepVerifier.withVirtualTime(() -> new DefaultPriceService(cryptoService).averagePrice( Flux.interval(Duration.ofSeconds(0), Duration.ofSeconds(5)) .map(i -> i + 1) .doOnNext(i -> System.out.println("Interval: " + i)), Flux.interval(Duration.ofMillis(500), Duration.ofSeconds(1)) .map(p -> p + 100) .map(tick -> MessageDTO.price((float) tick, "U", "M")) .take(20) .doOnNext(p -> System.out.println("Price: " + p.getData())) .replay(1000) .autoConnect() ) .take(10) .take(Duration.ofHours(1)) .map(MessageDTO::getData) .doOnNext(a -> System.out.println("AVG: " + a)) ) .expectSubscription() .thenAwait(Duration.ofDays(1)) .expectNextMatches(expectedPrice(100.0F)) .expectNextMatches(expectedPrice(101.0F)) .expectNextMatches(expectedPrice(102.0F)) .expectNextMatches(expectedPrice(103.0F)) .expectNextMatches(expectedPrice(104.0F)) .expectNextMatches(expectedPrice(103.0F)) .expectNextMatches(expectedPrice(107.5F)) .expectNextMatches(expectedPrice(109.5F)) .expectNextMatches(expectedPrice(106.0F)) .expectNextMatches(expectedPrice(114.0F)) .verifyComplete(); }
### Question: Part1CreationTransformationTermination { @Complexity(EASY) public static Observable<String> justABC() { throw new RuntimeException("Not implemented"); } @Complexity(EASY) static Observable<String> justABC(); @Complexity(EASY) static Observable<String> fromArray(String... args); @Complexity(EASY) static Observable<String> error(Throwable t); @Complexity(EASY) static Observable<Integer> convertNullableValueToObservable(@Nullable Integer nullableElement); @Complexity(EASY) static Observable<String> deferCalculation(Func0<Observable<String>> calculation); @Complexity(EASY) static Observable<Long> interval(long interval, TimeUnit timeUnit); @Complexity(EASY) static Observable<String> mapToString(Observable<Long> input); @Complexity(EASY) static Observable<String> findAllWordsWithPrefixABC(Observable<String> input); @Complexity(MEDIUM) static Observable<String> fromFutureInIOScheduler(Future<String> future); @Complexity(MEDIUM) static void iterateNTimes(int times, AtomicInteger counter); @Complexity(MEDIUM) static Observable<Character> flatMapWordsToCharacters(Observable<String> input); }### Answer: @Test public void justABCTest() { justABC() .test() .assertValue("ABC") .assertCompleted() .awaitTerminalEvent(); }
### Question: Part1CreationTransformationTermination { @Complexity(EASY) public static Observable<String> fromArray(String... args) { throw new RuntimeException("Not implemented"); } @Complexity(EASY) static Observable<String> justABC(); @Complexity(EASY) static Observable<String> fromArray(String... args); @Complexity(EASY) static Observable<String> error(Throwable t); @Complexity(EASY) static Observable<Integer> convertNullableValueToObservable(@Nullable Integer nullableElement); @Complexity(EASY) static Observable<String> deferCalculation(Func0<Observable<String>> calculation); @Complexity(EASY) static Observable<Long> interval(long interval, TimeUnit timeUnit); @Complexity(EASY) static Observable<String> mapToString(Observable<Long> input); @Complexity(EASY) static Observable<String> findAllWordsWithPrefixABC(Observable<String> input); @Complexity(MEDIUM) static Observable<String> fromFutureInIOScheduler(Future<String> future); @Complexity(MEDIUM) static void iterateNTimes(int times, AtomicInteger counter); @Complexity(MEDIUM) static Observable<Character> flatMapWordsToCharacters(Observable<String> input); }### Answer: @Test public void fromArrayOfABCTest() { fromArray("A", "B", "C") .test() .assertValues("A", "B", "C") .assertCompleted() .awaitTerminalEvent(); }
### Question: Part1CreationTransformationTermination { @Complexity(EASY) public static Observable<String> error(Throwable t) { throw new RuntimeException("Not implemented"); } @Complexity(EASY) static Observable<String> justABC(); @Complexity(EASY) static Observable<String> fromArray(String... args); @Complexity(EASY) static Observable<String> error(Throwable t); @Complexity(EASY) static Observable<Integer> convertNullableValueToObservable(@Nullable Integer nullableElement); @Complexity(EASY) static Observable<String> deferCalculation(Func0<Observable<String>> calculation); @Complexity(EASY) static Observable<Long> interval(long interval, TimeUnit timeUnit); @Complexity(EASY) static Observable<String> mapToString(Observable<Long> input); @Complexity(EASY) static Observable<String> findAllWordsWithPrefixABC(Observable<String> input); @Complexity(MEDIUM) static Observable<String> fromFutureInIOScheduler(Future<String> future); @Complexity(MEDIUM) static void iterateNTimes(int times, AtomicInteger counter); @Complexity(MEDIUM) static Observable<Character> flatMapWordsToCharacters(Observable<String> input); }### Answer: @Test public void errorObservableTest() { NullPointerException testException = new NullPointerException("test"); error(testException) .test() .assertError(testException) .awaitTerminalEvent(); }
### Question: Part1CreationTransformationTermination { @Complexity(EASY) public static Observable<Integer> convertNullableValueToObservable(@Nullable Integer nullableElement) { throw new RuntimeException("Not implemented"); } @Complexity(EASY) static Observable<String> justABC(); @Complexity(EASY) static Observable<String> fromArray(String... args); @Complexity(EASY) static Observable<String> error(Throwable t); @Complexity(EASY) static Observable<Integer> convertNullableValueToObservable(@Nullable Integer nullableElement); @Complexity(EASY) static Observable<String> deferCalculation(Func0<Observable<String>> calculation); @Complexity(EASY) static Observable<Long> interval(long interval, TimeUnit timeUnit); @Complexity(EASY) static Observable<String> mapToString(Observable<Long> input); @Complexity(EASY) static Observable<String> findAllWordsWithPrefixABC(Observable<String> input); @Complexity(MEDIUM) static Observable<String> fromFutureInIOScheduler(Future<String> future); @Complexity(MEDIUM) static void iterateNTimes(int times, AtomicInteger counter); @Complexity(MEDIUM) static Observable<Character> flatMapWordsToCharacters(Observable<String> input); }### Answer: @Test public void emptyObservableTest() { convertNullableValueToObservable(1) .test() .assertValue(1) .assertCompleted() .awaitTerminalEvent(); convertNullableValueToObservable(null) .test() .assertNoValues() .assertCompleted() .awaitTerminalEvent(); }
### Question: Part1CreationTransformationTermination { @Complexity(EASY) public static Observable<String> deferCalculation(Func0<Observable<String>> calculation) { throw new RuntimeException("Not implemented"); } @Complexity(EASY) static Observable<String> justABC(); @Complexity(EASY) static Observable<String> fromArray(String... args); @Complexity(EASY) static Observable<String> error(Throwable t); @Complexity(EASY) static Observable<Integer> convertNullableValueToObservable(@Nullable Integer nullableElement); @Complexity(EASY) static Observable<String> deferCalculation(Func0<Observable<String>> calculation); @Complexity(EASY) static Observable<Long> interval(long interval, TimeUnit timeUnit); @Complexity(EASY) static Observable<String> mapToString(Observable<Long> input); @Complexity(EASY) static Observable<String> findAllWordsWithPrefixABC(Observable<String> input); @Complexity(MEDIUM) static Observable<String> fromFutureInIOScheduler(Future<String> future); @Complexity(MEDIUM) static void iterateNTimes(int times, AtomicInteger counter); @Complexity(MEDIUM) static Observable<Character> flatMapWordsToCharacters(Observable<String> input); }### Answer: @Test @SuppressWarnings("unchecked") public void deferCalculationObservableTest() { Func0<Observable<String>> factory = Mockito.mock(Func0.class); Mockito.when(factory.call()).thenReturn(Observable.just("Hello")).thenReturn(Observable.just("World")); Observable deferCalculation = deferCalculation(factory); Mockito.verifyZeroInteractions(factory); deferCalculation .test() .assertValue("Hello") .assertCompleted() .awaitTerminalEvent(); Mockito.verify(factory).call(); deferCalculation .test() .assertValue("World") .assertCompleted() .awaitTerminalEvent(); Mockito.verify(factory, Mockito.times(2)).call(); }
### Question: Part1CreationTransformationTermination { @Complexity(EASY) public static Observable<Long> interval(long interval, TimeUnit timeUnit) { throw new RuntimeException("Not implemented"); } @Complexity(EASY) static Observable<String> justABC(); @Complexity(EASY) static Observable<String> fromArray(String... args); @Complexity(EASY) static Observable<String> error(Throwable t); @Complexity(EASY) static Observable<Integer> convertNullableValueToObservable(@Nullable Integer nullableElement); @Complexity(EASY) static Observable<String> deferCalculation(Func0<Observable<String>> calculation); @Complexity(EASY) static Observable<Long> interval(long interval, TimeUnit timeUnit); @Complexity(EASY) static Observable<String> mapToString(Observable<Long> input); @Complexity(EASY) static Observable<String> findAllWordsWithPrefixABC(Observable<String> input); @Complexity(MEDIUM) static Observable<String> fromFutureInIOScheduler(Future<String> future); @Complexity(MEDIUM) static void iterateNTimes(int times, AtomicInteger counter); @Complexity(MEDIUM) static Observable<Character> flatMapWordsToCharacters(Observable<String> input); }### Answer: @Test @SuppressWarnings("unchecked") public void intervalTest() { TestScheduler testScheduler = new TestScheduler(); RxJavaHooks.setOnIOScheduler(s -> testScheduler); RxJavaHooks.setOnComputationScheduler(s -> testScheduler); RxJavaHooks.setOnNewThreadScheduler(s -> testScheduler); interval(1, TimeUnit.MINUTES) .test() .assertNoValues() .perform(() -> testScheduler.advanceTimeBy(1, TimeUnit.MINUTES)) .assertValue(0L) .perform(() -> testScheduler.advanceTimeBy(5, TimeUnit.MINUTES)) .assertValueCount(6) .assertNotCompleted() .awaitTerminalEventAndUnsubscribeOnTimeout(1, TimeUnit.MILLISECONDS); }
### Question: Part1CreationTransformationTermination { @Complexity(EASY) public static Observable<String> mapToString(Observable<Long> input) { throw new RuntimeException("Not implemented"); } @Complexity(EASY) static Observable<String> justABC(); @Complexity(EASY) static Observable<String> fromArray(String... args); @Complexity(EASY) static Observable<String> error(Throwable t); @Complexity(EASY) static Observable<Integer> convertNullableValueToObservable(@Nullable Integer nullableElement); @Complexity(EASY) static Observable<String> deferCalculation(Func0<Observable<String>> calculation); @Complexity(EASY) static Observable<Long> interval(long interval, TimeUnit timeUnit); @Complexity(EASY) static Observable<String> mapToString(Observable<Long> input); @Complexity(EASY) static Observable<String> findAllWordsWithPrefixABC(Observable<String> input); @Complexity(MEDIUM) static Observable<String> fromFutureInIOScheduler(Future<String> future); @Complexity(MEDIUM) static void iterateNTimes(int times, AtomicInteger counter); @Complexity(MEDIUM) static Observable<Character> flatMapWordsToCharacters(Observable<String> input); }### Answer: @Test public void mapToStringTest() { mapToString(Observable.just(1L, 2L, 3L, 4L)) .test() .assertValues("1", "2", "3", "4") .assertCompleted() .awaitTerminalEvent(); }
### Question: Part1CreationTransformationTermination { @Complexity(EASY) public static Observable<String> findAllWordsWithPrefixABC(Observable<String> input) { throw new RuntimeException("Not implemented"); } @Complexity(EASY) static Observable<String> justABC(); @Complexity(EASY) static Observable<String> fromArray(String... args); @Complexity(EASY) static Observable<String> error(Throwable t); @Complexity(EASY) static Observable<Integer> convertNullableValueToObservable(@Nullable Integer nullableElement); @Complexity(EASY) static Observable<String> deferCalculation(Func0<Observable<String>> calculation); @Complexity(EASY) static Observable<Long> interval(long interval, TimeUnit timeUnit); @Complexity(EASY) static Observable<String> mapToString(Observable<Long> input); @Complexity(EASY) static Observable<String> findAllWordsWithPrefixABC(Observable<String> input); @Complexity(MEDIUM) static Observable<String> fromFutureInIOScheduler(Future<String> future); @Complexity(MEDIUM) static void iterateNTimes(int times, AtomicInteger counter); @Complexity(MEDIUM) static Observable<Character> flatMapWordsToCharacters(Observable<String> input); }### Answer: @Test public void filterTest() { findAllWordsWithPrefixABC(Observable.just("asdas", "gdfgsdfg", "ABCasda")) .test() .assertValue("ABCasda") .assertCompleted() .awaitTerminalEvent(); }
### Question: Part1CreationTransformationTermination { @Complexity(MEDIUM) public static Observable<String> fromFutureInIOScheduler(Future<String> future) { throw new RuntimeException("Not implemented"); } @Complexity(EASY) static Observable<String> justABC(); @Complexity(EASY) static Observable<String> fromArray(String... args); @Complexity(EASY) static Observable<String> error(Throwable t); @Complexity(EASY) static Observable<Integer> convertNullableValueToObservable(@Nullable Integer nullableElement); @Complexity(EASY) static Observable<String> deferCalculation(Func0<Observable<String>> calculation); @Complexity(EASY) static Observable<Long> interval(long interval, TimeUnit timeUnit); @Complexity(EASY) static Observable<String> mapToString(Observable<Long> input); @Complexity(EASY) static Observable<String> findAllWordsWithPrefixABC(Observable<String> input); @Complexity(MEDIUM) static Observable<String> fromFutureInIOScheduler(Future<String> future); @Complexity(MEDIUM) static void iterateNTimes(int times, AtomicInteger counter); @Complexity(MEDIUM) static Observable<Character> flatMapWordsToCharacters(Observable<String> input); }### Answer: @Test public void fromFutureTest() { AssertableSubscriber<String> assertable = fromFutureInIOScheduler(CompletableFuture.completedFuture("test")) .test() .awaitValueCount(1, 10, TimeUnit.SECONDS) .assertValue("test") .assertCompleted() .awaitTerminalEvent(); Thread lastSeenThread = assertable.getLastSeenThread(); Assert.assertTrue("Expect execution on I/O thread", lastSeenThread.getName().contains("RxIoScheduler-")); }
### Question: Part1CreationTransformationTermination { @Complexity(MEDIUM) public static void iterateNTimes(int times, AtomicInteger counter) { for (int i = 0; i < times; i++) { counter.incrementAndGet(); } } @Complexity(EASY) static Observable<String> justABC(); @Complexity(EASY) static Observable<String> fromArray(String... args); @Complexity(EASY) static Observable<String> error(Throwable t); @Complexity(EASY) static Observable<Integer> convertNullableValueToObservable(@Nullable Integer nullableElement); @Complexity(EASY) static Observable<String> deferCalculation(Func0<Observable<String>> calculation); @Complexity(EASY) static Observable<Long> interval(long interval, TimeUnit timeUnit); @Complexity(EASY) static Observable<String> mapToString(Observable<Long> input); @Complexity(EASY) static Observable<String> findAllWordsWithPrefixABC(Observable<String> input); @Complexity(MEDIUM) static Observable<String> fromFutureInIOScheduler(Future<String> future); @Complexity(MEDIUM) static void iterateNTimes(int times, AtomicInteger counter); @Complexity(MEDIUM) static Observable<Character> flatMapWordsToCharacters(Observable<String> input); }### Answer: @Test public void iterate10TimesTest() throws Exception { ArgumentCaptor<Integer> captor = ArgumentCaptor.forClass(Integer.class); PowerMockito.spy(Observable.class); PowerMockito .doAnswer(InvocationOnMock::callRealMethod) .when(Observable.class, "range", anyInt(), captor.capture()); AtomicInteger counter = new AtomicInteger(); iterateNTimes(10, counter); Assert.assertEquals("Atomic counter must be increased to 10", 10, counter.get()); Assert.assertEquals("Observable#range(int, int) should be called", 1, captor.getAllValues().size()); }
### Question: DefaultTradeService implements TradeService { Flux<MessageDTO<MessageDTO.Trade>> filterAndMapTradingEvents(Flux<Map<String, Object>> input) { return Flux.never(); } DefaultTradeService(CryptoService service, TradeRepository repository); @Override Flux<MessageDTO<MessageDTO.Trade>> tradesStream(); }### Answer: @Test public void verifyTradeInfoMappingToDTO() { StepVerifier.create( new DefaultTradeService(cryptoService, tradeRepository).filterAndMapTradingEvents( Flux.just( map().put("Invalid", "A").build(), map().put(TYPE_KEY, "1").build(), map().put(TYPE_KEY, "0") .put(TIMESTAMP_KEY, 1F) .put(PRICE_KEY, 0.1F) .put(FLAGS_KEY, "1") .put(QUANTITY_KEY, 1.2F) .put(CURRENCY_KEY, "USD") .put(MARKET_KEY, "External").build() ) ) .take(Duration.ofSeconds(1)) ) .expectNext(MessageDTO.trade(1000, 0.1F, 1.2F, "USD", "External")) .verifyComplete(); }
### Question: Part1CreationTransformationTermination { @Complexity(MEDIUM) public static Observable<Character> flatMapWordsToCharacters(Observable<String> input) { throw new RuntimeException("Not implemented"); } @Complexity(EASY) static Observable<String> justABC(); @Complexity(EASY) static Observable<String> fromArray(String... args); @Complexity(EASY) static Observable<String> error(Throwable t); @Complexity(EASY) static Observable<Integer> convertNullableValueToObservable(@Nullable Integer nullableElement); @Complexity(EASY) static Observable<String> deferCalculation(Func0<Observable<String>> calculation); @Complexity(EASY) static Observable<Long> interval(long interval, TimeUnit timeUnit); @Complexity(EASY) static Observable<String> mapToString(Observable<Long> input); @Complexity(EASY) static Observable<String> findAllWordsWithPrefixABC(Observable<String> input); @Complexity(MEDIUM) static Observable<String> fromFutureInIOScheduler(Future<String> future); @Complexity(MEDIUM) static void iterateNTimes(int times, AtomicInteger counter); @Complexity(MEDIUM) static Observable<Character> flatMapWordsToCharacters(Observable<String> input); }### Answer: @Test public void flatMapWordsToCharactersTest() { flatMapWordsToCharacters(Observable.just("ABC", "DEFG", "HJKL")) .test() .assertValues('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L') .assertCompleted() .awaitTerminalEvent(); }