Skip to content

Commit 8b5ec90

Browse files
fix(kafka): deserialize empty string record key instead of returning None (#8698)
Co-authored-by: Leandro Damascena <lcdama@amazon.pt>
1 parent db2f8f0 commit 8b5ec90

2 files changed

Lines changed: 23 additions & 1 deletion

File tree

‎aws_lambda_powertools/utilities/kafka/consumer_records.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ def key(self) -> Any:
3232
key = self.get("key")
3333

3434
# Return None if key doesn't exist
35-
if not key:
35+
if key is None:
3636
return None
3737

3838
logger.debug("Deserializing key field")

‎tests/functional/kafka_consumer/required_dependencies/test_kafka_consumer.py‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -338,6 +338,28 @@ def handler(event: ConsumerRecords, context):
338338
assert result is None
339339

340340

341+
def test_kafka_consumer_default_deserializer_key_is_empty_string(kafka_event_with_json_data, lambda_context):
342+
# GIVEN
343+
# A Kafka event where record key is empty string ""
344+
kafka_event_with_empty_key = deepcopy(kafka_event_with_json_data)
345+
kafka_event_with_empty_key["records"]["my-topic-1"][0]["key"] = ""
346+
347+
# A Kafka consumer with no schema configuration specified
348+
@kafka_consumer()
349+
def handler(event: ConsumerRecords, context):
350+
record = next(event.records)
351+
return record.key
352+
353+
# WHEN
354+
# The handler processes the Kafka event with an empty string key
355+
result = handler(kafka_event_with_empty_key, lambda_context)
356+
357+
# THEN
358+
# The key should be decoded to an empty string, not None
359+
assert result == ""
360+
assert result is not None
361+
362+
341363
def test_kafka_consumer_json_with_wrong_avro_schema(kafka_event_with_json_data, lambda_context):
342364
# GIVEN
343365
# A Kafka event with a null key in the record

0 commit comments

Comments
 (0)