Skip to content

Commit 697846f

Browse files
authored
Merge branch 'main' into fix-2052
2 parents 90b361a + 653207d commit 697846f

File tree

3 files changed

+17
-6
lines changed

3 files changed

+17
-6
lines changed

CHANGELOG.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
2222
([#2044](https://github.com/open-telemetry/opentelemetry-python/pull/2044))
2323
- `opentelemetry-sdk` Treat limit even vars set to empty values as unset/unlimited.
2424
([#2044](https://github.com/open-telemetry/opentelemetry-python/pull/2054))
25-
25+
- `opentelemetry-api` Attribute keys must be non-empty strings.
26+
([#2057](https://github.com/open-telemetry/opentelemetry-python/pull/2057))
2627

2728
## [0.23.1](https://github.com/open-telemetry/opentelemetry-python/pull/1987) - 2021-07-26
2829

opentelemetry-api/src/opentelemetry/attributes/__init__.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -47,8 +47,8 @@ def _clean_attribute(
4747
- It needs to be encoded/decoded e.g, bytes to strings.
4848
"""
4949

50-
if key is None or key == "":
51-
_logger.warning("invalid key `%s` (empty or null)", key)
50+
if not (key and isinstance(key, str)):
51+
_logger.warning("invalid key `%s`. must be non-empty string.", key)
5252
return None
5353

5454
if isinstance(value, _VALID_ATTR_VALUE_TYPES):
@@ -118,7 +118,7 @@ def _clean_attribute_value(
118118
if isinstance(value, bytes):
119119
try:
120120
value = value.decode()
121-
except ValueError:
121+
except UnicodeDecodeError:
122122
_logger.warning("Byte attribute could not be decoded.")
123123
return None
124124

opentelemetry-api/tests/attributes/test_attributes.py

+12-2
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,16 @@ def assertValid(self, value, key="k"):
3131
def assertInvalid(self, value, key="k"):
3232
self.assertIsNone(_clean_attribute(key, value, None))
3333

34+
def test_attribute_key_validation(self):
35+
# only non-empty strings are valid keys
36+
self.assertInvalid(1, "")
37+
self.assertInvalid(1, 1)
38+
self.assertInvalid(1, {})
39+
self.assertInvalid(1, [])
40+
self.assertInvalid(1, b"1")
41+
self.assertValid(1, "k")
42+
self.assertValid(1, "1")
43+
3444
def test_clean_attribute(self):
3545
self.assertInvalid([1, 2, 3.4, "ss", 4])
3646
self.assertInvalid([dict(), 1, 2, 3.4, 4])
@@ -142,10 +152,10 @@ def test_bounded_dict(self):
142152
def test_no_limit_code(self):
143153
bdict = BoundedAttributes(maxlen=None, immutable=False)
144154
for num in range(100):
145-
bdict[num] = num
155+
bdict[str(num)] = num
146156

147157
for num in range(100):
148-
self.assertEqual(bdict[num], num)
158+
self.assertEqual(bdict[str(num)], num)
149159

150160
def test_immutable(self):
151161
bdict = BoundedAttributes()

0 commit comments

Comments
 (0)