philipnee commented on code in PR #14364:
URL: https://github.com/apache/kafka/pull/14364#discussion_r1346463825


##########
clients/src/test/java/org/apache/kafka/clients/consumer/internals/HeartbeatRequestManagerTest.java:
##########
@@ -0,0 +1,346 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.kafka.clients.consumer.internals;
+
+import org.apache.kafka.clients.ClientResponse;
+import org.apache.kafka.clients.consumer.ConsumerConfig;
+import org.apache.kafka.common.Node;
+import org.apache.kafka.common.Uuid;
+import org.apache.kafka.common.errors.TimeoutException;
+import org.apache.kafka.common.message.ConsumerGroupHeartbeatResponseData;
+import org.apache.kafka.common.protocol.ApiKeys;
+import org.apache.kafka.common.protocol.Errors;
+import org.apache.kafka.common.requests.ConsumerGroupHeartbeatResponse;
+import org.apache.kafka.common.requests.RequestHeader;
+import org.apache.kafka.common.serialization.StringDeserializer;
+import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.common.utils.MockTime;
+import org.apache.kafka.common.utils.Time;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Optional;
+import java.util.Properties;
+
+import static 
org.apache.kafka.clients.consumer.ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG;
+import static 
org.apache.kafka.clients.consumer.ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG;
+import static 
org.apache.kafka.clients.consumer.ConsumerConfig.RETRY_BACKOFF_MS_CONFIG;
+import static 
org.apache.kafka.clients.consumer.ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG;
+import static org.apache.kafka.clients.consumer.internals.MemberState.FAILED;
+import static org.apache.kafka.clients.consumer.internals.MemberState.STABLE;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+public class HeartbeatRequestManagerTest {
+
+    private final int heartbeatIntervalMs = 1000;
+    private final long retryBackoffMaxMs = 3000;
+    private final long retryBackoffMs = 100;
+    private final String groupId = "group-id";
+
+    private Time mockTime;
+    private LogContext mockLogContext;
+    private CoordinatorRequestManager mockCoordinatorRequestManager;
+    private SubscriptionState mockSubscriptionState;
+    private HeartbeatRequestManager heartbeatRequestManager;
+    private MembershipManager mockMembershipManager;
+    private HeartbeatRequestManager.HeartbeatRequestState 
heartbeatRequestState;
+    private ConsumerConfig config;
+
+    private String memberId = "member-id";
+    private int memberEpoch = 1;
+    private ErrorEventHandler errorEventHandler;
+
+    private ConsumerGroupHeartbeatResponseData.Assignment mockAssignment() {
+        return new ConsumerGroupHeartbeatResponseData.Assignment()
+            .setAssignedTopicPartitions(Arrays.asList(
+                new ConsumerGroupHeartbeatResponseData.TopicPartitions()
+                    .setTopicId(Uuid.randomUuid())
+                    .setPartitions(Arrays.asList(0, 1, 2)),
+                new ConsumerGroupHeartbeatResponseData.TopicPartitions()
+                    .setTopicId(Uuid.randomUuid())
+                    .setPartitions(Arrays.asList(3, 4, 5))
+            ));
+    }
+
+    @BeforeEach
+    public void setUp() {
+        mockTime = new MockTime();
+        mockLogContext = new LogContext();
+        Properties properties = new Properties();
+        properties.put(BOOTSTRAP_SERVERS_CONFIG, "localhost:9999");
+        properties.put(KEY_DESERIALIZER_CLASS_CONFIG, 
StringDeserializer.class);
+        properties.put(VALUE_DESERIALIZER_CLASS_CONFIG, 
StringDeserializer.class);
+        properties.put(RETRY_BACKOFF_MS_CONFIG, "100");
+        config = new ConsumerConfig(properties);
+        mockCoordinatorRequestManager = mock(CoordinatorRequestManager.class);
+        
when(mockCoordinatorRequestManager.coordinator()).thenReturn(Optional.of(new 
Node(1, "localhost", 9999)));
+        mockSubscriptionState = mock(SubscriptionState.class);
+        mockMembershipManager = spy(new MembershipManagerImpl(groupId));
+        heartbeatRequestState = 
mock(HeartbeatRequestManager.HeartbeatRequestState.class);
+        errorEventHandler = mock(ErrorEventHandler.class);
+        heartbeatRequestManager = new HeartbeatRequestManager(
+            mockLogContext,
+            mockTime,
+            config,
+            mockCoordinatorRequestManager,
+            mockSubscriptionState,
+            mockMembershipManager,
+            heartbeatRequestState,
+            errorEventHandler);
+    }
+
+    @Test
+    public void testHeartbeatOnStartup() {
+        // The initial heartbeatInterval is set to 0
+        heartbeatRequestState = new 
HeartbeatRequestManager.HeartbeatRequestState(
+            mockLogContext,
+            mockTime,
+            0,
+            retryBackoffMs,
+            retryBackoffMaxMs,
+            0);
+        heartbeatRequestManager = createManager();
+        NetworkClientDelegate.PollResult result = 
heartbeatRequestManager.poll(mockTime.milliseconds());
+        assertEquals(1, result.unsentRequests.size());
+
+        // Ensure we do not resend the request without the first request being 
completed
+        NetworkClientDelegate.PollResult result2 = 
heartbeatRequestManager.poll(mockTime.milliseconds());
+        assertEquals(0, result2.unsentRequests.size());
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = {true, false})
+    public void testSendHeartbeatOnMemberState(boolean shouldSendHeartbeat) {
+        // Mocking notInGroup
+        
when(mockMembershipManager.shouldSendHeartbeat()).thenReturn(shouldSendHeartbeat);
+        when(heartbeatRequestState.canSendRequest(anyLong())).thenReturn(true);
+
+        NetworkClientDelegate.PollResult result;
+        result = heartbeatRequestManager.poll(mockTime.milliseconds());
+
+        if (shouldSendHeartbeat) {
+            assertEquals(1, result.unsentRequests.size());
+            assertEquals(0, result.timeUntilNextPollMs);
+        } else {
+            assertEquals(0, result.unsentRequests.size());
+            assertEquals(Long.MAX_VALUE, result.timeUntilNextPollMs);
+
+        }
+    }
+
+    @ParameterizedTest
+    @MethodSource("stateProvider")
+    public void testTimerNotDue(final MemberState state) {
+        this.heartbeatRequestState = new 
HeartbeatRequestManager.HeartbeatRequestState(
+            mockLogContext,
+            mockTime,
+            heartbeatIntervalMs,
+            retryBackoffMs,
+            retryBackoffMaxMs);
+        heartbeatRequestManager = createManager();
+
+        when(mockMembershipManager.state()).thenReturn(state);
+        mockTime.sleep(100); // time elapsed < heartbeatInterval, no heartbeat 
should be sent
+        NetworkClientDelegate.PollResult result = 
heartbeatRequestManager.poll(mockTime.milliseconds());
+        assertEquals(0, result.unsentRequests.size());
+
+        if (mockMembershipManager.shouldSendHeartbeat()) {
+            assertEquals(heartbeatIntervalMs - 100, 
result.timeUntilNextPollMs);
+        } else {
+            assertEquals(Long.MAX_VALUE, result.timeUntilNextPollMs);
+        }
+    }
+
+    @Test
+    public void testBackoffOnHeartbeatTimeout() {
+        heartbeatRequestState = new 
HeartbeatRequestManager.HeartbeatRequestState(
+            mockLogContext,
+            mockTime,
+            0,
+            retryBackoffMs,
+            retryBackoffMaxMs,
+            0);
+        heartbeatRequestManager = createManager();
+        
when(mockCoordinatorRequestManager.coordinator()).thenReturn(Optional.of(new 
Node(1, "localhost", 9999)));
+        when(mockMembershipManager.shouldSendHeartbeat()).thenReturn(true);
+        NetworkClientDelegate.PollResult result = 
heartbeatRequestManager.poll(mockTime.milliseconds());
+        assertEquals(1, result.unsentRequests.size());
+        result.unsentRequests.get(0).future().completeExceptionally(new 
TimeoutException("timeout"));
+
+        // assure the manager will backoff on timeout
+        mockTime.sleep(retryBackoffMs - 1);
+        result = heartbeatRequestManager.poll(mockTime.milliseconds());
+        assertEquals(0, result.unsentRequests.size());
+
+        mockTime.sleep(1);
+        result = heartbeatRequestManager.poll(mockTime.milliseconds());
+        assertEquals(1, result.unsentRequests.size());
+    }
+

Review Comment:
   Added `testValidateConsumerGroupHeartbeatRequest` - which validate the 
fields in the the requestBuilder.build(version) - Is that what do you mean?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscr...@kafka.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org

Reply via email to