greyp9 commented on code in PR #6131:
URL: https://github.com/apache/nifi/pull/6131#discussion_r921429640


##########
nifi-nar-bundles/nifi-kafka-bundle/nifi-kafka-2-6-processors/src/test/java/org/apache/nifi/processors/kafka/pubsub/TestConsumeKafkaMock.java:
##########
@@ -0,0 +1,520 @@
+/*
+ * 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.nifi.processors.kafka.pubsub;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import com.fasterxml.jackson.databind.node.TextNode;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerConfig;
+import org.apache.kafka.clients.consumer.ConsumerGroupMetadata;
+import org.apache.kafka.clients.consumer.ConsumerRecord;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.header.Header;
+import org.apache.kafka.common.header.Headers;
+import org.apache.kafka.common.header.internals.RecordHeader;
+import org.apache.kafka.common.header.internals.RecordHeaders;
+import org.apache.kafka.common.record.TimestampType;
+import org.apache.nifi.json.JsonRecordSetWriter;
+import org.apache.nifi.json.JsonTreeReader;
+import org.apache.nifi.logging.ComponentLog;
+import org.apache.nifi.processor.ProcessContext;
+import org.apache.nifi.reporting.InitializationException;
+import org.apache.nifi.serialization.RecordReaderFactory;
+import org.apache.nifi.serialization.RecordSetWriterFactory;
+import org.apache.nifi.util.MockFlowFile;
+import org.apache.nifi.util.TestRunner;
+import org.apache.nifi.util.TestRunners;
+import org.junit.jupiter.api.Test;
+
+import java.io.ByteArrayOutputStream;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.regex.Pattern;
+
+import static java.nio.charset.StandardCharsets.ISO_8859_1;
+import static java.nio.charset.StandardCharsets.UTF_8;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+public class TestConsumeKafkaMock {
+
+    /**
+     * JSON serialization helper.
+     */
+    private final ObjectMapper mapper = new ObjectMapper();
+
+    /**
+     * Kafka server endpoint (mock) for test interactions.
+     */
+    private static final String BOOTSTRAP_SERVER = "localhost:59092";
+
+    /**
+     * Ensure fresh data for each test run.
+     */
+    private static final long TIMESTAMP = System.currentTimeMillis();
+
+    /**
+     * The name of the test kafka topic to be created.
+     */
+    private static final String TEST_TOPIC = "nifi-consume-" + TIMESTAMP;
+
+    /**
+     * The name of the test kafka group to use.
+     */
+    private static final String TEST_GROUP = "nifi-group-" + TIMESTAMP;
+
+    @Test
+    public void testConsumeRecordNullKey() throws JsonProcessingException, 
InitializationException {
+        final ObjectNode node = mapper.createObjectNode().put("a", 1).put("b", 
"2");
+        final String value = mapper.writeValueAsString(node);
+        final ArrayNode nodeRecordSet = mapper.createArrayNode().add(node);
+        final String valueRecordSet = mapper.writeValueAsString(nodeRecordSet);
+        final ConsumerRecord<byte[], byte[]> record = new ConsumerRecord<>(
+                TEST_TOPIC, 0, 0, null, value.getBytes(UTF_8));
+        final ConsumerRecords<byte[], byte[]> consumerRecords = 
getConsumerRecords(record);
+
+        final TestRunner runner = getTestRunner(consumerRecords, TEST_TOPIC, 
TEST_GROUP);
+        runner.run(1);
+        runner.assertTransferCount("success", 1);
+        runner.assertTransferCount("parse.failure", 0);
+        final List<MockFlowFile> flowFiles = 
runner.getFlowFilesForRelationship("success");
+        final MockFlowFile flowFile = flowFiles.iterator().next();
+        assertEquals(valueRecordSet, flowFile.getContent());
+        assertNull(flowFile.getAttribute("kafka.key"));
+        assertEquals("0", flowFile.getAttribute("kafka.partition"));
+        assertEquals(TEST_TOPIC, flowFile.getAttribute("kafka.topic"));
+        assertEquals(TEST_GROUP, flowFile.getAttribute("kafka.consumer.id"));
+    }
+
+    @Test
+    public void testConsumeRecordTextKey() throws Exception {
+        final String key = "a-kafka-record-key";
+        final ObjectNode node = mapper.createObjectNode().put("c", 3).put("d", 
"4");
+        final String value = mapper.writeValueAsString(node);
+        final ArrayNode nodeRecordSet = mapper.createArrayNode().add(node);
+        final String valueRecordSet = mapper.writeValueAsString(nodeRecordSet);
+        final ConsumerRecord<byte[], byte[]> record = new ConsumerRecord<>(
+                TEST_TOPIC, 0, 0, key.getBytes(UTF_8), value.getBytes(UTF_8));
+        final ConsumerRecords<byte[], byte[]> consumerRecords = 
getConsumerRecords(record);
+
+        final TestRunner runner = getTestRunner(consumerRecords, TEST_TOPIC, 
TEST_GROUP);
+        runner.run(1);
+        runner.assertTransferCount("success", 1);
+        runner.assertTransferCount("parse.failure", 0);
+        final List<MockFlowFile> flowFiles = 
runner.getFlowFilesForRelationship("success");
+        final MockFlowFile flowFile = flowFiles.iterator().next();
+        assertEquals(valueRecordSet, flowFile.getContent());
+        assertEquals(key, flowFile.getAttribute("kafka.key"));
+        assertEquals("0", flowFile.getAttribute("kafka.partition"));
+        assertEquals(TEST_TOPIC, flowFile.getAttribute("kafka.topic"));
+        assertEquals(TEST_GROUP, flowFile.getAttribute("kafka.consumer.id"));
+    }
+
+    @Test
+    public void testConsumeRecordJsonKeyNoKeyReader() throws Exception {
+        final ObjectNode nodeKey = mapper.createObjectNode().put("key", true);
+        final String key = mapper.writeValueAsString(nodeKey);
+        final ObjectNode node = mapper.createObjectNode().put("e", 5).put("f", 
"6");
+        final String value = mapper.writeValueAsString(node);
+        final ArrayNode nodeRecordSet = mapper.createArrayNode().add(node);
+        final String valueRecordSet = mapper.writeValueAsString(nodeRecordSet);
+        final ConsumerRecord<byte[], byte[]> record = new ConsumerRecord<>(
+                TEST_TOPIC, 0, 0, key.getBytes(UTF_8), value.getBytes(UTF_8));
+        final ConsumerRecords<byte[], byte[]> consumerRecords = 
getConsumerRecords(record);
+
+        final TestRunner runner = getTestRunner(consumerRecords, TEST_TOPIC, 
TEST_GROUP);
+        runner.run(1);
+        runner.assertTransferCount("success", 1);
+        runner.assertTransferCount("parse.failure", 0);
+        final List<MockFlowFile> flowFiles = 
runner.getFlowFilesForRelationship("success");
+        final MockFlowFile flowFile = flowFiles.iterator().next();
+        assertEquals(valueRecordSet, flowFile.getContent());
+        assertEquals(key, flowFile.getAttribute("kafka.key"));
+        assertEquals("0", flowFile.getAttribute("kafka.partition"));
+        assertEquals(TEST_TOPIC, flowFile.getAttribute("kafka.topic"));
+        assertEquals(TEST_GROUP, flowFile.getAttribute("kafka.consumer.id"));
+    }
+
+    @Test
+    public void testConsumeRecordWrapperStrategyKeyFormatDefault() throws 
Exception {
+        final ObjectNode nodeToKafkaKey = mapper.createObjectNode().put("key", 
true);
+        final String textToKafkaKey = 
mapper.writeValueAsString(nodeToKafkaKey);
+        final ObjectNode nodeToKafkaValue = mapper.createObjectNode().put("g", 
7).put("h", "8");
+        final String textToKafkaValue = 
mapper.writeValueAsString(nodeToKafkaValue);
+        final ConsumerRecord<byte[], byte[]> record = new 
ConsumerRecord<>(TEST_TOPIC, 0, 0L,
+                0L, TimestampType.CREATE_TIME, 0L, textToKafkaKey.length(), 
textToKafkaValue.length(),
+                textToKafkaKey.getBytes(UTF_8), 
textToKafkaValue.getBytes(UTF_8), getKafkaHeaders());
+        final ConsumerRecords<byte[], byte[]> consumerRecords = 
getConsumerRecords(record);
+
+        final TestRunner runner = getTestRunner(consumerRecords, TEST_TOPIC, 
TEST_GROUP);
+        final String keyReaderId = "key-record-reader";
+        final RecordReaderFactory keyReaderService = new JsonTreeReader();
+        runner.addControllerService(keyReaderId, keyReaderService);
+        runner.enableControllerService(keyReaderService);
+        runner.setProperty(keyReaderId, keyReaderId);
+        runner.setProperty("consume-strategy", "use-wrapper");
+        runner.setProperty("key-format", "byte-array");
+        runner.run(1);
+
+        runner.assertTransferCount("success", 1);
+        runner.assertTransferCount("parse.failure", 0);
+        final List<MockFlowFile> flowFiles = 
runner.getFlowFilesForRelationship("success");
+        final MockFlowFile flowFile = flowFiles.iterator().next();
+        // consume strategy "use-wrapper" emits ArrayNode due to 
JsonRecordSetWriter
+        final JsonNode nodeFlowFile = mapper.readTree(flowFile.getContent());
+        assertTrue(nodeFlowFile instanceof ArrayNode);
+        assertEquals(1, nodeFlowFile.size());
+        // extract the NiFi json object representation of Kafka input record
+        final JsonNode flowFileValue = nodeFlowFile.iterator().next();
+        // wrapper object contains "key", "value", "headers", "metadata"
+        assertEquals(4, flowFileValue.size());
+        final JsonNode nodeWrapperKey = flowFileValue.get("key");
+        final JsonNode nodeWrapperValue = flowFileValue.get("value");
+        final JsonNode nodeWrapperHeaders = flowFileValue.get("headers");
+        final JsonNode nodeWrapperMetadata = flowFileValue.get("metadata");
+        assertNotNull(nodeWrapperKey);
+        assertNotNull(nodeWrapperValue);
+        assertNotNull(nodeWrapperHeaders);
+        assertNotNull(nodeWrapperMetadata);

Review Comment:
   I was able to tighten this up a bit by using `Objects.requireNonNull()`.  
This highlighted a few instances where the get was subsequently unused.  But 
when multiple of these values are used, I couldn't think of a clear 
alternative. 



-- 
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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to