Skip to content

Commit

Permalink
modify kafka context getter helper methods to work on dict and list
Browse files Browse the repository at this point in the history
  • Loading branch information
mrajashree committed Feb 20, 2023
1 parent 24b7234 commit 389d707
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -41,16 +41,26 @@ class KafkaContextGetter(textmap.Getter):
def get(self, carrier: textmap.CarrierT, key: str) -> Optional[List[str]]:
if carrier is None:
return None
for item_key, value in carrier:

carrier_items = carrier
if isinstance(carrier, dict):
carrier_items = carrier.items()

for item_key, value in carrier_items:
if item_key == key:
if value is not None:
return [value.decode()]

return None

def keys(self, carrier: textmap.CarrierT) -> List[str]:
if carrier is None:
return []
return [key for (key, value) in carrier]

carrier_items = carrier
if isinstance(carrier, dict):
carrier_items = carrier.items()
return [key for (key, value) in carrier_items]


class KafkaContextSetter(textmap.Setter):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
)
from opentelemetry.instrumentation.confluent_kafka.utils import (
KafkaContextSetter,
KafkaContextGetter,
)


Expand Down Expand Up @@ -89,3 +90,17 @@ def test_context_setter(self) -> None:
carrier_list = [("key1", "val1")]
context_setter.set(carrier_list, "key2", "val2")
self.assertTrue(("key2", "val2".encode()) in carrier_list)

def test_context_getter(self) -> None:
context_setter = KafkaContextSetter()
context_getter = KafkaContextGetter()

carrier_dict = {}
context_setter.set(carrier_dict, "key1", "val1")
self.assertEqual(context_getter.get(carrier_dict, "key1"), ["val1"])
self.assertEqual(["key1"], context_getter.keys(carrier_dict))

carrier_list = []
context_setter.set(carrier_list, "key1", "val1")
self.assertEqual(context_getter.get(carrier_list, "key1"), ["val1"])
self.assertEqual(["key1"], context_getter.keys(carrier_list))

0 comments on commit 389d707

Please sign in to comment.