package de.juplo.kafka;
+import com.mongodb.client.MongoClient;
import lombok.extern.slf4j.Slf4j;
-import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.utils.Bytes;
import org.junit.jupiter.api.*;
import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
+import org.springframework.boot.autoconfigure.kafka.KafkaProperties;
+import org.springframework.boot.autoconfigure.mongo.MongoProperties;
+import org.springframework.boot.test.autoconfigure.data.mongo.AutoConfigureDataMongo;
import org.springframework.boot.test.context.ConfigDataApplicationContextInitializer;
import org.springframework.boot.test.context.TestConfiguration;
+import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
+import org.springframework.kafka.config.KafkaListenerEndpointRegistry;
+import org.springframework.kafka.core.ConsumerFactory;
import org.springframework.kafka.test.context.EmbeddedKafka;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
import java.time.Duration;
import java.util.*;
-import java.util.concurrent.ExecutorService;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.stream.Collectors;
@SpringJUnitConfig(initializers = ConfigDataApplicationContextInitializer.class)
@TestPropertySource(
properties = {
- "consumer.bootstrap-server=${spring.embedded.kafka.brokers}",
- "consumer.topic=" + TOPIC,
- "consumer.commit-interval=1s" })
+ "spring.kafka.bootstrap-servers=${spring.embedded.kafka.brokers}",
+ "sumup.adder.topic=" + TOPIC,
+ "spring.kafka.consumer.auto-commit-interval=500ms",
+ "spring.mongodb.embedded.version=4.4.13" })
@EmbeddedKafka(topics = TOPIC, partitions = PARTITIONS)
+@EnableAutoConfiguration
+@AutoConfigureDataMongo
@Slf4j
abstract class GenericApplicationTests<K, V>
{
@Autowired
- KafkaConsumer<K, V> kafkaConsumer;
+ org.apache.kafka.clients.consumer.Consumer<K, V> kafkaConsumer;
@Autowired
- Consumer<ConsumerRecord<K, V>> consumer;
+ KafkaProperties kafkaProperties;
@Autowired
- ApplicationProperties properties;
+ ApplicationProperties applicationProperties;
@Autowired
- ExecutorService executor;
+ MongoClient mongoClient;
+ @Autowired
+ MongoProperties mongoProperties;
+ @Autowired
+ KafkaListenerEndpointRegistry kafkaListenerEndpointRegistry;
+ @Autowired
+ TestRecordHandler recordHandler;
+ @Autowired
+ EndlessConsumer endlessConsumer;
KafkaProducer<Bytes, Bytes> testRecordProducer;
KafkaConsumer<Bytes, Bytes> offsetConsumer;
- EndlessConsumer<K, V> endlessConsumer;
Map<TopicPartition, Long> oldOffsets;
- Map<TopicPartition, Long> newOffsets;
- Set<ConsumerRecord<K, V>> receivedRecords;
final RecordGenerator recordGenerator;
/** Tests methods */
@Test
- void commitsCurrentOffsetsOnSuccess()
+ void commitsCurrentOffsetsOnSuccess() throws Exception
{
int numberOfGeneratedMessages =
recordGenerator.generate(false, false, messageSender);
await(numberOfGeneratedMessages + " records received")
.atMost(Duration.ofSeconds(30))
.pollInterval(Duration.ofSeconds(1))
- .until(() -> receivedRecords.size() >= numberOfGeneratedMessages);
+ .until(() -> recordHandler.receivedMessages >= numberOfGeneratedMessages);
await("Offsets committed")
.atMost(Duration.ofSeconds(10))
.untilAsserted(() ->
{
checkSeenOffsetsForProgress();
- compareToCommitedOffsets(newOffsets);
+ assertSeenOffsetsEqualCommittedOffsets(recordHandler.seenOffsets);
});
- assertThatExceptionOfType(IllegalStateException.class)
- .isThrownBy(() -> endlessConsumer.exitStatus())
- .describedAs("Consumer should still be running");
+ assertThat(endlessConsumer.running())
+ .describedAs("Consumer should still be running")
+ .isTrue();
+ endlessConsumer.stop();
recordGenerator.assertBusinessLogic();
}
.until(() -> !endlessConsumer.running());
checkSeenOffsetsForProgress();
- compareToCommitedOffsets(newOffsets);
+ assertSeenOffsetsEqualCommittedOffsets(recordHandler.seenOffsets);
endlessConsumer.start();
await("Consumer failed")
.until(() -> !endlessConsumer.running());
checkSeenOffsetsForProgress();
- compareToCommitedOffsets(newOffsets);
- assertThat(receivedRecords.size())
+ assertSeenOffsetsEqualCommittedOffsets(recordHandler.seenOffsets);
+ assertThat(recordHandler.receivedMessages)
.describedAs("Received not all sent events")
.isLessThan(numberOfGeneratedMessages);
- assertThatNoException()
- .describedAs("Consumer should not be running")
- .isThrownBy(() -> endlessConsumer.exitStatus());
- assertThat(endlessConsumer.exitStatus())
- .describedAs("Consumer should have exited abnormally")
- .containsInstanceOf(RecordDeserializationException.class);
+ assertThat(endlessConsumer.running())
+ .describedAs("Consumer should have exited")
+ .isFalse();
recordGenerator.assertBusinessLogic();
}
@Test
@SkipWhenErrorCannotBeGenerated(logicError = true)
- void doesNotCommitOffsetsOnLogicError()
+ void commitsOffsetsOfUnseenRecordsOnLogicError()
{
int numberOfGeneratedMessages =
recordGenerator.generate(false, true, messageSender);
.until(() -> !endlessConsumer.running());
checkSeenOffsetsForProgress();
- compareToCommitedOffsets(oldOffsets);
+ assertSeenOffsetsEqualCommittedOffsets(recordHandler.seenOffsets);
endlessConsumer.start();
await("Consumer failed")
.pollInterval(Duration.ofSeconds(1))
.until(() -> !endlessConsumer.running());
- checkSeenOffsetsForProgress();
- compareToCommitedOffsets(oldOffsets);
- assertThat(receivedRecords.size())
- .describedAs("Received not all sent events")
- .isLessThan(numberOfGeneratedMessages);
+ assertSeenOffsetsEqualCommittedOffsets(recordHandler.seenOffsets);
- assertThatNoException()
+ assertThat(endlessConsumer.running())
.describedAs("Consumer should not be running")
- .isThrownBy(() -> endlessConsumer.exitStatus());
- assertThat(endlessConsumer.exitStatus())
- .describedAs("Consumer should have exited abnormally")
- .containsInstanceOf(RuntimeException.class);
+ .isFalse();
recordGenerator.assertBusinessLogic();
}
/** Helper methods for the verification of expectations */
- void compareToCommitedOffsets(Map<TopicPartition, Long> offsetsToCheck)
+ void assertSeenOffsetsEqualCommittedOffsets(Map<TopicPartition, Long> offsetsToCheck)
{
doForCurrentOffsets((tp, offset) ->
{
Long expected = offsetsToCheck.get(tp) + 1;
- log.debug("Checking, if the offset for {} is {}", tp, expected);
+ log.debug("Checking, if the offset {} for {} is exactly {}", offset, tp, expected);
assertThat(offset)
.describedAs("Committed offset corresponds to the offset of the consumer")
.isEqualTo(expected);
});
}
+ void assertSeenOffsetsAreBehindCommittedOffsets(Map<TopicPartition, Long> offsetsToCheck)
+ {
+ List<Boolean> isOffsetBehindSeen = new LinkedList<>();
+
+ doForCurrentOffsets((tp, offset) ->
+ {
+ Long expected = offsetsToCheck.get(tp) + 1;
+ log.debug("Checking, if the offset {} for {} is at most {}", offset, tp, expected);
+ assertThat(offset)
+ .describedAs("Committed offset must be at most equal to the offset of the consumer")
+ .isLessThanOrEqualTo(expected);
+ isOffsetBehindSeen.add(offset < expected);
+ });
+
+ assertThat(isOffsetBehindSeen.stream().reduce(false, (result, next) -> result | next))
+ .describedAs("Committed offsets are behind seen offsets")
+ .isTrue();
+ }
+
void checkSeenOffsetsForProgress()
{
// Be sure, that some messages were consumed...!
partitions().forEach(tp ->
{
Long oldOffset = oldOffsets.get(tp) + 1;
- Long newOffset = newOffsets.get(tp) + 1;
+ Long newOffset = recordHandler.seenOffsets.get(tp) + 1;
if (!oldOffset.equals(newOffset))
{
log.debug("Progress for {}: {} -> {}", tp, oldOffset, newOffset);
{
Properties props;
props = new Properties();
- props.put("bootstrap.servers", properties.getBootstrapServer());
+ props.put("bootstrap.servers", kafkaProperties.getBootstrapServers());
props.put("linger.ms", 100);
props.put("key.serializer", BytesSerializer.class.getName());
props.put("value.serializer", BytesSerializer.class.getName());
testRecordProducer = new KafkaProducer<>(props);
props = new Properties();
- props.put("bootstrap.servers", properties.getBootstrapServer());
+ props.put("bootstrap.servers", kafkaProperties.getBootstrapServers());
props.put("client.id", "OFFSET-CONSUMER");
- props.put("group.id", properties.getGroupId());
+ props.put("group.id", kafkaProperties.getConsumer().getGroupId());
props.put("key.deserializer", BytesDeserializer.class.getName());
props.put("value.deserializer", BytesDeserializer.class.getName());
offsetConsumer = new KafkaConsumer<>(props);
+ mongoClient.getDatabase(mongoProperties.getDatabase()).drop();
seekToEnd();
oldOffsets = new HashMap<>();
- newOffsets = new HashMap<>();
- receivedRecords = new HashSet<>();
+ recordHandler.seenOffsets = new HashMap<>();
+ recordHandler.receivedMessages = 0;
doForCurrentOffsets((tp, offset) ->
{
oldOffsets.put(tp, offset - 1);
- newOffsets.put(tp, offset - 1);
+ recordHandler.seenOffsets.put(tp, offset - 1);
});
- Consumer<ConsumerRecord<K, V>> captureOffsetAndExecuteTestHandler =
- record ->
- {
- newOffsets.put(
- new TopicPartition(record.topic(), record.partition()),
- record.offset());
- receivedRecords.add(record);
- consumer.accept(record);
- };
-
- endlessConsumer =
- new EndlessConsumer<>(
- executor,
- properties.getClientId(),
- properties.getTopic(),
- kafkaConsumer,
- captureOffsetAndExecuteTestHandler);
-
endlessConsumer.start();
}
try
{
endlessConsumer.stop();
+ }
+ catch (Exception e)
+ {
+ log.debug("{}", e.toString());
+ }
+
+ try
+ {
testRecordProducer.close();
offsetConsumer.close();
}
@Import(ApplicationConfiguration.class)
public static class Configuration
{
+ @Bean
+ public RecordHandler recordHandler(RecordHandler applicationRecordHandler)
+ {
+ return new TestRecordHandler(applicationRecordHandler);
+ }
+
+ @Bean(destroyMethod = "close")
+ public org.apache.kafka.clients.consumer.Consumer<String, Message> kafkaConsumer(ConsumerFactory<String, Message> factory)
+ {
+ return factory.createConsumer();
+ }
}
}