Class TestUtils
java.lang.Object
org.apache.kafka.test.TestUtils
Helper functions for writing unit tests
-
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final Stringstatic final Stringstatic final Stringstatic final Stringstatic final Stringstatic final Stringstatic final Stringstatic final longstatic final longstatic final longstatic final Stringstatic final Filestatic final Stringstatic final Stringstatic final Randomstatic final Randomstatic final Stringstatic final Stringstatic final StringThe name to use for a test with a parameterized quorum.static final Stringstatic final Stringstatic final String -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionstatic org.apache.kafka.common.protocol.ApiKeysapiKeyFrom(org.apache.kafka.common.network.NetworkReceive networkReceive) static <T extends Throwable>
TassertFutureThrows(Class<T> exceptionCauseClass, Future<?> future) Assert that a future raises an expected exception cause type.static <T extends Throwable>
voidassertFutureThrows(Class<T> expectedCauseClassApiException, Future<?> future, String expectedMessage) static voidassertFutureThrowsException(org.apache.kafka.common.errors.ApiException expectedException, Future<?> future) static <T extends Throwable>
voidassertFutureThrowsWithMessageContaining(Class<T> expectedCauseClassApiException, Future<?> future, String expectedMessage) static voidassertNoLeakedThreadsWithNameAndDaemonStatus(String threadName, boolean isDaemon) Asserts that there are no leaked threads with a specified name prefix and daemon status.static <T> voidassertOptional(Optional<T> optional, Consumer<T> assertion) static <T> voidcheckEquals(Iterable<T> it1, Iterable<T> it2) Checks the two iterables for equality by first converting both to a list.static <T> voidcheckEquals(Iterator<T> it1, Iterator<T> it2) static <T> voidcheckEquals(Set<T> c1, Set<T> c2, String firstDesc, String secondDesc) static org.apache.kafka.common.ClusterclusterWith(int nodes) static org.apache.kafka.common.ClusterclusterWith(int nodes, String topic, int partitions) static org.apache.kafka.common.ClusterclusterWith(int nodes, Map<String, Integer> topicPartitionCounts) static org.apache.kafka.common.ClusterclusterWith(int nodes, Map<String, Integer> topicPartitionCounts, Map<String, org.apache.kafka.common.Uuid> topicIds) static org.apache.kafka.common.requests.ApiVersionsResponseconfluentCloudApiVersionsResponse(int throttleTimeMs, org.apache.kafka.common.message.ApiMessageType.ListenerType listenerType) static org.apache.kafka.common.requests.ApiVersionsResponseconfluentCloudApiVersionsResponse(org.apache.kafka.common.message.ApiMessageType.ListenerType listenerType) static PropertiesconsumerConfig(String bootstrapServers, Class<?> keyDeserializer, Class<?> valueDeserializer) returns consumer config with random UUID for the Group IDstatic PropertiesconsumerConfig(String bootstrapServers, String groupId, Class<?> keyDeserializer, Class<?> valueDeserializer) static PropertiesconsumerConfig(String bootstrapServers, String groupId, Class<?> keyDeserializer, Class<?> valueDeserializer, Properties additional) static org.apache.kafka.common.requests.ApiVersionsResponsecreateApiVersionsResponse(int throttleTimeMs, org.apache.kafka.common.message.ApiVersionsResponseData.ApiVersionCollection apiVersions) static org.apache.kafka.common.requests.ApiVersionsResponsecreateApiVersionsResponse(int throttleTimeMs, org.apache.kafka.common.message.ApiVersionsResponseData.ApiVersionCollection apiVersions, org.apache.kafka.common.feature.Features<org.apache.kafka.common.feature.SupportedVersionRange> latestSupportedFeatures, boolean zkMigrationEnabled) static org.apache.kafka.common.requests.ApiVersionsResponsedefaultApiVersionsResponse(int throttleTimeMs, org.apache.kafka.common.message.ApiMessageType.ListenerType listenerType, boolean enableUnstableLastVersion, org.apache.kafka.common.message.ApiMessageType.ApiVisibility apiVisibility) static org.apache.kafka.common.requests.ApiVersionsResponseerrorApiVersionsResponse(int throttleTimeMs, org.apache.kafka.common.protocol.Errors error, org.apache.kafka.common.message.ApiMessageType.ListenerType listenerType) static <T> TfieldValue(Object o, Class<?> clazz, String fieldName) static intgetIntMetricValue(org.apache.kafka.common.metrics.Metrics metrics, String attribute) static List<org.apache.kafka.common.metrics.KafkaMetric> getKafkaMetrics(org.apache.kafka.common.metrics.Metrics metrics, String attribute, Map<String, String> tags) static doublegetMetricValue(org.apache.kafka.common.metrics.Metrics metrics, String attribute) static doublegetMetricValue(org.apache.kafka.common.metrics.Metrics metrics, String attribute, Map<String, String> tags) getNewlyLeakedThreads(long waitTimeMs, Set<String> unexpectedThreadNames) static ObjectgetObjectMetricValue(org.apache.kafka.common.metrics.Metrics metrics, String attribute) static ObjectgetObjectMetricValue(org.apache.kafka.common.metrics.Metrics metrics, String attribute, Map<String, String> tags) static voidisValidClusterId(String clusterId) Checks if a cluster id is valid.static org.apache.kafka.clients.MetadataSnapshotmetadataSnapshotWith(int nodes) Test utility function to get MetadataSnapshot of cluster with configured, and 0 partitions.static org.apache.kafka.clients.MetadataSnapshotmetadataSnapshotWith(int nodes, Map<String, Integer> topicPartitionCounts) Test utility function to get MetadataSnapshot with configured nodes and partitions.static PropertiesproducerConfig(String bootstrapServers, Class<?> keySerializer, Class<?> valueSerializer) static PropertiesproducerConfig(String bootstrapServers, Class<?> keySerializer, Class<?> valueSerializer, Properties additional) static byte[]randomBytes(int size) Generate an array of random bytesstatic FilerandomPartitionForTopicLogDir(File parentDir, String topicName) Create a random log directory in the format- used for Kafka partition logs. static FilerandomPartitionLogDir(File parentDir) Create a random log directory in the format- used for Kafka partition logs. static <T> TrandomSelect(Collection<T> elements) Select a random element from collectionsstatic StringrandomString(int len) Generate a random string of letters and digits of the given lengthstatic voidreplaceLine(Path path, int lineToReplace, String replaceString) Replace a particular line in a file with the provided string value.static Propertiesstatic voidretryOnExceptionWithTimeout(long timeoutMs, long pollIntervalMs, ValuelessCallable runnable) Wait for the given runnable to complete successfully, i.e.static voidretryOnExceptionWithTimeout(long timeoutMs, ValuelessCallable runnable) Wait for the given runnable to complete successfully, i.e.static voidretryOnExceptionWithTimeout(ValuelessCallable runnable) Wait for the given runnable to complete successfully, i.e.static <T> booleansameElementsWithOrder(Iterator<T> iterator1, Iterator<T> iterator2) Returns true if both iterators have same elements in the same order.static <T> booleansameElementsWithoutOrder(Iterator<T> iterator1, Iterator<T> iterator2) Returns true if both the iterators have same set of elements irrespective of order and duplicates.static voidsetFieldValue(Object obj, Class<?> clazz, String fieldName, Object value) static voidsetFieldValue(Object obj, String fieldName, Object value) static voidsetFieldValueInSuperClass(Object obj, String fieldName, Object value) static org.apache.kafka.common.Clusterstatic org.apache.kafka.common.ClustersingletonCluster(String topic, int partitions) static FileCreate a temporary relative directory in the default temporary-file directory with a prefix of "kafka-"static FiletempDirectory(String prefix) Create a temporary relative directory in the default temporary-file directory with the given prefix.static FiletempDirectory(Path parent, String prefix) Create a temporary relative directory in the specified parent directory with the given prefix.static FiletempFile()Create an empty file in the default temporary-file directory, using `kafka` as the prefix and `tmp` as the suffix to generate its name.static FileCreate a file with the given contents in the default temporary-file directory, using `kafka` as the prefix and `tmp` as the suffix to generate its name.static FileCreate an empty file in the default temporary-file directory, using the given prefix and suffix to generate its name.static FileCreate a file with the given contents in the default temporary-file directory, using the given prefix and suffix to generate its namestatic FiletempRelativeDir(String root) Create a temporary directory under the given root directory.static StringtoHexStringUpperCase(byte[] bytes) static <T> List<T> static <T> List<T> static voidverifyEmptyFields(Object object, int levels, String... fieldsToIgnore) Verifies that all collections and maps in `object` are empty.static voidstatic voidwaitForCondition(TestCondition testCondition, long maxWaitMs, long pollIntervalMs, Supplier<String> conditionDetailsSupplier) Wait for condition to be met for at mostmaxWaitMswith a polling interval ofpollIntervalMsand throw assertion failure otherwise.static voidwaitForCondition(TestCondition testCondition, long maxWaitMs, String conditionDetails) Wait for condition to be met for at mostmaxWaitMsand throw assertion failure otherwise.static voidwaitForCondition(TestCondition testCondition, long maxWaitMs, Supplier<String> conditionDetailsSupplier) Wait for condition to be met for at mostmaxWaitMsand throw assertion failure otherwise.static voidwaitForCondition(TestCondition testCondition, String conditionDetails) uses default value of 15 seconds for timeoutstatic voidwaitForCondition(TestCondition testCondition, Supplier<String> conditionDetailsSupplier) uses default value of 15 seconds for timeoutstatic voidwriteToFile(File file, String contents)
-
Field Details
-
TEST_WITH_PARAMETERIZED_QUORUM_NAME
The name to use for a test with a parameterized quorum.- See Also:
-
TEST_WITH_PARAMETERIZED_QUORUM_NAME_AND_K2PROXY_ENABLED
- See Also:
-
TEST_WITH_PARAMETERIZED_HTTP2_MODE
- See Also:
-
TEST_WITH_PARAMETERIZED_QUORUM_NAME_AND_HTTP2_MODE
- See Also:
-
TEST_WITH_PARAMETERIZED_QUORUM_NAME_SASL_MECHANISM
- See Also:
-
TEST_WITH_PARAMETERIZED_QUORUM_AND_API_VERSION_AND_HTTP2_MODE
- See Also:
-
CLUSTER_LINK_TEST_WITH_PARAMETERIZED_QUORUM_NAME
- See Also:
-
CLUSTER_LINK_TEST_WITH_PARAMETERIZED_QUORUM_NAME_AND_HTTP2
- See Also:
-
CLUSTER_LINK_TEST_WITH_PARAMETERIZED_QUORUM_NAME_AND_CLUSTER_TYPE
- See Also:
-
CLUSTER_LINK_TEST_WITH_PARAMETERIZED_QUORUM_NAME_AND_CLUSTER_TYPE_AND_DEST_SKU
public static final String CLUSTER_LINK_TEST_WITH_PARAMETERIZED_QUORUM_NAME_AND_CLUSTER_TYPE_AND_DEST_SKU- See Also:
-
CLUSTER_LINK_TEST_WITH_PARAMETERIZED_QUORUM_NAME_AND_CLUSTER_TYPE_AND_K2PROXY
public static final String CLUSTER_LINK_TEST_WITH_PARAMETERIZED_QUORUM_NAME_AND_CLUSTER_TYPE_AND_K2PROXY- See Also:
-
CLUSTER_LINK_TEST_WITH_PARAMETERIZED_QUORUM_NAME_AND_REPLICATION_NAME
- See Also:
-
CLUSTER_LINK_TEST_WITH_PARAMETERIZED_QUORUM_NAME_AND_REPLICATION_NAME_AND_HTTP2
public static final String CLUSTER_LINK_TEST_WITH_PARAMETERIZED_QUORUM_NAME_AND_REPLICATION_NAME_AND_HTTP2- See Also:
-
IO_TMP_DIR
-
LETTERS
- See Also:
-
DIGITS
- See Also:
-
LETTERS_AND_DIGITS
- See Also:
-
SEEDED_RANDOM
-
RANDOM
-
DEFAULT_POLL_INTERVAL_MS
public static final long DEFAULT_POLL_INTERVAL_MS- See Also:
-
DEFAULT_MAX_WAIT_MS
public static final long DEFAULT_MAX_WAIT_MS- See Also:
-
DEFAULT_ECKU_MAX_WAIT_MS
public static final long DEFAULT_ECKU_MAX_WAIT_MS- See Also:
-
-
Constructor Details
-
TestUtils
public TestUtils()
-
-
Method Details
-
singletonCluster
public static org.apache.kafka.common.Cluster singletonCluster() -
singletonCluster
-
clusterWith
public static org.apache.kafka.common.Cluster clusterWith(int nodes) -
clusterWith
-
clusterWith
-
clusterWith
-
metadataSnapshotWith
public static org.apache.kafka.clients.MetadataSnapshot metadataSnapshotWith(int nodes, Map<String, Integer> topicPartitionCounts) Test utility function to get MetadataSnapshot with configured nodes and partitions.- Parameters:
nodes- number of nodes in the clustertopicPartitionCounts- map of topic -> # of partitions- Returns:
- a MetadataSnapshot with number of nodes, partitions as per the input.
-
assertNoLeakedThreadsWithNameAndDaemonStatus
public static void assertNoLeakedThreadsWithNameAndDaemonStatus(String threadName, boolean isDaemon) throws InterruptedException Asserts that there are no leaked threads with a specified name prefix and daemon status. This method checks all threads in the JVM, filters them by the provided thread name prefix and daemon status, and verifies that no matching threads are alive. Use thewaitForConditionto retry the check at a regular interval until either no matching threads are found or the timeout is exceeded. If any matching, alive threads are found after the timeout has elapsed, the assertion will fail.- Parameters:
threadName- The prefix of the thread names to check. Only threads whose names start with this prefix will be considered.isDaemon- The daemon status to check. Only threads with the specified daemon status (either true for daemon threads or false for non-daemon threads) will be considered.- Throws:
AssertionError- If any thread with the specified name prefix and daemon status are found after the timeout.InterruptedException
-
metadataSnapshotWith
public static org.apache.kafka.clients.MetadataSnapshot metadataSnapshotWith(int nodes) Test utility function to get MetadataSnapshot of cluster with configured, and 0 partitions.- Parameters:
nodes- number of nodes in the cluster.- Returns:
- a MetadataSnapshot of cluster with number of nodes in the input.
-
randomBytes
public static byte[] randomBytes(int size) Generate an array of random bytes- Parameters:
size- The size of the array
-
randomString
Generate a random string of letters and digits of the given length- Parameters:
len- The length of the string- Returns:
- The random string
-
randomSelect
Select a random element from collections- Parameters:
elements- A collection we can select- Returns:
- A element from collection
-
tempFile
Create an empty file in the default temporary-file directory, using the given prefix and suffix to generate its name.- Throws:
IOException
-
tempFile
Create an empty file in the default temporary-file directory, using `kafka` as the prefix and `tmp` as the suffix to generate its name.- Throws:
IOException
-
tempFile
Create a file with the given contents in the default temporary-file directory, using `kafka` as the prefix and `tmp` as the suffix to generate its name.- Throws:
IOException
-
tempFile
Create a file with the given contents in the default temporary-file directory, using the given prefix and suffix to generate its name- Throws:
IOException
-
writeToFile
- Throws:
IOException
-
tempDirectory
-
tempDirectory
Create a temporary relative directory in the default temporary-file directory with a prefix of "kafka-"- Returns:
- the temporary directory just created.
-
tempRelativeDir
Create a temporary directory under the given root directory. The root directory is removed on JVM exit if it doesn't already exist when this function is invoked.- Parameters:
root- path to create temporary directory under- Returns:
- the temporary directory created within
root
-
tempDirectory
Create a temporary relative directory in the specified parent directory with the given prefix.- Parameters:
parent- The parent folder path name, if null using the default temporary-file directoryprefix- The prefix of the temporary directory, if null using "kafka-" as default prefix
-
getNewlyLeakedThreads
-
verifyNoUnexpectedThreads
-
randomPartitionLogDir
-
randomPartitionForTopicLogDir
-
producerConfig
public static Properties producerConfig(String bootstrapServers, Class<?> keySerializer, Class<?> valueSerializer, Properties additional) -
producerConfig
public static Properties producerConfig(String bootstrapServers, Class<?> keySerializer, Class<?> valueSerializer) -
requiredConsumerConfig
-
consumerConfig
public static Properties consumerConfig(String bootstrapServers, String groupId, Class<?> keyDeserializer, Class<?> valueDeserializer, Properties additional) -
consumerConfig
public static Properties consumerConfig(String bootstrapServers, String groupId, Class<?> keyDeserializer, Class<?> valueDeserializer) -
consumerConfig
public static Properties consumerConfig(String bootstrapServers, Class<?> keyDeserializer, Class<?> valueDeserializer) returns consumer config with random UUID for the Group ID -
waitForCondition
public static void waitForCondition(TestCondition testCondition, String conditionDetails) throws InterruptedException uses default value of 15 seconds for timeout- Throws:
InterruptedException
-
waitForCondition
public static void waitForCondition(TestCondition testCondition, Supplier<String> conditionDetailsSupplier) throws InterruptedException uses default value of 15 seconds for timeout- Throws:
InterruptedException
-
waitForCondition
public static void waitForCondition(TestCondition testCondition, long maxWaitMs, String conditionDetails) throws InterruptedException Wait for condition to be met for at mostmaxWaitMsand throw assertion failure otherwise. This should be used instead ofThread.sleepwhenever possible as it allows a longer timeout to be used without unnecessarily increasing test time (as the condition is checked frequently). The longer timeout is needed to avoid transient failures due to slow or overloaded machines.- Throws:
InterruptedException
-
waitForCondition
public static void waitForCondition(TestCondition testCondition, long maxWaitMs, Supplier<String> conditionDetailsSupplier) throws InterruptedException Wait for condition to be met for at mostmaxWaitMsand throw assertion failure otherwise. This should be used instead ofThread.sleepwhenever possible as it allows a longer timeout to be used without unnecessarily increasing test time (as the condition is checked frequently). The longer timeout is needed to avoid transient failures due to slow or overloaded machines.- Throws:
InterruptedException
-
waitForCondition
public static void waitForCondition(TestCondition testCondition, long maxWaitMs, long pollIntervalMs, Supplier<String> conditionDetailsSupplier) throws InterruptedException Wait for condition to be met for at mostmaxWaitMswith a polling interval ofpollIntervalMsand throw assertion failure otherwise. This should be used instead ofThread.sleepwhenever possible as it allows a longer timeout to be used without unnecessarily increasing test time (as the condition is checked frequently). The longer timeout is needed to avoid transient failures due to slow or overloaded machines.- Throws:
InterruptedException
-
retryOnExceptionWithTimeout
public static void retryOnExceptionWithTimeout(long timeoutMs, ValuelessCallable runnable) throws InterruptedException Wait for the given runnable to complete successfully, i.e. throw nowExceptions orAssertionErrors, or for the given timeout to expire. If the timeout expires then the last exception or assertion failure will be thrown thus providing context for the failure.- Parameters:
timeoutMs- the total time in milliseconds to wait forrunnableto complete successfully.runnable- the code to attempt to execute successfully.- Throws:
InterruptedException- if the current thread is interrupted while waiting forrunnableto complete successfully.
-
retryOnExceptionWithTimeout
public static void retryOnExceptionWithTimeout(ValuelessCallable runnable) throws InterruptedException Wait for the given runnable to complete successfully, i.e. throw nowExceptions orAssertionErrors, or for the default timeout to expire. If the timeout expires then the last exception or assertion failure will be thrown thus providing context for the failure.- Parameters:
runnable- the code to attempt to execute successfully.- Throws:
InterruptedException- if the current thread is interrupted while waiting forrunnableto complete successfully.
-
retryOnExceptionWithTimeout
public static void retryOnExceptionWithTimeout(long timeoutMs, long pollIntervalMs, ValuelessCallable runnable) throws InterruptedException Wait for the given runnable to complete successfully, i.e. throw nowExceptions orAssertionErrors, or for the given timeout to expire. If the timeout expires then the last exception or assertion failure will be thrown thus providing context for the failure.- Parameters:
timeoutMs- the total time in milliseconds to wait forrunnableto complete successfully.pollIntervalMs- the interval in milliseconds to wait between invokingrunnable.runnable- the code to attempt to execute successfully.- Throws:
InterruptedException- if the current thread is interrupted while waiting forrunnableto complete successfully.
-
isValidClusterId
Checks if a cluster id is valid.- Parameters:
clusterId-
-
checkEquals
-
checkEquals
-
checkEquals
-
toList
-
toList
-
assertFutureThrows
public static <T extends Throwable> T assertFutureThrows(Class<T> exceptionCauseClass, Future<?> future) Assert that a future raises an expected exception cause type. This method will wait for the future to complete or timeout(15000 milliseconds).- Type Parameters:
T- Exception cause type parameter- Parameters:
exceptionCauseClass- Class of the expected exception causefuture- The future to await- Returns:
- The caught exception cause
-
assertFutureThrows
-
assertFutureThrowsException
public static void assertFutureThrowsException(org.apache.kafka.common.errors.ApiException expectedException, Future<?> future) -
assertFutureThrowsWithMessageContaining
-
apiKeyFrom
public static org.apache.kafka.common.protocol.ApiKeys apiKeyFrom(org.apache.kafka.common.network.NetworkReceive networkReceive) -
assertOptional
-
fieldValue
-
setFieldValue
-
setFieldValueInSuperClass
-
setFieldValue
-
sameElementsWithOrder
-
sameElementsWithoutOrder
Returns true if both the iterators have same set of elements irrespective of order and duplicates.- Type Parameters:
T- type of element in the iterators.- Parameters:
iterator1- first iterator.iterator2- second iterator.
-
confluentCloudApiVersionsResponse
public static org.apache.kafka.common.requests.ApiVersionsResponse confluentCloudApiVersionsResponse(org.apache.kafka.common.message.ApiMessageType.ListenerType listenerType) -
confluentCloudApiVersionsResponse
public static org.apache.kafka.common.requests.ApiVersionsResponse confluentCloudApiVersionsResponse(int throttleTimeMs, org.apache.kafka.common.message.ApiMessageType.ListenerType listenerType) -
defaultApiVersionsResponse
public static org.apache.kafka.common.requests.ApiVersionsResponse defaultApiVersionsResponse(int throttleTimeMs, org.apache.kafka.common.message.ApiMessageType.ListenerType listenerType, boolean enableUnstableLastVersion, org.apache.kafka.common.message.ApiMessageType.ApiVisibility apiVisibility) -
errorApiVersionsResponse
public static org.apache.kafka.common.requests.ApiVersionsResponse errorApiVersionsResponse(int throttleTimeMs, org.apache.kafka.common.protocol.Errors error, org.apache.kafka.common.message.ApiMessageType.ListenerType listenerType) -
createApiVersionsResponse
public static org.apache.kafka.common.requests.ApiVersionsResponse createApiVersionsResponse(int throttleTimeMs, org.apache.kafka.common.message.ApiVersionsResponseData.ApiVersionCollection apiVersions) -
createApiVersionsResponse
public static org.apache.kafka.common.requests.ApiVersionsResponse createApiVersionsResponse(int throttleTimeMs, org.apache.kafka.common.message.ApiVersionsResponseData.ApiVersionCollection apiVersions, org.apache.kafka.common.feature.Features<org.apache.kafka.common.feature.SupportedVersionRange> latestSupportedFeatures, boolean zkMigrationEnabled) -
getMetricValue
public static double getMetricValue(org.apache.kafka.common.metrics.Metrics metrics, String attribute) -
getMetricValue
-
getIntMetricValue
public static int getIntMetricValue(org.apache.kafka.common.metrics.Metrics metrics, String attribute) -
getObjectMetricValue
-
getObjectMetricValue
-
getKafkaMetrics
-
verifyEmptyFields
public static void verifyEmptyFields(Object object, int levels, String... fieldsToIgnore) throws Exception Verifies that all collections and maps in `object` are empty. If levels > 1, also verifies entries of objects in fields of `object` recursively.- Parameters:
object- Object to verify.levels- Levels of fields to verify, 1 represents fields of `object`, 2 represents fields of fields of `object` and so on.fieldsToIgnore- Names of fields that are ignored (at all levels).- Throws:
Exception
-
replaceLine
public static void replaceLine(Path path, int lineToReplace, String replaceString) throws IOException Replace a particular line in a file with the provided string value.- Parameters:
path- path of the file.lineToReplace- line number to replace , line numbers are zero indexed.replaceString- the string to replace the line with.- Throws:
IOException
-
toHexStringUpperCase
-