Class TestUtils

java.lang.Object
org.apache.kafka.test.TestUtils

public class TestUtils extends Object
Helper functions for writing unit tests
  • Field Details

    • TEST_WITH_PARAMETERIZED_QUORUM_NAME

      public static final String 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

      public static final String TEST_WITH_PARAMETERIZED_QUORUM_NAME_AND_K2PROXY_ENABLED
      See Also:
    • TEST_WITH_PARAMETERIZED_HTTP2_MODE

      public static final String TEST_WITH_PARAMETERIZED_HTTP2_MODE
      See Also:
    • TEST_WITH_PARAMETERIZED_QUORUM_NAME_AND_HTTP2_MODE

      public static final String TEST_WITH_PARAMETERIZED_QUORUM_NAME_AND_HTTP2_MODE
      See Also:
    • TEST_WITH_PARAMETERIZED_QUORUM_NAME_SASL_MECHANISM

      public static final String TEST_WITH_PARAMETERIZED_QUORUM_NAME_SASL_MECHANISM
      See Also:
    • TEST_WITH_PARAMETERIZED_QUORUM_AND_API_VERSION_AND_HTTP2_MODE

      public static final String TEST_WITH_PARAMETERIZED_QUORUM_AND_API_VERSION_AND_HTTP2_MODE
      See Also:
    • IO_TMP_DIR

      public static final File IO_TMP_DIR
    • LETTERS

      public static final String LETTERS
      See Also:
    • DIGITS

      public static final String DIGITS
      See Also:
    • LETTERS_AND_DIGITS

      public static final String LETTERS_AND_DIGITS
      See Also:
    • SEEDED_RANDOM

      public static final Random SEEDED_RANDOM
    • RANDOM

      public static final 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

      public static org.apache.kafka.common.Cluster singletonCluster(String topic, int partitions)
    • clusterWith

      public static org.apache.kafka.common.Cluster clusterWith(int nodes)
    • clusterWith

      public static org.apache.kafka.common.Cluster clusterWith(int nodes, Map<String,Integer> topicPartitionCounts, Map<String, org.apache.kafka.common.Uuid> topicIds)
    • clusterWith

      public static org.apache.kafka.common.Cluster clusterWith(int nodes, Map<String,Integer> topicPartitionCounts)
    • clusterWith

      public static org.apache.kafka.common.Cluster clusterWith(int nodes, String topic, int partitions)
    • 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 cluster
      topicPartitionCounts - 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 the waitForCondition to 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

      public static String randomString(int len)
      Generate a random string of letters and digits of the given length
      Parameters:
      len - The length of the string
      Returns:
      The random string
    • randomSelect

      public static <T> T randomSelect(Collection<T> elements)
      Select a random element from collections
      Parameters:
      elements - A collection we can select
      Returns:
      A element from collection
    • tempFile

      public static File tempFile(String prefix, String suffix) throws IOException
      Create an empty file in the default temporary-file directory, using the given prefix and suffix to generate its name.
      Throws:
      IOException
    • tempFile

      public static File tempFile() throws IOException
      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

      public static File tempFile(String contents) throws IOException
      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

      public static File tempFile(String prefix, String suffix, String contents) throws IOException
      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

      public static void writeToFile(File file, String contents) throws IOException
      Throws:
      IOException
    • tempDirectory

      public static File tempDirectory(String prefix)
      Create a temporary relative directory in the default temporary-file directory with the given prefix.
      Parameters:
      prefix - The prefix of the temporary directory, if null using "kafka-" as default prefix
    • tempDirectory

      public static File tempDirectory()
      Create a temporary relative directory in the default temporary-file directory with a prefix of "kafka-"
      Returns:
      the temporary directory just created.
    • tempRelativeDir

      public static File tempRelativeDir(String root)
      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

      public static File tempDirectory(Path parent, String prefix)
      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 directory
      prefix - The prefix of the temporary directory, if null using "kafka-" as default prefix
    • getNewlyLeakedThreads

      public static List<Thread> getNewlyLeakedThreads(long waitTimeMs, Set<String> unexpectedThreadNames)
    • verifyNoUnexpectedThreads

      public static void verifyNoUnexpectedThreads() throws Exception
      Throws:
      Exception
    • randomPartitionLogDir

      public static File randomPartitionLogDir(File parentDir)
      Create a random log directory in the format - used for Kafka partition logs. It is the responsibility of the caller to set up a shutdown hook for deletion of the directory.
    • randomPartitionForTopicLogDir

      public static File randomPartitionForTopicLogDir(File parentDir, String topicName)
      Create a random log directory in the format - used for Kafka partition logs. It is the responsibility of the caller to set up a shutdown hook for deletion of the directory.
    • 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

      public static Properties 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 most maxWaitMs and throw assertion failure otherwise. This should be used instead of Thread.sleep whenever 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 most maxWaitMs and throw assertion failure otherwise. This should be used instead of Thread.sleep whenever 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 most maxWaitMs with a polling interval of pollIntervalMs and throw assertion failure otherwise. This should be used instead of Thread.sleep whenever 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 now Exceptions or AssertionErrors, 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 for runnable to complete successfully.
      runnable - the code to attempt to execute successfully.
      Throws:
      InterruptedException - if the current thread is interrupted while waiting for runnable to complete successfully.
    • retryOnExceptionWithTimeout

      public static void retryOnExceptionWithTimeout(ValuelessCallable runnable) throws InterruptedException
      Wait for the given runnable to complete successfully, i.e. throw now Exceptions or AssertionErrors, 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 for runnable to 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 now Exceptions or AssertionErrors, 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 for runnable to complete successfully.
      pollIntervalMs - the interval in milliseconds to wait between invoking runnable.
      runnable - the code to attempt to execute successfully.
      Throws:
      InterruptedException - if the current thread is interrupted while waiting for runnable to complete successfully.
    • isValidClusterId

      public static void isValidClusterId(String clusterId)
      Checks if a cluster id is valid.
      Parameters:
      clusterId -
    • checkEquals

      public static <T> void checkEquals(Iterable<T> it1, Iterable<T> it2)
      Checks the two iterables for equality by first converting both to a list.
    • checkEquals

      public static <T> void checkEquals(Iterator<T> it1, Iterator<T> it2)
    • checkEquals

      public static <T> void checkEquals(Set<T> c1, Set<T> c2, String firstDesc, String secondDesc)
    • toList

      public static <T> List<T> toList(Iterator<? extends T> iterator)
    • toList

      public static <T> List<T> toList(Iterable<? extends T> iterable)
    • 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 cause
      future - The future to await
      Returns:
      The caught exception cause
    • assertFutureThrows

      public static <T extends Throwable> void assertFutureThrows(Class<T> expectedCauseClassApiException, Future<?> future, String expectedMessage)
    • assertFutureThrowsException

      public static void assertFutureThrowsException(org.apache.kafka.common.errors.ApiException expectedException, Future<?> future)
    • assertFutureThrowsWithMessageContaining

      public static <T extends Throwable> void assertFutureThrowsWithMessageContaining(Class<T> expectedCauseClassApiException, Future<?> future, String expectedMessage)
    • apiKeyFrom

      public static org.apache.kafka.common.protocol.ApiKeys apiKeyFrom(org.apache.kafka.common.network.NetworkReceive networkReceive)
    • assertOptional

      public static <T> void assertOptional(Optional<T> optional, Consumer<T> assertion)
    • fieldValue

      public static <T> T fieldValue(Object o, Class<?> clazz, String fieldName)
    • setFieldValue

      public static void setFieldValue(Object obj, String fieldName, Object value) throws Exception
      Throws:
      Exception
    • setFieldValueInSuperClass

      public static void setFieldValueInSuperClass(Object obj, String fieldName, Object value) throws Exception
      Throws:
      Exception
    • setFieldValue

      public static void setFieldValue(Object obj, Class<?> clazz, String fieldName, Object value) throws Exception
      Throws:
      Exception
    • sameElementsWithOrder

      public static <T> boolean sameElementsWithOrder(Iterator<T> iterator1, Iterator<T> iterator2)
      Returns true if both iterators have same elements in the same order.
      Type Parameters:
      T - type of element in the iterators.
      Parameters:
      iterator1 - first iterator.
      iterator2 - second iterator.
    • sameElementsWithoutOrder

      public static <T> boolean sameElementsWithoutOrder(Iterator<T> iterator1, Iterator<T> iterator2)
      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

      public static double getMetricValue(org.apache.kafka.common.metrics.Metrics metrics, String attribute, Map<String,String> tags)
    • getIntMetricValue

      public static int getIntMetricValue(org.apache.kafka.common.metrics.Metrics metrics, String attribute)
    • getObjectMetricValue

      public static Object getObjectMetricValue(org.apache.kafka.common.metrics.Metrics metrics, String attribute)
    • getObjectMetricValue

      public static Object getObjectMetricValue(org.apache.kafka.common.metrics.Metrics metrics, String attribute, Map<String,String> tags)
    • getKafkaMetrics

      public static List<org.apache.kafka.common.metrics.KafkaMetric> getKafkaMetrics(org.apache.kafka.common.metrics.Metrics metrics, String attribute, Map<String,String> tags)
    • 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

      public static String toHexStringUpperCase(byte[] bytes)