method2testcases
stringlengths
118
3.08k
### Question: KafkaStreams { public void close() { close(DEFAULT_CLOSE_TIMEOUT, TimeUnit.SECONDS); } KafkaStreams(final TopologyBuilder builder, final Properties props); KafkaStreams(final TopologyBuilder builder, final StreamsConfig config); KafkaStreams(final TopologyBuilder builder, final StreamsConfig config, final KafkaClientSupplier clientSupplier); void setStateListener(final KafkaStreams.StateListener listener); synchronized State state(); Map<MetricName, ? extends Metric> metrics(); synchronized void start(); void close(); synchronized boolean close(final long timeout, final TimeUnit timeUnit); @Override String toString(); String toString(final String indent); void cleanUp(); void setUncaughtExceptionHandler(final Thread.UncaughtExceptionHandler eh); Collection<StreamsMetadata> allMetadata(); Collection<StreamsMetadata> allMetadataForStore(final String storeName); StreamsMetadata metadataForKey(final String storeName, final K key, final Serializer<K> keySerializer); StreamsMetadata metadataForKey(final String storeName, final K key, final StreamPartitioner<? super K, ?> partitioner); T store(final String storeName, final QueryableStoreType<T> queryableStoreType); }### Answer: @Test public void testCloseIsIdempotent() throws Exception { streams.close(); final int closeCount = MockMetricsReporter.CLOSE_COUNT.get(); streams.close(); Assert.assertEquals("subsequent close() calls should do nothing", closeCount, MockMetricsReporter.CLOSE_COUNT.get()); }
### Question: KafkaStreams { public Map<MetricName, ? extends Metric> metrics() { return Collections.unmodifiableMap(metrics.metrics()); } KafkaStreams(final TopologyBuilder builder, final Properties props); KafkaStreams(final TopologyBuilder builder, final StreamsConfig config); KafkaStreams(final TopologyBuilder builder, final StreamsConfig config, final KafkaClientSupplier clientSupplier); void setStateListener(final KafkaStreams.StateListener listener); synchronized State state(); Map<MetricName, ? extends Metric> metrics(); synchronized void start(); void close(); synchronized boolean close(final long timeout, final TimeUnit timeUnit); @Override String toString(); String toString(final String indent); void cleanUp(); void setUncaughtExceptionHandler(final Thread.UncaughtExceptionHandler eh); Collection<StreamsMetadata> allMetadata(); Collection<StreamsMetadata> allMetadataForStore(final String storeName); StreamsMetadata metadataForKey(final String storeName, final K key, final Serializer<K> keySerializer); StreamsMetadata metadataForKey(final String storeName, final K key, final StreamPartitioner<? super K, ?> partitioner); T store(final String storeName, final QueryableStoreType<T> queryableStoreType); }### Answer: @Test public void testNumberDefaultMetrics() { final KafkaStreams streams = createKafkaStreams(); final Map<MetricName, ? extends Metric> metrics = streams.metrics(); assertEquals(metrics.size(), 16); }
### Question: KafkaStreams { public Collection<StreamsMetadata> allMetadata() { validateIsRunning(); return streamsMetadataState.getAllMetadata(); } KafkaStreams(final TopologyBuilder builder, final Properties props); KafkaStreams(final TopologyBuilder builder, final StreamsConfig config); KafkaStreams(final TopologyBuilder builder, final StreamsConfig config, final KafkaClientSupplier clientSupplier); void setStateListener(final KafkaStreams.StateListener listener); synchronized State state(); Map<MetricName, ? extends Metric> metrics(); synchronized void start(); void close(); synchronized boolean close(final long timeout, final TimeUnit timeUnit); @Override String toString(); String toString(final String indent); void cleanUp(); void setUncaughtExceptionHandler(final Thread.UncaughtExceptionHandler eh); Collection<StreamsMetadata> allMetadata(); Collection<StreamsMetadata> allMetadataForStore(final String storeName); StreamsMetadata metadataForKey(final String storeName, final K key, final Serializer<K> keySerializer); StreamsMetadata metadataForKey(final String storeName, final K key, final StreamPartitioner<? super K, ?> partitioner); T store(final String storeName, final QueryableStoreType<T> queryableStoreType); }### Answer: @Test(expected = IllegalStateException.class) public void shouldNotGetAllTasksWhenNotRunning() throws Exception { streams.allMetadata(); }
### Question: KafkaStreams { public Collection<StreamsMetadata> allMetadataForStore(final String storeName) { validateIsRunning(); return streamsMetadataState.getAllMetadataForStore(storeName); } KafkaStreams(final TopologyBuilder builder, final Properties props); KafkaStreams(final TopologyBuilder builder, final StreamsConfig config); KafkaStreams(final TopologyBuilder builder, final StreamsConfig config, final KafkaClientSupplier clientSupplier); void setStateListener(final KafkaStreams.StateListener listener); synchronized State state(); Map<MetricName, ? extends Metric> metrics(); synchronized void start(); void close(); synchronized boolean close(final long timeout, final TimeUnit timeUnit); @Override String toString(); String toString(final String indent); void cleanUp(); void setUncaughtExceptionHandler(final Thread.UncaughtExceptionHandler eh); Collection<StreamsMetadata> allMetadata(); Collection<StreamsMetadata> allMetadataForStore(final String storeName); StreamsMetadata metadataForKey(final String storeName, final K key, final Serializer<K> keySerializer); StreamsMetadata metadataForKey(final String storeName, final K key, final StreamPartitioner<? super K, ?> partitioner); T store(final String storeName, final QueryableStoreType<T> queryableStoreType); }### Answer: @Test(expected = IllegalStateException.class) public void shouldNotGetAllTasksWithStoreWhenNotRunning() throws Exception { streams.allMetadataForStore("store"); }
### Question: KafkaStreams { public <K> StreamsMetadata metadataForKey(final String storeName, final K key, final Serializer<K> keySerializer) { validateIsRunning(); return streamsMetadataState.getMetadataWithKey(storeName, key, keySerializer); } KafkaStreams(final TopologyBuilder builder, final Properties props); KafkaStreams(final TopologyBuilder builder, final StreamsConfig config); KafkaStreams(final TopologyBuilder builder, final StreamsConfig config, final KafkaClientSupplier clientSupplier); void setStateListener(final KafkaStreams.StateListener listener); synchronized State state(); Map<MetricName, ? extends Metric> metrics(); synchronized void start(); void close(); synchronized boolean close(final long timeout, final TimeUnit timeUnit); @Override String toString(); String toString(final String indent); void cleanUp(); void setUncaughtExceptionHandler(final Thread.UncaughtExceptionHandler eh); Collection<StreamsMetadata> allMetadata(); Collection<StreamsMetadata> allMetadataForStore(final String storeName); StreamsMetadata metadataForKey(final String storeName, final K key, final Serializer<K> keySerializer); StreamsMetadata metadataForKey(final String storeName, final K key, final StreamPartitioner<? super K, ?> partitioner); T store(final String storeName, final QueryableStoreType<T> queryableStoreType); }### Answer: @Test(expected = IllegalStateException.class) public void shouldNotGetTaskWithKeyAndSerializerWhenNotRunning() throws Exception { streams.metadataForKey("store", "key", Serdes.String().serializer()); } @Test(expected = IllegalStateException.class) public void shouldNotGetTaskWithKeyAndPartitionerWhenNotRunning() throws Exception { streams.metadataForKey("store", "key", new StreamPartitioner<String, Object>() { @Override public Integer partition(final String key, final Object value, final int numPartitions) { return 0; } }); }
### Question: KafkaStreams { @Override public String toString() { return toString(""); } KafkaStreams(final TopologyBuilder builder, final Properties props); KafkaStreams(final TopologyBuilder builder, final StreamsConfig config); KafkaStreams(final TopologyBuilder builder, final StreamsConfig config, final KafkaClientSupplier clientSupplier); void setStateListener(final KafkaStreams.StateListener listener); synchronized State state(); Map<MetricName, ? extends Metric> metrics(); synchronized void start(); void close(); synchronized boolean close(final long timeout, final TimeUnit timeUnit); @Override String toString(); String toString(final String indent); void cleanUp(); void setUncaughtExceptionHandler(final Thread.UncaughtExceptionHandler eh); Collection<StreamsMetadata> allMetadata(); Collection<StreamsMetadata> allMetadataForStore(final String storeName); StreamsMetadata metadataForKey(final String storeName, final K key, final Serializer<K> keySerializer); StreamsMetadata metadataForKey(final String storeName, final K key, final StreamPartitioner<? super K, ?> partitioner); T store(final String storeName, final QueryableStoreType<T> queryableStoreType); }### Answer: @Test public void testToString() { streams.start(); String streamString = streams.toString(); streams.close(); String appId = streamString.split("\\n")[1].split(":")[1].trim(); Assert.assertNotEquals("streamString should not be empty", "", streamString); Assert.assertNotNull("streamString should not be null", streamString); Assert.assertNotEquals("streamString contains non-empty appId", "", appId); Assert.assertNotNull("streamString contains non-null appId", appId); }
### Question: Windows { protected Windows<W> segments(final int segments) throws IllegalArgumentException { if (segments < 2) { throw new IllegalArgumentException("Number of segments must be at least 2."); } this.segments = segments; return this; } protected Windows(); Windows<W> until(final long durationMs); long maintainMs(); abstract Map<Long, W> windowsFor(final long timestamp); abstract long size(); public int segments; }### Answer: @Test public void shouldSetNumberOfSegments() { final int anySegmentSizeLargerThanOne = 5; assertEquals(anySegmentSizeLargerThanOne, new TestWindows().segments(anySegmentSizeLargerThanOne).segments); } @Test(expected = IllegalArgumentException.class) public void numberOfSegmentsMustBeAtLeastTwo() { new TestWindows().segments(1); }
### Question: Windows { public Windows<W> until(final long durationMs) throws IllegalArgumentException { if (durationMs < 0) { throw new IllegalArgumentException("Window retention time (durationMs) cannot be negative."); } maintainDurationMs = durationMs; return this; } protected Windows(); Windows<W> until(final long durationMs); long maintainMs(); abstract Map<Long, W> windowsFor(final long timestamp); abstract long size(); public int segments; }### Answer: @Test(expected = IllegalArgumentException.class) public void retentionTimeMustNotBeNegative() { new TestWindows().until(-1); }
### Question: TimeWindows extends Windows<TimeWindow> { public static TimeWindows of(final long sizeMs) throws IllegalArgumentException { if (sizeMs <= 0) { throw new IllegalArgumentException("Window size (sizeMs) must be larger than zero."); } return new TimeWindows(sizeMs, sizeMs); } private TimeWindows(final long sizeMs, final long advanceMs); static TimeWindows of(final long sizeMs); TimeWindows advanceBy(final long advanceMs); @Override Map<Long, TimeWindow> windowsFor(final long timestamp); @Override long size(); @Override TimeWindows until(final long durationMs); @Override long maintainMs(); @Override boolean equals(final Object o); @Override int hashCode(); final long sizeMs; final long advanceMs; }### Answer: @Test public void shouldSetWindowSize() { assertEquals(ANY_SIZE, TimeWindows.of(ANY_SIZE).sizeMs); } @Test(expected = IllegalArgumentException.class) public void windowSizeMustNotBeZero() { TimeWindows.of(0); } @Test(expected = IllegalArgumentException.class) public void windowSizeMustNotBeNegative() { TimeWindows.of(-1); }
### Question: WindowedStreamPartitioner implements StreamPartitioner<Windowed<K>, V> { public Integer partition(final Windowed<K> windowedKey, final V value, final int numPartitions) { final byte[] keyBytes = serializer.serializeBaseKey(topic, windowedKey); return toPositive(Utils.murmur2(keyBytes)) % numPartitions; } WindowedStreamPartitioner(final String topic, final WindowedSerializer<K> serializer); Integer partition(final Windowed<K> windowedKey, final V value, final int numPartitions); }### Answer: @Test public void testCopartitioning() { Random rand = new Random(); DefaultPartitioner defaultPartitioner = new DefaultPartitioner(); WindowedSerializer<Integer> windowedSerializer = new WindowedSerializer<>(intSerializer); WindowedStreamPartitioner<Integer, String> streamPartitioner = new WindowedStreamPartitioner<>(topicName, windowedSerializer); for (int k = 0; k < 10; k++) { Integer key = rand.nextInt(); byte[] keyBytes = intSerializer.serialize(topicName, key); String value = key.toString(); byte[] valueBytes = stringSerializer.serialize(topicName, value); Integer expected = defaultPartitioner.partition("topic", key, keyBytes, value, valueBytes, cluster); for (int w = 1; w < 10; w++) { TimeWindow window = new TimeWindow(10 * w, 20 * w); Windowed<Integer> windowedKey = new Windowed<>(key, window); Integer actual = streamPartitioner.partition(windowedKey, value, infos.size()); assertEquals(expected, actual); } } }
### Question: KStreamFlatMap implements ProcessorSupplier<K, V> { @Override public Processor<K, V> get() { return new KStreamFlatMapProcessor(); } KStreamFlatMap(KeyValueMapper<? super K, ? super V, ? extends Iterable<? extends KeyValue<? extends K1, ? extends V1>>> mapper); @Override Processor<K, V> get(); }### Answer: @Test public void testFlatMap() { KStreamBuilder builder = new KStreamBuilder(); KeyValueMapper<Number, Object, Iterable<KeyValue<String, String>>> mapper = new KeyValueMapper<Number, Object, Iterable<KeyValue<String, String>>>() { @Override public Iterable<KeyValue<String, String>> apply(Number key, Object value) { ArrayList<KeyValue<String, String>> result = new ArrayList<>(); for (int i = 0; i < key.intValue(); i++) { result.add(KeyValue.pair(Integer.toString(key.intValue() * 10 + i), value.toString())); } return result; } }; final int[] expectedKeys = {0, 1, 2, 3}; KStream<Integer, String> stream; MockProcessorSupplier<String, String> processor; processor = new MockProcessorSupplier<>(); stream = builder.stream(Serdes.Integer(), Serdes.String(), topicName); stream.flatMap(mapper).process(processor); driver = new KStreamTestDriver(builder); for (int expectedKey : expectedKeys) { driver.process(topicName, expectedKey, "V" + expectedKey); } assertEquals(6, processor.processed.size()); String[] expected = {"10:V1", "20:V2", "21:V2", "30:V3", "31:V3", "32:V3"}; for (int i = 0; i < expected.length; i++) { assertEquals(expected[i], processor.processed.get(i)); } }
### Question: KStreamFlatMapValues implements ProcessorSupplier<K, V> { @Override public Processor<K, V> get() { return new KStreamFlatMapValuesProcessor(); } KStreamFlatMapValues(ValueMapper<? super V, ? extends Iterable<? extends V1>> mapper); @Override Processor<K, V> get(); }### Answer: @Test public void testFlatMapValues() { KStreamBuilder builder = new KStreamBuilder(); ValueMapper<Number, Iterable<String>> mapper = new ValueMapper<Number, Iterable<String>>() { @Override public Iterable<String> apply(Number value) { ArrayList<String> result = new ArrayList<String>(); result.add("v" + value); result.add("V" + value); return result; } }; final int[] expectedKeys = {0, 1, 2, 3}; KStream<Integer, Integer> stream; MockProcessorSupplier<Integer, String> processor; processor = new MockProcessorSupplier<>(); stream = builder.stream(Serdes.Integer(), Serdes.Integer(), topicName); stream.flatMapValues(mapper).process(processor); driver = new KStreamTestDriver(builder); for (int expectedKey : expectedKeys) { driver.process(topicName, expectedKey, expectedKey); } assertEquals(8, processor.processed.size()); String[] expected = {"0:v0", "0:V0", "1:v1", "1:V1", "2:v2", "2:V2", "3:v3", "3:V3"}; for (int i = 0; i < expected.length; i++) { assertEquals(expected[i], processor.processed.get(i)); } }
### Question: Cast implements Transformation<R> { @Override public void configure(Map<String, ?> props) { final SimpleConfig config = new SimpleConfig(CONFIG_DEF, props); casts = parseFieldTypes(config.getList(SPEC_CONFIG)); wholeValueCastType = casts.get(WHOLE_VALUE_CAST); schemaUpdateCache = new SynchronizedCache<>(new LRUCache<Schema, Schema>(16)); } @Override void configure(Map<String, ?> props); @Override R apply(R record); @Override ConfigDef config(); @Override void close(); static final String OVERVIEW_DOC; static final String SPEC_CONFIG; static final ConfigDef CONFIG_DEF; }### Answer: @Test(expected = ConfigException.class) public void testConfigEmpty() { final Cast<SourceRecord> xform = new Cast.Key<>(); xform.configure(Collections.singletonMap(Cast.SPEC_CONFIG, "")); } @Test(expected = ConfigException.class) public void testConfigInvalidSchemaType() { final Cast<SourceRecord> xform = new Cast.Key<>(); xform.configure(Collections.singletonMap(Cast.SPEC_CONFIG, "foo:faketype")); } @Test(expected = ConfigException.class) public void testConfigInvalidTargetType() { final Cast<SourceRecord> xform = new Cast.Key<>(); xform.configure(Collections.singletonMap(Cast.SPEC_CONFIG, "foo:array")); } @Test(expected = ConfigException.class) public void testConfigInvalidMap() { final Cast<SourceRecord> xform = new Cast.Key<>(); xform.configure(Collections.singletonMap(Cast.SPEC_CONFIG, "foo:int8:extra")); } @Test(expected = ConfigException.class) public void testConfigMixWholeAndFieldTransformation() { final Cast<SourceRecord> xform = new Cast.Key<>(); xform.configure(Collections.singletonMap(Cast.SPEC_CONFIG, "foo:int8,int32")); }
### Question: SessionKeySerde implements Serde<Windowed<K>> { @Override public Serializer<Windowed<K>> serializer() { return new SessionKeySerializer(keySerde.serializer()); } SessionKeySerde(final Serde<K> keySerde); @Override void configure(final Map<String, ?> configs, final boolean isKey); @Override void close(); @Override Serializer<Windowed<K>> serializer(); @Override Deserializer<Windowed<K>> deserializer(); static long extractEnd(final byte[] binaryKey); static long extractStart(final byte[] binaryKey); static byte[] extractKeyBytes(final byte[] binaryKey); static Windowed<K> from(final byte[] binaryKey, final Deserializer<K> keyDeserializer, final String topic); static Windowed<Bytes> fromBytes(Bytes bytesKey); static Bytes toBinary(final Windowed<K> sessionKey, final Serializer<K> serializer, final String topic); static Bytes bytesToBinary(final Windowed<Bytes> sessionKey); }### Answer: @Test public void shouldSerializeNullToNull() throws Exception { assertNull(sessionKeySerde.serializer().serialize(topic, null)); }
### Question: SessionKeySerde implements Serde<Windowed<K>> { @Override public Deserializer<Windowed<K>> deserializer() { return new SessionKeyDeserializer(keySerde.deserializer()); } SessionKeySerde(final Serde<K> keySerde); @Override void configure(final Map<String, ?> configs, final boolean isKey); @Override void close(); @Override Serializer<Windowed<K>> serializer(); @Override Deserializer<Windowed<K>> deserializer(); static long extractEnd(final byte[] binaryKey); static long extractStart(final byte[] binaryKey); static byte[] extractKeyBytes(final byte[] binaryKey); static Windowed<K> from(final byte[] binaryKey, final Deserializer<K> keyDeserializer, final String topic); static Windowed<Bytes> fromBytes(Bytes bytesKey); static Bytes toBinary(final Windowed<K> sessionKey, final Serializer<K> serializer, final String topic); static Bytes bytesToBinary(final Windowed<Bytes> sessionKey); }### Answer: @Test public void shouldDeSerializeEmtpyByteArrayToNull() throws Exception { assertNull(sessionKeySerde.deserializer().deserialize(topic, new byte[0])); } @Test public void shouldDeSerializeNullToNull() throws Exception { assertNull(sessionKeySerde.deserializer().deserialize(topic, null)); }
### Question: KStreamMap implements ProcessorSupplier<K, V> { @Override public Processor<K, V> get() { return new KStreamMapProcessor(); } KStreamMap(KeyValueMapper<? super K, ? super V, ? extends KeyValue<? extends K1, ? extends V1>> mapper); @Override Processor<K, V> get(); }### Answer: @Test public void testMap() { KStreamBuilder builder = new KStreamBuilder(); KeyValueMapper<Integer, String, KeyValue<String, Integer>> mapper = new KeyValueMapper<Integer, String, KeyValue<String, Integer>>() { @Override public KeyValue<String, Integer> apply(Integer key, String value) { return KeyValue.pair(value, key); } }; final int[] expectedKeys = new int[]{0, 1, 2, 3}; KStream<Integer, String> stream = builder.stream(intSerde, stringSerde, topicName); MockProcessorSupplier<String, Integer> processor; processor = new MockProcessorSupplier<>(); stream.map(mapper).process(processor); driver = new KStreamTestDriver(builder); for (int expectedKey : expectedKeys) { driver.process(topicName, expectedKey, "V" + expectedKey); } assertEquals(4, processor.processed.size()); String[] expected = new String[]{"V0:0", "V1:1", "V2:2", "V3:3"}; for (int i = 0; i < expected.length; i++) { assertEquals(expected[i], processor.processed.get(i)); } }
### Question: KTableSource implements ProcessorSupplier<K, V> { @Override public Processor<K, V> get() { return new KTableSourceProcessor(); } KTableSource(String storeName); @Override Processor<K, V> get(); void enableSendingOldValues(); final String storeName; }### Answer: @Test public void testValueGetter() throws IOException { final KStreamBuilder builder = new KStreamBuilder(); String topic1 = "topic1"; KTableImpl<String, String, String> table1 = (KTableImpl<String, String, String>) builder.table(stringSerde, stringSerde, topic1, "anyStoreName"); KTableValueGetterSupplier<String, String> getterSupplier1 = table1.valueGetterSupplier(); driver = new KStreamTestDriver(builder, stateDir, null, null); KTableValueGetter<String, String> getter1 = getterSupplier1.get(); getter1.init(driver.context()); driver.process(topic1, "A", "01"); driver.process(topic1, "B", "01"); driver.process(topic1, "C", "01"); assertEquals("01", getter1.get("A")); assertEquals("01", getter1.get("B")); assertEquals("01", getter1.get("C")); driver.process(topic1, "A", "02"); driver.process(topic1, "B", "02"); assertEquals("02", getter1.get("A")); assertEquals("02", getter1.get("B")); assertEquals("01", getter1.get("C")); driver.process(topic1, "A", "03"); assertEquals("03", getter1.get("A")); assertEquals("02", getter1.get("B")); assertEquals("01", getter1.get("C")); driver.process(topic1, "A", null); driver.process(topic1, "B", null); assertNull(getter1.get("A")); assertNull(getter1.get("B")); assertEquals("01", getter1.get("C")); }
### Question: KTableSource implements ProcessorSupplier<K, V> { public void enableSendingOldValues() { sendOldValues = true; } KTableSource(String storeName); @Override Processor<K, V> get(); void enableSendingOldValues(); final String storeName; }### Answer: @Test public void testSendingOldValue() throws IOException { final KStreamBuilder builder = new KStreamBuilder(); String topic1 = "topic1"; KTableImpl<String, String, String> table1 = (KTableImpl<String, String, String>) builder.table(stringSerde, stringSerde, topic1, "anyStoreName"); table1.enableSendingOldValues(); assertTrue(table1.sendingOldValueEnabled()); MockProcessorSupplier<String, Integer> proc1 = new MockProcessorSupplier<>(); builder.addProcessor("proc1", proc1, table1.name); driver = new KStreamTestDriver(builder, stateDir, null, null); driver.process(topic1, "A", "01"); driver.process(topic1, "B", "01"); driver.process(topic1, "C", "01"); driver.flushState(); proc1.checkAndClearProcessResult("A:(01<-null)", "B:(01<-null)", "C:(01<-null)"); driver.process(topic1, "A", "02"); driver.process(topic1, "B", "02"); driver.flushState(); proc1.checkAndClearProcessResult("A:(02<-01)", "B:(02<-01)"); driver.process(topic1, "A", "03"); driver.flushState(); proc1.checkAndClearProcessResult("A:(03<-02)"); driver.process(topic1, "A", null); driver.process(topic1, "B", null); driver.flushState(); proc1.checkAndClearProcessResult("A:(null<-03)", "B:(null<-02)"); }
### Question: ByteArrayConverter implements Converter { @Override public byte[] fromConnectData(String topic, Schema schema, Object value) { if (schema != null && schema.type() != Schema.Type.BYTES) throw new DataException("Invalid schema type for ByteArrayConverter: " + schema.type().toString()); if (value != null && !(value instanceof byte[])) throw new DataException("ByteArrayConverter is not compatible with objects of type " + value.getClass()); return (byte[]) value; } @Override void configure(Map<String, ?> configs, boolean isKey); @Override byte[] fromConnectData(String topic, Schema schema, Object value); @Override SchemaAndValue toConnectData(String topic, byte[] value); }### Answer: @Test public void testFromConnect() { assertArrayEquals( SAMPLE_BYTES, converter.fromConnectData(TOPIC, Schema.BYTES_SCHEMA, SAMPLE_BYTES) ); } @Test public void testFromConnectSchemaless() { assertArrayEquals( SAMPLE_BYTES, converter.fromConnectData(TOPIC, null, SAMPLE_BYTES) ); } @Test(expected = DataException.class) public void testFromConnectBadSchema() { converter.fromConnectData(TOPIC, Schema.INT32_SCHEMA, SAMPLE_BYTES); } @Test(expected = DataException.class) public void testFromConnectInvalidValue() { converter.fromConnectData(TOPIC, Schema.BYTES_SCHEMA, 12); } @Test public void testFromConnectNull() { assertNull(converter.fromConnectData(TOPIC, Schema.BYTES_SCHEMA, null)); }
### Question: KStreamMapValues implements ProcessorSupplier<K, V> { @Override public Processor<K, V> get() { return new KStreamMapProcessor(); } KStreamMapValues(ValueMapper<V, V1> mapper); @Override Processor<K, V> get(); }### Answer: @Test public void testFlatMapValues() { KStreamBuilder builder = new KStreamBuilder(); ValueMapper<CharSequence, Integer> mapper = new ValueMapper<CharSequence, Integer>() { @Override public Integer apply(CharSequence value) { return value.length(); } }; final int[] expectedKeys = {1, 10, 100, 1000}; KStream<Integer, String> stream; MockProcessorSupplier<Integer, Integer> processor = new MockProcessorSupplier<>(); stream = builder.stream(intSerde, stringSerde, topicName); stream.mapValues(mapper).process(processor); driver = new KStreamTestDriver(builder); for (int expectedKey : expectedKeys) { driver.process(topicName, expectedKey, Integer.toString(expectedKey)); } assertEquals(4, processor.processed.size()); String[] expected = {"1:1", "10:2", "100:3", "1000:4"}; for (int i = 0; i < expected.length; i++) { assertEquals(expected[i], processor.processed.get(i)); } }
### Question: ByteArrayConverter implements Converter { @Override public SchemaAndValue toConnectData(String topic, byte[] value) { return new SchemaAndValue(Schema.OPTIONAL_BYTES_SCHEMA, value); } @Override void configure(Map<String, ?> configs, boolean isKey); @Override byte[] fromConnectData(String topic, Schema schema, Object value); @Override SchemaAndValue toConnectData(String topic, byte[] value); }### Answer: @Test public void testToConnect() { SchemaAndValue data = converter.toConnectData(TOPIC, SAMPLE_BYTES); assertEquals(Schema.OPTIONAL_BYTES_SCHEMA, data.schema()); assertTrue(Arrays.equals(SAMPLE_BYTES, (byte[]) data.value())); } @Test public void testToConnectNull() { SchemaAndValue data = converter.toConnectData(TOPIC, null); assertEquals(Schema.OPTIONAL_BYTES_SCHEMA, data.schema()); assertNull(data.value()); }
### Question: SessionWindows { public static SessionWindows with(final long inactivityGapMs) { if (inactivityGapMs <= 0) { throw new IllegalArgumentException("Gap time (inactivityGapMs) cannot be zero or negative."); } return new SessionWindows(inactivityGapMs); } private SessionWindows(final long gapMs); static SessionWindows with(final long inactivityGapMs); SessionWindows until(final long durationMs); long inactivityGap(); long maintainMs(); }### Answer: @Test(expected = IllegalArgumentException.class) public void windowSizeMustNotBeNegative() { SessionWindows.with(-1); } @Test(expected = IllegalArgumentException.class) public void windowSizeMustNotBeZero() { SessionWindows.with(0); }
### Question: JoinWindows extends Windows<Window> { public static JoinWindows of(final long timeDifferenceMs) throws IllegalArgumentException { return new JoinWindows(timeDifferenceMs, timeDifferenceMs); } private JoinWindows(final long beforeMs, final long afterMs); static JoinWindows of(final long timeDifferenceMs); JoinWindows before(final long timeDifferenceMs); JoinWindows after(final long timeDifferenceMs); @Override Map<Long, Window> windowsFor(final long timestamp); @Override long size(); @Override JoinWindows until(final long durationMs); @Override long maintainMs(); @Override final boolean equals(final Object o); @Override int hashCode(); final long beforeMs; final long afterMs; }### Answer: @Test(expected = IllegalArgumentException.class) public void timeDifferenceMustNotBeNegative() { JoinWindows.of(-1); }
### Question: WallclockTimestampExtractor implements TimestampExtractor { @Override public long extract(final ConsumerRecord<Object, Object> record, final long previousTimestamp) { return System.currentTimeMillis(); } @Override long extract(final ConsumerRecord<Object, Object> record, final long previousTimestamp); }### Answer: @Test public void extractSystemTimestamp() { final TimestampExtractor extractor = new WallclockTimestampExtractor(); final long before = System.currentTimeMillis(); final long timestamp = extractor.extract(new ConsumerRecord<>("anyTopic", 0, 0, null, null), 42); final long after = System.currentTimeMillis(); assertThat(timestamp, is(new InBetween(before, after))); }
### Question: StateRestorer { void restore(final byte[] key, final byte[] value) { stateRestoreCallback.restore(key, value); } StateRestorer(final TopicPartition partition, final StateRestoreCallback stateRestoreCallback, final Long checkpoint, final long offsetLimit, final boolean persistent); TopicPartition partition(); }### Answer: @Test public void shouldCallRestoreOnRestoreCallback() throws Exception { restorer.restore(new byte[0], new byte[0]); assertThat(callback.restored.size(), equalTo(1)); }
### Question: StateRestorer { boolean hasCompleted(final long recordOffset, final long endOffset) { return endOffset == 0 || recordOffset >= readTo(endOffset); } StateRestorer(final TopicPartition partition, final StateRestoreCallback stateRestoreCallback, final Long checkpoint, final long offsetLimit, final boolean persistent); TopicPartition partition(); }### Answer: @Test public void shouldBeCompletedIfRecordOffsetGreaterThanEndOffset() throws Exception { assertTrue(restorer.hasCompleted(11, 10)); } @Test public void shouldBeCompletedIfRecordOffsetGreaterThanOffsetLimit() throws Exception { assertTrue(restorer.hasCompleted(51, 100)); } @Test public void shouldBeCompletedIfEndOffsetAndRecordOffsetAreZero() throws Exception { assertTrue(restorer.hasCompleted(0, 0)); } @Test public void shouldBeCompletedIfOffsetAndOffsetLimitAreZero() throws Exception { final StateRestorer restorer = new StateRestorer(new TopicPartition("topic", 1), callback, null, 0, true); assertTrue(restorer.hasCompleted(0, 10)); }
### Question: AbstractProcessorContext implements InternalProcessorContext { @Override public void register(final StateStore store, final boolean loggingEnabled, final StateRestoreCallback stateRestoreCallback) { if (initialized) { throw new IllegalStateException("Can only create state stores during initialization."); } Objects.requireNonNull(store, "store must not be null"); stateManager.register(store, loggingEnabled, stateRestoreCallback); } AbstractProcessorContext(final TaskId taskId, final String applicationId, final StreamsConfig config, final StreamsMetrics metrics, final StateManager stateManager, final ThreadCache cache); @Override String applicationId(); @Override TaskId taskId(); @Override Serde<?> keySerde(); @Override Serde<?> valueSerde(); @Override File stateDir(); @Override StreamsMetrics metrics(); @Override void register(final StateStore store, final boolean loggingEnabled, final StateRestoreCallback stateRestoreCallback); @Override String topic(); @Override int partition(); @Override long offset(); @Override long timestamp(); @Override Map<String, Object> appConfigs(); @Override Map<String, Object> appConfigsWithPrefix(String prefix); @Override void setRecordContext(final RecordContext recordContext); @Override RecordContext recordContext(); @Override void setCurrentNode(final ProcessorNode currentNode); @Override ProcessorNode currentNode(); @Override ThreadCache getCache(); @Override void initialized(); }### Answer: @Test public void shouldNotThrowIllegalStateExceptionOnRegisterWhenContextIsNotInitialized() throws Exception { context.register(stateStore, false, null); } @Test(expected = NullPointerException.class) public void shouldThrowNullPointerOnRegisterIfStateStoreIsNull() { context.register(null, false, null); }
### Question: AbstractProcessorContext implements InternalProcessorContext { @Override public String topic() { if (recordContext == null) { throw new IllegalStateException("This should not happen as topic() should only be called while a record is processed"); } final String topic = recordContext.topic(); if (topic.equals(NONEXIST_TOPIC)) { return null; } return topic; } AbstractProcessorContext(final TaskId taskId, final String applicationId, final StreamsConfig config, final StreamsMetrics metrics, final StateManager stateManager, final ThreadCache cache); @Override String applicationId(); @Override TaskId taskId(); @Override Serde<?> keySerde(); @Override Serde<?> valueSerde(); @Override File stateDir(); @Override StreamsMetrics metrics(); @Override void register(final StateStore store, final boolean loggingEnabled, final StateRestoreCallback stateRestoreCallback); @Override String topic(); @Override int partition(); @Override long offset(); @Override long timestamp(); @Override Map<String, Object> appConfigs(); @Override Map<String, Object> appConfigsWithPrefix(String prefix); @Override void setRecordContext(final RecordContext recordContext); @Override RecordContext recordContext(); @Override void setCurrentNode(final ProcessorNode currentNode); @Override ProcessorNode currentNode(); @Override ThreadCache getCache(); @Override void initialized(); }### Answer: @Test public void shouldReturnTopicFromRecordContext() throws Exception { assertThat(context.topic(), equalTo(recordContext.topic())); }
### Question: AbstractProcessorContext implements InternalProcessorContext { @Override public int partition() { if (recordContext == null) { throw new IllegalStateException("This should not happen as partition() should only be called while a record is processed"); } return recordContext.partition(); } AbstractProcessorContext(final TaskId taskId, final String applicationId, final StreamsConfig config, final StreamsMetrics metrics, final StateManager stateManager, final ThreadCache cache); @Override String applicationId(); @Override TaskId taskId(); @Override Serde<?> keySerde(); @Override Serde<?> valueSerde(); @Override File stateDir(); @Override StreamsMetrics metrics(); @Override void register(final StateStore store, final boolean loggingEnabled, final StateRestoreCallback stateRestoreCallback); @Override String topic(); @Override int partition(); @Override long offset(); @Override long timestamp(); @Override Map<String, Object> appConfigs(); @Override Map<String, Object> appConfigsWithPrefix(String prefix); @Override void setRecordContext(final RecordContext recordContext); @Override RecordContext recordContext(); @Override void setCurrentNode(final ProcessorNode currentNode); @Override ProcessorNode currentNode(); @Override ThreadCache getCache(); @Override void initialized(); }### Answer: @Test public void shouldReturnPartitionFromRecordContext() throws Exception { assertThat(context.partition(), equalTo(recordContext.partition())); }
### Question: AbstractProcessorContext implements InternalProcessorContext { @Override public long offset() { if (recordContext == null) { throw new IllegalStateException("This should not happen as offset() should only be called while a record is processed"); } return recordContext.offset(); } AbstractProcessorContext(final TaskId taskId, final String applicationId, final StreamsConfig config, final StreamsMetrics metrics, final StateManager stateManager, final ThreadCache cache); @Override String applicationId(); @Override TaskId taskId(); @Override Serde<?> keySerde(); @Override Serde<?> valueSerde(); @Override File stateDir(); @Override StreamsMetrics metrics(); @Override void register(final StateStore store, final boolean loggingEnabled, final StateRestoreCallback stateRestoreCallback); @Override String topic(); @Override int partition(); @Override long offset(); @Override long timestamp(); @Override Map<String, Object> appConfigs(); @Override Map<String, Object> appConfigsWithPrefix(String prefix); @Override void setRecordContext(final RecordContext recordContext); @Override RecordContext recordContext(); @Override void setCurrentNode(final ProcessorNode currentNode); @Override ProcessorNode currentNode(); @Override ThreadCache getCache(); @Override void initialized(); }### Answer: @Test public void shouldReturnOffsetFromRecordContext() throws Exception { assertThat(context.offset(), equalTo(recordContext.offset())); }
### Question: AbstractProcessorContext implements InternalProcessorContext { @Override public long timestamp() { if (recordContext == null) { throw new IllegalStateException("This should not happen as timestamp() should only be called while a record is processed"); } return recordContext.timestamp(); } AbstractProcessorContext(final TaskId taskId, final String applicationId, final StreamsConfig config, final StreamsMetrics metrics, final StateManager stateManager, final ThreadCache cache); @Override String applicationId(); @Override TaskId taskId(); @Override Serde<?> keySerde(); @Override Serde<?> valueSerde(); @Override File stateDir(); @Override StreamsMetrics metrics(); @Override void register(final StateStore store, final boolean loggingEnabled, final StateRestoreCallback stateRestoreCallback); @Override String topic(); @Override int partition(); @Override long offset(); @Override long timestamp(); @Override Map<String, Object> appConfigs(); @Override Map<String, Object> appConfigsWithPrefix(String prefix); @Override void setRecordContext(final RecordContext recordContext); @Override RecordContext recordContext(); @Override void setCurrentNode(final ProcessorNode currentNode); @Override ProcessorNode currentNode(); @Override ThreadCache getCache(); @Override void initialized(); }### Answer: @Test public void shouldReturnTimestampFromRecordContext() throws Exception { assertThat(context.timestamp(), equalTo(recordContext.timestamp())); }
### Question: TopicAdmin implements AutoCloseable { public boolean createTopic(NewTopic topic) { if (topic == null) return false; Set<String> newTopicNames = createTopics(topic); return newTopicNames.contains(topic.name()); } TopicAdmin(Map<String, Object> adminConfig); TopicAdmin(Map<String, Object> adminConfig, AdminClient adminClient); static NewTopicBuilder defineTopic(String topicName); boolean createTopic(NewTopic topic); Set<String> createTopics(NewTopic... topics); @Override void close(); }### Answer: @Test public void shouldReturnFalseWhenSuppliedNullTopicDescription() { Cluster cluster = createCluster(1); try (MockKafkaAdminClientEnv env = new MockKafkaAdminClientEnv(cluster)) { env.kafkaClient().setNode(cluster.controller()); env.kafkaClient().setNodeApiVersions(NodeApiVersions.create()); env.kafkaClient().prepareMetadataUpdate(env.cluster(), Collections.<String>emptySet()); TopicAdmin admin = new TopicAdmin(null, env.adminClient()); boolean created = admin.createTopic(null); assertFalse(created); } }
### Question: StandbyTask extends AbstractTask { Map<TopicPartition, Long> checkpointedOffsets() { return checkpointedOffsets; } StandbyTask(final TaskId id, final String applicationId, final Collection<TopicPartition> partitions, final ProcessorTopology topology, final Consumer<byte[], byte[]> consumer, final ChangelogReader changelogReader, final StreamsConfig config, final StreamsMetrics metrics, final StateDirectory stateDirectory); @Override void resume(); @Override void commit(); @Override void suspend(); @Override void close(final boolean clean); List<ConsumerRecord<byte[], byte[]>> update(final TopicPartition partition, final List<ConsumerRecord<byte[], byte[]>> records); }### Answer: @Test public void testStorePartitions() throws Exception { StreamsConfig config = createConfig(baseDir); StandbyTask task = new StandbyTask(taskId, applicationId, topicPartitions, topology, consumer, changelogReader, config, null, stateDirectory); assertEquals(Utils.mkSet(partition2), new HashSet<>(task.checkpointedOffsets().keySet())); }
### Question: StateDirectory { File directoryForTask(final TaskId taskId) { final File taskDir = new File(stateDir, taskId.toString()); if (!taskDir.exists() && !taskDir.mkdir()) { throw new ProcessorStateException(String.format("task directory [%s] doesn't exist and couldn't be created", taskDir.getPath())); } return taskDir; } StateDirectory(final String applicationId, final String stateDirConfig, final Time time); StateDirectory(final String applicationId, final String threadId, final String stateDirConfig, final Time time); void cleanRemovedTasks(final long cleanupDelayMs); }### Answer: @Test public void shouldCreateTaskStateDirectory() throws Exception { final TaskId taskId = new TaskId(0, 0); final File taskDirectory = directory.directoryForTask(taskId); assertTrue(taskDirectory.exists()); assertTrue(taskDirectory.isDirectory()); } @Test(expected = ProcessorStateException.class) public void shouldThrowProcessorStateException() throws Exception { final TaskId taskId = new TaskId(0, 0); Utils.delete(stateDir); directory.directoryForTask(taskId); } @Test public void shouldCreateDirectoriesIfParentDoesntExist() throws Exception { final File tempDir = TestUtils.tempDirectory(); final File stateDir = new File(new File(tempDir, "foo"), "state-dir"); final StateDirectory stateDirectory = new StateDirectory(applicationId, stateDir.getPath(), time); final File taskDir = stateDirectory.directoryForTask(new TaskId(0, 0)); assertTrue(stateDir.exists()); assertTrue(taskDir.exists()); }
### Question: StateDirectory { boolean lock(final TaskId taskId, int retry) throws IOException { final File lockFile; if (locks.containsKey(taskId)) { log.trace("{} Found cached state dir lock for task {}", logPrefix, taskId); return true; } try { lockFile = new File(directoryForTask(taskId), LOCK_FILE_NAME); } catch (ProcessorStateException e) { return false; } final FileChannel channel; try { channel = getOrCreateFileChannel(taskId, lockFile.toPath()); } catch (NoSuchFileException e) { return false; } final FileLock lock = tryLock(retry, channel); if (lock != null) { locks.put(taskId, lock); log.debug("{} Acquired state dir lock for task {}", logPrefix, taskId); } return lock != null; } StateDirectory(final String applicationId, final String stateDirConfig, final Time time); StateDirectory(final String applicationId, final String threadId, final String stateDirConfig, final Time time); void cleanRemovedTasks(final long cleanupDelayMs); }### Answer: @Test public void shouldNotLockDeletedDirectory() throws Exception { final TaskId taskId = new TaskId(0, 0); Utils.delete(stateDir); assertFalse(directory.lock(taskId, 0)); }
### Question: StateDirectory { public void cleanRemovedTasks(final long cleanupDelayMs) { final File[] taskDirs = listTaskDirectories(); if (taskDirs == null || taskDirs.length == 0) { return; } for (File taskDir : taskDirs) { final String dirName = taskDir.getName(); TaskId id = TaskId.parse(dirName); if (!locks.containsKey(id)) { try { if (lock(id, 0)) { if (time.milliseconds() > taskDir.lastModified() + cleanupDelayMs) { log.info("{} Deleting obsolete state directory {} for task {} as cleanup delay of {} ms has passed", logPrefix, dirName, id, cleanupDelayMs); Utils.delete(taskDir); } } } catch (OverlappingFileLockException e) { } catch (IOException e) { log.error("{} Failed to lock the state directory due to an unexpected exception", logPrefix, e); } finally { try { unlock(id); } catch (IOException e) { log.error("{} Failed to release the state directory lock", logPrefix); } } } } } StateDirectory(final String applicationId, final String stateDirConfig, final Time time); StateDirectory(final String applicationId, final String threadId, final String stateDirConfig, final Time time); void cleanRemovedTasks(final long cleanupDelayMs); }### Answer: @Test public void shouldNotRemoveNonTaskDirectoriesAndFiles() throws Exception { final File otherDir = TestUtils.tempDirectory(stateDir.toPath(), "foo"); directory.cleanRemovedTasks(0); assertTrue(otherDir.exists()); }
### Question: StreamTask extends AbstractTask implements Punctuator { @Override protected void flushState() { log.trace("{} Flushing state and producer", logPrefix); super.flushState(); recordCollector.flush(); } StreamTask(final TaskId id, final String applicationId, final Collection<TopicPartition> partitions, final ProcessorTopology topology, final Consumer<byte[], byte[]> consumer, final ChangelogReader changelogReader, final StreamsConfig config, final StreamsMetrics metrics, final StateDirectory stateDirectory, final ThreadCache cache, final Time time, final Producer<byte[], byte[]> producer); @Override void resume(); @SuppressWarnings("unchecked") boolean process(); @Override void punctuate(final ProcessorNode node, final long timestamp); @Override void commit(); @Override void suspend(); @Override void close(boolean clean); @SuppressWarnings("unchecked") int addRecords(final TopicPartition partition, final Iterable<ConsumerRecord<byte[], byte[]>> records); void schedule(final long interval); }### Answer: @Test public void shouldFlushRecordCollectorOnFlushState() throws Exception { final AtomicBoolean flushed = new AtomicBoolean(false); final StreamsMetrics streamsMetrics = new MockStreamsMetrics(new Metrics()); final StreamTask streamTask = new StreamTask(taskId00, "appId", partitions, topology, consumer, changelogReader, config, streamsMetrics, stateDirectory, null, time, producer) { @Override RecordCollector createRecordCollector() { return new NoOpRecordCollector() { @Override public void flush() { flushed.set(true); } }; } }; streamTask.flushState(); assertTrue(flushed.get()); }
### Question: StreamTask extends AbstractTask implements Punctuator { @Override public void punctuate(final ProcessorNode node, final long timestamp) { if (processorContext.currentNode() != null) { throw new IllegalStateException(String.format("%s Current node is not null", logPrefix)); } updateProcessorContext(new StampedRecord(DUMMY_RECORD, timestamp), node); log.trace("{} Punctuating processor {} with timestamp {}", logPrefix, node.name(), timestamp); try { node.punctuate(timestamp); } catch (final KafkaException e) { throw new StreamsException(String.format("%s Exception caught while punctuating processor '%s'", logPrefix, node.name()), e); } finally { processorContext.setCurrentNode(null); } } StreamTask(final TaskId id, final String applicationId, final Collection<TopicPartition> partitions, final ProcessorTopology topology, final Consumer<byte[], byte[]> consumer, final ChangelogReader changelogReader, final StreamsConfig config, final StreamsMetrics metrics, final StateDirectory stateDirectory, final ThreadCache cache, final Time time, final Producer<byte[], byte[]> producer); @Override void resume(); @SuppressWarnings("unchecked") boolean process(); @Override void punctuate(final ProcessorNode node, final long timestamp); @Override void commit(); @Override void suspend(); @Override void close(boolean clean); @SuppressWarnings("unchecked") int addRecords(final TopicPartition partition, final Iterable<ConsumerRecord<byte[], byte[]>> records); void schedule(final long interval); }### Answer: @Test public void shouldCallPunctuateOnPassedInProcessorNode() throws Exception { task.punctuate(processor, 5); assertThat(processor.punctuatedAt, equalTo(5L)); task.punctuate(processor, 10); assertThat(processor.punctuatedAt, equalTo(10L)); }
### Question: StreamTask extends AbstractTask implements Punctuator { public void schedule(final long interval) { if (processorContext.currentNode() == null) { throw new IllegalStateException(String.format("%s Current node is null", logPrefix)); } punctuationQueue.schedule(new PunctuationSchedule(processorContext.currentNode(), interval)); } StreamTask(final TaskId id, final String applicationId, final Collection<TopicPartition> partitions, final ProcessorTopology topology, final Consumer<byte[], byte[]> consumer, final ChangelogReader changelogReader, final StreamsConfig config, final StreamsMetrics metrics, final StateDirectory stateDirectory, final ThreadCache cache, final Time time, final Producer<byte[], byte[]> producer); @Override void resume(); @SuppressWarnings("unchecked") boolean process(); @Override void punctuate(final ProcessorNode node, final long timestamp); @Override void commit(); @Override void suspend(); @Override void close(boolean clean); @SuppressWarnings("unchecked") int addRecords(final TopicPartition partition, final Iterable<ConsumerRecord<byte[], byte[]>> records); void schedule(final long interval); }### Answer: @Test(expected = IllegalStateException.class) public void shouldThrowIllegalStateExceptionOnScheduleIfCurrentNodeIsNull() throws Exception { task.schedule(1); }
### Question: StreamTask extends AbstractTask implements Punctuator { @Override public void suspend() { suspend(true); } StreamTask(final TaskId id, final String applicationId, final Collection<TopicPartition> partitions, final ProcessorTopology topology, final Consumer<byte[], byte[]> consumer, final ChangelogReader changelogReader, final StreamsConfig config, final StreamsMetrics metrics, final StateDirectory stateDirectory, final ThreadCache cache, final Time time, final Producer<byte[], byte[]> producer); @Override void resume(); @SuppressWarnings("unchecked") boolean process(); @Override void punctuate(final ProcessorNode node, final long timestamp); @Override void commit(); @Override void suspend(); @Override void close(boolean clean); @SuppressWarnings("unchecked") int addRecords(final TopicPartition partition, final Iterable<ConsumerRecord<byte[], byte[]>> records); void schedule(final long interval); }### Answer: @Test public void shouldCommitTransactionOnSuspendEvenIfTransactionIsEmptyIfEosEnabled() throws Exception { final MockProducer producer = new MockProducer(); task = new StreamTask(taskId00, applicationId, partitions, topology, consumer, changelogReader, eosConfig, streamsMetrics, stateDirectory, null, time, producer); task.suspend(); assertTrue(producer.transactionCommitted()); assertFalse(producer.transactionInFlight()); }
### Question: StreamsMetadataState { public synchronized Collection<StreamsMetadata> getAllMetadata() { return allMetadata; } StreamsMetadataState(final TopologyBuilder builder, final HostInfo thisHost); synchronized Collection<StreamsMetadata> getAllMetadata(); synchronized Collection<StreamsMetadata> getAllMetadataForStore(final String storeName); synchronized StreamsMetadata getMetadataWithKey(final String storeName, final K key, final Serializer<K> keySerializer); synchronized StreamsMetadata getMetadataWithKey(final String storeName, final K key, final StreamPartitioner<? super K, ?> partitioner); synchronized void onChange(final Map<HostInfo, Set<TopicPartition>> currentState, final Cluster clusterMetadata); static final HostInfo UNKNOWN_HOST; }### Answer: @Test public void shouldGetAllStreamInstances() throws Exception { final StreamsMetadata one = new StreamsMetadata(hostOne, Utils.mkSet(globalTable, "table-one", "table-two", "merged-table"), Utils.mkSet(topic1P0, topic2P1, topic4P0)); final StreamsMetadata two = new StreamsMetadata(hostTwo, Utils.mkSet(globalTable, "table-two", "table-one", "merged-table"), Utils.mkSet(topic2P0, topic1P1)); final StreamsMetadata three = new StreamsMetadata(hostThree, Utils.mkSet(globalTable, "table-three"), Collections.singleton(topic3P0)); Collection<StreamsMetadata> actual = discovery.getAllMetadata(); assertEquals(3, actual.size()); assertTrue("expected " + actual + " to contain " + one, actual.contains(one)); assertTrue("expected " + actual + " to contain " + two, actual.contains(two)); assertTrue("expected " + actual + " to contain " + three, actual.contains(three)); }
### Question: ProcessorTopology { public List<StateStore> globalStateStores() { return globalStateStores; } ProcessorTopology(final List<ProcessorNode> processorNodes, final Map<String, SourceNode> sourceByTopics, final Map<String, SinkNode> sinkByTopics, final List<StateStore> stateStores, final Map<String, String> storeToChangelogTopic, final List<StateStore> globalStateStores); Set<String> sourceTopics(); SourceNode source(String topic); Set<SourceNode> sources(); Set<String> sinkTopics(); SinkNode sink(String topic); Set<SinkNode> sinks(); List<ProcessorNode> processors(); List<StateStore> stateStores(); Map<String, String> storeToChangelogTopic(); List<StateStore> globalStateStores(); @Override String toString(); String toString(final String indent); }### Answer: @SuppressWarnings("unchecked") @Test public void shouldDriveGlobalStore() throws Exception { final StateStoreSupplier storeSupplier = Stores.create("my-store") .withStringKeys().withStringValues().inMemory().disableLogging().build(); final String global = "global"; final String topic = "topic"; final TopologyBuilder topologyBuilder = this.builder .addGlobalStore(storeSupplier, global, STRING_DESERIALIZER, STRING_DESERIALIZER, topic, "processor", define(new StatefulProcessor("my-store"))); driver = new ProcessorTopologyTestDriver(config, topologyBuilder); final KeyValueStore<String, String> globalStore = (KeyValueStore<String, String>) topologyBuilder.globalStateStores().get("my-store"); driver.process(topic, "key1", "value1", STRING_SERIALIZER, STRING_SERIALIZER); driver.process(topic, "key2", "value2", STRING_SERIALIZER, STRING_SERIALIZER); assertEquals("value1", globalStore.get("key1")); assertEquals("value2", globalStore.get("key2")); }
### Question: InternalTopicConfig { boolean isCompacted() { return cleanupPolicies.contains(CleanupPolicy.compact); } InternalTopicConfig(final String name, final Set<CleanupPolicy> defaultCleanupPolicies, final Map<String, String> logConfig); Properties toProperties(final long additionalRetentionMs); String name(); void setRetentionMs(final long retentionMs); @Override boolean equals(final Object o); @Override int hashCode(); }### Answer: @Test public void shouldBeCompactedIfCleanupPolicyCompactOrCompactAndDelete() throws Exception { assertTrue(new InternalTopicConfig("name", Collections.singleton(InternalTopicConfig.CleanupPolicy.compact), Collections.<String, String>emptyMap()).isCompacted()); assertTrue(new InternalTopicConfig("name", Utils.mkSet(InternalTopicConfig.CleanupPolicy.compact, InternalTopicConfig.CleanupPolicy.delete), Collections.<String, String>emptyMap()).isCompacted()); } @Test public void shouldNotBeCompactedWhenCleanupPolicyIsDelete() throws Exception { assertFalse(new InternalTopicConfig("name", Collections.singleton(InternalTopicConfig.CleanupPolicy.delete), Collections.<String, String>emptyMap()).isCompacted()); }
### Question: StreamPartitionAssignor implements PartitionAssignor, Configurable { Cluster clusterMetadata() { if (metadataWithInternalTopics == null) { return Cluster.empty(); } return metadataWithInternalTopics; } @Override void configure(Map<String, ?> configs); @Override String name(); @Override Subscription subscription(Set<String> topics); @Override Map<String, Assignment> assign(Cluster metadata, Map<String, Subscription> subscriptions); @Override void onAssignment(Assignment assignment); void close(); final static int NOT_AVAILABLE; }### Answer: @Test public void shouldReturnEmptyClusterMetadataIfItHasntBeenBuilt() throws Exception { final Cluster cluster = partitionAssignor.clusterMetadata(); assertNotNull(cluster); }
### Question: ProcessorNode { public void init(ProcessorContext context) { this.context = context; try { nodeMetrics = new NodeMetrics(context.metrics(), name, "task." + context.taskId()); nodeMetrics.metrics.measureLatencyNs(time, initDelegate, nodeMetrics.nodeCreationSensor); } catch (Exception e) { throw new StreamsException(String.format("failed to initialize processor %s", name), e); } } ProcessorNode(String name); ProcessorNode(String name, Processor<K, V> processor, Set<String> stateStores); final String name(); final Processor<K, V> processor(); final List<ProcessorNode<?, ?>> children(); void addChild(ProcessorNode<?, ?> child); void init(ProcessorContext context); void close(); void process(final K key, final V value); void punctuate(long timestamp); @Override String toString(); String toString(String indent); final Set<String> stateStores; }### Answer: @SuppressWarnings("unchecked") @Test (expected = StreamsException.class) public void shouldThrowStreamsExceptionIfExceptionCaughtDuringInit() throws Exception { final ProcessorNode node = new ProcessorNode("name", new ExceptionalProcessor(), Collections.emptySet()); node.init(null); }
### Question: ProcessorNode { public void close() { try { nodeMetrics.metrics.measureLatencyNs(time, closeDelegate, nodeMetrics.nodeDestructionSensor); nodeMetrics.removeAllSensors(); } catch (Exception e) { throw new StreamsException(String.format("failed to close processor %s", name), e); } } ProcessorNode(String name); ProcessorNode(String name, Processor<K, V> processor, Set<String> stateStores); final String name(); final Processor<K, V> processor(); final List<ProcessorNode<?, ?>> children(); void addChild(ProcessorNode<?, ?> child); void init(ProcessorContext context); void close(); void process(final K key, final V value); void punctuate(long timestamp); @Override String toString(); String toString(String indent); final Set<String> stateStores; }### Answer: @SuppressWarnings("unchecked") @Test (expected = StreamsException.class) public void shouldThrowStreamsExceptionIfExceptionCaughtDuringClose() throws Exception { final ProcessorNode node = new ProcessorNode("name", new ExceptionalProcessor(), Collections.emptySet()); node.close(); }
### Question: SourceNode extends ProcessorNode<K, V> { K deserializeKey(String topic, Headers headers, byte[] data) { return keyDeserializer.deserialize(topic, headers, data); } SourceNode(String name, List<String> topics, TimestampExtractor timestampExtractor, Deserializer<K> keyDeserializer, Deserializer<V> valDeserializer); SourceNode(String name, List<String> topics, Deserializer<K> keyDeserializer, Deserializer<V> valDeserializer); @SuppressWarnings("unchecked") @Override void init(ProcessorContext context); @Override void process(final K key, final V value); @Override String toString(); String toString(String indent); TimestampExtractor getTimestampExtractor(); }### Answer: @Test public void shouldProvideTopicHeadersAndDataToKeyDeserializer() { final SourceNode<String, String> sourceNode = new MockSourceNode<>(new String[]{""}, new TheExtendedDeserializer(), new TheExtendedDeserializer()); final RecordHeaders headers = new RecordHeaders(); final String deserializeKey = sourceNode.deserializeKey("topic", headers, "data".getBytes(StandardCharsets.UTF_8)); assertThat(deserializeKey, is("topic" + headers + "data")); }
### Question: SourceNode extends ProcessorNode<K, V> { V deserializeValue(String topic, Headers headers, byte[] data) { return valDeserializer.deserialize(topic, headers, data); } SourceNode(String name, List<String> topics, TimestampExtractor timestampExtractor, Deserializer<K> keyDeserializer, Deserializer<V> valDeserializer); SourceNode(String name, List<String> topics, Deserializer<K> keyDeserializer, Deserializer<V> valDeserializer); @SuppressWarnings("unchecked") @Override void init(ProcessorContext context); @Override void process(final K key, final V value); @Override String toString(); String toString(String indent); TimestampExtractor getTimestampExtractor(); }### Answer: @Test public void shouldProvideTopicHeadersAndDataToValueDeserializer() { final SourceNode<String, String> sourceNode = new MockSourceNode<>(new String[]{""}, new TheExtendedDeserializer(), new TheExtendedDeserializer()); final RecordHeaders headers = new RecordHeaders(); final String deserializedValue = sourceNode.deserializeValue("topic", headers, "data".getBytes(StandardCharsets.UTF_8)); assertThat(deserializedValue, is("topic" + headers + "data")); }
### Question: ProcessorStateManager implements StateManager { @Override public StateStore getStore(final String name) { return stores.get(name); } ProcessorStateManager(final TaskId taskId, final Collection<TopicPartition> sources, final boolean isStandby, final StateDirectory stateDirectory, final Map<String, String> storeToChangelogTopic, final ChangelogReader changelogReader, final boolean eosEnabled); static String storeChangelogTopic(final String applicationId, final String storeName); @Override File baseDir(); @Override void register(final StateStore store, final boolean loggingEnabled, final StateRestoreCallback stateRestoreCallback); @Override Map<TopicPartition, Long> checkpointed(); @Override StateStore getStore(final String name); @Override void flush(); @Override void close(final Map<TopicPartition, Long> ackedOffsets); @Override void checkpoint(final Map<TopicPartition, Long> ackedOffsets); @Override StateStore getGlobalStore(final String name); static final String STATE_CHANGELOG_TOPIC_SUFFIX; }### Answer: @Test public void testGetStore() throws IOException { final MockStateStoreSupplier.MockStateStore mockStateStore = new MockStateStoreSupplier.MockStateStore(nonPersistentStoreName, false); final ProcessorStateManager stateMgr = new ProcessorStateManager( new TaskId(0, 1), noPartitions, false, stateDirectory, Collections.<String, String>emptyMap(), changelogReader, false); try { stateMgr.register(mockStateStore, true, mockStateStore.stateRestoreCallback); assertNull(stateMgr.getStore("noSuchStore")); assertEquals(mockStateStore, stateMgr.getStore(nonPersistentStoreName)); } finally { stateMgr.close(Collections.<TopicPartition, Long>emptyMap()); } }
### Question: MinTimestampTracker implements TimestampTracker<E> { public long get() { Stamped<E> stamped = ascendingSubsequence.peekFirst(); if (stamped == null) return lastKnownTime; else return stamped.timestamp; } void addElement(final Stamped<E> elem); void removeElement(final Stamped<E> elem); int size(); long get(); }### Answer: @Test public void shouldReturnNotKnownTimestampWhenNoRecordsEverAdded() throws Exception { assertThat(tracker.get(), equalTo(TimestampTracker.NOT_KNOWN)); }
### Question: MinTimestampTracker implements TimestampTracker<E> { public void removeElement(final Stamped<E> elem) { if (elem == null) { return; } if (ascendingSubsequence.peekFirst() == elem) { ascendingSubsequence.removeFirst(); } if (ascendingSubsequence.isEmpty()) { lastKnownTime = elem.timestamp; } } void addElement(final Stamped<E> elem); void removeElement(final Stamped<E> elem); int size(); long get(); }### Answer: @Test public void shouldIgnoreNullRecordOnRemove() throws Exception { tracker.removeElement(null); }
### Question: MinTimestampTracker implements TimestampTracker<E> { public void addElement(final Stamped<E> elem) { if (elem == null) throw new NullPointerException(); Stamped<E> maxElem = ascendingSubsequence.peekLast(); while (maxElem != null && maxElem.timestamp >= elem.timestamp) { ascendingSubsequence.removeLast(); maxElem = ascendingSubsequence.peekLast(); } ascendingSubsequence.offerLast(elem); } void addElement(final Stamped<E> elem); void removeElement(final Stamped<E> elem); int size(); long get(); }### Answer: @Test(expected = NullPointerException.class) public void shouldThrowNullPointerExceptionWhenTryingToAddNullElement() throws Exception { tracker.addElement(null); }
### Question: CarManufacturer { public Car manufactureCar(Specification spec) { Car car = carFactory.createCar(spec); entityManager.merge(car); return car; } Car manufactureCar(Specification spec); }### Answer: @Test public void test() { Specification spec = new Specification(); Car car = new Car(spec); when(entityManager.merge(any())).then(a -> a.getArgument(0)); when(carFactory.createCar(any())).thenReturn(car); assertThat(testObject.manufactureCar(spec)).isEqualTo(car); verify(carFactory).createCar(spec); verify(entityManager).merge(car); } @Test public void test() { Specification spec = new Specification(); Car car = new Car(spec); when(testObject.entityManager.merge(any())).then(a -> a.getArgument(0)); when(testObject.carFactory.createCar(any())).thenReturn(car); assertThat(testObject.manufactureCar(spec)).isEqualTo(car); verify(testObject.carFactory).createCar(spec); verify(testObject.entityManager).merge(car); }
### Question: Types { public static boolean isAssignable(Class<?> lhsType, Class<?> rhsType) { if (lhsType.isAssignableFrom(rhsType)) { return true; } return lhsType.isPrimitive() ? lhsType.equals(Primitives.unwrap(rhsType)) : lhsType.isAssignableFrom(Primitives.wrap(rhsType)); } private Types(); static boolean isAssignable(Class<?> lhsType, Class<?> rhsType); static boolean equals(Class<?> lhsType, Class<?> rhsType); }### Answer: @Test public void testIsAssignable() throws Exception { assertThat(Types.isAssignable(int.class, Integer.class), is(true)); assertThat(Types.isAssignable(Integer.class, Integer.class), is(true)); assertThat(Types.isAssignable(Integer.class, int.class), is(true)); assertThat(Types.isAssignable(int.class, int.class), is(true)); assertThat(Types.isAssignable(int.class, long.class), is(false)); assertThat(Types.isAssignable(Integer.class, Long.class), is(false)); assertThat(Types.isAssignable(A.class, B.class), is(true)); assertThat(Types.isAssignable(A.class, A.class), is(true)); assertThat(Types.isAssignable(B.class, B.class), is(true)); assertThat(Types.isAssignable(B.class, A.class), is(false)); }
### Question: Soundex implements StringEncoder { public int difference(final String s1, final String s2) throws EncoderException { return SoundexUtils.difference(this, s1, s2); } Soundex(); Soundex(final char[] mapping); Soundex(final String mapping); int difference(final String s1, final String s2); @Override Object encode(final Object obj); @Override String encode(final String str); @Deprecated int getMaxLength(); @Deprecated void setMaxLength(final int maxLength); String soundex(String str); static final String US_ENGLISH_MAPPING_STRING; static final Soundex US_ENGLISH; }### Answer: @Test public void testDifference() throws EncoderException { Assert.assertEquals(0, this.getStringEncoder().difference(null, null)); Assert.assertEquals(0, this.getStringEncoder().difference("", "")); Assert.assertEquals(0, this.getStringEncoder().difference(" ", " ")); Assert.assertEquals(4, this.getStringEncoder().difference("Smith", "Smythe")); Assert.assertEquals(2, this.getStringEncoder().difference("Ann", "Andrew")); Assert.assertEquals(1, this.getStringEncoder().difference("Margaret", "Andrew")); Assert.assertEquals(0, this.getStringEncoder().difference("Janet", "Margaret")); Assert.assertEquals(4, this.getStringEncoder().difference("Green", "Greene")); Assert.assertEquals(0, this.getStringEncoder().difference("Blotchet-Halls", "Greene")); Assert.assertEquals(4, this.getStringEncoder().difference("Smith", "Smythe")); Assert.assertEquals(4, this.getStringEncoder().difference("Smithers", "Smythers")); Assert.assertEquals(2, this.getStringEncoder().difference("Anothers", "Brothers")); }
### Question: Soundex implements StringEncoder { public Soundex() { this.soundexMapping = US_ENGLISH_MAPPING; } Soundex(); Soundex(final char[] mapping); Soundex(final String mapping); int difference(final String s1, final String s2); @Override Object encode(final Object obj); @Override String encode(final String str); @Deprecated int getMaxLength(); @Deprecated void setMaxLength(final int maxLength); String soundex(String str); static final String US_ENGLISH_MAPPING_STRING; static final Soundex US_ENGLISH; }### Answer: @Test public void testNewInstance() { Assert.assertEquals("W452", new Soundex().soundex("Williams")); } @Test public void testNewInstance2() { Assert.assertEquals("W452", new Soundex(Soundex.US_ENGLISH_MAPPING_STRING.toCharArray()).soundex("Williams")); } @Test public void testNewInstance3() { Assert.assertEquals("W452", new Soundex(Soundex.US_ENGLISH_MAPPING_STRING).soundex("Williams")); } @Test public void testUsEnglishStatic() { Assert.assertEquals("W452", Soundex.US_ENGLISH.soundex("Williams")); }
### Question: TransactionManager { public TransactionManager() { } TransactionManager(); TransactionManager(ConnectionSource connectionSource); void initialize(); T callInTransaction(final Callable<T> callable); T callInTransaction(String tableName, final Callable<T> callable); static T callInTransaction(final ConnectionSource connectionSource, final Callable<T> callable); static T callInTransaction(String tableName, final ConnectionSource connectionSource, final Callable<T> callable); static T callInTransaction(final DatabaseConnection connection, final DatabaseType databaseType, final Callable<T> callable); static T callInTransaction(final DatabaseConnection connection, boolean saved, final DatabaseType databaseType, final Callable<T> callable); void setConnectionSource(ConnectionSource connectionSource); }### Answer: @Test public void testTransactionManager() throws Exception { ConnectionSource connectionSource = createMock(ConnectionSource.class); DatabaseConnection conn = createMock(DatabaseConnection.class); expect(conn.isAutoCommitSupported()).andReturn(false); Savepoint savePoint = createMock(Savepoint.class); expect(savePoint.getSavepointName()).andReturn("name").anyTimes(); expect(conn.setSavePoint(isA(String.class))).andReturn(savePoint); conn.commit(savePoint); expect(connectionSource.getDatabaseType()).andReturn(databaseType); expect(connectionSource.getReadWriteConnection(null)).andReturn(conn); expect(connectionSource.saveSpecialConnection(conn)).andReturn(true); connectionSource.clearSpecialConnection(conn); connectionSource.releaseConnection(conn); replay(connectionSource, conn, savePoint); TransactionManager tm = new TransactionManager(connectionSource); tm.callInTransaction(new Callable<Void>() { @Override public Void call() { return null; } }); verify(connectionSource, conn, savePoint); }
### Question: TransactionManager { public void initialize() { if (connectionSource == null) { throw new IllegalStateException("dataSource was not set on " + getClass().getSimpleName()); } } TransactionManager(); TransactionManager(ConnectionSource connectionSource); void initialize(); T callInTransaction(final Callable<T> callable); T callInTransaction(String tableName, final Callable<T> callable); static T callInTransaction(final ConnectionSource connectionSource, final Callable<T> callable); static T callInTransaction(String tableName, final ConnectionSource connectionSource, final Callable<T> callable); static T callInTransaction(final DatabaseConnection connection, final DatabaseType databaseType, final Callable<T> callable); static T callInTransaction(final DatabaseConnection connection, boolean saved, final DatabaseType databaseType, final Callable<T> callable); void setConnectionSource(ConnectionSource connectionSource); }### Answer: @Test(expected = IllegalStateException.class) public void testTransactionManagerNoSet() { TransactionManager tm = new TransactionManager(); tm.initialize(); }
### Question: TransactionManager { private static void rollBack(DatabaseConnection connection, Savepoint savePoint) throws SQLException { String name = (savePoint == null ? null : savePoint.getSavepointName()); connection.rollback(savePoint); if (name == null) { logger.debug("rolled back savePoint transaction"); } else { logger.debug("rolled back savePoint transaction {}", name); } } TransactionManager(); TransactionManager(ConnectionSource connectionSource); void initialize(); T callInTransaction(final Callable<T> callable); T callInTransaction(String tableName, final Callable<T> callable); static T callInTransaction(final ConnectionSource connectionSource, final Callable<T> callable); static T callInTransaction(String tableName, final ConnectionSource connectionSource, final Callable<T> callable); static T callInTransaction(final DatabaseConnection connection, final DatabaseType databaseType, final Callable<T> callable); static T callInTransaction(final DatabaseConnection connection, boolean saved, final DatabaseType databaseType, final Callable<T> callable); void setConnectionSource(ConnectionSource connectionSource); }### Answer: @Test public void testRollBack() throws Exception { if (connectionSource == null) { return; } TransactionManager mgr = new TransactionManager(connectionSource); final Dao<Foo, Integer> fooDao = createDao(Foo.class, true); testTransactionManager(mgr, new RuntimeException("What!! I protest!!"), fooDao); }
### Question: TransactionManager { public <T> T callInTransaction(final Callable<T> callable) throws SQLException { return callInTransaction(connectionSource, callable); } TransactionManager(); TransactionManager(ConnectionSource connectionSource); void initialize(); T callInTransaction(final Callable<T> callable); T callInTransaction(String tableName, final Callable<T> callable); static T callInTransaction(final ConnectionSource connectionSource, final Callable<T> callable); static T callInTransaction(String tableName, final ConnectionSource connectionSource, final Callable<T> callable); static T callInTransaction(final DatabaseConnection connection, final DatabaseType databaseType, final Callable<T> callable); static T callInTransaction(final DatabaseConnection connection, boolean saved, final DatabaseType databaseType, final Callable<T> callable); void setConnectionSource(ConnectionSource connectionSource); }### Answer: @Test public void testTransactionWithinTransaction() throws Exception { if (connectionSource == null) { return; } final TransactionManager mgr = new TransactionManager(connectionSource); final Dao<Foo, Integer> dao = createDao(Foo.class, true); mgr.callInTransaction(new Callable<Void>() { @Override public Void call() throws Exception { testTransactionManager(mgr, null, dao); return null; } }); } @Test public void testTransactionWithinTransactionFails() throws Exception { if (connectionSource == null) { return; } final TransactionManager mgr = new TransactionManager(connectionSource); final Dao<Foo, Integer> dao = createDao(Foo.class, true); try { mgr.callInTransaction(new Callable<Void>() { @Override public Void call() throws Exception { dao.create(new Foo()); mgr.callInTransaction(new Callable<Void>() { @Override public Void call() throws Exception { dao.create(new Foo()); throw new SQLException("Exception ahoy!"); } }); return null; } }); fail("Should have thrown"); } catch (SQLException se) { } List<Foo> results = dao.queryForAll(); assertNotNull(results); assertEquals(0, results.size()); }
### Question: SqlExceptionUtil { public static SQLException create(String message, Throwable cause) { SQLException sqlException; if (cause instanceof SQLException) { sqlException = new SQLException(message, ((SQLException) cause).getSQLState()); } else { sqlException = new SQLException(message); } sqlException.initCause(cause); return sqlException; } private SqlExceptionUtil(); static SQLException create(String message, Throwable cause); }### Answer: @Test public void testException() { Throwable cause = new Throwable(); String msg = "hello"; SQLException e = SqlExceptionUtil.create(msg, cause); assertEquals(msg, e.getMessage()); assertEquals(cause, e.getCause()); } @Test public void testExceptionWithSQLException() { String sqlReason = "sql exception message"; String sqlState = "sql exception state"; Throwable cause = new SQLException(sqlReason, sqlState); String msg = "hello"; SQLException e = SqlExceptionUtil.create(msg, cause); assertEquals(msg, e.getMessage()); assertEquals(sqlState, e.getSQLState()); assertEquals(cause, e.getCause()); }
### Question: BaseDaoEnabled { public int create() throws SQLException { checkForDao(); @SuppressWarnings("unchecked") T t = (T) this; return dao.create(t); } int create(); int refresh(); int update(); int updateId(ID newId); int delete(); String objectToString(); ID extractId(); boolean objectsEqual(T other); void setDao(Dao<T, ID> dao); Dao<T, ID> getDao(); }### Answer: @Test public void testCreate() throws Exception { Dao<One, Integer> dao = createDao(One.class, true); One one = new One(); String stuff = "fewpfjewfew"; one.stuff = stuff; one.setDao(dao); assertEquals(1, one.create()); } @Test(expected = SQLException.class) public void testCreateNoDao() throws Exception { One one = new One(); String stuff = "fewpfjewfew"; one.stuff = stuff; one.create(); }
### Question: BaseDaoEnabled { public int update() throws SQLException { checkForDao(); @SuppressWarnings("unchecked") T t = (T) this; return dao.update(t); } int create(); int refresh(); int update(); int updateId(ID newId); int delete(); String objectToString(); ID extractId(); boolean objectsEqual(T other); void setDao(Dao<T, ID> dao); Dao<T, ID> getDao(); }### Answer: @Test public void testUpdate() throws Exception { Dao<One, Integer> dao = createDao(One.class, true); One one = new One(); String stuff1 = "fewpfjewfew"; one.stuff = stuff1; assertEquals(1, dao.create(one)); String stuff2 = "fjpfejpwewpfjewfew"; one.stuff = stuff2; assertEquals(1, one.update()); One one2 = dao.queryForId(one.id); assertEquals(stuff2, one2.stuff); }
### Question: BaseDaoEnabled { public int updateId(ID newId) throws SQLException { checkForDao(); @SuppressWarnings("unchecked") T t = (T) this; return dao.updateId(t, newId); } int create(); int refresh(); int update(); int updateId(ID newId); int delete(); String objectToString(); ID extractId(); boolean objectsEqual(T other); void setDao(Dao<T, ID> dao); Dao<T, ID> getDao(); }### Answer: @Test public void testUpdateId() throws Exception { Dao<One, Integer> dao = createDao(One.class, true); One one = new One(); String stuff1 = "fewpfjewfew"; one.stuff = stuff1; assertEquals(1, dao.create(one)); int id = one.id; assertNotNull(dao.queryForId(id)); assertEquals(1, one.updateId(id + 1)); assertNull(dao.queryForId(id)); assertNotNull(dao.queryForId(id + 1)); }
### Question: BaseDaoEnabled { public int delete() throws SQLException { checkForDao(); @SuppressWarnings("unchecked") T t = (T) this; return dao.delete(t); } int create(); int refresh(); int update(); int updateId(ID newId); int delete(); String objectToString(); ID extractId(); boolean objectsEqual(T other); void setDao(Dao<T, ID> dao); Dao<T, ID> getDao(); }### Answer: @Test public void testDelete() throws Exception { Dao<One, Integer> dao = createDao(One.class, true); One one = new One(); String stuff1 = "fewpfjewfew"; one.stuff = stuff1; assertEquals(1, dao.create(one)); assertNotNull(dao.queryForId(one.id)); assertEquals(1, one.delete()); assertNull(dao.queryForId(one.id)); }
### Question: BaseDaoEnabled { public String objectToString() { try { checkForDao(); } catch (SQLException e) { throw new IllegalArgumentException(e); } @SuppressWarnings("unchecked") T t = (T) this; return dao.objectToString(t); } int create(); int refresh(); int update(); int updateId(ID newId); int delete(); String objectToString(); ID extractId(); boolean objectsEqual(T other); void setDao(Dao<T, ID> dao); Dao<T, ID> getDao(); }### Answer: @Test(expected = IllegalArgumentException.class) public void testObjectEqualsNoDao() { One one = new One(); String stuff1 = "fewpfjewfew"; one.stuff = stuff1; one.objectToString(); }
### Question: BaseDaoEnabled { public ID extractId() throws SQLException { checkForDao(); @SuppressWarnings("unchecked") T t = (T) this; return dao.extractId(t); } int create(); int refresh(); int update(); int updateId(ID newId); int delete(); String objectToString(); ID extractId(); boolean objectsEqual(T other); void setDao(Dao<T, ID> dao); Dao<T, ID> getDao(); }### Answer: @Test public void testExtractId() throws Exception { Dao<One, Integer> dao = createDao(One.class, true); One one = new One(); String stuff1 = "fewpfjewfew"; one.stuff = stuff1; assertEquals(1, dao.create(one)); assertEquals(one.id, (int) one.extractId()); }
### Question: LocalLog implements Log { @Override public boolean isLevelEnabled(Level level) { return this.level.isEnabled(level); } LocalLog(String className); static void openLogFile(String logPath); @Override boolean isLevelEnabled(Level level); @Override void log(Level level, String msg); @Override void log(Level level, String msg, Throwable throwable); static final String LOCAL_LOG_LEVEL_PROPERTY; static final String LOCAL_LOG_FILE_PROPERTY; static final String LOCAL_LOG_PROPERTIES_FILE; }### Answer: @Test public void testLevelProperty() { Log log = new LocalLog("foo"); if (log.isLevelEnabled(Level.TRACE)) { return; } System.setProperty(LocalLog.LOCAL_LOG_LEVEL_PROPERTY, "TRACE"); try { log = new LocalLog("foo"); assertTrue(log.isLevelEnabled(Level.TRACE)); } finally { System.clearProperty(LocalLog.LOCAL_LOG_LEVEL_PROPERTY); } }
### Question: LocalLog implements Log { public static void openLogFile(String logPath) { if (logPath == null) { printStream = System.out; } else { try { printStream = new PrintStream(new File(logPath)); } catch (FileNotFoundException e) { throw new IllegalArgumentException("Log file " + logPath + " was not found", e); } } } LocalLog(String className); static void openLogFile(String logPath); @Override boolean isLevelEnabled(Level level); @Override void log(Level level, String msg); @Override void log(Level level, String msg, Throwable throwable); static final String LOCAL_LOG_LEVEL_PROPERTY; static final String LOCAL_LOG_FILE_PROPERTY; static final String LOCAL_LOG_PROPERTIES_FILE; }### Answer: @Test(expected = IllegalArgumentException.class) public void testInvalidFileProperty() { LocalLog.openLogFile("not-a-proper-directory-name-we-hope/foo.txt"); }
### Question: LocalLog implements Log { static List<PatternLevel> readLevelResourceFile(InputStream stream) { List<PatternLevel> levels = null; if (stream != null) { try { levels = configureClassLevels(stream); } catch (IOException e) { System.err.println( "IO exception reading the log properties file '" + LOCAL_LOG_PROPERTIES_FILE + "': " + e); } finally { IOUtils.closeQuietly(stream); } } return levels; } LocalLog(String className); static void openLogFile(String logPath); @Override boolean isLevelEnabled(Level level); @Override void log(Level level, String msg); @Override void log(Level level, String msg, Throwable throwable); static final String LOCAL_LOG_LEVEL_PROPERTY; static final String LOCAL_LOG_FILE_PROPERTY; static final String LOCAL_LOG_PROPERTIES_FILE; }### Answer: @Test public void testInvalidLevelsFile() { StringWriter stringWriter = new StringWriter(); stringWriter.write("x\n"); stringWriter.write("com\\.j256\\.ormlite\\.stmt\\.StatementExecutor = INVALID_LEVEL\n"); LocalLog.readLevelResourceFile(new ByteArrayInputStream(stringWriter.toString().getBytes())); } @Test public void testIoErrorsReadingLevelFile() { InputStream errorStream = new InputStream() { @Override public int read() throws IOException { throw new IOException("simulated exception"); } @Override public void close() throws IOException { throw new IOException("simulated exception"); } }; LocalLog.readLevelResourceFile(errorStream); } @Test public void testInputStreamNull() { LocalLog.readLevelResourceFile(null); }
### Question: LoggerFactory { public static Logger getLogger(Class<?> clazz) { return getLogger(clazz.getName()); } private LoggerFactory(); static Logger getLogger(Class<?> clazz); static Logger getLogger(String className); static String getSimpleClassName(String className); static final String LOG_TYPE_SYSTEM_PROPERTY; }### Answer: @Test public void testGetLoggerClass() { assertNotNull(LoggerFactory.getLogger(getClass())); } @Test public void testGetLoggerString() { assertNotNull(LoggerFactory.getLogger(getClass().getName())); }
### Question: LoggerFactory { public static String getSimpleClassName(String className) { String[] parts = className.split("\\."); if (parts.length <= 1) { return className; } else { return parts[parts.length - 1]; } } private LoggerFactory(); static Logger getLogger(Class<?> clazz); static Logger getLogger(String className); static String getSimpleClassName(String className); static final String LOG_TYPE_SYSTEM_PROPERTY; }### Answer: @Test public void testGetSimpleClassName() { String first = "foo"; String name = LoggerFactory.getSimpleClassName(first); assertEquals(first, name); String second = "bar"; String className = first + "." + second; name = LoggerFactory.getSimpleClassName(className); assertEquals(second, name); }
### Question: TableInfo { public TableInfo(ConnectionSource connectionSource, BaseDaoImpl<T, ID> baseDaoImpl, Class<T> dataClass) throws SQLException { this(connectionSource.getDatabaseType(), baseDaoImpl, DatabaseTableConfig.fromClass(connectionSource, dataClass)); } TableInfo(ConnectionSource connectionSource, BaseDaoImpl<T, ID> baseDaoImpl, Class<T> dataClass); TableInfo(DatabaseType databaseType, BaseDaoImpl<T, ID> baseDaoImpl, DatabaseTableConfig<T> tableConfig); Class<T> getDataClass(); String getTableName(); FieldType[] getFieldTypes(); FieldType getFieldTypeByColumnName(String columnName); FieldType getIdField(); Constructor<T> getConstructor(); String objectToString(T object); T createObject(); boolean isUpdatable(); boolean isForeignAutoCreate(); FieldType[] getForeignCollections(); boolean hasColumnName(String columnName); }### Answer: @Test(expected = IllegalArgumentException.class) public void testTableInfo() throws SQLException { new TableInfo<NoFieldAnnotations, Void>(connectionSource, null, NoFieldAnnotations.class); }
### Question: TableInfo { public String objectToString(T object) { StringBuilder sb = new StringBuilder(64); sb.append(object.getClass().getSimpleName()); for (FieldType fieldType : fieldTypes) { sb.append(' ').append(fieldType.getColumnName()).append('='); try { sb.append(fieldType.extractJavaFieldValue(object)); } catch (Exception e) { throw new IllegalStateException("Could not generate toString of field " + fieldType, e); } } return sb.toString(); } TableInfo(ConnectionSource connectionSource, BaseDaoImpl<T, ID> baseDaoImpl, Class<T> dataClass); TableInfo(DatabaseType databaseType, BaseDaoImpl<T, ID> baseDaoImpl, DatabaseTableConfig<T> tableConfig); Class<T> getDataClass(); String getTableName(); FieldType[] getFieldTypes(); FieldType getFieldTypeByColumnName(String columnName); FieldType getIdField(); Constructor<T> getConstructor(); String objectToString(T object); T createObject(); boolean isUpdatable(); boolean isForeignAutoCreate(); FieldType[] getForeignCollections(); boolean hasColumnName(String columnName); }### Answer: @Test public void testObjectToString() throws Exception { String id = "f11232oo"; Foo foo = new Foo(); foo.id = id; assertEquals(id, foo.id); TableInfo<Foo, String> tableInfo = new TableInfo<Foo, String>(connectionSource, null, Foo.class); assertTrue(tableInfo.objectToString(foo).contains(id)); }
### Question: TableInfo { public String getTableName() { return tableName; } TableInfo(ConnectionSource connectionSource, BaseDaoImpl<T, ID> baseDaoImpl, Class<T> dataClass); TableInfo(DatabaseType databaseType, BaseDaoImpl<T, ID> baseDaoImpl, DatabaseTableConfig<T> tableConfig); Class<T> getDataClass(); String getTableName(); FieldType[] getFieldTypes(); FieldType getFieldTypeByColumnName(String columnName); FieldType getIdField(); Constructor<T> getConstructor(); String objectToString(T object); T createObject(); boolean isUpdatable(); boolean isForeignAutoCreate(); FieldType[] getForeignCollections(); boolean hasColumnName(String columnName); }### Answer: @Test public void testNoTableNameInAnnotation() throws Exception { TableInfo<NoTableNameAnnotation, Void> tableInfo = new TableInfo<NoTableNameAnnotation, Void>(connectionSource, null, NoTableNameAnnotation.class); assertEquals(NoTableNameAnnotation.class.getSimpleName().toLowerCase(), tableInfo.getTableName()); }
### Question: TableInfo { public T createObject() throws SQLException { try { T instance; ObjectFactory<T> factory = null; if (baseDaoImpl != null) { factory = baseDaoImpl.getObjectFactory(); } if (factory == null) { instance = constructor.newInstance(); } else { instance = factory.createObject(constructor, baseDaoImpl.getDataClass()); } wireNewInstance(baseDaoImpl, instance); return instance; } catch (Exception e) { throw SqlExceptionUtil.create("Could not create object for " + constructor.getDeclaringClass(), e); } } TableInfo(ConnectionSource connectionSource, BaseDaoImpl<T, ID> baseDaoImpl, Class<T> dataClass); TableInfo(DatabaseType databaseType, BaseDaoImpl<T, ID> baseDaoImpl, DatabaseTableConfig<T> tableConfig); Class<T> getDataClass(); String getTableName(); FieldType[] getFieldTypes(); FieldType getFieldTypeByColumnName(String columnName); FieldType getIdField(); Constructor<T> getConstructor(); String objectToString(T object); T createObject(); boolean isUpdatable(); boolean isForeignAutoCreate(); FieldType[] getForeignCollections(); boolean hasColumnName(String columnName); }### Answer: @Test public void testConstruct() throws Exception { TableInfo<Foo, String> tableInfo = new TableInfo<Foo, String>(connectionSource, null, Foo.class); Foo foo = tableInfo.createObject(); assertNotNull(foo); }
### Question: TableInfo { public FieldType getFieldTypeByColumnName(String columnName) { if (fieldNameMap == null) { Map<String, FieldType> map = new HashMap<String, FieldType>(); for (FieldType fieldType : fieldTypes) { map.put(fieldType.getColumnName().toLowerCase(), fieldType); } fieldNameMap = map; } FieldType fieldType = fieldNameMap.get(columnName.toLowerCase()); if (fieldType != null) { return fieldType; } for (FieldType fieldType2 : fieldTypes) { if (fieldType2.getFieldName().equals(columnName)) { throw new IllegalArgumentException("You should use columnName '" + fieldType2.getColumnName() + "' for table " + tableName + " instead of fieldName '" + fieldType2.getFieldName() + "'"); } } throw new IllegalArgumentException("Unknown column name '" + columnName + "' in table " + tableName); } TableInfo(ConnectionSource connectionSource, BaseDaoImpl<T, ID> baseDaoImpl, Class<T> dataClass); TableInfo(DatabaseType databaseType, BaseDaoImpl<T, ID> baseDaoImpl, DatabaseTableConfig<T> tableConfig); Class<T> getDataClass(); String getTableName(); FieldType[] getFieldTypes(); FieldType getFieldTypeByColumnName(String columnName); FieldType getIdField(); Constructor<T> getConstructor(); String objectToString(T object); T createObject(); boolean isUpdatable(); boolean isForeignAutoCreate(); FieldType[] getForeignCollections(); boolean hasColumnName(String columnName); }### Answer: @Test public void testUnknownForeignField() throws Exception { TableInfo<Foreign, Void> tableInfo = new TableInfo<Foreign, Void>(connectionSource, null, Foreign.class); try { tableInfo.getFieldTypeByColumnName("foo"); fail("expected exception"); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().contains("'" + Foreign.FOREIGN_FIELD_NAME + "'")); assertTrue(e.getMessage().contains("'foo'")); } }
### Question: TableInfo { public boolean hasColumnName(String columnName) { for (FieldType fieldType : fieldTypes) { if (fieldType.getColumnName().equals(columnName)) { return true; } } return false; } TableInfo(ConnectionSource connectionSource, BaseDaoImpl<T, ID> baseDaoImpl, Class<T> dataClass); TableInfo(DatabaseType databaseType, BaseDaoImpl<T, ID> baseDaoImpl, DatabaseTableConfig<T> tableConfig); Class<T> getDataClass(); String getTableName(); FieldType[] getFieldTypes(); FieldType getFieldTypeByColumnName(String columnName); FieldType getIdField(); Constructor<T> getConstructor(); String objectToString(T object); T createObject(); boolean isUpdatable(); boolean isForeignAutoCreate(); FieldType[] getForeignCollections(); boolean hasColumnName(String columnName); }### Answer: @Test public void testHasColumnName() throws Exception { Dao<Foo, String> dao = createDao(Foo.class, true); TableInfo<Foo, String> tableInfo = ((BaseDaoImpl<Foo, String>) dao).getTableInfo(); assertTrue(tableInfo.hasColumnName(COLUMN_NAME)); assertFalse(tableInfo.hasColumnName("not this name")); }
### Question: DatabaseTableConfigLoader { public static <T> void write(BufferedWriter writer, DatabaseTableConfig<T> config) throws SQLException { try { writeConfig(writer, config); } catch (IOException e) { throw SqlExceptionUtil.create("Could not write config to writer", e); } } static List<DatabaseTableConfig<?>> loadDatabaseConfigFromReader(BufferedReader reader); static DatabaseTableConfig<T> fromReader(BufferedReader reader); static void write(BufferedWriter writer, DatabaseTableConfig<T> config); }### Answer: @Test public void testConfigFile() throws Exception { DatabaseTableConfig<NoFields> config = new DatabaseTableConfig<NoFields>(); StringBuilder body = new StringBuilder(); StringWriter writer = new StringWriter(); BufferedWriter buffer = new BufferedWriter(writer); Class<NoFields> clazz = NoFields.class; config.setDataClass(clazz); body.append("dataClass=").append(clazz.getName()).append(LINE_SEP); checkConfigOutput(config, body, writer, buffer, false); String tableName = "pojgefwpjoefwpjo"; config.setTableName(tableName); body.append("tableName=").append(tableName).append(LINE_SEP); checkConfigOutput(config, body, writer, buffer, false); DatabaseFieldConfig field1 = new DatabaseFieldConfig(); String columnName = "efjpowefpjoefw"; field1.setColumnName(columnName); config.setFieldConfigs(Arrays.asList(field1)); StringWriter fieldWriter = new StringWriter(); BufferedWriter fieldBuffer = new BufferedWriter(fieldWriter); DatabaseFieldConfigLoader.write(fieldBuffer, field1, tableName); fieldBuffer.flush(); body.append("# --table-fields-start--").append(LINE_SEP); body.append(fieldWriter.toString()); checkConfigOutput(config, body, writer, buffer, true); }
### Question: DatabaseTableConfig { public DatabaseTableConfig() { } DatabaseTableConfig(); DatabaseTableConfig(Class<T> dataClass, List<DatabaseFieldConfig> fieldConfigs); DatabaseTableConfig(Class<T> dataClass, String tableName, List<DatabaseFieldConfig> fieldConfigs); private DatabaseTableConfig(Class<T> dataClass, String tableName, FieldType[] fieldTypes); void initialize(); Class<T> getDataClass(); void setDataClass(Class<T> dataClass); String getTableName(); void setTableName(String tableName); void setFieldConfigs(List<DatabaseFieldConfig> fieldConfigs); void extractFieldTypes(ConnectionSource connectionSource); FieldType[] getFieldTypes(DatabaseType databaseType); List<DatabaseFieldConfig> getFieldConfigs(); Constructor<T> getConstructor(); void setConstructor(Constructor<T> constructor); static DatabaseTableConfig<T> fromClass(ConnectionSource connectionSource, Class<T> clazz); static String extractTableName(Class<T> clazz); static Constructor<T> findNoArgConstructor(Class<T> dataClass); }### Answer: @Test public void testDatabaseTableConfig() throws SQLException { DatabaseTableConfig<DatabaseTableAnno> dbTableConf = DatabaseTableConfig.fromClass(connectionSource, DatabaseTableAnno.class); assertEquals(DatabaseTableAnno.class, dbTableConf.getDataClass()); assertEquals(TABLE_NAME, dbTableConf.getTableName()); dbTableConf.extractFieldTypes(connectionSource); FieldType[] fieldTypes = dbTableConf.getFieldTypes(databaseType); assertEquals(1, fieldTypes.length); assertEquals("stuff", fieldTypes[0].getColumnName()); }
### Question: DatabaseTableConfig { public void initialize() { if (dataClass == null) { throw new IllegalStateException("dataClass was never set on " + getClass().getSimpleName()); } if (tableName == null) { tableName = extractTableName(dataClass); } } DatabaseTableConfig(); DatabaseTableConfig(Class<T> dataClass, List<DatabaseFieldConfig> fieldConfigs); DatabaseTableConfig(Class<T> dataClass, String tableName, List<DatabaseFieldConfig> fieldConfigs); private DatabaseTableConfig(Class<T> dataClass, String tableName, FieldType[] fieldTypes); void initialize(); Class<T> getDataClass(); void setDataClass(Class<T> dataClass); String getTableName(); void setTableName(String tableName); void setFieldConfigs(List<DatabaseFieldConfig> fieldConfigs); void extractFieldTypes(ConnectionSource connectionSource); FieldType[] getFieldTypes(DatabaseType databaseType); List<DatabaseFieldConfig> getFieldConfigs(); Constructor<T> getConstructor(); void setConstructor(Constructor<T> constructor); static DatabaseTableConfig<T> fromClass(ConnectionSource connectionSource, Class<T> clazz); static String extractTableName(Class<T> clazz); static Constructor<T> findNoArgConstructor(Class<T> dataClass); }### Answer: @Test(expected = IllegalStateException.class) public void testBadSpringWiring() { DatabaseTableConfig<NoFields> dbTableConf = new DatabaseTableConfig<NoFields>(); dbTableConf.initialize(); }
### Question: ConsoleLogger extends AbstractInternalLogger { @Override public void trace(String msg) { println(msg); } protected ConsoleLogger(String name); @Override boolean isTraceEnabled(); @Override void trace(String msg); @Override void trace(String format, Object arg); @Override void trace(String format, Object argA, Object argB); @Override void trace(String format, Object... arguments); @Override void trace(String msg, Throwable t); @Override boolean isDebugEnabled(); @Override void debug(String msg); @Override void debug(String format, Object arg); @Override void debug(String format, Object argA, Object argB); @Override void debug(String format, Object... arguments); @Override void debug(String msg, Throwable t); @Override boolean isInfoEnabled(); @Override void info(String msg); @Override void info(String format, Object arg); @Override void info(String format, Object argA, Object argB); @Override void info(String format, Object... arguments); @Override void info(String msg, Throwable t); @Override boolean isWarnEnabled(); @Override void warn(String msg); @Override void warn(String format, Object arg); @Override void warn(String format, Object... arguments); @Override void warn(String format, Object argA, Object argB); @Override void warn(String msg, Throwable t); @Override boolean isErrorEnabled(); @Override void error(String msg); @Override void error(String format, Object arg); @Override void error(String format, Object argA, Object argB); @Override void error(String format, Object... arguments); @Override void error(String msg, Throwable t); }### Answer: @Test public void testMsg() throws Exception { ConsoleLogger logger = new ConsoleLogger("org"); logger.trace("ok"); }
### Question: DatabaseTableConfig { public FieldType[] getFieldTypes(DatabaseType databaseType) throws SQLException { if (fieldTypes == null) { throw new SQLException("Field types have not been extracted in table config"); } return fieldTypes; } DatabaseTableConfig(); DatabaseTableConfig(Class<T> dataClass, List<DatabaseFieldConfig> fieldConfigs); DatabaseTableConfig(Class<T> dataClass, String tableName, List<DatabaseFieldConfig> fieldConfigs); private DatabaseTableConfig(Class<T> dataClass, String tableName, FieldType[] fieldTypes); void initialize(); Class<T> getDataClass(); void setDataClass(Class<T> dataClass); String getTableName(); void setTableName(String tableName); void setFieldConfigs(List<DatabaseFieldConfig> fieldConfigs); void extractFieldTypes(ConnectionSource connectionSource); FieldType[] getFieldTypes(DatabaseType databaseType); List<DatabaseFieldConfig> getFieldConfigs(); Constructor<T> getConstructor(); void setConstructor(Constructor<T> constructor); static DatabaseTableConfig<T> fromClass(ConnectionSource connectionSource, Class<T> clazz); static String extractTableName(Class<T> clazz); static Constructor<T> findNoArgConstructor(Class<T> dataClass); }### Answer: @Test(expected = SQLException.class) public void testNoFields() throws SQLException { new DatabaseTableConfig<DatabaseTableAnno>().getFieldTypes(databaseType); }
### Question: TableUtils { public static <T> int clearTable(ConnectionSource connectionSource, Class<T> dataClass) throws SQLException { String tableName = DatabaseTableConfig.extractTableName(dataClass); DatabaseType databaseType = connectionSource.getDatabaseType(); if (databaseType.isEntityNamesMustBeUpCase()) { tableName = databaseType.upCaseEntityName(tableName); } return clearTable(connectionSource, tableName); } private TableUtils(); static int createTable(ConnectionSource connectionSource, Class<T> dataClass); static int createTable(Dao<?, ?> dao); static int createTableIfNotExists(ConnectionSource connectionSource, Class<T> dataClass); static int createTable(ConnectionSource connectionSource, DatabaseTableConfig<T> tableConfig); static int createTableIfNotExists(ConnectionSource connectionSource, DatabaseTableConfig<T> tableConfig); static List<String> getCreateTableStatements(ConnectionSource connectionSource, Class<T> dataClass); static List<String> getCreateTableStatements(ConnectionSource connectionSource, DatabaseTableConfig<T> tableConfig); static int dropTable(ConnectionSource connectionSource, Class<T> dataClass, boolean ignoreErrors); static int dropTable(Dao<T, ID> dao, boolean ignoreErrors); static int dropTable(ConnectionSource connectionSource, DatabaseTableConfig<T> tableConfig, boolean ignoreErrors); static int clearTable(ConnectionSource connectionSource, Class<T> dataClass); static int clearTable(ConnectionSource connectionSource, DatabaseTableConfig<T> tableConfig); }### Answer: @Test public void testClearTable() throws Exception { Dao<LocalFoo, Integer> fooDao = createDao(LocalFoo.class, true); assertEquals(0, fooDao.countOf()); LocalFoo foo = new LocalFoo(); assertEquals(1, fooDao.create(foo)); assertEquals(1, fooDao.countOf()); TableUtils.clearTable(connectionSource, LocalFoo.class); assertEquals(0, fooDao.countOf()); }
### Question: TableUtils { public static <T> int createTableIfNotExists(ConnectionSource connectionSource, Class<T> dataClass) throws SQLException { Dao<T, ?> dao = DaoManager.createDao(connectionSource, dataClass); return doCreateTable(dao, true); } private TableUtils(); static int createTable(ConnectionSource connectionSource, Class<T> dataClass); static int createTable(Dao<?, ?> dao); static int createTableIfNotExists(ConnectionSource connectionSource, Class<T> dataClass); static int createTable(ConnectionSource connectionSource, DatabaseTableConfig<T> tableConfig); static int createTableIfNotExists(ConnectionSource connectionSource, DatabaseTableConfig<T> tableConfig); static List<String> getCreateTableStatements(ConnectionSource connectionSource, Class<T> dataClass); static List<String> getCreateTableStatements(ConnectionSource connectionSource, DatabaseTableConfig<T> tableConfig); static int dropTable(ConnectionSource connectionSource, Class<T> dataClass, boolean ignoreErrors); static int dropTable(Dao<T, ID> dao, boolean ignoreErrors); static int dropTable(ConnectionSource connectionSource, DatabaseTableConfig<T> tableConfig, boolean ignoreErrors); static int clearTable(ConnectionSource connectionSource, Class<T> dataClass); static int clearTable(ConnectionSource connectionSource, DatabaseTableConfig<T> tableConfig); }### Answer: @Test public void testCreateTableIfNotExists() throws Exception { dropTable(LocalFoo.class, true); Dao<LocalFoo, Integer> fooDao = createDao(LocalFoo.class, false); try { fooDao.countOf(); fail("Should have thrown an exception"); } catch (Exception e) { } TableUtils.createTableIfNotExists(connectionSource, LocalFoo.class); assertEquals(0, fooDao.countOf()); TableUtils.createTableIfNotExists(connectionSource, LocalFoo.class); assertEquals(0, fooDao.countOf()); }
### Question: BaseSqliteDatabaseType extends BaseDatabaseType { @Override protected void configureGeneratedId(String tableName, StringBuilder sb, FieldType fieldType, List<String> statementsBefore, List<String> statementsAfter, List<String> additionalArgs, List<String> queriesAfter) { if (fieldType.getSqlType() != SqlType.INTEGER && fieldType.getSqlType() != SqlType.LONG) { throw new IllegalArgumentException( "Sqlite requires that auto-increment generated-id be integer or long type"); } sb.append("PRIMARY KEY AUTOINCREMENT "); } @Override boolean isVarcharFieldWidthSupported(); @Override boolean isCreateTableReturnsZero(); @Override boolean isCreateIfNotExistsSupported(); @Override FieldConverter getFieldConverter(DataPersister dataPersister, FieldType fieldType); @Override void appendInsertNoColumns(StringBuilder sb); }### Answer: @Test(expected = IllegalArgumentException.class) public void testConfigureGeneratedIdNotInteger() throws Exception { Field field = Foo.class.getField("stringField"); FieldType fieldType = FieldType.createFieldType(connectionSource, "foo", field, Foo.class); OurSqliteDatabaseType dbType = new OurSqliteDatabaseType(); StringBuilder sb = new StringBuilder(); dbType.configureGeneratedId(null, sb, fieldType, new ArrayList<String>(), null, new ArrayList<String>(), new ArrayList<String>()); } @Test public void testConfigureGeneratedIdInteger() throws Exception { Field field = Foo.class.getField("val"); FieldType fieldType = FieldType.createFieldType(connectionSource, "foo", field, Foo.class); OurSqliteDatabaseType dbType = new OurSqliteDatabaseType(); StringBuilder sb = new StringBuilder(); dbType.configureGeneratedId(null, sb, fieldType, new ArrayList<String>(), null, new ArrayList<String>(), new ArrayList<String>()); assertTrue(sb.toString().contains("PRIMARY KEY AUTOINCREMENT")); }
### Question: BaseSqliteDatabaseType extends BaseDatabaseType { @Override public boolean isVarcharFieldWidthSupported() { return false; } @Override boolean isVarcharFieldWidthSupported(); @Override boolean isCreateTableReturnsZero(); @Override boolean isCreateIfNotExistsSupported(); @Override FieldConverter getFieldConverter(DataPersister dataPersister, FieldType fieldType); @Override void appendInsertNoColumns(StringBuilder sb); }### Answer: @Test public void testIsVarcharFieldWidthSupported() { assertFalse(new OurSqliteDatabaseType().isVarcharFieldWidthSupported()); }
### Question: BaseSqliteDatabaseType extends BaseDatabaseType { @Override public boolean isCreateTableReturnsZero() { return false; } @Override boolean isVarcharFieldWidthSupported(); @Override boolean isCreateTableReturnsZero(); @Override boolean isCreateIfNotExistsSupported(); @Override FieldConverter getFieldConverter(DataPersister dataPersister, FieldType fieldType); @Override void appendInsertNoColumns(StringBuilder sb); }### Answer: @Test public void testIsCreateTableReturnsZero() { assertFalse(new OurSqliteDatabaseType().isCreateTableReturnsZero()); }
### Question: BaseSqliteDatabaseType extends BaseDatabaseType { @Override protected boolean generatedIdSqlAtEnd() { return false; } @Override boolean isVarcharFieldWidthSupported(); @Override boolean isCreateTableReturnsZero(); @Override boolean isCreateIfNotExistsSupported(); @Override FieldConverter getFieldConverter(DataPersister dataPersister, FieldType fieldType); @Override void appendInsertNoColumns(StringBuilder sb); }### Answer: @Test public void testGeneratedIdSqlAtEnd() { assertFalse(new OurSqliteDatabaseType().generatedIdSqlAtEnd()); }
### Question: BaseSqliteDatabaseType extends BaseDatabaseType { @Override public boolean isCreateIfNotExistsSupported() { return true; } @Override boolean isVarcharFieldWidthSupported(); @Override boolean isCreateTableReturnsZero(); @Override boolean isCreateIfNotExistsSupported(); @Override FieldConverter getFieldConverter(DataPersister dataPersister, FieldType fieldType); @Override void appendInsertNoColumns(StringBuilder sb); }### Answer: @Test public void testIsCreateIfNotExistsSupported() { assertTrue(new OurSqliteDatabaseType().isCreateIfNotExistsSupported()); }
### Question: BaseSqliteDatabaseType extends BaseDatabaseType { @Override public FieldConverter getFieldConverter(DataPersister dataPersister, FieldType fieldType) { switch (dataPersister.getSqlType()) { case BOOLEAN : return booleanConverter; case BIG_DECIMAL : return BigDecimalStringType.getSingleton(); default : return super.getFieldConverter(dataPersister, fieldType); } } @Override boolean isVarcharFieldWidthSupported(); @Override boolean isCreateTableReturnsZero(); @Override boolean isCreateIfNotExistsSupported(); @Override FieldConverter getFieldConverter(DataPersister dataPersister, FieldType fieldType); @Override void appendInsertNoColumns(StringBuilder sb); }### Answer: @Test public void testGetFieldConverter() throws Exception { OurSqliteDatabaseType dbType = new OurSqliteDatabaseType(); assertEquals(Byte.valueOf((byte) 1), dbType.getFieldConverter(DataType.BOOLEAN.getDataPersister(), null) .parseDefaultString(null, "true")); } @Test public void testDefaultFieldConverter() { OurSqliteDatabaseType dbType = new OurSqliteDatabaseType(); assertSame(DataType.STRING.getDataPersister(), dbType.getFieldConverter(DataType.STRING.getDataPersister(), null)); }
### Question: DateLongType extends BaseDateType { @Override public Object parseDefaultString(FieldType fieldType, String defaultStr) throws SQLException { try { return Long.parseLong(defaultStr); } catch (NumberFormatException e) { throw SqlExceptionUtil.create("Problems with field " + fieldType + " parsing default date-long value: " + defaultStr, e); } } private DateLongType(); protected DateLongType(SqlType sqlType, Class<?>[] classes); static DateLongType getSingleton(); @Override Object parseDefaultString(FieldType fieldType, String defaultStr); @Override Object resultToSqlArg(FieldType fieldType, DatabaseResults results, int columnPos); @Override Object sqlArgToJava(FieldType fieldType, Object sqlArg, int columnPos); @Override Object javaToSqlArg(FieldType fieldType, Object obj); @Override boolean isEscapedValue(); @Override Class<?> getPrimaryClass(); }### Answer: @Test(expected = SQLException.class) public void testDateLongParseInvalid() throws Exception { FieldType fieldType = FieldType.createFieldType(connectionSource, TABLE_NAME, LocalDateLong.class.getDeclaredField(DATE_COLUMN), LocalDateLong.class); DataType.DATE_LONG.getDataPersister().parseDefaultString(fieldType, "not valid long number"); }
### Question: SerializableType extends BaseDataType { @Override public Object parseDefaultString(FieldType fieldType, String defaultStr) throws SQLException { throw new SQLException("Default values for serializable types are not supported"); } private SerializableType(); protected SerializableType(SqlType sqlType, Class<?>[] classes); static SerializableType getSingleton(); @Override Object parseDefaultString(FieldType fieldType, String defaultStr); @Override Object resultToSqlArg(FieldType fieldType, DatabaseResults results, int columnPos); @Override Object sqlArgToJava(FieldType fieldType, Object sqlArg, int columnPos); @Override Object javaToSqlArg(FieldType fieldType, Object obj); @Override boolean isValidForField(Field field); @Override boolean isStreamType(); @Override boolean isComparable(); @Override boolean isAppropriateId(); @Override boolean isArgumentHolderRequired(); @Override Object resultStringToJava(FieldType fieldType, String stringValue, int columnPos); @Override Class<?> getPrimaryClass(); }### Answer: @Test(expected = SQLException.class) public void testSerializableParseDefault() throws Exception { DataType.SERIALIZABLE.getDataPersister().parseDefaultString(null, null); }
### Question: DateTimeType extends BaseDataType { @Override public Object javaToSqlArg(FieldType fieldType, Object javaObject) throws SQLException { return extractMillis(javaObject); } private DateTimeType(); protected DateTimeType(SqlType sqlType, Class<?>[] classes); static DateTimeType getSingleton(); @Override String[] getAssociatedClassNames(); @Override Object javaToSqlArg(FieldType fieldType, Object javaObject); @Override Object parseDefaultString(FieldType fieldType, String defaultStr); @Override Object resultToSqlArg(FieldType fieldType, DatabaseResults results, int columnPos); @Override Object sqlArgToJava(FieldType fieldType, Object sqlArg, int columnPos); @Override boolean isEscapedValue(); @Override boolean isAppropriateId(); @Override Class<?> getPrimaryClass(); @Override boolean isValidForVersion(); @Override Object moveToNextValue(Object currentValue); }### Answer: @Test(expected = SQLException.class) public void testJavaToSqlArg() throws Exception { DateTimeType.getSingleton().javaToSqlArg(null, new Object()); }
### Question: DateTimeType extends BaseDataType { @Override public Object parseDefaultString(FieldType fieldType, String defaultStr) throws SQLException { try { return Long.parseLong(defaultStr); } catch (NumberFormatException e) { throw SqlExceptionUtil.create("Problems with field " + fieldType + " parsing default DateTime value: " + defaultStr, e); } } private DateTimeType(); protected DateTimeType(SqlType sqlType, Class<?>[] classes); static DateTimeType getSingleton(); @Override String[] getAssociatedClassNames(); @Override Object javaToSqlArg(FieldType fieldType, Object javaObject); @Override Object parseDefaultString(FieldType fieldType, String defaultStr); @Override Object resultToSqlArg(FieldType fieldType, DatabaseResults results, int columnPos); @Override Object sqlArgToJava(FieldType fieldType, Object sqlArg, int columnPos); @Override boolean isEscapedValue(); @Override boolean isAppropriateId(); @Override Class<?> getPrimaryClass(); @Override boolean isValidForVersion(); @Override Object moveToNextValue(Object currentValue); }### Answer: @Test public void testParseDefaultString() throws SQLException { Long value = 423424234234L; assertEquals(value, DateTimeType.getSingleton().parseDefaultString(null, value.toString())); }
### Question: DateTimeType extends BaseDataType { @Override public Object resultToSqlArg(FieldType fieldType, DatabaseResults results, int columnPos) throws SQLException { return results.getLong(columnPos); } private DateTimeType(); protected DateTimeType(SqlType sqlType, Class<?>[] classes); static DateTimeType getSingleton(); @Override String[] getAssociatedClassNames(); @Override Object javaToSqlArg(FieldType fieldType, Object javaObject); @Override Object parseDefaultString(FieldType fieldType, String defaultStr); @Override Object resultToSqlArg(FieldType fieldType, DatabaseResults results, int columnPos); @Override Object sqlArgToJava(FieldType fieldType, Object sqlArg, int columnPos); @Override boolean isEscapedValue(); @Override boolean isAppropriateId(); @Override Class<?> getPrimaryClass(); @Override boolean isValidForVersion(); @Override Object moveToNextValue(Object currentValue); }### Answer: @Test(expected = SQLException.class) public void testResultToSqlArg() throws Exception { DatabaseResults results = createMock(DatabaseResults.class); int col = 21; long value = 2094234324L; expect(results.getLong(col)).andReturn(value); replay(results); DateTimeType.getSingleton().resultToJava(null, results, col); }
### Question: DateType extends BaseDateType { @Override public Object parseDefaultString(FieldType fieldType, String defaultStr) throws SQLException { DateStringFormatConfig dateFormatConfig = convertDateStringConfig(fieldType, getDefaultDateFormatConfig()); try { return new Timestamp(parseDateString(dateFormatConfig, defaultStr).getTime()); } catch (ParseException e) { throw SqlExceptionUtil.create("Problems parsing default date string '" + defaultStr + "' using '" + dateFormatConfig + '\'', e); } } private DateType(); protected DateType(SqlType sqlType, Class<?>[] classes); static DateType getSingleton(); @Override Object parseDefaultString(FieldType fieldType, String defaultStr); @Override Object resultToSqlArg(FieldType fieldType, DatabaseResults results, int columnPos); @Override Object sqlArgToJava(FieldType fieldType, Object sqlArg, int columnPos); @Override Object javaToSqlArg(FieldType fieldType, Object javaObject); @Override boolean isArgumentHolderRequired(); }### Answer: @Test(expected = SQLException.class) public void testDateParseInvalid() throws Exception { FieldType fieldType = FieldType.createFieldType(connectionSource, TABLE_NAME, LocalDate.class.getDeclaredField(DATE_COLUMN), LocalDate.class); DataType.DATE.getDataPersister().parseDefaultString(fieldType, "not valid date string"); }
### Question: BindingParameter { public String getFullName() { return Strings.getFullName(parameterName, propertyPath); } BindingParameter(String parameterName, String propertyPath, JdbcType jdbcType); static BindingParameter create(String parameterName, String propertyPath, JdbcType jdbcType); BindingParameter rightShift(); String getParameterName(); String getPropertyPath(); JdbcType getJdbcType(); String getFullName(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void testGetFullName() throws Exception { BindingParameter bp = BindingParameter.create("a", "b", null); assertThat(bp.getFullName(), equalTo(":a.b")); bp = BindingParameter.create("a", "", null); assertThat(bp.getFullName(), equalTo(":a")); }
### Question: BindingParameter { @Override public boolean equals(Object obj) { if (obj == null) return false; if (getClass() != obj.getClass()) return false; final BindingParameter other = (BindingParameter) obj; return Objects.equal(this.getParameterName(), other.getParameterName()) && Objects.equal(this.getPropertyPath(), other.getPropertyPath()) && Objects.equal(this.getJdbcType(), other.getJdbcType()); } BindingParameter(String parameterName, String propertyPath, JdbcType jdbcType); static BindingParameter create(String parameterName, String propertyPath, JdbcType jdbcType); BindingParameter rightShift(); String getParameterName(); String getPropertyPath(); JdbcType getJdbcType(); String getFullName(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void testEquals() throws Exception { BindingParameter bp = BindingParameter.create("a", "b", null); BindingParameter bp2 = BindingParameter.create("a", "b", null); assertThat(bp.equals(bp2), equalTo(true)); assertThat(bp.equals(null), equalTo(false)); assertThat(bp.equals(new Object()), equalTo(false)); }
### Question: FunctionalBindingParameterInvoker implements BindingParameterInvoker { public static FunctionalBindingParameterInvoker create( Type originalType, BindingParameter bindingParameter) { try { FunctionalBindingParameterInvoker invokerGroup = new FunctionalBindingParameterInvoker(originalType, bindingParameter); return invokerGroup; } catch (UnreachablePropertyException e) { throw new BindingException("Parameter '" + bindingParameter + "' can't be readable", e); } } private FunctionalBindingParameterInvoker(Type originalType, BindingParameter bindingParameter); static FunctionalBindingParameterInvoker create( Type originalType, BindingParameter bindingParameter); @Override Type getTargetType(); @Override Object invoke(Object obj); @Override BindingParameter getBindingParameter(); }### Answer: @Test public void testBindingException4() throws Exception { thrown.expect(BindingException.class); thrown.expectMessage("Parameter ':user.userBag.ite' can't be readable; " + "caused by: There is no getter/setter for property named 'ite' in 'class org.jfaster.mango.binding.FunctionalBindingParameterInvokerTest$UserBag'"); FunctionalBindingParameterInvoker.create(User.class, BindingParameter.create("user", "userBag.ite", null)); }